Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process raw data (in python)? [closed]

***I'm not explaining this well so hopefully this edit makes more sense: basically I have to write code that will work for a ton of test cases, the input below is just an example. So I can't manually enter the input into my function

Say I have the following input:

    0
    4
    0,2,2,3

and I need to generate some sort of output like

    1

How can I do this?

What I mean is, if I'm normally given a problem, I can just define a function and then input the values manually, but how do I read raw data (perform a series of functions/operations on the data)?

(For the assignment I am supposed to receive input on STDIN -> and print correct output on STDOUT

like image 306
Noob Coder Avatar asked Dec 02 '25 04:12

Noob Coder


1 Answers

STDIN is just a file (or a file-like object) represented by sys.stdin; you can treat it like a normal file and read data from it. You can even iterate over it; for example:

sum = 0
for line in sys.stdin:
    item = int(line.strip())
    sum += item
print sum

or just

entire_raw_data = sys.stdin.read()
lines = entire_raw_data.split()
... # do something with lines

Also, you can either iteratively call raw_input() which returns successive lines sent to STDIN, or even turn it into an iterator:

for line in iter(raw_input, ''):  # will iterate until an empty line
    # so something with line

which is equivalent to:

while True:
    line = raw_input()
    if not line:
        break
    # so something with line

See also: https://en.wikibooks.org/wiki/Python_Programming/Input_and_output

like image 134
Erik Kaplun Avatar answered Dec 04 '25 17:12

Erik Kaplun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!