Run-time error in my realization of deque in Python3 - deque

Could you please help me to find an error in the realization of deque? There is a restriction on the number of possible elements in the deque (namely 100).
I suppose that my code has mistakes because it runs out with a run-time error when I am trying to pass it on the contest. The problem is that when I seek to
find this mistake manually I can't get such an error.
Here is my code:
def push_front(dequeue, elem):
global dequeuestart
dequeue[dequeuestart] = elem
dequeuestart -= 1
print('ok')
def push_back(dequeue, elem):
global dequeueend
dequeue[dequeueend] = elem
dequeueend += 1
print('ok')
def pop_front(dequeue):
global dequeuestart
dequeuestart += 1
return dequeue[dequeuestart]
def pop_back(dequeue):
global dequeueend
dequeueend -= 1
return dequeue[dequeueend]
def front(dequeue):
return dequeue[dequeuestart + 1]
def back(dequeue):
return dequeue[dequeueend - 1]
def size(dequeue):
return dequeueend - dequeuestart - 1
def clear(dequeue):
global dequeuestart
global dequeueend
dequeuestart = 99
dequeueend = 100
print('ok')
def exit(dequeue):
print('bye')
dequeue = ['None' for i in range(200)]
dequeuestart = 99
dequeueend = 100
line = input()
while line:
elems = line.split()
if elems[0] == 'push_front':
push_front(dequeue, elems[1])
elif elems[0] == 'push_back':
push_back(dequeue, int(elems[1]))
elif elems[0] == 'pop_front':
print(pop_front(dequeue))
elif elems[0] == 'pop_back':
print(pop_back(dequeue))
elif elems[0] == 'front':
print(front(dequeue))
elif elems[0] == 'back':
print(back(dequeue))
elif elems[0] == 'size':
print(size(dequeue))
elif elems[0] == 'clear':
clear(dequeue)
else:
exit(dequeue)
break
line = input()
Thanks in advance!

Related

How can I compare lists properly?

So I am trying to teach myself some coding and decided to create a little lotto simulator but I just cannot manage to get the program to compare my four lists properly, what is the matter with my def compList code?.
from random import randint as rnd
myGuess_list = []
myGuess_normal = []
myGuess_bonus = []
numbers =[]
drawNumbers = []
normalNumbers = []
bonusNumbers = []
normal_correct = 0
bonus_correct = 0
CORRECT_list = []
BONUS_list = []
winnings = 0
def main():
# generate list of possible numbers
i = 0
for i in range(0, 34):
i += 1
numbers.append(i)
print(numbers)
# draw random numbers from list as lists guessed
def myGuess():
for i in range(0, 10):
numbers = rnd(1, 34)
while numbers in myGuess_list:
numbers = rnd(1, 34)
myGuess_list.append(numbers)
myGuess_list.sort()
myGuess_normal = myGuess_list[0:7]
myGuess_bonus = myGuess_list[-3:]
return myGuess_normal, myGuess_bonus
print(myGuess())
# drawing the lotto numbers from the pool of numbers
def drawNumber(numbers, N):
for i in range(0, N):
number = random.choice(numbers)
while number in drawNumbers:
number = random.choice(numbers)
drawNumbers.append(number)
drawNumbers.sort()
normalNumbers = drawNumbers[0:7]
bonusNumbers = drawNumbers[-3:]
return normalNumbers, bonusNumbers
print(drawNumber(numbers, 10))
comparing list drawn list A with guessed list B and drawn list C with guessed list D
def compList(A, B, C, D):
global normal_correct
global bonus_correct
for i in A and j in C:
if i in B:
normal_correct += 1
CORRECT_list.append(i)
elif j in D:
bonus_correct += 1
BONUS_list.append(j)
print(CORRECT_list + BONUS_list)
return normal_correct, bonus_correct
print(compList(normalNumbers, myGuess_normal, bonusNumbers, myGuess_bonus))
calculate winnings base on previous function
def Winnings(normal_correct, bonus_correct):
global winnings
i = 0
for i in range(0, 10):
i += 1
if normal_correct <= 3:
winnings = 0 - 5
elif normal_correct == 4:
winnings = 45 - 5
elif normal_correct == 5:
winnings = 100 - 5
elif normal_correct == 6:
winnings = 3695 - 5
elif normal_correct == 6 and bonus_correct == 1:
winnings = 169410 - 5
elif normal_correct == 7:
winnings = 'JACKPOT!!'
return winnings
print(Winnings(normal_correct, bonus_correct))
calling main
main()

Ruby: Why is my Code false?

