0

if print(list(ns)) is added, the result is 50, while if print(list(ns)) is deleted, the result is 0, why?

import itertools

def PI(N):
    natuals = itertools.count(1,2) #start=1,step=2
    ns = itertools.takewhile(lambda x: x <= 2*N-1, natuals)
    #print(list(ns))
    na = map(lambda x: x/2, ns)#(-1)**(y//2)*4/y
    return sum(na)

if __name__ == '__main__':
    print(PI(10))
OmG
  • 18,337
  • 10
  • 57
  • 90
Noiccy
  • 3
  • 1
  • Because [`itertools.takewhile`](https://docs.python.org/3/library/itertools.html#itertools.takewhile) makes an iterator. – Georgy Sep 15 '18 at 14:57
  • Check https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory/48393588#48393588 (the 1st part - that covers this particular aspect). – CristiFati Sep 15 '18 at 15:02

1 Answers1

1

As mentioned in the comments, itertools.takewhile return an iterator, and when you apply list on ns, you iterate over the iterator and receive to end, then get nothing for the next statement (na), when you call the iterator again (ns).

Hence, it does not happen when you just print the ns instead of list(ns).

OmG
  • 18,337
  • 10
  • 57
  • 90