I looked up the answer which was 100% different from mine, but I want to know if mine can work, because I feel like I was close


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096

What I have so far is these 2 sections of code

lst = []
def reverse(x):
    for c in str(x):
        lst.append(str(c))
    print ''.join(lst)
    return lst
print reverse("reverse")

AND:

def custorange(i):
    custrange = [range(len(i), 0, -1)]
    for x in custrange:
        return x
    return custrange
print custorange("hello")

My idea was to reference the indices and connect them to their letters, thereby creating a reverse list of the strings, then merge them into back into one word. I feel like all I'm missing is the connecting the indexes to the strings in the first list, but I cannot figure out for the life of me how to do that.


#2

My question is, what do we expect x to represent? A string? A list? Assuming it is a string, means we do not need to convert to string. Assuming it is a list, converting to a string will encase the list in quotes, rendering it a very poor iterable.

So we stipulate that x can be either a string or a list. They can both be iterated. No conversion required. For the time, let's start with string.

for c in x:

The string is the iterable, and its character elements inherit, so they too are string. c is therefore a string. No conversion needed.

lst.append(c)

Only problem here is the code is simply rebuilding the same string. What's needed here is a way to insert an item at the start...

lst.insert(c)

Now we get to this...

range() returns an iterator. Python 2 will cast it directly to a list which is cached in that form. We do not need to enclose it in a list object.

custrange = range( ... )

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.