p_input = 312051 total, level = 1, 1 while total < p_input: level += 2 total = total + level*4 - 4 # or the easy (not my) way: total = level ** 2 offset = total - p_input steps = offset % (level - 1) print (level - 1) / 2 + abs((level / 2) - steps) # x, y, value values = [(0, 0, 1)] directions = [(0, 1), (-1, 0), (0, -1), (1, 0)] level = 1 x, y = 0, 0 terminate = False while not terminate: for direction in range(4): if terminate: break dirX, dirY = directions[direction] if direction == 0: moveN = level - 2 elif direction in [1, 2]: moveN = level - 1 else: moveN = level for _ in range(moveN): x += dirX y += dirY new = sum([k[2] for k in values if abs(x-k[0]) <= 1 and abs(y-k[1]) <= 1]) values.append((x, y, new)) if new >= p_input: print new terminate = True break level += 2
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question