Home > Software design >  Python Find the sum in a string NO IMPORTS
Python Find the sum in a string NO IMPORTS

Time:03-17

I know the question might not seem hard but it is a tricky one, let me explain.

Input
Bla bla this is 45 text 10.5 bla bla -1 this is tricky
Output
54.5
Explanation
45 10.5 -1 = 54.5

I can already sum digits or numbers from a string but I don't know how to seperate the float numbers and negative ones like 10.5 and -1. Below is the code I have now which only sums the ints not floats or negative numbers:

def findSum(text):
string = "0"
Sum = 0

for char in text:
     if (char.isnumeric()) :
        string  = char
        nums = char.split('.')
     else:
         Sum  = float(string)
         string = "0"
return Sum   float(string)

 text = "sqdkl 45 qsd 10.5 qsdaf -1"
 print(findSum(text))

ALSO NO IMPORTS

CodePudding user response:

Use regular expressions:

import re

inpt = "Bla bla this is 45 text 10.5 bla bla -1 this is tricky"

result = 0

matches = re.findall("[-]*[0-9.] ", inpt)

for match in matches:
    result  = float(match)
    
result # 54.5

CodePudding user response:

Check if each "word" is a positive or negative number and add to total:

def findSum(text):
    total = 0
    for word in text.split():
        if word[0]=="-" and word[1:].count(".")<=1 and word[1:].replace(".", "").isnumeric():
            total  = float(word)
        elif word.count(".")<=1 and word.replace(".", "").isnumeric():
            total  = float(word)
    return total

>>> findSum("Bla bla this is 45 text 10.5 bla bla -1 this is tricky")
54.5

Alternatively, try to add every "word" and ignore exceptions:

def findSum(text):
    total = 0
    for word in text.split():
        try:
            total  = float(word)
        except ValueError:
            continue
    return total

CodePudding user response:

Eliminated every alphabetical characters using str.replace, split the string and cast to float.

The list of the alphabetical characters can be obtained using string.ascii_letters. Since you cannot use imports, copy-paste its output in your code (print(string.ascii_letters)).

text = "sqdkl 45 qsd 10.5 qsdaf -1"
import string # it can be removed and introduce an own list

chars_to_be_removed = string.ascii_letters   ',:;' # depends on the data

for char in chars_to_be_removed:
    text = text.replace(char, '')

sum_ = sum(float(n.strip()) for n in text.split(' ') if n != '')
print(sum_)

EDIT: stronger approach

Since no rules is given concerning the allowed characters in string, repetitions of . or '-' (are parts of both language and arithmetical expressions!), here a more robust implementation. It is based on groupby function of the itertools-build-in package. It can handle string such as

"sqdkl 45 qsd 10.5 qsd....af -1 bih-ds----a10".

It uses an allowed set of characters instead of set of characters to be removed.

import itertools as it

text = "sqdkl 45 qsd 10.5 qsd....af -1 bih-ds----a"

import string # it can be removed and introduce an own list
allowed_chars = string.digits '-.'

sum = 0
for match, chars in it.groupby(text, lambda s: s in allowed_chars):
    if match:
        num = ''.join(chars)
        # group with 1 element
        if '.' == num or '-' == num:
            continue
        # group with more elements
        if num.count('-') > 1 or num.count('.') > 1:
            continue
        #print(num)
        sum  = float(''.join(num))
print(sum)
  • Related