Make a binary tree using lists - python

I am trying to make a binary tree using lists, but it is showing me this error, can you help me with this?
class BT:
def __init__(self, lp , data , rp):
self.LeftPointer = lp
self.data = data
self.RightPointer = rp
def insert(x):
#current_position
c = 0
#temporary_position
t = 0
while True:
if dsBT[c].data == None :
dsBT[c].data = x
break
elif x > dsBT[c].data:
if dsBT[c].RightPointer == 0:
t = c
while dsBT[t].data != None :
t += 1
dsBT[t].data = x
dsBT[c].RightPointer = t
break
else:
c = dsBT[c].RightPointer
else:
if dsBT[c].LeftPointer == 0:
t = c
while dsBT[t].data != None:
t += 1
dsBT[t].data = x
dsBT[c].LeftPointer = t
break
else:
c = dsBT[c].LeftPointer
**this part is for printing out the data **
dsBT = []
for j in range(2):
dsBT.append(BT( None ,None , None ))
for h in range(len(dsBT)):
#video game name
vgm = input(str("enter the game name:\n"))
insert(vgm)
for i in range(len(dsBT)):
print(dsBT[i].LeftPointer , dsBT[i].data ,dsBT[i].RightPointer)
the error it is showing:
enter the game name:
sarim
enter the game name:
dasr
Traceback (most recent call last):
File "C:\Users\workm\Desktop\Sarim\untitled0.py", line 44, in <module>
insert(vgm)
File "C:\Users\workm\Desktop\Sarim\untitled0.py", line 14, in insert
if dsBT[c].data == None :
TypeError: list indices must be integers or slices, not NoneType

Related

Dijkstra's shortest path

I'm VERY new to Python (self learning) and am writing some code, and have read as much as possible (both on this website and youtube) to figure it out, and I'm perplexed as to why it's not working for me
I've generated this dictionary of dictionaries (may not be most efficient, please let me know how to improve, been doing this a couple weeks only):
graphx = []
all_locs = []
def graph(width, height):
for r in range(height):
row = []
for c in range(width):
t = (r, c)
row.append(t)
all_locs.append(t)
graphx.append(row)
graph(width, height)
# # Builds a dictionary of all nodes, and their weight
weighted_grid = {}
for node in graphx:
for c in node:
n = {}
s = {}
e = {}
w = {}
if (c[0] < height) and (c[0] > 0):
n[c[0] + 1, c[1]] = 1
s[c[0] - 1, c[1]] = 1
elif c[0] == 0:
n[c[0] + 1, c[1]] = 1
elif c[0] == height:
s[c[0] - 1, c[1]] = 1
if c[1] < width and c[1] > 0:
e[c[0], c[1] + 1] = 1
w[c[0], c[1] - 1] = 1
elif c[1] == 0:
e[c[0], c[1] + 1] = 1
elif c[1] == height:
w[c[0], c[1] - 1] = 1
temp = {}
blank = {}
if n != blank:
temp[c[0] + 1, c[1]] = 1
if e != blank:
temp[c[0], c[1] + 1] = 1
if s != blank:
temp[c[0] - 1, c[1]] = 1
if w != blank:
temp[c[0], c[1] - 1] = 1
weighted_grid[c[0],c[1]] = temp
When I run dijikstras, using the the tuples as start and destination, I get an error. Here's the version of dijkstras I'm running:
def dijkstra(graph, start, goal):
shortest_distance = {} # records the current cost to reach that node.
track_predecessor = {} # keeps track of the path that led to this node.
unseen_nodes = graph # Iterate through the graph to check all nodes.
infinity = 99999 # Make it any large number,greater than possible path weights.
track_path = [] # gives us the trace-back path of the optimal route
for node in unseen_nodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
while unseen_nodes:
min_distance_node = None
for node in unseen_nodes:
if min_distance_node is None:
min_distance_node = node
elif shortest_distance[node] < shortest_distance[min_distance_node]:
min_distance_node = node
path_options = graph[min_distance_node].items()
for child_node, weight in path_options:
if weight + shortest_distance[min_distance_node] < shortest_distance[child_node]:
shortest_distance[child_node] = weight + shortest_distance[min_distance_node]
track_predecessor[child_node] = min_distance_node
unseen_nodes.pop(min_distance_node)
current_node = goal
while current_node != start:
try:
track_path.insert(0, current_node)
current_node = track_predecessor[current_node]
except KeyError:
break
track_path.insert(0, start)
if shortest_distance[goal] != infinity:
pass
The error I get is:
Traceback (most recent call last):
File "C:/Users/Dave/Desktop/Important/PycharmProjects/DMT2/dungeonmasterstome/Main.py", line 318, in <module>
dijkstra(weighted_grid, (0, 0), (0,1))
File "C:/Users/Dave/Desktop/Important/PycharmProjects/DMT2/dungeonmasterstome/Main.py", line 300, in dijkstra
if weight + shortest_distance[min_distance_node] < shortest_distance[child_node]:
KeyError: (0, 30)
Thoughts and thanks for any help and constructive criticism.

