Python keeps printing list too many times - python

How can i make python print only one copy of the illegalstates-list?
It seems to list it for far too long, when all i would require is one copy.
import itertools
import copy
BOAT = "B"
def illegalStates(roles):
allstates = []
legalstates = []
illegalstates = []
husbands = []
wifes = []
sisalto = []
persons = copy.deepcopy(roles)
persons.remove(BOAT)
for i in range(1, len(persons)+1):
els = [list(x) for x in itertools.combinations(persons, i)]
allstates.extend(els)
allstates.append([])
for state in allstates:
husbands.append([])
wifes.append([])
for henkilo in state:
if henkilo == "H1":
husbands[len(sisalto)-1].append(1)
elif henkilo == "H2":
husbands[len(sisalto)-1].append(2)
elif henkilo == "H3":
husbands[len(sisalto)-1].append(3)
elif henkilo == "W1":
wifes[len(sisalto)-1].append(1)
elif henkilo == "W2":
wifes[len(sisalto)-1].append(2)
elif henkilo == "W3":
wifes[len(sisalto)-1].append(3)
for i in range(0, len(husbands)):
if len(husbands[i]) == 0 or len(wifes[i]) == 0:
legalstates.append(allstates[i])
print(*legalstates)
#--------------------------------
return illegalstates
if __name__ == "__main__":
main()
Here is the whole code, just in case its some other part of the code that keeps making this happen.
Also, when that list is printed, it does not print empty slots. Could this be printed somehow?

Your loop that starts while len(openlist) > 0:, contains a call to legalstates(), which contains a call to illegalstates(), which contains your print statement. Therefore, you're calling the method containing the print every time your while loop...loops

Related

Creating two list using three validation functions

Hello this is my first question and sorry I don't know how to phrase it,
I am trying to create a two list. The first list is for one set of codes (code1) and is validated in the VC function. The second function (VC) is to validate the second list. Both functions work well in validating the numbers. However in the third function (add_validations). In that function I want to repeat VC and VQ until the user either types in END or either of the functions return False. When true I want the inputs to be appended into the two separate lists. However, the third function not only does not append any of the list it does not identify/run either of the two functions and comes up with:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
And I'm sorry I didn't know which code to add so I added everything (delete if not allowed sorry):
Code:
def add_validations():
code1 = []
code2 = []
VC()
VQ()
while True:
record = []
i = VC()
q = VQ()
if i != "END":
VQ()
VC()
code1.append(int(i))
code2.append(int(q))
elif VC == True and VQ() == True:
VQ()
VC()
code1.append(int(i))
code2.append(int(q))
elif VC == False and VQ() == True:
print("Invalid code")
else:
print("Invalid quantity")
return code1,code2
def VC():
i = input("What is the item code \n")
minimum = 0
maximum = 39
if i == "END":
i = "END"
return showRecord()
elif int(i) > minimum and int(i) <= maximum:
return int(i)
True
else:
False
def VQ():
q = input("What quanity \n")
minimum = 0
maximum = 49
if q == "END":
isValidCode = "END"
return showRecord()
elif int(q) > minimum and int(q) <= maximum:
True
else:
False

UnboundLocalError: local variable 'validSqaures' referenced before assignment

