0

the program needs to return true if the factors of n other than n sum up to n. i need to use the function name during runtime. when i input

factors(45) 

it shows that there is an unexpexted token error. please check what is wrong with the program.

def factors(n):#unexpected token error
 factorlist = []
 for i in range(1,n):
  if n%i == 0:
    factorlist = factorlist + [i]
 return(factorlist)
def perfect(n):
 if sum(factorlist) == n:
  return(True)
 else :
  return(False)
  • `factorlist` not referenced in `perfect(n)` function. May be you wanted `factorlist = factors(n)` ? – Tushar Gupta Aug 06 '17 at 09:27
  • can u do the correction in the program. i am not able to get it. im just beginning to learn python. please – Benetha Thambi Aug 06 '17 at 09:37
  • `45` is not perfect number . so, it returns `False`. – Md. Rezwanul Haque Aug 06 '17 at 09:40
  • People have answered below. Use one the answers ;) – Tushar Gupta Aug 06 '17 at 09:44
  • FWIW, this approach is ok to test if small number are perfect, but it gets very slow if you want to search for larger ones. If you want to generate even perfect numbers, you can do that fairly quickly via their relationship with Mersenne primes (see [here](https://stackoverflow.com/a/40631767/4014959)). If you want to see if any odd perfect numbers exist, then (as far as we know) you have to add the factors, but there are ways to make it more efficient than a simple brute-force search. – PM 2Ring Aug 06 '17 at 09:50
  • are you trying to give input on the command line or in the code? – Pravitha V Aug 06 '17 at 09:53
  • like, during execution – Benetha Thambi Aug 06 '17 at 09:56
  • 1
    Are you using Python 3? If so, to read a number from the user at runtime you can do `n = int(input('Enter number '))`. – PM 2Ring Aug 06 '17 at 10:01

2 Answers2

1

You do not call factors(n) into the perfect(n) function. So, you have to use factorlist = factors(n) into the perfect(n) function.

and then try this way :

def factors(n):
  factorlist = []
  for i in range(1, n):
    if n % i == 0:
      factorlist = factorlist + [i]
  return (factorlist)


def perfect(n):
  factorlist = factors(n)  # use this line
  if sum(factorlist) == n:
    return (True)
  else:
    return (False)

print(perfect(45)) # Ouput : False
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
0

Try :

def factors(n):
    factorlist = []
    for i in range(1,n):
        if n%i == 0:
            factorlist = factorlist + [i]
    print factorlist
    return factorlist

def perfect(n):
    factorlist = factors(n)
    if sum(factorlist) == n:
        return True
    else :
        return False

n = int(raw_input('Enter the number: '))
print(perfect(n))

Output:

enter image description here

Pravitha V
  • 3,308
  • 4
  • 33
  • 51