This question already has answers here:
How are Python in-place operator functions different than the standard operator functions?
(2 answers)
Closed 6 years ago.
I'm trying to update a multiplicative value to a variable.
I know that I can do += and -= for addition and subtraction and *= for multiplication, but I don't fully grasp the entirety of that type of operation. Can someone point me to the documentation that covers this? I can't seem to find it on python.org.
Well technically you are never updating python variables (integers, strings and floats among many other are immutable), you are re-assigning a value to a name.
+ is shorthand for add(), * is shorthand for mul() and - is short for sub().
since you are re-assigning variable, you are essentially performing these operations (when adding, substracting, multiplying, dividing or whatever it is that you do):
a = 1
a = a + 1 # a = 2
a = a * 2 # a = 4
a = a - 1 # a = 3
+=, -= and *= are just shorts for the above expressions.
i.e. the above can be restated as:
a = 1
a += 1
a *= 2
a -= 1
python docs for operators: https://docs.python.org/3.5/library/operator.html
see also python docs for inplace operators for more information: https://docs.python.org/3.5/library/operator.html#inplace-operators
Related
This question already has answers here:
How to check if a number is a power of 2
(32 answers)
Closed 3 years ago.
What is the most efficient (in terms of speed and space) way to check if a decimal number only has a single '1' in its binary representation without using special functions (math, numpy, etc.)?
e.g. 1 is '001' and 4 is '100'.
I've tried this
binary = "{0:b}".format(value)
if binary.count('1') != 1:
return 1
else:
return 0
I believe this is O(log n) in terms of space and O(n) in terms of speed? Is there a way to do this more efficiently?
One of the method to do it could be-
binary_num = '00101010'
result = [1 for x in binary_num if x == '1']
if len(result) == 1:
print('Success')
else:
print('Failed')
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm trying to create a function that receive as argument a number and return an array of 3 numbers max.
I have 3 tokens. 1 unit, 5 unit and 25 unit.
calculateUnit(4) should = [4,0,0]
calculateUnit(7) should = [2,1,0] (because 2 unit of 1 and 1 unit of 5 = 7)
calculateUnit(36) should = [1,2,1] (because 1 unit of 1, 2 unit of 5 and 1 unit of 25 = 36)
I have a basic code and I think I need to use modulo division, I already tried to search here and every other resources I have but I may not use the correct terms.
You can reduce your solution to:
def convertInToken(am):
return [am//25, (am%25)//5, am%5]
This leverages integer-division (3.x upwards, also named floor division) and modulo division.
Floor division returns the full integer that woud have been returned if you did a normal division and floored it.
Modulu division returns the "remainder" of a division.
I managed to do that, but thanks anyway :)
# your code goes here
import math
def convertInToken(am):
result = [];
#need to use 25
if am >= 25:
amount25 = math.floor((am/25))
amount5 = math.floor((am-(amount25*25))/5)
amount1 = math.floor(((am-(amount25*25)-(amount5*5))/1))
result = result+[amount1]
result = result+[amount5]
result = result+[amount25]
#need to use 5
elif am >= 5:
amount5 = math.floor((am/5))
amount1 = math.floor(((am-(amount5*5))/1))
result = result+[amount1]
result = result+[amount5]
result = result+[0]
#need to use 1
elif am < 5:
result = result+[am]
result = result+[0]
result = result+[0]
return result
print(convertInToken(4))
print(convertInToken(7))
print(convertInToken(12))
print(convertInToken(37))
This question already has answers here:
Outerzip / zip longest function (with multiple fill values)
(3 answers)
Closed 5 years ago.
I need to zip two lists inclusively. I.e. keep values of the longer list and, possibly, add a default value for the shorter one:
e.g.
lst_a = [1,2,3] # len = 3
lst_b = [5,6,7,8] # len = 4
# no default values
inclusive_zip(lst_a, lst_b) = [(1,5),(5,6),(3,7),(None,8)]
# with default value (e.g. for position in 2D space)
inclusive_zip(lst_a, 0, lst_b, 0) = [(1,5),(5,6),(3,7),(0,8)]
I can make something of my own, but was wondering if there's a built-in or super simple solution.
itertools.zip_longest(*iterables, fillvalue=None)
import itertools
def add_by_zip(p1,p2):
p_out = [a+b for a,b in itertools.zip_longest(p1,p2, fillvalue=0)]
print(p_out)
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed 7 years ago.
In C# I would do this if I wanted the word 'Many' to display if the count was 10 or more:
int count = 10;
var result = count < 10 ? count : "Many";
How do you do this in python?
Simply use print function and if-else statement:
>>> count =10
>>> print('many') if count>=10 else ''
many
I'm using python 3 for a small extra credit assignment to write an RSA cracker. The teacher has given us a fairly large (large enough to require more than 32 bits) int and the public key. My code works for primes < 32 bits. One of the reasons I chose python 3 is because I heard it can handle arbitrarily large integers. In the python terminal I tested this by doing small things such as 2**35 and factorial(70). This stuff worked fine.
Now that I've written the code, I'm running in to problems with overflow errors etc. Why is it that operations on large numbers seem to work in the terminal but won't work in my actual code? The errors state that they cannot be converted to their C types, so my first guess would be that for some reason the stuff in the python interpreter is not being converter to C types while the coded stuff is. Is there anyway to get this working?
As a first attempt, I tried calculating a list of all primes between 1 and n (the large number). This sort of worked until I realized that the list indexers [ ] only accept ints and explode if the number is higher than int. Also, creating an array that is n in length won't work if n > 2**32. (not to mention the memory this would take up)
Because of this, I switched to using a function I found that could give a very accurate guess as to whether or not a number was prime. These methods are pasted below.
As you can see, I am only doing , *, /, and % operations. All of these seem to work in the interpreter but I get "cannot convert to c-type" errors when used with this code.
def power_mod(a,b,n):
if b < 0:
return 0
elif b == 0:
return 1
elif b % 2 == 0:
return power_mod(a*a, b/2, n) % n
else:
return (a * power_mod(a,b-1,n)) % n
Those last 3 lines are where the cannot convert to c-type appears.
The below function estimates with a very high degree of certainty that a number is prime. As mentioned above, I used this to avoid creating massive arrays.
def rabin_miller(n, tries = 7):
if n == 2:
return True
if n % 2 == 0 or n < 2:
return False
p = primes(tries**2)
if n in p:
return True
s = n - 1
r = 0
while s % 2 == 0:
r = r+1
s = s/2
for i in range(tries):
a = p[i]
if power_mod(a,s,n) == 1:
continue
else:
for j in range(0,r):
if power_mod(a, (2**j)*s, n) == n - 1:
break
else:
return False
continue
return True
Perhaps I should be more specific by pasting the error:
line 19, in power_mod
return (a * power_mod(a,b-1,n)) % n
OverflowError: Python int too large to convert to C double
This is the type of error I get when performing arithmetic. Int errors occur when trying to create incredibly large lists, sets etc
Your problem (I think) is that you are converting to floating point by using the / operator. Change it to // and you should stay in the int domain.
Many C routines still have C int limitations. Do your work using Python routines instead.