here2share

# recursion_vs_iterations.py

Sep 19th, 2020
943
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # recursion_vs_iterations.py
  2.  
  3. import timeit
  4. setu="""
  5. def test(x):
  6.     x=x-1
  7.     if x==0:
  8.         return x
  9.     test(x)
  10. """
  11.  
  12. setu2="""
  13. x=10
  14. while x>0:
  15.    x=x-1
  16. """
  17.  
  18. setu3="""
  19. x=10
  20. for x in range(10):
  21.    pass
  22. """
  23.  
  24. setu4="""
  25. x=10
  26. for x in xrange(10):
  27.    pass
  28. """
  29. print '%.8f'%timeit.timeit(stmt="test(10)",setup=setu,number=100)
  30. print '%.8f'%timeit.timeit(stmt=setu2,number=100)
  31. print '%.8f'%timeit.timeit(stmt=setu3,number=100)
  32. print '%.8f'%timeit.timeit(stmt=setu4,number=100)
  33.  
  34. setu5='''
  35. def test(i):
  36.    for x in range(i):
  37.       yield x
  38. t=test(10)
  39. while 1:
  40.     try:
  41.         t.next()
  42.     except:
  43.         break
  44. '''
  45. print '%.8f'%timeit.timeit(stmt=setu5,number=100)
  46.  
  47. def test(i):
  48.     for x in range(i):
  49.        yield x
  50. t=test(10)
  51. while 1:
  52.     try:
  53.         t.next()
  54.     except:
  55.         break
  56.  
  57. def get_odd_numbers(i):
  58.     return range(1, i, 2)
  59. foo = get_odd_numbers(10)
  60. print(foo)
  61.  
  62. def yield_odd_numbers(i):
  63.     for x in range(1, i, 2):
  64.        yield x
  65. bar = yield_odd_numbers(10)
  66. print(bar)
  67. # <generator object yield_odd_numbers at 0x1029c6f50>
  68. print(bar.next())
  69. # 1
  70. print(bar.next())
  71. # 3
  72. print(bar.next())
  73. # 5
  74.  
RAW Paste Data