Doubt Python, as a list is iterated in a repeat

Asked

Viewed 90 times

2

Hello, the following algorithm relates people and friendship relationships between them. My doubt however refers to the block is indicated in the code.

def not_the_same(user, other_user):
    return user["id"] != other_user["id"]

def not_friends(user, other_user):
    return all(not_the_same(friends, other_user)
                for friend in user["friends"])

def friends_of_friends_ids(user):
    return Counter(foaf["id"]
                   for friend in user["friends"] //dúvida
                   for foaf in friend["friends"] //nesse trecho
                   if not_the_same(user,foaf)
                   and not_friends(user,foaf))
users = [
{"id":0,"name":"Hero"},
{"id":1,"name":"Dunn"},
{"id":2,"name":"Sue"},
{"id":3,"name":"Chi"},
{"id":4,"name":"Thor"},
{"id":5,"name":"Clive"},
{"id":6,"name":"Hicks"},
{"id":7,"name":"Devin"},
{"id":8,"name":"Kate"},
{"id":9,"name":"Klein"}
]

friendship = [(0,1),(0,2),(1,2),(1,3),(2,3),(3,4),
              (4,5),(5,6),(5,7),(6,8),(7,8),(8,9)]

for user in users:
    user["friends"] = []

for i,j in friendship:
    users[i]["friends"].append(users[j])    #adicion i como um amigo de j 
    users[j]["friends"].append(users[i])    #adicion j como um amigo de i

friends_of_friends_id(users[3])

In the function call friends_of_friends_id(users[3]) I pass the list of users, but only the one exposed in the index and that should represent only {"friends":[1,2,4],"id":3,"name":"Chi"}.

for friend in user["friends"]
    for foaf in friend["friends"] 
       if not_the_same(user,foaf)
       and not_friends(user,foaf)

In the first for understand that it accesses the values of the key Friends 1,2 and 4, but in the second is it passes the variable that is used in the previous block Friend to be iterated as if it were the list of the global scope users(and it works).

My question is, did I just pass the part represented in the index {"friends":[1,2,4],"id":3,"name":"Chi"}, how can it access the rest of the indexes? I understand that python works with references but I don’t understand how this can apply here.

Thanks in advance.

1 answer

1


The problem you are having is just before the one quoted in the second for:

for i,j in friendship:
    users[i]["friends"].append(users[j])    #adicion i como um amigo de j 
    users[j]["friends"].append(users[i])    #adicion j como um amigo de i

You’re actually putting every reference in that user’s dictionary into memory (users[i]). If you print out users soon after this for you can see that he won’t be {"friends":[1,2,4],"id":3,"name":"Chi"}

What I believe you really want is

for i,j in friendship:
    users[i]["friends"].append(j)    #adicion i como um amigo de j 
    users[j]["friends"].append(i)    #adicion j como um amigo de i

Browser other questions tagged

You are not signed in. Login or sign up in order to post.