Code is after all the screenshots
Please refer screenshot of the code for indentation!
Feel free to ask any doubts and give feedback!
sales.txt
output.txt:
code(use this for proper indentation)
CODE:
#take input, name of the file
filename=input("Enter the name of the file: ")
#open the file
file=open(filename)
#2 dictionaries to hold purchased and copurchased items and their counts
purchased={}
co_purchased={}
#file.readlines will return a list of all the lines from the file
#for every line in the file
for line in file.readlines():
#split the line, get transaction id at data[0], item1 id at data[1] and item2 id at data[2]
data=line.split()
#if item2 does not exist, its a single item purchase
if data[2]=='0':
#if item exists in purchased dictionary,increase it's count
if data[1] in purchased:
purchased[data[1]]+=1
#otherwise add it to purchase dictionary with count 1
else:
purchased[data[1]]=1
#else if item2 exists
else:
#form a tuple containing item1 and item2 together
#this is because a dictionary cannot have a list as key, only tuples,numbers,string,etc can be keys
t=tuple(data[1:3])
#if t is in copurchased history,increase it's count
if t in co_purchased:
co_purchased[t]+=1
#otherwise add it to copurchase dictionary with count 1
else:
co_purchased[t]=1
#sort the 2 dictionaries based on count
#this is a standard method to sort a dictionary by value
sorted_purchased=sorted(purchased.items(),key=lambda x:x[1],reverse=True)
sorted_co_purchased=sorted(co_purchased.items(),key=lambda x:x[1],reverse=True)
#open output.txt in write mode
output_file=open("output.txt","w")
#write a heading
output_file.write("Top 10 Purchased items:\n")
#for every item in purchased
for i in sorted_purchased:
#write it to file
output_file.write(i[0]+"\n")
#write one more heading
output_file.write("Top 10 Co-Purchased items:\n")
#for every set of co-items in copurchased
for i in sorted_co_purchased:
#write them into file
output_file.write(i[0][0]+" "+i[0][1]+"\n")
3) Top-selling products (30 points) Use Python programming to find most popular single products and co-purchased...