Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- in_file = "data-small.txt"
- out_file = "result-small.txt"
- def main(in_file,out_file):
- fin = open(in_file,"r")
- fout = open(out_file,"w")
- valid = 0
- count = fin.readline()
- count = int(count)
- print("Number of items : ",count)
- summary_data = {} #Use a dictonary for the summary data
- for data in fin:
- data = data.split()
- first = int(data[0])
- second = int(data[1])
- i=0
- if ((first > 0) and (first <= count) and (second > 0)):
- print("%5d %10d"%(first,second))
- fout.write("%5d %10d"%(first,second))
- fout.write('\n')
- if first in summary_data.keys(): #first we check if already a item number exists in our dictionary
- summary_data[first]+=second # We then add the order amount to the existing value
- else: # otherwise we insert the order number and order value to the summary data
- summary_data[first]=second
- valid += 1
- elif (first > count):
- print("%5d %10d %s"%(first,second,"invalid item number"))
- fout.write("%5d %10d %s"%(first,second,"invalid item number"))
- fout.write('\n')
- elif (first <= 0):
- print("%5d %10d %s"%(first,second,"invalid item number"))
- fout.write("%5d %10d %s"%(first,second,"invalid item number"))
- fout.write('\n')
- elif (second <= 0):
- print("%5d %10d %s"%(first,second,"invalid quantity"))
- fout.write("%5d %10d %s"%(first,second,"invalid quantity"))
- fout.write("%s %d"%("\nNumber of valid orders =\n",valid))
- print("\nNumber of valid orders =",valid,"\n")
- fout.write("Summary:\n") #summary of the valid orders
- print("Summary:")
- for key,value in sorted(summary_data.items()): #we then iterate the sorted dictionary of sumary data and display records
- fout.write("%5d %10d\n"%(key,value))
- print("%5d %10d"%(key,value))
- fout.close()
- fin.close()
- main(in_file,out_file)
Advertisement
Add Comment
Please, Sign In to add comment