### Thread: New to python, need help

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
15
Rep Power
0

#### New to python, need help

Hi Friends

I'm a DBA and new to python. I failed to solve a question in a interview exam. But interested to know the process. Here is the question, please help me with answer:

Here is an infinite series of alternating positive and negative terms: 1 - 1/3 + 1/5 - 1/7 + ... This series converges to PI/4. Write a Python generator for it and return the first 20 values from the generator
2. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2013
Posts
7
Rep Power
0
hey every one i am a novice to python programming.I learned from my friend that it is quite helpful in understanding java. Please do comment on this, anyone..
3. Without testing, I wrote following code.
Code:
```import fractions

def pi_over_4_terms():
'''
T = 1 - 1/3 + 1/5 - 1/7

>>> L = []
>>> for (i,term,) in enumerate(pi_over_4_terms()):
...     L.append(term)
...     if i == 3:
...         break
...
>>> [term*denominator for (term,denominator,) in zip(L, (1, 3, 5, 7))]
[1, -1, 1, -1]
>>> (1.0-1.0/3+1.0/5-1.0/7) == float(sum(L))
True
'''
n = 0
while True:
yield fractions.Fraction((-1)**n,n*2+1)
n += 1```

Turns out that when I do test my code both doctests fail. As you see, I didn't realize that integral Fraction remain as Fraction. I wasn't too sure that my sum test would pass because of intolerant comparisons. But I know better than this, and in retrospect should have written that test as
Code:
`abs(sum(reversed((1.0,-1.0/3,1.0/5,-1.0/7)))-float(sum(L))) < 1e-6`
I'm quite sure I would have passed the interview question with my code.

Code:
```\$ ( cd /tmp && python3 -m doctest s.py )
**********************************************************************
File "s.py", line 13, in s.pi_over_4_terms
Failed example:
[term*denominator for (term,denominator,) in zip(L, (1, 3, 5, 7))]
Expected:
[1, -1, 1, -1]
Got:
[Fraction(1, 1), Fraction(-1, 1), Fraction(1, 1), Fraction(-1, 1)]
**********************************************************************
File "s.py", line 15, in s.pi_over_4_terms
Failed example:
(1.0-1.0/3+1.0/5-1.0/7) == float(sum(L))
Expected:
True
Got:
False
**********************************************************************
2 of   4 in s.pi_over_4_terms
***Test Failed*** 2 failures.```

• eliskan agrees : You're hired
4. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
15
Rep Power
0

#### Thanks b49P23TIvg

Thanks b49P23TIvg
5. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
15
Rep Power
0

#### Not getting required results

Hi

What it the exact code should I use to get a Python generator for it and return the first 20 values from the generator.
6. pi_over_4_terms_iterator = iter(pi_over_4_terms())
print([next(pi_over_4_terms_iterator) for i in range(20)])

In future, you spend time with the python interpreter, tutorials, and documents.
7. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
15
Rep Power
0

#### Got error while printing

Hi I used the following code, every thing worked fine but got a error while printing:

Code:
```>>> def sqr(x):
return x*x

>>> def firstn(g, n):
for i in range(n):
yield g.next()

>>> def pi_series():
sum = 0
i = 1.0; j = 1
while(1):
sum = sum + j/i
yield 4*sum
i = i + 2; j = j * -1

>>> def euler_accelerator(g):
s0 = g.next() # Sn-1
s1 = g.next() # Sn
s2 = g.next() # Sn+1
while 1:
yield s2 - (sqr(s2 - s1))/(s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, g.next()

>>> if __name__ == '__main__': print (list(firstn(euler_accelerator(pi_series()), 8)))

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
if __name__ == '__main__': print (list(firstn(euler_accelerator(pi_series()), 8)))
File "<pyshell#3>", line 3, in firstn
yield g.next()
AttributeError: 'generator' object has no attribute 'next'```
8. Maybe the troubles in "everything worked except for my program" are python 2.7 versus python 3 issues. Use the next function, not a .next method, and make iterators.
In python3:
Code:
```def sqr(x):
return x*x

def firstn(it, n):
for i in range(n):
yield next(it)

def pi_series():
sum = 0
i, j = 1.0, 1
while True:
sum += j/i
yield 4*sum
i += 2
j *= -1

def euler_accelerator(g):
it = g()
s0 = next(it) # Sn-1
s1 = next(it) # Sn
s2 = next(it) # Sn+1
while 1:
yield s2 - (sqr(s2 - s1))/(s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, next(it)

if __name__ == '__main__':
print(list(firstn(euler_accelerator(pi_series), 8)))```
Last edited by b49P23TIvg; April 18th, 2013 at 09:32 AM.
9. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Mar 2013
Posts
15
Rep Power
0

#### Worked great thanks

Worked great thanks

Originally Posted by b49P23TIvg
Maybe the troubles in "everything worked except for my program" are python 2.7 versus python 3 issues. Use the next function, not a .next method, and make iterators.
In python3:
Code:
```def sqr(x):
return x*x

def firstn(it, n):
for i in range(n):
yield next(it)

def pi_series():
sum = 0
i, j = 1.0, 1
while True:
sum += j/i
yield 4*sum
i += 2
j *= -1

def euler_accelerator(g):
it = g()
s0 = next(it) # Sn-1
s1 = next(it) # Sn
s2 = next(it) # Sn+1
while 1:
yield s2 - (sqr(s2 - s1))/(s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, next(it)

if __name__ == '__main__':
print(list(firstn(euler_accelerator(pi_series), 8)))```