Authors: PePe, Li-aung Yip
Overview: Example of this nested while loop is a bad idea, and noting the while loop in python require resetting the loop counter to be 0. And for usage of getting the combination of everything, use either nested for loop with range() function, or itertools, which takes list and return every possible combination from each element in the list you give as argument. And also, xrange() is replaced by range() at 3.0.
In C++, although it might not be recommended, we can write a nested while loop and the following code will work. Because of unknown reason.
a = 0 b = 0 c = 0 while a <= 5: while b <=3: while c <= 8: print(a , b , c) c += 1 b += 1 a += 1Output is the following
0 0 0 0 0 1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0 7 0 0 8Answer Because we need to remember to reset the loop's counter, a, b, c respectively on each iteration. But this method is kind of funky.
a = 0 b = 0 c = 0 while a <= 5: while b <=3: while c <= 8: print(a , b , c) c += 1 b += 1 c = 0 # reset a += 1 b = 0 # reset c = 0 # resetI think most python programmer would prefer using the for loop over the range() function. It is interesting also to note and learn that, xrange() is the range() function, if you are using python 2.x. From 3.0 on, use range instead. :)
for a in range(5+1): # Note xrange(n) produces 0,1,2...(n-1) and does not include n. for b in range (3+1): for c in range (8+1): print(a, b, c)But then wait... from the Li-aung Yip, there is a better way. Check out this solution which involve using itertools.product()
import itertools for a, b, c in itertools.product(range(5+1), range(3+1), range(8+1)): print a,b,cFor even more reading: Dan Goodger's "Code Like a Pythonista: Idiomatic Python" Thought: I think 2 second way resemble C++ the most to me, I don't know if I want to use while loop even in C++. But it is great to learn another function from the itertools, the itertools.product(). And nice to see the use for for a, b, c. I think it is powerful, but never use it in my code yet, should practice using it.
import itertools colors = ['red', 'green', 'blue'] vehicles = ['car', 'train', 'ship', 'boat'] numbers = [1, 2, 3, 4, 5] """Pints out all the possible combination of number of color vehicles""" for color, vehicle, number in itertools.product(colors, vehicles, numbers): print(number, color, vehicle)More reference: http://docs.python.org/library/itertools.html
No comments:
Post a Comment