def f(x):
I'm trying to make a function, f(x), that would return the middle letters eg.
f(["a", "b", "c", "d" "e"])
outputs:
["c"]
and
f(["a", "b", "c", "d" "e", "f"])
because there is an even number of letters, outputs:
["c", "d"]
def f(x):
I'm trying to make a function, f(x), that would return the middle letters eg.
f(["a", "b", "c", "d" "e"])
outputs:
["c"]
and
f(["a", "b", "c", "d" "e", "f"])
because there is an even number of letters, outputs:
["c", "d"]
A brute force way
def f(x):
l = len(x)
if l%2 == 0:
return x[l//2-1:l//2+1]
return [x[l//2]]
Demo
>>> f(["a", "b", "c", "d", "e"])
['c']
>>> f(["a", "b", "c", "d", "e", "f"])
['d', 'e']
>>> f(["an", "pat", "but", "bet", "ten", "king"])
['but', 'bet']
Small-Note: Refer to this question to understand the difference between /
and //
operators in python
def f(x):
l = len(x)
if l % 2 == 0:
return [x[l/2 - 1], x[l/2]]
else:
return [x[l/2]]
print f(["a", "b", "c", "d" "e"])
print f(["a", "b", "c", "d" "e", "f"])
So you should have something like :
def f(x):
if len(x) % 2 == 0:
return [x[len(x)/2], x[len(x)/2+1]]
else:
return x[ceil(len(x)/2)]
>>> def f(x):
... return x[round(len(l)/2-0.5):round(len(l)/2+0.5)]
...
>>> f(["a", "b", "c", "d", "e", "f"])
['c', 'd']
>>> f(["a", "b", "c", "d", "e"])
['c']