I'm trying to follow a python tutorial on chess, but when i run the function to check for Checkmates and possible moves, I get the following error:
File "d:\Coding\Projects\Chess\stuff\ChessEngine.py", line 86, in getValidMoves
if not (moves[i].endRow, moves[i].endCol) in validSqaures:
UnboundLocalError: local variable 'validSqaures' referenced before assignment
This is the code I used for the function
def getValidMoves(self):
moves = []
self.inCheck, self.pins, self.checks = self.checkForPinsAndChecks()
if self.whiteToMove:
kingRow = self.whiteKingLocation[0]
kingCol = self.whiteKingLocation[1]
else:
kingRow = self.blackKingLocation[0]
kingCol = self.blackKingLocation[1]
if self.inCheck:
if len(self.checks) == 1: #Only 1 piece checking the King
moves = self.getAllPossibleMoves()
check = self.checks[0]
checkRow = check[0]
checkCol = check[1]
pieceChecking = self.board[checkRow][checkCol]
validSquares = [] #Sqaures pieces can move to
if pieceChecking[1] == "N":
validSqaures = [(checkRow, checkCol)]
else:
for i in range(1, 8):
validSquare = (kingRow + check[2] * i, kingCol + check[3] * i)
validSquares.append(validSquare)
if validSquares[0] == checkRow and validSquares[1] == checkCol:
break
for i in range(len(moves) -1 ,-1, -1):
if moves[i].pieceMoved[1] != 'K':
if len(moves) != 0:
if not (moves[i].endRow, moves[i].endCol) in validSqaures:
moves.remove(moves[i])
else: #Double check, King has to move
self.getKingMoves(kingRow, kingCol, moves)
else: #Not in check so any move is fine
moves = self.getAllPossibleMoves()
if len(moves) == 0: #either CheckMate or Stalemate
if self.inCheck == True:
self.checkMate = True
else:
self.staleMate = True
else:
self.checkMate = False
self.staleMate = False
return moves
When I try placing the list validSqaures anywhere else, it just turns blank and doesnt allow me to make anymore moves after putting the opponent king in check.

Runtime error when submitting Kattis problem in python: I can guess the data structure

I'm trying for a while now to submit my solution to the following problem on Kattis: I can guess the data structure!. However, I keep getting a runtime error; I cannot think of anywhere it can go wrong since it works with all my input. Here is my solution:
import heapq, sys
def throwin(q,s,h,x, results):
if results[0]:
q.append(x)
if results[1]:
s.append(x)
if results[2]:
heapq.heappush(h, -x)
return (q,s ,h )
def printstructures(l):
for j in l:
if j[0] and j[1] or j[0] and j[2] or j[1] and j[2]:
print("not sure")
elif not j[0] and not j[1] and not j[2]:
print("impossible")
elif j[0]:
print("queue")
elif j[1]:
print("stack")
else:
print("priority queue")
def main():
results_global = []
stackops = []
current = []
while True:
try:
line = input()
if len(line) == 1:
if len(current) != 0:
stackops.append(current)
current = []
else:
current.append(tuple(map(int, line.split(" "))))
except EOFError:
break
stackops.append(current)
for op in stackops:
q,s,h = [],[],[]
heapq._heapify_max(h)
results = [True, True, True]
for i in range(len(op)):
o, x = op[i]
if o == 1:
q,s,h = throwin(q,s,h,x, results)
else:
if len(q) == 0 or q[0] != x:
results[0] = False
else:
q.pop(0)
if len(s) == 0 or s[-1] != x:
results[1] = False
else:
s.pop()
if len(h) == 0 or h[0] != -x :
results[2] = False
else:
heapq.heappop(h)
if i == len(op)-1:
results_global.append(results)
printstructures(results_global)
if __name__ == "__main__":
main()
I was wondering if anyone can give me a push in the right direction and point out where my thinking is wrong or if I made a mistake somewhere I overlooked.
I had the same runtime-error problem for this question, I think it has something to do with python input/output EOFError. I couldn't figure the specific error out but I just put a try/except pass over my entire program and kattis accepted the solution.
import sys
try:
def solve(n):
stack = []
queue = []
priority_queue = []
type_ds = [True, True, True]
for i in range(n):
command, element = map(int, input().split())
if command == 1:
if type_ds[0] != False:
stack.append(element)
if type_ds[1] != False:
queue.append(element)
if type_ds[2] != False:
priority_queue.append(element)
elif command == 2:
if type_ds[0] != False:
if len(stack) == 0:
return "impossible"
if element != stack.pop():
type_ds[0] = False
stack.clear()
if type_ds[1] != False:
if len(queue) == 0:
return "impossible"
if element != queue.pop(0):
type_ds[1] = False
queue.clear()
if type_ds[2] != False:
if len(priority_queue) == 0:
return "impossible"
priority_queue.sort(reverse=True)
if element != priority_queue.pop(0):
type_ds[2] = False
priority_queue.clear()
if type_ds.count(True) > 1:
return "not sure"
elif type_ds.count(True) == 0:
return "impossible"
else:
if type_ds[0] == True:
return "stack"
elif type_ds[1] == True:
return "queue"
else:
return "priority queue"
for line in sys.stdin:
if line.strip() == "":
break
n = int(line.strip())
print(solve(n))
except:
pass
Are you sure you're breaking out of the while loop? Is it running correctly on your computer? In competitive programming, with time limits, it's normally not a good idea to use try/except statements, it's slowing down the script by a lot.

