Self-study Python3, now began every day in the python2.71 100 cases to do a problem, with python3 realization, and write down some thinking ~ refueling (??? Know??)?
Topic website (http://www.runoob.com/python/python-100-examples.html)
001 Title: There are four numbers: 1, 2, 3, 4, how many different and no repetition of the number of three digits? What's the number?
My answer:
defFun (): N=0 forXinchRange (1,5): forYinchRange (1,5): forZinchRange (1,5): if(x!=y) and(x!=z) and(y!=z):Print("%d%d%d"%(x, Y, z)) n=n+1Print("tatal:%d"%n
Fun ()
Thinking:
1. Use three loop nesting to traverse all possible values and then filter them with the IF condition. But traversing when the data volume is large may prolong the time. So you can improve the code:
defFun (): N=0 forXinchRange (1,5): forYinchRange (1,5) : ify!=x: #增加if条件语句 to reduce the number of cycles to be generated, and to save time forZinchRange (1,5): if(x!=z) and(y!=z):Print("%d%d%d"%(x, Y, z)) n=n+1Print("tatal%d"%N) Fun ()
2. Using the Permutations method
from Import for in permutations ([1,2,3,4],3): print("%d%d%d"% (i[0],i[1 ],I[2]))
Itertools.permutations (Iterable,r)
An iterator is created that returns the sequence of all items of length r in the Iterable, and if R is omitted, the length of the sequence is the same as the number of items in the iterable: Returns an iterator to the tuple that has any of the r elements arranged in p.
It is equivalent to taking three elements from the list [1,2,3,4], and then returning a tuple with three elements after a variety of permutations. The final output of the time to format a bit better ~
python3.0 Exercises 100 Questions--001