Solutions to strings HW07:


#-----------------------
def extractSlice(string, start, stop, step):
    result = ""
    for i in range(start,stop,step):
        result += string[i]
    return result


#-----------------------
def findLetter(A, B):
    # ... reuse findLetter from hw6

def lastFirst(fullname):
    spaceI = findLetter(fullname, " ")
    #          "first last"
    #indices:   0123456789
    #spaceI:         ^
    first = extractSlice(fullname, 0, spaceI, 1) # from 0 to before the space
    last = extractSlice(fullname, spaceI+1, len(fullname), 1) # after space to the end
    return last + ", " + first

def lastFirst2(fullname): # Now using the built-in slices
    spaceI = findLetter(fullname, " ")
    return fullname[spaceI+1:] + ", " + fullname[:spaceI]


#-----------------------
def repeatFront(text, n):
    result = ""
    for curr_n in range(n, 0, -1): #loop n, n-1, ... 1
        result += extractSlice(text, 0, curr_n, 1) #get first curr_n chars
    return result

#-----------------------
# We can either loop over the number n of characters to keep each time, 
# (but then we have to figure out where the right slice sizes are for that)

# Or we can figure out in advance which i's to loop over
# (and then the slice is just from i to the end)

def repeatBack(text, n): # Each loop, the curr_n is how many last characters to keep
    result = ""
    for curr_n in range(n, 0, -1): #loop n, n-1, ... 1
        result += extractSlice(text, len(text)-curr_n, len(text), 1) #get last curr_n chars
    return result

def repeatBack2(text, n):
    result = ""
    for i in range(len(text)-n, len(text)): #loop len()-n, len()-n+1, ... len()-1
        result += extractSlice(text, i, len(text), 1) #get from i to end
    return result