Getting False with my Def, What is wrong with my code?
Question:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(n, n+1):
if n % i ==0:
nb.append(i)
sum1 = sum(nb) - nb[-1]
if sum1 > n:
return True
else:
return False
n = int(input("n:"))
print(richNumber(n))
I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100
With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False
Answers:
for i in (n, n+1)
Iterates over two numbers, n
and n + 1
, not all divisors. You need to use range
to iterate from 1
to n
for i in range(1, n + 1)
Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(1, n):
if n % i == 0:
nb.append(i)
sum1 = sum(nb)
if sum1 > n:
return True
else:
return False
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(n, n+1):
if n % i ==0:
nb.append(i)
sum1 = sum(nb) - nb[-1]
if sum1 > n:
return True
else:
return False
n = int(input("n:"))
print(richNumber(n))
I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100
With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False
for i in (n, n+1)
Iterates over two numbers, n
and n + 1
, not all divisors. You need to use range
to iterate from 1
to n
for i in range(1, n + 1)
Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(1, n):
if n % i == 0:
nb.append(i)
sum1 = sum(nb)
if sum1 > n:
return True
else:
return False