0

I have been working on a problem that should return a list with all k-Primed numbers within a range, noted as (k, start, end).

The code I wrote until then is as follows:

def check_prime(x):
    c=2
    if x==2:
        return True
    if x==0 or x==1:
        return False
    while c<x:
        if x%c==0:
            return False
            break
        else:
            c+=1
    if c==x:
        return True

def prime_divs(x):
    aux=2
    nums=[]
    primes=[]
    i=0
    while aux<x/2:
        if x%aux==0:
            nums.append(aux)
        aux+=1
    while i<len(nums):
        if check_prime(nums[i])==True:
            primes.append(nums[i])
        i+=1
    return primes

def k_prime(x):
    k=0
    primes=prime_divs(x)
    if check_prime(x)==True:
        k=1
    else:
        while x!=1:
            if x%max(primes)==0:
                x=int(x/max(primes))    
                k+=1
            else:
                del primes[len(primes)-1]
    return k

def count_Kprimes(k_lim, start, end):
    i=start
    nums=[]
    while i<=end:
        if k_lim==k_prime(i):
            nums.append(i)
        i+=1
    return nums

After testing the last function, I get this error:

line 38, in k_prime
    if x%max(primes)==0:
ValueError: max() arg is an empty sequence

All the other functions before count_Kprimes work properly. Why is the last one leading to this error?

André Diniz
  • 11
  • 2
  • 4
  • 5
    `prime_divs()` must be returning an empty list. I can't be more specific because you didn't show us an example of how the code is being called. – John Gordon Jan 30 '18 at 02:23
  • Use `print(count_Kprimes(5,500,600))` – André Diniz Jan 30 '18 at 02:28
  • FYR, you have a lot of unnecessary statements and badly designed loops in your code. – DYZ Jan 30 '18 at 02:28
  • Thank you. Had forgotten to copy that part. – André Diniz Jan 30 '18 at 02:43
  • The problem is likely in this line: `del primes[len(primes)-1]` but it's not clear to me what you're trying to do, so I can't suggest how to fix it. You're deleting elements from the list `primes` but you're not checking to make sure that it's not empty. I'd also check out [this answer](https://stackoverflow.com/a/27946768/5858851). – pault Jan 30 '18 at 03:02
  • I am deleting the last element so the next number that I will use on `x=int(x/max(primes))` is the second biggest number on the list and so on. – André Diniz Jan 30 '18 at 03:18
  • Instead of deleting, why not `sort()` and iterate? – pault Jan 30 '18 at 11:24

1 Answers1

0

As John said, prime_divs must be returning an empty list.

If one of your testing scenarios is a range being provided with no k-prime numbers, then your function k_prime should test the length of primes and, if zero, route the thread somewhere else or raise an exception.

if not primes
    raise ValueError('No k-prime results found')

or

if not primes
    return 0
John R
  • 1,505
  • 10
  • 18