Python doubt, such that a list is iterated in a repetition

2

Hello, the following algorithm relates the people and the friendly relationships between them. My question however refers to the for block 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 I understand that it accesses the values of the friends key 1,2 and 4, but in the second it passes the variable that is used in the previous for friend to be iterated as if it were the list of the global scope users (and works).

My question is, if I only passed 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 do not understand how this can apply here.

Thank you in advance.

    
asked by anonymous 14.02.2017 / 23:50

1 answer

1

The problem you are experiencing is a little before you mention it 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

In fact, you are putting all that user's dictionary reference in memory ( users[i] ). If you give a print to users right after this for you can see that it will not 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
    
16.02.2017 / 21:46