2

I'm trying to split the following code into a separate if statement.

def second_half(s):
    return s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]

I've already tried doing the following:

def second_half(s):
    if len(s) % 2 == 0:
        return s[len(s)//2]
    else:
        return s[((len(s)//2)+1):]

and receive the following output in my doctest (although majority of my other tests passed):

Failed example:
    second_half("abcdef")
Expected:
    'def'
Got:
    'd'

Would appreciate any help. Cheers.

puppyonkik
  • 213
  • 1
  • 7

3 Answers3

1

In your original list-comprehension code, the start index of the slice is calculated and the last index is taken as (len(s)

But when you translate this into two if-statements, You forgot the slice operator : in the the first if condition, which caused only one element to be returned, but what you want is the whole slice in both if conditions, which will happen when you do return s[len(s)//2:] instead of return s[len(s)//2] in the first if condition

So the updated code will be

def second_half(s):

    if len(s) % 2 == 0:
        #Added the missing slice
        return s[len(s)//2:]
    else:
        return s[((len(s)//2)+1):]

And the code will work as expected

print(second_half('abcde'))
#de
print(second_half('abcdef'))
#def
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

whats happening here:

len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1)

Ternary operator expression:

syntax:

value_when_true if condition else value_when_false

this part of code will return integer (some_integer)

and then you will have:

 s[some_integer:] # a[start:] items start through the rest of the array

Slicing strings:

Syntax:

substring = original_string[first_pos:last_pos]

def second_half(s):
    if len(s) % 2 == 0:
        n=len(s) // 2
    else:
        n=(len(s)//2)+1

    return s[n:]

print (second_half("abcdef"))


def second_half(s):
    if len(s) % 2 == 0:
        return s[len(s)//2:]
    else:
        return s[len(s)//2)+1]

output:

def
ncica
  • 7,015
  • 1
  • 15
  • 37
0

As commented, your first return is missing the colon. This is called list slicing, see here for more info.

def second_half_original(s):
    return s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]

def second_half_split(s):
    if len(s) % 2 == 0:
        return s[len(s) // 2:]
    else:
        return s[len(s)//2 + 1:]

Result:

>>> def second_half_original(s):
...     return s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]
...
>>> def second_half_split(s):
...     if len(s) % 2 == 0:
...         return s[len(s) // 2:]
...     else:
...         return s[len(s)//2 + 1:]
...
>>> s = 'abcdef'
>>> print('Old\t{old}\nNew\t{new}'.format(
...        old=second_half_original(s),
...        new=second_half_split(s)
...     )
... )
Old     def
New     def