+ 3
*args in python
The given code defined a function called my_min(), which takes two arguments and returns the smaller one. You need to improve the function, so that it can take any number of variables, so that the function call works. def my_min(x, y): if x < y: return x else: return y print(my_min(8, 13, 4, 42, 120, 7))
18 odpowiedzi
+ 6
faster approach
def myfunc(*args):
return min(*args)
print(myfunc(1,2,3,4))
print(myfunc([1,2,3,4]))
+ 5
def my_min(*args):
minval = args[0]
for num in args:
if num<minval:
minval=num
return minval
print(my_min(8, 13, 4, 42, 120, 7))
+ 3
how about this it worked;
def my- min(x, y, *args):
return min (args)
if x < y:
return x
else:
return y
print(my-min( 8, 13, 4, 42, 120, 7))
+ 2
Look I have following solution it may help you.
def my_min(x, *args):
if len(args) == 1:
if x < args[0]:
return x
else:
return args[0]
y, *args = args
if x < y:
return my_min(x, *args)
else:
return my_min(y, *args)
print(my_min(8, 13, 4, 42, 120, 7))
It's a recursive way of finding minimum value
DHANANJAY
+ 1
You should add the language name in tags while asking a question.
+ 1
def myFunc(*args):
...
will populate args with a list containing all non keywords args.
you should just find min value of this list and return it ;)
+ 1
AssasinStudent
if OP have to implement a my_min() function, he's probably not allowed to use min() built-in...
and if he could, shorter would be:
my_min = min
anyway, if you give complete solution to OP, he will learn nothing appart copy-pasting without understanding ^^
0
ya thanks
0
Agree. Giving hints to an OP rather than a complete solution is recommended in this section.
0
Slution:
def my_min(*args):
return min(args)
print(my_min(8, 13, 4, 42, 120, 7))
0
Why it doesn't wok ?
def my_min(x, *args):
for y in args:
if x < y:
return x
else:
return y
print(my_min(8, 13, 4, 42, 120, 7))
0
def my_min(*args):
return min(args)
print(my_min(8, 13, 4, 42, 120, 7))
0
def my_min(x,*args):
for i in args:
if x < i:
res = x
else:
res = i
return res
print(my_min(8, 13, 4, 42, 120, 7))
Who can explain why it's not work?
0
Truc Tran
Above code will not work to find minimum value
It will always compare with first value (means x) during the loop
Here, it is 8, so it will always return minimum value between first value and last value in case of your code it will return 7
Since, between 8 and 7 minimum value is 7
Thanks for your concern
DHANANJAY PATEL
0
Oh I understand now. Thank you so much
0
@DHANANJAY PATEL
I understand your comment why it wouldn't work, because it will only compare with the first digit... However, that was the question of the assignment. If not, the assignment was poorly set up!! (... which takes two arguments and returns the smaller one....)
Punctuation is key!!
- 1
which language?