My function is returning an empty list and I don't understand why?

I am writing a file overlap function that takes two arguments: longestFile and shorterFile. I want to see if two files have the same numbers and if they do, it will append that number to an empty list.
These are the two lists I am using for the program:
The first file that I am using to compare and The second file that I use
def longestFile(firstFile, secondFile):
if len(firstFile)>len(secondFile):
return firstFile
else:
return secondFile
def shortestFile(firstFile, secondFile):
if len (firstFile) < len(secondFile):
return firstFile
else:
return secondFile
def middleNumber(theLongestFile):
return theLongestFile[len(theLongestFile)//2]
def fileOverlap(lstFirstFile,lstSecondFile):
lstMatchingNums = []
lstLongerFile = longestFile(lstFirstFile,lstSecondFile)
lstShortestFile = shortestFile(lstFirstFile,lstSecondFile)
for eachLines in range(len(lstShortestFile)):
lstLongerFile = longestfile(lstFirstFile,lstSecondFile)
for eachLine in range(len(lstLongerFile)):
if lstShortestFile[eachLines] == middleNumber(lstLongerFile):
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif lstShortestFile[eachLines] < middleNumber(lstLongerFile):
lstLongerFile = lstLongerFile[0:len(lstLongerFile)//2+1]
if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <=2:
break
elif lstShortestFile[eachLines] > middleNumber(lstLongerFile):
lstLongerFile = lstLongerFile[len(lstLongerFile)//2:]
if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <= 2:
break
return lstMatchingNums
lstHappyNums = open('happynumbs.txt','r')
lstReadingHappyLines = lstHappyNums.readlines()
lstHappyNums.close()
lstPrimeNumsFile = open('primenumbers.txt','r')
lstReadingPrimeLines = lstPrimeNumsFile.readlines()
lstPrimeNumsFile.close()
print(fileOverlap(lstReadingHappyLines,lstReadingPrimeLines))
If I was to run this program, it would give me an empty list and I am not sure why.

empty output after recursive call issue

Here is my code for 8 queen problem and why my output are all empty list ([])?
I have checked this statement print "result ok", result will get non-empty results.
class Solution(object):
def __init__(self, finalResult):
self.finalResult = finalResult
def Valid(self,result):
currentX = len(result) - 1
currentY = result[-1]
if currentX == 0:
return True
for i in range(0, len(result) - 1):
if result[i] == currentY:
return False
elif abs(i - currentX) == abs(result[i] - currentY):
return False
return True
def NQueens(self, result):
if result == []:
row = 0
else:
row = len(result)
for col in range(0, 8):
result.append(col)
if self.Valid(result) == True:
# print "check valid ok", row, col, result
if row == 7:
# print "result ok", result
self.finalResult.append(result)
else:
self.NQueens(result)
result.pop(-1)
return
if __name__ == "__main__":
finalResult = []
s = Solution(finalResult)
s.NQueens([])
print len(s.finalResult)
for i in s.finalResult:
print i
Output,
92
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
You should replace
self.finalResult.append(result)
with
self.finalResult.append(result[:])
This will create a copy of the "result". Your current code is creating several references to the same result which all get emptied by result.pop(-1)
You have only one list result that you manipulate. When you append, you append a 'reference' to that list and then you keep modifiying it. At the end it is empty so you print 92 times that empty list. You just need to create a copy of the current result before appending it.

Categories