Double Slash Assignment division in Python [duplicate] - python

This question already has answers here:
What exactly does += do?
(17 answers)
Closed 3 years ago.
I am new to Python and found a function that checks to see if an array of arguments can be made equal by only multiplying the number by 2. However, there is some notation that I do not understand.
Function:
def isEqual(a,n): # a is an arrary, n is the length of array
for i in range(0,n):
while a[i]%2==0:
a[i]//=2 # this is the part I do not understand
print(a[i])
if a[i] != a[0]:
return print("False")
# Otherwise, all elements equal, return true
return print("True")
When I step through the function I see that it replaces the a[i] number by a[i]//2, but I do not understand why you would write // equals to number
I understand the // is "floor" division, but not why someone would write a[i]//=2. I would have thought to write it as a[i]=a[i]//2. I can only assume these are the same things, I just never saw it written this way.
Test code:
a = [50, 4, 2]
n = len(a)
isEqual(a, n)

You might have came across operations that also assign value. Think
a += 1 # same as: a = a + 1
This is exactly the same. It integer divides and assigns the value. Probably better understood with proper spacing:
a //= 2 # same as: a = a // 2

Related

Printing binary without trailing 0s? [duplicate]

This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 4 months ago.
Trying to create a small program that takes in positive integers and converts it into reverse binary.
I've gotten this far:
import math
integer = int(input())
while integer > 0:
x = integer % 2
print(int(math.floor(x)), end='')
integer = integer / 2
The problem with this is that the output would have unnecessary trailing 0s. For example, if the input is 12, the output would be 0011000......
I've tried the int function to remove floats, I also tried floor function to round up(albeit I might've done it wrong).
Could the problem be a lack of sentinel value?
It sounds like you have reversed a binary number like this:
def reverse_bits(n):
res = 0
for i in range(n.bit_length(), -1, -1):
if n & (1 << i):
res += 1 << (n.bit_length() - i)
return res
bin(reverse_bits(12)) # '0b110'
You can bit shift to the right, until there is a 1 in the rightmost bit, to remove trailing zeros:
def remove_trailing_zeros(n):
while not n & 1:
n = n >> 1
return n
All together:
bin(remove_trailing_zeros(reverse_bits(12)))
Out[11]: '0b11'
use // instead of / in division
Here is an alternate approach:
integer = 3
print (bin(integer)[2:][::-1])

Python function that turns a number into binary [duplicate]

This question already has answers here:
Python int to binary string?
(36 answers)
Closed last year.
I know that in python there are certain functions like bin that turn
decimal numbers into binary numbers. I would like to build one myself. I have tried the following:
def binary(n):
bina = ''
B = []
if n == 0:
bina = '0'
else:
while n>0:
x = 0
while 2**x<n:
x = x+1
B.append(x-1)
n = n-2**(x-1)
The problem is that when I have the exponents with base 2 in the array B I don’t know how to actually read them so that I obtain the actual binary number made of ones and zeroes. How can I make the code above work?
before someone says that my question was already asked, my question is how can I make the code above work,I know that there are other methods to make a binary convertion in python, but I would like to know what's wrong with mine and possibly make my code work.
def make_binary(num):
binary = ''
while num > 0:
binary = str(num % 2) + binary
num = num // 2
return binary
print(make_binary(15))

How can I repeatedly divide a number by the elements of a list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
divisors = []
def check_for_prime(x):
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
if isinstance(divisors, float):
yield x
When I try to run this code, it shows an error: 'list object cannot be interpreted as an integer'. How can I fix this so the loop can successfully divide everything?
It seems like you are trying to check if a given number is prime through list comprehension. There are a good bunch of things wrong with your logic-
divisors = [x / d for d in list(range(x)) if x != any([0, 1, x])]
I believe you're trying to find a list of divisors for x here. This makes no sense though, even if I assume that you thought x != any([0, 1, x]) means "if x is either 0, 1, or x" (that's not actually what this code means). Wouldn't that statement always be true? I mean x has got to be x (unless it's nan, but that's a different topic).
If you wanted to express "if x is either 0, 1 or x" in python, you'd use if x in [0, 1, x] (you shouldn't want to though since that makes 0 sense as explained above). Not any. Read what any does.
To get a list of divisors for x, you should instead do-
divisors = [d for d in range(2, math.floor(x/2) + 1) if x % d == 0]
Essentially, you start from 2 (not 0 because that's impossible, and not 1 because we want to avoid that for prime checking), and stop at half the given number (because after that point, you can't divide the given number and get an integral result). Throughout this range, you only add those d for which x % d is 0. I.E, the result is integral. Notice, 6 % 3 is 0, because 3 is indeed a divisor of 6.
I have 0 clue what the hell you're trying to do here though-
if isinstance(divisors, float):
yield x
You're checking whether or not divisors is a float? why? you already know it's a list, you made it in the previous line.
I think you want to know if the given number is a prime or not. In that case, you can just check if the length of divisors is more than 0.
return len(divisors) > 0
Edit: As #RiccardoBucco mentioned below. If you don't want the list of divisors at all, you can simply return as soon as you find a divisor. A simple loop will suffice for that.
for d in range(2, math.floor(x/2) + 1):
if x % d == 0:
# x is not prime
return False
# x is prime
return True
However, DO NOT forget to factor in the exceptional case when x = 1, 1 is not a prime number. Should be factored in both the for loop and the list comprehension method.
You are passing your list as the input argument to range, which expects an integer. Don't do that. Say for i in list.
This will always fail because you're creating a new list by using the comprehension in line 3. Line 4 will always evaluate to False because a list is obviously not a float.

