Check if a number is a palindrome without changing it into string - python

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,

Related

How many times x is divisible by y using function

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

The incrementing here continues to return a 0 value

I was writing the solution to this codewars problem however I've ran into a bit of an issue.
Problem statement:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit, e.g.:
persistence(39) # returns 3, because 39=27, 27=14, 1*4=4 and 4 has only one digit
def persistence(n, t=1, x=0):
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
for i in number:
t = t * i
if len(str(t)) > 1:
x += 1
return(persistence(t,x))
else:
return(x)
else:
return 0
I can't quite figure out what the error is in this code. My hunch is that it's either a parameter error or the way the return() value is placed.
In essence, the code for distilling an integer to it's multiples is correct, so I just added an extra parameter to persistence; setting x = 0 and making it so that each time the if condition was fulfilled it would increment that exact x value. Once the number was distilled, simply output x. Yet it continues to simply output 0 as the final answer. What's the problem here?
Edit: Solution was in the comments, didn't realise how the parameters were passing. Correct version is:
return(persistence(t,1,x))
Also had to set x = 1 for the logic to work on codewars.
There are 2 flaws in Your code:
return(persistence(t,x))
should be
return(persistence(t,1,x))
otherwise the value of x will be assigned to t and x will be defaulted to 0.
Then you must increment x directly after the first test, otherwise You will miss one iteration.
Another way to calculate this is not to switch over to strings, but to do it numerically:
def persistence(n):
iterations = 0; # no iterations yet
while n > 9: # while n has more than 1 digit:
product = 1 # neutrum for result product
while n > 0: # while there a digit to process:
digit = n % 10 # retrieve the right most digit
product *= digit # do the multiplication
n = n // 10 # cut off the processed digit
iterations += 1 # increment iterations
n = product # let n be the newly calculated product
return iterations # return the result
I think you your function's parameters work not as you expect them to do.
When you call function persistence(t, x), the first argument n should become t, and second argument x, should become new x. But in your function, x becomes new t because of their position.
It is quite useful to have bunch of print statements to reveal the bug.
def persistence(n, x=1, t=1):
print('x:', x)
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
for i in number:
t = t * i
print('t:', t)
if len(str(t)) > 1:
x += 1
print('x has changed:', x)
return persistence(t, x)
else:
return x
else:
return 0
print(persistence(39))
print('---------------')
print(persistence(999))
print('---------------')
print(persistence(4))
Passes all test cases with two changes:
You were not updating your n with the new t everytime
Your x was being set to 0 every time. That should be set to 1 in the beginning (default value)
def persistence(n, t=1, x=1):
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
for i in number:
t = t * i
if len(str(t)) > 1:
x += 1
return (persistence(n=t, x=x))
else:
return (x)
else:
return 0
Actually, you can write it without needing both parameters t and n. Just one n is fine as shown below:
def persistence(n, x=1):
if len(str(n)) > 1:
number = [int(i) for i in str(n)]
t = 1
for i in number:
t = t * i
if len(str(t)) > 1:
return x + (persistence(n=t, x=x))
else:
return (x)
else:
return 0

Function to evaluate validity of numerical palindrome for floating point numbers using Python

