Exercise in python is returning None - python-3.x

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?

Related

Using Python3: how to get a boolean statement for numbers in a list being divisible by 3

I am running my code through an example set: [9,20,2,3]
I have been using the modulo operator (%) and my code is:
if index < len(the_list):
for m in the_list:
print(m)
if m % 3 == 0:
a = True
else:
a = False
return a
else:
return False
Args:
the_list (list): The input list
index (int): The index
Returns:
_type_: True: if the value is divisible by 3,
False: if the value is not divisible by 3,
False: if the index is invalid
One additional condition I must include is if the index position is larger than the length of the list to return False, but I believe I already have that properly integrated.
You can just use a list comprehension.
[(num%3 == 0) for num in myList]
here is a function that could help you :
def divisible_by_three(numbers):
for number in numbers:
if number % 3 == 0:
return True
else:
return False
This should work, just replace myList with your actual list
myList = [9,20,2,3]
finalList = []
for x in myList:
if x % 3 == 0:
finalList.append(True)
else:
finalList.append(False)
print(finalList)

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.

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: TypeError: 'int' object is not iterable

I'm tackling this following question:
Write a function is_fib(n) that returns True if n is a Fibonacci number, and False otherwise.
This is my code:
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in n:
if fib(a) == n:
result = True
break
else:
result = False
return result
Running this give rise to:
TypeError: 'int' object is not iterable.
I have been staring at the code for half an hour. Any help is greatly appreciated.
I think you mean
for a in range(n)
not
for a in n
As jozefg said you are missing range(n)
also notice that you need range(n+2) to cover all cases
def is_fib(n):
def fib(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
for a in range(n+2):
if fib(a) == n:
return True
return False
print(is_fib(3))
Firstly thanks to the two guys that helped me.
However, for Yoav's edition, python will run into an error when n is a really big number.
This is my new and improved version.
def is_fib(n):
if n < 0:
return False
else:
fib_0 = 0
fib_1 = 1
if n == fib_0 or n == fib_1:
return True
else:
for a in range(2,n+2):
fib = fib_0 + fib_1
fib_0,fib_1 = fib_1,fib
if fib >= n:
break
return fib == n

Resources