0

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?

asked May 22, 2020 at 12:05
2
  • 1
    You're printing set(line). You're not using fields or colour1 at all... Commented May 22, 2020 at 12:07
  • 1
    Since you are not assigning set(line) to a variable, things like set(line).add(colour1) are creating sets which are promptly lost forever. The last 4 lines of your loop can probably be replaced by print({colour1,colour2,colour3}). Just create the set you want directly. There is no point in building it item by item. Commented May 22, 2020 at 12:09

1 Answer 1

2

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)
answered May 22, 2020 at 12:11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.