So there are plenty of algorithms to evaluate whether an int is a palindrome, i.e.
def ReverseNumber(n, partial=0):
if n == 0:
return partial
return ReverseNumber(n // 10, partial * 10 + n % 10)
or this one:
def isPalindrome(x):
if (x < 0):
return False
div = 1
while (x / div >= 10):
div *= 10
while (x != 0):
l = x / div
r = x % 10
if (l != r):
return False
x = (x % div) / 10
div /= 100
return True
However what I'd like to do is assess whether a number such as 1.01 or 22.22 and so on, whether such numbers are themselves palindromes.
How could either of those algorithms above be adapted to function for floats in addition to ints?
This is the code I'm using to call it:
import sys
# This method determines whether or not the number is a Palindrome
def isPalindrome(x):
x = str(x).replace('.','')
a, z = 0, len(x) - 1
while a < z:
if x[a] != x[z]:
return False
a += 1
z -= 1
return True
if '__main__' == __name__:
trial = int(sys.argv[1])
# check whether we have a Palindrome
if isPalindrome(trial):
print("It's a Palindrome!")
The simplest thing to do is just convert the number to a string, then compare characters from the ends to the middle. The string conversion is less expensive than repeated multiplications and divisions.
def isPalindrome(x):
x = str(x).replace('.','')
a, z = 0, len(x) - 1
while a < z:
if x[a] != x[z]:
return False
a += 1
z -= 1
return True

lucky sevens, sum of 3 consecutive numbers in array == 7

Write a function lucky_sevens(numbers), which takes in an array of
integers and returns true if any three consecutive elements sum to 7.
Why isn't this producing an output of True? The last 3 values sum = 7.
def lucky_sevens(numbers):
x, y = 0, 3
sum_of_numbers = sum(numbers[x:y])
while (sum_of_numbers != 7) and (y < len(numbers)):
x = x + 1
y = y + 1
if sum_of_numbers == 7:
return True
else:
return False
print(lucky_sevens([1,2,3,4,5,1,1]))
The problem that when the function first gets called the sum_of_numbers variable gets assigned the value of the sum of the first 3 values in the list, and never gets updated with the new x,y values, you'd probably want to create a callback function to achieve that behavior.
As it stands, you'll need to move the sum statement into the while loop so the sum gets updated with the new x,y values:
def lucky_sevens(numbers):
result = False
x, y = 0, 3
while (y <= len(numbers)):
if sum(numbers[x:y]) == 7:
result = True
break
x += 1
y += 1
return result
print(lucky_sevens([1,2,3,4,5,1,1]))
How about something as simple as
def lucky_sevens(numbers):
for x in range(len(numbers) - 2):
if sum(numbers[x:x+3]) == 7:
return True
return False
Or with your original code, just cleaned up a little bit.
def lucky_sevens(numbers):
if len(numbers) < 3:
return False
x, y = 0, 3
sum_of_numbers = sum(numbers[x: y])
while sum_of_numbers != 7 and y < len(numbers):
x += 1
y += 1
sum_of_numbers = sum(numbers[x: y])
if sum_of_numbers == 7:
return True
return False
Your error came in your while loop. As you were looping, sum_of_numbers was staying constant. Instead, you have to update it for every new x and y within the while loop.
Also some repetitive stuff like else: return False, can be simplified to return False, as it can only get to that line if sum_of_numbers == 7 is False.
Finally x = x + 1 can be written in the more common shorthand x += 1, the same going with y = y + 1.
This ought to do the trick:
def lucky_sevens(numbers):
if len(numbers) < 3:
return False
return 7 in [sum(numbers[i:i+3]) for i in range(0, len(numbers)-2)]
print(lucky_sevens([1,2,3,4,5,1,1]))
# True
The list comprehension will move through your list 3 numbers at a time and compute the sum of each set of three integers. If 7 is in that list, then there are 3 consecutive numbers that sum to 7. Otherwise, there isn't.
The one caveat is that doing this sort of list comprehension requires that the list have more than 3 elements in it. That's why the if statement is there.
If you wanted to use your original code though, you just have to make a few adjustments. Your logic was all there, just needs a little cleaning.
def lucky_sevens(numbers):
x, y = 0, 3
sum_of_numbers = sum(numbers[x:y])
while (sum_of_numbers != 7) and (y < len(numbers)):
x = x + 1
y = y + 1
sum_of_numbers = sum(numbers[x:y])
if sum_of_numbers == 7:
return True
else:
return False
You simply needed to redo the sum within your while loop. That way, sum_of_numbers updates with each loop and each new selection of indices.
This code returns the consecutive elements in the Array whose sum is 7 and index of initial element.
function lucky_seven(arr){
let i=0;
let lastIndex = 0;
if(arr.length < 3){
return false;
}
while(i <= lastIndex){
let sum = 0;
lastIndex = i + 3;
let subArr = arr.slice(i,lastIndex);
if(subArr.length === 3) {
sum = subArr.reduce((acc, cur) => acc + cur);
if(sum === 7){
return {
subArr: subArr,
index: i
};
}
i++;
} else{
return false;
}
}
}
lucky_seven([3,2,1,4,2])
I just used this:
def lucky_sevens(numbers):
x = 0
y = False
for i in numbers:
if i == 7:
x += 7
if x == 21:
y = True
else:
x = 0
return y
There are some very interesting responses here. Thought I will share my work as well.
def lucky_seven(num_list):
if len(num_list) < 3: return False
return any([True if sum(num_list[i:i+3]) == 7 else False for i in range(len(num_list)-2)])
print ('lucky seven for [1,2,3] is :',lucky_seven([1,2,3]))
print ('lucky seven for [3,4] is :',lucky_seven([3,4]))
print ('lucky seven for [3,4,0] is :',lucky_seven([3,4,0]))
print ('lucky seven for [1,2,3,4,5,1,1] is :',lucky_seven([1,2,3,4,5,1,1]))
print ('lucky seven for [1,2,3,4,-2,5,1] is :',lucky_seven([1,2,3,4,-2,5,1]))
The output of this will be:
lucky seven for [1,2,3] is : False
lucky seven for [3,4] is : False
lucky seven for [3,4,0] is : True
lucky seven for [1,2,3,4,5,1,1] is : True
lucky seven for [1,2,3,4,-2,5,1] is : True
def f(l):
if len(l) < 3:
return False
for i in range(len(l)):
if i+3 <= len(l):
if sum(l[i:i+3]) == 7:
return True
continue
else:
return False

Finding the sum of even valued terms in Fibonacci sequence

#!/usr/bin/python2
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
odd, even = 0,1
total = 0
while True:
odd = odd + even #Odd
even = odd + even #Even
if even < 4000000:
total += even
else:
break
print total
My algo:
If I take first 2 numbers as 0, 1; the number that I find first in while loop will be an odd number and first of Fibonacci series.
This way I calculate the even number and each time add the value of even to total.
If value of even is greater than 4e6, I break from the infinite loop.
I have tried so much but my answer is always wrong. Googling says the answer should be 4613732 but I always seem to get 5702886
Basically what you're doing here is adding every second element of the fibonacci sequence while the question asks to only sum the even elements.
What you should do instead is just iterate over all the fibonacci values below 4000000 and do a if value % 2 == 0: total += value. The % is the remainder on division operator, if the remainder when dividing by 2 equals 0 then the number is even.
E.g.:
prev, cur = 0, 1
total = 0
while True:
prev, cur = cur, prev + cur
if cur >= 4000000:
break
if cur % 2 == 0:
total += cur
print(total)
def fibonacci_iter(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
print sum(a for a in fibonacci_iter(4e6) if not (a & 1))
Here is simple solution in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=1,j=1,sum=0;
while(i<4000000)
{
i=i+j;
j=i-j;
if(i%2==0)
sum+=i;
}
printf("Sum is: %d",sum);
}
Your code includes every other term, not the even-valued ones. To see what's going on, print even just before total += even - you'll see odd numbers. What you need to do instead is check the number you're adding to the total for evenness with the modulo operator:
total = 0
x, y = 0, 1
while y < 4000000:
x, y = y, x + y
if x % 2:
continue
total += x
print total
code in python3:
sum = 2
a = 1
b = 2
c = 0
while c <= 4000000:
c = a + b
if c%2 == 0:
sum += c
a,b = b,c
print(sum)
output >>> 4613732
You just misunderstood with the even sequence and even value.
Example: 1, 2, 3, 5, 8, 13, 21
In the above sequence we need to pick 1, 3, 5, 13, 21 and not 2, 5, 13.
Here is the solution fro JAVA
public static void main(String[] args) {
int sum = 2; // Starts with 1, 2: So 2 is added
int n1=1;
int n2=2;
int n=0;
while(n<4000000){
n=n1+n2;
n1=n2;
n2=n;
if(n%2==0){
sum=sum+n;
}
}
System.out.println("Sum: "+sum);
}
Output is,
Sum: 4613732
def fibLessThan(lim):
a ,b = 1,2
total = 0
while b<lim:
if b%2 ==0:
total+=b
a,b = b,a+b
return total
I tried this exactly working answer. Most of us are adding number after fib formula where we are missing 2. With my code I am adding 2 first then fib formula. This is what exact answer for the Euler problem.
This is the second problem in the Project Euler series.
It is proven that every third Fibonacci number is even (originally the zero was not part of the series). So I start with a, b, c being 0,1,1 and the sum will be every recurring first element in my iteration.
The values of my variables will be updated with each being the sum of the preceding two:
a = b + c, b = c + a , c = a + b.
The variable a will be always even. In this way I can avoid the check for parity.
In code:
def euler2():
a, b, c, sum = 0, 1, 1, 0
while True:
print(a, b, c)
a, b, c = (b + c), (2 * c + b), (2 * b + 3 * c)
if a >= 4_000_000:
break
sum += a
return sum
print(euler2())
it should be:
odd, even = 1,0
Also, every third numer is even (even + odd + odd = even).
If you add every second value of the fibonacci sequence you'll get the next fibonacci value after the last added value. For example:
f(0) + f(2) + f(4) = f(5)
0 + 1 + 3 + 8 = 13
But your code currently does not add the first even value 1.
Other answers are correct but note that to just add all even numbers in an array, just do
myarray=[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
sum(map(lambda k:k if k%2 else 0, myarray))
or
sum([k if k%2 else 0 for k in [1,2,3,4,5]])
Every 3rd item in the Fibonnaci sequence is even. So, you could have this:
prev, cur = 0, 1
count = 1
total = 0
while True:
prev, cur = cur, prev + cur
count = count + 1
if cur >= 4000000:
break
if count % 3 == 0:
total += cur
print(total)
or this (changing your code as little as possible):
even, odd = 0,1 # this line was corrected
total = 0
while True:
secondOdd = even + odd # this line was changed
even = odd + secondOdd #Even # this line was changed
if even < 4000000:
total += even
odd = secondOdd + even # this line was added
else:
break
print total
Another way would be (by the use of some simple math) to check that the sum of a2+a5+a8+a11+...+a(3N+2) (the sum of even Fibonacci values) is equal to (a(3N+4)-1)/2. So, if you can calculate directly that number, there is no need to calculate all the previous Fibonacci numbers.
not sure if your question is already answered or you've found a solution, but here's what you're doing wrong. The problem asks you to find even-valued terms, which means that you'll need to find every value in the fibonacci sequence which can be divided by 2 without a remainder. The problem does not ask you to find every even-indexed value. Here's the solution to your problem then, which gives a correct answer:
i = 1
total = 0
t = fib(i)
while t <= 4000000:
t = fib(i)
if t % 2 == 0:
total += t
i += 1
print total
Basically you loop through every each value in fibonacci sequence, checking if value is even by using 'mod' (% operator) to get remainder, and then if it's even you add it to sum.
Here is how I was able to solve this using native javascript.
var sum = 0,
x = 1,
y = 2,
z = 0;
while (z < 4000000) {
if (y%2==0){
sum +=y;
}
z = x + y;
x = y;
y = z;
} console.log(sum);
I did it differently.
def fibLessThan(lim):
#################
# Initial Setup #
#################
fibArray=[1, 1, 2]
i=3
#####################
# While loop begins #
#####################
while True:
tempNum = fibArray[i-2]+fibArray[i-1]
if tempNum <= lim:
fibArray.append(tempNum)
i += 1
else:
break
print fibArray
return fibArray
limit = 4000000
fibList = fibLessThan(limit)
#############
# summation #
#############
evenNum = [x for x in fibList if x%2==0]
evenSum = sum(evenNum)
print "evensum=", evenSum
Here is my Python code:
even_sum = 0
x = [1, 1] # Fibonacci sequence starts with 1,1...
while (x [-2] + x [-1]) < 4000000: # Check if the coming number is smaller than 4 million
if (x [-2] + x [-1]) % 2 == 0: # Check if the number is even
even_sum += (x [-2] + x [-1])
x.append (x [-2] + x [-1]) # Compose the Fibonacci sequence
print (even_sum)
Although it's hard to believe that a question with 17 answers needs yet another, nearly all previous answers have problems in my view: first, they use the modulus operator (%) aka division to solve an addition problem; second, they calculate all the numbers in the sequence and toss the odd ones; finally, many of them look like C programs, using little of Python's advantages.
Since we know that every third number of the Fibonacci sequence is even, we can generate every third number starting from 2 and sum the result:
def generate_even_fibonacci(limit):
previous, current = 0, 2
while current < limit:
yield current
previous, current = current, current * 4 + previous
print(sum(generate_even_fibonacci(4_000_000)))
OUTPUT
> python3 test.py
4613732
>
So much code for such a simple series. It can be easily shown that f(i+3) = f(i-3) + 4*f(i) so you can simply start from 0,2 which are f(0),f(3) and progress directly through the even values striding by 3 as you would for the normal series:
s,a,b = 0,0,2
while a <= 4000000: s,a,b = s+a,b,a+4*b
print(s)
I solved it this way:
list=[1, 2]
total =2
while total< 4000000:
list.append(list[-1]+list[-2])
if list[-1] % 2 ==0:
total += list[-1]
print(total)
long sum = 2;
int start = 1;
int second = 2;
int newValue = 0;
do{
newValue = start + second;
if (newValue % 2 == 0) {
sum += newValue;
}
start = second;
second = newValue;
} while (newValue < 4000000);
System.out.println("Finding the totoal sum of :" + (sum));`enter code here`
The first mistake was you messed the Fibonacci sequence and started with 0 and 1 instead of 1 and 2. The sum should therefore be initialized to 2
#!/usr/bin/python2
firstNum, lastNum = 1, 2
n = 0
sum = 2 # Initialize sum to 2 since 2 is already even
maxRange = input("Enter the final number")
max = int(maxRange)
while n < max:
n = firstNum + lastNum
firstNum = lastNum
lastNum = n
if n % 2 == 0:
sum = sum + n
print(sum)
I did it this way:)
It works completely fine:)
n = int(input())
f = [0, 1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
sum = 0
for i in f:
if i>n:
break
elif i % 2 == 0:
sum += i
print(sum)
There are many great answers here. Nobody's posted a recursive solution so here's one of those in C
#include <stdio.h>
int filt(int n){
return ( n % 2 == 0);
}
int fib_func(int n0, int n1, int acc){
if (n0 + n1 > 4000000)
return acc;
else
return fib_func(n1, n0+n1, acc + filt(n0+n1)*(n0+n1));
}
int main(int argc, char* argv){
printf("%d\n", fib_func(0,1,0));
return 0;
}
This is the python implementation and works perfectly.
from math import pow
sum=0
summation=0
first,second=1,2
summation+=second
print first,second,
while sum < 4*math.pow(10,6):
sum=first+second
first=second
second=sum
#i+=1
if sum > 4*math.pow(10,6):
break
elif sum%2==0:
summation+=sum
print "The final summation is %d" %(summation)
problem in your code basicly related with looping style and checking condition timing. with below algorithm coded in java you can find (second + first) < 4000000 condition check and it brings you correct ( which less than 4000000) result, have a nice coding...
int first = 0, second = 1, pivot = 0;
do {
if ((second + first) < 4000000) { // this is the point which makes your solution correct
pivot = second + first;
first = second;
second = pivot;
System.out.println(pivot);
} else {
break;
}
} while (true);

Categories