Your first problem is a simple typo. Your defined your "smaller than" function as smaller_then_ten
but called it as smaller_then_n
. I'm going to go out on a limb here and say that you meant to call it smaller_than_len
. Next is that your function smaller_then_ten
doesn't take your variable n
into account at all, it only uses the length of the input list. What you really want is a function that accepts an upper bound and returns a function which checks the first element of the list against it. Something like this.
def smaller_than_len(n):
def f(e):
return e[0] < n
return f
def foo(los, n=None):
n = n or len(los)
h = it.takewhile(smaller_than_len(n), enumerate(los))
...
Your final problem is that you removed the key argument from the sorted
and groupby
functions. Since you said that you didn't want to use lambdas for your adjustment, you can replace them with a new function named "key_func".
def smaller_than_len(n):
def f(e):
return e[0] < n
return f
def key_func(e):
return e[1]
def foo(los, n=None):
n = n or len(los)
h = it.takewhile(smaller_than_len(n), enumerate(los))
s = sorted(h, key=key_func)
g = it.groupby(s, key=key_func)
return dict(it.starmap(lambda k, vs: (k, sum(map(lambda i: 1, vs))), g))
Now your function should work correctly.