Given a text file such as this one called \"sample.txt\" : REAL: 45 FAKE: 20 REA
ID: 664088 • Letter: G
Question
Given a text file such as this one called "sample.txt" :
REAL: 45
FAKE: 20
REAL: -10
FAKE: 30
REAL: 5
FAKE: 40
REAL: 12
FAKE: 50
REAL: 1
FAKE: 60
REAL: -15
FAKE: 70
REAL: 0
FAKE: 80
REAL: 35
FAKE: 90
Can you do this in one line of code:
1. Use a list comprehension to separate out the lines of the file that start with “REAL:” .
2. Add up the sum of the numbers marked as REAL, and print this out. For the file given above, the output would be:
>>>
The sum of the REAL numbers is 73 .
3. Do this using as few lines of code as possible. The best solution uses 1 line, with a fixed filename (you can assume the name, and don’t have to ask the user).
Should be IN PYTHON
Explanation / Answer
print "THE SUM IS: ",
sum([(int(line.rstrip(' ')[6:])
if (line.rstrip(' ')[:4] == "REAL") else 0) for line in open('sample.txt')])
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.