Analysis of data structure running efficiency of Python common use

Source: Internet
Author: User

Comparison of the operating efficiency of the 1.while loop and for loop under the same conditions:

The following code:

1 ImportTime as TM2 ImportTimeit as TT3 ImportRandom as RM4 5 defwhile_time ():6i =07      whileI < 100000001:8i + = 19         ifI > 100000:Ten              Break One     returnI A  -  - deffor_time (): thej =0 -      forIinchRange (100000001): -J + = 1 -         ifJ > 100000: +              Break -     returnJ +  A if __name__=="__main__": atT1 = TT. Timer ("for_time ()","From __main__ import for_time") -         Print(T1.timeit (number=10)) -t2 = TT. Timer ("while_time ()","From __main__ import while_time") -         Print(T2.timeit (number=10))

Results:

Note: As a result above, the time complexity of the for loop and while loop is T (n) =5*n+1, but the for loop is slightly more efficient than the while loop.

2. Efficiency comparisons for traversing lists, tuples, and collections:
The following code:

1 deflist_time ():2      forIinchList1:3i + = 14 5 6 deftuple_time ():7      forIinchTP1:8i + = 19 Ten  One defset_time (): A      forIinchSet1: -i + = 1 -  the defMain (): -List1 = List (range (30000000)) -TP1 =tuple (List1) -Set1 =Set (List1) +T1 = TT. Timer ("list_time ()","From __main__ import list_time") -     Print(T1.timeit (number=10)) +t2 = TT. Timer ("tuple_time ()","From __main__ import tuple_time") A     Print(T2.timeit (number=10)) atT3 = TT. Timer ("set_time ()","From __main__ import set_time") -     Print(T3.timeit (number=10)) - if __name__=="__main__": -Main ()

Results:


Description: The time complexity of the three functions is O (n), the traversal efficiency of the list and the tuple is similar, and the efficiency of the set traversal is slightly lower.

Analysis of data structure running efficiency of Python common use

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.