Sum of the number of digits using Python/while loop

Asked 2 years ago, Updated 2 years ago, 102 views

Hello,

Store an arbitrary number in a variable as an variable Find the sum of each digit It's a problem of finding the sum of the numbers of digits that are greater than 2 and less than 8. (Arithmetic operators must be used.)

code = 12345678
sum = 0
while code:
    a = code%10
    if 2 < a <8:
        sum = a + sum
        code = code//10
    else:
        code = code//10
print(sum)

I solved it like above If you don't use an if statement and just use a while statement, I wonder what kind of logical structure you can solve.

python while-loop

2022-09-21 10:43

2 Answers

code = 1234567894
_str = str(code)
_result = 0
for i in _str:
    if (int(i) > 2) and (int(i) < 8):
        _result += int(i)
print(_result)

#When you only use arithmetic operators,
_result = 0
while (code > 0):
    b = int(code) % 10
    if (b > 2) and (b < 8):
        _result += b
    code /= 10
print(_result)

Additional) The question has changed a little. I wonder why you don't want to use the if statement


2022-09-21 10:43

limit = min(len(str(code)), 7)
code = code // 100
counter = 2;
result = 0
while counter < limit:
    result += code % 10
    code = code // 10
    counter += 1

print(result)

If you don't want to use if (I don't know what this means), it seems like you have no choice but to meet all the conditions in advance and enter the repeat door.

Is it an extreme coding test?

By:

# My personal opinion is that List Processing is Python.
sum(map(int, str(code)[-7:-2]))


2022-09-21 10:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.