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'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,
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
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
I have joined the dark side and have decided to learn Python. I am using Python 3.
Here is a straight forward way using C++ to read two integers at a time until both of them are 0:
int x, y;
while (cin >> x >> y && (x != 0 || y != 0)) {
//x or y can be 0 but not both
}
//now x = 0 and y = 0 OR can't find two int's
It's easy, simple and works 99.999% of the time. I have the following in Python but it doesn't seem Pythonic to me. Also, this is doomed to fail on some inputs (i.e. if the int's are on 2 different lines)
while True:
line = sys.stdin.readline()
values = [int(i) for i in line.split()]
if (values[0] == 0 and values[1] == 0):
break
x = values[0]
y = values[1]
print(x + y)
print("both are 0 or couldn't find 2 int's")
Can someone please tell me the cleanest, most Pythonic way to read two int's at a time until both are 0 using Python 3?
Try this out. My simple tests seem to work. It will throw an error if you only type one number, though.
while True:
x,y = map(int, input().split())
if x == 0 and y == 0:
break
print(x + y)
print("both are 0 or couldn't find 2 int's")
This version correctly handles the "couldn't find 2 int's" case.
while True:
line = input()
data = line.split()
if len(data) < 2:
break
x,y = map(int, data)
if x == 0 and y == 0:
break
print(x + y)
print("both are 0 or couldn't find 2 int's")
With Python 2.x you'll want to use raw_input whereas for Python 3.x you use simply input
inputs = raw_input("Enter two numbers")
values = [int(x) for x in inputs.split()]
The example code is almost reasonable except that it could unpack the variables immediately and use exception handling to deal with errors
import sys
while True:
try:
x,y = [int(i) for i in sys.stdin.readline().split()]
if x == 0 and y == 0:
break
print(x+y)
except ValueError:
# didn't have 2 values or one of them isn't an int
break
print("both are 0 or couldn't find 2 int's")
More generally, you can apply a typelist to a sequence of whitespace-separated values:
>>> types = (int, str, int, float)
>>> inputs = '1234 "WESTA" 4 1.05'
>>> values = inputs.split()
>>> (type(value) for (type, value) in zip(types, values)
(1234, 'WESTA', 4, 1.05)
You could also trust the interpreter to create the correct type with ast.literal_eval
>>> map(literal_eval, values)
[1234, 'WESTA', 4, 1.05]