Run Time Error Exited with error status 1 - python

The problem is this :
I tried to solve it and I think I did too but when I mailed it for evaluation it says
We have tested your solution, and while doing so we unfortunately
discovered the following error:
Run Time Error
Exited with error status 1
Here is my code :
import re
import sys
def fun():
for ind in ratio:
max_num = ratio_list[0]
if ratio[ind] == max_num:
print ind
ratio_list.remove(ratio_list[0])
hits = []
song = []
n,m = raw_input().split(' ',1)
for i in range(0,int(n)):
h,n = raw_input().split(" ",1)
is_number = isinstance( int(h), int )
is_string = len(n)<=30 and bool(re.match('[a-z_0-9]+$', n))
if not(is_number and is_string):
sys.exit("Error");
hits.append(int(h))
song.append(n)
ratio = {}
ratio_list = []
f_of_i = hits[0]
counter = 1
index = 0
for hit in hits:
ratio_list.append(hit*counter)
ratio[song[index]] = hit*counter
index = index +1
counter = counter +1
ratio_list.sort()
ratio_list.reverse()
for j in range(0,int(m)):
fun()
What am I doing wrong ? I am curious why the solution is unacceptable killing me.

I suspect you're hitting
sys.exit("Error");
As explained in the documentation:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1.
Might be worth relaxing your input validation a little? Right now it's so strict it would reject inputs that to me appear within the spec (say if there were two spaces between the play count and the song title).
Another possibility is that your code raises an exception. On my machine this also results in an exit code of 1.
Finally, while not a bug, I think the way you reuse the variable called n is questionable style.

Related

Running Python recursion on large numbers doesn't output or throws exception

import sys
sys.setrecursionlimit(10**8)
T = dict()
def downToZero(n):
if n in T : return T[n]
if n==1 : return 1
T[n] = 1+downToZero(n-1)
return T[n]
x = int(input())
print(downToZero(x))
Here is the code and it works for numbers like 100,1000 but when you input large numbers like 10,000, the console neither gives output nor it throws an error
You probably get something like:
Process finished with exit code -1073741571 (0xC00000FD)
The error code 0xC00000FD indicates StackOverflow.
Setting max recursion level with setrecursionlimit to 10**8 doesn't actually change the limit to that number; highest possible limit is platform-dependent (and smaller).

Retry requests from an API that returns errors

I am requesting data from an API that returns back end errors occasionally. I have a list of identifiers that I hand to the apifunction by index to retrieve its respective data. The returned dataframe is stored.
x=0
while x <= 13000:
file_checked = Path("path\\%05d.pkl" % (x))
if file_checked.is_file():
print(str(x) + list_of_identifiers[x])
x += 1
else:
identifier = list_of_identifiers[x]
data = apifunction
data.to_pickle("path\\\\%05d.pkl" % (x))
print(str(x) + list_of_identifiers[x])
x += 1
The print command just gives me visual feedback on the progression. Checking if the file exists makes it easier for me to restart the loop as I don't have to set the x manually when my loop breaks.
And this is my big problem. The loop breaks. Occasionally the server returns back end errors of various different types (maybe around three different error codes).
Can someone help me to make this code (or alternative ways) robust to the mentioned errors? It should simply retry the same "x" and afterwards proceed. I should mention that from my experience the errors seem to occur arbitrarily which makes it highly unlikely that one could get stuck in an endless loop of retries.
Although I have found several posts on this topic, I was not able to transfer it to my problem.
Can someone comment on my current solution:
x=0
while x <= 13073:
file_checked = Path("path\\%05d.pkl" % (x))
if file_checked.is_file():
x += 1
else:
while x <= 13073:
try:
identifier = list_of_identifiers[x]
data = apifunction
data.to_pickle("path\\%05d.pkl" % (x))
x += 1
except:
print("Error")
continue

Please help me better understand this one "except"conditional line

I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)

If statement doesn't take place

I have been testing some my code and for some reason my if statement is being ignored. The first if statement works but the second if statement doesn't, i have tried changing it to elif and it still doesn't work. Thanks in advance.
import random
diff = input("What is the ritual difficulty? ")
level = input("How many ritual levels do you have that pertain to this ritual? ")
bag = []
for success in xrange(10):
bag.append("Success")
bag.append("Flaw")
bag.append("Fail")
extra = level - diff
if extra >= 1:
extra = extra / 2
int(extra)
for chance in xrange(extra):
bag.append("Success")
if extra < 0:
for chance in xrange(extra):
bag.append("Flaw")
bag.append("Fail")
bag.append("Backlash")
print bag
random.shuffle(bag)
outcome = bag.pop()
print "The outcome of the ritual is: ", outcome
You second if will be entered if the diff is larger than the level. However, even if it does get entered it won't actally do something:
if extra < 0:
for chance in xrange(extra):
bag.append("Flaw")
bag.append("Fail")
bag.append("Backlash")
The xrange function will yield an empty "list" (it's not actually a list, as the documentation for xrange explains) for negative values, i.e. nothing will be appended to the bag.
It is not ignored, but when you run a for loop on xrange(extra) with extra being negative, then obviously this loop is immediately terminated.
P.S.: you might wanna try xrange(-extra) instead...

Replacement value not working?

So I've got a try/except block set up, which will go through a database dependent on certain conditions:
try:
for searchnumber in itertools.count(0):
print searchnumber
c.execute("""SELECT words from searchterms where onstate = 1 AND progid = %d;""") % searchnumber
searchterms = (c.fetchall())
searchterms = [",".join(x) for x in searchterms]
print searchterms
except:
pass
For some reason, it isn't iterating on progid, in fact, it isn't even getting the first value assigned to it (0). Why would this be? As far as I know, %d should be replaced by the integer value of searchnumber
You're probably hiding a TypeError because you're trying to use the % operator on whatever object or value is equivalent to c.execute("string"). You might've caught it if you hadn't hidden all errors with the bare except. You'll note this is a specific antipattern in the official Python Dos and Don'ts page.
Never use except: pass, it hides information.
The information it's currently hiding is probably a failure from this code:
c.execute("""SELECT words from searchterms where onstate = 1 AND progid = %d;""") % searchnumber

Categories

Resources