0

I have to make a (def) program using Python language where user inserts a string ( up to 8 digits numbers (0-9) and letters (a-z) together), program has to find out how many numbers are there in a string. Program will calculate the sum and average of those numbers.

dimitrisli
  • 20,895
  • 12
  • 59
  • 63

2 Answers2

1

Approach 1 : Pure implementation by string, without using list at all.

def sum_and_average(string):
    COUNT = 0
    SUM   = 0
    for value in string:
        if value.isdigit():
            SUM += int(value)
            COUNT +=1
    print('Sum :',SUM)
    print('Average :',SUM/COUNT)

Approach 2 : Using List Comprehensions and Ascii values

def sum_and_average2(s):
    L = [int(var) for var in s if 48<=ord(var)<=57]
    print('Sum :', sum(L))
    print('Average :', sum(L)/len(L))

Approach 3 : Using Regex, Already Mentioned However Regex will also store values as list object so in your case approach 1 would be best but approach 3 will be fastest in case of long string input.

gagandeep
  • 45
  • 8
0

you can use regular expression to parse the spring to get your numbers and letters separately and then perform the required operation on the numbers. Example

import re
def spring_program(spring):
    regex = re.compile("([0-9]+)([a-z]+)")
    numbers = regex.match(spring).group(1)
    letters = regex.match(spring).group(2)
    print(numbers)
    print(letters)
    #you can now do any manipulation to the numbers