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

What units are pgfphysicalheight and pgfphysicalwidth defined in?

What is /etc/mtab in Linux?

Is this homebrew racial feat, Stonehide, balanced?

Raising a bilingual kid. When should we introduce the majority language?

Does Feeblemind produce an ongoing magical effect that can be dispelled?

Why is an operator the quantum mechanical analogue of an observable?

Flash for group photos near wall

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

Why didn't the Space Shuttle bounce back into space many times as possible so that it loose lot of kinetic energy over there?

Why is this method for solving linear equations systems using determinants works?

Is accepting an invalid credit card number a security issue?

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

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

Additive group of local rings

What if Force was not Mass times Acceleration?

Would reducing the reference voltage of an ADC have any effect on accuracy?

Error: Syntax error. Missing ')' for CASE Statement

How to find the right literary agent in the USA?

How to translate "red flag" into Spanish?

What to do with someone that cheated their way through university and a PhD program?

Are these square matrices always diagonalisable?

Is there any hidden 'W' sound after 'comment' in : Comment est-elle?

A Paper Record is What I Hamper

What is ls Largest Number Formed by only moving two sticks in 508?



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 5 hours ago









      200_success

      131k17157422




      131k17157422










      asked 6 hours ago









      SaelythSaelyth

      1553




      1553




















          1 Answer
          1






          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
            4 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
            4 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
            4 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

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          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
            4 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
            4 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
            4 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
            4 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
            4 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
            4 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 5 hours ago

























          answered 5 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
            4 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
            4 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
            4 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
            4 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
            4 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
            4 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
          4 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
          4 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
          4 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
          4 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
          4 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
          4 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

          六本木駅

          Integral that is continuous and looks like it converges to a geometric seriesTesting if a geometric series converges by taking limit to infinitySummation of arithmetic-geometric series of higher orderGeometric series with polynomial exponentHow to Recognize a Geometric SeriesShowing an integral equality with series over the integersDiscontinuity of a series of continuous functionsReasons why a Series ConvergesSum of infinite geometric series with two terms in summationUsing geometric series for computing IntegralsLimit of geometric series sum when $r = 1$

          Joseph Lister