List index out of range ? It should not be - list

def trav(r,c):
#print("(",r,",",c,")")
ch = a[r+1][c+1]
lu= a[r][c]
#print(lu)
u = a[r][c+1]
#print(u)
ru= a[r][c+2]
#print(ru)
l = a[r+1][c]
#print(l)
r = a[r+1][c+2]
#print(r)
ld= a[r+2][c]
#print(ld)
d = a[r+2][c+1]
#print(d)
rd= a[r+2][c+2]
#print(rd)
a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = 0
if(ch == lu-1):
a1 = trav(r-1,c-1)
if(ch == u-1):
a2 = trav(r-1,c)
if(ch == ru-1):
a3 = trav(r-1,c+1)
if(ch == l-1):
a4 = trav(r,c-1)
if(ch == r-1):
a5 = trav(r,c+1)
if(ch == ld-1):
a6 = trav(r+1,c-1)
if(ch == d-1):
a7 = trav(r+1,c)
if(ch == rd-1):
a8 = trav(r+1,c+1)
return max(a1,a2,a3,a4,a5,a6,a7,a8) + 1
while(1):
row,col = [int(x) for x in input().split(" ")]
if(row == 0):
break
a = []
for index in range(10):
a.append([])
for jindex in range(10):
a[index].append('a')
b = []
for index in range(row):
str = input()
for jindex in range(col):
a[index+1][jindex + 1] = ord(str[jindex])
if(str[jindex] == 'A'):
b.append([index,jindex])
#print (a)
#print (b)
ans = max([trav(x[0],x[1]) for x in b])
print(ans)
The code is generating the following error
Traceback (most recent call last): File "C:/Users/DELL/Desktop/ABCPATH.py", line 80, in <module>
ans = max([trav(x[0],x[1]) for x in b]) File "C:/Users/DELL/Desktop/ABCPATH.py", line 80, in <listcomp>
ans = max([trav(x[0],x[1]) for x in b]) File "C:/Users/DELL/Desktop/ABCPATH.py", line 17, in trav
ld= a[r+2][c] IndexError: list index out of range
But according to me it should not, and as I am extremely new to python , I am not able to debug it. Please help
sample input taken:
4 3
ABC
CFG
BDH
ABC

It has to break
r = a[r+1][c+2]
you're reassigning the value of 'r' in that line. please also note that you shouldn't name your string "str" as it is the name of the python string module and you won't be able to use it.

Related

Google Sheets QUERY with WHERE on multiple columns at the same time

