3

So the below Python code gets the error: TypeError: 'NoneType' object has no attribute 'getitem'

I can't figure out why the list 'path1' doesn't get recognized as a list, but instead is recognized as NoneType.

I've checked previous Stack questions, googled, all of that, but I can't figure out why it is happening. This came close-ish (I think) but I can't tell why my state = path[-1] call is turning up this error.

Any thoughts? Much appreciated.

Thanks

Code:

import re
import string



gr = {
    "A":["B","C","D"],
    "B":["A","E"],
    "C":["A","E"],
    "D":["A","H","I","J"],
    "E":["B","C","F","G","H"],
    "F":["E"],
    "G":["E","H"],
    "H":["D","E","G","K"],
    "I":["D","K","L"],
    "J":["D","M"],
    "K":["I","M","H"],
    "L":["I"],
    "M":["K","J"]
    }

def graphSearch(graph, start, dest):
    frontier = [[start]]
    explored = []
    options = []
    if frontier == []: return "I hope you enjoyed riding aboard the failboat"
    while len(frontier)>0:
        path = frontier.pop()
        state = path[-1]
        if state == dest: 
            return path
        else:
            for a in graph[state]:
                if a not in path:
                    newP = path.append(a)
                    frontier.append(newP)
    return options



print graphSearch(gr, "A", "M")
Community
  • 1
  • 1
BWStearns
  • 2,567
  • 2
  • 19
  • 33

1 Answers1

5
newP = path.append(a)
frontier.append(newP)

append doesn't return anything (it modifies the original list in place), so you wind up appending a bunch of None to your list.

.pop() works fine; it's the state = path[1] that fails, because the pop() popped off one of the None items you appended in a previous iteration.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • Thanks a ton, I haven't gotten it working fully yet, but I switched " if a not in path: newP = path.append(a) frontier.append(newP)" to " if a not in path: newP = path newP.append(a) frontier.append(newP)" which got me over the typeerror hurdle. Appreciate it, cheers! – BWStearns Jan 23 '13 at 05:09
  • FYI, doing `newP = path` doesn't make a copy, so you're modifying the original list as well as the new one. If you want a copy, you can do `newP = list(path)` or just `newP = path[:]`. – Amber Jan 23 '13 at 07:08