Fantasy game inventory — Ch. 5 Automate the Boring StuffDynamic class instancing (with conditional parameters and methods) based on a dictionaryMy implementation of item objects in a text adventureText-based fighting simulation in C++Comma Code (project from “Automate the Boring Stuff with Python”)Comma Code - Automate the Boring StuffPython Automate the Boring Stuff Collatz exerciseText-Turn based dueling gameAutomate the Boring Stuff with Python - The Collatz sequence projectComma Code - Ch. 4 Automate the Boring StuffAutomate the Boring Stuff - Collatz Exercise

Can a character with the Polearm Master feat make an opportunity attack against an invisible creature that enters their reach?

Harmonic Series Phase Difference?

How did space travel spread throughout the Star Wars galaxy?

When is the phrase "j'ai bon" used?

King or Queen-Which piece is which?

What are the mechanical differences between Adapt and Monstrosity?

In a Fish that is not a Fish

How to recover a single blank shot from a film camera

How to ask if I can mow my neighbor's lawn

How can I detect if I'm in a subshell?

How "fast" do astronomical events occur?

Credit card validation in C

Why we can't jump without bending our knees?

writing a function between sets vertically

Boundaries and Buddhism

Does knowing the surface area of all faces uniquely determine a tetrahedron?

How to make a villain when your PCs are villains?

Justifying Affordable Bespoke Spaceships

Are there examples of rowers who also fought?

What is "dot" sign in •NO?

Explicit song lyrics checker

How can the US president give an order to a civilian?

How can I ping multiple IP addresses at the same time?

Fibonacci sequence and other metallic sequences emerged in the form of fractions



Fantasy game inventory — Ch. 5 Automate the Boring Stuff


Dynamic class instancing (with conditional parameters and methods) based on a dictionaryMy implementation of item objects in a text adventureText-based fighting simulation in C++Comma Code (project from “Automate the Boring Stuff with Python”)Comma Code - Automate the Boring StuffPython Automate the Boring Stuff Collatz exerciseText-Turn based dueling gameAutomate the Boring Stuff with Python - The Collatz sequence projectComma Code - Ch. 4 Automate the Boring StuffAutomate the Boring Stuff - Collatz Exercise






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








2












$begingroup$


Here is a practice exercise — Fantasy Game Inventory $-$




You are creating a fantasy video game. The data structure to model the
player’s inventory will be a dictionary where the keys are string
values describing the item in the inventory and the value is an
integer value detailing how many of that item the player has. For
example, the dictionary value 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12 means the player has 1 rope, 6 torches,
42 gold coins, and so on.



Write a function named display_inventory() that would take any
possible “inventory” and display it like the following -



Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62


Hint - You can use a for loop to loop through all the keys in a
dictionary.




I have written the following code. Any feedback is highly appreciated.



stuff = 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

def display_inventory(inventory):
total_items = 0
print ("Inventory:")
for item in inventory:
print(str(inventory[item]) + ' ' + item)
total_items += inventory[item]
print("Total number of items: " + str(total_items))

if __name__ == '__main__':
display_inventory(stuff)









share|improve this question











$endgroup$







  • 3




    $begingroup$
    The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one.
    $endgroup$
    – Roland Illig
    10 hours ago

















2












$begingroup$


Here is a practice exercise — Fantasy Game Inventory $-$




You are creating a fantasy video game. The data structure to model the
player’s inventory will be a dictionary where the keys are string
values describing the item in the inventory and the value is an
integer value detailing how many of that item the player has. For
example, the dictionary value 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12 means the player has 1 rope, 6 torches,
42 gold coins, and so on.



Write a function named display_inventory() that would take any
possible “inventory” and display it like the following -



Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62


Hint - You can use a for loop to loop through all the keys in a
dictionary.




I have written the following code. Any feedback is highly appreciated.



stuff = 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

