Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Python help, please?

Name: Anonymous 2013-03-19 15:39

/prog/ How do I do this using recursion? I finished this using a loop but it turns out that I cannot do this question using any sort of iteration. Heres my code:


def replace_str(base, target, rep):
    for i in range(len(base)):
        if target == base[i:i + len(target)]:
            base = base[:i] + rep + base[i + len(target):]
    print base


Heres the assignment:

The Microsoft Word Find and Replace function finds the target in the whole document    and replaces it with the given replacement text. Write a function replace_str to implement this    functionality. Your function will consume 3 non-empty strings, base, target and    rep. The first string, base, represents a base string that you want to update.    The    second string target represents the target string that you want to replace and    the    third    string rep represents a string that will replace the target in the updated string. The function produces a new string in which the target string    is replaced by the rep string in the base string, but produces the same base string if    either of the following conditions hold     true.
• If the target string is not found in the base string or,   
• If the target and rep are the same strings.
For    example,

replace_str("This is a book","a","the")=>'This is the book'
replace_str("This is my book","a","the")=>'This is my book'
replace_str("I like this book","I","I")=> 'I like this book'
replace_str ("my brother reads books and sometimes he reads magazines", "reads", "likes") =>'my brother likes books and sometimes he likes magazines'
replace_str("Apple is a fruit", "f" , "t" )=>'Apple is a truit'
replace_str("aaaaa","aa","x")=>'xxa'

Note:
• You are    not allowed to use the string methods replace and find for this question.

Name: Anonymous 2013-03-19 15:57


def replace_str(str):
    return append(str[0:1], replace_str(str[1:])


I don't know python and didn't do the replacement part, but that's the general pattern.

Name: Anonymous 2013-03-19 16:02

turn into char array
observe length of word to find
scan that number of characters
print the first letter if not match
if match remove all characters and insert with target word, remember to correct for unwanted white space
send 2nd-last back to the function
go to step 1, 2 , 3 or 4 depending on implementation

Don't change these.
Name: Email:
Entire Thread Thread List