[Solved] Python — divisibility and count [closed]


Do you mean something along these lines?

def count(n):
    occurrences = 0
    for i in range(n, 0, -1):  # i -> n, n-1, n-2, ... 3, 2, 1
        occurrences += i//2    # add whole number of 2's in this value of i
    return occurrences

print(count(10))  # 25
print(count(9))   # 20

If what that does is correct, it can be optimized and shorted to just:

def count(n):
    return sum(i//2 for i in range(n, 0, -1))

Which applies the built-insum()function to agenerator expression.

Therange(n, 0, -1)is an iterator that produces all the numbers fromnto1backwards — which I used since that’s how you described what you wanted. Since doing it in that order doesn’t really matter, it would probably be better (simpler) to just userange(1, n+1)which produces the sequence in ascending order (1, 2, 3, ... n-2, n-1, n).

4

solved Python — divisibility and count [closed]