Search code examples
pythonpython-3.xclasscomputer-science

DrunkWalk Classes


    class Drunk:
    def __init__(self, name):
        """The name is assumed to be a string representing the drunk"""
        self.name = name
    def __str__(self):
        if self.name != None:
            return 'Anonymous'
        else:
            return self.name

# We will now define "a special case" of a drunk [A Subclass]
import random
class UsualDrunk3D(Drunk):
    def takeStep(self):
        # choose one of up/down/left/right/forward/backward with equal probability
        steps = [(1,0,0), (0,-1,0), (-1,0,0), (0,1,0), (0,0,-1), (0,0,1)]
        return random.choice(steps)


class UsualDrunk4D(Drunk):
    def takeStep(self):
        # choose one of the eight possible moves with equal probability
        steps = [(1,0,0,0), (0,-1,0,0), (-1,0,0,0), (0,1,0,0), (0,0,-1,0), (0,0,1,0), (0,0,0,1), (0,0,0,-1)]
        return random.choice(steps)

field = Field()
drunk = UsualDrunk3D('XYZW')
field.addDrunk(drunk, Location(0,0,0,0))
field.moveDrunk(drunk)
print(field.getLoc(drunk))

Hi, I am doing a drunk walk simulation, I have already defined classes for field and location but I'm having trouble with the Drunk class, I was able to cut down the error to this part of the code?

The error is coming up:

ValueError                                Traceback (most recent call last)
<ipython-input-17-9bc178e381fe> in <module>()
     27 drunk = UsualDrunk3D('XYZW')
     28 field.addDrunk(drunk, Location(0,0,0,0))
---> 29 field.moveDrunk(drunk)
     30 print(field.getLoc(drunk))

<ipython-input-12-2846f0083c6c> in moveDrunk(self, drunk)
     11             raise ValueError("Drunk not in field")
     12         else:
---> 13             dx, dy, dz, dw = drunk.takeStep()
     14             self.drunks[drunk] = self.drunks[drunk].move(dx,dy,dz,dw)
     15     def getLoc(self, drunk):

ValueError: not enough values to unpack (expected 4, got 3)

Solution

  • UsualDrunk3D.takeStep returns a tuple with 3 values.

    UsualDrunk4D.takeStep returns a tuple with 4 values.

    The code you don't show, moveDrunk, expects takeStep to return a tuple with 4 values:

    dx, dy, dz, dw = drunk.takeStep()
    

    You could make UsualDrunk3D.takeStep return 0 for one of the dimensions, e.g. dw:

    steps = [(1,0,0,0), (0,-1,0,0), (-1,0,0,0), (0,1,0,0), (0,0,-1,0), (0,0,1,0)]