1
votes

I have to return the middle part of string. When the string has odd number of elements, the middle part is one letter and when the string has even number of elements, the middle part is two letters. If string is empty, return empty string

"help" -> "el"
"hi" -> "hi"
"hey" -> "e"

I wrote a code:

if len(s) % 2 != 0:
    return s[len(s)//2]
elif len(s) % 2 == 0:
    return s[len(s)//2 - 1] + s[len(s)//2]

With this I got a neede output but also an error that index is out of range. Where is mistake?

2
For zero-length strings, you're accessing s[-1]. - randomir
@AITs the hint is when the string is empty return an empty string otherwise your code is correct. I vote up because you tried before asking :) - Mohamed Ali JAMAOUI
@MedAli Ah, ok, thanks. I thought that it returns an empty string by default when the length is zero - AlTs

2 Answers

2
votes

The issue is your code, as written, always accesses a location in the string. You can add a check for this exception.

def middle(s):
    if len(s) == 0:
        return ""
    elif len(s) % 2 != 0:
        return s[len(s)//2]
    elif len(s) % 2 == 0:
        return s[len(s)//2 - 1] + s[len(s)//2]

print(middle(""))

Alternatively, you could make your code more condensed with:

def middle(s):
    offset = len(s)%2==0
    return s[len(s)//2-offset:round(len(s)/2)+offset]

print(middle("helloworld"))
1
votes

You are close; however, you need list slicing for the even case:

s = ["help", "hi", "hey"]
new_s = [i[len(i)//2] if len(i)%2 != 0 else i[(len(i)//2)-1:(len(i)//2)+1] for i in s]

Output:

['el', 'hi', 'e']

To view the pairings:

new_s = dict(zip(s, [i[len(i)//2] if len(i)%2 != 0 else i[(len(i)//2)-1:(len(i)//2)+1] for i in s]))

Output:

{'hi': 'hi', 'help': 'el', 'hey': 'e'}