Boolean expressions: function not returning expected output - python-3.x

Question:
Write a function should_shutdown(battery_level, time_on) which returns True if the battery level is less than 4.8 except when the time_on is less than 60, in which case the function returns True only if the battery level is less than 4.7. In all other situations the function returns False.
def should_shutdown(battery_level, time_on):
if battery_level < 4.8:
if time_on < 60:
return False
else:
return True
else:
if battery_level < 4.7:
return True
else:
return False
Testings:
should_shutdown(4.69, 50) Evaluates to: 'False'. Should return "True"
should_shutdown(5, 10) Evaluates to: False
should_shutdown(4.74, 90) Evaluates to: True
should_shutdown(4.74, 50) Evaluates to: False
should_shutdown(4.7, 50) Evaluates to: False
should_shutdown(4.75, 60) Evaluates to: True
should_shutdown(4.75, 59) Evaluates to: False
The first test is not returning the expected output by the quiz server. i don't understand the question very much so that's why I've copy pasted it.

Note that:
When battery_level < 4.7, the function should always return True.
When battery_level < 4.8 and time_on is not less than 60, the function should also return True.
Putting these two together yields:
def should_shutdown(battery_level, time_on):
return (battery_level < 4.7) or (battery_level < 4.8 and time_on >= 60)

def should_shutdown(battery_level, time_on):
if battery_level < 4.8:
return (time_on >= 60) or (time_on < 60 and battery_level < 4.7)
return False
This should be the function for the above question

Related

How to create a perfect number function using lists

