0

I came across the following code from this question :

from collections import defaultdict
import random

class Markov:
    memory = defaultdict(list)
    separator = ' '

    def learn(self, txt):
        for part in self.breakText(txt):
            key = part[0]
            value = part[1]

            self.memory[key].append(value)

    def ask(self, seed):
        ret = []

        if not seed:
            seed = self.getInitial()

        while True:
            link = self.step(seed)

            if link is None:
                break

            ret.append(link[0])
            seed = link[1]

        return self.separator.join(ret)

    def breakText(self, txt):
        #our very own (ε,ε)
        prev = self.getInitial()

        for word in txt.split(self.separator):
            yield prev, word
            prev = (prev[1], word)

        #end-of-sentence, prev->ε
        yield (prev, '')

    def step(self, state):
        choice = random.choice(self.memory[state] or [''])

        if not choice:
            return None

        nextState = (state[1], choice)
        return choice, nextState

    def getInitial(self):
        return ('', '')

When i ran the code on my system the example didn't work.

When i ran the bob.ask() line i got an error saying ask() required 2 parameters whereas it got just one. Also when i ran the bob.ask("Mary had") part i got ' ' as the output.

P.S I ran the the code exactly as told in the answer.

Could anyone help? Thanks!

Community
  • 1
  • 1
Vin
  • 729
  • 9
  • 15
  • Could you fix the indentation between `class Markov:` and `def ask(self, seed):` ? – Aurel Apr 20 '16 at 12:17
  • For clarification there is no syntax/indentation error I probably copied it wrong into the ask question box on this website. You can ignore the small indentation errors. – Vin Apr 20 '16 at 13:57

1 Answers1

1

I think you're right. It doesn't work because ask expects an argument (seed), as defined by

def ask(self, seed): 

This line

if not seed:
    seed = self.getInitial()

suggests that you can fix the issue by setting a default argument for seed. Try this:

def ask(self, seed=False):

which works for me.

JARS
  • 1,109
  • 7
  • 10