1
votes

I am coding a program in python. I introduce an entire number and the program gives back to me the decomposition in prime factors of this number. For example 6 ---> 3, 2. Another example 16 --> 2, 2, 2, 2.

I am doing it with OOP. I have created a class (PrimeFactors) with 2 methods (is_prime and prime_factor_decomposition). The first method says wether the number is prime, and the second gives the decomposition back.

This is the code:

class PrimeFactors(object):
    def __init__(self, number):
        self.number = number

    def is_prime(self):
        n = self.number - 1
        a = 0
        loop = True

        if self.number == 1 or self.number == 2:
            loop = False

        while n >= 2 and loop:
            if self.number % n != 0:
                n -= 1
            else:
                a += 1
                loop = False
        return a == 0

    def prime_factor_decomposition(self): 
        factors = [] 
        n = self.number - 1
        loop = True

        if PrimeFactors.is_prime(self.number):
            factors.append(self.number)
            loop = False

        while n >= 2 and loop:
            if self.number % n == 0 and PrimeFactors.is_prime(n):
                factors.append(n)
                self.number = self.number / n
                if self.number % n == 0:
                    n += 1
            n -= 1
        return factors

s = PrimeFactors(37)
print(s.is_prime())

I am getting a mistake. I think it is something related to the method call. My question is, How can I call a method from another method if they both are from the same class?

3

3 Answers

6
votes

You need to use self. to call another method of the same class:

class Foo:
    def __init__(self):
        pass

    def method1(self):
        print('Method 1')

    def method2(self):
        print('Method 2')
        self.method1()
1
votes

Jkdc's answer is absolutely correct. I also wanted to note that your method calls are going to be problematic. You defined is_prime to take self as its only argument, but when you call it, you're passing in self.number or n.

If you need is_prime to work with arbitrary numbers, and not just whatever the class was initialized with, you should add an extra argument.

1
votes

Just a general advise: there are good (and FAST!) algorithms to check if a number is prime. your loop starts with n-1, thats highly inefficient. lets say the number is 1000000, so your algorithm starts with 999999, but the first even POSSIBLE number is the half of n! so instead i would go from 2 up to n/2:

for i in range(n/2):
    if self.number%i==0:
        return true
return false

i think even better for your purpose is to return not a boolean, but the number, which is found to be the divisor:

for i in range(n/2):
    if self.number%i==0:
        return i
return 0

then you can repeatedly call the method and will only get the prime numbers.