This question already has answers here:
Can a variable number of arguments be passed to a function?
(6 answers)
Closed 8 years ago.
How could I integrate multiple values as parameters without using a tuple or a list? Does python have overloaded parameters?
I'm thinking something like this:
add(1,2) # 3
add(1,2,3,4) # 10
def add(numbers):
return sum(list(numbers))
Thanks in advance.
You are probably looking for Arbitrary Argument List.
However, you are probably doing more work than you need to and also I am not entirely sure what you are exactly trying to do (or what you mean by efficient algorithm), but the sum builtin function already does what you needed, you just need to read the documentation on what it actually expects in its arguments.
>>> sum([1,2,3])
6
>>> sum([1,2,3,4,5,6])
21
Or heck, if you want to go without a list or tuple (actually, arguments are a list already so you are just using unnecessary syntactic sugar) you can just do this then.
def add(*numbers):
return sum(numbers)
Just think a little and you can put together the above function.
Related
This question already has answers here:
Pythonic way to have a choice of 2-3 options as an argument to a function
(9 answers)
Closed 3 months ago.
I need to force function inputs to take specific values. Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?
def product(product_type = ['apple','banana']):
print(product_type)
But the function requires product_type as single string (product('apple') or product('banana')), and gives error when typed different values.
Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?
Not really.
You can use typing with an Enum or a Literal but that assumes a type checker is actually being run on the codebase in all cases.
Python is otherwise dynamically, it will not normally validate parameters, if you need that you must do it internally. Though you do not need an if: else: block inside the function, you can just use an assertion:
def product(product_type: Literal['apple', 'banana']):
assert product_type in ['apple','banana']
print(product_type)
This way the input will be
actually checked at runtime
documented for IDEs and friends
optionally checked at compile-time
This question already has answers here:
What does it mean when the parentheses are omitted from a function or method call?
(6 answers)
Closed 2 years ago.
In Python, there are functions that need parentheses and some that don't, e.g. consider the following example:
a = numpy.arange(10)
print(a.size)
print(a.var())
Why does the size function not need to be written with parentheses, as opposed to the variance function? Is there a general scheme behind this or do you just have to memorize it for every function?
Also, there are functions that are written before the argument (as opposed to the examples above), like
a = numpy.arange(10)
print(np.round_(a))
Why not write a.round_ or a.round_()?
It sounds like you're confused with 3 distinct concepts, which are not specific to python, rather to (object oriented) programming.
attributes are values, characteristics of an object. Like array.shape
methods are functions an object can run, actions it can perform. array.mean()
static methods are functions which are inherent to a class of objects, but don't need an object to be executed like np.round_()
It sounds like you should look into OOP: here is a python primer on methods.
Also, a more pythonic and specific kind of attributes are propertys. They are methods (of an object) which are not called with (). Sounds a bit weird but can be useful; look into it.
arrange returns an ndarray. size isn't a function, it's just an attribute of the ndarray class. Since it's just a value, not a callable, it doesn't take parenthesis.
This question already has answers here:
Why are "pure" functions called "pure"? [closed]
(5 answers)
Closed 6 years ago.
Can pure functions take an argument? For example,
def convert(n):
Thank you in advance
Of course they can have arguments. The only difference is whether they have side effects beyond the input and output parameters. Without input arguments to use as "inspiration", it's difficult for a pure function to do something useful.
Yes they can have arguments. Find some details below:
Pure functions: Functions have some input (their arguments) and return some output
(the result of applying them). The built-in function:
>>> abs(-2)
gives the result:
2
No effects beyond returning a value.
Non-pure functions: In addition to returning a value, applying a non-pure function can generate side effects, which make some change to the state of the interpreter or
computer. A common side effect is to generate additional output beyond the return
value, using the print function.
print(1, 2, 3)
1 2 3
This question already has answers here:
Difference between len() and .__len__()?
(5 answers)
Closed 7 years ago.
I have two examples:
a = [1,2,3]
b = 4
print (a.__len__())
print (len(a))
print(b.__add__(4))
print (b + 4)
I guess my question is, is there a difference when using __len__ magic method versus the built in len() method? The only time I see people use __len__ is when trying to trying to find the length of an object of a user-created class.
Same with other dunder methods, such as __str__, or __add__ I never seem them used outside of a class or OOP in general.
There are only small differencies. Function is just a function, that call len. Something like
def len(x):
return x.__len__()
Of course, you can override builtin len, but that is dump (maybe except debugging). Only different thing is len(x) is easier to read, and x.__len__ allows you create your own implentation of operator. x.__len__ also can be bit faster, but it is a good reason to use it.
When operator have 2 arguments its implementation do more. a+b at first it tries, whether is callable a.__add__ and if it is not, than tries to call b.__radd__.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python: How do I pass a variable by reference?
I'm trying to write a function that modifies one of the passed parameters. Here's the current code:
def improve_guess(guess, num):
return (guess + (num/guess)) / 2
x = 4.0
guess = 2.0
guess = improve_guess(guess, x)
However, I want to write the code in such a way that I don't have to do the final assignment. That way, I can just call:
improve_guess(guess,x)
and get the new value in guess.
(I intentionally didn't mention passing-by-reference because during my net-searching, I found a lot of academic discussion about the topic but no clean way of doing this. I don't really want to use globals or encapsulation in a list for this.)
You can't do this directly since integer and floating-point types are immutable in Python.
You could wrap guess into a mutable structure of some sort (e.g. a list or a custom class), but that would get very ugly very quickly.
P.S. I personally really like the explicit nature of guess = improve_guess(guess, x) since it leaves no doubt as to what exactly is being modified. I don't even need to know anything about improve_guess() to figure that out.
But those are the only two ways to do it: either use a global, or use a mutable type like a list. You can't modify a non-mutable variable in Python: doing so just rebinds the local name to a new value.
If you really don't like wrapping in a list, you could create your own class and pass around an instance that will be mutable, but I can't see any benefit in doing that.