1
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

    def __str__(self):
        return "Node({})".format(self.value)

    __repr__ = __str__


class Stack:
    def __init__(self):
        self.top = None

    def __str__(self):
        #output presentation:
        #format show: top and stack.
        temp=self.top
        out=[]
        while temp:
            out.append(str(temp.value))
            temp=temp.next
        out='\n'.join(out)
        return ('Top:{}\nStack:\n{}'.format(self.top,out))

    __repr__=__str__

    def isEmpty(self):
        #write your code here
        return self.top == None

    def len(self):
        #write your code here
        current = self.top
        len = 0
        while current:
            len += 1
            current = current.next
        return len

    def peek(self):
        #write your code here
        if self.isEmpty():
            return None
        else:
            return self.top.value

    def push(self,value):
        #write your code here
        node = Node(value)
        if self.top is None:
            self.top = node
        else:
            node.next = self.top
            self.top = node

    def pop(self):
        #write your code here
        if self.isEmpty():
            return "Stack is Empty"
        else:
            popped = self.top.value
            self.top = self.top.next
            return popped

class StackTower:
    def __init__(self, numDisks, A = Stack(), B = Stack(), C = Stack()):
        self.numDisks = numDisks
        self.A = A
        self.B = B
        self.C = C

    def validMove(self, A, B):
        if not len(A):
            A.push(B.pop())
        elif not len(B):
            B.push(A.pop())
        elif peek(A) > peek(B):
            A.push(B.pop())
        else:
            B.push(A.pop())

    def hanoi(self, n):
        if n%2==0:
            self.B, self.C, self.A = self.C, self.A, self.B
        for i in range(1, 2**n-1):
            if i%3 == 1:
                validMove(A, C)
            if i%3 == 2:
                validMove(A, B)
            if i%3 == 0:
                validMove(B, C)


n = int(input("enter number: "))
tower = StackTower(3, "A", "B", "C")
tower.hanoi(n)
print(tower)

For this assignment, I have to write iterative python code to showcase the step for the algo of towers of Hanoi.

The output said that the function validMove is not defined. I understand the pseudo code but Im not proficient in python.

Other than that, what is the most efficient way I can do to display output of every step?

Please help me. Thank you! I really appreciate any help.

Hang Nguyen
  • 367
  • 2
  • 9
  • Hang, your error is that you need to use the prefix `self.` to reference member functions of classes, in other methods of the class. Please see the duplicate I linked to for more information. – Christian Dean Mar 11 '19 at 02:42

0 Answers0