Trying to multiply each number by array position, and it's coming out false:
def the_sum(number)
i = 0
number = 0
ans = 0
while i < 0
ans = string[idx] * string.index
i += idx
end
return ans
end
test =
the_sum([2, 3]) == 3 # (2*0) + (3*1)
the_sum([2, 3, 5]) == 13 # (2*0) + (3*1) + (5*2)
and it comes out false?
There are a few problems here
def the_sum(number)
i = 0
number = 0 # You just cleared your input variable!
ans = 0
while i < 0 # You previously i = 0 so this will never be true
ans = string[idx] * string.index
i += idx
end
return ans # Ans is and was always 0
end
This can be fixed by calling each_with_index on the Array that you're passing.
def the_array_sum(array)
ans = 0
array.each_with_index do |val, index|
ans += val * index
end
return ans
end
the_array_sum([2, 3]) == 3
# => true
the_array_sum([2, 3, 5]) == 13
# => true

My wxpython program suddenly doesn't work for no reason

I made a program for school few weeks ego.. i have finished it yet.
for some reason, when i am trying to run the program now, it doesn't work, although it worked well in the last time a tried.
I am sure that i didn't change anything in the code, but there is always a chance that something has changed and i didn't payed attention..
I need to pass it to my teacher in these days and i have no idea what is wrong with the program.
I will glad to get some help here..
here is the code:
import wx
import winsound
import wx.grid as gridlib
from random import randint
OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, "DEL", 0, "SEND"]
# these are the events' IDs sent to a function when you click a button.
# the OPTIONS_ID is in the same order of OPTIONS.
OPTIONS_ID = [-31984,-31983,-31982,-31981,-31980,-31979, -31978, -31977, -31976, -31975, -31974, -31973, -31985] # the built in wxpython IDs for the buttons
GAME_POSITION = (400, 100)
GAME_SIZE = [900, 600]
def RandomNum():
count = 5
while count > 4:
num = randint(1000, 9999)
digits = str(num)
count = 0
for digit in digits:
for digit2 in digits:
if digit == digit2:
count = count + 1
return digits
class Frame(wx.Frame): # class for all the frames in our game.
def __init__(self, parent, id, title, pos, size):
wx.Frame.__init__(self, parent, id, title, pos, size)
self.panel = wx.Panel(self)
self.fdf = wx.TextCtrl(self.panel, size=(275, 75), pos=(520, 20))
self.count = 0
self.turnsCounter = 0
self.numbers = RandomNum()
self.bulls = 0
self.cows = 0
self.counter_of_turns = 0
self.check = False
self.grid = gridlib.Grid(self.panel, pos = (85, 150), size=(323, 212))
self.grid.CreateGrid(10, 3)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel, 1, wx.EXPAND)
sizer.Add(self.grid, 1, wx.EXPAND)
self.panel.SetSizer(sizer)
for i in range(10):
for j in range(4):
self.grid.SetReadOnly(i, j)
self.grid.SetColLabelValue(0, "guess")
self.grid.SetColLabelValue(1, "cows")
self.grid.SetColLabelValue(2, "bulls")
def message_dialog(self, message, caption, style=wx.YES_NO, position=GAME_POSITION):
if message != "": # making sure not to execute a message if its empety
message = wx.MessageDialog(None, message, caption, style, position)
answer = message.ShowModal()
if answer == wx.ID_YES:
self.reset()
else:
self.Destroy()
else:
return -1
# this function creates a textbox at a specific position with a specific size.
def write(self, panel, txt, pos, size=20, font_family=wx.SWISS, font_style = wx.NORMAL,font_weight = wx.BOLD, underline = False, color=wx.WHITE):
# create a textbox at a specific position with a specific size.
your_txt = wx.StaticText(panel, -1, txt, pos)
your_txt.SetFont(wx.Font(size,font_family,font_style,font_weight,underline))
your_txt.SetForegroundColour(color)
# same as above, just for a button.
def create_button(self, panel, txt, position, width, height, color, disable):
Size = wx.Size(width, height)
self.button = wx.Button(panel, -1, txt, position, Size)
self.button.SetBackgroundColour(color)
self.border = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.button)
self.Bind(wx.EVT_BUTTON, lambda evt: self.OnButton(evt), self.button)
if disable == True:
self.button.Disable()
def count_bulls(self, txtctrl, seria):
for i in range(4):
if seria[i] == txtctrl[i]:
self.bulls += 1
replacement = self.bulls
self.bulls = 0
return replacement
def count_cows(self, txtctrl, seria):
for i in range(4):
if seria[i] != txtctrl[i] and seria[i] in txtctrl:
self.cows += 1
replacement = self.cows
self.cows = 0
return replacement
def reset(self):
self.fdf.Clear()
self.grid.ClearGrid()
self.count = 0
self.turnsCounter = 0
self.numbers = RandomNum()
self.bulls = 0
self.cows = 0
self.counter_of_turns = 0
self.check = False
for child in self.panel.GetChildren():
if child.GetLabel() != "SEND":
child.Enable()
else:
child.Disable()
if self.count == 0:
if child.GetLabel() == "DEL" or child.GetLabel() == "0":
child.Disable()
def OnButton(self, event):
print repr(event.Id) + ","
print self.numbers
if event.Id in OPTIONS_ID: # if indeed an option button was pressed
exited = -1 # exited is 5100 if the user exited his dialog box
# assigning the events to the button.
for i in range(13):
if event.Id != -31985 and event.Id != -31975 and event.Id != -31974 and event.Id != -31973 and event.Id == OPTIONS_ID[i]:
self.fdf.AppendText(str(OPTIONS[i]))
self.count += 1
if event.Id == -31974:
self.fdf.AppendText(str(OPTIONS[10]))
self.count += 1
if event.Id == -31985:
self.reset()
if event.Id == -31973:
self.counter_of_turns += 1
print self.numbers
print self.fdf.GetValue()
cows = self.count_cows(self.fdf.GetValue(), self.numbers)
bulls = self.count_bulls(self.fdf.GetValue(), self.numbers)
self.grid.SetCellValue(self.turnsCounter,0, self.fdf.GetValue())
self.grid.SetCellValue(self.turnsCounter, 1, str(cows))
self.grid.SetCellValue(self.turnsCounter, 2, str(bulls))
self.fdf.Clear()
self.count = 0
if self.turnsCounter < 9:
self.turnsCounter += 1
if bulls == 4:
self.check = True
winsound.PlaySound('The_Power_-_Snap_1_.wav', winsound.SND_ASYNC | winsound.SND_LOOP)
self.message_dialog("Well done! you won this game..\n You won the game in %s turns .. \n Play again ? " % self.counter_of_turns , "You won!")
winsound.PlaySound(None, 0)
if event.Id == -31975:
if self.count > 0:
self.count -= 1
self.fdf.Remove(self.fdf.GetLastPosition()-1, self.fdf.GetLastPosition())
if self.count == 4:
for child in self.panel.GetChildren():
if isinstance(child, wx.Button):
try:
int(child.GetLabel())
except ValueError:
if child.GetLabel() == "SEND":
child.Enable()
else:
child.Disable()
elif self.check == False:
for child in self.panel.GetChildren():
if child.GetLabel() != "SEND":
child.Enable()
else:
child.Disable()
if self.count == 0:
if child.GetLabel() == "DEL" or child.GetLabel() == "0":
child.Disable()
#for child in self.panel.GetChildren():
#if isinstance(child, wx.Button):
#if child.GetLabel() in self.fdf.GetValue():
#child.Disable()
if self.counter_of_turns == 10 and self.check == False:
self.message_dialog("YOU LOST :( \n THE NUMBERS WERE %s \n PLAY AGAIN ?" % self.numbers,"Bad news ..")
class Game(wx.App):
def OnInit(self): # upon game opening
# I would like the options window to be the first window's parent
# so I will first set up our options window:
window = Frame(None, -1, "Good Luck!", GAME_POSITION, GAME_SIZE)
first_panel = window.panel
window.SetBackgroundColour(wx.BLACK)
window.write(first_panel, "BULLS AND COWS!", (50, 50), size=(35))
countX = 500
countY = 100
window.create_button(first_panel,"restart!", (50, 400), 100, 100, wx.WHITE, False)
for option in OPTIONS:
if str(option) == "SEND" or str(option) == "DEL":
window.create_button(first_panel,str(option), (countX, countY), 100, 100, wx.GREEN, True)
elif str(option) == "0":
window.create_button(first_panel,str(option), (countX, countY), 100, 100, wx.WHITE, True)
else:
window.create_button(first_panel,str(option), (countX, countY), 100, 100, wx.WHITE, False)
countX += 110
if str(option) == "3" or str(option) == "6" or str(option) == "9":
countY += 110
countX = 500
window.Show(True)
return True
def main():
MasterMind = Game()
MasterMind.MainLoop()
if __name__ == '__main__':
main()
PLEASE NOTE:
I upgraded my windows to windows 10 few days ego, it means that it doesn't work since the upgrade if it means something. (sorry if the grammer of my english not so well, it is not my native language..).
In my computer works fine (Python 2.7.11 and windows 7). If you import this class in another file, make sure if you call the main function.

how to create graph (data structure) using linked lists

I have create my linked list and I need to create a graph without using dictionaries and normal lists, i have to use linked list, how anyone recommended me to build it? my linked list looks like this:
class LinkList:
def __init__(self):
self.head = None
self.tail = None
self.count = int()
def add(self, value):
if not self.head:
self.head = Node(value)
self.tail = self.head
else:
self.tail.next = Node(value)
self.tail = self.tail.next
self.count += 1
def get(self, position):
node = self.head
for i in range(position):
if node:
node = node.next
if not node:
return "posicion no encontrada"
else:
return node.value
def delete_first(self):
if self.head is None:
print("lista vacia, imposible eliminar primer elemento")
elif self.head == self.tail:
self.head = None
self.tail = None
self.count -= 1
print("habia un elemento, lista vacia")
else:
self.head = self.head.next
self.count -= 1
def delete_last(self):
if self.tail is None:
print("lista vacia, imposible eliminar ultimo elemento")
elif self.head == self.tail:
self.head = None
self.tail = None
self.count -= 1
print("habia un elemento, lista vacia")
else:
validate = True
temp = self.head
while validate:
if temp.next == self.tail:
self.tail = temp
self.count -= 1
validate = False
else:
temp = temp.next
def delete(self, number):
temp = self.head
temp2 = self.head
if self.head is None:
print("Lista vacia, imposible eliminar elemento")
else:
if self.head.value == number:
self.delete_first()
elif self.tail.value == number:
self.delete_last()
else:
validate = True
while validate:
temp = temp.next
if temp.value == number:
temp2.next = temp.next
self.count -= 1
validate = False
elif self.tail == temp:
print("El elemento no esta en la lista")
validate = False
temp2 = temp2.next
def __repr__(self):
if self.head is None:
return str("[]")
rep = '['
actual_node = self.head
while actual_node:
if actual_node != self.tail:
rep += '{0},'.format(actual_node.value)
else:
rep += '{0}]'.format(actual_node.value)
break
actual_node = actual_node.next
return rep
To create a graph data structure, you need to modify your linked list so that each node has a pointer to multiple nodes. Since you have a max of 7 connections, this could be an array with the list of connections.
Instead of just having node.next, you might have an array of connections, like node.links where you would add a link to connect a node to any other node in the graph.

