0
Py args practice : can anyone helps correcting my code plz
def my_min(x, *args): if x < args: return x else: for arg in args: if arg < x: yield arg print(my_min(8, 13, 4, 42, 120, 7))
3 Respostas
+ 2
what's the purpose if your code?
if you expect to return the min value from the arguments passed, you can simply do:
def my_min(*args):
return min(args)
but why not using directly min function ;P
if you want to make a recursive function (only for *args practice, as you use min built-in inside):
def my_min(x, *args):
if len(args) == 0 or x < min(args):
return x
else:
return my_min(*args)
+ 2
You're probably having issues because it's a generator function and your if statement isn't correct.
Your if statement is equivalent to the following with the current given arguments;
if 8 < [13, 4, 42, 120, 7]:
You can make the code work like;
def my_min(x, *args):
if x < min(args):
yield x
else:
for arg in args:
if arg < x:
yield arg
[print(x) for x in my_min(8, 13, 4, 42, 120, 7)]
Or
def my_min(x, *args):
if x < min(args):
return [x]
def nums_less_than_x():
for arg in args:
if arg < x:
yield arg
return nums_less_than_x()
[print(x) for x in my_min(2, 13, 4, 42, 120, 7)]
0
(from “Ipang”)
def my_min( x, *args ):
return min( x, min( args ) )