Take out numbers from String without list

76 views Asked by At

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.

2

There are 2 answers

0
Kilu Vander On

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
0
gagandeep On

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.