def display_inventory(inventory):
total_items = 0
print ("Inventory:")
for item in inventory:
print(str(inventory[item]) + ' ' + item)
total_items += inventory[item]
print("Total number of items: " + str(total_items))

if __name__ == '__main__':
display_inventory(stuff)









share|improve this question











$endgroup$







  • 3




    $begingroup$
    The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one.
    $endgroup$
    – Roland Illig
    10 hours ago













2












2








2


1



$begingroup$


Here is a practice exercise — Fantasy Game Inventory $-$




You are creating a fantasy video game. The data structure to model the
player’s inventory will be a dictionary where the keys are string
values describing the item in the inventory and the value is an
integer value detailing how many of that item the player has. For
example, the dictionary value 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12 means the player has 1 rope, 6 torches,
42 gold coins, and so on.



Write a function named display_inventory() that would take any
possible “inventory” and display it like the following -



Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62


Hint - You can use a for loop to loop through all the keys in a
dictionary.




I have written the following code. Any feedback is highly appreciated.



stuff = 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

def display_inventory(inventory):
total_items = 0
print ("Inventory:")
for item in inventory:
print(str(inventory[item]) + ' ' + item)
total_items += inventory[item]
print("Total number of items: " + str(total_items))

if __name__ == '__main__':
display_inventory(stuff)









share|improve this question











$endgroup$




Here is a practice exercise — Fantasy Game Inventory $-$




You are creating a fantasy video game. The data structure to model the
player’s inventory will be a dictionary where the keys are string
values describing the item in the inventory and the value is an
integer value detailing how many of that item the player has. For
example, the dictionary value 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12 means the player has 1 rope, 6 torches,
42 gold coins, and so on.



Write a function named display_inventory() that would take any
possible “inventory” and display it like the following -



Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62


Hint - You can use a for loop to loop through all the keys in a
dictionary.




I have written the following code. Any feedback is highly appreciated.



stuff = 'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

def display_inventory(inventory):
total_items = 0
print ("Inventory:")
for item in inventory:
print(str(inventory[item]) + ' ' + item)
total_items += inventory[item]
print("Total number of items: " + str(total_items))

if __name__ == '__main__':
display_inventory(stuff)






python performance python-3.x formatting role-playing-game






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago







Justin

















asked 11 hours ago









JustinJustin

1,640528




1,640528







  • 3




    $begingroup$
    The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one.
    $endgroup$
    – Roland Illig
    10 hours ago












  • 3




    $begingroup$
    The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one.
    $endgroup$
    – Roland Illig
    10 hours ago







3




3




$begingroup$
The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one.
$endgroup$
– Roland Illig
10 hours ago




$begingroup$
The interesting part of this task is to generate the correct plural forms from the singulars. You completely missed this one.
$endgroup$
– Roland Illig
10 hours ago










2 Answers
2






active

oldest

votes


















4












$begingroup$

I am suggesting to use fstrings and the dictionary items() method.



The



print(f'value key')


instead of



print(str(inventory[item]) + ' ' + item)


is more neatly:



def display_inventory(inventory):
total_items = 0
print ("Inventory:")

for key, value in inventory.items():
print(f'value key')
total_items += value

print(f'Total number of items: total_items')


Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.



def display_inventory(inventory):
print ("Inventory:")

for key, value in inventory.items():
print(f'value key')

print(f'Total number of items: sum(inventory.values())')





share|improve this answer









