Why is python telling me "TypeError: pow expected 2 arguments, got 3" despite it working in IDLE (sometimes it tells me that in IDLE as well)? im simply doing pow(a,b,c). my program is very short and i do not change the definition of pow at any time since i need to use it for some exponentiation.
NOTE: This is the pow from __builtin__, not Math
Built-in pow takes two or three arguments. If you do from math import * then it is replaced by math's pow, which takes only two arguments. My recommendation is to do import math, or explicitly list functions you use in import list. Similar issue happens with open vs. os.open.
If you are using math functions a lot and the three parameter version of pow infrequently a way around this in python 2.7 is to import __builtin__ and call __builtin__.pow for the 3 paramete
http://docs.python.org/release/2.6.5/library/functions.html
pow(x, y[, z]) Return x to the power
y; if z is present, return x to the
power y, modulo z (computed more
efficiently than pow(x, y) % z). The
two-argument form pow(x, y) is
equivalent to using the power
operator: x**y.
The arguments must have numeric types.
With mixed operand types, the coercion
rules for binary arithmetic operators
apply. For int and long int operands,
the result has the same type as the
operands (after coercion) unless the
second argument is negative; in that
case, all arguments are converted to
float and a float result is delivered.
For example, 102 returns 100, but
10-2 returns 0.01. (This last
feature was added in Python 2.2. In
Python 2.1 and before, if both
arguments were of integer types and
the second argument was negative, an
exception was raised.) If the second
argument is negative, the third
argument must be omitted. If z is
present, x and y must be of integer
types, and y must be non-negative.
(This restriction was added in Python
2.2. In Python 2.1 and before, floating 3-argument pow() returned
platform-dependent results depending
on floating-point rounding accidents.)
Perhaps you're violating the bold portion?
Related
Is there a way in Python to let the len(x) function (or any similar function) return 1 if x is a simple float?
In my case, I have x as a input parameter to a function, and I want to make it robust to (NumPy) array type inputs of x as well as simple scalar float input of x. In the function, the len(x) function is used, but it throws an error object of type 'float' has no len() if x is a float, whereas I want it to return 1. Of course I can write an if statement, but I feel like there should be a shorter solution.
def myfunc(x):
y=np.zeros((5,len(x)))
y[1,:]=x
....
return y
No, there is no built-in function like this.
One of the core aspects of how Python is designed is that it is strongly typed, meaning that values are not implicitly coerced from one type to another. For example, you cannot do 'foo' + 3 to make a string 'foo3'; you have to write 'foo' + str(3) to explicitly convert the int to str in order to use string concatenation. So having built-in operators or functions which could treat a scalar value as if it's a sequence of length 1 would violate the principle of strong typing.
This is in contrast with weakly typed languages like Javascript and PHP, where type coercion is done with the idea that the programmer doesn't have to think so much about data types and how they are converted; in practice, if you write in these languages then you still do have to think about types and conversions, you just have to also know which conversions are or aren't done implicitly.
So, in Python if you want a function to work with multiple different data types, then you either have to do a conversion explicitly (e.g. if isinstance(x, float): x = np.array([x])) or you have to only use operations which are supported by every data type your function accepts (i.e. duck typing).
I was recently working with Python and wanted to use another way of finding square roots. For example I wanted to find square root of n with Newton-Raphson approximation. I need to overload the overload the ** (only when you raise a number to 0.5),o perator as well as math.sqrt(), because I have several older projects that could be sped up by doing so and replacing all math.sqrt() and **(0.5) with another function isn't ideal.
Could this be done in Python?
Is it possible to overload either ** or math.sqrt?
Any helpful links are also much appreciated.
def Square_root(n):
r = n/2
while(abs(r-(n/r)) > t):
r = 0.5 * (r + (n/r))
return r
print(2**(0.5)) ## changes to print(Square_root(2))
print(math.sqrt(2)) ## that also becomes print(Square_root(2))
In short: you can't change the behavior of __pow__ for built-in types.
Long answer: you can subclass the float, but it will require additional coding and refactoring of the input values of the program, to the new float class with overwritten operators and functions.
And you can overwrite the math.sqrt, but this is not recommended:
import math
math.sqrt = lambda x, y: print(x, y)
math.sqrt(3, 2)
# 3 2
This will require the custom function to have the same signature.
If you really want to overload languages int and float objects - you can use variants of magic functions. In order to be consistent, you'll have to write a lot of code.
A lot of work. Python is for lazy people - if you like to write a lot, stick to Java or C++ :)
I am new to SAGE and am having a problem with something very simple. I have the following code:
delay = float(3.5)
D = delay%1.0
D
But this returns the value -0.5 instead of the expected 0.5. What am I doing wrong?
If I change delay to be delay = float(2.5), I get the right answer, so I don't know why it isn't consistent (I am sure I am using the modulo wrong somehow).
I think that this question will answer things very well indeed for you.
However, I don't know why you are using float in Sage. Then you could just use Python straight up. Anyway, the % operator is tricky to use outside of integers. For example, here is the docstring for its use on Sage rational numbers.
Return the remainder of division of self by other, where other is
coerced to an integer
INPUT:
* ``other`` - object that coerces to an integer.
OUTPUT: integer
EXAMPLES:
sage: (-4/17).__mod__(3/1)
1
I assume this is considered to be a feature, not a bug.
I am new to python! Done my studying, gone through several books and now attempting pyschools challenges. Done Variables and data types successfully but Question 7 of Topic 2 (Functions) is giving me hell.
I am using Eclipse with Python (ver 3.2). in my eclipse, I get the answers 100, 51 and 525. Those are the same answers pyschools expects but it shows that my function returns 100, 0 and 500.
Here is the question (Hope am allowed to post it here!):
Write a function percent(value, total) that takes in two numbers as arguments, and returns the percentage value as an integer.
And below is my function
def percent (value, total):
a = value
b = total
return(int((a / b) * 100))
percent(70, 70)
percent(46, 90)
percent(63, 12)
Can anyone tell me what pyschools really want me to do or where am going wrong?
Thanks!
You're using Python 3.x and they're using Python 2.x. In Python 2.x, the / operation is always an integer division when the arguments are integers. 1/2 is 0. So, use float() to change one of your arguments to a floating-point number, such as int((float(a) / b) * 100). Then a/b will have a fractional part.
Or, assuming they are using a recent version of Python 2.x, you can just add this to the beginning of your script and it should work on the site:
from __future__ import division
As an aside, why are you assigning your input parameters to variables? They're already variables. If you want them named a and b, just receive them that way:
def percent(a, b):
return int((float(a) / b) * 100)
because it is using python 2.x you need to atleast convert one value to float
def percent(number, total):
return int((float(number)/total) * 100)
this will work fine
Python performs mathematical operations on integers with strictly integer math, truncating fractional parts.
To avoid that, multiply one of the inputs by 1.0 before dividing.
You can use the truncating divide, like this:
def percent(value, total):
return value * 100 // total
Advantages:
(0) Works with all Pythons from 2.2 onwards.
(1) The reader knows what that one line does without having to guess what version of Python is being run and without having to inspect the start of the module for from __future__ magic.
(2) Avoids any potential floating-point problems.
(3) Avoids using float and int i.e. saves two (relatively expensive) function calls.
Note carefully: // works on float objects as well as int objects. The question says that the args are "numbers" (can include float objects) and the result should be an "integer" (not necessarily an int object). That gives you considerable licence.
>>> percent(63.001, 11.9999)
525.0 # That's an integer
If they insist on the return value being an int object, then of course you'll need an int().
What does this mean in Python:
sock.recvfrom(2**16)
I know what sock is, and I get the gist of the recvfrom function, but what the heck is 2**16? Specifically, the two asterisk/double asterisk operator?
(english keywords, because it's hard to search for this: times-times star-star asterisk-asterisk double-times double-star double-asterisk operator)
It is the power operator.
From the Python 3 docs:
The power operator has the same semantics as the built-in pow() function, when called with two arguments: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common type, and the result is of that type.
It is equivalent to 216 = 65536, or pow(2, 16)
http://docs.python.org/library/operator.html#mapping-operators-to-functions
a ** b = pow(a,b)
2 raised to the 16th power
I believe that's the power operator, such that 2**5 = 32.
It is the awesome power operator which like complex numbers is another thing you wonder why more programming languages don't have.