Check if graph is Bipartite

so I need to check if a Graph is Bipartite using Numpy arrays and Python 2
This is the code that I've developed to check the graph:
from __future__ import print_function
import numpy as np
class grafo:
visited = []
def __init__(self, n):
self.vertices = []
self.adjacency = np.zeros((n,n))
self.visited.append(True)
self.size = n
self.color = [-1] * self.size
self.color.append(0)
def isBipartita(self):
finalRes = str()
init = 0
self.color[init] = 1
self.visited.append(init)
while self.visited:
i = self.visited.pop()
print("[FIRST CHECK] adyacencia[" + str(i)+"][" + str(i) + "] == 1?")
if self.adjacency[i][i] == 1: //HERE IT CORRUPTS AT SOME POINT
finalRes = "NO"
print("True")
return finalRes;
for f in range(self.size):
print("[SECOND CHECK] adyacencia[" + str(i)+"][" + str(f) + "] == 1 and color[" + str(f) +"] == -1")
if self.adjacency[i][f] == 1 and self.color[f] == -1:
print("True")
self.color[f] = 1 - self.color[i]
self.visited.append(f)
else:
print("[THIRD CHECK] adyacencia[" + str(i)+"][" + str(f) + "] == 1 and color[" + str(f) +"] == color[" + str(i) +"]")
if self.adjacency[i][f] == 1 and self.color[f] == self.color[i]:
print("True")
finalRes = "NO"
return finalRes
finalRes = "YES"
return finalRes
def __str__(self):
return str(self.adjacency)
#PROGRAM
lenV = raw_input("") #This is the length of the Adjacency array for the graph
lenV = int(lenV)
inputs = []
for i in range(0, lenV):
inputs.append(raw_input())
print("\n-> Inputs:")
print(inputs)
print("\n-> List with Inputs Values:")
tempVal = list()
for numC in inputs:
tempVal.append(numC)
print(tempVal)
print("\n-> Split and get into array:")
G = grafo(lenV)
for x in range(0,lenV):
tempList = list(tempVal[x])
print(tempList)
for y in range(0, lenV):
G.adjacency[x][y] = tempList[y]
print("\n-> Array to check:")
print(G)
print("\n")
print(G.isBipartita())
The problem is in the class "grafo", in the isBipartita method; at some point while checking, the numpy integer array returns a boolean and gives a ValueError as an output.
This are some examples that I've used to test this:
TEST CASES
3
011
101
110
4
0101
1010
0101
1010
and this is the output that I get:
/** LIKE 20 SUCCESSFUL CHECKS LATER **/
[SECOND CHECK] adyacencia[1][3] == 1 and color[3] == -1
[THIRD CHECK] adyacencia[1][3] == 1 and color[3] == color[1]
[FIRST CHECK] adyacencia[True][True] == 1?
Traceback (most recent call last):
File "bipartitaChecker.py", line 76, in <module>
print(G.isBipartita())
File "bipartitaChecker.py", line 23, in isBipartita
if self.adjacency[i][i] == 1:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
As you can see, before the Traceback call, the last "[FIRST CHECK]" has adyacencia[True][True], and this is not intended to be this way... I have done research on the ValueError, but everything leads me to a point where only in some foreign cases this error is presented, but in my case it shouldn't be causing it...
I don't know what is happening?!
I'll appreciate any help.

TypeError: 'int' object is not subscriptable (nested functions)

So, whenever I call a function that calls another function I get this TypeError and I don't know why because it doesn't happen when I call first function. Here's the code:
def codeChar(c,key):
k = ord(c) + key
if key > 26:
key = key % 26
if 91 <= k <= 96:
k = k - 26
elif 123 <= k:
k = k - 26
c = chr(k)
return c
def codeBlock(word,key):
i = 0
result = ""
while i < len(word):
k = int(key[i])
result = result + codeChar(word[i],k)
i = i + 1
return result
def isletter(h):
i = ord(h)
if 65 <= i <= 90:
return True
elif 97 <= i <= 122:
return True
else:
return False
def codeString(string,key):
i = 0
result = ""
while i < len(string):
k = int(key[i])
if isletter(string[i]) == True:
result = result + codeBlock(string[i],k)
i = i + 1
else:
i = i + 1
return result
print(codeString(input("Enter a sentence to be coded: "),input("Enter an 8 digit key: ")))
The error code received when I run it is this:
Enter a sentence to be coded: Hello world
Enter your student number: 16061226
Traceback (most recent call last):
File "E:\cw.1\cw.1.py", line 89, in <module>
print(codeString(input("Enter a sentence to be coded: "),input("Enter your student number: ")))
File "E:\cw.1\cw.1.py", line 82, in codeString
result = result + codeBlock(string[i],k)
File "E:\cw.1\cw.1.py", line 39, in codeBlock
k = key[i]
TypeError: 'int' object is not subscriptable
Thanks in advance!
When you pass k to codeBlock on line 36, it's an integer, rather than the string that your function is expecting. Perhaps you intended to use key here instead?
It has nothing to do with calling a function from another function. When you call codeBlock from within codeString, you pass it a parameter k, which is an integer. On the other side, with key in the codeBlock function, you try to index into that integer by doing int(key[i]), hence the typeError.

