I have a long list of numbers that I would like to input into my code through a raw_input. It includes numbers that are spaced out through SPACES and ENTER/RETURN. The list looks like this . When I try to use the function raw_input, and copy paste the long list of numbers, my variable only retains the first row of numbers. This is my code so far:
def main(*arg):
for i in arg:
print arg
if __name__ == "__main__": main(raw_input("The large array of numbers"))
How can I make my code continue to read the rest of the numbers?
Or if that's not possible, can I make my code acknowledge the ENTER in any way?
P.s. While this is a project euler problem I don't want code that answers the project euler question, or a suggestion to hard code the numbers in. Just suggestions for inputting the numbers into my code.
If I understood your question correctly, I think this code should work (assuming it's in python 2.7):
sentinel = '' # ends when this string is seen
rawinputtext = ''
for line in iter(raw_input, sentinel):
rawinputtext += line + '\n' #or delete \n if you want it all in a single line
print rawinputtext
(code taken from: Raw input across multiple lines in Python )
PS: or even better, you can do the same in just one line!
rawinputtext = '\n'.join(iter(raw_input, '') #replace '\n' for '' if you want the input in one single line
(code taken from: Input a multiline string in python )
I think what you are actually looking for is to directly read from stdin via sys.stdin. But you need to accept the fact that there should be a mechanism to stop accepting any data from stdin, which in this case is feasible by passing an EOF character. An EOF character is passed via the key combination [CNTRL]+d
>>> data=''.join(sys.stdin)
Hello
World
as
a
single stream
>>> print data
Hello
World
as
a
single stream
Related
I am new to regex so please explain how you got to the answer. Anyway I want to know the best way to match input function from a separate python file.
For example:
match.py
a = input("Enter a number")
b = input()
print(a+b)
Now I want to match ONLY the input statement and replace it with a random number. I will do this in a separate file main.py. So my aim is to replace input function in the match.py with a random numbers so I can check the output will come as expected. You can think of match.py like a coding exercise where he writes the code in that file and main.py will be the file where it evaluates if the users code is right. And to do that I need to replace the input myself and check if it works for all kinds of inputs. I looked for "regex patterns for python input function" but the search did not work right. I have a current way of doing it but I don't think it works in all kinds of cases. I need a perfect pattern which works in all kinds of cases referring to the python syntax. Here is the current main.py I have (It doesn't work for all cases I mean when you write a string with single quote, it does not replace but here is the problem I can just add single quote in pattern but I also need to detect if both are used):
# Evaluating python file checking if input 2 numbers and print sum is correct
import re
import subprocess
input_pattern = re.compile(r"input\s?\([\"]?[\w]*[\"]?\)")
file = open("match.py", 'r')
read = file.read()
file.close()
code = read
matches = input_pattern.findall(code)
for match in matches:
code = code.replace(match, '8')
file = open("match.py", 'w')
file.write(code)
file.close()
process = subprocess.Popen('python3 match.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out = process.communicate()[0]
print(out == b"16\n")
file = open("match.py", 'w')
file.write(read)
file.close()
Please let me know if you don't understand this question.
The following regex statement is very close to what you need:
input\s?\((?(?=[\"\'])[\"\'].*[\"\']\)|\))
I am using a conditional regex statement. However, I think it may need a nested conditional to avoid the situation that the user enters something like:
input(' text ")
But hopefully this gets you on the right track.
I"m trying to store 2 multi line inputs in 2 variables. However, std input methods keep getting hung up. I cannot change input format, but I can always expect 2 strings will be provided together. There is a new line character at the end of the first block and a new line character at the end of the second block.
I have tried several solutions from previous posts on how to accept multi line input, but none work for this case:
Store multi-line input into a String (Python)
When I try to use this code:
y input is accepted but x input is never accepted. I think the compiler is misinterpreting a line break somehow.
Any suggestions would be really appreciated.
y = input().strip()
x = input().strip()
TGGGAGGAGCAGTGATAATGCTACCTTGCTCGTGCCCCTTTAATGCCGGTGTCATCGCCTTAATGGGGTTCACAAGCAGTTACGGGGGGTCAAGTAATCATCGCGTTCGTCTTAGACGTGTCAGAGAACTAGTTTTGGAATCATTAACGACCTGCAATACTAGGTGCCAGCATAGGGTCTTTCGGAAGCACAACGTTGGAAGGCATCGCTTAGTGTAACCTAGTTACGGGAAGGCTACAGGTGCGGATGGTGGGGCCCAGCTGGGACTCAATCCAGGGACATCGGACTTTCGTTGGGGTTGAGCGGTCGCGAGGATTCGCAAGAGGGCGCCTTACAATGTTACCGTTTAGATTTACGGCCATTCCGACTTTGCAATTATTACCTTGAGCGATGCCGGCCATGCCGCGACATTATCAGTGATGTGTTCTCTCTCGGCTTGGTCGTTCAAACACGGGGCGTCATAGCTGAGTAGCCAAGGCAAACCAATTACCTACGTTCTGACCTGGCTGAATCTTGTGGAGCACCGGATCCAAGCAGTCGTGCCGGAGATTGTAGGCCAGCTTGTCATTCTGGATTGCGTTCCGCCCGATGTGAGCTTGTTCATACACCGAGTACGGGCTGCATTGGATCGTTCTATACGACAACGCTTCAGATCTCGAGTGCGTGGATCGAAGAAAGCGGAAGTCCGTTCGCGGACGCTCACAGCTGGTTGCTGCCGGCACCAACATGAACCGATCACCTAGCGCTTATAGTAAGCGGATATATCTTAGTATTAACCTTTCATTCCGGGCGGCACCTGAATGGGCAGTCTCGATTGATTAAGATCCCTTACTCTTCGAACTCGCGCGGACACGTCGTGCGCATCAATGGCAGTTATCTCGTATTAATACATACGCGTGATCAGCGCTATAGGGTATTTTTAGTTTTGGTCAACTCCGCAGTCACTGTGGATTGAATTGAGCATGCGGGCGAAGATCTGCTTTTCATCGCCTCTAACCAA
TATGGAGGACCAATGGTAGATGATACCGTTGCTCGGGGCGCTTTAAAGCCGGAGTAATGCGCCTATGAATGTGGGTTCACAGAGGAGTTCCCGGGGGGTCAACATCATCATGCGAGTGTCGTCTTAAAAGTGGCAGAATAACTGGTTTCTATGTATATCATTGAGCACCATCAATACGAGGTGTCAGCATGAGGCTCGTTCGGATGCCCGGCCTTGGAAGGCATCTGAGTTAGTATAACACTAGTTACGCGAAGGCTACAGGTGCGTGATCGTGCGGCCCAGTTGGGACTCAATTGAGGGACACGCGGACTTTCGTCGGGCTGTCAGAGGCCGGTCGGGGGAATGCGCAGGTTGTGCGGCACATACAATGTTATCGTTTCAGAATTTTATCGGCCATATCCGACTTTGCAATTATATTCCTTGCAGCGATGCCGGGGGAGCCGCGTACATGCATCAGTGTATGTATGCTCACTCGGCTATGTCGGTTCATAACCTGGCGCATATTAGCTGAGTAGACAAGGACTAAACCAATTAAACTACGTTCTGACCTCGCTATAGTATGTGAGTGAGTCACCGGATCCGAGCAGTTCGGGCCGCAGATTGGAGGCCAGCTTGTCATACTGGGTTGACCGTTTCGCCCGATGGGAGCTTGGTATCATACATCGAGTTACGTGGCTGCATTGTGTATCGTTCTGTTACGTACAACGCCTTCAAGGTCCCGAGTGCGAGGGTTCCCAGAAAAGCTGGAAGCGCAGTTCGTGAACTGCTCACAGCTGGTGGCTGCCGGCACCAACATGCACTTCGACTCACCTACCCAGCTAAATGTAAGCGCATATCTCTTAGTATATAACCTTTACATATCCGGGCGACGTACAGTAAAGAAGCAGGCTCGATGTCGTAGAGTTACCCTTACTACACTCGCAAATCGCGCGGACACGGTATGTACGCATTGAATCGACAGTTCTCTCGTATTTAGTACATACGCGTGATCAGCTGCTATAGAGTAATTCTAGCTTTGAGTGAACACCTCAGTGATGGCTGGATTGTAACTGAGCAACGCGGTCTGAGCGAACGGTTTTTGCATCGCGCTCTAACCAGG
I figured out that the problem was IDE specific. VS Code cannot accept large string input from console. No problems when using PyCharm.
I've settled on a text-file based save system for my game, storing the values of required variables with keywords - for example, the password that tells the game which chapter to play. However, it appears to be malfunctioning, and I can't see why.
Before starting the game, we have:
if not os.file.isfile('TSGsave{0}.txt'.format(name)):
TSGsave=open('TSGsave{0}.txt'.format(name),'wt')
TSGsave.write('\nw5CT$n<jfW=-#J%4Ya5##')
TSGsave.close()
(the keyword used is a bunch of jibberish so that the user can't change it knowing what's going to happen). This adds w5CT$n<jfW=-#J%4Ya5## to the text file. We then have:
for i in range (len(lines)):
if 'w5CT$n<jfW' in lines[i]:
findpass=lines[i]
for i in range (len(findpass)):
if findpass[i]=='=':
cutfrom=i+1
password=findpass[cutfrom:len(findpass)]
to retrieve the variable (which can change, so it can't be written in as definite value). I know it works, because I added print (password) to the code and it returned -#J%4Ya5##. Then to start the corresponding chapter, the code is:
if password=='-#J%4Ya5##':
but it isn't starting the indented block. In the shell, the program ends and goes back to the >>> line.
If there is a way to fix this code, great - but another code to do the same thing would work just as well.
Your lines contain newlines, and these are being included. Strip these from the line:
findpass = lines[i].rstrip('\n')
Printing a value with a newline in it will simply add an extra black line after the print. Always use the repr() function to produce a Python representation of strings to see such characters:
>>> print '-#J%4Ya5##\n'
-#J%4Ya5##
>>> print repr('-#J%4Ya5##\n')
'-#J%4Ya5##\n'
Your parsing code is overly complicated; you can use str.split() or str.partition() to split your password from the line instead. You should just loop over the lines list directly rather than produce indices with range():
for line in lines:
if 'w5CT$n<jfW' in line:
password = line.partition('=')[2].rstrip('\n')
I'm trying to solve a Krypto Problem on https://www.spoj.pl in Python, which involves console input.
My Problem is, that the Input String has multiple Lines but is needed as one single String in the Programm.
If I just use raw_input() and paste (for testing) the text in the console, Python threats it like I pressed enter after every Line -> I need to call raw_input() multiple times in a loop.
The Problem is, that I cannot modify the Input String in any way, it doesn't have any Symbol thats marks the End and I don't know how many Lines there are.
So what do I do?
Upon reaching end of stream on input, raw_input will return an empty string. So if you really need to accumulate entire input (which you probably should be avoiding given SPOJ constraints), then do:
buffer = ''
while True:
line = raw_input()
if not line: break
buffer += line
# process input
Since the end-of-line on Windows is marked as '\r\n' or '\n' on Unix system it is straight forward to replace those strings using
your_input.replace('\r\n', '')
Since raw_input() is designed to read a single line, you may have trouble this way.
A simple solution would be to put the input string in a text file and parse from there.
Assuming you have input.txt you can take values as
f = open(r'input.txt','rU')
for line in f:
print line,
Using the best answer here, you will still have an EOF error that should be handled. So, I just added exception handling here
buffer = ''
while True:
try:
line = raw_input()
except EOFError:
break
if not line:
break
buffer += line
Write a program that outputs the first number within a file specified by the user. It should behave like:
Enter a file name: l11-1.txt
The first number is 20.
You will need to use the file object method .read(1) to read 1 character at a time, and a string object method to check if it is a number. If there is no number, the expected behaviour is:
Enter a file name: l11-2.txt
There is no number in l11-2.txt.
Why is reading 1 character at a time a better algorithm than calling .read() once and then processing the resulting string using a loop?
I have the files and it does correspond to the answers above but im not sure how to make it output properly.
The code i have so far is below:
filenm = raw_input("Enter a file name: ")
datain=file(filenm,"r")
try:
c=datain.read(1)
result = []
while int(c) >= 0:
result.append(c)
c = datain.read(1)
except:
pass
if len(result) > 0:
print "The first number is",(" ".join(result))+" . "
else:
print "There is no number in" , filenm + "."
so far this opens the file and reads it but the output is always no number even if there is one. Can anyone help me ?
OK, you've been given some instructions:
read a string input from the user
open the file given by that string
.read(1) a character at a time until you get the first number or EOF
print the number
You've got the first and second parts here (although you should use open instead of file to open a file), what next? The first thing to do is to work out your algorithm: what do you want the computer to do?
Your last line starts looping over the lines in the file, which sounds like not what your teacher wants -- they want you to read a single character. File objects have a .read() method that lets you specify how many bytes to read, so:
c = datain.read(1)
will read a single character into a string. You can then call .isdigit() on that to determine if it's a digit or not:
c.isdigit()
It sounds like you're supposed to keep reading a digit until you run out, and then concatenate them all together; if the first thing you read isn't a digit (c.isdigit() is False) you should just error out
Your datain variable is a file object. Use its .read(1) method to read 1 character at a time. Take a look at the string methods and find one that will tell you if a string is a number.
Why is reading 1 character at a time a better algorithm than calling .read() once and then processing the resulting string using a loop?
Define "better".
In this case, it's "better" because it makes you think.
In some cases, it's "better" because it can save reading an entire line when reading the first few bytes is enough.
In some cases, it's "better" because the entire line may not be sitting around in the input buffer.
You could use regex like (searching for an integer or a float):
import re
with open(filename, 'r') as fd:
match = re.match('([-]?\d+(\.\d+|))', fd.read())
if match:
print 'My first number is', match.groups()[0]
This with with anything like: "Hello 111." => will output 111.