Python Forum
Python Coding Help: Calculating Sums
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Coding Help: Calculating Sums
#1
Hello,

I am completely new to python and I'm taking a course online that has the following question:

When inputting a number, how can you verify if the digits of that number are divisible by 4?

For example, the input is input = "4007-6000-0000"

I'm having trouble converting this string of numbers to digits so I can add them up and see if they are divisible by 4.

The code I'm trying is the following:
sum = 0
length = len(number)
for i in range(0, length) :
 if number[1] != '-' :
  c += int(number[i])
Any help would be greatly appreciated!
Larz60+ write Jan-11-2021, 11:04 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use code tags on future posts.
Reply
#2
use the modulo operator, see: https://docs.python.org/3/library/operat...-functions
Reply
#3
(Jan-11-2021, 11:07 PM)Larz60+ Wrote: use the modulo operator, see: https://docs.python.org/3/library/operat...-functions

Hi Larz60,

Thank you for your response!

I forgot to mention I know how to use the modulo operator.

The issue I'm having is getting the initial sum of the digits in the list of numbers.

I'm unable to get a single number sum from all of the digits.

Is my range correct?

I should be getting that the sum = 17. (4 + 7 + 6).

But I'm unable to get that.

Any suggestions?
Reply
#4
Can you iterate over every character in the string?
If it's a digit, can you convert the character to a number?
If it's a digit, can you add its value to a total?

Those would be the different parts of a solution.
Reply
#5
If you want to loop through the letters in a string, loop through the letters in a string.
letters = 'abcdefg'
vowels = 0
constantans = 0
for letter in letters:
    if letter in 'aeiou':
        vowels += 1
    else:
        constantans += 1
print(vowels, constantans)
Doesn't that make a lot more sense than all your code that generates results you don't want?
length = len(number)
for i in range(0, length) :
 if number[1] != '-' :
Why do we care about the length of the number? Is the length involved in your calculation? Why make an iterator that returns numbers from 0 to length-1? Do you need any of those numbers? Are they involved in calculating the sum? If you are only doing those things so you can get at the characters in "number", skip all the hullaballoo and get the characters directly.

You can add '7' and '6', but that gives you '76' and I think you want 13. To get a number as a result you need numbers as operands. How can you convert a character to an integer? As with all problems there are multiple ways this can be solved. Try coming up with three different ways and pick the solution you like best.
banidjamali likes this post
Reply
#6
(Jan-12-2021, 06:12 AM)deanhystad Wrote: If you want to loop through the letters in a string, loop through the letters in a string.
letters = 'abcdefg'
vowels = 0
constantans = 0
for letter in letters:
    if letter in 'aeiou':
        vowels += 1
    else:
        constantans += 1
print(vowels, constantans)
Doesn't that make a lot more sense than all your code that generates results you don't want?
length = len(number)
for i in range(0, length) :
 if number[1] != '-' :
Why do we care about the length of the number? Is the length involved in your calculation? Why make an iterator that returns numbers from 0 to length-1? Do you need any of those numbers? Are they involved in calculating the sum? If you are only doing those things so you can get at the characters in "number", skip all the hullaballoo and get the characters directly.

You can add '7' and '6', but that gives you '76' and I think you want 13. To get a number as a result you need numbers as operands. How can you convert a character to an integer? As with all problems there are multiple ways this can be solved. Try coming up with three different ways and pick the solution you like best.

Hi deanhystad!

I think I forgot to mention that the number must be 12 digits and formatted like this:

####-####-####

So I created the range of indices 0 to the length of the number. Which I now realize I can just search from indices 0 to 14.

I figured out a possible solution to adding up all the digits of the 14 digit number and seeing if it's evenly divisible by 4.

c = 0
  length = len(number)
  for i in range(0, length) :
    if number[i] != '-' :
      c += int(number[i])
  if c % 4 != 0 :
   print("true")
Whereas if the index is a number, it adds it to c. If the index is a '-' it won't do anything.

So inputting the number "4094-3460-2754" would print true.
Reply
#7
To test format I would use something like this
substr = number.split('-')
if len(number < 15)
    raise ValueError(f'{number} is too short')
if len(substr) != 3:
    raise ValueError('Not three numbers')

for s in substr:
    if len(s) != 4:
        raise ValueError(f'Number {s} is not length 4')
If you need to know the indices you can use enumerate
for index, digit in enumerate(number):
    if digit == '-':
         if index not in [4, 9]:
             raise ValueError('not all numbers are length 4')
    else:
         add to sum
if c % 4 != 0 : is inadequate for format verification. Does it catch 12345-123-4321?
Reply
#8
Dean is trying to show you that although you COULD iterate through your sequence by using length and range functions, python has a superior option with its ability to iterate directly over any sequential object (including a string).

for char in "Python":
    print(char)
P
y
t
h
o
n
A simple function that sums all the digits in a string but ignores everything else:
mystring = "123-abc^^456!!!"

def sum_nums(string_in):
    result = 0
    for char in string_in: # Don't use an index, just loop over the string!
        if char.isdigit(): 
            result += int(char)
    return result

print(sum_nums(mystring))
buran likes this post
Reply
#9
Use a regular expression to see that the input is correct, for example:
import re

pattern = re.compile(r'\d{4}-\d{4}-\d{4}') #  3 4-digit groups with hyphen in between
Then if your input matches the pattern, add all digits in the expression and take the result modulo 4. I generate a list of digits, take the sum of the digits in the list modulo 4. If the number i equals zero then the sum was divisible by 4
x = "4007-6000-0000"

if pattern.matches(x):
    i = sum([int(c) for c in x if c.isdigit()]) % 4
Reply
#10
Additional tidbit regarding str.isdigit() which may help avoid some pitfalls in real life scenarios:

>>> num = '1²'
>>> num.isdigit()
True
>>> all(i.isdigit() for i in num)
True
>>> sum(int(i) for i in num if i.isdigit())
/.../
ValueError: invalid literal for int() with base 10: '²'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calculating BLEU scores in Python kg17 1 2,544 Jan-12-2021, 08:26 PM
Last Post: Gribouillis
  create new variable that sums the array prasanthbab1234 3 2,309 Sep-26-2020, 02:03 PM
Last Post: jefsummers
  Loop of sums MathFreak 2 2,616 Mar-20-2019, 10:07 PM
Last Post: MathFreak
  Calculating of difficult integrals in python enitorc 0 5,540 Apr-15-2018, 01:24 PM
Last Post: enitorc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020