Search code examples
pythonsetset-intersection

Python - Intersection of sets returns only the first value


If I input three names (Rolf, Charlie, Mike) the friends_nearby_set intersection returns only the first input (Rolf).

If I input (Charlie, Rolf, Mike) the friends_nearby_set intersection returns only (Charlie).

Expected output from friends_nearby_set intersection should be (Rolf, Charlie).

The author's code returns correct value in video tutorial I'm watching. But for some reason for me it isn't return a proper intersection. Any explanation?

friends = input('Enter three friends name, separated by commas (no spaces, please): ').split(',')

people = open('people.txt', 'r')
people_nearby = [line.strip() for line in people.readlines()]

people.close()

friends_set = set(friends)
people_nearby_set = set(people_nearby)

friends_nearby_set = friends_set.intersection(people_nearby_set)

nearby_friends_file = open('nearby_friends.txt', 'w')

for friend in friends_nearby_set:
    print(f'{friend} is nearby! Meet up with them.')
    nearby_friends_file.write(f'{friend}\n')

nearby_friends_file.close()

Here is a screenshot during debugging.

debug


Solution

  • The following is the output before you input the names Enter three friends name, separated by commas (no spaces, please)

    python sets might be case sensitive try to remove space between comma and the next name here is example

    set_1 = {'Rolf', ' Charlie'}
    set_2 = {'Rolf', 'Charlie'}
    
    print(set_1.intersection(set_2))
    

    output

    {'Rolf'}
    

    not {'Rolf', 'Charlie'} because the first got space before. so make attention when you input names input them like Rolf,Charlie,Mike

    and also try to remove extra spaces before and after the input like the following

    friends = input('Enter three friends name, separated by commas (no spaces, please): ').strip().split(',')
    

    And I saw here how you're writing might be the source of the error to just open file in the append mode instead of writing mode

    nearby_friends_file = open('nearby_friends.txt', 'w')

    to

    nearby_friends_file = open('nearby_friends.txt', 'a')

    because w will overwrite the file while a will append on the file