How to improve time complexity of this code piece?

I am having a hard time trying to down down the time. If this can be done in O(n^2) thatd be awesome.
def printDistance(file)
line = file.gets
if line == nil then return end
sz, sx, sy, ex, ey = line.split(/\s/)
#counter = 0
while line = file.gets do
if line[0...4] == "path"
else
x, y, ds, w = line.split(/\s/,4)
x = x.to_i
y = y.to_i
matrix= Array.new
later = Array.new
tmp = Array.new
processing = Array.new
if matrix[y].class != Array
matrix[y] = Array.new
end
if ds == "" #this cell has NO way to get to
matrix[y][x] = nil
else
matrix[y][x] = ds
end
end
end
for y in 0...matrix.length
processing[y] = Array.new
tmp[y] = Array.new
later[y] = Array.new
end
printing = Array.new
counter = 0
sy = sy.to_i
sx = sx.to_i
processing[sy][sx] = matrix[sy][sx]
matrix[sy][sx] = nil
puts "#{counter},(#{sx},#{sy})" #first one
counter += 1
loop do
print "#{counter},"
counter += 1
for y in 0...processing.length
for x in 0...processing[y].length
if processing[y][x].class != nil
tmp[y][x] = processing[y][x]
dirArr = tmp[y][x].to_s.split(//)
dirArr.each { |c|
if c == "u"
newY = y - 1
newX = x
elsif c == "d"
newY = y + 1
newX = x
elsif c == "l"
newY = y
newX = x - 1
else #c == r
newY = y
newX = x + 1
end
if matrix[newY][newX] != nil
tmpStr = "(#{newX},#{newY})"
printing.unshift(tmpStr)
later[newY][newX] = matrix[newY][newX]
matrix[newY][newX] = nil
end
}
end
end
end
printing.sort!
for i in 0...printing.length
print printing[i]
if i < printing.length - 1
print ","
end
end
printing = [] #resetting
puts
for i in 0...later.length
for j in 0...later[i].length
if later[i][j] != nil
processing[i][j] = later[i][j]
end
end
end
break if NotEmpty(matrix) == false
end
end
def NotEmpty (a)
for i in 0...a.length
for j in 0...a[i].length
if a[i][j] != nil
return true
end
end
end
return false
end
Basically this code reads in a file and places it in a 2-d array representing a maze, then based on maze's starting point it will perform a BFS to put all cells in order from closest to the start to the farthest, then print everything out
This code is now O(n^3) but I am trying to shrink it to O(n^2), is there anyway I can traverse a 2-d array and keeping track of the x and y values without using two forloops?
Any help is appreciated!! Thanks!

Resources