Several Python exercises

Source: Internet
Author: User

python from the public to see a few of the Python exercises, take to practice practiced hand, the results to find themselves or special water, not very difficult 8 questions, I only made out 5, of which also 3 problems stuck, while the side of the search. the original title link is here: http://python.jobbole.com/83641/

1. Write code to print an even number within 1.1 billion

After reading the topic, I did not want to write directly a sentence:

1 Print  for inch if i% 2 = = 0  ]

Start running results. And then. It's freezing. Restart time to reflect on, well, it is a bit two, a list of 50 million elements generated, the computer did not blow up even if its good temper. However, can not be a for loop printing, it is too low. Think about it, or use the co-process to be a little more reliable. Then wrote another (in the QQ group to see others write slightly improved a little):

 1  def   Even_maker (x):  2  for  i  (i for  i in  xrange (1, 50000001< Span style= "color: #000000;" ):  3  yield  i * 24  for  i in  even_maker (10**9 6  print  I,  " ,   ' , 

The efficiency is not too high, the feeling should have the better method, but I did not want to continue to think deeply at the moment.

2. Write a function that clears [] and the contents of the string with a regular expression. s = "[lol] hello, help me to clear out these markup, [smile]." Thank you! "

This is no difficulty, it is appropriate to use regular processing.

1 " [lol] Hello, help me to clear out these markup, [smile]. Thank you!  "2print re.sub ('\[.*?\]", s)

A line is done (don't spit the groove This is two lines).

3. Use Python to process the following function,

def hello (name):p rint "Hello,%s"% name

Print time-consuming details when a function is invoked

<function name:hello><function Call Begin>hello, Tom<function call End>[timecosts: 3.81469726562E-06S]

A typical decorator. But I am really not familiar with the decorator, basically by the Mongolian. Before reprinted a blog: Http://www.cnblogs.com/anpengapple/p/5068580.html is a decorator, write well, I almost every time to follow this copy. This time the decorator is already quite simple.

1 defName_and_time_func (func):2     defName_time (*param):3Start_time =Datetime.datetime.now ()4         Print '<function Name:%s>', Func.__name__5         Print '<function Call begin>'6Func (*param)7         Print '<function Call end>'8Time.sleep (1)#can not add, but do not see the time interval9         Print '[Time costs:%s]', Datetime.datetime.now ()-start_timeTen     returnName_time One  A @name_and_time_func - defHello (name): -     Print "Hello,%s"%name the  -Hello'An Peng')

4. Write a function that turns the hump nomenclature string into an underscore string, such as GetItem, Get_item,getitem, get_item

At first do not know what to do, wrote a loop, one character processing, if it is uppercase, it is underlined + lowercase form. But I think it's too low to write. The group of students pointing to use SED, but I just want to practice Python ah is not playing shell. Later on the Internet to check the use of re.sub. It was not used before, and the string matched to the same string was assumed to be the only one. I checked it out. The second argument can be replaced by a function or lambda expression on a matching string. It is much more convenient to have this powerful weapon.

1 defcamel_name (name):2_name = Re.sub ('[A-z]',LambdaX:'_'+x.group (0). Lower (), name)3     return_nameif_NAME[0]! ='_' Else_name[1:]#after the replacement, it is possible that the first letter is underlined and needs to be removed4 5names = ['GetItem','GetItem','GetItem']6      forIinchnames:7         PrintCamel_name (i)

5. Print the list: [1, 2, 3, 4...n],n=20; Write your code to print the following regular output:

        1 [1*, 2, 3, 4, 5]        2 [1,, 3, 4, 5]        3 [1, 2, * *, 4, 5] 4 [2, 3,, 5, 6        ]        5 [3, 4, 5*, 6, 7]        6 [4, 5] , 6*, 7, 8] ...        20 [16, 17, 18, 19, 20*]

It's pretty much the page-flipping format. This is not too difficult, but I still small card, mainly obsessive-compulsive disorder, want to change this to a more general form. A few times after the effect is good, the total number of pages and displayed page numbers can be passed on their own parameters, * page numbers always appear in the middle. When the page number is greater than the total page count or less than 1, it adjusts itself.

1 defPage_print (page, total=20, width=5):2     #Page is the current page number, which is the page number of the marked *3     #Total is the page number4     #width is the number of pages displayed (* page numbers appear in the middle)5 6     #Set print page numbers to avoid out of range7     ifPage < 1:8page = 19     ifPage >Total:Tenpage = Total One  A     #Set Start Page number -     ifPage < WIDTH/2 + 1: -Start = 1 the     elifPage > TOTAL-WIDTH/2: -Start = Total-width -     Else: -Start = PAGE-WIDTH/2 +  -ret = str (page) +'[' +      forIinchXrange (Start, start + width + 1): A         ifi = =page: atRET + ='*' -RET + =Str (i) -         ifI! = start +Width: -RET + =', ' -         Else: -RET + =']\n' in  - returnret to  +t = 18 -  forIinchXrange (1, T + 1): the     PrintPage_print (Page=i, total=t, width=8)

6. Write a program to simulate the bank queue, there is only one team, a user will be allowed to jump in the queue (enter any position), but to ensure that each time the team changes, the team affected people are notified

Customer A line up @ position 11Customer B:order changed to 12Customer C:order changed to 13Customer D:order changed t o 14

No. Feel like a certain design pattern of things, I do not know much about the design pattern, temporarily did not think of any good way. Forced writing is able to write, but the program will certainly be very ugly to write. Think again when you are free (the subtext is too lazy to move your brain).

7. User system, there is a mutual concern of the action, when access to a person's profile, need to show their fans, concerns, fan list and watchlist. Briefly describe the solution, including the DB modeling/Data layer/business layer, and the processing logic for dealing with high concurrency/attention-to-take situations.

Slightly.

8. Given some nxn matrices, for any route, define its "and" for the number of all nodes on its line and calculate the alignment and minimum values from the upper left to the lower right corner. Each route can only be from a point to its periphery (up or down), not oblique. For example

4,62,8 's route and minimum values are 4-2-8 14
1,2,34,5,67,8,9 's route and minimum value is 1-2-3-6-9 21

The program only needs to output minimum and value (a number)

This is a typical dynamic programming problem. When learning dynamic planning, the first example of an introduction to the algorithm is this thing, the pipelining problem. But however, dynamic planning I almost forgot. Put it here first, write a log in a few days to fill it up.

Several Python exercises

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.