By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,089 Members | 2,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,089 IT Pros & Developers. It's quick & easy.

help with loop of upper & lower letters

Thekid
100+
P: 145
I had made a post about making a loop using letters instead of numbers and dshimer gave me this solution:
Expand|Select|Wrap|Line Numbers
  1. for i in range(65,70):
  2.     for j in range(65,70):
  3.         for k in range(65,70):
  4.             print chr(i),chr(j),chr(k)
  5.  
which used an example I had posted using numbers. That code works (thanks dshimer) but after toying with it I see that I am going about it in a method that takes a long time to run through and I also need uppers in the loop. I need a loop that will print out like this:
aaaaa
aaaaA
aaaAa
aaAaa
ans so on through every combination. I now have this portion which seems closer but still not quite there:
Expand|Select|Wrap|Line Numbers
  1. from string import letters
  2. #my 'lowers' list has extra chars at the end so I have to trim it
  3. lowers = letters[26:52]
  4. uppers = letters[:26]
  5. for lower in lowers:
  6.     for upper in uppers:
  7.         print lower,upper
  8.  
a A
a B
a C
a D

So my question is how can I get this to run through with 5 values and through every combination, without doing something like this:
Expand|Select|Wrap|Line Numbers
  1. for lower in lowers:
  2.     for upper in uppers:
  3.         print lower,lower,lower,lower,upper
  4.         print lower,lower,lower,upper,lower
  5.  
May 22 '09 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Try this:
Expand|Select|Wrap|Line Numbers
  1. def permute5(a):
  2.     b = [(v,w,x,y,z) for v in a for w in a for x in a for y in a for z in a]
  3.     c = ["".join(z) for z in b]
  4.     return b,c
  5.  
  6. b, c = permute5('abcABC')
  7.  
  8. print "\n".join(c)
Partial output:
>>> aaaaa
aaaab
aaaac
aaaaA
aaaaB
aaaaC
aaaba
aaabb
aaabc
aaabA
aaabB
aaabC
aaaca
aaacb
aaacc
aaacA
aaacB
aaacC
aaaAa
..................
CCCcC
CCCAa
CCCAb
CCCAc
CCCAA
CCCAB
CCCAC
CCCBa
CCCBb
CCCBc
CCCBA
CCCBB
CCCBC
CCCCa
CCCCb
CCCCc
CCCCA
CCCCB
CCCCC
>>>
May 22 '09 #2

Thekid
100+
P: 145
Wow....that's great! Thanks!
May 22 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.