我目前正在学习有关算法的课程。我已经成功完成了这项作业。所有测试用例都通过了。我的代码看起来很乱,我想知道Python中是否有任何可用的东西可以帮助我更快地运行代码。谢谢
问题陈述如下:您将获得一个原始计算器,该计算器可以执行以下三个操作: 当前数字:乘以2,乘以3,或加1。您的目标被赋予 正整数,找到获得数量所需的最小操作数 从数字1开始。
# Uses python3
import sys
def optimal_sequence(m):
a=[0,0]
for i in range(2,m+1):
if i%3==0 and i%2==0:
a.append(min(a[i//2],a[i//3],a[i-1])+1)
elif i%3==0:
a.append(min(a[i//3],a[i-1])+1)
elif i%2==0:
a.append(min(a[i//2],a[i-1])+1)
else:
a.append((a[i-1])+1)
return backtrack(a,m)
def backtrack(a,m):
result=[]
result.append(m)
current = m
for i in range(a[-1],0,-1):
if current%3==0 and a[current//3]==(i-1):
current=current//3
result.append(current)
elif current%2==0 and a[current//2]==(i-1):
current = current//2
result.append(current)
elif a[current-1]==(i-1):
current = current-1
result.append(current)
return result
n = int(input())
if n == 1:
print(0)
print(1)
sys.exit(0)
a= (optimal_sequence(n))
print(len(a)-1)
for x in reversed(a):
print(x,end=" ")
答案 0 :(得分:0)
我会从数字 n 开始对数字1进行广度优先搜索。跟踪已访问的号码,以便搜索回溯已访问的号码。对于访问的号码,请记住您是“到达”的号码,即到达 n 的最短路径中的下一个号码。
在我的测试中,该代码的运行速度比您的代码快:
from collections import deque
def findOperations(n):
# Perform a BFS
successor = {} # map number to next number in shortest path
queue = deque() # queue with number pairs (curr, next)
queue.append((n,None)) # start at n
while True:
curr, succ = queue.popleft()
if not curr in successor:
successor[curr] = succ
if curr == 1:
break
if curr%3 == 0: queue.append((curr//3, curr))
if curr%2 == 0: queue.append((curr//2, curr))
queue.append((curr-1, curr))
# Create list from successor chain
result = []
i = 1
while i:
result.append(i)
i = successor[i]
return result
使用参数 n 调用此函数:
findOperations(n)
它返回一个列表。