runtime error(nzec) in python - python-2.7

It works fin in my pc and in an online compiler+debugger. However, when I submit it in codechef, it gives me a runtime error(nzec). When do you get a runtime error and how to you resolve it. What is the problem in this code? I keep getting runtime error very frequently. How do I avoid it? Any kind of help will be deeply appreciated!
t = int(raw_input())
for i in range(t):
a = map(int, raw_input())
if a.index(min(a)) != 0:
if min(a) == 0:
print a.index(min(a))
else:
print str(str(a.index(min(a))) * (min(a)+1))
elif a.index(min(a)) == 0:
k = min(a)
a[0] = 99
l = min(a)
if l == k:
print str(str(a.index(min(a))) * min(a))
elif l > k:
print '1'+ ('0' * (k+1))

You have to split the raw_input()
raw_input() receives the input as just a string. Use raw_input().split() to convert the string to a list. Else you will have indexing problems, since the spaces given in the input are taken for mapping. So you get the nzec (non-zero exit code) error
a=map(int,raw_input().split())
will do

Many times it is due to some white places left.
Try this:
raw_input().strip().split(" ")
if the data is separated by " ".

Related

For-loop error: list index out of range

So I am rather new to programming and just recently started with Classes and we are supposed to make a phonebook that can be loaded in seperate text files.
I however keep running into the problem in this section that when I get into the for-loop. It hits a brick wall on
if storage[2] == permaStorage[i].number:
And tells me "IndexError: list index out of range". I am almost certain it is due to permaStorage starts out empty, but even when I attempt to fill it with temporary instances of Phonebook it tells me it out of range. The main reason it is there is to check if a phone number already exists within the permaStorage.
Anyone got a good tip on how to solve this or work around it?
(Sorry if the text is badly written. Just joined this site and not sure on the style)
class Phonebook():
def __init__(self):
self.name = ''
self.number = ''
def Add(name1, number1):
y = Phonebook()
y.name = name1
y.number = number1
return y
def Main():
permaStorage = []
while True:
print " add name number\n lookup name\n alias name newname\n change name number\n save filename\n load filename\n quit\n"
choices = raw_input ("What would you like to do?: ")
storage = choices.split(" ")
if storage[0] == "add":
for i in range(0, len(permaStorage)+1):
if storage[2] == permaStorage[i].number:
print "This number already exists. No two people can have the same phonenumber!\n"
break
if i == len(permaStorage):
print "hej"
try:
tempbox = Add(storage[1], storage[2])
permaStorage.append(tempbox)
except:
raw_input ("Remember to write name and phonenumber! Press any key to continue \n")
I think problem is that permaStorage is empty list and then u try to:
for i in range(0, len(permaStorage)+1):
if storage[2] == permaStorage[i].number:
will cause an error because permaStorage has 0 items but u trying to get first (i=0, permaStorage[0]) item.
I think you should replace second if clause with first one:
for i in range(0, len(permaStorage)+1):
if i == len(permaStorage):
print "hej"
try:
tempbox = Add(storage[1], storage[2])
permaStorage.append(tempbox)
if storage[2] == permaStorage[i].number:
print "This number already exists. No two people can have the same phonenumber!\n"
break
So in this case if perStorage is blank you will append some value and next if clause will be ok.
Indexing starts at zero in python. Hence, a list of length 5 has the last element index as 4 starting from 0. Change range to range(0, len(permastorage))
You should iterate upto the last element of the list, not beyond.
Try -
for i in range(0, len(permaStorage)):
The list of numbers produced in range() is from the start, but not including the end, so range(3) == [0, 1, 2].
So if your list x has length 10, range(0, len(x)) will give you 0 through 9, which is the correct indices of the elements of your list.
Adding 1 to len(x) will produce the range 0 through 10, and when you try to access x[10], it will fail.

Q: Python3 - If Statements for changing list lengths

I am attempting to analyze data sets as lists of differing lengths. I am calling lines (rows) of my data set one by one to be analyzed by my function. I want the function to still be run properly regardless of the length of the list.
My Code:
f = open('DataSet.txt')
for line in iter(f):
remove_blanks = ['']
entries = line.split()
''.join([i for i in entries if i not in remove_blanks])
trash = (entries[0], entries[1])
time = int(entries[2])
column = [int(v) for v in entries[3:]]
def myFun():
print(entries)
print_string = ''
if column[0] == 100:
if column[1] >= 250 and column[2] == 300:
if len(column) >= 9:
digit = [chr(x) for x in column[4:9]]
print_string = ('code: ' + ''.join(str(digit[l]) for l in range(5)) + ' ')
if len(column) >= 13:
optional_digit = [chr(d) for d in column[9:13]]
for m in range(0, 4):
print_string += 'Optional Field: ' + optional_digit[m] + ''
else:
print_string += 'No Optional Field '
pass
pass
print(print_string)
print('')
myFun()
f.close()
What is happening is if the length of a line of my data is not long enough (i.e. the list ends at column[6]), I get the error:
line 17, in function
print('Code: ' + digit[l])
IndexError: list index out of range
I want it to still print Code: #number #number #number #number and leave any non-existent columns as blanks when it is printed so that one line may print as Code: ABC9 and the next print as Code: AB if there are differing list lengths.
Please help! :)
Well, just make sure you're not looping over a list longer than available:
print_string = 'code: ' + ''.join(str(digit[l]) for l in range(min(5, len(digit)))) + ' '
or better:
print_string = "code {} ".format("".join(str(dig) for dig in digit[:5]))
Although I have a feeling you're over-complicating this.

