I was trying to make a python game using only characters, honestly I did it, but the end condition was too vague. To make one, I simply assigned startLocation as a normal location, and having finished the objective, I would return to the starting location and quit the game to give new line texts. However:
def locations():
startLocation = random.choice(mapaGrid)
monsterLocation = random.choice(mapaGrid)
wellLocation = random.choice(mapaGrid)
goldLocation = random.choice(mapaGrid)
arrowLocation = random.choice(mapaGrid)
if monsterLocation == goldLocation or monsterLocation == startLocation or goldLocation == startLocation or monsterLocation == arrowLocation or wellLocation == goldLocation or wellLocation == startLocation or wellLocation == monsterLocation:
return locations()
return startLocation, monsterLocation, goldLocation, arrowLocation, wellLocation
#Locais do jogador, monstro, ouro, poco, flecha e entrada.
playerLocation, monsterLocation, goldLocation, arrowLocation, wellLocation, startLocation = locations()
So this is where the code fails. When I assign startLocation to locations() in the end, I get the error in the title, even though adding any other completely made up location didn't result in this error. I did try searching but due to my inexperience I couldn't relate the answers to my code.
You return 5 elements:
return startLocation, monsterLocation, goldLocation, arrowLocation, wellLocation
^1 ^2 ^3 ^4 ^5
While in the values that you try to set from the function - you have six of them:
playerLocation, monsterLocation, goldLocation, arrowLocation, wellLocation, startLocation = locations()
^1 ^2 ^3 ^4 ^5 ^6
What do you expect from python to put in the 6th variable?
The error that you got is that you can't assign into 6 variables, because you returned only 5.
Related
I have generated a .csv file with a list of assets and have had to go back and make some changes. which require me to regenerate my NFT Images(done this multiple times at this point) But now the script isn't recognizing my .csv file and even allowing me to run the script that has worked flawlessly up until this point...
def generateOneRandRow(ADATvID):
FILENAME = "ADA Tv" + str(ADATvID)
NO = ADATvID
BACKGROUND = randBackground()
ACCESSORIES = randAccessories()
HEAD = randHead()
HAT = randHat()
BODY = randBody()
CHEST = randChest()
ARMS = randArms()
FACE = randFace()
singleRow = [FILENAME, NO, BACKGROUND, ACCESSORIES, HEAD, HAT, BODY, CHEST, ARMS, FACE]
def checkIfExists(checkRow):
aData = pd.read_csv('adalist.csv')
index_list = aData[(aData['Background'] == checkRow[2])
& (aData['Accessories'] == checkRow[3]) &
(aData['Head'] == checkRow[4]) &
(aData['Hat'] == checkRow[5]) &
(aData['Body'] == checkRow[6]) &
(aData['Chest'] == checkRow[7]) &
(aData['Arms'] == checkRow[8]) &
(aData['Face'] == checkRow[9])].index.tolist()
if index_list == []:
return False
else:
return True
df = pd.read_csv(adalist.csv)
rowCount = df["NO"].count()
print("number of rows is:" + str(rowCount))
the first appearance of adalist.csv shows fine. the last appearance is giving me WHY!?!?!?!
The .csv is in the same Source folder as everything else... this error just occurred and wont even allow me to press Run on my script.
As stated before, this script ran FLAWLESSLY multiple times, Up until I muted some code to convert the .csv into JSON for Metadata. even removing the JSON conversion its still not recognizing the .csv
Please help... I don't have the days it took me to re organize 3500 Images to my Liking [Face Palm]
New to Python & taking a course where teacher provided a code snippet to work on. The provided snippet is giving me a TabError as below, but I cannot seem to figure out why. I was hoping someone here could point out the issue.
Error Received:
Error Received
Code where error occurs (Updated to have code lines instead of screen shot):
def filterResultsAcc(self, qcoverage=0.6, scoverage=0.6, evalue=0.01, best_taxon=False):
results = []
hits_by_taxon = {}
for(qstart,qend,sacc,staxid,slen,sstart,send,evalu) in self.blasthits:
qcov = ((qend-qstart) + 1.0) / float(self.querylen)
scov = ((send-sstart) + 1.0 / float(slen)
if qcov >= qcoverage and scov >= scoverage and evalu <= evalue:
if best_taxon:
if staxid in hits_by_taxon.keys():
(sid,e,qc,sc) = hits_by_taxon[staxid]
if evalu < e:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
elif evalu == e:
if qcov > qc:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
elif qvoc == qc:
if scov > sc:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
else:
hits_by_taxon[staxid] = (sacc,evalu,qcov,scov)
else:
results.append(sacc)
if best_taxon:
for taxid in hits_by_taxon.keys():
(sac,e,qc,sc) = hits_by_taxon[taxid]
results.append(sacc)
results.sort()
return results
The error shows that you've mixed tab and spaces, just as it says.
If your editor supports it – turn something like "show unprintable characters" to see what your whitespaces really is.
Another way is to select all code, usually editors will distinguish between spaces and tabs.
The goal is simple: show a dialog with options, then when a option is selected it will automatically replace some values (to decrease the possibility of making an error while typing the values manually). The following code is part of a larger code, but this is the most important part. The larger piece of code was written by someone else. I wrote the following block:
if expInfo2['quadrant'] == 'UL':
expInfo['refOrientation':'45','x':'-4.24','y':'4.24']
elif expInfo2['quadrant'] == 'LL':
expInfo['refOrientation':'-45','x':'-4.24','y':'-4.24']
elif expInfo2['quadrant'] == 'UR':
expInfo['refOrientation':'-45','x':'4.24','y':'4.24']
elif expInfo2['quadrant'] == 'LR':
expInfo['refOrientation':'45','x':'4.24','y':'-4.24']
The code works fine until it reads the second line, and gives the following error:
Traceback (most recent call last):
File "D:\User\File\Experiment.py", line 48, in <module>
expInfo['refOrientation':'45','x':'-4.24','y':'4.24']
TypeError: unhashable type
()
My experience with programming is limited, but I understand that the things I put in that second line do not fit together. However, I was thinking of splitting them piece by piece but I do not think that will work, like in the following:
if expInfo2['quadrant'] == 'UL':
expInfo['refOrientation':'45']
expInfo['x':'-4.24']
expInfo['y':'4.24']
et cetera...
The full code:
#present a dialogue to chose lab room and whether eyetracker is on or not
expInfo2 = {'lab':'2','eyetracker': '0','quadrant':''}
dlg = gui.Dlg(title="Info", pos=(200, 400))
dlg.addField('Which lab are you in? 2 for lab-2, 3 for lab-3',expInfo2['eyelab'])
dlg.addField('Do you want the eyetracker on? 0 for yes, 1 for no',expInfo2['eyetracker'])
dlg.addField('What quadrant is used? UL=Upper Left, LL=Lower Left, UR=Upper Right, LR=Lower Right',expInfo2['quadrant'])
inf = dlg.show()
expInfo2['lab']=inf[0]
expInfo2['eyetracker'] = inf[1]
expInfo2['quadrant'] = inf[2]
############################## THIS IS THE CODE FOR LAB 2 ###########################################
if expInfo2['lab'] == '2':
expInfo = {'observer':'insert','typeofstaircase':'insert','refOrientation':'','startorient':'insert','x':'','y':'','numstair':4,}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time
if expInfo2['quadrant'] == 'UL':
expInfo['refOrientation':'45','x':'-4.24','y':'4.24']
elif expInfo2['quadrant'] == 'LL':
expInfo['refOrientation':'-45','x':'-4.24','y':'-4.24']
elif expInfo2['quadrant'] == 'UR':
expInfo['refOrientation':'-45','x':'4.24','y':'4.24']
elif expInfo2['quadrant'] == 'LR':
expInfo['refOrientation':'45','x':'4.24','y':'-4.24']
#present a dialogue to change params
dlg = gui.Dlg(title="Info", pos=(200, 400))
dlg.addField('Observer:',expInfo['observer'])
dlg.addField('Type of staircase?', expInfo['typeofstaircase'])
dlg.addField('Start Orientation Increment:',expInfo['startorient'])
dlg.addField('X:',expInfo['x'])
dlg.addField('Y:',expInfo['y'])
dlg.addField('Ref. Orienation:',expInfo['refOrientation'])
#dlg.addField('Number of Staircases',expInfo['numstair'])
inf = dlg.show()
expInfo['observer']=inf[0]
expInfo['typeofstaircase'] = inf[1]
expInfo['startorient']=inf[2]
expInfo['x']=inf[3]
expInfo['y']=inf[4]
expInfo['refOrientation']=inf[5]
#expInfo['numstair'] = inf[6]
#dlg = gui.DlgFromDict(expInfo, title='info', fixed=['date'])
#if dlg.OK:
# print(expInfo)
#else:
# core.quit()#the user hit cancel so exit
Any suggestions?
expInfo['refOrientation':'-45','x':'-4.24','y':'-4.24']
So this is interpreted as
expInfo.__getitem__((
slice('refOrientation', '-45', None),
slice('x', '-4.24', None),
slice('y', '-4.24', None)
))
, a 3-tuple of slice objects. expInfo is a dictionary, and only takes hashable types and
hash((
slice('refOrientation', '-45', None),
slice('x', '-4.24', None),
slice('y', '-4.24', None)
))
raises the error
TypeError: unhashable type: 'slice'
because, well, they aren't hashable. It's very, very weird to use strings in slices like that so I don't think you are inputting the key in the correct way.
I think what you are trying to do is update the dictionary. To do this you want:
if expInfo2['quadrant'] == 'UL':
expInfo.update({'refOrientation': '45', 'x': '-4.24', 'y': '4.24'})
elif expInfo2['quadrant'] == 'LL':
...
(note the whitespace I put in to make it more readable. I'd advise reading PEP8 before going any further with python since you throw the style guide out the window).
First of, i'm sort of new to Python so sorry if this question is obvious. The detect english module appears to be wrong, but it functions perfectly fine when calling it and running it on its own, theres no errors when running it alone and i've rewritten it a couple times to triple check it.
Traceback (most recent call last):
File "H:\Python\Python Cipher Program\transposition hacker.py", line 49, in <module>
main()
File "H:\Python\Python Cipher Program\transposition hacker.py", line 11, in main
hackedMessage = hackTransposition(myMessage)
File "H:\Python\Python Cipher Program\transposition hacker.py", line 34, in hackTransposition
if detectEnglish.isEnglish(decryptedText):
File "H:\Python\Python Cipher Program\detectEnglish.py", line 48, in isEnglish
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
this is the error i am getting when trying to run the Transposition Hacker (copied directly from here
Here is the code for the Detect English Module
# Detect english Module
# to use this code
# import detectEnglish
# detectEnglish.isEnglish(somestring)
# returns true of false
# there must be a dictionary.txt file in the same directory
# all english words
# one per line
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary()
dictionaryFile = open('Dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possibleWords)
def removeNonLetters(message):
lettersOnly = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
lettersOnly.append(symbol)
return ''.join(lettersOnly)
def isEnglish(message, wordPercentage=20, letterPercentage=85):
# by default 20% of the words mustr exist in dictionary file
# 85% of charecters in messafe must be spaces or letters
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
numLetters = len(removeNonLetters(message))
messageLettersPercentage = float(numLetters) / len(message) * 100
lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatcht
getEnglishCount looks like it is missing a return statement. If python gets to the end of a function without hitting a return statement it will return None as you're seeing.
try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
# if possibleWords == []: # redundant
# return 0.0
return len(possibleWords)
Edit: #Kevin Yea I think you're right - there was more in that function. Maybe try this:
def getEnglishCount(message):
message = message.upper()
message = removeNonLetters(message)
possibleWords = message.split()
if possibleWords == []:
return 0.0
matches = 0.
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
return matches / len(possibleWords)
I'd guess the indentation somehow got changed when you copy and pasted the code, with the return statement nested under the if.
As the other poster has said, you're missing a return for the getEnglishCount method, so it's returning NoneType, meaning that there is no value to be returned.
You can't do math on NoneTypes, so the NoneType*100 fails, which is what the bottom of your error traceback says.
I am trying to produce a PDF document with different odd/even page layouts (to allow asymmetric borders for binding) using Python 2.7 and ReportLab. To further complicate matters I am trying to produce two-columns per page.
def WritePDF(files):
story = []
doc = BaseDocTemplate("Polar.pdf", pagesize=A4, title = "Polar Document 5th Edition")
oddf1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='oddcol1')
oddf2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='oddcol2')
evenf1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='evencol1')
evenf2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='evencol2')
doc.addPageTemplates([PageTemplate(id='EvenTwoC',frames=[evenf1,evenf2],onPage=evenFooter),
PageTemplate(id='OddTwoC', frames=[oddf1, oddf2], onPage=oddFooter)])
...
story.append(Paragraph(whatever, style))
What I can't figure out is how to make ReportLab alternate between right and left (or odd and even) pages. Any suggestions?
I found the solution I guess ! :)
I had to dig into the source code. I found the solution in the file reportlab/platypus/doctemplate.py on line 636. It's not the first time I had to do this, as the documentation is pretty limited...
Now, what I found:
def handle_nextPageTemplate(self,pt):
'''On endPage change to the page template with name or index pt'''
if type(pt) is StringType:
# ... in short, set self._nextPageTemplate
elif type(pt) is IntType:
# ... in short, set self._nextPageTemplate
elif type(pt) in (ListType, TupleType):
#used for alternating left/right pages
#collect the refs to the template objects, complain if any are bad
c = PTCycle()
for ptn in pt:
found = 0
if ptn=='*': #special case name used to short circuit the iteration
c._restart = len(c)
continue
for t in self.pageTemplates:
if t.id == ptn:
c.append(t)
found = 1
if not found:
raise ValueError("Cannot find page template called %s" % ptn)
if not c:
raise ValueError("No valid page templates in cycle")
elif c._restart>len(c):
raise ValueError("Invalid cycle restart position")
#ensure we start on the first one
self._nextPageTemplateCycle = c.cyclicIterator()
else:
raise TypeError("argument pt should be string or integer or list")
And I checked where this self._nextPageTemplateCycle is used, so this is what I think should work (not tested though):
story = []
# ...
# doc.addPageTemplates([...])
story.append(NextPageTemplate(['pageLeft', 'pageRight'])) # this will cycle through left/right/left/right/...
story.append(NextPageTemplate(['firstPage', 'secondPage', '*', 'pageLeft', 'pageRight'])) # this will cycle through first/second/left/right/left/right/...
Add this to story once, when you want to start alternating pages. Use another normal NextPageTemplate to stop this cycle (because in the source, there's a del self._nextPageTemplateCycle if you do that).
Hope it helps, and do say if it works, I can't make sure right now, but I will!