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

Should I include salary information on my CV?

Can the US president have someone sent to jail?

How to get cool night-vision without lame drawbacks?

Why do some professors with PhDs leave their professorships to teach high school?

Go Get the Six Six-Pack

How to split an equation over two lines?

What do you call a weak person's act of taking on bigger opponents?

Require advice on power conservation for backpacking trip

What kind of wire should I use to pigtail an outlet?

Short and long term plans in a closed game in the Sicilian Defense

In the Marvel universe, can a human have a baby with any non-human?

What happens when I sacrifice a creature when my Teysa Karlov is on the battlefield?

Animation advice please

Should my manager be aware of private LinkedIn approaches I receive? How to politely have this happen?

Is this one of the engines from the 9/11 aircraft?

Why do some games show lights shine through walls?

Is there any set of 2-6 notes that doesn't have a chord name?

What reason would an alien civilization have for building a Dyson Sphere (or Swarm) if cheap Nuclear fusion is available?

Does ultrasonic bath cleaning damage laboratory volumetric glassware calibration?

Why would people reject a god's purely beneficial blessing?

How can I repair scratches on a painted French door?

Would a two-seat light aircaft with a landing speed of 20 knots and a top speed of 180 knots be technically possible?

STM Microcontroller burns every time

What is the legal status of travelling with (unprescribed) methadone in your carry-on?



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;








5












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







  • 8




    $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
    Jun 15 at 14:38










  • $begingroup$
    @RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out.
    $endgroup$
    – Justin
    Jun 16 at 4:13

















5












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







  • 8




    $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
    Jun 15 at 14:38










  • $begingroup$
    @RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out.
    $endgroup$
    – Justin
    Jun 16 at 4:13













5












5








5


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 Jun 15 at 18:19







Justin

















asked Jun 15 at 14:01









JustinJustin

1,8666 silver badges29 bronze badges




1,8666 silver badges29 bronze badges







  • 8




    $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
    Jun 15 at 14:38










  • $begingroup$
    @RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out.
    $endgroup$
    – Justin
    Jun 16 at 4:13












  • 8




    $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
    Jun 15 at 14:38










  • $begingroup$
    @RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out.
    $endgroup$
    – Justin
    Jun 16 at 4:13







8




8




$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
Jun 15 at 14:38




$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
Jun 15 at 14:38












$begingroup$
@RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out.
$endgroup$
– Justin
Jun 16 at 4:13




$begingroup$
@RolandIllig - Please check my answer below which covers your suggestion. Thank you for pointing this out.
$endgroup$
– Justin
Jun 16 at 4:13










2 Answers
2






active

oldest

votes


