Project Euler number 3 - Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was curious if anyone could fix my code, this is for project Euler Question 3 (What is the largest prime factor of the number 600851475143 ?), as of now, I am sticking to a program that will find all the prime factors in 100, but am getting an error message for divide by 0, in my head the code seems to work, but it isn't. Unless absolutely necessary, I'd like to keep the while loops. Thanks.
def isPrime(A):
x = 2
while x < A:
if A % x == 0:
return False
x += 1
return A
def isInt(x):
if x == int(x):
return True
return False
A = int(input("Number? "))
counter = 2
while counter <= A:
if isInt(A/isPrime(counter)) == True:
print(counter)
counter += 1
print ("Done")
It seems the key issue is that isPrime() sometimes returns a boolean, and other times returns the input (an integer). You should avoid having functions that do too many things at once - a function called isPrime() should just indicate whether the input is prime or not (i.e. always return a boolean). Some other suggestions inline:
def isPrime(n): # n is a common variable name to use for "some number"
x = 2
while x < n:
if n % x == 0:
return False
x += 1 # this isn't an ideal way to detect primes, can you think of any improvements?
return True
def isInt(n): # use consistent variables - you used A above and x here, which is confusing
return n == int(n) # you can just return the boolean result directly
input = int(input("Number? ")) # use meaningful variable names when possible
counter = 2
while counter <= input:
# I *think* this is what you were trying to do:
# if counter is prime and input/counter is an integer.
# If not you may need to play with this conditional a bit
# also no need to say ' == True' here
if isPrime(counter) and isInt(input/counter):
print(counter)
counter += 1
print ("Done")
This should run (whether it works or not, I leave to you!), but it's still not as efficient as it could be. As you get into harder Project Euler problems you'll need to start paying careful attention to efficiency and optimizations. I'll let you dig into this further, but here's two hints to get you started:
Incrementing by one every time is wasteful - if you know something is not divisible by 2 you also know it's not divisible by 4, 8, 16, and so on, yet your code will do those checks.
In general finding primes is expensive, and it's a very repetitive operation - can you re-use any work done to find one prime when finding the next one?

Python Implicit if statement with variable assignment -- How does this work? [duplicate]

This question already has answers here:
Is it Pythonic to use bools as ints?
(7 answers)
Closed 8 years ago.
I started learning python within the last month. I recently came across a code example where a counter in the code was incremented based on a condition. The way the author did it was:
x = 0
x += [-1, 1][a == b]
From testing this works the same as if you used an if a==b: increment, else: decrement.
I can't find this syntax anywhere else I've looked in the python documentation. It seems quite powerful and allows a variety of conditional assignments and aids conciseness.
Is there a reason I shouldn't use this structure also what is the structure doing?
The Zen of Python says:
Explicit is better than implicit.
Simple is better than complex.
Readability counts.
Stick to the more explicit, readable and widely used version:
x += 1 if a == b else -1
[a == b] evaluates to False or True which are effectively 0 or 1, so then that's used as the index into [-1, 1]...
So when a==b you get [-1, 1][1] (which is 1) or where they're not equal you get [-1, 1][0] (which is -1), the respective value is then added to x.
Some would call it a hack, and it can be difficult to read (as evidenced by this question) but it's equivalent to:
x = 0
if(a == b):
x += 1
else:
x -= 1
Because the integer version of the (boolean) result of a == b is 0 or 1.

Categories