Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # recursion_vs_iterations.py
- import timeit
- setu="""
- def test(x):
- x=x-1
- if x==0:
- return x
- test(x)
- """
- setu2="""
- x=10
- while x>0:
- x=x-1
- """
- setu3="""
- x=10
- for x in range(10):
- pass
- """
- setu4="""
- x=10
- for x in xrange(10):
- pass
- """
- print '%.8f'%timeit.timeit(stmt="test(10)",setup=setu,number=100)
- print '%.8f'%timeit.timeit(stmt=setu2,number=100)
- print '%.8f'%timeit.timeit(stmt=setu3,number=100)
- print '%.8f'%timeit.timeit(stmt=setu4,number=100)
- setu5='''
- def test(i):
- for x in range(i):
- yield x
- t=test(10)
- while 1:
- try:
- t.next()
- except:
- break
- '''
- print '%.8f'%timeit.timeit(stmt=setu5,number=100)
- def test(i):
- for x in range(i):
- yield x
- t=test(10)
- while 1:
- try:
- t.next()
- except:
- break
- def get_odd_numbers(i):
- return range(1, i, 2)
- foo = get_odd_numbers(10)
- print(foo)
- def yield_odd_numbers(i):
- for x in range(1, i, 2):
- yield x
- bar = yield_odd_numbers(10)
- print(bar)
- # <generator object yield_odd_numbers at 0x1029c6f50>
- print(bar.next())
- # 1
- print(bar.next())
- # 3
- print(bar.next())
- # 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement