I'm currently trying to code an equivalent for the built-in min-max function in python, and my code return a pretty weird exception which I don't understand at all:
TypeError: 'generator' object is not subscriptable, min, 7, , 9
when i try it with:
min(abs(i) for i in range(-10, 10))
Here is my code:
def min(*args, **kwargs):
key = kwargs.get("key", None)
argv=0
for i in args:
argv+=1
if argv == 1 and (type(args) is list or type(args) is tuple or type(args) is str):
min=args[0][0]
for i in args[0]:
if key != None:
if key(i) < key(min):
min = i
else:
if i < min:
min = i
return min
else:
min=args[0]
for i in args:
if key != None:
if key(i) < key(min):
min = i
else:
if i < min:
min = i
return min
According to the documentation, i should be able to iterate over a generator...
generator[0]("not subscriptable"). It complains aboutmin=args[0][0].Nonefirst and then check if it isNonewhen iterating over the generator (so you can set it to the first element) and afterwards (if there are no elements).argswill always be a tuple, so yourifblock will always be entered, and yourelseblock will never be entered. Furthermore, since bothifandelsehave an unconditionalreturninside them, your firstforloop will never get past the first iteration. You may as well remove it, and theargvcheck as well.