0

I am trying to create a Graph of nodes as a Dictionary but I'm getting some unexpected results:

It is a Node of the Graph if the word's last letter is equal of the second name first letter

My list:

names = ["Mark", "Kelly", "Kurt", "Terk"]

My code:

n = [ x.lower() for x in names ]
graph = {}
temp = []
for x in n:
    temp.clear()
    for y in n:
        if(x[-1]==y[0] and not x==y):
            temp.append(y)
    graph[x] = temp

Result:

{'kurt': ['kelly', 'kurt'], 'terk': ['kelly', 'kurt'], 'kelly': ['kelly', 'kurt'], 'mark': ['kelly', 'kurt']}

Expected behavior

{'kurt': ['terk'], 'terk': ['kelly', 'kurt'], 'kelly': [], 'mark': ['kelly', 'kurt']}

What am I doing wrong?

halfer
  • 19,824
  • 17
  • 99
  • 186
Ludisposed
  • 1,709
  • 4
  • 18
  • 38
  • 2
    `graph[x] = temp` doesn't copy the `list`. You then `clear` and repopulate it. All `graph[x]` are using the same `list` – Peter Wood May 19 '17 at 09:57
  • Possible duplicate of [Changing an element in one list changes multiple lists ..?](http://stackoverflow.com/questions/18946728/changing-an-element-in-one-list-changes-multiple-lists) – Arya McCarthy May 19 '17 at 09:59

1 Answers1

2

.clear only empties the list, but the same list is being assigned to the keys and then cleared again; the final state of the list is what you have across all keys. Consider creating a new list for each item:

...
for x in n:
    temp = []
    for y in n:
        if x[-1]==y[0] and x!=y:
            temp.append(y)
    graph[x] = temp
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139