9












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

    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 = "torch"
    print(f"The plural of 'word' is 'p.plural(word)'.")


    >>> The plural of 'torch' is 'torches'.



    word = "torches"
    print(f"The singular of 'word' is 'p.singular_noun(word)'.")


    >>> The singular of 'torches' is 'torch'.



    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 != 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 the following output -



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


    OR



    In cases like this -



    stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0


    where -



    'ropes': 1, 'torches': 1, 'daggers': 1


    you will need to generate the correct singular forms from the plurals.



    Therefore, expanding more on the previous code, I get -



    import inflect
    p = inflect.engine()

    stuff = stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0

    def display_inventory(inventory):
    print ("Inventory:")
    for key, value in inventory.items():

    if value != 1:
    key = p.plural(key)
    else:
    key = p.singular_noun(key)

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

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


    This will give the following output:



    Inventory:
    1 rope
    1 torch
    42 gold coins
    1 dagger
    0 arrows
    Total number of items: 45







    share|improve this answer











    $endgroup$












    • $begingroup$
      Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
      $endgroup$
      – Graipher
      Jun 16 at 9:42






    • 1




      $begingroup$
      @Graipher The documentation of the inflict package suggests p.plural(key, value).
      $endgroup$
      – Roland Illig
      Jun 16 at 11:07










    • $begingroup$
      @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
      $endgroup$
      – Graipher
      Jun 16 at 11:16













    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









    9












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

















      9












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















        9












        9








        9





        $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 Jun 15 at 15:48









        MiniMaxMiniMax

        3561 silver badge7 bronze badges




        3561 silver badge7 bronze badges























            4












            $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 = "torch"
            print(f"The plural of 'word' is 'p.plural(word)'.")


            >>> The plural of 'torch' is 'torches'.



            word = "torches"
            print(f"The singular of 'word' is 'p.singular_noun(word)'.")


            >>> The singular of 'torches' is 'torch'.



            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 != 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 the following output -



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


            OR



            In cases like this -



            stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0


            where -



            'ropes': 1, 'torches': 1, 'daggers': 1


            you will need to generate the correct singular forms from the plurals.



            Therefore, expanding more on the previous code, I get -



            import inflect
            p = inflect.engine()

            stuff = stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0

            def display_inventory(inventory):
            print ("Inventory:")
            for key, value in inventory.items():

            if value != 1:
            key = p.plural(key)
            else:
            key = p.singular_noun(key)

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

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


            This will give the following output:



            Inventory:
            1 rope
            1 torch
            42 gold coins
            1 dagger
            0 arrows
            Total number of items: 45







            share|improve this answer











            $endgroup$












            • $begingroup$
              Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
              $endgroup$
              – Graipher
              Jun 16 at 9:42






            • 1




              $begingroup$
              @Graipher The documentation of the inflict package suggests p.plural(key, value).
              $endgroup$
              – Roland Illig
              Jun 16 at 11:07










            • $begingroup$
              @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
              $endgroup$
              – Graipher
              Jun 16 at 11:16















            4












            $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 = "torch"
            print(f"The plural of 'word' is 'p.plural(word)'.")


            >>> The plural of 'torch' is 'torches'.



            word = "torches"
            print(f"The singular of 'word' is 'p.singular_noun(word)'.")


            >>> The singular of 'torches' is 'torch'.



            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 != 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 the following output -



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


            OR



            In cases like this -



            stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0


            where -



            'ropes': 1, 'torches': 1, 'daggers': 1


            you will need to generate the correct singular forms from the plurals.



            Therefore, expanding more on the previous code, I get -



            import inflect
            p = inflect.engine()

            stuff = stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0

            def display_inventory(inventory):
            print ("Inventory:")
            for key, value in inventory.items():

            if value != 1:
            key = p.plural(key)
            else:
            key = p.singular_noun(key)

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

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


            This will give the following output:



            Inventory:
            1 rope
            1 torch
            42 gold coins
            1 dagger
            0 arrows
            Total number of items: 45







            share|improve this answer











            $endgroup$












            • $begingroup$
              Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
              $endgroup$
              – Graipher
              Jun 16 at 9:42






            • 1




              $begingroup$
              @Graipher The documentation of the inflict package suggests p.plural(key, value).
              $endgroup$
              – Roland Illig
              Jun 16 at 11:07










            • $begingroup$
              @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
              $endgroup$
              – Graipher
              Jun 16 at 11:16













            4












            4








            4





            $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 = "torch"
            print(f"The plural of 'word' is 'p.plural(word)'.")


            >>> The plural of 'torch' is 'torches'.



            word = "torches"
            print(f"The singular of 'word' is 'p.singular_noun(word)'.")


            >>> The singular of 'torches' is 'torch'.



            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 != 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 the following output -



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


            OR



            In cases like this -



            stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0


            where -



            'ropes': 1, 'torches': 1, 'daggers': 1


            you will need to generate the correct singular forms from the plurals.



            Therefore, expanding more on the previous code, I get -



            import inflect
            p = inflect.engine()

            stuff = stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0

            def display_inventory(inventory):
            print ("Inventory:")
            for key, value in inventory.items():

            if value != 1:
            key = p.plural(key)
            else:
            key = p.singular_noun(key)

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

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


            This will give the following output:



            Inventory:
            1 rope
            1 torch
            42 gold coins
            1 dagger
            0 arrows
            Total number of items: 45







            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 = "torch"
            print(f"The plural of 'word' is 'p.plural(word)'.")


            >>> The plural of 'torch' is 'torches'.



            word = "torches"
            print(f"The singular of 'word' is 'p.singular_noun(word)'.")


            >>> The singular of 'torches' is 'torch'.



            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 != 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 the following output -



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


            OR



            In cases like this -



            stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0


            where -



            'ropes': 1, 'torches': 1, 'daggers': 1


            you will need to generate the correct singular forms from the plurals.



            Therefore, expanding more on the previous code, I get -



            import inflect
            p = inflect.engine()

            stuff = stuff = 'ropes': 1, 'torches': 1, 'gold coin': 42, 'daggers': 1, 'arrow': 0

            def display_inventory(inventory):
            print ("Inventory:")
            for key, value in inventory.items():

            if value != 1:
            key = p.plural(key)
            else:
            key = p.singular_noun(key)

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

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


            This will give the following output:



            Inventory:
            1 rope
            1 torch
            42 gold coins
            1 dagger
            0 arrows
            Total number of items: 45








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 17 at 2:32

























            answered Jun 15 at 18:03









            JustinJustin

            1,8666 silver badges29 bronze badges




            1,8666 silver badges29 bronze badges











            • $begingroup$
              Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
              $endgroup$
              – Graipher
              Jun 16 at 9:42






            • 1




              $begingroup$
              @Graipher The documentation of the inflict package suggests p.plural(key, value).
              $endgroup$
              – Roland Illig
              Jun 16 at 11:07










            • $begingroup$
              @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
              $endgroup$
              – Graipher
              Jun 16 at 11:16
















            • $begingroup$
              Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
              $endgroup$
              – Graipher
              Jun 16 at 9:42






            • 1




              $begingroup$
              @Graipher The documentation of the inflict package suggests p.plural(key, value).
              $endgroup$
              – Roland Illig
              Jun 16 at 11:07










            • $begingroup$
              @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
              $endgroup$
              – Graipher
              Jun 16 at 11:16















            $begingroup$
            Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
            $endgroup$
            – Graipher
            Jun 16 at 9:42




            $begingroup$
            Yes, that works. An easier way would probably be using a ternary: key = p.plural(key) if value > 1 else p.singular_noun(key)
            $endgroup$
            – Graipher
            Jun 16 at 9:42




            1




            1




            $begingroup$
            @Graipher The documentation of the inflict package suggests p.plural(key, value).
            $endgroup$
            – Roland Illig
            Jun 16 at 11:07




            $begingroup$
            @Graipher The documentation of the inflict package suggests p.plural(key, value).
            $endgroup$
            – Roland Illig
            Jun 16 at 11:07












            $begingroup$
            @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
            $endgroup$
            – Graipher
            Jun 16 at 11:16




            $begingroup$
            @RolandIllig Might be, I don't know the packet. I just used the commands as they are in the post.
            $endgroup$
            – Graipher
            Jun 16 at 11:16

















            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

            Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form