why this python code is producing Runtime Error in ideone? - python

import sys
def func():
T = int(next(sys.stdin))
for i in range(0,T):
N = int(next(sys.stdin))
print (N)
func()
Here I am taking input T for for loop and iterating over T it gives Runtime error time: 0.1 memory: 10088 signal:-1 again-again . I have tried using sys.stdin.readline() it also giving same error .

I looked at your code at http://ideone.com/8U5zTQ . at the code itself looks fine, but your input can't be processed.
Because it is:
5 24 2
which will be the string:
"5 24 2"
this is not nearly an int, even if you try to cast it. So you could transform it to the a list with:
inputlist = next(sys.stdin[:-2]).split(" ")
to get the integers in a list that you are putting in one line. The loop over that.
After that the code would still be in loop because it want 2 integers more but at least you get some output.
Since I am not totally shure what you try to achieve, you could now iterate over that list and print your inputs:
inputlist = next(sys.stdin[:-2]).split(" ")
for i in inputlist
print(i)
Another solution would be, you just put one number per line in, that would work also
so instead of
5 24 2
you put in
5
24
2
Further Advice
on Ideone you also have an Error Traceback at the bottom auf the page:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
File "./prog.py", line 3, in func
ValueError: invalid literal for int() with base 10: '1 5 24 2\n'
which showed you that it can't handle your input

Related

ValueError in Python 3 code

