2

This is the problem description at checkIo -

"You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be (zero)."

The result is supposed to be this -

if __name__ == '__main__':
    assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30"
    assert checkio([1, 3, 5]) == 30, "(1+5)*5=30"
    assert checkio([6]) == 36, "(6)*6=36"
    assert checkio([]) == 0, "Empty"

This is what I came up with -

def checkio(array):
    total = sum(array[::2]) * array[-1]
    return total

It works okay with the first 3 results. The last one gives assertion error saying Index out of range. I am not able to get around this issue. There is a possibility that whole of my code is wrong. But since first three are success, I am not able to say whether it is.

Lastly, I don't understand what this is for -

if __name__ == '__main__':
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
Umm Maryam
  • 41
  • 1
  • 7

1 Answers1

2

You need to do this:

def checkio(array):
    if array:
        return sum(array[::2]) * array[-1] 
    else:
        return 0

Or you could get it to one line with:

def checkio(array):
    return sum(array[::2]) * array[-1] if array else 0

As for

if __name__ == '__main__'

I have a stellar answer here:

What does if __name__ == "__main__": do?

But the short course is that __main__ is the name of the top-level module namespace you're currently executing out of, and this code will only execute when it's in that top level module. Type __name__ into an interpreter, and it will return the same. Or in your module that you're executing, include:

print('__name__ is: ', __name__ )

And you'll see when you execute the module, it will print __main__.

Community
  • 1
  • 1
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331