0

I'm currently trying to create a function that will switch the nodes at index with the head of the list. So if my list (list) has the values [1, 7, 9, 12] and I call switch(list, 2), my result will be [9, 7, 1, 12]. This is the code I have so far:

"""
Creates and returns a linked list containing all of the elements
of the Python-style list parameter.  A useful shortcut for testing.
"""
def createList(plist):

    linkedList = None
    # goes backwards, adding each element to the beginning
    # of the list.  
    for index in range(len(plist)-1, -1, -1):
        linkedList = insertValueHead(linkedList, plist[index])
    return linkedList

'''
Create an empty linked list
'''
def emptyList():
  return None   #absence of a value -- nothing

'''
Creates a string representation of the values in the linked list such as:
5->6->9->14.
'''
def listString(linkedList):
  ptr = linkedList
  str1 = ''
  while ptr != None:
    str1 += str(ptr['data'])
    ptr = ptr['next']
    if ptr != None:
      str1 += "->"
  str1 = str1
  return str1

'''
Inserts a new node containing the value "value" to the head of the list.
LinkedList is the head of the list to be added to
Value is the data to be stored in the node
'''
def insertValueHead(linkedList, value):
    newnode = {}
    newnode["data"] = value
    #set the next pointer of this new node to the head of the list, linkedList
    #newnode is now the head of the list 
    newnode["next"] = linkedList
    return newnode

"""
Helper method: returns a reference to node n in a list counting from zero).
Parameters: the list and an index n
If there is no node n, returns None.
"""
def nthNode(linkedList, n):
    ptr = linkedList
    count = 0
    if n < 0:
        return None
    while ptr != None and count < n:
        ptr = ptr['next']
        count += 1
    return ptr

def switch(j, index):
  head = j
  currentItem = j       # The head again
  prevItem = None       # The item that links to tempItem
  for x in range(index):    # Find the item to swap
    prevItem = currentItem
    currentItem = currentItem['next']

  # Now we swap. We're rotating three items' .next values, so we can't
  # do the really optimized way.
  temp = currentItem['next']
  currentItem.next = head['next']
  head['next'] = prevItem['next']
  prevItem['next'] = temp


def testSwitch():
    #test code to ensure that switch() is working correctly.
    myList = createList([10, 20, 30, 40, 50, 60])
    print "The initial list", listString(myList)
    myList = switch(myList, 2)
    print "Switching the 1 and the 2.  Resulting list is ", listString(myList)
    myList = switch(myList, 3)
    print "Switching the 4 and the 5.  Resuling list is ", listString(myList)
    myList = switch(myList, 5)  
    myList = switch(myList, 29)  #should result in an error

From the switch() function I get an error saying AttributeError: 'dict' object has no attribute 'next'. How can I get around this to run the function? Where am I going wrong?

Edit 1: I've changed the parameter list to j and changed the switch functions .nexts to ['next']. Now, when running testSwitch() it comes up with the error "TypeError: 'NoneType' object has no attribute 'getitem'". Any idea where this is coming from? I've combed the code and I doesn't seem like it should be returning None before reaching the test portion...

bas_rutten19
  • 25
  • 1
  • 4

1 Answers1

0

That switch() code I wrote in your previous question assumed that each item was an object with attributes. If you've implemented it as a dictionary, use currentItem['next'] instead of currentItem.next.

EDIT: don't use the word list as a variable; that's already the name of a function. That's going to cause problems.

Community
  • 1
  • 1
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42
  • must start out as a dict but eventually becomes a list! actually ends up as a NoneType – Padraic Cunningham Aug 04 '14 at 20:23
  • @PadraicCunningham well he's implementing each node in his linked list as a dictionary, with a key for "next". So he's passing in the head of the linked list, which is a dictionary. A custom object would probably work better, but then again I wouldn't be making a linked list at all. – TheSoundDefense Aug 04 '14 at 20:27
  • 1
    I certainly would not spend this much time on it anyway! – Padraic Cunningham Aug 04 '14 at 20:28
  • Combing through my code now but it seems im getting a TypeError: 'NoneType' object has no attribute '__getitem__'. So somewhere in the code I'm getting a NONE returned... – bas_rutten19 Aug 04 '14 at 21:36
  • @bas_rutten19 you should edit your question to include the new, full error. Also I really need to ask why you're making a linked list. In Python there are so few instances where they're useful. – TheSoundDefense Aug 04 '14 at 21:38
  • I'm currently learning how to use linked lists for future languages. I know python has easier functions for the task im asking of but I really want to get in my head how to do it the "hard" way first if that makes sense. – bas_rutten19 Aug 04 '14 at 21:55
  • 1
    @bas_rutten19 that's fine, but you really need to learn how to find small errors in your code. We're handling a lot of minor typographical stuff here that you can probably detect on your own if you know how. http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – TheSoundDefense Aug 04 '14 at 21:57