Thursday, July 30, 2020

Collections.OrderedDict()-HackerRank Solution

 Collections.OrderedDict()-HackerRank Solution

 An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.



Example

Code

>>> from collections import OrderedDict
>>> 
>>> ordinary_dictionary = {}
>>> ordinary_dictionary['a'] = 1
>>> ordinary_dictionary['b'] = 2
>>> ordinary_dictionary['c'] = 3
>>> ordinary_dictionary['d'] = 4
>>> ordinary_dictionary['e'] = 5
>>> 
>>> print ordinary_dictionary
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> 
>>> ordered_dictionary = OrderedDict()
>>> ordered_dictionary['a'] = 1
>>> ordered_dictionary['b'] = 2
>>> ordered_dictionary['c'] = 3
>>> ordered_dictionary['d'] = 4
>>> ordered_dictionary['e'] = 5
>>> 
>>> print ordered_dictionary
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

Task

You are the manager of a supermarket.
You have a list of  items together with their prices that consumers bought on a particular day.
Your task is to print each item_name and net_price in order of its first occurrence.

item_name
net_price

Input Format

The first line contains the number of items, .
The next  lines contains the item's name and price, separated by a space.

Constraints

Output Format

Print the item_name and net_price in order of its first occurrence.

Sample Input

9
BANANA FRIES 12
POTATO CHIPS 30
APPLE JUICE 10
CANDY 5
APPLE JUICE 10
CANDY 5
CANDY 5
CANDY 5
POTATO CHIPS 30

Sample Output

BANANA FRIES 12
POTATO CHIPS 60
APPLE JUICE 20
CANDY 20

Explanation

BANANA FRIES: Quantity bought: , Price: 
Net Price: 
POTATO CHIPS: Quantity bought: , Price: 
Net Price: 
APPLE JUICE: Quantity bought: , Price: 
Net Price: 
CANDY: Quantity bought: , Price: 
Net Price: 20

Collections.OrderedDict() Solution
from collections import OrderedDict
d=OrderedDict()
N=int(input())

for i in range(N):
    item,space,price=input().rpartition(' ')
    d[item]=d.get(item,0)+int(price)
    #Here d.get(item,0) will returns the price of item present in dict d if item is not present it return 0
for item, price in d.items():
    print(item, price)

Explanation- Since while taking input we have space we are managing it using rpartition where separates the input based on the mentioned separator  (' ') and, returns it in a tuple. In the next line, we used get function to get the price and add price of the same key. d.items() returns all key with value pair, which is later printed one by one using for loop.

To read more about rpartition follow this link- https://www.geeksforgeeks.org/python-string-rpartition/

0 comments:

Post a Comment

Feel free to share your thoughts and suggestion...