-3

I'm trying to create a function that receive as argument a number and return an array of 3 numbers max.

I have 3 tokens. 1 unit, 5 unit and 25 unit.

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)

I have a basic code and I think I need to use modulo division, I already tried to search here and every other resources I have but I may not use the correct terms.

btc4cash
  • 375
  • 1
  • 4
  • 15
  • 2
    SO is neither a code-writing nor tutorial service. Please take the [tour] and review [ask]. If you have a specific issue with one of your attempts then [edit] to give a [mcve] of that, but being *"kinda bad"* and *"tired"* aren't really justifications for an off-topic question. – jonrsharpe Jul 23 '18 at 09:29
  • 2
    The question is underspecified. What prevents me from `def calculateUnit(n):return [n,0,0]`? – user202729 Jul 23 '18 at 09:29
  • 2
    This is known as the coin change problem, and for this denomination set, greedy algorithm works. https://stackoverflow.com/questions/30138887/coin-change-greedy-approach – user202729 Jul 23 '18 at 09:31
  • Dude of course I asked and searched. SO is a community, I prefer earning point asking questions than moderate others one thanks you. – btc4cash Jul 23 '18 at 09:32
  • Thanks for the greedy approach – btc4cash Jul 23 '18 at 09:33
  • 1
    When you solved your problem, you may want to post a self-answer. It's not good to answer in comment. – user202729 Jul 23 '18 at 09:43

2 Answers2

1

You can reduce your solution to:

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

This leverages integer-division (3.x upwards, also named floor division) and modulo division.

Floor division returns the full integer that woud have been returned if you did a normal division and floored it.

Modulu division returns the "remainder" of a division.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

I managed to do that, but thanks anyway :)

    # 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))  
btc4cash
  • 375
  • 1
  • 4
  • 15