+ 11
More efficient way in Pyhton ?
Say I have a code for i in range(10): for j in range(10): for k in range(10): print(i,j,k) If someday I want more than i,j,k it would be quite bothersome using this, so is there any other efficient way for this? Thank You!
7 Answers
+ 13
Here's a simpler one without using a list comprehension:
n=3
for i in range(10**n):
print(" ".join("{:0{z}}".format(i, z=n)))
edit: added some explanation, hopefully helpful
===========================================
if you have three slots, you're counting from 000-999 (1000 values, or 10*10*10, or 10^3)
for i in range(10**3) # count from 0 to 999
The leading 0 and number in the format string controls zero-padding:
"{:02}".format(1) would print "01"
"{:03}".format(1) would print "001"
I'm using the substitution z=n to send in the value of n
{:0{z}} is the same as {:03} when z=n and n=3
For some reason I can't just use n.
The output of format() is a string.
Any string is automatically iterable as a list.
for c in "123":
print(c) # prints 1 then 2 then 3
" ".join(string) takes every element of a list (here, a string) and joins them with spaces:
" ".join("123") is "1 2 3"
+ 10
Thanks a lot đ
Kirk Schafer
If I could upvote multiple times I would do so
+ 8
n=3
for i in range(10**n):
print(*str(i).zfill(n))
#This is working too
+ 7
Thanks I will try to comprehend your way
+ 3
This is just counting in base 10 for three slots.
I'm hoping to come up with something simpler, but this works.
n=3
print(*map(" ".join, ["{:0{z}}".format(i, z=n) for i in range(10**n)]), sep="\n")
+ 1
Kirk Schafer beautifully written đ
+ 1
this was helpful to me also