***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
You can use the function
raw_input()
to read from the standard input and then process as you need.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:or just
Also, you can either iteratively call
raw_input()
which returns successive lines sent to STDIN, or even turn it into an iterator:which is equivalent to:
See also: https://en.wikibooks.org/wiki/Python_Programming/Input_and_output
We can easily use
raw_input()
for this case:If you're using Python 3, you can use
input()
in the same way:Or, if you prefer to run your program with command line arguments, use
sys.argv
Here is a good read: http://www.linuxtopia.org/online_books/programming_books/python_programming/python_ch06s03.html
EDIT
Okay, just understand the real question here.
The simple way: you store the data in a text file, and read it with your program.
This way you can process your data quickly. After processed, you can write it down to another file:
As what to do with your command file, you can structure it yourself and process it with
str.split()
method, and loop through it.Tips: So you don't forget to close the file, it is recommended to use the
with
statement:More on file processing:
http://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files
Hope that helps!
use this raw_input() it's the basic python input function.
for more information about raw input please refer to:
http://docs.python.org/2/library/functions.html#raw_input
Usually you want to do:
or
And then:
or
However, you can also (but probably don't want to) do this:
This is more or less what
print
andinput
do behind the scenes.sys.stdin
,sys.stdout
(andsys.stderr
) work just like files - you can read and write to them etc. In Python terminology they are known as file-like objects.From what I understand, you want something like this:
If run, that would look something like this: