How to create a perfect number function using lists - python-3.x

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.

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)

Checking if a number is palindrome

I have this code for checking if a number is a palindrome and for some reason it returns false for number=1 even though it is palindrome. Why is that? The code works for other cases such as 12321.
def palindrome_integer(number):
if number != int:
return False
elif str(number) == str(number)[::-1]:
return True
else:
return False
If you want to check if number is integer, you should use isistance.
def palindrome_integer(number):
if not isinstance(number, int):
return False
elif str(number) == str(number)[::-1]:
return True
else:
return False
The rest of your code seems to work fine.
One-liner:
return isinstance(n, int) and str(n) == str(n)[::-1]
Or slightly more contrived:
import re
x = str(n)
return re.match(r”\d+“, x) and x == x[::-1]
solution without string
def palindrome_integer(num):
copy = num
rev = 0
while num!= 0:
rev = rev*10+num%10
num = num//10
return rev == copy
def palindrome_integer(number):
return type(number) == int and str(number)[::-1] == str(number)
Don't hesitate to comment if you have problem in understanding the solution.

Resolving syntax error in line 7

Here is my code, where I get the syntax error:
def cube(number):
return number*number*number
def by_three(number):
if number % 3==0:
cube(number)
return number
else:
return False
Please note that indentation in Python is extremely important since it defines where blocks start and end. I guess your code should be:
def by_three(number):
if number % 3==0:
cube(number)
return number
else:
return False
This should work:
First, indent your code correctly.
def by_three(number):
if number % 3==0:
cube(number)
return number
else:
return False
For cube(number), you can use base**exponent
def cube(number):
return number**3
Alternatively, number^3 is the same as number*number*number, so
def cube(number):
return number*number*number
In addition to indentation, you might want to use mathematical order of precedence and indicating a * for the multiplication.
This works for me with python 3
#!/usr/local/bin/python3
def cube(number):
return (number * number * number)
def by_three(number):
if (number % 3) == 0:
cubed = cube(number)
return cubed
else:
return False
def main():
x = 3
output = '%d' % by_three(x)
print(output)
if __name__ == "__main__":
main()

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

Recursion: Palindromes [duplicate]

This question already has answers here:
Recursive Function palindrome in Python [closed]
(10 answers)
Closed 7 years ago.
So I have this code for detecting if a string is a palindrome (the same forward and backwards) and I'm not sure how to change it to a recursive program
def isPalindrome(string):
i = 0
j = len(string) - 1
k = 0
while (i <= j):
if string[j] != string[i]:
k = 1
else:
i += 1
j -= 1
if k == 0:
return True
else:
return False
def main():
print("This program tests if strings are palindromes.")
word = input("Enter a string: ")
while word != "quit" :
if isPalindrome(word) == True:
print(word,"is a palindrome.")
else:
print(word,"is not a palindrome.")
word = input("Enter a string: ")
main()
I'm really bad with recursions and I don't really understand them any help would be great. Thanks
Without Recursion:
Ideally you might not need recursion for palindrome detection. It can be done simply as below.
def is_palindrome(word):
if word=="".join(reversed(word)):
return True
return False
Another shorter method
def is_palindrome(word):
return word[::-1]==word
Using Recursions:
For some reasons if you still require recursion and comfortable with arrays and indices, Use it like this.
def is_palindrome(word, end=0, start=0):
if end == 0:
end = len(word)-1
if start >= end:
return True
if word[start] != word[end]:
return False
start = start+1
end = end-1
return is_palindrome(start, end, word)
word = 'ramar'
print (is_palindrome(word))
This will be more Pythonic way with recursion
def is_palindrome(word):
if not word:
return True
else:
return word[0]==word[-1] and is_palindrome(word[1:-1])

Resources