Prime factoriser raises an unexpected TypeError-py3

Viewed 48

I am making a function that prime factorises a number. However, instead of doing what it should, it raises a weird TypeError.

def isprime(num):
    if num > 1:
    # check for factors
       for i in range(2,num):
          if num%i==0:
              return False
              break
          else:
              return True
     else:
        return False
def primes(no):
   nolist=[]
   for a in range(1,(no+1)):
       if isprime(a)==True:
          nolist.append(a)
   return nolist
def factors(b):
   Lst=[]
   while True:
      for prime in primes(b):
          if b%prime==0:
              b=b/prime
              Lst.append(b)
              if b==1:
                 break
   return Lst
factors(6)

Raises weird TypeError:

Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
 
exec (open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 71, in <module>
File "<string>", line 64, in factors
File "<string>", line 58, in primes
TypeError: 'float' object cannot be interpreted as an integer

My (idiotic) logic tells me that 'float' object has nothing to do with my code. I just don't get it. Any correction to my code will be highly appreciated

1 Answers

Problems with your code

  • Prime number list not including 2. (isprime function is wrong)
  • You are calling primes function again and again. Not neccessary
  • When you divide b/prime it is returning float
  • You are appending b in prime factor list Lst instead of prime

Find Number is prime or not

def isprime(num):
  if num > 1:
    for i in range(2,num):
      if num%i==0:
          return False
    else:
        return False

FUll Code

def isprime(num):
  if num > 1:
  # check for factors
    for i in range(2,num):
      if num%i==0:
          return False
    else:
        return True

def primes(no):
   nolist=[]
   print(type(no))
   for a in range(1,(no+1)):
       if isprime(a)==True:
          nolist.append(a)
   return nolist
def factors(b):
   Lst=[]
   prime_nums = primes(b)
   while True:
      for prime in prime_nums:
          if b%prime==0:
              b=b//prime
              Lst.append(prime)
              break
      if b==1:
          break
   return Lst
print(factors(6))
Related