Rick
Rick

Reputation: 45261

Odd RuntimeError in Google foobar coding challenge

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

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

My solution is below, and it works just fine 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, the Google foobar console is giving a RuntimeError on line 4. I have tried tracking down the problem by splitting the logic up into separate chunks (hard to do without being able to print to the console screen), and it seems to be caused by this bit: str(x).

Might be relevant: the Google foobar constraints mentions code is run inside of a Python 2.7.6 sandbox. I learned using 100% Python 3, so there's a decent chance I'm doing something wrong. The constraints also say the input will be a long (which is same as an int in modern Python) between 1 and 2147483647.

Does anyone have an idea what the problem could be?

Upvotes: 3

Views: 1790

Answers (1)

Lance Ruo Zhang
Lance Ruo Zhang

Reputation: 401

One thing I have noticed (This happened with another challenge called String Cleaning), too many recursive calls don't work well in Google Foobar. It simply takes too long and then never returns back anything. I optimized my code and reduced a lot of recursion calls, which then worked.

Upvotes: 3

Related Questions