Python crashes with large number of inputs

I am trying to run a python program with a large number of inputs.
It works with 1k inputs, but when I try 1M it just freezes forever.
This is how I read the inputs:
This is my main:
def main():
global raiz
inputs = raw_input()
output = []
inputs = inputs.lower()
split = inputs.split(" ")
while (inputs!=""):
if (split[0] == "pass"):
if (split[2] == "r"):
novo = No(split[1].upper(), 1, True)
else:
novo = No(split[1].upper(), 1, False)
if raiz == None:
raiz = novo
else:
encontraNo(novo)
elif (split[0] == "status"):
if (raiz == None):
output.append(split[1].upper()+" NO RECORD")
else:
novo = No(split[1].upper(), 0, False)
output.append(procuraStatus(novo))
elif (split[0] == "unflag"):
if (raiz != None):
novo = No(split[1].upper(),0, False)
actualizaEstado(novo)
inputs = raw_input()
inputs = inputs.lower()
split = inputs.split(" ")
for out in output:
print out
main()
Is there a limit of inputs I can "feed" to my program?
I am using Wing IDE 5.0.
I can post the rest of my code, but I dont think that this problem is related to it but rather related with a limit of inputs that I can give to a python program
EDIT:
I've tryed running it on the console, and it worked fine with the 50k inputs.
However, when I run with 1 million inputs and left it to work (for about 2 hours), I got no results, so I stopped the program. Here is what I got in the console:
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>python TP2C.py
Traceback (most recent call last):
File "TP2C.py", line 210, in <module>
main()
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>python TP2C.py < F50K.txt
A15833 5 R
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>python TP2C.py < F1M.txt
Traceback (most recent call last):
File "TP2C.py", line 210, in <module>
main()
File "TP2C.py", line 191, in main
encontraNo(novo)
File "TP2C.py", line 84, in encontraNo
valor_matricula_noActual = ''.join(str(ord(c)) for c in so)
File "TP2C.py", line 84, in <genexpr>
valor_matricula_noActual = ''.join(str(ord(c)) for c in so)
KeyboardInterrupt
C:\Users\Tomás\Documents\Engenharia Informática\PYTHON>
This is my full code, in case you want to check it out...
class No_Avl(object):
def __init__(self, matricula, estado, numero):
self.filhoDireito = None
self.filhoEsquerdo = None
self.matricula = matricula
self.numero = numero
self.estado = estado
self.altura = 0
class Arvore_Avl(object):
global raiz
def __init__(self):
global raiz
raiz = None
def altura(self,noActual):
if (noActual == None):
return (-1)
return noActual.altura
def adicionaNoo(self, matricula, estado, numero):
global raiz
raiz = self.adicionaNo(matricula, estado, numero, raiz)
def adicionaNo(self,matricula, estado, numero, noActual):
if (noActual == None):
noActual = No_Avl(matricula, estado, numero)
elif (noActual != None):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
s = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in s)
if(valor_matricula < valor_matricula_noActual):
noActual.filhoEsquerdo = self.adicionaNo(matricula, estado, numero, noActual.filhoEsquerdo)
if (self.altura(noActual.filhoEsquerdo) - self.altura(noActual.filhoDireito) == 2):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
s = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in s)
if (valor_matricula < valor_matricula_noActual):
noActual = self.rotateWithLeftChild(noActual)
else:
noActual = self.doubleWithLeftChild(noActual)
elif (valor_matricula > valor_matricula_noActual):
noActual.filhoDireito = self.adicionaNo(matricula, estado, numero, noActual.filhoDireito)
if (self.altura(noActual.filhoDireito) - self.altura(noActual.filhoEsquerdo) == 2):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
s = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in s)
if (valor_matricula > valor_matricula_noActual):
noActual = self.rotateWithRightChild(noActual)
else:
noActual = self.doubleWithRightChild(noActual)
else:
return None
noActual.altura = max(self.altura(noActual.filhoEsquerdo), self.altura(noActual.filhoDireito)) +1
return noActual
def encontraNoo(self, matricula):
global raiz
return self.encontraNo(matricula, raiz)
def encontraNo(self, matricula, noActual):
while (noActual != None):
s = matricula
valor_matricula = ''.join(str(ord(c)) for c in s)
so = noActual.matricula
valor_matricula_noActual = ''.join(str(ord(c)) for c in so)
if (valor_matricula < valor_matricula_noActual):
noActual = noActual.filhoEsquerdo
elif (valor_matricula > valor_matricula_noActual):
noActual = noActual.filhoDireito
else:
return noActual
return None
def rotateWithLeftChild(self, k2):
k1 = k2.filhoEsquerdo
k2.filhoEsquerdo = k1.filhoDireito
k1.filhoDireito = k2
k2.altura = max(self.altura(k2.filhoEsquerdo), self.altura(k2.filhoDireito))+1
k1.altura = max(self.altura(k1.filhoEsquerdo), k2.altura) +1
return k1
def rotateWithRightChild(self, k1):
k2 = k1.filhoDireito
k1.filhoDireito = k2.filhoEsquerdo
k2.filhoEsquerdo = k1
k1.altura = max(self.altura(k1.filhoEsquerdo), self.altura(k1.filhoDireito))+1
return k2
def doubleWithLeftChild(self, k3):
k3.filhoEsquerdo = rotateWithRightChild(k3.leftChild)
return rotateWithLeftChild(k3)
def doubleWithRightChild(self, k1):
k1.filhoDireito = rotateWithLeftChild(k1.filhoDireito)
return rotateWithRightChild(k1)
def main():
global raiz
arvore = Arvore_Avl()
inputs = raw_input()
inputs = inputs.lower()
split = inputs.split(" ")
while (inputs!=""):
if (split[0] == "pass"):
if(arvore.encontraNoo(split[1]) != None):
arvore.encontraNoo(split[1]).numero += 1
arvore.encontraNoo(split[1]).estado = split[2]
else:
arvore.adicionaNoo(split[1], split[2], 1)
elif (split[0] == "status"):
mat = split[1]
if (arvore.encontraNoo(mat)!= None):
print(split[1].upper() + " "+ str(arvore.encontraNoo(split[1]).numero) + " "+arvore.encontraNoo(split[1]).estado.upper())
else:
print(split[1].upper()+" NO RECORD")
elif (split[0] == "unflag"):
if (arvore.encontraNoo(split[1]) != None):
arvore.encontraNoo(split[1]).estado = "R"
inputs = raw_input()
inputs = inputs.lower()
split = inputs.split(" ")
main()

