Python Forum
a generator that computes squares of first 20 natural numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a generator that computes squares of first 20 natural numbers
#1
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 ?
Reply


Messages In This Thread
a generator that computes squares of first 20 natural numbers - by mdshamim06 - Oct-01-2019, 10:26 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,369 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  Manually raising two error types with a function that computes sqfeet to sqmeters sean1 7 2,071 Nov-12-2021, 05:01 PM
Last Post: deanhystad
  Descending order unique squares OmegaRed94 6 2,373 Sep-26-2021, 04:33 PM
Last Post: ndc85430
  Natural language processing project maaaa2401 1 1,778 Dec-04-2020, 07:26 PM
Last Post: Larz60+
  Convert list of numbers to string of numbers kam_uk 5 2,935 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  need help in natural language processing irsyadfm 7 4,455 Aug-07-2019, 07:42 AM
Last Post: tkorol
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 4,054 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE
  natural logarithm print atux_null 5 3,585 Oct-20-2017, 02:14 PM
Last Post: sparkz_alot
  Natural Logarithm in Python yg89 8 26,658 May-07-2017, 12:36 AM
Last Post: yg89

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020