Split coins into combinations of different denominations Announcing the arrival of Valued...

Second order approximation of the loss function (Deep learning book, 7.33)

How long after the last departure shall the airport stay open for an emergency return?

How would this chord from "Rocket Man" be analyzed?

How do I check if a string is entirely made of the same substring?

Protagonist's race is hidden - should I reveal it?

What's the difference between using dependency injection with a container and using a service locator?

Multiple options vs single option UI

"My boss was furious with me and I have been fired" vs. "My boss was furious with me and I was fired"

What's parked in Mil Moscow helicopter plant?

The art of proof summarizing. Are there known rules, or is it a purely common sense matter?

What ability score does a Hexblade's Pact Weapon use for attack and damage when wielded by another character?

Implementing 3DES algorithm in Java: is my code secure?

Why do games have consumables?

Additive group of local rings

Co-worker works way more than he should

How can I wire a 9-position switch so that each position turns on one more LED than the one before?

How to use @AuraEnabled base class method in Lightning Component?

Is it acceptable to use working hours to read general interest books?

My bank got bought out, am I now going to have to start filing tax returns in a different state?

A faster way to compute the largest prime factor

How to open locks without disable device?

Rolling Stones Sway guitar solo chord function

Why didn't the Space Shuttle bounce back into space as many times as possible so as to lose a lot of kinetic energy up there?

Contradiction proof for inequality of P and NP?



Split coins into combinations of different denominations



Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Split Django into appsSplit large file into smaller filesSplit up an iterable into batchesMaking the same amount from different combinations of coins (top-down approach)Something to store any (standard) data in pythonSplit DAG into disjoint setsSplit mp3 of album into individual tracksSplit a data file into files for each time stepFlipping coins performanceScrape data from website into dataframe(s) using Split function





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







6












$begingroup$


I have 3 types of coins: Gold, Silver, Copper.

1 silver = 100 copper.

1 gold = 100 silver.



My input is always in coppers, and I want to be able to make it a bit more readable. So far my code is:



def api_wallet_translate_gold(value):
"""Translate a value into string of money"""
if value >= 10000: # Gold
return ("{0} gold, {1} silver and {2} copper."
.format(str(value)[:-4], str(value)[-4:-2], str(value)[-2:]))
elif value >= 100: # Silver
return "{0} silver and {1} copper.".format(str(value)[-4:-2], str(value)[-2:])
else: # Copper
return "{0} copper.".format(str(value)[-2:])


It works, but I am wondering how could it be improved. I think there was a way to format it like {xx:2:2} or something but I can't remember how to do it.



Note: We never know how many gold digits we have, it could be 999999 to 1










share|improve this question











