In: Computer Science
Python 3.7:
Give the following sample code, write the following
programs:
• An iterator class called Iteratefirstn that implements __iter__()
and __next__() methods where next method should raise an exception
for the cur index if it is passed the last element otherwise set
cur index to the next index and advance the index by one, i.e. cur,
num = num, num+1. Instantiate the class to calculate the sum of
1000000 elements similar to the example.
• Instead of implementing the class, write a generator function
that does the same thing.
Sample code:
def firstn(n):
num, nums = 0, []
while num < n:
nums.append(num)
num += 1
return nums
sum_of_first_n = sum(firstn(1000000))
// FIRST PART OF THE QUESTION class Iteratefirstn(): def __init__(self,N): self.N=N self.current_value=0 def __iter__(self): return self def __next__(self): if self.current_value <= self.N: current_number=self.current_value self.current_value+=1 return current_number else: raise StopIteration obj = Iteratefirstn(10) sum=0 for num in obj: sum+=num print('Sum = ',sum)
# using generator function
def firstN_generator(N): i=0 while i<=N: yield i i+=1 sum_of_first_n =0 for num in firstN_generator(1000000): sum_of_first_n +=num print(sum_of_first_n )