DEV Community

loading...

Day 14 of 100DaysofCode: Finding Numerical Data And Summing Them

Durga Pokharel
A mathematics student learning to code.
・2 min read

Today is my 14th day of #100DayaofCode. Today I worked in some assignment on python to access web data in coursera.

Also I learned more properties of CSS including introduction to the applied accessibility challenges, add a text alternative to images for visually impaired accessibility, use heading to show hierarchical relationships of content, jump straight to the content using the main element etc form Freecodecamp.

Finding Numerical Data From File And Summing Them

At first we start with importing regular expression as re, operator and reduce.

import re
import operator
from functools import reduce
Enter fullscreen mode Exit fullscreen mode

I opened the file and read through each lines. I make a list whose name is total. Then I star looping and remove whitespace with rstrip(). In words I applied re.findall method which include any digit in the line. If line does not contain numbers then it skip that line and continue and my program is given below. num includes all the numbers from words. I kept in total's list.

fh=open('file2.txt').readlines()
total=[]
#print(fh)
for line in fh:
    line=line.rstrip()
    words=re.findall('[0-9]+',line)
    #print(words)
    if len(words) == 0: continue
    num= [int(i) for i in words]
    total.extend(num)

print(total)
summ= lambda total: reduce(operator.add, total)
print(summ(total))

Enter fullscreen mode Exit fullscreen mode

Discussion (3)

Collapse
otumianempire profile image
Otu Michael
summ= lambda total: reduce(operator.add, total)
print(summ(total))
Enter fullscreen mode Exit fullscreen mode

Has a typo, summ

In all, you a lambda function. I don't remember the last time I did use a lambda function.

Collapse
otumianempire profile image
Otu Michael • Edited

pardon me, I mistook summ as a typo for sum, which is a built-in function that performs the same functionality as the summ. I run your code not long from now.

summ= lambda total: reduce(operator.add, total)
Enter fullscreen mode Exit fullscreen mode

was translated

def summ(total):
    return reduce(operator.add, total)
Enter fullscreen mode Exit fullscreen mode

In all, all is good. Thanks!!

Collapse
iamdurga profile image
Durga Pokharel Author

yeah that's cool

Forem Open with the Forem app