Collections.OrderedDict() | HackerRank Solutions

admin
By -
0

Here you just need to use collection module ordereddict and track the items is already existed inside or not if its and increment its price  and with second loop  just unpacked them here we have to usng right-side split cause some item we getting which have more then two  spaces if you  look problem sample input you understand. Here we have to use two  two  form loop  first loop  runs n-times to  takes user  two inputs item_name and its price and if item already exist in dict we just  updated its price.

This helpful to  keep the input order .




Problem:https://www.hackerrank.com/challenges/py-collections-ordereddict/problem?isFullScreen=true

Code:

# Enter your code here. Read input from STDIN. Print output to STDOUT
#naive Code:
from collections import OrderedDict

n = int(input())
order_dict = OrderedDict()
i=1
while i<=n:
    #item_name,price = input().split()
    line = input().rsplit(' ', 1)  # Split from the right (last space)
    item_name, price = line[0], int(line[1])
    if item_name in order_dict:
        order_dict[item_name]= order_dict[item_name]+int(price)
    else:
        order_dict[item_name] = int(price)
    i+=1
#print(order_dict)

for item_name, net_price in  order_dict.items():
    print(item_name, net_price)
   

for more better you can replace the while loop with for loop for_ so avoide the extarte iteration



Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*