【问题标题】:Split a number per unit of token python function [closed]每单位令牌python函数拆分一个数字[关闭]
【发布时间】:2018-07-23 09:27:28
【问题描述】:

我正在尝试创建一个函数,它接收一个数字作为参数并返回一个最多包含 3 个数字的数组。

我有 3 个令牌。 1 单元、5 单元和 25 单元。

calculateUnit(4) should = [4,0,0]

calculateUnit(7) should = [2,1,0]  (because 2 unit of 1 and 1 unit of 5 = 7)

calculateUnit(36) should = [1,2,1] (because 1 unit of 1, 2 unit of 5 and 1 unit of 25 = 36)

我有一个基本代码,我认为我需要使用模除法,我已经尝试在这里搜索以及我拥有的所有其他资源,但我可能没有使用正确的术语。

【问题讨论】:

  • SO 既不是代码编写也不是教程服务。请使用tour 并查看How to Ask。如果您的其中一项尝试有特定问题,那么 edit 给出一个 minimal reproducible example,但是 “有点糟糕” 和 “疲倦” 不是t 为题外话的问题提供真正的理由。
  • 问题未指定。是什么阻止了我def calculateUnit(n):return [n,0,0]?
  • 这被称为硬币找零问题,对于这个面额集合,贪心算法有效。 stackoverflow.com/questions/30138887/…
  • 伙计,我当然问过并搜索过。 SO 是一个社区,我更喜欢通过提问获得积分而不是管理其他人,谢谢。
  • 当你解决了你的问题后,你可能想发布一个自我回答。评论里不好回答。

标签: python-3.x math


【解决方案1】:

您可以将解决方案简化为:

def convertInToken(am):
    return [am//25, (am%25)//5, am%5]

这利用了integer-division (3.x upwards, also named floor division) 和modulo division。

如果您进行了正常除法并对其进行了取整,则除法返回完整的整数。

模除法返回除法的“余数”。

【讨论】:

  • 看起来很酷 thabks :)
【解决方案2】:

我设法做到了,但无论如何谢谢:)

    # your code goes here
import math

def convertInToken(am):
    result = [];
    #need to use 25
    if am >= 25:
        amount25 = math.floor((am/25))
        amount5 = math.floor((am-(amount25*25))/5)
        amount1 = math.floor(((am-(amount25*25)-(amount5*5))/1))

        result = result+[amount1]
        result = result+[amount5]
        result = result+[amount25]
    #need to use 5    
    elif am >= 5:
        amount5 = math.floor((am/5))
        amount1 = math.floor(((am-(amount5*5))/1))

        result = result+[amount1]
        result = result+[amount5]
        result = result+[0]
    #need to use 1   
    elif am < 5:
        result = result+[am]
        result = result+[0]
        result = result+[0]

    return result    

print(convertInToken(4))    
print(convertInToken(7))    
print(convertInToken(12))  
print(convertInToken(37))  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 2018-09-14
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多