Need help Recording a recursive function that finds the cheapest route through a list of numbers

So, I have been working on this homework problem for several hours, I will do my best to explain it.

I need to write a program in python that takes a list and launches you in the first element in the list, you can either move to one place or jump over an item and land on the other hand, each element that you land on the expenses number at that place. The goal is to get to the end as cheaply as possible.

I wrote this function,

def player(cost, board, player_pos):
    if player_pos == (len(board)) - 1:    
        return cost
    if player_pos < (len(board)) - 2:     
        if board[player_pos + 1] > board[player_pos + 2]:
            return player(cost + board[player_pos + 2], board, player_pos + 2)
        else:
            return player(cost + board[player_pos + 1], board, player_pos + 1)
    elif player_pos == (len(board)) - 2:
        return (cost + board[player_pos] + board[player_pos + 1])

, . [0,1,2,1000,0], 3, 1 2, 2 1000, 0. 3, - 2, 0.

, , , , , , .

EDIT: , , . . , , , , . [0, 98, 7, 44, 25, 3, 5, 85, 46, 4] , 87, 124. :

def player(cost, board, player_pos):
    if player_pos == (len(board)) - 1:    
        return cost
    if player_pos < (len(board)) - 2:     
        if (player(cost + board[player_pos + 2], board, player_pos + 2)) < (player(cost + board[player_pos + 1], board, player_pos + 1)):
            return player(cost + board[player_pos + 2], board, player_pos + 2)
        else: return player(cost + board[player_pos + 1], board, player_pos + 1)
    elif player_pos == (len(board)) - 2:
        return (cost + board[player_pos] + board[player_pos + 1])
+4
3

:

def player(l):
    a = b = l[0]
    for v in l[1:]:
        a, b = b, min(a, b) + v
    return b

:

>>> player([0, 98, 7, 44, 25, 3, 5, 85, 46, 4])
87

. c(i) , i, :

c (1) =

c (2) =

i > 2 - , i - 1 th, i th , i - 2 th, i th .

c (i) = min (c (i - 1), c (i - 2)) + i th element

, a, b .

:

def player(l):
    return min(player(l[:-1]), player(l[:-2])) + l[-1] if l else 0

2 , fibonnaci. , . , memoization, :

def player(l, cache=None):
    n = len(l)
    if cache is None:
        cache = [-1] * (n + 1)
    if cache[n] < 0:
        cache[n] = min(player(l[:-1], cache), player(l[:-2], cache)) + l[-1] if l else 0
    return cache[n]
+7

. ! , , ( ) ( ). , , , 1.

def best_choice(l):
    if len(l) == 0:
        return 0
    elif len(l) == 1:
        return l[0]
    else: 
        return min(l[0] + best_choice(l[1:]), l[1] + best_choice(l[2:]))
+1

Your algorithm should not drop the 0 → 2 jump just because 0 → 1 seems immediately better. He must explore both possibilities.

So, your branches of your program, and two branches investigate the subtasks [1, 2, 1000, 0] and [2, 1000, 0]. Then the second branch of the program will be able to find the path 0 → 2 → 0.

0
source

All Articles