Can't return an element in python at a certain position on a grid

i am a beginner to Python and i'm having some problem with a project.
My grid looks like this :
class World(object):
def __init__(self):
self.grid = []
xsize = 20
ysize = 20
self.maxX = xsize
self.maxY = ysize
for irow in range(self.maxY):
row = []
for icol in range(self.maxX):
row.append(None)
self.grid.append(row)
positions = []
for i in range(self.maxX):
for j in range(self.maxY):
positions.append((i,j))
numteam1 = 0
numteam2 = 0
numrobot = 0
randpos = random.sample(positions, numteam1 + numteam2)
team1 = randpos[0:numrobot-1]
team2 = randpos[numrobot:]
for point in team1:
x = point[0]
y = point[1]
self.grid[y][x] = AttackRobot(1, x, y, self)
self.grid[y][x] = MedicRobot(1, x, y, filename)
for point in team2:
x = point[0]
y = point[1]
self.grid[y][x] = AttackRobot(2,x,y,self)
self.grid[y][x] = MedicRobot(2,x,y,self, filename)
and then i have this method:
def test_position(self, x, y):
if x <0 or x >= 20:
return None
if y <0 or y >= 20:
return None
else:
return ( self.grid[y][x] = Robot)
this fonction is supposed to return element at (x,y) on the grid
Then i use this method in this method :
def print_board(w):
print "-" * 60
for y in range(19,-1,-1):
line = ""
for x in range(0,20):
r = w.test_position(x, y)
if r == None:
line += ".... "
else:
if isinstance(r, AttackRobot):
rtype = "A"
elif isinstance(r, MedicRobot):
rtype = "M"
else:
rtype = "!"
if r.get_team() == 1:
line += "%s%02i%s " % (rtype, r.get_health(), r.get_direction())
else:
line += "%s%02i%s " % (rtype.lower(), r.get_health(), r.get_direction())
print line
print "-" * 60
and i get an error.
Traceback (most recent call last):
File "T05.py", line 10, in <module>
print_board(world)
File "/Users/quentindumoulin/Desktop/test.py", line 19, in print_board
if r.get_team() == 1:
AttributeError: 'bool' object has no attribute 'get_team'
return ( self.grid[y][x] = Robot)
What is it? Maybe you want
return self.grid[y][x]
?

Categories