This Python script is designed to solve a problem where we need to calculate the total price for each item. The items and their prices are inputted by the user. The script uses the collections module, specifically the OrderedDict() function, to keep track of the items and their cumulative prices. The OrderedDict() function is used because it maintains the order in which elements are inserted, which is a key requirement in this problem.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The script works by first initializing an empty OrderedDict. It then enters a loop where it accepts user input for the item name and price. The item name and price are extracted using regular expressions. If the item is not already in the OrderedDict, it is added with its price. If it is already in the OrderedDict, the price is added to the existing price. This is done for all items. Finally, the script prints out each item and its total price. The use of OrderedDict() ensures that the items are printed in the order they were entered.
import collections
import re
n = int(input())
item_od = collections.OrderedDict()
for _ in range(n):
record_list = re.split(r"(\d+)$", input().strip())
item_name = record_list[0]
item_price = int(record_list[1])
if item_name not in item_od:
item_od[item_name] = item_price
else:
item_od[item_name] = item_od[item_name] + item_price
for i in item_od:
print(f"{i}{item_od[i]}")
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.