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

Number combinations

P: n/a
Hi all,

Just wondering if there is a better way of generating a 4 digit number
(that gets converted to a string), ive got the following code which
generates strings between 0000-9999.

<code>

for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
print "%s%s%s%s" %(str(a), str(b), str(c),str(d)

</code>
--Cheers

http://bulkan.googlepages.com/python

Jul 19 '06 #1
Share this Question
Share on Google+
5 Replies


P: n/a
Just wondering if there is a better way of generating a 4 digit number
(that gets converted to a string), ive got the following code which
generates strings between 0000-9999.

<code>

for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
print "%s%s%s%s" %(str(a), str(b), str(c),str(d)

</code>
Is there something wrong with

for i in xrange(0,10000): print "%04i" % i

If you need the individual digits for something, you can use

for i in xrange(0,10000):
d1,d2,d3,d4 = list("%04i" % i)
# do something with d1,d2,d3,d4

somewhat indelicate, but it works for me. :)

-tkc


Jul 19 '06 #2

P: n/a
How about

print ["%04d" % x for x in xrange(10000)]

Jul 19 '06 #3

P: n/a
placid wrote:
Hi all,

Just wondering if there is a better way of generating a 4 digit number
(that gets converted to a string), ive got the following code which
generates strings between 0000-9999.

<code>

for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
You could reuse the same range...
print "%s%s%s%s" %(str(a), str(b), str(c),str(d)
And there's no need to convert to string here.

def parrot():
r = range(10)
return ["%s%s%s%s" % (a, b, c, d) \
for a in r \
for b in r \
for c in r \
for d in r]

But there's certainly better solutions...

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jul 19 '06 #4

P: n/a
placid <Bu****@gmail.comwrote:
Hi all,

Just wondering if there is a better way of generating a 4 digit number
(that gets converted to a string), ive got the following code which
generates strings between 0000-9999.

<code>

for a in range(0,10):
for b in range(0,10):
for c in range(0,10):
for d in range(0,10):
print "%s%s%s%s" %(str(a), str(b), str(c),str(d)
for n in xrange(10000):
print "%4.4d" % n
Alex
Jul 19 '06 #5

P: n/a
Tim Chase wrote:
....
If you need the individual digits for something, you can use

for i in xrange(0,10000):
d1,d2,d3,d4 = list("%04i" % i)
strings are sequences too, and you need only write

d1,d2,d3,d4 = "%04i" % i
Jul 19 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.