-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsumnums.py
More file actions
50 lines (43 loc) · 1.29 KB
/
sumnums.py
File metadata and controls
50 lines (43 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import operator
def sumfile(fname):
with open(fname, 'r') as f:
return [reduce(operator.add,
map(int,
line.strip().split()), 0)
for line in f]
print(sumfile('numbs'))
def sumfile_ignore(fname):
res = []
with open(fname) as f:
for line in f:
# split each line into separate tokens
tokens = line.strip().split()
# filter out non-numbers
numbers_str = filter(str.isdigit, tokens)
# convert to integers
numbers = map(int, numbers_str)
# add 'em up
res.append(reduce(operator.add, numbers, 0))
return res
print(sumfile_ignore('numbs2'))
def tryfunc(x):
res = 0
try:
res = int(x)
except ValueError as e:
pass
finally:
return res
def sumfile_ignore_except(fname):
res = []
with open(fname) as f:
for line in f:
# split each line into separate tokens
tokens = line.strip().split()
# filter out non-numbers
# convert to integers
numbers = map(tryfunc, tokens)
# add 'em up
res.append(reduce(operator.add, numbers, 0))
return res
print(sumfile_ignore_except('numbs2'))