-1
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"]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Jake Johnson
  • 9
  • 1
  • 5

4 Answers4

1

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

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 3
    Well `//` will work the same for 2.x and 3.x... using `/` will break in 3.x – Jon Clements Apr 02 '15 at 09:43
  • would this also work for f(["an", "pat", "but", "bet", "ten", "king"]), outputting ["but", "bet"]? – Jake Johnson Apr 02 '15 at 11:23
  • it says "Traceback (most recent call last): File "", line 1, in TypeError: f() takes 1 positional argument but 6 were given" – Jake Johnson Apr 02 '15 at 11:27
  • Aha! You missed the square brackets `[...]` inside the parenthesis `(...)`. Try passing it inside square brackets as you have shown – Bhargav Rao Apr 02 '15 at 11:28
  • Oh woops. Okay I tried again. Says: "Traceback (most recent call last): File "", line 1, in File "program.py", line 4, in f return x[l/2-1:l/2+1] TypeError: slice indices must be integers or None or have an __index__ method" – Jake Johnson Apr 02 '15 at 11:32
  • It works fine for an odd number of words/letters but same error for an even number of words – Jake Johnson Apr 02 '15 at 11:38
1
 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"])
hyades
  • 3,110
  • 1
  • 17
  • 36
1

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)]
vekah
  • 980
  • 3
  • 13
  • 31
1
>>> 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']
matsjoyce
  • 5,744
  • 6
  • 31
  • 38