Finding 2 numbers and send a message about it

I need to find 2 random numbers from 1-100 and send a message:
to high or to low according to the random number,
This is the code I wrote..., it doesn't work after the first if...,
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while guess != a:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = raw_input("guess a new number:")
from random import randint
a = randint(1, 101)
guess = input("guess the number:")
while True:
if guess > a:
print "your guess is too high"
elif guess < a:
print "your guess is too low"
else:
print 'You are correct'
break
guess = input("guess again:")
If I understood correctly your aim this code will work. It will stop when he guesses correctly the number. You had many mistakes with input and int. For future reference - if you use input() instead of raw_input() it will automatically pick the right type for the var.
In order to make your code work as intended just fix the input:
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while True:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = input("guess a new number:") #not raw_input()

Convert from decimal to binary - python

I'm having an issue with this piece of code I wrote. I'm trying to convert an integer input and print an output with its equivalent in binary base. For example for 5 it should drop an output of '101' however it just prints '10' like if it doesn't take into account the last digit. Please any comments would be greatly appreciated
T = raw_input()
for i in range(0, int(T)):
n = raw_input()
dec_num = int(n)
cnv_bin = ''
while dec_num//2 > 0:
if dec_num%2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
dec_num = dec_num//2
print cnv_bin[::-1]
while dec_num//2 > 0:
should be:
while dec_num > 0:
The first time through the loop, 5//2==2, so it continues.
The second time through the loop, 2//2==1, so it continues.
The third time, 1//2==0 and the loop quits without handling the last bit.
Also, you can just do the following to display a number in binary:
print format(dec_num,'b')
Format string version:
print '{0} decimal is {0:b} binary.'.format(5)
Why not use the build-in function bin()?
eg:
bin(5)
output
0b101
If you don't want the prefix(0b), you can exclude it.
bin(5)[2:]
hope to be helpful!
import math
def roundup(n):
return math.ceil(n)
D = eval(input("Enter The Decimal Value: "))
n = roundup(math.log2(D+1))-1
bi = 0
di = D
qi = 0
i = n
print("Binary Value:",end = " ")
while(i>=0):
qi = math.trunc(di/2**i)
bi = qi
print(bi,end = "")
di = di - bi*(2**i)
i = i-1

Difficulty with solving sudoku puzzle

I was stuck solving a sudoku puzzle with python.I am solving it using the method of backtracking error.My Code is implementing this method correctly upto some number of elements.But after some element it is not moving to the next empty cell to implement this,but it is staing at that particular cell.I think my function to check whether a value is valid at a position is working correctly.I was not able to figure out the mistake I was doing. Can someone help me regarding this.
code:
from numpy import *
def isValid(matrix,row,col):
element = matrix[row][col]
#print element
#print where(matrix[row,:] == element)
if len(where(matrix[row,:] == element)[0]) == 1 and len(where(matrix[:,col] == element)[0]) == 1:
#print 'entered'
row_type = row%3;col_type =col%3
row_index = row-row_type;col_index = col-col_type
if len(where(matrix[row_index:row_index+3,col_index:col_index+3])[0] == 1):
return 1
else:
return 0
else :
return 0
sudoku = loadtxt('1')
sudoku = array(sudoku,dtype = int)
blankRow,blankCol = where(sudoku == 0)
i=0
while i< len(blankRow):
print 'i:',i
#print 'entered'
while sudoku[blankRow[i],blankCol[i]] < 9:
#print 'entered',sudoku[blankRow[i],blankCol[i]]
sudoku[blankRow[i],blankCol[i]] += 1
#j = sudoku[blankRow[i],blankCol[i]]
valid = isValid(sudoku,blankRow[i],blankCol[i])
if valid == 1:
break
if sudoku[blankRow[i],blankCol[i]] == 9 and valid != 1:
print 'entered' #invalid,i:',i,'j',j,'row:',blankRow[i],'col:',blankCol[i]
sudoku[blankRow[i],blankCol[i]] = 0
i-= 1
i+=1
Your backtracking never works, because you unconditionally add 1 to i at the end of the outer loop. I think you want to put that increment in an else block, attached to the if just above it:
if sudoku[blankRow[i],blankCol[i]] == 9 and valid != 1:
print 'entered' #invalid,i:',i,'j',j,'row:',blankRow[i],'col:',blankCol[i]
sudoku[blankRow[i],blankCol[i]] = 0
i-= 1
else: # add this!
i+=1 # indent this!
Note that you might need to add some additional checking to make your code behave properly if it is given an unsolvable puzzle. In that situation, i will become negative, as it backtracks past the first position. This won't actually lead to an immediate error, as you can index a list or array with a negative value, but it will eventually raise an exception after trying (and failing) to solve the puzzle again several times.