Home > Blockchain >  How to get the sum of a list of numbers excluding integers that are divisible by 3 and 7 with recurs
How to get the sum of a list of numbers excluding integers that are divisible by 3 and 7 with recurs

Time:09-22

I am trying to find the summation of integer in list with elements that are divisible by 3 or 7 excluded

def SumSkip37(numList,sum = 0):
    if numList:
        i = numList.pop()
        if i % 3 == 0 or i % 7 == 0:
            return sum
        else:
            sum  = i
            return SumSkip37(numList, sum=sum)



numList = [1, 3, 5, 7, 9]
print(f'The result is {SumSkip37(numList)}.')

Pls help me figure out

CodePudding user response:

You can update your code to:

def SumSkip37(numList, my_sum = 0): # avoid using sum
    if numList:
        i = numList.pop()
        if i % 3 == 0 or i % 7 == 0:
            return SumSkip37(numList, my_sum=my_sum) # pass the unchanged sum
        else:
            return SumSkip37(numList, my_sum=my_sum i) # pass the sum   i
    else:
        return my_sum

NB. I tried to stay as close as possible to the original, but you can simplify greatly!

To avoid mutating the input:

def SumSkip37(numList, my_sum = 0):
    if numList:
        if numList[0] % 3 != 0 and numList[0] % 7 != 0:
            my_sum  = numList[0]
        return SumSkip37(numList[1:], my_sum=my_sum)
    return my_sum
print(f'The result is {SumSkip37(numList)}.')

Also, recursion is overkill here, better use a short generator expression:

sum(i for i in numList if i%7!=0 and i%3!=0)

CodePudding user response:

On relatively clean way:

def SumSkip37(numList):
    if not numList:
        return 0
    head, *tail = numList
    return (head % 3 and head % 7)   SumSkip37(tail)

CodePudding user response:

You are on the right track. You just weren't iterating through the whole list:

def SumSkip37(numList, total=0):
    if numList:
        i = numList.pop()
        if i % 3 != 0 and i % 7 != 0:
            total  = i
        return SumSkip37(numList, total=total)
    return total

I flipped the comparison to remove the unnecessary else branch. It doesn't matter if the current number is divisible with 3 or 7 or not, you always want to continue the recursion until the list runs out.

CodePudding user response:

Without Recursive function:

def SumSkip37(list):
    sum = 0
    for i in list:
        if i % 3 == 0 or i % 7 == 0:
            continue
        else:
            sum  = i
    return sum

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(SumSkip37(list))

With Recursive Function:

def SumSkip37(lst):
    if len(lst) == 0:
        return 0
    else:
        if lst[0] % 3 == 0 or lst[0] % 7 == 0:
            return SumSkip37(lst[1:])
        else:
            return lst[0]   SumSkip37(lst[1:])

print(SumSkip37([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
  • Related