Zèro
Zèro

Reputation: 3

Why doesn't my specific implementation work for returning middle letter from a function?

The aim is to return the middle letter of a string, or " " if the string's even. I'm failing to see why my code doesn't work. Any sort of clarification would be great, thanks!

def mid(ml):

    x=len(ml)
    y=x+1
    z=y/2
    if isinstance(z,int)==True:
        return (ml[z-1])
    else:
        return (" ")
        
print (mid("abc"))

Upvotes: 0

Views: 54

Answers (3)

Carcigenicate
Carcigenicate

Reputation: 45806

/ doesn't return an int; even if the number it returns can be represented as one:

>>> 4 / 2
2.0  # A float

It would be better to explicitly check if the number is even or not:

# Read as: "If z is odd", or, "If division of z by 2 has a remainder of 1"
if z % 2 == 1:  
    return ml[z-1]
else:
    return " "

Upvotes: 4

Tom Gebel
Tom Gebel

Reputation: 805

This behavior occurs, because the / operator returns a float. Although the smarter way to solve this would be the use of the modulo operator, if you want to stick to your code, could use the is_integer() method of float like this:

def mid(ml):

    x=len(ml)
    y=x+1
    z=y/2
    if z.is_integer():
        return (ml[int(z)-1])
    else:
        return (" ")
        
print (mid("abc"))

Better way to do it:

def mid(ml):
    return ml[len(ml)//2] if len(ml) % 2 else ""

Upvotes: 1

shiv
shiv

Reputation: 1952

Following the answer from @Carcigenicate above you can try following code:

def mid(ml):
    x=len(ml)
    y=x+1
    z=y/2
    return (ml[int(z-1)])
        
print (mid("abc"))

Upvotes: -3

Related Questions