为什么我的函数定义开始引发语法错误?

时间:2018-11-06 17:15:52

标签: python python-3.x coin-change

首先,在使用python时,我是一个初学者。我正在编写一个针对硬币兑换问题的函数,并附加了一些限制(在给出每种硬币类型的数量及其值的列表后,找到最好的付款方式)。

该函数运行良好,当函数开头的突然语句引起语法错误时,我几乎完成了工作。我一开始都没有编辑过它们,我正在整理发生时的最后几个问题。

我已粘贴函数的开头,注意更改( amount )将返回最合适的支付 amount 的方式。 谁能说出为什么以前的许多测试都没有这样做,为什么会开始出现语法错误?

def pay_with_coins(amount, pocket):
    change_otpt = change(amount)
    import copy
    amount = amount*100 #puts amount in pennies
    original_pocket = copy.deepcopy(pocket)
    original_amount = copy.deepcopy(amount)
    change_amount = copy.deepcopy(amount)
    original_pocket2 = copy.deepcopy(original_pocket)
    original_amount2 = (copy.deepcopy(original_amount)
    coins = [200,100,50,20,10,5,2,1]    #syntax error 1
    output = [0 for i in range(9)]      #syntax error 2
    ##find pocket value
    def value(pocket):
        value = 0
        for i in range(8):
            value += (pocket[i]*coins[i])
        return value
    pocket_val = value(pocket)
    #print("pocket value is:", pocket_val)

    ##easy case: is there enough money to pay (pocket value less than)
    if pocket_val < amount:
        print('False')
        return False

    ##checking if change() can give a suitable answer########
    count = 0 #variable to check how indexes in change_otpt are within pocket
    for i in range (8):
        if change_otpt[i] <= pocket[i]:
            count += 1
    if count == 8:#i.e output of change() is contained within pocket
        change_otpt.append(0)
    elif:
        change_otpt = [0 for i in range(8)]
    change_used = sum(change_otpt) #how many coins did this method use?
    print('change method returned: ', change_otpt)
    for i in range(7):
        change_amount -= change_otpt[i]*coins[i]
    print('change_amount is',change_amount)

1 个答案:

答案 0 :(得分:2)

第9行有一个额外的开头括号。

 ...
 8: original_pocket2 = copy.deepcopy(original_pocket)
 9: original_amount2 = (copy.deepcopy(original_amount)
                       ^ remove this parenthesis here
10: coins = [200,100,50,20,10,5,2,1]    #syntax error 1
11: output = [0 for i in range(9)]      #syntax error 2
...