Odd RuntimeError in google foobar coding program

This is my second task - it's called "guard_game".

The challenge is to create a function that recursively adds the digits of a number until you have a single digit, and returns that digit.

My solution is below and it works great on my machine:

answers = {}

def answer(x):
     return answers[x] if answers.setdefault(x,sum(int(_) for _ in str(x))) in xrange(1,10) else answer(answers[x])

if __name__ == '__main__':
    print answer(1235)
    print answer(13)

      

However, Google foobar console provides RuntimeError

on line 4. I tried to keep track of the problem, breaking the logic into separate fragments (hard to do, not being able print

to display the console), and it looks like it is caused by this bit: str(x)

.

Perhaps relevant: the Google foobar code mentioned indicates that the code is run inside the Python 2.7.6 sandbox. I found out using 100% Python 3, so there is a decent chance that I am doing something wrong. The constraints also say that the input will be long

(which is similar int

in modern Python) between 1 and 2147483647.

Anyone can figure out what the problem might be?

+3


source to share


1 answer


One thing I noticed (this happened with another call called String Cleaning), too many recursive calls don't work well in Google Foobar. It just takes too long and then never returns anything. I optimized my code and reduced the number of recursion calls that then worked.



+2


source







All Articles