elena1234

Legendary Farming ( sort dictionary in Python )

Jan 27th, 2022 (edited)
1,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. def check_winner(_dict):
  2.     for key, value in _dict.items():
  3.         if value < 250:
  4.             continue
  5.         _dict[key] -= 250
  6.         if key == "shards":
  7.             print("Shadowmourne obtained!")
  8.         elif key == "fragments":
  9.             print("Valanyr obtained!")
  10.         elif key == "motes":
  11.             print("Dragonwrath obtained!")
  12.         return True
  13.     return False
  14.  
  15. def order_dict_keys(dict_keys):
  16.     # Order by quantity (value) in descending order, then by name (key) in ascending order
  17.     sorted_dict = dict(sorted(dict_keys.items(), key = lambda x: (-x[1], x[0])))
  18.     return sorted_dict
  19.    
  20. def order_dict_junk(dict_junk):  
  21.     # Order by key in alphabetical order.
  22.     sorted_dict = dict(sorted(dict_junk.items(), key = lambda x: x[0]))
  23.     return sorted_dict
  24.  
  25. def print_sorted_dict(sorted_dict):
  26.     for key, value in sorted_dict.items():
  27.         print(f"{key}: {value}")
  28.    
  29.            
  30. dict_items = {"shards": 0, "fragments": 0, "motes": 0}
  31. dict_junk = {}
  32. winner = False
  33. while not winner:
  34.     line = input().split()  
  35.     for i in range(0, len(line), 2):
  36.         quantity = int(line[i])
  37.         item = line[i +1].lower()
  38.                        
  39.         if item in dict_items.keys():
  40.            dict_items[item] += quantity
  41.         else:
  42.             if item not in dict_junk:
  43.                 dict_junk[item] = 0
  44.             dict_junk[item] += quantity
  45.            
  46.         winner = check_winner(dict_items)
  47.         if winner:
  48.             break
  49.                
  50. sorted_dict_items = order_dict_keys(dict_items) # sorting is not included in Judge
  51. sorted_dict_junk = order_dict_junk(dict_junk)
  52. print_sorted_dict(sorted_dict_items)
  53. print_sorted_dict(sorted_dict_junk)      
  54.          
Add Comment
Please, Sign In to add comment