This question already has answers here:
BODMAS - python
(4 answers)
How do order of operations go on Python?
(5 answers)
Closed last year.
I don't get why this function returns 2.0.
1+1/2*2
For order of operations, I thought it would be multiplication first, then division, left to right, so 1+1/4 to 1+.25 or maybe even return 2/4 =0.5...
I am really confused how it outputs 2.0.
Thanks in advance! Currently studying for an exam.
As for the multiplication and division, the order is left to right. So here is the division first.
1 + 1 / 2 * 2 = 1 + 0.5 * 2 = 1 + 1 = 2
For the next problem, I think if a == 'A' or 'B' is 2 expressions, a == 'A' and 'B'. I've learned a little about C++, and the 'B' refers 66 in the ASCII, which is not 0, so the expression 'B' is always true. Maybe in python it will be the same.
So the code should be if a == 'A' or a == 'B':
See the stackoverflow post: How do order of operations go on Python?
According to that your math, 1+1/2*2, is as follows:
/ 1 \
ans = 1 + ( --- ) X 2
\ 2 /
= 1 + (0.5 X 2)
= 1 + 1
= 2
Multiplication and division are in the same group and are performed left to right (aggregating the answers from the link I referenced).
Enjoy the ASCII art ¯\_(ツ)_/¯
Related
This question already has answers here:
Convert String to Int without int()
(4 answers)
Closed 2 years ago.
I need to create a function that takes in a string e.g. '142' and return it as an integer, without the use of the int() function. I'm not sure where to start at all and the 'hint' provided to us is to use a list such as
digits = list('0123456789')
edit: We have not yet learnt chr, ord, eval() or ast.literal_eval? We have not yet learnt what string and integer literals are nor have we learnt dictionaries. for loops as well as 'in' are discouraged as well.
Does anyone have any ideas as to how to approach this?
From '5768' you can get 8 * 1 + 6 * 10 + 7 * 100 + 5 * 1000. You can use a loop to access the characters of the string and you have to keep track of the multiplier.
index can be used to find the position of the current character in the list and then you have the correct integer value for multiplication.
digits = list('0123456789')
value = 0
exp = 0
for c in reversed('5768'):
print(f'c={c} exp={exp}')
i = digits.index(c)
value += i * 10 ** exp
exp += 1
print(value)
After getting some more constraints in the question this code can be adjusted to the following.
digits = list('0123456789')
number = '5768'
value = 0
character_position = 0
while character_position < len(number):
i = digits.index(number[character_position])
value += i * 10 ** (len(number) - character_position - 1)
character_position += 1
print(value)
A one liner solution:
print(sum('0123456789'.index(c) * 10 ** exp for exp, c in enumerate(reversed('5768'))))
Convert to int using eval:
str = '0123456789'
def str_to_int(str):
return eval(str.lstrip("0"))
print(str_to_int(str))
print(type(str_to_int(str)))
Returns:
123456789
<class 'int'>
This question already has answers here:
How to find integer nth roots?
(11 answers)
Closed 7 years ago.
Recently I encountered a problem:
I want to calculate various roots of various numbers like this:
x = x ** 1/y+1
None of the methods I know result in a working code.
Method 1:
x = 54
y = 2
x = x ** 1/y+1
print(x)
Printed value is 28.0 instead of 3.7798
Method 2:
x = 54
y = 2
x = x ** 1/(y+1)
print(x)
Printed value is 18.0 istead of 3.7798
Method 3:
x = 216
y = 2
x = x ** (1/(y+1))
print(x)
Printed value is 5.99 instead of 6
Is there a way that would work with y being up to 20?
Edit:
Another suggested method:
def nth_root(val, n):
ret = int(val**(1./n))
return ret + 1 if (ret + 1) ** n == val else ret
y = 1
print(nth_root(19, (y+1)))
prints 4
Since everyone else has already told you why your Method 3 is correct, I'll stick to getting you an accurate answer. You can read more about why you're not getting exactly 6, but basically it's because your computer doesn't represent the 1/3 exactly when doing the calculation and makes the final answer off.
So, the easiest solution is to use sympy:
import sympy
y = 216
x = 2
x = sympy.root(y,x+1)
print(x)
You don't seem to understand (yet) order of operations in a programming language. You need parentheses to make sure you add 1 to y, then take the reciprocal, and then use that as an exponent. The "natural" order is the opposite.
x = x ** (1.0/(y+1))
What you want is this (assuming you are using Python 3):
x = x ** (1/(y+1))
For Python 2, either of the following will work:
from __future__ import division
x = x ** (1/(y+1))
or (also fine on Python 3):
x = x ** (1.0/(y+1))
The issue is you need to apply the parentheses in the correct locations to get the order of operations right.
Method 3 is to do with floating point arithmetic. See: https://docs.python.org/3.5/tutorial/floatingpoint.html
For more info on Python 2 vs. Python 3 division:
Division in Python 2.7. and 3.3
Only your last code works because ** has higher precedence than / (and / has higher precendence than +).
The value is not exactly 6, because floating point numbers are not perfectly accurate. A third can not be represented as a float.
All your values are just as expected. According to the python operator precedence:
x ** 1/y+1 is parsed as ((x ** 1) / y) + 1, and
x ** 1/(y+1) is actually (x ** 1) / (y + 1).
What you probably want is x ** (1. / (y + 1)). Note, that 1. is a floating point number, causing the whole expression to be evaluated as floats. This also means that you will work with finite precision, e.g., getting 5.99999 instead fo 6 is to be expected.
This question already has answers here:
floating point equality in Python and in general
(8 answers)
Closed 9 years ago.
I'm learning python and have been trying various things... for some reason this isn't working!
x = (-2.1)
if ( (0.4*(x)) - (0.02*(x)) + (1.396) ) == 0.598:
print "TRUE!"
else:
print "FALSE!"
print ( (0.4*(x)) - (0.02*(x)) + (1.396) )
It prints FALSE! followed by 0.598 obviously the answer is 0.598 so why does'nt the "if" statement work? Thanks!
If you try to print out
(0.38 * x) + 1.396 # note simplified maths and syntax
You will quickly see why:
0.5979999999999999
This is not exactly equal to 0.598, because of the way floating point numbers (float) work. You are better testing these using tolerance:
a = (0.38 * x) + 1.396
if abs(a - 0.598) < 0.0001:
You're confused because python print is using float.__str__, which in turn trims up to 12 digits, so numbers are not what is printed:
>>> ( (0.4*(x)) - (0.02*(x)) + (1.396) ).__str__()
'0.598'
>>> ( (0.4*(x)) - (0.02*(x)) + (1.396) ).__repr__()
'0.5979999999999999'
This question already has answers here:
What does the caret (^) operator do?
(5 answers)
Closed 9 years ago.
I'm struggling to find documentation on what the ^ does in python.
EX.
6^1 =
7
6^2 =
4
6^3 =
5
6^4 =
2
6^5 =
3
6^6 =
0
Help?
It is the bitwise exclusive-or operator, often called "xor". For each pair of corresponding bits in the operands, the corresponding bit in the result is 0 if the operand bits are the same, 1 if they are different.
Consider 6^4:
6 = 0b0110
4 = 0b0100
6^4 = 0b0010 = 2
As you can see the least-significant bit (the one on the right, in the "one's" place) is zero in both numbers. Thus the least-significant bit in the answer is zero. The next bit is 1 in the first operand and 0 in the second, so the result is 1.
XOR has some interesting properties:
a^b == b^a # xor is commutative
a^(b^c) == (a^b)^c # xor is associative
(a^b)^b == a # xor is reversible
0^a == a # 0 is the identity value
a^a == 0 # xor yourself and you go away.
You can change the oddness of a value with xor:
prev_even = odd ^ 1 (2 = 3 ^ 1)
next_odd = even ^ 1 (3 = 2 ^ 1)
for more information on XOR , please react the documentation on Python.org at here:
http://docs.python.org/2/library/operator.html
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 9 years ago.
Improve this question
I'm confused with the logic of 1% 2 will be 1. Because from what I know 1/2 is 0 so there is no remainder for this.
1/2 is 0 with a remainder of 1. The % operator returns that remainder.
% returns the remainder of a / b:
>>> 1 % 2
1
>>> 1/2
0
>>> 1 - 0
1
Also, the modulo expression can be expressed as:
r = a - nq
Where q is floor(a/n). So:
>>> import math
>>> 1 - 2 * math.floor(1/2)
1.0
% is the modulo operator. It returns the remainder after dividing the left hand side by the right hand side. Since 2 divides zero times into 1, the remainder is one.
In general, if a and b are positive integers, and a < b, then a % b == a.
The arguments do not need to be integers, though. More detail is available from the python reference documentation (http://docs.python.org/2/reference/expressions.html):
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
The integer division and modulo operators are connected by the following identity: x == (x/y)*y + (x%y). Integer division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x/y, x%y). These identities don’t hold for floating point numbers; there similar identities hold approximately where x/y is replaced by floor(x/y) or floor(x/y) - 1 [3].
Certainly there is a remainder. How many 2s can you get out of 1? 0 of them, with 1 left over.
Ok, the answer has been posted like 6 times already, just adding this for completeness, If there's one way to understand modulo (%), it's converting from base 10 to base 2, 1 can't be divided by 2 so we leave it alone (get a remainder of 1). You can imagine the binary numbers in the third column to be the results of a modulo operation.
eg. 9 (base 10) to (base 2)..
2 | 9 | 1
2 | 4 | 0
2 | 2 | 0
2 | 1 | 1
2*0 is 0
hence the remainder is 1
if the question is to find m%n
we find smallest or equal q such that n*(some whole number) = q and q<=m
we then find (m-q) which is the remainder..
What the % operator is doing:
a % b equals a value c such as 0 <= c < b and there exists a number k so that b * k + c = a.