lundi 12 octobre 2020

Python return sum of list where 5 counts as double and the number after 5 counts quadruple

Given a list, return a sum of all the numbers in the list. However, if the number 5 appears in the list, you have to double it and the number that immediately comes after 5 needs to be quadrupled. So the following list [1, 2, 4, 1, 5, 2] should return 26 and [5, 1, 6] should return 20.

This is what I have so far:

def list_sum(x):
    if len(x) == 0:
        return 0
    else:
        sum2 = 0
        for i in x:
            if i == 5:
                sum2 += 5*2
            if x[i - 1] == 5:
                sum2 += i * 4
            else:
                sum2 += i
       
    return sum2

I can successfully do the first part of the problem where I multiply any 5s in the list by 2 but having trouble with the second part where I have to ask the code to quadruple the number that comes after 5. I was thinking x[i - 1] == 5 would basically be indexing the element that comes after 5 but after trying out a few print statements, it came to my attention that that line of code isn't really doing anything... So any tips?

Quick note: only using loops and if statements to solve this problem

Aucun commentaire:

Enregistrer un commentaire