I have this code that will allow me to count the number of missing rows of numbers within the csv for a script in Python 3.6. However, these are the following errors in the program:
Error:
Traceback (most recent call last):
File "C:\Users\GapReport.py", line 14, in <module>
EndDoc_Padded, EndDoc_Padded = (int(s.strip()[2:]) for s in line)
File "C:\Users\GapReport.py", line 14, in <genexpr>
EndDoc_Padded, EndDoc_Padded = (int(s.strip()[2:]) for s in line)
ValueError: invalid literal for int() with base 10: 'AC-SEC 000000001'
Code:
import csv
def out(*args):
print('{},{}'.format(*(str(i).rjust(4, "0") for i in args)))
prev = 0
data = csv.reader(open('Padded Numbers_export.csv'))
print(*next(data), sep=', ') # header
for line in data:
EndDoc_Padded, EndDoc_Padded = (int(s.strip()[2:]) for s in line)
if start != prev+1:
out(prev+1, start-1)
prev = end
out(start, end)
I'm stumped on how to fix these issues.Also, I think the csv many lines in it, so if there's a section that limits it to a few numbers, please feel free to update me on so.
CSV Snippet (Sorry if I wasn't clear before!):
The values you have in your CSV file are not numeric.
For example, FMAC-SEC 000000001 is not a number. So when you run int(s.strip()[2:]), it is not able to convert it to an int.
Some more comments on the code:
What is the utility of doing EndDoc_Padded, EndDoc_Padded = (...)? Currently you are assigning values to two variables with the same name. Either name one of them something else, or just have one variable there.
Are you trying to get the two different values from each column? In that case, you need to split line into two first. Are the contents of your file comma separated? If yes, then do for s in line.split(','), otherwise use the appropriate separator value in split().
You are running this inside a loop, so each time the values of the two variables would get updated to the values from the last line. If you're trying to obtain 2 lists of all the values, then this won't work.

TypeError: not all arguments converted during string formatting 11

def main():
spiral = open('spiral.txt', 'r') # open input text file
dim = spiral.readline() # read first line of text
print(dim)
if (dim % 2 == 0): # check to see if even
dim += 1 # make odd
I know this is probably very obvious but I can't figure out what is going on. I am reading a file that simply has one number and checking to see if it is even. I know it is being read correctly because it prints out 10 when I call it to print dim. But then it says:
TypeError: not all arguments converted during string formatting
for the line in which I am testing to see if dim is even. I'm sure it's basic but I can't figure it out.
The readline method of file objects always returns a string; it will not convert the number into an integer for you. You need to do this explicitly:
dim = int(spiral.readline())
Otherwise, dim will be a string and doing dim % 2 will cause Python to try to perform string formatting with 2 as an argument:
>>> '10' % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>
Also, doing print(dim) outputed 10 instead of '10' because print automatically removes the apostrophes when printing:
>>> print('10')
10
>>>

Reading a float value from standard input and using in time.sleep

I'm currently struggling with simple code, it works with seconds but I want to allow users to use minutes instead, which is much easier. Here it is:
import time
import os
import math
import subprocess
input1 = raw_input("Broj minuta:")
min = input1 * 60
min1 = float(min)
print min1
time.sleep(min1)
os.system("shutdown")
I get this error:
Broj minuta:2
Traceback (most recent call last):
File "timer.py", line 8, in <module>
time.sleep(min)
TypeError: a float is required
When I try to convert it to float using code below, it says that sleep time is big, and it is, if I choose 2 minutes I get:
min = input1 * 60
min1 = float(min)
Broj minuta:2
2.22222222222e+59
Traceback (most recent call last):
File "timer.py", line 10, in <module>
time.sleep(min1)
OverflowError: sleep length is too large
input1 = raw_input("Broj minuta:")
raw_input returns a string. You need to convert that to a number, like this
input1 = int(raw_input("Broj minuta:"))
If you don't do this, let say if you enter 2, it will still be a string and you are doing
input * 60
which means '2' * 60, which is equal to '222222222222222222222222222222222222222222222222222222222222' and it is still a string. That's why time.sleep(min) complains that
TypeError: a float is required
In the second case, you are converting '222222222222222222222222222222222222222222222222222222222222' to a float properly, but the value is 2.22222222222e+59, which is tooo big for time.sleep.
(Your traceback must be out of date; it shows time.sleep(min) (in which case the error is justified), but your code has time.sleep(min1).)
The issue is that the result of raw_input is a string. When you write input1 * 60, you repeat the string 60 times (i.e. instead of 120, you get '222222222222222222222222222222222222222222222222222222').
You're performing the conversion too late. input1 is a string, and multiplying a string by an integer
min = input1 * 60
does string repetition: '12' * 60 == '12121212...
Instead, convert to float, then multiply:
min = float(input1) * 60
The variable returned by raw_input is a string.
To add more information to what is happening in your code, here is an example session.
In [1]: i = raw_input("Something")
Something20
In [2]: i
Out[2]: '20'
In [3]: type(i)
Out[3]: str
In [4]: i*60
Out[4]: '202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020'
In [5]: float(i*20)
Out[5]: 2.02020202020202e+39
Out [2] shows the string '20'. This is confirmed when we check the type of i, which is str.
Now, in Python, when you multiply a string with a number x, you get a string with x times the original string repeated.
This is what was happening in your code. Thus, as suggested in the other answer, you need to cast your input to a float.
Another, way of doing this (on Python 2.x) is to NOT use raw_input() and instead use input()
In [6]: j = input('Something else?')
Something else?20
In [7]: j
Out[7]: 20
In [8]: j*60
Out[8]: 1200

Python integer issues

EDIT: SOLVED--SOURCE CODE HERE: http://matthewdowney20.blogspot.com/2011/09/source-code-for-roku-remote-hack.html
thanks in advance for reading and possibly answering this. So I have a slice of code that looks like this (the commands Down() Select() and Up() are all predefined):
def c1(row):
row_down = row
row_up = row
while row_down > '1':
Down()
row_down = row_down - 1
time.sleep(250)
Select()
time.sleep(.250)
while row_up > '1':
Up()
row_up = row_up - 1
time.sleep(250)
So when I run this with either c1('3') or c1(3) (not jut 3, any number does this) it stops responding, no error or anything, but it executes the first Down() command, and it doesnt seem to get past the row_down = row_down - 1 . So i figure maybe it is stuck on time.sleep(.250), because it isnt executing the Select(), so if i remove time.sleep(.250) from the code i get an error like this:
Traceback (most recent call last):
File "test.py", line 338, in <module>
c1('3')
File "test.py", line 206, in c1
row_down = row_down - 1
TypeError: unsupported operand type(s) for -: 'str' and 'int'
this code snippet is part of a larger program designed for controlling the roku player from a computer, and so far everything has worked but this, which is to automate the typing in the search field, so that you do not have to continually scroll until you find a letter and select. c1(row) would be column 1 row x, if any of you would like the source code for the program over all, i would be happy to send it out. Anyway thanks for listening.
Perhaps you meant
while row_down > 1:
(note 1 is written without quotes). If so, call c1 with c1(3) not c1('3').
Also, in CPython (version 2, but not version 3) integers are comparable to strings, but the answer is not what you might expect:
3 > '1'
# False
When comparing any integer to any string, the integer is always less than string because (believe it or not!) i (as in integer) comes before s (as in string) in the alphabet.
As TokenMacGuy has already pointed out, addition of integers with strings raises a TypeError:
'3' - 1
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
This might explain the error you are seeing when calling c1('3').
>>> x = raw_input('enter a number: ')
enter a number: 5
>>> x
'5'
>>> type(x)
<type 'str'>
>>> x + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> type(int(x))
<type 'int'>
>>> int(x) + 5
10
>>>
(if you're using python3, use input instead of raw_input)
I suspect that the loop is running with out error because you can subtract from a character to change it: "b - 1 = a". (read edit) It also doesn't error is because, like Marcelo Cantos said in his comment, the first time.sleep is for 250 seconds, not .250 seconds. The error when you remove the time.sleep might be coming up when you subtract past the the ASCII character range since it runs through the loop a lot quicker without the time.sleep.
I hope that helps!
Edit: Actually, I think what I said works in C or something. In python, it doesn't work. The other stuff I said might shed some light though!

Unable to have a command line parameter in Python

I run
import sys
print "x \tx^3\tx^3+x^3\t(x+1)^3\tcube+cube=cube+1"
for i in range(sys.argv[2]): // mistake here
cube=i*i*i
cube2=cube+cube
cube3=(i+1)*(i+1)*(i+1)
truth=(cube2==cube3)
print i, "\t", cube, "\t", cube + cube, "\t", cube3, "\t", truth
I get
Traceback (most recent call last):
File "cube.py", line 5, in <module>
for i in range(sys.argv[2]):
IndexError: list index out of range
How can you use command line parameter as follows in the code?
Example of the use
python cube.py 100
It should give
x x^3 x^3+x^3 (x+1)^3 cube+cube=cube+1
0 0 0 1 False
1 1 2 8 False
2 8 16 27 False
--- cut ---
97 912673 1825346 941192 False
98 941192 1882384 970299 False
99 970299 1940598 1000000 False
Use:
sys.argv[1]
also note that arguments are always strings, and range expects an integer.
So the correct code would be:
for i in range(int(sys.argv[1])):
You want int(sys.argv[1]) not 2.
Ideally you would check the length of sys.argv first and print a useful error message if the user doesn't provide the proper arguments.
Edit: See http://www.faqs.org/docs/diveintopython/kgp_commandline.html
Here are some tips on how you can often solve this type of problem yourself:
Read what the error message is telling you: "list index out of range".
What list? Two choices (1) the list returned by range (2) sys.argv
In this case, it can't be (1); it's impossible to get that error out of
for i in range(some_integer) ... but you may not know that, so in general, if there are multiple choices within a line for the source of an error, and you can't see which is the cause, split the line into two or more statements:
num_things = sys.argv[2]
for i in range(num_things):
and run the code again.
By now we know that sys.argv is the list. What index? Must be 2. How come that's out of range? Knowledge-based answer: Because Python counts list indexes from 0. Experiment-based answer: Insert this line before the failing line:
print list(enumerate(sys.argv))
So you need to change the [2] to [1]. Then you will get another error, because in range(n) the n must be an integer, not a string ... and you can work through this new problem in a similar fashion -- extra tip: look up range() in the docs.
I'd like to suggest having a look at Python's argparse module, which is a giant improvement in parsing commandline parameters - it can also do the conversion to int for you including type-checking and error-reporting / generation of help messages.
Its sys.argv[1] instead of 2. You also want to makes sure that you convert that to an integer if you're doing math with it.
so instead of
for i in range(sys.argv[2]):
you want
for i in range(int(sys.argv[1])):

Categories