So I'm trying to make a recommendation system but with sets and text files. I currently have:
colours=["black","yellow","pink","gold","light red",
"turquoise","olive","orchid","brown","orange",
"purple","golden","light blue","sandy brown","spring green",
"maroon","gray","red","green","cyan","chocolate","salmon"]
user_rec=set()
for x in range (3):
user=input(str(x+1)+". Enter the numbers of your 3 favourite colours:\n> ")
print()
user_rec.add(user)
print(user_rec)
with open("Colours.txt") as f:
for line in f:
fields=line.split(' ')
colour1=int(fields[0])
colour2=int(fields[1])
colour3=int(fields[2])
set(line).add(colour1)
set(line).add(colour2)
set(line).add(colour3)
print(set(line))
where Colours is the text file that contains 100 lines of 3 randomly generated numbers which represent the colours in the array.
The first line of the line is "8 9 17" but I get the output "{' ','7','1','9','8','\n'}" when I just want {8,9,17} so I can compare each line set to the user's set to recommend them another colour using intersection.
Can anyone tell me what I'm doing wrong?
1 Answer 1
set(line) constructs a set of all characters in the line, and that's what you print. What you want to do is:
with open("Colours.txt") as f:
for line in f:
fields=line.strip().split() # you want to remove \n
s = {int(item) for item in fields}
print(s)
set(line). You're not usingfieldsorcolour1at all...set(line)to a variable, things likeset(line).add(colour1)are creating sets which are promptly lost forever. The last 4 lines of your loop can probably be replaced byprint({colour1,colour2,colour3}). Just create the set you want directly. There is no point in building it item by item.