Think Python X8

From XPUB & Lens-Based wiki
Revision as of 11:05, 11 November 2008 by Michael Murtaugh (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Exercise 8.x.1

Strings have a function called replace:

S.replace (old, new[, count]) -> string

Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Write a function removechars:

replacechars(old, new, string)

So that all characters in old get replaced by new in string, for instance:

replacechars("aeiou", "", "Tomato")
=>
Tmt
	
replacechars("aeiou", "*", "Tomato")
=>
T*m*t*

Exercise 8.x.2

Use your rotate_word function from Exercise 8.12 and the idea of a "read-eval-print" loop (like that of Exercise 7.4), to create an "unscramble game".

Let the user type an initial message, scramble it some random amount, and display the scrambled message to the user. Ask the user to enter a number to rotate the message, and display the result. Repeat this until the message has been "unlocked" (ie the message is the same as it was at the beginning). You could keep a "score" of how many tries it takes to unscramble the message and display this at the end.