sKyScRaPeR challenge

“Create a function that takes in a string and returns a string with every even letter uppercase and every odd letter lowercase.”

This one threw me for a loop. I worked on it for a long time before I finally figured out what to do.
I tried this:
def myfunc(string):
for letter in string:
if [::2]
…and I couldn’t get anywhere with it.

I also tried this:
def myfunc(string):
x = list(string)
for x in x[::2]:
x.upper()
return(x)

..and couldn’t get anywhere with that either. I finally caved in and asked for help after trying to solve this by myself for like a week. Turns out I was on the right track with one of my ideas:

def myfunc(str):
result = “”
for i in range(len(str)):
if i % 2 == 1:
result += str[i].upper()
elif i %2 == 0:
result += str[i].lower()
return result

So basically what this means is this…I set up a function that takes in strings (str). In the function, the first thing it does is creates an empty string called results.

for i in range(len(str)) means that it will be taking the range of whatever the length of the string is (if the string is 5 letters long, it will return a result of 0, 1, 2, 3, 4.)

Then, it takes those numbers and sees whether they are even or not (if i % 2 == 0). What I had to do that was sort of tricky was think about an extra step that defies common sense. If i % 2 == 0, should be even…BUT if i do the str[i] with even numbers, it will actually complete the method on the odd letters.

Think about this:

Say the word is “Bobby”. The function would find the range of the length (0:5), so  B=0, o=1, b=2, b=3, y=4. So if I completed the .upper() method on the even numbers, it would actually capitalize the b (index 0), b (index 2), and y (index 4).

BUUUUUT, when we look at these letters without the Python indexing system, it is the first letter, third letter, fifth letter

So I had to reverse it (kindof).

So once I figured that out, I just switched it (look at the code), and the next part of the function was adding str[i].upper() to the result string using +=, then doing the same thing with the str[i].lower().

WOW!

Long story short, with the help of a fellow programmer, I finally figured it out. Good news, it only gets harder from here!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s