Bottom Page

• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 a generator that computes squares of first 20 natural numbers mdshamim06 Unladen Swallow Posts: 1 Threads: 1 Joined: Oct 2019 Reputation: 0 Likes received: 0 #1 Oct-01-2019, 10:26 AM Problem Statement: Define two functions f1 and f2 such that, f1 returns a list of squares of first 20 natural numbers using list comprehension. f2 returns a generator that computes squares of first 20 natural numbers. Determine the time taken by each function to get executed 100000 times. Print the time for each function in separate lines. Hint : Explore timeit module Answer : ```import timeit def f1(): f= [i**2 for i in range(1,21)] return f def f2(): g = (x**2 for x in range(1,21)) yield g s1 = timeit.timeit(stmt="f1()",setup="from __main__ import f1",number=100000) print(s1) s2 = timeit.timeit(stmt="next(f2())",setup="from __main__ import f2",number=100000) print(s2) ```Can anybody check the answer is correct or not ? buran Posts: 6,020 Threads: 102 Joined: Sep 2016 Reputation: 462 Likes received: 1259 #2 Oct-01-2019, 10:38 AM (This post was last modified: Oct-01-2019, 10:38 AM by buran. Edited 5 times in total.) I don't think you need to time calling `next(f2())`. I would expect to call it the same way as f1(). The idea is to see the difference in timing when creating list in memory and just creating the generator. Also note that they want f2 to return generator, not f2 to be generator ```import timeit def f1(): f= [i**2 for i in range(1,21)] return f def f2(): g = (x**2 for x in range(1,21)) return g s1 = timeit.timeit(stmt="f1()",setup="from __main__ import f1",number=100000) print(s1) s2 = timeit.timeit(stmt="f2()",setup="from __main__ import f2",number=100000) print(s2)`````````Output:1.0165985100029502 0.1487332629985758`````` « Next Oldest | Next Newest »

Top Page

 Possibly Related Threads... Thread Author Replies Views Last Post need help in natural language processing irsyadfm 7 1,684 Aug-07-2019, 07:42 AM Last Post: tkorol Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 1,747 Dec-05-2017, 09:48 AM Last Post: DeaD_EyE natural logarithm print atux_null 5 1,374 Oct-20-2017, 02:14 PM Last Post: sparkz_alot Natural Logarithm in Python yg89 8 18,915 May-07-2017, 12:36 AM Last Post: yg89

Forum Jump:

Users browsing this thread: 1 Guest(s)