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
Related
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.
yesterday I tried to made a simple library to convert HSL to RGB color space and vise-versa program in python.
but when I tried to run everything seems normal but sometimes on some input they miss by the one digit difference.
here is my code and result.
import re
# helper hsl functions
hslString=r'^hsl\((\d+)\,(\d+)%\,(\d+)%\)$'
hslaString=r'^hsla\((\d+)\,(\d+)%\,(\d+)%\,(0?\.?\d+)\)$'
wrongHslaString=r'^hsl\((\d+)\,(\d+)%\,(\d+)%\,(0?\.?\d+)\)$'
wrongHslString=r'^hsla\((\d+)\,(\d+)%\,(\d+)%\)$'
def hasall(obj,*args):
return False if False in [True if i in obj else False for i in args] else True
def ishsl(*hsl):
rl=len(hsl)
if rl==1:
arg=hsl[0]
if isinstance(arg,dict):
a=hasall(arg,'h','s','l','a') or hasall(arg,'h','s','l')
return [*arg.values()] if a else False
elif isinstance(arg,str):
values=re.findall(hslaString,arg) or re.findall(hslString,arg) or re.findall(wrongHslaString,arg) or re.findall(wrongHslString,arg)
return [float(v) for v in values[0]] if values else False
elif isinstance(arg,(list,tuple)):
return [*arg] if len(arg) in [3,4] else False
elif rl in [3,4]:
return [*hsl]
return False
def typehsl(*hsl):
check=ishsl(*hsl)
if check:
return 'hsla' if len(check)==4 else 'hsl'
else:
return False
# helper rgb functions
rgbString=r'^rgb\(\s*?(\-?\d+)\s*?\,\s*?(\-?\d+)\s*?\,\s*?(\-?\d+)\s*?\)$'
rgbaString=r'^rgba\(\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,(\-?0?\.?\d+)\)$'
wrongRgbaString=r'^rgba\(\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,\s*(\-?\d+)\)$'
wrongRgbString=r'^rgb\(\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,(\-?0?\.?\d+)\)$'
# sampleRgbString='rgb(150,150,252)'
# compiled=re.compile(rgbString).findall(sampleRgbString)
def hasall(obj,*args):
"""check if given object has all property name or not"""
value=False
for i in args:
if obj.get(i):
value=True
else:
value=False
return value
def getinorder(obj,*args):
all=hasall(obj,*args)
vals=[]
if all:
for i in args:
vals.append(obj.get(i))
return vals
def isrgb(*rgb):
rl=len(rgb)
if rl==1:
arg=rgb[0]
if isinstance(arg,dict):
a=hasall(arg,'r','g','b','a') or hasall(arg,'r','g','b')
values = getinorder(arg,'r','g','b','a') or getinorder(arg,'r','g','b')
return [int(v) for v in values] if a else False
elif isinstance(arg,str):
values=re.findall(rgbaString,arg) or re.findall(rgbString,arg) or re.findall(wrongRgbaString,arg) or re.findall(wrongRgbString,arg)
return [int(v) for v in values[0]] if values else False
elif isinstance(arg,(list,tuple)):
return [*arg] if len(arg) in [3,4] else False
elif rl in [3,4]:
return [*rgb]
return False
def typergb(*rgb):
check=isrgb(*rgb)
if check:
rl=len(check)
return 'rgba' if rl==4 else 'rgb' if rl==3 else False
def RGB2HSL(*rgb):
check=isrgb(*rgb)
if check:
h=s=l=0
tr=typergb(check)
A=float(check.pop()) if tr=='rgba' else False
check=[0 if v<0 else 255 if v>255 else v for v in check]
r,g,b=[int(v)/255 for v in check]
maxi,mini=max(r,g,b),min(r,g,b)
l=(maxi+mini)/2
if maxi==mini:
h=s=0
return [h,s,l,A] if tr=='rgba' else [h,s,l]
else:
s=(maxi-mini)/(1-abs(2*l-1))
if maxi==r:
h=((g-b)/(maxi-mini))%6
if maxi==g:
h=(b-r)/(maxi-mini)+2
if maxi==b:
h=(r-g)/(maxi-mini)+4
h=cr(h*60)
return [h,s,l,A] if tr=='rgba' else [h,s,l]
else:return False
def cr(n):
from math import ceil,floor
return floor(n) if (n-floor(n))<0.5 else ceil(n)
def HSL2RGB(*hsl):
check=ishsl(*hsl)
if check:
r=g=b=0
tl=typehsl(check)
A=float(check.pop()) if len(check)==4 else False
h,s,l=[v for v in check]
s,l=s if s<=1 else s/100,l if l<=1 else l/100
c=(1-abs((2*l)-1))*s
x=c*(1-abs((h/60)%2-1))
m=l-(c/2)
if h>=0 and h<60:
r,g,b=c,x,0
elif h>=60 and h<120:
r,g,b=x,c,0
elif h>=120 and h<180:
r,g,b=0,c,x
elif h>=180 and h<240:
r,g,b=0,x,c
elif h>=240 and h<300:
r,g,b=x,0,c
elif h>=300 and h<360:
r,g,b=c,0,x
R,G,B=(r+m)*255,(g+m)*255,(b+m)*255
R,G,B=[cr(v) for v in [R,G,B]]
return [R,G,B,A] if tl=='hsla' else [R,G,B]
print(HSL2RGB(RGB2HSL(6,50,90)))
I think the result should be [6,50,90] but it print [6,49,90]. Why? how can I solve this?
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?
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
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