第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 中貪婪方法的硬幣找零問題

Python 中貪婪方法的硬幣找零問題

哈士奇WWW 2022-12-20 11:33:48
我正在嘗試在硬幣找零問題中實現(xiàn)貪心方法,但需要降低時間復雜度,因為編譯器不會接受我的代碼,而且由于我無法驗證我什至不知道我的代碼是否真的正確. 該函數(shù)應返回進行更改所需的注釋總數(shù)。如果無法獲得給定金額的找零,則返回 -1。如果金額等于面額列表中可用的一種貨幣,則返回 1。def make_change(denomination_list, amount):    denomination_list.sort()    n = len(denomination_list)    i = n - 1    ans = 0    x = 0    while i>= 0 :        while denomination_list[i]<= amount:            ans = +1            amount -= denomination_list[i]            i -= 1        if amount == 0:            x = 1        elif amount<0:            x = -1    return x    amount= 20    denomination_list = [1,15,10]    print(make_change(denomination_list, amount))
查看完整描述

1 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

如果可能,您希望盡量減少列表索引的使用,并迭代列表本身。這是一個有效的代碼:


# Pre-process denomination list before function, sorting in decreasing order

denomination_list = [1,15,10]

denomination_list.sort(reverse = True)

# Ensure ones are available for change (or infinite loop may result)

if denomination_list[-1] != 1:

    denomination_list.append(1)


def make_change(denomination_list, amount):

    change = []

    # Iterate through coins

    for coin in denomination_list:

        # Add current coin as long as not exceeding ampoiunt

        while amount:

            if coin <= amount:

                change.append(coin)

                amount -= coin

            else:

                break

    return change


amount= 43

print(make_change(denomination_list, amount))

這將適用于 的非整數(shù)值,amount并將列出向下舍入金額的變化。


查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號