So, basically I have to built an algorithm that tells me how many times X is divisible by Y. If its not divisible, it should return print -1.
Here's what i've got so far:
def divisible(x, y):
n = int(x/y)
if (n != 0 and x%y == 0):
print(x, "its divisible by",y,n,"times")
else:
print(-1)
divisible(5, 2)
The exercise its asking to use a counter to do this. How can I make It?
Thanks
Integer division and the modulo function should get you there -
divisible = lambda x, y: x // y if x % y == 0 else -1
divisible(13, 3)
# -1
divisible(12, 3)
# 4
def divisible (x, y):
# Initialize times to keep track of how many times x is
# divisible by y:
times = 0
# Enter an infinite loop:
while True:
# If the remainder of x divided by y is 0
# (= if x is divisible by y):
if ( x % y == 0 ):
# Increment times by 1 and actually divide x by y:
times += 1
x = x / y
# If x is *not* divisible by y, break out of the infinite loop:
else:
break
# If the original x was not divisible by y at all, return -1
# (otherwise, keep times unchanged):
if times == 0:
times = -1
return times
print(divisible(2, 2))
# 1
print(divisible(3, 2))
# -1
print(divisible(8, 2))
# 3
print(divisible(10000, 2))
# 4
Related
class Solution:
def isPalindrome(self, x: int) -> bool:
# If x is a negative number it is not a palindrome
# If x % 10 = 0, in order for it to be a palindrome the first digit should also be 0
if x < 0 and x%10 == 0):
return False
reversedNum = 0
while x > reversedNum:
reversedNum = reversedNum * 10 + x % 10
x = x // 10
# If x is equal to reversed number then it is a palindrome
# If x has odd number of digits, dicard the middle digit before comparing with x
# Example, if x = 23132, at the end of for loop x = 23 and reversedNum = 231
# So, reversedNum/10 = 23, which is equal to x
return True if (x == reversedNum or x == reversedNum // 10) else False
This is my code which is giving wrong output for 660,
Expected output : False
My output : True
Can someone tell me how to correct this.
reversedNum = 0
Num=x
while x > 0:
reversedNum = reversedNum * 10 + x % 10
x = x // 10
return True if (Num == reversedNum) else False
You don't really need an explicit check for a negative number because the while loop (in the following code) will not be entered and the return value will be an equality test between zero and some negative number - which is obviously False.
So:
def ispalindrome(x):
n = x
r = 0
while n > 0:
r *= 10
r += n % 10
n //= 10
return r == x
if you convert the number to a string is very simple. you only need to check that the string written backwards is the same
def ispalindrome(x):
return str(x) == str(x)[::-1]
ispalindrome(23132)
>>> True
I want to check if number, based on lower and upper bound, has prime divisors only 3 and 5 and number should be multiplication of power of 3 and power of 5. My current solution is this. I want to optimize it, since checking powers with for loops isn't good way in my opinion. Thanks in advance.
def checkNum(x):
for i in range(1,50):
for j in range(1,50):
return x == (3**i) * (5**j)
def printResult(l, r):
for i in range(l,r):
if checkNum(i):
print(i)
Based on comments I think this is the best way:
def checkNum(x):
while x%3==0:
x = x //3
while x%5==0:
x = x//5
return x==1
I want to optimize it, since checking powers with for loops isn't good
way in my opinion.
Over a range of random numbers, we improve its speed by doing:
def checkNum0(x):
if x % 2 == 0: # eliminate half the numbers in one test!
return False
while x % 15 == 0: # speed up the process
x = x // 15
while x % 5 == 0:
x = x // 5
while x % 3 == 0:
x = x // 3
return x == 1
Or we can use a nested loop and combine both divisions into one:
def checkNum(x):
if x % 2 == 0: # eliminate half the numbers in one test!
return False
for divisor in (15, 5, 3):
while (quotient_remainder := divmod(x, divisor))[1] == 0:
x = quotient_remainder[0]
return x == 1
Here is my code:
def isPalindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
while x > rev:
rev = (rev*10 + x % 10)
x /= 10
return x == rev or x == rev/10
x = 11
print(isPalindrome(x))
Why does this code not give the desired results for all positive integer inputs?
Your code has two problems.
The first is that x /= 10 performs a floating point divide, so 11 /= 10 is 1.1, not 1. Integer divide in Python is //.
The second is that you don't want to keep looping while x > rev but rather while x > 0 because you want to reverse every digit of your number. When x > 0, you still have digits in x that you haven't added to the reversed value. The accumulated portion of the reversed value being greater than the part of the answer still to be processed doesn't mean anything.
So here's a working version of your code, at least for your two test cases and a few more I did. I didn't do an exhaustive test.
def isPalindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
y = x
while y > 0:
rev = (rev*10 + y % 10)
y //= 10
return x == rev or x == rev/10
I'm having trouble with this problem that simply return True of False if a number n, is a palindrome.
Note: wherever I have a ____ indicates where there is a blank that needs to be filled in. There are 2 blank spaces.
def is_palindrome(n):
x, y = n, 0
f = lambda: ____
while x > 0:
x, y = ____ , f()
return y == n
I've spent about an hour on this. I've found out that putting x//10 in the second blank space will allow the function to iterate over the number of digits in n. It then comes down to the function f.
Ideally, every time it is called, it should add the last digit in n to a new number, y. Thus, if n = 235, the while loop will iterate 3 times, and each time f() is called, it should add 5, 3, and 2, to the value y.
Here's the logic: (y * 10) + x % 10
def is_palindrome(n):
x, y = n, 0
f = lambda: (y * 10) + x % 10
while x > 0:
x, y = x//10 , f()
return y == n
print(is_palindrome(123454321))
# True
print(is_palindrome(12))
# False
y*10 moves the current y to the left by 1 digit, and x%10 adds the last digit.
print(is_palindrome(235))
# False
Pre-iteration: x = 235, y = 0
First iteration: x = 23, y = 5
Second iteration: x = 2, y = 53
Third iteration: x = 0, y = 532
Excellent solution, mate! Maybe one little suggestion. Your solution iterates over all n digits, but you have only to iterate n/2 digits. Moreover, you can handle negative values directly because they aren't palindromes.
def is_palindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
head, tail = x, 0
while head > tail:
head, tail = head // 10, tail * 10 + head % 10
# When the length is an odd number, we can get rid of the middle digit by tail // 10
return head == tail or head == tail // 10
Time complexity: O(log(n)) because we divided 10 in every iteration
Space complexity: O(1)
Below is the code which has 11510 leetcode test cases and it is accepted
check a number is palindrome without converting it into string
var isPalindrome = function(x) {
let list=[]
if(x<0){
return false
}
while(x>0){
if(x<10){
list.push(parseInt(x))
break;
}
let num=parseInt( x%10)
list.push(num)
x=parseInt( x/10)
}
for(var i=0;i<list.length/2;i++){
if(list[i]!=list[list.length-(i+1)]){
return false
}
}
return true
};
thanks,
x = y // 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print(y, 'has factor', x)
break # Skip else
x -= 1
else: # Normal exit
print(y, 'is prime')
This is an example for understanding while loop in a book I'm reading, I don't quite understand why a floor division and then y % x? Can someone please explain this piece of code, whats it doing?
Thanks!
This is a lame primality test.
% is the mod operator. It performs division and returns the remainder rather than the result of the division. For example, 5 // 2 == 2, and 5 % 2 == 1.
Commented:
x = y // 2 # For some y > 1 ##Reduce search space to half of y
while x > 1:
if y % x == 0: # Remainder ##If x divides y cleanly (4 / 2 == 2)
print(y, 'has factor', x) ##y is not prime
break # Skip else ##Exit the loop
x -= 1 # Normal exit ##Try the next value
else:
print(y, 'is prime')
The program prints at least one factor of an integer y, or if it has no factors (other than itself and 1), prints that y is prime.
It uses the variable x to try all possible factors greater than one. It starts at the floor of y divided by 2, because no number larger than half of y could be a factor. Using normal division rather than floor division could give you a fractional value if y is odd. (An even better solution is to start with the square root of y - if y is not prime, one of its factors will be less than or equal to its square root.)
Inside the loop, it tests y % x, which is the remainder after dividing y by x. If the remainder is zero, that means that x is a factor of y, and it prints it.
The else clause is executed at the end of the loop, unless a factor is found, in which case the "break" skips out of the loop and the else clause. So either a factor is found, or it's prime.
Here's the improved code with the indentation fixed:
import math
def check_primality(y):
x = int(math.sqrt(y))
while x > 1:
if y % x == 0:
print y, 'has factor', x
break
x -= 1
else:
print y, 'is prime'
The code simply checks if the square root of x has been reached. Note that you can check the primality of a number by checking if the integers from 2 up to the square root of x divides x perfectly (without a remainder).
the logic is:
if y modulo x is 0, it means that x is a dividor of y, so y has a factor. print that, and break out of the loop.
if not, decrease x by 1, and try again.
but some things are broken in this code:
the else statement position
the fact the 'print y is prime' is after the loop - it will always print it.
For any number (x) which is not prime, there would be a factor greater than 1 and less than (x/2).
9 = 3*3
The logic is to iterate through all the numbers <= x/2 and check if the number divides.
I think the program tries to find the biggest prime factors of y.
If y is a prime factor it prints this as well.
x = y // 2 is for testing the numbers in the range x: 2..y/2.
A better approach would be to test only the numbers x: 2..sqrt(y)
the % denotes a modulus which gives you the remainder of division...
and this code checks for prime Y and also checks if Y is a multiplier of x...
x = y // 2 #x=the division or modulus of y , 2
while x > 1: #you want to check if this is a division result or a modulus
if y % x == 0: # if y is a multiplier of x
print(y, 'has factor', x)
break # break the while loop
x -= 1 # decreament x
else: # this line executes if the wihle reached x > 1 and didnt break
print(y, 'is prime')
so if y is a multiplier of x it will decreament x and the loop continue
otherwise it will print y is prime