My perfect number function is not working as intended :(. It prints false even though it should print true :(
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
You have put the if-else statement inside your for loop. It should be outside the for loop. Then, your code will work correctly.

Exercise in python is returning None

I need to write a recursive function that receives a list and a target element and returns True if the element is in the list and False, otherwise.
EXAMPLES:
busca ([1,2,3], 2) -> returns True
busca ([], 49) -> returns False
I can't use Python's "x in list" command.
I've developed code, but it returns None for some cases. For others, it works correctly.
def busca(lista, alvo):
if len(lista) == 0:
return False
if alvo == lista[0]:
return True
if len(lista) == 1:
return False
else:
nova = lista[1:]
busca(nova, alvo)
# busca([3, 2, 1], 3)
Your function returns None when it ends in the following condition:
else:
nova = lista[1:]
busca(nova, alvo) # even when this execution return True/False it's not returned by calling function
Did you mean?
else:
nova = lista[1:]
return busca(nova, alvo)
I don't understand why you return False when the length of the list is equal to 1. I mean
2 in [2] => True
despite
len([2]) => 1
and:
busca([2], 2) => True
This makes more sense to me:
def busca(lst, tgt):
if len(lst) !=0:
if lst[0] == tgt:
return True
else:
return busca(lst[1:], tgt)
else:
return False
Can you explain?

Recursive palindrome check - having issues when recalling the function

The problem is simple, check if palindrome or not using recursion. They also provided a template so I can't change that.
The template:
def isPalindrome(s): # Wrapper function
def isPalindromeRec(s,low,high):
""" Recursive function which checks if substring s[low ... high] is palindrome
returns a True/False value"""
n = len(s)
return isPalindromeRec(s,0,n-1)
I am nearly there but I think I am having trouble understanding how recursion exactly works. (especially how the values changes in the recursion)
My code:
def isPalindrome(s): # Wrapper function
def isPalindromeRec(s,low,high):
if len(s)<=1:
return True
else:
if s[0]==s[len(s)-1]:
return isPalindromeRec(s[low+1:high],low+1,high-1)
else:
return False
n = len(s)
return isPalindromeRec(s,0,n-1)
print(isPalindrome("anna"))
print(isPalindrome("civic"))
print(isPalindrome("a"))
print(isPalindrome("tx1aa1xt"))
print(isPalindrome(""))
print(isPalindrome("Civic"))
print(isPalindrome("ab"))
this is the output:
runfile('/Users/Rayan/Desktop/AUB Spring 2019/EECE 230 /HW/Homework 7/Problem2.py', wdir='/Users/Rayan/Desktop/AUB Spring 2019/EECE 230 /HW/Homework 7')
True
True
True
False
True
False
False
the first false should be True.
Thank you for your help!
Rewrote it:
def isPalindrome(s):
def isPalindromeRec(s,low,high):
if (low == high):
return True
if (s[low] != s[high]) :
return False
if (low < high + 1) :
return isPalindromeRec(s, low + 1, high - 1);
return True
n = len(s)
if (n == 0) :
return True
return isPalindromeRec(s, 0, n - 1);
print(isPalindrome("anna"))
print(isPalindrome("civic"))
print(isPalindrome("a"))
print(isPalindrome("tx1aa1xt"))
print(isPalindrome(""))
print(isPalindrome("Civic"))
print(isPalindrome("ab"))
output:
True
True
True
True
True
False
False

Write a Python function squareprime(l)

Write a Python function squareprime(l) that takes a non-empty list of integers and returns True if the elements of l alternate between perfect squares and prime numbers, and returns False otherwise. Note that the alternating sequence of squares and primes may begin with a square or with a prime.
Here are some examples to show how your function should work.
>>> primesquare([4])
True
>>> primesquare([4,5,16,101,64])
True
>>> primesquare([5,16,101,36,27])
False
Function prime_checker checks if a number is prime or not.
Function is_square checks if a number is prefect_square or not.
If the number at index 0 is square, then the chain is like [square, prime, square...]
else the sequence goes like [prime, square, prime, square..]
If the input sequence is not either of the two, then it is not a valid sequence and it will return False.
import math
def prime_checker(num):
flag = True
if num == 2:
return True
elif num < 2:
return False
else:
for i in range(2, int(num/2)):
if num % i == 0:
flag = False
break
return flag
def is_square(integer):
if integer == 0:
return false
root = math.sqrt(integer)
if int(root + 0.5) ** 2 == integer:
return True
return False`
def primesquare(list_nums):
if len(list_nums) == 0:
return False
if len(list_nums) == 1:
if (is_square(list_nums[0]) or prime_checker(list_nums[0])):
return True
else:
return False
else:
flag = True
if is_square(list_nums[0]):
check_for = 'prime'
elif prime_checker(list_nums[0]):
check_for = 'square'
else:
return False
for i in range(1,len(list_nums)):
if (check_for == 'prime' and prime_checker(list_nums[i])):
check_for = 'square'
elif (check_for == 'square' and is_square(list_nums[i])):
check_for = 'prime'
else:
flag = False
break
if flag:
return True
else:
return False
Update:
As the element at the 0th index has already been checked, we are not concerned about that number anymore. Hence, if the 0th element is a prime number, then the sequence will be [prime, square, prime, square,...].
If it is a perfect square, then the sequence will be [square, prime, square, prime...].
If it is neither of the two, then it is not a valid sequence and hence, false is returned.
Now, if the first number was either of the two, and the length of the list is greater than 1, then we will iterate over the remaining elements and check if they are similar to what we expected, but changing the value of check_for variable.
If the value of check_for is prime and the value that we encountered is also prime, then we know that the next number of the sequence should be a square number for the sequence to be a valid sequence. The similar thing happens when a square number is encountered.
from math import sqrt
def square(n):
if(sqrt(n) % 1 == 0):
return True
else:
return False
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def primesquare(list_nums):
if len(list_nums) == 0:
return False
if len(list_nums) == 1:
if (square(list_nums[0]) or isprime(list_nums[0])):
return True
else:
return False
else:
flag = True
if square(list_nums[0]):
check_for = 'prime'
elif isprime(list_nums[0]):
check_for = 'square'
else:
return False
for i in range(1,len(list_nums)):
if (check_for == 'prime' and isprime(list_nums[i])):
check_for = 'square'
elif (check_for == 'square' and square(list_nums[i])):
check_for = 'prime'
else:
flag = False
break
if flag:
return True
else:
return False
from math import sqrt
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def primesquare(l):
flag=0
if len(l)==1:
n=l[0]
if(sqrt(n)%1==0):
return True
else:
for i in range(0,len(l)):
if(sqrt(l[i])%1==0):
if(i==0):
if(isprime(l[i+1])==True):
flag=1
else:
if(isprime(l[i-1])==True):
if(isprime[i+1]==True):
flag=1
else:
flag=0
else:
flag=0
if(flag==0):
return False
else:
return True
from math import sqrt
def square(n):
if(sqrt(n) % 1 == 0):
return True
else:
return False
def isprime(n):
if (n == 1):
return(False)
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def squareprime(l):
s=l[0]
if(isprime(s)):
for i in range(0,len(l),2):
if(isprime(l[i])==False):
return False
for i in range(1,len(l),2):
if(square(l[i])==False):
return False
return True
elif(square(s)):
for i in range(0,len(l),2):
if(square(l[i])==False):
return False
for i in range(1,len(l),2):
if(isprime(l[i])==False):
return False
return True
else:
return False

Python how to check if it is a leap year with ==int

def leapyear(year):
if year/400 == int :
return False
if year/100 == int :
return False
if year/4 == int :
return True
hello I would like to know why my code doesn't work with it == to int because essentially its the same thing as using modulo and == to 0 this is just a question that came to me.
def check(n): if n > 200: return "large"
x = n/2 if x !=int: return "odd"
elif x==0 and n< 100: return "small"
elif x==0 and n>100: return "medium"
also how come the int works here
Your issue is that int is a type. If you try to compare a number to a type of object, which is what you are doing when you write if year/400 == int :, it will always return False, because these can never be the same.
A better way to check if year/400 is an integer would be:
if year%400 == 0:
return False
This is saying:
If the remainder of year/400 is equal to 0, return False, which is what you wanted.
Some other things are:
You should use elif instead of if in most cases. In this one, it doesn't matter, since the return statement terminates the execution of the function early, but you should still use it anyways. Otherwise, even when you have your final result, it will go through the rest of the if statements.
The other thing isn't related to your code, but your leap year criteria are incorrect. If the year is divisible by 4, then it's a leap year.
Unless the year is divisible by 100, then it's not.
Unless it's divisible by 400, then it is.
Improved code:
def leapyear(year):
if year%400 == 0:
return True
elif year%100 == 0:
return False
elif year%4 == 0:
return True
return False
In Python int is considered as Class. You can use type() function on a variable to get it's datatype in Python. So, to use your logic you have to rewrite your code as below:
def leapyear(year):
if type(year/400) == int :
return False
if type(year/100) == int :
return False
if type(year/4) == int :
return True
Note: I have just replicated your code by adding the type() function wherever necessary but it would be suggested to use if, elif and else rather than just if, as it will optimize your code.
You are checking direct number not its type. You should use....
if type(year/400) == int :
Then here is the conditional block.
elif type(year/100) == int:
Another Conditional check
elif type(year/4) == int:
Another conditional block.
And you also have a logical error please see the complete code given below.
So your function can be re-written with corrected logic as...
def leap_year(year):
if type(year/400) == int :
return False
elif type(year/100) == int:
return False
elif type(year/4) == int:
return False
else:
return True
This is the Complete code.
You should know output is FLOAT if use '/' .
e.g.
2020/400 -> 5.05
2020/100 -> 20.2
2020/4 -> 505
You have to change type like using int()
e.g.
2020/400 -> 5.05 int(2020/400) -> 5
2020/100 -> 20.2 int(2020/100) -> 20
2020/4 -> 505 int(2020/4) -> 505
from __future__ import division
import sys
time_year = int(sys.argv[1])
def leapyear(year):
if (year/400) == int(year/400) :
result = False
elif (year/100) == int(year/100) :
result = False
elif (year/4) == int(year/4) :
result = True
else :
result = 'something worg'
return result
a=leapyear(time_year)
print a
Hope can help you :)
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
You can check a year whether it is leap year or not by returning True or False
without using any libraries.
(lambda year : (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0))(2020)

Resources