Following this post Google Sheets QUERY with WHERE on multiple columns I build up my formula to select specific values from more columns but when I had a condition data start to be confused and not equal to what I selected. I started from this query which works perfectly on one column for each IF:
=QUERY(Concerti!A1:AL; "SELECT * WHERE 1=1" &IF(A2="TUTTI";"";" AND E = '"&A2&"' ") &IF(E2="TUTTI";"";" AND H = '"&E2&"' ") &IF(F2="TUTTI";"";" AND B = "&F2&" "); 1)
Then I wrote this query to select (and filter) the content in A4, E4 and F4 but it doesn't work correctly i.e. it keeps some data which doesn't exactly match with the values on A4, E4 and F4.
=QUERY(Concerti!A1:AL; "SELECT * WHERE 1=1" &IF(A2="TUTTI";"";" AND E = '"&A2&"' ") &IF(E2="TUTTI";"";" AND H = '"&E2&"' ") &IF(F2="TUTTI";"";" AND B = "&F2&" ") &IF(A4="TUTTI";"";" AND I = ('"&A$4&"') OR (K='"&A$4&"' OR M='"&A$4&"' OR O='"&A$4&"' OR Q='"&A$4&"' OR S='"&A$4&"') ") &IF(E4="TUTTI";"";" AND J = ('"&E$4&"') OR (L='"&E$4&"' OR N='"&E$4&"' OR P='"&E$4&"' OR R='"&E$4&"' OR T='"&E$4&"') ") &IF(F4="TUTTI";"";" AND Y = ('"&F$4&"') OR (AA='"&F$4&"' OR AC='"&F$4&"' OR AE='"&F$4&"' OR AG='"&F$4&"' OR AI='"&E$4&"') "); 1)
Where is my mistake? Thank you so much in advance!!! I post a screenshot of the project:
[![Filtering mask](https://i.stack.imgur.com/cRFLv.png)](https://i.stack.imgur.com/cRFLv.png)
try:
=QUERY(Concerti!A1:AL; "where 1=1"&
IF(A2="TUTTI";;" and E = '"&A2&"'")&
IF(E2="TUTTI";;" and H = '"&E2&"'")&
IF(F2="TUTTI";;" and B = "&F2&" ")&
IF(A4="TUTTI";;" and (I = '"&A$4&"'
or K = '"&A$4&"'
or M = '"&A$4&"'
or O = '"&A$4&"'
or Q = '"&A$4&"'
or S = '"&A$4&"')")&
IF(E4="TUTTI";;" and (J = '"&E$4&"'
or L = '"&E$4&"'
or N = '"&E$4&"'
or P = '"&E$4&"'
or R = '"&E$4&"'
or T = '"&E$4&"')")&
IF(F4="TUTTI";;" and (Y = '"&F$4&"'
or AA= '"&F$4&"'
or AC= '"&F$4&"'
or AE= '"&F$4&"'
or AG= '"&F$4&"'
or AI= '"&E$4&"')"); 1)

printing sorted columns based on values in python

I have a CSV file with 11 columns. I am new to Python and trying to make a code that sorted column 2 alphabetically (string) and then prints the rows of the sorted list.
I only want the rows printed where column 1 == 1.
If column 1 == 0 then i want the script to ignore this row and continue on to the next line without printing it.
in_file = open('filename.csv', 'r')
dict = {}
#should print all rows where field [0] == 1
print('List of rows where column one is equal to zero in alphabetical order of column 2')
for line in in_file:
line = line.strip('\n')
fields = line.split(',')
c1 = fields[0]
c2 = fields[1]
c3 = fields[2]
c4 = fields[3]
c5 = fields[4]
c6 = fields[5]
c7 = fields[6]
c8 = fields[7]
c9 = fields[8]
c10 = fields[9]
c11 = fields[10]
if c2 not in dict:
dict[c2] = c1
if c3 not in dict:
dict[c3] = c1
if c4 not in dict:
dict[c4] = c1
if c5 not in dict:
dict[c5] = c1
if c6 not in dict:
dict[c6] = c1
if c7 not in dict:
dict[c7] = c1
if c8 not in dict:
dict[c8] = c1
if c9 not in dict:
dict[c9] = c1
if c10 not in dict:
dict[c10] = c1
if c11 not in dict:
dict[c11] = c1
name = dict.keys()
sorted_names = sorted(name)
for name in sorted_names:
c1 = dict[name]
rows = [row for row in in_file if row ['c1']!= 1]
for row in rows:
print(c3, c2, c4, c5)
in_file.close()
As you commented, the error pops up in the 'rows = [row for row in in_file if row ['c1']!= 1]' line. As far as i know, the error is really simple:
you input indices as strings, but they Always have to be integers, as the error says. for example: your index is ['c1'], but c1 is a variable. using [c1] would probably solve the problem.

chunk of data into fixed lengths chunks and then add a space and again add them all as a string

I have got hex values as a85b080040010000. I want it to be as a8 5b 08 00 40 01 00 00. I have done it by using below code. But I have to work with very large data. So I want computed time to be very low.
import binascii
import re
filename = 'calc.exe'
with open(filename, 'rb') as f:
content = f.readline()
text = binascii.hexlify(content)
text1 = binascii.unhexlify(text)
length1 = 32
length2 = 16
list = re.findall('.{%d}' % length1, text)
list1 = re.findall('.{%d}' % length2, text1)
d = []
for i in range (0, len(list), 1):
temp = ""
l = re.findall('.{%d}' % length2, list[i])
s = l[0]
t = iter(s)
temp += str(' '.join(a+b for a,b in zip(t, t)))
temp += " "
s = l[1]
t = iter(s)
temp += str(' '.join(a+b for a,b in zip(t, t)))
temp += " | " + list1[i]
print temp
You can simply do
x="a85b080040010000"
print re.sub(r"(.{2})",r"\1 ",x)
or
x="a85b080040010000"
print " ".join([i for i in re.split(r"(.{2})",x) if i])

raw_input() invalid syntax

I want to input a string of five numbers with spaces between them and use raw_input() for it. However the second item(the portion that's between the first and second spaces) is claimed to be a syntax error. Code below:
#class for final output - used as an ad hoc static string
class StatString:
outstring = ""
#function to check if Boom or Trach or both
def BoomTrach(num,B,T):
Boom = False
Trach = False
temp = num
while temp != 0:
if num % B == 0:
Boom == True
break
if (temp % 10) % B == 0:
Boom = True
break
temp = (temp - temp % 10) / 10
temp = num
while temp != 0:
if num % T == 0:
Trach = True
break
if (temp % 10) % T == 0:
Trach = True
break
temp = (temp - temp % 10) / 10
if Boom and Trach:
herestring.outstring = herestring.outstring + "Boom-Trach"
elif Boom:
herestring.outstring = herestring.outstring + "Boom"
elif Trach:
herestring.outstring = herestring.outstring + "Trach"
else:
herestring.outstring = herestring.outstring + str(num)
#start of "main" portion
def main():
inS = raw_input() <<<--- Input here
arr = inS.split(' ')
X = int(arr[0])
Y = int(arr[1])
CountFrom = int(arr[2])
jump = int(arr[3])
CountUntil = int(arr[4])
#variable for error check
error = False
#checking for errors
if X < 1 or X > 9 or Y < 1 or Y > 9:
print "X and Y must be between 1 and 9"
error = True
if jump == 0:
print "jump cannot be 0"
error = True
elif (CountUntil - CountFrom) % jump != 0:
print "cannot jump from %d to %d",CountFrom,CountUntil
error = True
if error:
exit()
if CountFrom < 0 and CountUntil < 0 and jump > 0:
jump = jump * (-1)
herestring = StatString()
while CountFrom != CountUntil:
BoomTrach(CountFrom,X,Y)
CountFrom = CountFrom + jump
if(CountFrom != CountUntil):
herestring.outstring = herestring.outstring + ","
print herestring.outstring
error message: (the second 1 was marked as the source of the error)
>>> 1 1 1 1 1
SyntaxError: invalid syntax
>>>
I know what happened. You just run this module, and you thought that you start running it from the main function (like in C for example).
There is no problem with the raw_input line (the first line of the input). The problem is that your module does not try to read anything! You just typed "1 1 1 1 1" which is of course syntax error...
Append to your code this line to run the main function:
main()
You can also write the code of the main function not in some function, to get the same effect.

How to consolidate if / elif statements in Python

I looked around and did some research, but for some reason I still couldn't get it to work as planned. Basically, as a beginner, I wrote a Mastermind code game- same rules and all. Here's the code:
import random
trial = 0
def geuss():
geuss = raw_input("What is your geuss? ")
global g1
global g2
global g3
global g4
a = geuss[:-3]
b = geuss[1:-2]
c = geuss[2:-1]
d = geuss[3:]
if a == peg1:
g1 = 'R'
elif a == peg2:
g1 = 'W'
elif a == peg3:
g1 = 'W'
elif a == peg4:
g1 = 'W'
else:
g1 = 'X'
if b == peg2:
g2 = 'R'
elif b == peg1:
g2 = 'W'
elif b == peg3:
g2 = 'W'
elif b == peg4:
g2 = 'W'
else:
g2 = 'X'
if c == peg3:
g3 = 'R'
elif c == peg1:
g3 = 'W'
elif c == peg2:
g3 = 'W'
elif c == peg4:
g3 = 'W'
else:
g3 = 'X'
if d == peg4:
g4 = 'R'
elif d == peg1:
g4 = 'W'
elif d == peg2:
g4 = 'W'
elif d == peg3:
g4 = 'W'
else:
g4 = 'X'
print g1, g2, g3, g4
global trial
trial = trial + 1
return trial
colour = ['B', 'G', 'Y', 'P', 'R']
peg1 = random.choice(colour)
peg2 = random.choice(colour)
peg3 = random.choice(colour)
peg4 = random.choice(colour)
g1 = 0
g2 = 0
g3 = 0
g4 = 0
print ""
while g1 != 'R' or g2 != 'R' or g3 != 'R' or g4 != 'R':
geuss()
print "Congratulations! It took you %d tries to crack the code!" % trial
print ""
print "The code was %s%s%s%s." % (peg1, peg2, peg3, peg4)
As you can see the if and elif statements in the function 'geuss()' are needlessly wrong- but when I tried putting them together the script would always put a W.
if a == peg1:
g1 = 'R'
elif a == peg2 or peg 3 or peg4:
g1 = 'W'
else:
g1 = 'X'
Even when I put "QWER" in as an input, I would get an X. Is there some way I can consolidate them while still getting the correct response?
Also, off topic, if there are any other suggestions you can give me on the script as I am a beginner, that would be much appreciated! Thank you!
When you use or or and, you need to specify which operation you are using. Here is what you wrote...
if a == peg1:
g1 = 'R'
elif a == peg2 or peg 3 or peg4:
g1 = 'W'
else:
g1 = 'X'
The elif in that asks if a is equal to peg2, and then if peg3 or peg4 exists. You need to change it so a == peg3/4 also. Like this...
elif a == peg2 or a == peg3 or a == peg4:
In regards to your if/elif question a typical Python idiom to use a dictionary for a switch statement.
// http://stackoverflow.com/questions/374239/why-doesnt-python-have-a-switch-statement
{'option1': function1,
'option2': function2,
'option3': function3,
'option4': function4,
}.get(value, defaultfunction)()
However, in this case I believe you are taking the wrong approach. "Thinking" in Python is a little different than other languages and takes awhile to get used to doing things "the Python way". You seem to understand lists, and string slices which is good. You can leverage that a bit more to simplify your Mastermind program as shown below.
import random
trial = 0
colour = ['B', 'G', 'Y', 'P', 'R']
pegs = [random.choice(colour), random.choice(colour), random.choice(colour), random.choice(colour)]
guess_pegs = ['?', '?', '?', '?']
def main():
print "Generating a code"
print pegs
guess()
print "Congratulations! It took you %d tries to crack the code!\n" % trial
print "The code was: " + ', '.join(pegs)
def guess():
global trial
global pegs
global guess_pegs
entry_list = ['?', '?', '?', '?']
while pegs != guess_pegs :
entry_list = raw_input("What is your guess? ").split(' ')
trial = trial + 1
if len(pegs) == len(entry_list) :
for i in range(0,4) :
if(entry_list[i] == pegs[i]) :
guess_pegs[i] = entry_list[i]
print guess_pegs
guess()
# Kick things off
main()
An experienced python programmer would write:-
elif a == peg2 or a == peg3 or a == peg4:
as:-
elif a in (peg2, peg3, peg4):