$endgroup$



















    6












    $begingroup$


    I have 3 types of coins: Gold, Silver, Copper.

    1 silver = 100 copper.

    1 gold = 100 silver.



    My input is always in coppers, and I want to be able to make it a bit more readable. So far my code is:



    def api_wallet_translate_gold(value):
    """Translate a value into string of money"""
    if value >= 10000: # Gold
    return ("{0} gold, {1} silver and {2} copper."
    .format(str(value)[:-4], str(value)[-4:-2], str(value)[-2:]))
    elif value >= 100: # Silver
    return "{0} silver and {1} copper.".format(str(value)[-4:-2], str(value)[-2:])
    else: # Copper
    return "{0} copper.".format(str(value)[-2:])


    It works, but I am wondering how could it be improved. I think there was a way to format it like {xx:2:2} or something but I can't remember how to do it.



    Note: We never know how many gold digits we have, it could be 999999 to 1










    share|improve this question











    $endgroup$















      6












      6








      6





      $begingroup$


      I have 3 types of coins: Gold, Silver, Copper.

      1 silver = 100 copper.

      1 gold = 100 silver.



      My input is always in coppers, and I want to be able to make it a bit more readable. So far my code is:



      def api_wallet_translate_gold(value):
      """Translate a value into string of money"""
      if value >= 10000: # Gold
      return ("{0} gold, {1} silver and {2} copper."
      .format(str(value)[:-4], str(value)[-4:-2], str(value)[-2:]))
      elif value >= 100: # Silver
      return "{0} silver and {1} copper.".format(str(value)[-4:-2], str(value)[-2:])
      else: # Copper
      return "{0} copper.".format(str(value)[-2:])


      It works, but I am wondering how could it be improved. I think there was a way to format it like {xx:2:2} or something but I can't remember how to do it.



      Note: We never know how many gold digits we have, it could be 999999 to 1










      share|improve this question











      $endgroup$




      I have 3 types of coins: Gold, Silver, Copper.

      1 silver = 100 copper.

      1 gold = 100 silver.



      My input is always in coppers, and I want to be able to make it a bit more readable. So far my code is:



      def api_wallet_translate_gold(value):
      """Translate a value into string of money"""
      if value >= 10000: # Gold
      return ("{0} gold, {1} silver and {2} copper."
      .format(str(value)[:-4], str(value)[-4:-2], str(value)[-2:]))
      elif value >= 100: # Silver
      return "{0} silver and {1} copper.".format(str(value)[-4:-2], str(value)[-2:])
      else: # Copper
      return "{0} copper.".format(str(value)[-2:])


      It works, but I am wondering how could it be improved. I think there was a way to format it like {xx:2:2} or something but I can't remember how to do it.



      Note: We never know how many gold digits we have, it could be 999999 to 1







      python python-3.x formatting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 14 hours ago









      200_success

      131k17157422




      131k17157422










      asked 14 hours ago









      SaelythSaelyth

      1553




      1553






















          2 Answers
          2






          active

          oldest

          votes


















          8












          $begingroup$

          It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.



          You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with divmod(). After than it's a matter of deciding how you want to format the resulting dict:



          coins = [
          ("gold", 100 * 100),
          ("silver", 100),
          ("copper", 1)
          ]

          def translate_coins(value, coins):
          res = {}
          for coin, v in coins:
          res[coin], value = divmod(value, v)
          return res

          translate_coins(1013323, coins)


          Result:



          {'gold': 101, 'silver': 33, 'copper': 23}





          share|improve this answer











          $endgroup$













          • $begingroup$
            This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
            $endgroup$
            – S0AndS0
            13 hours ago








          • 2




            $begingroup$
            Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
            $endgroup$
            – MarkM
            13 hours ago












          • $begingroup$
            After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
            $endgroup$
            – S0AndS0
            12 hours ago



















          1












          $begingroup$

          That was a nice little break from work, tks for asking this question :-)
          I think this is a good use case for an object/class vs. a method.



          I would create a Currency class, which then allows you to either print it, or access its attributes independently...



          class Currency(object):

          COPPER_CONVERSION_MAP = {
          'copper': 1,
          'gold': 100 * 100,
          'silver': 100
          }
          gold = 0
          silver = 0
          copper = 0

          def __init__(self, copper=0, silver=0, gold=0):
          # convert all inputs into copper
          self.copper = (
          copper +
          silver * self.COPPER_CONVERSION_MAP['silver'] +
          gold * self.COPPER_CONVERSION_MAP['gold']
          )
          self.break_currency()

          def break_currency(self):
          for coin_type in ['gold', 'silver']:
          coins, coppers = divmod(self.copper, self.COPPER_CONVERSION_MAP[coin_type])
          setattr(self, coin_type, coins)
          self.copper = coppers

          def __str__(self):
          return '{:,} gold, {:,} silver and {:,} copper'.format(self.gold, self.silver, self.copper)


          You can then consume like so:



          >>> c = Currency(copper=653751735176)
          >>> str(c)
          '65,375,173 gold, 51 silver and 76 copper'
          >>> c.copper
          76
          >>> c.silver
          51
          >>> c.gold
          65375173





          share|improve this answer








          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$













          • $begingroup$
            Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
            $endgroup$
            – greybeard
            3 hours ago












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f219029%2fsplit-coins-into-combinations-of-different-denominations%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8












          $begingroup$

          It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.



          You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with divmod(). After than it's a matter of deciding how you want to format the resulting dict:



          coins = [
          ("gold", 100 * 100),
          ("silver", 100),
          ("copper", 1)
          ]

          def translate_coins(value, coins):
          res = {}
          for coin, v in coins:
          res[coin], value = divmod(value, v)
          return res

          translate_coins(1013323, coins)


          Result:



          {'gold': 101, 'silver': 33, 'copper': 23}





          share|improve this answer











          $endgroup$













          • $begingroup$
            This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
            $endgroup$
            – S0AndS0
            13 hours ago








          • 2




            $begingroup$
            Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
            $endgroup$
            – MarkM
            13 hours ago












          • $begingroup$
            After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
            $endgroup$
            – S0AndS0
            12 hours ago
















          8












          $begingroup$

          It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.



          You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with divmod(). After than it's a matter of deciding how you want to format the resulting dict:



          coins = [
          ("gold", 100 * 100),
          ("silver", 100),
          ("copper", 1)
          ]

          def translate_coins(value, coins):
          res = {}
          for coin, v in coins:
          res[coin], value = divmod(value, v)
          return res

          translate_coins(1013323, coins)


          Result:



          {'gold': 101, 'silver': 33, 'copper': 23}





          share|improve this answer











          $endgroup$













          • $begingroup$
            This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
            $endgroup$
            – S0AndS0
            13 hours ago








          • 2




            $begingroup$
            Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
            $endgroup$
            – MarkM
            13 hours ago












          • $begingroup$
            After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
            $endgroup$
            – S0AndS0
            12 hours ago














          8












          8








          8





          $begingroup$

          It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.



          You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with divmod(). After than it's a matter of deciding how you want to format the resulting dict:



          coins = [
          ("gold", 100 * 100),
          ("silver", 100),
          ("copper", 1)
          ]

          def translate_coins(value, coins):
          res = {}
          for coin, v in coins:
          res[coin], value = divmod(value, v)
          return res

          translate_coins(1013323, coins)


          Result:



          {'gold': 101, 'silver': 33, 'copper': 23}





          share|improve this answer











          $endgroup$



          It may less fragile if you deal with the numbers directly rather than converting to strings. It will also be cleaner code.



          You could start with your values in a list sorted highest to lowest. Then in your function you can find the next-largest value and remained with divmod(). After than it's a matter of deciding how you want to format the resulting dict:



          coins = [
          ("gold", 100 * 100),
          ("silver", 100),
          ("copper", 1)
          ]

          def translate_coins(value, coins):
          res = {}
          for coin, v in coins:
          res[coin], value = divmod(value, v)
          return res

          translate_coins(1013323, coins)


          Result:



          {'gold': 101, 'silver': 33, 'copper': 23}






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 14 hours ago

























          answered 14 hours ago









          MarkMMarkM

          28316




          28316












          • $begingroup$
            This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
            $endgroup$
            – S0AndS0
            13 hours ago








          • 2




            $begingroup$
            Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
            $endgroup$
            – MarkM
            13 hours ago












          • $begingroup$
            After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
            $endgroup$
            – S0AndS0
            12 hours ago


















          • $begingroup$
            This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
            $endgroup$
            – S0AndS0
            13 hours ago








          • 2




            $begingroup$
            Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
            $endgroup$
            – MarkM
            13 hours ago












          • $begingroup$
            After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
            $endgroup$
            – S0AndS0
            12 hours ago
















          $begingroup$
          This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
          $endgroup$
          – S0AndS0
          13 hours ago






          $begingroup$
          This is almost perfect @MarkM, though the def translate_coins(value, coins): line combined with res[coin], value = divmod(value, v), could have the values (one of'em) renamed for easier reading... Neat trick with the dictionary assignment there... One question too, why not use a dict for coins instead of a list of tuples?... Then for coin, quantity in coins.items(): could be used with similar effect and one less object within another. That all said I think your answer is solid, just had a few nits to be picked that I could see.
          $endgroup$
          – S0AndS0
          13 hours ago






          2




          2




          $begingroup$
          Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
          $endgroup$
          – MarkM
          13 hours ago






          $begingroup$
          Thanks for the comment @S0AndS0 those a re great suggestions. I didn't use a dictionary for the coin values because this depends on doing the division in order from highest to lowest. It's only recently that you can count on the order of python dictionaries.
          $endgroup$
          – MarkM
          13 hours ago














          $begingroup$
          After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
          $endgroup$
          – S0AndS0
          12 hours ago




          $begingroup$
          After further testing I see what you're doing, clever @MarkM, really clever there with reassigning value... though I don't envy debugging such mutations, it does totally make sense in this context to mutate... I also now see your wisdom in using a list of tuples, and retract my previous question in regards to using a dict as input to the translate_coins function; that would have made code far hairier than needed... Consider me impressed, eleven lines of code and you've taught me plenty new perversions with Python.
          $endgroup$
          – S0AndS0
          12 hours ago













          1












          $begingroup$

          That was a nice little break from work, tks for asking this question :-)
          I think this is a good use case for an object/class vs. a method.



          I would create a Currency class, which then allows you to either print it, or access its attributes independently...



          class Currency(object):

          COPPER_CONVERSION_MAP = {
          'copper': 1,
          'gold': 100 * 100,
          'silver': 100
          }
          gold = 0
          silver = 0
          copper = 0

          def __init__(self, copper=0, silver=0, gold=0):
          # convert all inputs into copper
          self.copper = (
          copper +
          silver * self.COPPER_CONVERSION_MAP['silver'] +
          gold * self.COPPER_CONVERSION_MAP['gold']
          )
          self.break_currency()

          def break_currency(self):
          for coin_type in ['gold', 'silver']:
          coins, coppers = divmod(self.copper, self.COPPER_CONVERSION_MAP[coin_type])
          setattr(self, coin_type, coins)
          self.copper = coppers

          def __str__(self):
          return '{:,} gold, {:,} silver and {:,} copper'.format(self.gold, self.silver, self.copper)


          You can then consume like so:



          >>> c = Currency(copper=653751735176)
          >>> str(c)
          '65,375,173 gold, 51 silver and 76 copper'
          >>> c.copper
          76
          >>> c.silver
          51
          >>> c.gold
          65375173





          share|improve this answer








          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$













          • $begingroup$
            Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
            $endgroup$
            – greybeard
            3 hours ago
















          1












          $begingroup$

          That was a nice little break from work, tks for asking this question :-)
          I think this is a good use case for an object/class vs. a method.



          I would create a Currency class, which then allows you to either print it, or access its attributes independently...



          class Currency(object):

          COPPER_CONVERSION_MAP = {
          'copper': 1,
          'gold': 100 * 100,
          'silver': 100
          }
          gold = 0
          silver = 0
          copper = 0

          def __init__(self, copper=0, silver=0, gold=0):
          # convert all inputs into copper
          self.copper = (
          copper +
          silver * self.COPPER_CONVERSION_MAP['silver'] +
          gold * self.COPPER_CONVERSION_MAP['gold']
          )
          self.break_currency()

          def break_currency(self):
          for coin_type in ['gold', 'silver']:
          coins, coppers = divmod(self.copper, self.COPPER_CONVERSION_MAP[coin_type])
          setattr(self, coin_type, coins)
          self.copper = coppers

          def __str__(self):
          return '{:,} gold, {:,} silver and {:,} copper'.format(self.gold, self.silver, self.copper)


          You can then consume like so:



          >>> c = Currency(copper=653751735176)
          >>> str(c)
          '65,375,173 gold, 51 silver and 76 copper'
          >>> c.copper
          76
          >>> c.silver
          51
          >>> c.gold
          65375173





          share|improve this answer








          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$













          • $begingroup$
            Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
            $endgroup$
            – greybeard
            3 hours ago














          1












          1








          1





          $begingroup$

          That was a nice little break from work, tks for asking this question :-)
          I think this is a good use case for an object/class vs. a method.



          I would create a Currency class, which then allows you to either print it, or access its attributes independently...



          class Currency(object):

          COPPER_CONVERSION_MAP = {
          'copper': 1,
          'gold': 100 * 100,
          'silver': 100
          }
          gold = 0
          silver = 0
          copper = 0

          def __init__(self, copper=0, silver=0, gold=0):
          # convert all inputs into copper
          self.copper = (
          copper +
          silver * self.COPPER_CONVERSION_MAP['silver'] +
          gold * self.COPPER_CONVERSION_MAP['gold']
          )
          self.break_currency()

          def break_currency(self):
          for coin_type in ['gold', 'silver']:
          coins, coppers = divmod(self.copper, self.COPPER_CONVERSION_MAP[coin_type])
          setattr(self, coin_type, coins)
          self.copper = coppers

          def __str__(self):
          return '{:,} gold, {:,} silver and {:,} copper'.format(self.gold, self.silver, self.copper)


          You can then consume like so:



          >>> c = Currency(copper=653751735176)
          >>> str(c)
          '65,375,173 gold, 51 silver and 76 copper'
          >>> c.copper
          76
          >>> c.silver
          51
          >>> c.gold
          65375173





          share|improve this answer








          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$



          That was a nice little break from work, tks for asking this question :-)
          I think this is a good use case for an object/class vs. a method.



          I would create a Currency class, which then allows you to either print it, or access its attributes independently...



          class Currency(object):

          COPPER_CONVERSION_MAP = {
          'copper': 1,
          'gold': 100 * 100,
          'silver': 100
          }
          gold = 0
          silver = 0
          copper = 0

          def __init__(self, copper=0, silver=0, gold=0):
          # convert all inputs into copper
          self.copper = (
          copper +
          silver * self.COPPER_CONVERSION_MAP['silver'] +
          gold * self.COPPER_CONVERSION_MAP['gold']
          )
          self.break_currency()

          def break_currency(self):
          for coin_type in ['gold', 'silver']:
          coins, coppers = divmod(self.copper, self.COPPER_CONVERSION_MAP[coin_type])
          setattr(self, coin_type, coins)
          self.copper = coppers

          def __str__(self):
          return '{:,} gold, {:,} silver and {:,} copper'.format(self.gold, self.silver, self.copper)


          You can then consume like so:



          >>> c = Currency(copper=653751735176)
          >>> str(c)
          '65,375,173 gold, 51 silver and 76 copper'
          >>> c.copper
          76
          >>> c.silver
          51
          >>> c.gold
          65375173






          share|improve this answer








          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer






          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered 5 hours ago









          FredFred

          1112




          1112




          New contributor




          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          Fred is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.












          • $begingroup$
            Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
            $endgroup$
            – greybeard
            3 hours ago


















          • $begingroup$
            Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
            $endgroup$
            – greybeard
            3 hours ago
















          $begingroup$
          Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
          $endgroup$
          – greybeard
          3 hours ago




          $begingroup$
          Welcome to Code Review. Now that you have created Currency and can compare both approaches and executions (including MarkM's thereof: What is your assessment of the relative merits?
          $endgroup$
          – greybeard
          3 hours ago


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f219029%2fsplit-coins-into-combinations-of-different-denominations%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Why do type traits not work with types in namespace scope?What are POD types in C++?Why can templates only be...

          Will tsunami waves travel forever if there was no land?Why do tsunami waves begin with the water flowing away...

          Simple Scan not detecting my scanner (Brother DCP-7055W)Brother MFC-L2700DW printer can print, can't...