Python crashes with large number of inputs - python

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()

Related

use class to make dec_to_bin function

I had to hand in a python project for my school and I completely skipped it, so I'm a week late. I'm not sure if anyone can help me with this, but I know that is so easy for some people so it would be great to have someone help me because I have to hand it in as soon as possible.
The subject (translated from french to english so maybe some errrors): https://docs.google.com/document/d/17S_vqe7oqFsBjpP5ACIS5371a4t9eiOpxnPuMwlnj5Q/edit?usp=sharing
I already make part 1.
--> I need help on part 2, I already made the dec_to_bin function which return correctly binary but i don't know how to use a class to made that function like i had to do:
def dec_to_bin(n):
if n >= 1:
dec_to_bin(n // 2)
print(n % 2, end = '')
if __name__ == '__main__':
dec_val = 123456
dec_to_bin(dec_val)
My 2 previous class :
class Cellule:
def __init__(self, valeur, precedent=None, suivant=None):
self.valeur = valeur
self.precedent = precedent
self.suivant = suivant
class File:
def __init__(self):
self.longueur = 0
self.debut = None
self.fin = None
def estVide(self):
return self.longueur == 0
def enfiler(self, valeur):
if self.longueur == 0:
self.debut = self.fin = Cellule(valeur)
else:
self.fin = Cellule(valeur, self.fin)
self.fin.precedent.suivant = self.fin
self.longueur += 1
def defiler(self):
if self.longueur > 0:
valeur = self.debut.valeur
if self.longueur > 1:
self.debut = self.debut.suivant
self.debut.precedent = None
else:
self.debut = self.fin = None
self.longueur -= 1
return valeur
def __str__(self):
ch = "\nFile actuelle:\n"
cellule = self.debut
while cellule != None:
ch += str(cellule.valeur) + " "
cellule = cellule.suivant
return ch
and
class Cellule:
def __init__(self, valeur, suivant=None):
self.valeur = valeur
self.suivant = suivant
class Pile:
def __init__(self):
self.taille = 0
self.sommet = None
def estVide(self):
return self.taille == 0
def empiler(self, valeur):
self.sommet = Cellule(valeur, self.sommet)
self.taille += 1
def depiler(self):
if self.taille > 0:
valeur = self.sommet.valeur
self.sommet = self.sommet.suivant
self.taille -= 1
return valeur
def lsommet(self):
return self.sommet.valeur
def __str__(self):
ch = "\nEtat de la pile:\n"
sommet = self.sommet
while sommet != None:
ch += "|\t" + str(sommet.valeur) + "\t|" + "\n"
sommet = sommet.suivant
return ch

Make a binary tree using lists

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

Def function and printing on one line in a for loop python 3

I have a line function here and this is only one of the functions and parts is a dictionary
#! /usr/bin/python3
from sleep import sleep
from read_lines import read_lines
import arduino
import sys
import time
variables = {}
commands = {}
contin = True
ci = 0
i = 0
def cmd_credits(parts):
print('Written by Drew')
def cmd_connect(parts):
arduino.connect()
def cmd_disconnect(parts):
arduino.disconnect()
def cmd_date(parts):
print(time.strftime("%Y-%m-%d"), end=' ')
sys.stdout.flush()
def cmd_dec(parts):
global variables
value = parts[1]
variables[value] = variables[value] -1
def cmd_inc(parts):
global variables
value = variables.get(parts[1])
value += 1
variables[parts[1]] = value
def cmd_input(parts):
global variables
if parts[1] == 'int':
variables[parts[2]] = int(input())
elif parts[1] == 'float':
variables[parts[2]] = float(input())
elif parts[1] == 'string':
variables[parts[2]] = input()
else:
print('Unkonwn command')
def cmd_jump(parts):
global lines
global ci
ci = ci + int(parts[1]) -1
def cmd_jumpeq(parts):
global lines
global variables
global ci
if variables.get(parts[1][1]) == int(parts[2]):
ci = ci + int(parts[3]) -1
def cmd_jumpneq(parts):
global lines
global variables
global ci
if variables.get(parts[1][1]) != int(parts[2]):
ci = ci + int(parts[3]) -1
def cmd_print(parts):
global variables
for i in range(1, len(parts)):
if parts[i][0] == '$':
print(variables[parts[i][1]])
else:
print(parts[i])
def cmd_println(parts):
print(variables[parts])
print(" ")
def cmd_receive(parts):
global variables
i = arduino.receive()
variables['x'] = i
def cmd_sleep(parts):
x = float(parts[1])
if parts[2] == 's':
time.sleep(x)
elif parts[2] == 'm':
x = x * 60
time.sleep(x)
elif parts[2] == 'h':
x = x * 60 * 60
time.sleep(x)
elif parts[2] == 'ms':
x = x/1000
time.sleep(x)
else:
print('Invalid format')
def cmd_send(parts):
sep = ' '
lst = parts[1:]
command_sent = sep.join(lst)
arduino.send(command_sent)
def cmd_setint(parts):
global variables
if parts[2][0] == '$':
variables[parts[1]] = variables[parts[2][1]]
else:
variables[parts[1]] = int(parts[2])
def cmd_time(parts):
print(time.strftime("%I:%M:%S"), end=' ')
sys.stdout.flush()
def process_cmdline_args():
lines = []
for fileName in sys.argv[1:]:
file = open(fileName)
while True:
line = file.readline()
line = line.strip()
if not line:
break
lines.append(line)
file.close()
return lines
def cmd_unknown(parts):
print('Unknown command:', parts)
def do_cmd(line):
global commands
cmdParts = line.split()
while i in variables:
if i[0] == '$':
cmdParts = variables.append('i')
else:
cmdParts = variables
cmdName = cmdParts[0]
cmd = commands.get(cmdName, cmd_unknown)
cmd(cmdParts)
# print(cmd)
def initialize():
global commands
commands = {'input' : cmd_input, 'jumpneq' : cmd_jumpneq, 'jumpeq' : cmd_jumpeq, 'dec' : cmd_dec, 'inc' : cmd_inc, 'println' : cmd_println, 'receive' : cmd_receive, 'credits' : cmd_credits, 'date' : cmd_date, 'time' : cmd_time, 'sleep' : cmd_sleep, 'connect' : cmd_connect, 'disconnect' : cmd_disconnect, 'send' : cmd_send, 'jump' : cmd_jump, 'setint' : cmd_setint, 'print' : cmd_print}
def main():
global lines
global contin, ci
initialize()
lines = process_cmdline_args()
if not lines:
lines = read_lines()
ci = 0
contin = True
while contin:
if ci >= len(lines):
contin = False
else:
line = lines[ci]
ci = ci + 1
do_cmd(line)
print()
if __name__ == '__main__':
main()
after starting the function if I were to enter a command like
> print Please enter your name:
> input string name
> print Hi, $name
The output would be
Please
enter
your
name:
Drew
How would I get this to print on one line? and get the println function working?

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]
?

Linebreak not working - Python

Somehow the linebreaks are not working as they should.
This is what I get:
Expected:
O meu u2 2 post
http://www.yahoo.com
1 Gosto, 0 Nao gosto
<BLANKLINE>
O meu u2 post
http://www.altavista.com
1 Gosto, 0 Nao gosto
Got:
'O meu u2 2 post\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto\n\nO meu u2\nhttp://www.yahoo.com\n1 Gosto, 0 Nao Gosto'
This is the code used in the function.
The important parts should be the str and showRecentComments functions
class Comments():
def __init__(self, u=None, text='', link=None):
self.u = u
self.text = text
self.link = link
self.topo = None
self.fim = None
def __str__(self):
actual = self.topo
s = ''
if actual == None:
return None
while actual != None:
if actual.seg == None:
s += str(actual)
actual = actual.seg
else:
s += str(actual) + '\n' + '\n'
actual = actual.seg
return s
def add(self,comment):
if self.topo == None:
self.topo = comment
self.fim = comment
else:
comment.seg = self.topo
self.topo.ant = comment
self.topo = comment
def remove(self,comment):
actual = self.topo
if (self.topo == self.fim) and (self.topo == comment):
self.topo = None
self.fim = None
while actual!=None:
if actual == comment:
if self.topo==comment:
actual.seg.ant = None
self.topo = actual.seg
elif self.fim==comment:
actual.ant.seg = None
self.fim = actual.ant
else:
actual.seg.ant = actual.ant
actual.ant.seg = actual.seg
break
else:
actual = actual.seg
def countLike(self):
count = 0
actual = self.topo
while actual != None:
if len(actual.likeList) >= 1:
count += 1
actual = actual.seg
else:
actual = actual.seg
return count
def showRecentComments(self,n):
count = 1
actual = self.topo
sC = ''
if actual == None:
return None
while actual != None:
if count < n:
sC += str(actual) + '\n' + '\n'
count += 1
actual = actual.seg
elif count == n:
sC += str(actual)
count += 1
actual = actual.seg
elif count > n:
break
return sC
Regards, Nelson Gregório
It looks like you're looking at the representation of the string, which will show you the newline characters as \n. If you print or write to e.g. stdout (sys.stdout.write(s)) the string instead, the newlines will be expanded.

Categories