# [Baypiggies] return value from a recursive function is None while it should not be ...

Benjamin Sergeant bsergean at gmail.com
Wed Sep 3 20:57:50 CEST 2008

```== The background ==

I'm trying to solve problem 26 from project euler:
http://projecteuler.net/index.php?section=problems&id=26
The goal is to find digits recurring cycle in rational number fractional parts.
1 / 3 = 0.3333333 -> 3 is a recuring integer
1 / 7 = 0.142857

== The python problem ==

I have the following piece of code that try to solve that, probably
not elegant but it kind of work. You can copy paste it and you should
have the same output as I have, an assertion error: assert (
recurring_cycle(3) == '3'). find_recurring_part() returns a, that is
printed and equals 3, but when recurring_cycle get it, it has become
None !!

Does anyone know what's going on ?

Thanks !
- Benjamin.

\$ cat level26_strangeness.py
#!/usr/bin/env python

from decimal import Decimal, getcontext
from re import findall

def find_recurring_part(a, found):
'''
>>> re.findall(r'(\d+)\1', '32323232')
['3232']
'''
result = findall(r'(\d+)\1', a)
print a, result, found
if len(result) == 0:
return a if found else None # doing an old school if else does not help
else:
find_recurring_part(result, True)

def recurring_cycle(i):
q = Decimal(1) / Decimal(i)
q = str(q)[2:]
return find_recurring_part(q, False)

getcontext().prec = 10 # increase for bigger numbers
assert ( recurring_cycle(2) == None)
assert ( recurring_cycle(3) == '3')

\$ ./level26_strangeness.py
5 [] False
3333333333 ['33333'] False
33333 ['33'] True
33 ['3'] True
3 [] True
Traceback (most recent call last):
File "./level26_strangeness.py", line 25, in <module>
assert ( recurring_cycle(3) == '3')
AssertionError
```

More information about the Baypiggies mailing list