Python program for suggesting friends in a social network to those who have mutual friends

Question:

I’m trying to create a python program that reads a .txt file (a social network as input for the code)
(– means new line, for reference)

since i’m fairly new to python nothing i seem to do manages to make the code read the .txt file and work, so far i’ve only made it slightly work once but had to scrap the code since it only works with a very specific .txt file and the program must be able to run with any .txt file in the same layout as above.

My goal is to make it so those who aren’t friends but have mutual friends are suggested to each other.

I am looking for any sort of support with this task.

Asked By: sidar

||

Answers:

Here is an example of a Python program that reads a social network from a .txt file and suggests friends for users based on mutual friends:

def read_file(file_name):
    with open(file_name, "r") as file:
        lines = file.readlines()
        num_of_users = int(lines[0].strip())
        friends = {}
        for i in range(1, num_of_users + 1):
            user_friends = lines[i].strip().split()
            friends[user_friends[0]] = user_friends[1:]
    return friends

def suggest_friends(friends):
    suggested_friends = {}
    for user, friend_list in friends.items():
        suggested_friends[user] = []
        for friend in friend_list:
            suggested_friends[user] += [f for f in friends[friend] if f != user and f not in friend_list and f not in suggested_friends[user]]
    return suggested_friends

def main():
    friends = read_file("network.txt")
    suggested_friends = suggest_friends(friends)
    for user, suggested in suggested_friends.items():
        print(f"{user} should be friends with {', '.join(suggested)}")

if __name__ == "__main__":
    main()

This code reads the .txt file line by line and stores the relationships between users in a dictionary. Then, the code suggests friends for each user by checking the friends of each friend and adding those who are not already friends and not already suggested as friends. The code prints the suggested friends for each user.

Answered By: Elkorchi Alae
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.