Why is this definition returning False instead of True? - python-3.7

I'm not understanding why it only checks the first number of the list. (Number 4 in has23([4, 3]) and it breaks. Why doesn't it go back up and check for number 3? I need this definition to return True.
I've been trying to separate it with an 'elif' in between but no luck.
def has23(nums):
for num in nums:
if num == 2 or num == 3:
return True
else:
return False
has23([4, 3])
No error message. It returns false instead of True.

The problem is the return statement, it will break the for loop and return false if the first value in the array doesn't match the condition.
The code should be something like this (I'm not a python coder)
def has23(nums):
for num in nums:
if num == 2 or num == 3:
return True
return False # This return statement should be after the for loop
has23([4, 3])

It is happening because whenever if or else condition is satisfied return is taking it out of def. So it is better to store the result in a list and return the list.
status=[]
def has23(nums):
for num in nums:
if num == 2 or num == 3: status.append(True);
else: status.append(False)
return status
print has23([4,3])

def has23(nums):
if 2 in nums or 2 in nums:
return True
else:
return False
has23([4, 2])
Hope this will work

Related

LEETCODE 202 HAPPY NUMBER (PYTHON)

class Solution:
def isHappy(self, n: int) -> bool:
visit = set()
def happy(n):
temp = n
n = 0
for i in str(temp):
n += int(i)**2
if n == 1:
return True
elif n in visit:
return False
else:
visit.add(n)
happy(n)
return happy(n)
hello guys.
input is 19
n will be 100 > 82 > 68 > 1
but result is False
can somebody explain why?
End of the happy() function:
else:
visit.add(n)
return happy(n)
You're discarding the result of calling happy(n), you need to return that value.

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

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))

Define if numbers in list are less than one in parameter - Scala

Write a function which at the input takes two parameters: a list of integers and a number.
The output returns a logical value.
The function returns "true" if all numbers in the list are smaller than the number given in the second parameter. Otherwise, the function returns "false".
My code:
def less [A](list:List[A], number:Int):Boolean =
if (list == Nil) false
else ((List.head < number) && less[A](list:List.tail, number:Int))
less(List(1, 2, 3, 4), 5)
less(List(6,1,2,3),6)
Error message in IntelliJ:
On line 3: error: value head is not a member of object List
else (List.head < number) && less[A](list:List.tail, number:Int) //2
^
On line 3: error: type tail is not a member of object List
My question: What should I improve in this code to have it working?
Seems an awful lot like home work...
Scala has a forall function that can test a predicate against all values in the collection and returns a Boolean.
def less(xs: List[Int], number: Int) = xs.forall(x => ???)
I think you want something like this:
def less (list:List[Int], number:Int):Boolean =
if (list == Nil) true
else ((list.head < number) && less(list.tail, number))
less(List(1, 2, 3, 4), 5)//true
less(List(6,1,2,3),6)//false
But you should just use forall like #Brian said

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)
}

Negate condition of an if-statement

If I want to do something like:
if (!(condition)) { }
What is the equivalent expression in Scala?
Does it looks like?
if (not(condition)) { }
For example, in C++, I can do:
bool condition = (x > 0)
if(!condition){ printf("x is not larger than zero") }
EDIT: I have realized that Scala can definitely do the same thing as I asked. Please go ahead and try it.
In Scala, you can check if two operands are equal (==) or not (!=) and it returns true if the condition is met, false if not (else).
if(x!=0) {
// if x is not equal to 0
} else {
// if x is equal to 0
}
By itself, ! is called the Logical NOT Operator.
Use it to reverse the logical state of its operand.
If a condition is true then Logical NOT operator will make it false.
if(!(condition)) {
// condition not met
} else {
// condition met
}
Where !(condition) can be
any (logical) expression
eg: x==0
-> !(x==0)
any (boolean like) value
eg: someStr.isEmpty
-> !someStr.isEmpty
no need redundant parentheses
if (! condition) { doSomething() }
condition in the above if expression can be any expression which evaluates to Boolean
for example
val condition = 5 % 2 == 0
if (! condition) { println("5 is odd") }
!= is equivalent to negation of ==
if (x != 0) <expression> else <another expression>
Scala REPL
scala> if (true) 1
res2: AnyVal = 1
scala> if (true) 1
res3: AnyVal = 1
scala> if (true) 1 else 2
res4: Int = 1