Question

I'm going through the CodingBat python problems and decided to make my own questions to understand things better.

I am trying to make a calculator that adds 5 numbers but excludes primes up to the 10th prime (29) (primes beyond that don't matter for simplicity) and any number to the right of a prime becomes doubled. If there is more than 1 prime, the primes are not added and the numbers to the right of the primes become multiplied by the number of primes to the to the left of the number.

For examples 7 + 4 + 11 + 4 + 4 + 4 = 8 + 12 + 12 + 12.

I am trying to do this in a very stupid and inefficient way (very new to programming) so looking at my code might be disturbing to you but hopefully you can help me make it better.

def Function(a,b,c,d,e):
    if a == 2 or a ==  3 or a == 5 or a == 7 or a == 11 or a == 13 or a == 17 or a == 19 or a == 23 or a == 29:
        return (b + c + d + e) * 2
    elif b == 2 or b ==  3 or b == 5 or b == 7 or b == 11 or b == 13 or b == 17 or b == 19 or b == 23 or b == 29:
        return a + ((c + d + e) * 2)
    elif c == 2 or c ==  3 or c == 5 or c == 7 or c == 11 or c == 13 or c == 17 or c == 19 or c == 23 or c == 29:
        return a + b + ((d + e) * 2)
    elif d == 2 or d ==  3 or d == 5 or d == 7 or d == 11 or d == 13 or d == 17 or d == 19 or d == 23 or d == 29:
        return a + b + c ((e) * 2)
    elif e == 2 or e ==  3 or e == 5 or e == 7 or e == 11 or e == 13 or e == 17 or e == 19 or e == 23 or e == 29:
        return a + b + c + d
.
.
.

You see where this is going... not going to be pretty.

How can I do it quickly? Is there a way I can do something like this:

if a == 2,3,5,7,11,17,19,23,29:
    return (b + c + d + e) * 2
Was it helpful?

Solution

one option is:

l = [2,3,5,7,11,17,19,23,29]

if a in l:
    return whatever

EDIT: I don't see much logic (or much to learn) from your exercise, but this is the solution:

primes = [2,3,5,7,11,17,19,23,29]

def sum_except(l):
    numprimes = 0
    for item in l:
        if item in primes:
            numprimes = numprimes + 1
    if numprimes==0:
        return sum(l)
    elif numprimes==1:
        for (i,item) in enumerate(l):
            if item in primes:
                if i<len(l)-1:
                    l[i+1] = 2*l[i+1]
                else:
                    l[0] = 2*l[0]
                break
        del l[i]
        print l
        return sum(l)
    else: #numprimes >= 2
        numprimes_sofar = 1
        dropped = []
        for (i,item) in enumerate(l):
            if item in primes:
                numprimes_sofar = numprimes_sofar + 1
                dropped.append(i)
            else:
                l[i] = l[i]*numprimes_sofar
        l = [x for (i,x) in enumerate(l) if i not in dropped]
        print l
        return sum(l)

print sum_except([7 , 4 , 11 , 4 , 4 , 4])
print sum_except([ 4 ,  4 ,5, 4 , 4])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top