python3.0 Exercises 100 Questions--001

Source: Internet
Author: User
Tags iterable

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.