Python Problem with exercise

Asked

Viewed 56 times

-1

I’m having a hard time doing isPerfect(x) work. I’ve tried some other options but I don’t know if my logical reasoning is wrong.

Perfect number

A number is said to be Perfect if it is Equal to the sum of all its factors (for obvious reasons the list of factors being considered does not include the number itself). 6 = 3 + 2 + 1, Hence 6 is Perfect.)

    def getFactors(x):

    num_factors = []
    
    for i in range(1, x +1):
        if (x % i == 0):
            num_factors.append(i)

    return num_factors




    def isPrime(x):
    return len(getFactors(x)) == 2

    def isComposite(x):
    return False if isPrime(x) else True

    def isPerfect(x):
    return isPerfect(x)
    if sum(getFactors(x)) == (getFactors(x))
    else:
        return False

    def main():

    playing = True
    while playing == True:

        num_input = input('Give me a number from 1 to 10000.  Type -1 to exit. ')

        try:
            num = int(num_input)

            if (num == -1):
                playing = False
                continue

            if (num <= 0 or num > 10000):
                continue

            factors = getFactors(num)
            print("The factors of", num, "are", factors)

            if isPrime(num):
                print(str(num) + ' is prime')
            if isComposite(num):
                print(str(num) + ' is composite')
            if isPerfect(num):
                print(str(num) + ' is perfect')

        except ValueError:
            print('Sorry, the input is not an int.  Please try again.')
            
#This will automatically run the main function in your program
#Don't change this
    if __name__ == '__main__':
    main()
  • Welcome to Sopt. Your question is a little vague, which part isn’t working? You can edit your question and add more information.

3 answers

2

There are 2 basic problems in your logic:

  1. Its function getFactors(x) traverses the interval [1, x]. Which works well for your cousin implementation, although it goes through more elements than is really necessary. However, you are reusing this function to see if the number is Perfect, which will never calculate right, because the very number should be excluded, according to the definition you put in the statement: (for obvious reasons the list of factors being considered does not include the number itself).

  2. The function that checks whether it is Perfect is poorly done: besides going into infinite loop, lack : after the if and the command that would be executed if the condition were true. And that condition will never be true because you’re comparing a whole to a list.

Keeping in mind what I pointed out above, you could rewrite the function like this:

def isPerfect(x):
    return sum(getFactors(x)) == x * 2

Note the execution for x = 6: getFactors(6) = [1, 2, 3, 6]. sum([1, 2, 3, 6]) = 12 (Because you entered your own number in the list of factors).

To solve this, just compare with double the number.

NOTE: You could rewrite isComposite(x)to be more readable too:

def isComposite(x):
    return not isPrime(x)

0

Good afternoon. Follow the changes that will make your code work.

What were the mistakes?

1 - the isPerfec function kept returning itself, when it should return True

2 - isPerfect return happened before entering if condition

3 - I put getFactors up to half. To solve the issue of isPerfect does not need to pass half the number typed.

def getFactors(x):

    num_factors = []
    max = int(x/2) + 1
    for i in range(1, max):
        if (x % i == 0):
            num_factors.append(i)
    return num_factors

def isPrime(x):
    return len(getFactors(x)) == 2

def isComposite(x):
    return False if isPrime(x) else True

def isPerfect(x):
    if sum(getFactors(x)) == ((x)):
        return True
    else:
        return False

def main():

    playing = True

    while playing == True:

        num_input = input('Give me a number from 1 to 10000.  Type -1 to exit. ')

        try:
            num = int(num_input)

            if (num == -1):
                playing = False
                continue

            if (num <= 0 or num > 10000):
                continue

            factors = getFactors(num)
            print("The factors of", num, "are", factors)

            if isPrime(num):
                print(str(num) + ' is prime')
            if isComposite(num):
                print(str(num) + ' is composite')
            if isPerfect(num):
                print(str(num) + ' is perfect')

        except ValueError:
            print('Sorry, the input is not an int.  Please try again.')

main()

0

I would try this way, because there is a lot of redundancy in the if’s some identations were wrong, because in Python 3, identation is extremely important, because if a genuine code is a simple code and the smaller, the better. See more in: https://docs.python.org/pt-br/3/library/math.html

def getFactors(x):
    num_factors = []
    max = int(x / 2) + 1
    for i in range(1, max):
        if x % i == 0:
            num_factors.append(i)
    return num_factors


def isPrime(x):
    return len(getFactors(x)) == 2


def isComposite(x):
    return False if isPrime(x) else True


def isPerfect(x):
    if sum(getFactors(x)) == x:
        return True
    else:
        return False


def main():
    playing = True

    while playing:

        num_input = input('Give me a number from 1 to 10000.  Type -1 to exit: ')

        try:
            num = int(num_input)

            if num == -1:
                playing = False
                continue

            if num <= 0 or num > 10000:
                continue

            factors = getFactors(num)
            print("The factors of", num, "are", factors)

            if isPrime(num):
                print(str(num) + ' is prime')
            if isComposite(num):
                print(str(num) + ' is composite')
            if isPerfect(num):
                print(str(num) + ' is perfect')

        except ValueError:
            print('Sorry, the input is not an int.  Please try again.')


if __name__ == '__main__':
    main()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.