import time def np(x, y): trace = [[(0, 0)]] final = [] while trace: new_pos = [] current = trace.pop(-1) last_position = current[-1] if last_position == (x, y): final.append(current) else: new_pos.append((last_position[0] + 1, last_position[1])) new_pos.append((last_position[0], last_position[1] + 1)) new_pos.append((last_position[0] - 1, last_position[1])) new_pos.append((last_position[0], last_position[1] - 1)) for pos in new_pos: if (pos not in current) and ((0 <= pos[0] <= x) and (0 <= pos[1] <= y)): trace.append(current + [pos]) return len(final) def np2(x, y, trace=None): # Old version was done by recursion and is functional if trace is None: trace = [(0, 0)] current = trace[-1] if current in trace[:-1]: return 0 if current[0] > x or current[1] > y or current[0] < 0 or current[1] < 0: return 0 if (current[0], current[1]) == (x, y) and len(trace) > 1: return 1 if x + y < 2: return 1 x_1, y_1 = (current[0], current[1] + 1) if current[1] < y else (current[0], current[1]) x_2, y_2 = (current[0] + 1, current[1]) if current[0] < x else (current[0], current[1]) x_3, y_3 = current[0] - 1, current[1] x_4, y_4 = current[0], current[1] - 1 trace_1 = trace + [(x_1, y_1)] trace_2 = trace + [(x_2, y_2)] trace_3 = trace + [(x_3, y_3)] trace_4 = trace + [(x_4, y_4)] return np2(x, y, trace_1) + \ np2(x, y, trace_2) + \ np2(x, y, trace_3) + \ np2(x, y, trace_4) # for fun, I timed the two to see which is faster. both almost the same # start_time = time.time() # np2(3, 7) # end_time = time.time() # print(end_time - start_time) # start_time = time.time() # np(3, 7) # end_time = time.time() # print(end_time - start_time)