> Python recursive function?

Python recursive function?

Posted at: 2014-12-18 
The main problems I see are that you forgot to slice secret with [1:] on your second return statement, and that you are returning a tuple of your arguments (displayed, secret, guess) instead of just displayed in the final return statement.

There's a more subtle problem, though. You don't need to test for "if guess in secret" in this program. The recursive process will look at each character of secret and discover whether or not it's the guess or not.

It seems to kind of work. you failed to explain why you think it doesn't work.

In Python, it is important to show indentation (which Y!A removes) so, in the future, if you need to post code, either use "--- " for each indentation level, or use #end comments to delimit blocks, or use a code-posting site (ideone.com, codepad.org) and post the link here.

I guessed at your indentation.

You shouldn't use an elif when an else will do. In this case, you don't even need an else.

There doesn't seem to be any reason to return 3 values, but I didn't really analyze all the logic.

def update (displayed, secret, guess):

... if secret == '' or len (displayed) != len (secret):

... ... return ''

... else:

... ... if guess in secret:

... ... ... if secret [0]==guess: return (guess + displayed [1:])

... ... ... return update (displayed [:1])

... ... return (displayed)

print update ('too', 'big', 'b')

print update ('---------', 'recursive', 'r')

neither of these work

Write a function update(displayed, secret, guess) that takes as inputs three strings – the current version of the displayed word, the secret word, and a guess – and that returns a version of the displayed word that has been updated in light of the guess. In other words, for every position at which guess appears in secret, the returned string should include guess at that position. For every position at which guess does not appear in secret, the returned string should include whatever character is currently at that position in displayed. You can use while and for For example:

>>> update('---------', 'recursive', 'r')

'r---r----'

>>> update('too', 'big', 'b')

'boo'

This is what I have but it doesn't work

def update(displayed,secret,guess):

""" returns a version of the displayed word

that has been updated in light of the guess.

"""

if secret == '' or len(displayed) != len(secret):

return ''

else:

if guess in secret:

if secret[0]==guess:

return (guess+displayed[1:],secret,guess)

return update(displayed[:1],secret[1:],guess)

elif guess not in secret:

return (displayed, secret, guess)