Hi,
I'm trying to make a program in python that solves word puzzles like this:
"nj" (the answer to that is "ok")
where each letter is off by one, for example a or c instead of b.

the program is supposed to generate a list of possible words which will be checked against a dictionary.

it's recursive, and each time it's called it's supposed to find the two possible letters for the beginning letter and call itself on the word minus what's just been solved.

def one(s):
        print "s:"+s
        if s == '':
            return [s]
	else:
            ans = []
	    if s[1:] == '': return ans
            print "s1:"+s[1:]
            for o in one(s[1:]):
                ans.append(prevLetter(s[0])+string.join(one(s[1:]),''))
                ans.append(nextLetter(s[0])+string.join(one(s[1:]),''))
                print "o:"+o
            return ans

but i just can't figure out how to make it work.
can anybody help me?

by the way, the functions nextLetter and prevLetter return the next and previous letter, respectively, for example nextLetter('b') will return 'c'

Thanks,
Simon Chester

Recommended Answers

All 2 Replies

but i just can't figure out how to make it work.
can anybody help me?

You were very close:

def one(s):
    if s == '':
        return [s]
    else:
        ans = []
        if s[1:] == '': return ans
        for o in one(s[1:]):
            ans.append(prevLetter(s[0])+o)
            ans.append(nextLetter(s[0])+o)
        return ans

You never made use of o in your function. You were for whatever reason trying to use ''.join(x) (NOTE: that is equivalent to string.join(x, '') ).

Your function can be further simplified as such:

def one4(s):
    if s == '': return [s]
    else:
        return [prevLetter(s[0]) + o for o in one(s[1:])] + \
               [nextLetter(s[0]) + o for o in one(s[1:])]

Thanks so much, it works perfectly! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.