$endgroup$




















    1












    $begingroup$

    As mentioned in a comment by Roland Illig, I missed the interesting part of generating the correct plural forms from the singulars.



    Here's a module which supports Python 3 - Inflect.



    # Initialization
    import inflect
    p = inflect.engine()


    Examples -



    word = car
    print("The plural of ", word, " is ", p.plural(word))
    # cars



    word = cars
    print("The singular of ", word, " is ", p.singular_noun(word))
    # car



    My updated code, expanding on MiniMax's answer, is:



    import inflect
    p = inflect.engine()

    stuff = 'rope': 0, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

    def display_inventory(inventory):

    print ("Inventory:")
    for key, value in inventory.items():
    if value == 0 or value > 1:
    key = p.plural(key)
    print(f'value key')
    print(f'Total number of items: sum(inventory.values())')

    if __name__ == '__main__':
    display_inventory(stuff)


    This will give you the following output -



    Inventory:
    0 ropes
    6 torches
    42 gold coins
    1 dagger
    12 arrows
    Total number of items: 61





    share|improve this answer











    $endgroup$













      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%2f222354%2ffantasy-game-inventory-ch-5-automate-the-boring-stuff%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









      4












      $begingroup$

      I am suggesting to use fstrings and the dictionary items() method.



      The



      print(f'value key')


      instead of



      print(str(inventory[item]) + ' ' + item)


      is more neatly:



      def display_inventory(inventory):
      total_items = 0
      print ("Inventory:")

      for key, value in inventory.items():
      print(f'value key')
      total_items += value

      print(f'Total number of items: total_items')


      Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.



      def display_inventory(inventory):
      print ("Inventory:")

      for key, value in inventory.items():
      print(f'value key')

      print(f'Total number of items: sum(inventory.values())')





      share|improve this answer









      $endgroup$

















        4












        $begingroup$

        I am suggesting to use fstrings and the dictionary items() method.



        The



        print(f'value key')


        instead of



        print(str(inventory[item]) + ' ' + item)


        is more neatly:



        def display_inventory(inventory):
        total_items = 0
        print ("Inventory:")

        for key, value in inventory.items():
        print(f'value key')
        total_items += value

        print(f'Total number of items: total_items')


        Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.



        def display_inventory(inventory):
        print ("Inventory:")

        for key, value in inventory.items():
        print(f'value key')

        print(f'Total number of items: sum(inventory.values())')





        share|improve this answer









        $endgroup$















          4












          4








          4





          $begingroup$

          I am suggesting to use fstrings and the dictionary items() method.



          The



          print(f'value key')


          instead of



          print(str(inventory[item]) + ' ' + item)


          is more neatly:



          def display_inventory(inventory):
          total_items = 0
          print ("Inventory:")

          for key, value in inventory.items():
          print(f'value key')
          total_items += value

          print(f'Total number of items: total_items')


          Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.



          def display_inventory(inventory):
          print ("Inventory:")

          for key, value in inventory.items():
          print(f'value key')

          print(f'Total number of items: sum(inventory.values())')





          share|improve this answer









          $endgroup$



          I am suggesting to use fstrings and the dictionary items() method.



          The



          print(f'value key')


          instead of



          print(str(inventory[item]) + ' ' + item)


          is more neatly:



          def display_inventory(inventory):
          total_items = 0
          print ("Inventory:")

          for key, value in inventory.items():
          print(f'value key')
          total_items += value

          print(f'Total number of items: total_items')


          Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.



          def display_inventory(inventory):
          print ("Inventory:")

          for key, value in inventory.items():
          print(f'value key')

          print(f'Total number of items: sum(inventory.values())')






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 9 hours ago









          MiniMaxMiniMax

          23117




          23117























              1












              $begingroup$

              As mentioned in a comment by Roland Illig, I missed the interesting part of generating the correct plural forms from the singulars.



              Here's a module which supports Python 3 - Inflect.



              # Initialization
              import inflect
              p = inflect.engine()


              Examples -



              word = car
              print("The plural of ", word, " is ", p.plural(word))
              # cars



              word = cars
              print("The singular of ", word, " is ", p.singular_noun(word))
              # car



              My updated code, expanding on MiniMax's answer, is:



              import inflect
              p = inflect.engine()

              stuff = 'rope': 0, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

              def display_inventory(inventory):

              print ("Inventory:")
              for key, value in inventory.items():
              if value == 0 or value > 1:
              key = p.plural(key)
              print(f'value key')
              print(f'Total number of items: sum(inventory.values())')

              if __name__ == '__main__':
              display_inventory(stuff)


              This will give you the following output -



              Inventory:
              0 ropes
              6 torches
              42 gold coins
              1 dagger
              12 arrows
              Total number of items: 61





              share|improve this answer











              $endgroup$

















                1












                $begingroup$

                As mentioned in a comment by Roland Illig, I missed the interesting part of generating the correct plural forms from the singulars.



                Here's a module which supports Python 3 - Inflect.



                # Initialization
                import inflect
                p = inflect.engine()


                Examples -



                word = car
                print("The plural of ", word, " is ", p.plural(word))
                # cars



                word = cars
                print("The singular of ", word, " is ", p.singular_noun(word))
                # car



                My updated code, expanding on MiniMax's answer, is:



                import inflect
                p = inflect.engine()

                stuff = 'rope': 0, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

                def display_inventory(inventory):

                print ("Inventory:")
                for key, value in inventory.items():
                if value == 0 or value > 1:
                key = p.plural(key)
                print(f'value key')
                print(f'Total number of items: sum(inventory.values())')

                if __name__ == '__main__':
                display_inventory(stuff)


                This will give you the following output -



                Inventory:
                0 ropes
                6 torches
                42 gold coins
                1 dagger
                12 arrows
                Total number of items: 61





                share|improve this answer











                $endgroup$















                  1












                  1








                  1





                  $begingroup$

                  As mentioned in a comment by Roland Illig, I missed the interesting part of generating the correct plural forms from the singulars.



                  Here's a module which supports Python 3 - Inflect.



                  # Initialization
                  import inflect
                  p = inflect.engine()


                  Examples -



                  word = car
                  print("The plural of ", word, " is ", p.plural(word))
                  # cars



                  word = cars
                  print("The singular of ", word, " is ", p.singular_noun(word))
                  # car



                  My updated code, expanding on MiniMax's answer, is:



                  import inflect
                  p = inflect.engine()

                  stuff = 'rope': 0, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

                  def display_inventory(inventory):

                  print ("Inventory:")
                  for key, value in inventory.items():
                  if value == 0 or value > 1:
                  key = p.plural(key)
                  print(f'value key')
                  print(f'Total number of items: sum(inventory.values())')

                  if __name__ == '__main__':
                  display_inventory(stuff)


                  This will give you the following output -



                  Inventory:
                  0 ropes
                  6 torches
                  42 gold coins
                  1 dagger
                  12 arrows
                  Total number of items: 61





                  share|improve this answer











                  $endgroup$



                  As mentioned in a comment by Roland Illig, I missed the interesting part of generating the correct plural forms from the singulars.



                  Here's a module which supports Python 3 - Inflect.



                  # Initialization
                  import inflect
                  p = inflect.engine()


                  Examples -



                  word = car
                  print("The plural of ", word, " is ", p.plural(word))
                  # cars



                  word = cars
                  print("The singular of ", word, " is ", p.singular_noun(word))
                  # car



                  My updated code, expanding on MiniMax's answer, is:



                  import inflect
                  p = inflect.engine()

                  stuff = 'rope': 0, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12

                  def display_inventory(inventory):

                  print ("Inventory:")
                  for key, value in inventory.items():
                  if value == 0 or value > 1:
                  key = p.plural(key)
                  print(f'value key')
                  print(f'Total number of items: sum(inventory.values())')

                  if __name__ == '__main__':
                  display_inventory(stuff)


                  This will give you the following output -



                  Inventory:
                  0 ropes
                  6 torches
                  42 gold coins
                  1 dagger
                  12 arrows
                  Total number of items: 61






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 4 hours ago









                  AJNeufeld

                  8,7301831




                  8,7301831










                  answered 7 hours ago









                  JustinJustin

                  1,640528




                  1,640528



























                      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%2f222354%2ffantasy-game-inventory-ch-5-automate-the-boring-stuff%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

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單