trying to solve palindrome integer in python 3 code is working but giving wrong output - numbers

enter code here''' class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
lst = list(x)
str_val = []
count = len(lst)
for i in range(len(lst)):
str_val.append(lst[count-1])
count -= 1
value = [str(i) for i in str_val]
res = int("".join(value))
if int(res) == x:
return True
else:
return False
'''
trying to solve palindrome integer in python 3 code is working but giving wrong output.

If you're just trying to check for integers only, you can try the below code. It's a two pointer approach.
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if len(x) < 2: return True
s, e = 0, len(x)-1
while s < e:
if x[s] != x[e]: return False
s += 1
e -= 1
return True
You can also do this in one line in python to check if a number (as a string) and it's reverse is same or not.
str(x) == str(x)[::-1]

The reason your results are not as expected is due to the type change that you make in the first line of your function.
x = str(x)
It is necessary to convert x into a string so that you can iterate over it and put it into a list for your second line of code:
lst = list(x)
but by re-assigning that back to x, you get an x at the end of the function call that is not equal to the int(res) when you make the final comparison to get your boolean:
if int(res) == x:
A simple solution is to just not assign the temporary string that is created from the parameter x back to itself, and rather to just merge the first and second lines of your function into one:
lst = list(str(x))

Related

asInstanceOf err in Scala

why it is give me an error
I already write the code correctly
code :
x = 1 //true
val x1 = x.asInstanceOf[Boolean]
if (x1) {
println(s"Hello, $x1")
}
The problem is that the comment on this line is not correct:
x = 1 // true
1 is not true because 1 is of type Int and true is of type Boolean. Scala is strongly typed so it doesn't automatically convert between these two types, unlike languages such as C and Python.
To fix it, just convert the Int to a Boolean like this:
val x1 = x != 0

unable to understand the else if statement in scala code below

I am pretty new to Scala and was going through the docs when I came across this code in the below link
https://www.scala-lang.org/old/node/135.html
def filter(xs: List[Int], p: Int => Boolean): List[Int] =
if (xs.isEmpty) xs
else if (p(xs.head)) xs.head :: filter(xs.tail, p)
else filter(xs.tail, p)
Can anyone please tell me what the else if line does?
The second parameter to the filter function p is a function that takes Int as a parameter and returns Boolean.
So, in the else if, it is calling the function p with xs.head which is first element from xs which is Int. If it returns true, it adds an element at the beginning of a list and returns a list with the added element.
To test this -
You can try two variations of p one which returns true when number is even and one which returns true when the number is odd and see what it prints.
val output = filter(List(1,2,3,4), (p) => p % 2 != 0);
print(output) // prints `List(1, 3)`
val output = filter(List(1,2,3,4), (p) => p % 2 == 0);
print(output) // prints `List(2, 4)`
Hope this helps!

Scala : How to check every single digit of a number is even or odd?

def digitaleven(n:Int):Boolean = {
if (n%2==0){
return true
}
else {
return false
}
}
this is what i got so far but it only works for single digit number, how do i make it work for a number which has random digits using recursion (if else)?
f.e.: i know how to check every digit for even or odd, n%2 for last digit, n/10%2 for secound last and so on... but i have difficulties to implement it
thanks for helping
forall
Use forall to check if every digit is even (You need not use map to transform. Do transformation inside forall).
def isAllEven(n: Int) = s"$n".forall(_.asDigit % 2 == 0)
Recursive (tail recursive)
def isAllEven(n: Int): Boolean = {
val digits = s"$n".toList
def helper(rest: List[Char]): Boolean = rest match {
case Nil => true
case x :: xs =>
if (x.asDigit % 2 == 0)
helper(xs)
else false
}
helper(digits)
}
The above function converts the number into its string representation and then converts the string to list of chars and then check if each char is even digit.
Your code can be written like below but it will not check if each digit is even.
def digitaleven(n:Int): Boolean = n % 2 == 0
Your code checks if the number is even or not. But it will not check if each digit in the number is even. In order to do that use above recursive function.
A one-liner.
def digitaleven(n:Int):Boolean =
n == 0 || n % 2 == 0 && digitaleven(n/10)
What about this:
def allDigitsEven(number:Int) = {
number.toString.map(_.asDigit).forall(_%2==0)
}
First you need to identify the base case for which you are sure that all the digits are even and return true. Then if you're not sure about all digits but the current digit is even you enter the recursive case to check that all other digits are also even.
It's perfectly possible using only those formulas of yours.
Another way:
// Using explicit recursion and pattern matching
def digitaleven(n:Int):Boolean = n match {
case 0 => true
case n => ((n % 10) % 2 ==0) && digitaleven(n / 10)
}

Converting continuously updating values of C loop in scala

I have one c code.
I want to convert it in scala.
Here is the c code.
I am not getting the part How can I use continues updated values in scala?
Is it possible to use foldLeft in this case?
int value=9999,i,j,length=10;
A and B are some 2D Integer array and some value is changing for every element. Its not fixed for entire loop.
for(i=0;i<=5;i++){
for(j=0;j<=5;j++){
if(A[i][j]==value && B[i][j]==value)
length=length+44;
else if(A[i][j]!=value && B[i][j]==value)
if(length< 'Some value')
length=length+11
else
if(length< 'Some value')
length=length+22
}
}
How can I do this?
Equivalent code might go something like this:
def someValue(x: Int, y: Int): Int = ... // I'm treating this as some function that takes the array values and returns an Int
val A: Array[Array[Int]] = ...
val B: Array[Array[Int]] = ...
val Value = 9999 // Capitalised, so it can be used directly in case matches
( for {
i <- 0 to 5
j <- 0 to 5
} yield ((i, j)) ).foldLeft(10){ case (length, (i,j)) => (A(i)(j), B(i)(j)) match {
case (Value, Value) => length + 44
case (other, Value) if other != Value =>
if (length < someValue(A(i)(j), B(i)(j))) {
length + 11
} else {
length
}
case _ => length
}
}
I left off the second comparison of length against someValue because it isn't clear how this code could ever be reached in the C code above.

Scala - Type Mismatch Found Unit : required Array[Int]

Why does the method give a compile error in NetBeans
( error in question -- Type Mismatch Found Unit : required Array[Int] )
def createArray(n:Int):Array[Int] =
{
var x = new Array[Int](n)
for(i <- 0 to x.length-1)
x(i) = scala.util.Random.nextInt(n)
}
I know that if there was a if clause - and no else clause - then why we get the type mismatch.
However, I am unable to resolve this above error - unless I add this line
return x
The error is not happening because the compiler thinks what happens if n <= 0
I tried writing the function with n = 10 as hardcoded
Thoughts ?
Your for comprehension will be converted into something like:
0.to(x.length - 1).foreach(i => x(i) = scala.util.Random.nextInt(i))
Since foreach returns (), the result of your for comprehension is (), so the result of the entire function is () since it is the last expression.
You need to return the array x instead:
for(i <- 0 to x.length-1)
x(i) = scala.util.Random.nextInt(n)
x
Yet another one,
def createArray(n: Int): Array[Int] = Array.fill(n) { scala.util.Random.nextInt(n) }
Then, for instance
val x: Array[Int] = createArray(10)
You could do something cleaner in my own opinion using yield :
def createArray(n:Int):Array[Int] =
(for(i: Int <- 0 to n-1) yield scala.util.Random.nextInt(n)).toArray
This will make a "one lined function"