HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Print sum of numbers 1 to 200 except mults of 4 or 7 in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
200numbersprintmultspythonsumexcept

Problem

I had a question about using the modulus operator in Python and whether I have used it in a understandable way.

This is how I've written the script:

#sum numbers 1 to 200 except mults of 4 or 7
def main():
    sum = 0
    for x in range(200+1):
        if (x % 4 and x % 7): #is this bad???
            sum = sum + x
    print sum

if __name__ == '__main__':
    main()


So my questions are:

  • Should I spell out the modulo more clearly? ie if x % 4 != 0 and x % 7 != 0



  • Should I be approaching this in a very different way?

Solution

I think your use of % is fine, but that could be simplified to:

def main():
    print sum([i for i in range(201) if i % 4 and i % 7])

if __name__ == '__main__':
    main()


Edit: Since I had a bug in there, that's a pretty clear indication that the % is a tripwire. Instead, I'd probably do:

def divisible(numerator, denominator):
    return numerator % denominator == 0

def main():
    print sum(i for i in range(201) if not(divisible(i, 4) or divisible(i, 7)))

Code Snippets

def main():
    print sum([i for i in range(201) if i % 4 and i % 7])

if __name__ == '__main__':
    main()
def divisible(numerator, denominator):
    return numerator % denominator == 0

def main():
    print sum(i for i in range(201) if not(divisible(i, 4) or divisible(i, 7)))

Context

StackExchange Code Review Q#794, answer score: 10

Revisions (0)

No revisions yet.