Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given a text file such as this one called \"sample.txt\": REAL: 45 FAKE: 20 REAL

ID: 664010 • 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 please help me with the following steps:

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).

Please make sure the whole line of code is tested and functioning and shows up correctly in your posted answer! Should be done in Python 2.7. Please try to get it to one line.

Explanation / Answer

from System import *
from System.Collections.Generic import *
from System.Collections import *
from System.IO import *

class Real(object):
   def main(args):
       line = ""
       sum = 0
       try:
           fs = Scanner(File("d:\sample.txt"))
           while fs.hasNext():
               line = fs.next()
               if line.contains("REAL:"):
                   line = fs.next()
                   sum += Integer.parseInt(line)
               else:
                   line = fs.next()
           Console.WriteLine("The sum of REAL numbers is " + sum)
        except FileNotFoundException, e:
           e.printStackTrace()
       except NumberFormatException, nfe:
           nfe.printStackTrace()
       finally:

   main = staticmethod(main)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote