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.
Related
I would like to define my own operator. Does python support such a thing?
While technically you cannot define new operators in Python, this clever hack works around this limitation. It allows you to define infix operators like this:
# simple multiplication
x=Infix(lambda x,y: x*y)
print 2 |x| 4
# => 8
# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
print [1,2,3] |isa| []
print [1,2,3] <<isa>> []
# => True
No, Python comes with a predefined, yet overridable, set of operators.
No, you can't create new operators. However, if you are just evaluating expressions, you could process the string yourself and calculate the results of the new operators.
Sage provides this functionality, essentially using the "clever hack" described by #Ayman Hourieh, but incorporated into a module as a decorator to give a cleaner appearance and additional functionality – you can choose the operator to overload and therefore the order of evaluation.
from sage.misc.decorators import infix_operator
#infix_operator('multiply')
def dot(a,b):
return a.dot_product(b)
u=vector([1,2,3])
v=vector([5,4,3])
print(u *dot* v)
# => 22
#infix_operator('or')
def plus(x,y):
return x*y
print(2 |plus| 4)
# => 6
See the Sage documentation and this enhancement tracking ticket for more information.
Python 3.5 introduces the symbol # for an extra operator.
PEP465 introduced this new operator for matrix multiplication, to simplify the notation of many numerical code. The operator will not be implemented for all types, but just for arrays-like-objects.
You can support the operator for your classes/objects by implementing __matmul__().
The PEP leaves space for a different usage of the operator for non-arrays-like objects.
Of course you can implement with # any sort of operation different from matrix multiplication also for arrays-like objects, but the user experience will be affected, because everybody will expect your data type to behave in a different way.
If you intend to apply the operation on a particular class of objects, you could just override the operator that matches your function the closest... for instance, overriding __eq__() will override the == operator to return whatever you want. This works for almost all the operators.
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 have suddenly came across this, I am not able to understand why this is happening!
On python prompt,
using the ** operator on 3 onwards like below giving wrong result.
i.e.,
>>> 2**2**2
16
>>> 3**3**3
7625597484987L
>>> 4**4**4
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096L
Then i thought i must have to use parentheses, so i used it and it is giving correct result.
>>>(3**3)**3
19683
BUT the // operator is supporting and giving correct results
in this kind of operations, that is
>>> 4//4//4
0
>>> 40//4//6
1
please help me to understand.
** is right-associative. Mathematically, this makes sense: 333 is equal to 327, not 273.
The documentation states that it is right-associative:
In an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left.
As the docs say:
Operators in the same box group left to right (except for comparisons… and exponentiation, which groups from right to left).
In other words, ** is right-associative, while // (like all other operators except comparisons) is left-associative.
Elsewhere, there's a whole section on The power operator that, after giving a rule (which isn't relevant here) about how power and unary operators interacts, clarifies that:
[I]n an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left…
This is actually the way most programming languages do it.
Exponentiation isn't written with symmetrical operator syntax in mathematics, so there's really no reason it should have the same default associativity. And right-associative exponentiation is much less useful, because (2**3)**4 is exactly the same thing as 2**(3*4), whereas there's nothing obvious that's the same thing as 2**(3**4).
Looks like the ** operator is right-associative, meaning 3**3**3 evaluates as 3**27 and 4**4**4 as 4**256.
When you do stuff like 4**4**4, you should use parentheses to make your intentions explicit. The parser will resolve the ambiguity, as #cHao indicated, but it is confusing to others. You should use (4**4)**4 or 4**(4**4). Explicit here is better than implicit, since taking powers of powers is not exactly a workaday operation we see all of the time.
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().
I was just bitten by the following scenario:
>>> -1 ** 2
-1
Now, digging through the Python docs, it's clear that this is intended behavior, but why? I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.
Is there a reason it was done this way? Do other languages with power operators behave similarly?
That behaviour is the same as in math formulas, so I am not sure what the problem is, or why it is counter-intuitive. Can you explain where have you seen something different? "**" always bind more than "-": -x^2 is not the same as (-x)^2
Just use (-1) ** 2, exactly as you'd do in math.
Short answer: it's the standard way precedence works in math.
Let's say I want to evaluate the polynomial 3x3 - x2 + 5.
def polynomial(x):
return 3*x**3 - x**2 + 5
It looks better than...
def polynomial
return 3*x**3 - (x**2) + 5
And the first way is the way mathematicians do it. Other languages with exponentiation work the same way. Note that the negation operator also binds more loosely than multiplication, so
-x*y === -(x*y)
Which is also the way they do it in math.
If I had to guess, it would be because having an exponentiation operator allows programmers to easily raise numbers to fractional powers. Negative numbers raised to fractional powers end up with an imaginary component (usually), so that can be avoided by binding ** more tightly than unary -. Most languages don't like imaginary numbers.
Ultimately, of course, it's just a convention - and to make your code readable by yourself and others down the line, you'll probably want to explicitly group your (-1) so no one else gets caught by the same trap :) Good luck!
It seems intuitive to me.
Fist, because it's consistent with mathematical notaiton: -2^2 = -4.
Second, the operator ** was widely introduced by FORTRAN long time ago. In FORTRAN, -2**2 is -4, as well.
Ocaml doesn't do the same
# -12.0**2.0
;;
- : float = 144.
That's kind of weird...
# -12.0**0.5;;
- : float = nan
Look at that link though...
order of operations