Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 482
Rick supports Monica Avatar asked Dec 20 '25 14:12

Rick supports Monica


1 Answers

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.

like image 81
Lance Ruo Zhang Avatar answered Dec 22 '25 04:12

Lance Ruo Zhang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!