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

Array Dynamic resize in heap

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

How to find the right literary agent in the USA?

'Var' does not name a type!

How would I use different systems of magic when they are capable of the same effects?

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

Will I lose my paid in full property

401(k) cost basis

What is this word supposed to be?

FullSimplify a trigonometric expression doesn't work as expected

Why isn't everyone flabbergasted about Bran's "gift"?

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

As an international instructor, should I openly talk about my accent?

Is Electric Central Heating worth it if using Solar Panels?

Are all CP/M-80 implementations binary compatible?

Multiple options vs single option UI

SQL Query not selecting all points that it should?

How to translate "red flag" into Spanish?

Can you stand up from being prone using Skirmisher outside of your turn?

Co-worker works way more than he should

Could moose/elk survive in the Amazon forest?

Is Diceware more secure than a long passphrase?

How can I make a line end at the edge of an irregular shape?

What is "leading note" and what does it mean to "raise a note"?



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









      200_success

      131k17157422




      131k17157422










      asked 4 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
            3 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
            3 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
            2 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
            3 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
            3 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
            2 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
            3 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
            3 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
            2 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 4 hours ago

























          answered 4 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
            3 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
            3 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
            2 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
            3 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
            3 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
            2 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
          3 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
          3 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
          3 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
          3 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
          2 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
          2 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

          Bett Inhaltsverzeichnis Geschichte | Bettformen | Bettgrößen | Andere Bezeichnungen | Bettenmangel | Betten in der bildenden Kunst | Schlafmedizinische Gesichtspunkte | Siehe auch | Literatur | Weblinks | Einzelnachweise | NavigationsmenüBett, Bettstatt, BettstelleCommons: BettBabybetten: Anwendung, Ausstattungsmerkmale und VergleichskriterienWasserbetten. Vorurteile im TestHapfnNursch10.1007/s11818-012-0584-74006250-8AKS4329276-8

          Luksemburg Sisukord Nimi | Asend | Loodus | Riigikord | Haldusjaotus | Rahvastik | Riigikaitse | Majandus | Taristu | Ajalugu | Eesti ja Luksemburgi suhted | Haridus | Kultuur | Vaata ka | Viited | Välislingid | Navigeerimismenüü50° N, 6° EÜlevaade Luksemburgi kaitsealadest.Luksemburgi rahvaarv. Statistikaamet.World Bank'i andmebaasÜlevaade Luksemburgi loodusest.Ülevaade Luksemburgi metsadest.Guy Colling. "Red List of the Vascular Plants of Luxembourg." Travaux scientifiques du Musée national d’histoire naturelle Luxembourg. 2005.Luxembourg’s biodiversity at risk.Maailma kahepaiksete andmebaas.Denis Lepage. "Luxembourg." Avibase.Ülevaade temperatuuridest. Luksemburgi meteoroloogiateenistus.Ülevaade Luksemburgist. Euroopa Liidu esinduse koduleht.Système politique. TerritoireÜlevaade Luksemburgi rahvastikust. Luksemburgi statistikaamet.Luksemburgi rahvastik. Luksemburgi statistikaamet.The World FactbookMonique Borsenberger, Paul Dickes. "Religions au Luxembourg. Quelle évolution entre 1999-2008". Luksemburgi statistikaamet. 2011.Luksemburgi peapiiskopkond. Catholic-Hierarchy.Luksemburgi armee koduleht.Luksemburgi armee relvastus.Eesti Välisministeerium.Luksemburgi rahvastik. Luksemburgi statistikaamet.Luksemburgi Eesti Seltsi koduleht.Helen Eelrand. "Raadio, mis muutis maailma." Eesti Päevaleht. 13. märts 2004.Ülevaade Luksemburgi haridussüsteemist.Ülevaade Luksemburgi keskkoolidest.Luksemburgr

          Valle di Casies Indice Geografia fisica | Origini del nome | Storia | Società | Amministrazione | Sport | Note | Bibliografia | Voci correlate | Altri progetti | Collegamenti esterni | Menu di navigazione46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)46°46′N 12°11′E / 46.766667°N 12.183333°E46.766667; 12.183333 (Valle di Casies)Sito istituzionaleAstat Censimento della popolazione 2011 - Determinazione della consistenza dei tre gruppi linguistici della Provincia Autonoma di Bolzano-Alto Adige - giugno 2012Numeri e fattiValle di CasiesDato IstatTabella dei gradi/giorno dei Comuni italiani raggruppati per Regione e Provincia26 agosto 1993, n. 412Heraldry of the World: GsiesStatistiche I.StatValCasies.comWikimedia CommonsWikimedia CommonsValle di CasiesSito ufficialeValle di CasiesMM14870458910042978-6