I have this part of python code that should read input values from the screen.
When it runs, it keeps running forever. I tried CTRL+D as per the search results, but it does not work. This code is given and it works when I submit the code to an online grader but does not work on my windows machine.
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
Sample input should be:
3 2
20 50
12 12
51 51
On Windows you should use Ctrl-Z instead of Ctrl-D. Also, this should be the first character of a newline, and there should be a newline (enter) after the Ctrl-Z as well. There may be other characters after the Ctrl-Z, which will be ignored.
So, the shortest sequence to force an EOL on Windows is: Enter, Ctrl-Z, Enter.
I know this from experience and did found some answers or comments stating the same, but I couldn't find any official documentation where this is explained. If I find it, I will add it to this answer.
(please leave a comment if you know a reliable source for this behaviour.)
Related
I have a few python files that take input as two ints separated by spaces, and return an int. (My class requires this.) I'm having an issue where an extra "D" appears along with my output, after I hit Ctrl-D to end the input. It's running the programs correctly, though - the output is correct.
Here's what I'm seeing:
$ python gcd_euclid.py
144 100
4D
$ python pc_1_ucsd.py
3 4
7D
Oddly...this wasn't happening yesterday, and I'm not sure if I changed anything. Does anyone have any ideas why this is happening and how to fix it?
Edit: Here is the snippet that the course provided for reading the input. I hadn't used sys.stdin before this week.
import sys
input = sys.stdin.read()
tokens = input.split()
a = int(tokens[0])
b = int(tokens[1])
print(a + b)
(they chose to use the input keyword as a variable, not me!)
I suspect it is old keyboard echo (where did the line feed go?) Try feeding shell input using something like:
command-and-args <<!EOF
input lines
!EOF
While working on an image file I have, I tried reading it into a string and printing it on my IDLE 3.6. The string is roughly 160K bytes long and I already saved it into a txt file on my machine. That took about a second, so I figured printing it would take about the same...
Never have I been so wrong...
Now, I checked this and the first answer suggests that the print itself is problematic. In their case, the format was non-standard, so I'm not sure if my case is the same. Second, if the print is the problem, why the IDLE seem to be slow after the print is done?
This is how I run it:
with open(location_of_160KB_png_file, "rb") as imageFile:
f = imageFile.read()
b = bytearray(f)
b=''.join([str(bb) for bb in b])
b[:10] # this prints easily (on IDLE I don't have to use _print_ function, I can just type the variable name)
b # this, however...
The issue, as explained in the answers to the link you gave, is that the tk Text widget is optimized for handling short lines. I have loaded IDLE's Shell with over 500000 lines of maybe 40 chars. That is 20 million chars, way larger than any file a person would write. It is well suited for the intended use.
In the referenced link, a 10000 char line is built 1 char at a time. Tk Text bogs down somewhere in the low 1000s. You apparently threw 160000 chars all at once. 10000 all at once is enough.
PS: Echoing expressions without a print statement is standard Python interactive interpreter behavior. I an fairly sure that this was probably copied from predecessors.
I have a long-running script that loops over rows in a database. Every so often I'd like it to print how many rows it's processed, but without creating a new line each time. This is essentially what I have:
import sys
mystr = "{} rows complete\r"
for i in range(0, 100):
if i % 10 == 0:
sys.stdout.write(mystr.format(i))
sys.stdout.flush()
When I run this (on Python 2.7.5 64-bit, Windows) I get:
0 rows complete
10 rows complete
20 rows complete
...
100 rows complete
Can anyone think of why the carriage return isn't working? I've seen some similar questions here about Python and \r, but all the answers say to include sys.stdout.flush(), which I have.
Using \r is probably the correct way to go here, but the behaviour depends very much on how the text is being output. Not all terminals will respect a bare carriage return:
cmd.exe and powershell.exe should both output the text the way you expect (Powershell ISE doesn't but that's a red herring here).
Python's own idle will ignore the carriage return, all output comes on one long line.
As you noted, your own editor's command window also ignores \r.
Also, if you try from an interactive window you also get some numbers output at the end of each line: that's because the interactive windows helpfully outputs the result of the call to sys.stdout.flush().
So I'm writing a differential calculator program in python 2.4 (I know it's out of date, it's a school assignment and our sysadmin doesn't believe in updating anything) that accepts a user input in prefix notation (i.e. input = [+ - * x^2 2x 3x^2 x], equivalent to x^2 + 2x - 3x^2 * x) and calculates the differential.
I'm trying to find a way to read the command line user input and put the mathematical operators into a queue, but I can't figure it out! apparently, the X=input() and x=raw_input() commands aren't working, and I can find literally 0 documentation on how to read user input in python 2.4. My question is: How do I read in user input in python 2.4, and how do I put that input into a queue? Here is what I am trying:
1 formula = input("Enter Formula:")
2
3 operatorQueue=[]
4
5 int i = len(formula)
6
7 for x in formula:
8 if formula[x] == '*', '+', '-', '/':
9 operatorQueue.append(formula[x])
0
11 print "operator A:", operatorQueue.pop(0)
12
Which is not working (I keep getting errors like "print: command not found" and "formula:command not found")
Any help would be appreciated
#miku already answered with this being your initial problem, but I thought I would add some more.
The "sh-bang" line is required by command line scripts so that the proper process is used to interpret the language, whether it be bash, perl, python,etc. So in your case you would need: /usr/bin/env python
That being said, once you get it running you are going to hit a few other issues. raw_input should be used instead of input, because it will give you back a raw string. input is going to try and eval your string which will mostly likely give you problems.
You may need to review python syntax a bit more. Assignments in python don't require that you declare the variable type: int a = 1. It is dynamic and the compiler will handle it for you.
Also, you will need to review how to do your if elif else tests to properly handle the cases of your formula. That too wont work doing it all on one line with multiple params.
If you're on a unix-ish platform, put a
#!/usr/bin/env python
on top of your program. The shell does not seem to recognize that you are running a python script.
this piece of code is driving me crazy. I'm trying to print a help list for a program I'm writing. So I define a dictionary, where the keys are the words that the user might want to be clarified and the values are the descriptions of the words. Then I use a for... in... loop to print it all. To put it simple:
ERROR = '\x1B[1;31m ERROR!! \x1B[0m'
WARNING = '\x1B[1;33m WARNING! \x1B[0m'
SUCCESS = '\x1B[1;32m Operation successful! \x1B[0m'
ABORTED = '\x1B[1;33m Operation aborted! \x1B[0m'
help_descriptions = {'\x1B[34m NUMBERS \x1B[0m':'are the options you can take.',\
ERROR:'means you ran into and error and the program can\'t go on.',\
WARNING:'means that the data you entered might cause problems.',\
SUCCESS:'means that no run-time errors where encoutered.',\
ABORTED:'means you aborted a previous option, deleting\n the data associated.'}
def HelpMe():
print(70 * '~')
print(' HELP')
print(70 * '~')
for key in help_descriptions.keys():
print('%10s %s' % (key, help_descriptions.get(key)))
print(70 * '~')
The only thing that doesn't work is the %10s token. I mean, it does print the value of the key, but it does not puts extra spaces if needed. I've tried to run in an interactive section this piece of code
print('%10s' % 'foo')
and the output is right.
Does any of you have an idea of how make it work?
Additional info: I'm running Python 3 on a Linux machine running Ubuntu 11.04. This code is part of a custom module I've written to store some static text or simple functions that print text. So I import this module in the main application, it is not stand-alone.
Thank you in advance.
The problem is that those are at least 10 characters long: remember, the ANSI escape characters count. You could do any of the following:
Increase the field width until you get the width you want (since all of them seem to contain the same number of escape characters, this might work).
Strip the escape characters and use the result for padding.
Pad the labels (like "WARNING!") to the correct field width before adding the escape characters.
Any of these should achieve the desired effect.