SixPathsOfMen

I Am Now a Muslim

Mar 4th, 2023
729
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. in_file = "data-small.txt"
  2. out_file = "result-small.txt"
  3. def main(in_file,out_file):
  4.     fin = open(in_file,"r")
  5.     fout = open(out_file,"w")
  6.     valid = 0
  7.     count = fin.readline()
  8.     count = int(count)
  9.     print("Number of items : ",count)
  10.     summary_data = {} #Use a dictonary for the summary data
  11.     for data in fin:
  12.         data = data.split()
  13.         first = int(data[0])
  14.         second = int(data[1])
  15.         i=0
  16.         if ((first > 0) and (first <= count) and (second > 0)):
  17.             print("%5d %10d"%(first,second))
  18.             fout.write("%5d %10d"%(first,second))
  19.             fout.write('\n')
  20.             if first in summary_data.keys(): #first we check if already a item number exists in our dictionary
  21.                 summary_data[first]+=second # We then add the order amount to the existing value
  22.             else: # otherwise we insert the order number and order value to the summary data
  23.                 summary_data[first]=second
  24.             valid += 1
  25.         elif (first > count):
  26.             print("%5d %10d %s"%(first,second,"invalid item number"))
  27.             fout.write("%5d %10d %s"%(first,second,"invalid item number"))
  28.             fout.write('\n')
  29.         elif (first <= 0):
  30.             print("%5d %10d %s"%(first,second,"invalid item number"))
  31.             fout.write("%5d %10d %s"%(first,second,"invalid item number"))
  32.             fout.write('\n')
  33.         elif (second <= 0):
  34.             print("%5d %10d %s"%(first,second,"invalid quantity"))
  35.             fout.write("%5d %10d %s"%(first,second,"invalid quantity"))
  36.     fout.write("%s %d"%("\nNumber of valid orders =\n",valid))
  37.     print("\nNumber of valid orders =",valid,"\n")
  38.     fout.write("Summary:\n") #summary of the valid orders
  39.     print("Summary:")
  40.     for key,value in sorted(summary_data.items()): #we then iterate the sorted dictionary of sumary data and display records
  41.         fout.write("%5d %10d\n"%(key,value))
  42.         print("%5d %10d"%(key,value))
  43.     fout.close()
  44.     fin.close()
  45. main(in_file,out_file)
  46.  
Advertisement
Add Comment
Please, Sign In to add comment