跳它数字游戏 - Python

时间:2016-11-18 04:01:04

标签: python recursion

我正在尝试创建一个简单的“Jump It”游戏,它应该将数字排成一行(从文件中获取输入),并找到最便宜的路线到达终点。需要位置1和1的数字。 2并比较它们以找出哪一个较小,然后将其加到总“成本”中,然后继续下一个。

因此,对于0 3 80 6 57 10行,最便宜的路由将是3 + 6 + 10,总共19个。我得到的当前错误是“索引超出范围”,我将如何修复此错误?

def shouldJump(A):
    cost = []
    for line in A[0]:
        if (A[1] > A[2]):
            cost.append(A[1])
            shouldJump(A[2:])
        elif(A[1] < A[2]):
            cost.append(A[2])
            shouldJump(A[2:])
        elif(A[0]==''):
            shouldJump(A[1][1:])
        print(cost, end='\n')

def main():
    # This opens the file in read mode
    filename = open('input.dat', 'r')
    # Read in all the lines of the file into a list of lines
    linesList = filename.readlines()
    rows = [[int(n) for n in row.split()] for row in linesList]
    myData = [[int(val) for val in line.split()] for line in linesList[1:]]
    shouldJump(myData)
main()

3 个答案:

答案 0 :(得分:1)

这是一个用Python 2.7编写的简单递归代码。看看:

def shouldJump(A,i,n):
  if i>n-1:
    return 0
  elif i+1>n-1:
    return A[i]
  else:
    if A[i]<A[i+1]:
      return A[i] + shouldJump(A,i+2,n)
    else:
      return A[i+1] + shouldJump(A,i+2,n)


A = [[0,3,80,6,57,10],[0,1,5,7,2]]
cost = []
for line in A:
  cost.append(shouldJump(line,1,len(line)))

print cost

输出: [19, 3]

希望它有所帮助!!!

答案 1 :(得分:0)

这是实现此目的的一种简单方法

cost = 0
for pair in izip_longest(fillvalue=max(A) + 1, *[iter(A)] * 2):
    cost += min(pair)

请参阅https://docs.python.org/2/library/itertools.html#recipes

中的grouper食谱

答案 2 :(得分:0)

你可以用一行列表理解来做到这一点(不是递归的;之后添加了使用递归的要求,发牢骚):

min_cost = sum(min(pair) for pair in zip(A[::2], A[1::2]))
16

如果你想要'min_route':

min_route = [min(pair) for pair in zip(A[::2], A[1::2])]
[0, 6, 10]

其中'pair'成语取自Pairs from single list