How to fix "list index out of range" error? - python-2.7

I keep getting "list index out of range" error. I have been trying to Google a solution, but I can't find anything that fits my problem.
I tried to use other random things like random.shuffle() and randint().
import random
svart = [18,28,38,58,68,78,88,47,46,45,44,43,42,41,37,26,15,57,66,75,84]
vit = [11,21,31,51,61,71,81,42,43,44,45,46,47,48,32,23,14,52,63,74,85]
def schack(svart,vit):
hit = 0
miss = 0
for i in range(10000):
random.choice(svart)
random.choice(vit)
if svart == vit:
i = i + 1
elif svart[18] == vit[11]:
hit += 1
elif svart[28] == vit[21]:
hit += 1
elif svart[38] == vit[31]:
hit += 1
elif svart[58] == vit[51]:
hit += 1
elif svart[68] == vit[61]:
hit += 1
elif svart[78] == vit[71]:
hit += 1
elif svart[88] == vit[81]:
hit += 1
elif svart[7,46,45,44,43,42,41] == vit[42,43,44,45,46,47,48]:
hit += 1
elif svart[37] == vit[31,47,32]:
hit += 1
elif svart[26] == vit[21,23,46]:
hit += 1
elif svart[15] == vit[11,45,14]:
hit += 1
elif svart[57] == vit[51,52,47]:
hit += 1
elif svart[66] == vit[46,61,63]:
hit += 1
elif svart[75] == vit[71,45,74]:
hit += 1
elif svart[84] == vit[81,44,85]:
hit += 1
elif svart[38,37,42] == vit[32]:
hit += 1
elif svart[28,43,26] == vit[23]:
hit += 1
elif svart[18,15,44] == vit[14]:
hit += 1
elif svart[58,42,57] == vit[52]:
hit += 1
elif svart[68,43,66] == vit[63]:
hit += 1
elif svart[78,44,75] == vit[74]:
hit += 1
elif svart[84,88,45] == vit[85]:
hit += 1
else:
miss += 1
print hit
print miss
schack(svart,vit)
This is a so-called chess simulator, that will take a value and compare the numbers from both lists. If the numbers "threaten each other", a point will be added. If both values are the same, it will not register the hit or miss and add an extra loop turn.
I don't know if I am comparing the values to each other incorrectly or what I am doing wrong.
Any help would be highly appreciated.

The following gives the 29th element of the list "svart":
svart[28]
But the list has only 21 elements. So you are accessing an element out of the possible range. That is why you get an "list index out of range" error.

Related

how do you fix this error Can only concatenate list (not"float") to list

def Combat(player,Enemy):
userInput = input("How would you like to attack the enemy (P)ower attack, (Q)uick Attack,(C)ounter attack, or (N)ormal attack?").upper()
PlayerAttackRoll = [random.randint(1,20)-1]
EnemyAttackRoll = [random.randint(1,20)-1]
PlayerAttackBonus = player['Attack'] / 5
EnemyAttackBonus = Enemy['Attack'] / 5
PlayerDefenseBonus = player['Defense'] /5
EnemyDefenseBonus = Enemy['Defense'] / 5
if userInput == "P":
PlayerAttackBonus *= 2
EnemyAttackBonus *= 1.5
elif userInput =="Q":
PlayerAttackBonus *= 2
EnemyDefenseBonus *= 1.5
elif userInput =="C":
PlayerAttackBonus *= 2.5
PlayerAttackBonus *= 0
elif userInput =="N":
player['Attack']
while True:# This is where i keep getting the error at
PlayerDamage = PlayerAttackRoll + PlayerAttackBonus - EnemyDefenseBonus -10
EnemyDamage = EnemyAttackRoll + EnemyAttackBonus - PlayerDefenseBonus - 10
if PlayerDamage == "<=0":
print("You have missed Enemy took no damage.")
elif EnemyDamage == "<=0":
print("Enemy has missed you take no damage.")
return player,Enemy
I am making a little game but i keep getting this error
PlayerDamage=PlayerAttackRoll + PlayerAttackBonus - EnemyDefenseBonus - 10
TypeError: can only concatenate list (not "float") to list
Can someone help me fix this please.
PlayerAttackRoll is a list so when you are doing
PlayerAttackRoll + PlayerAttackBonus
It is trying to perform list concatenation.
Either
PlayerAttackRoll = random.randint(1,20)-1
or
PlayerAttackRoll = [random.randint(1,20)-1][0]
should work.
Although, you really don't need to initialize it as a list since it is a single value. Same thing with EnemyAttackRoll.

How to set an input limits on list with python 3

#room B register
#matrix method
roomB = [[],[]]
I am planning to enter only 3 units in here roomB=[[ ],[ ]] and if the first unit full, the system should suggest another unit.
def func():
row = int(input("Choose 0 or 1:"))
if (row == 0): # ROW 0 IS FOR HOUSE 1:
name = input("Enter your room name: ")
print("Enter M or N") #M for master room
room_type = input("") #N for normal room
for u in roomB: #3 units in roomB[0]
if(len(u)<3):
if (room_type == "M"):
return roomB[0].append([room_type,name,140])
if (room_type == "N"):
return roomB[0].append([room_type,name,140])
roomB = [[],[]]
def update(row): # takes sublist as argument
if len(roomB[row]) < 3: # checks if sublist length is less than 3
name = input("Enter your name: ")
room_type = input("Enter room type : M (master room) or N (normal room) : ").lower()
roomB[row].append([room_type,name,140])
return "your room no. is {} at row {}".format(roomB[row].index([room_type,name,140]) + 1, row) # returns string stating status
def func():
if len(roomB[0]) < 3 and len(roomB[1]) < 3: # ask for prompt only if space available in both sublist
row = int(input("Choose 0 or 1: ")) # allow to select row
return update(row)
elif len(roomB[0]) >= 3 and len(roomB[1]) < 3: # selects default sublist if no space on other sublist
print("No room available at 0 , selected 1 ")
return update(1) # returns string stating status
elif len(roomB[0]) < 3 and len(roomB[1]) >= 3: # selects default sublist if no space on other sublist
print("No room available at 1 , selected 0 ")
return update(0)
else: # in case any error occurs it goes here
print("Errrr.......")
print("room stat....: ", roomB)
while len(roomB[0]) <= 3 or len(roomB[1]) <= 3: # loop will flow if length of both sublist is greater than or equals to 3
if len(roomB[0]) != 0 or len(roomB[1]) != 0: # won't ask for confirmation if all all lists are empty (skips prompts for initial)
cond = input("do you want to continue?(Y/N) ").lower()
if cond == "n":
break # break the loop if pressed n or N otherwise continue to execute
elif len(roomB[0]) >= 3 and len(roomB[1]) >= 3: # error message to print if no space left in sublists
print("No room available.. Sorry for inconvinience.")
print(func())

My score list is not getting updated. Python (Tic Tac Toe)

Here is what happens.
mc_move
creates scores list and gives it to mc_update_score as an argument.
mc_update_score does all the calculations and updates the list (i checked it by print at the end of mc_update_score function.
But, on the next iteration in mc_move the scores list is set to initial value - all zeros. Though it is supposed to be the list with values from mc_update_score.
What do i miss here?
def mc_update_scores(scores, board, player):
print "scores at the begining of the function is"
print scores
for i in empty_list_score:
# iterate through all the squares of the board
col = i[1]
row = i[0]
if board.check_win() == provided.DRAW:
scores[row][col] += 0
#print score[row][col]
elif board.check_win() == provided.PLAYERX:
if board.square(row,col) == provided.PLAYERX:
scores[row][col] += SCORE_CURRENT
elif board.square(row,col) == provided.PLAYERO:
scores[row][col] -= SCORE_OTHER
else:
scores[row][col] += 0
# print score[row][col]
elif board.check_win() == provided.PLAYERO:
if board.square(row,col) == provided.PLAYERO:
scores[row][col] += SCORE_CURRENT
elif board.square(row,col) == provided.PLAYERX:
scores[row][col] -= SCORE_OTHER
else:
scores[row][col] += 0
print
print "Scores at the end"
print scores
def mc_move(board, player, trials):
global empty_list_score
empty_list_score =board.get_empty_squares()
scores = [[0 for col in range(board.get_dim())]for row in range(board.get_dim())] # create score board
# Here we create the scores list just once at function call and from here on
# it only gets updated. Like each element is getting changed by +1 or - 1.
# i do not see any spot where the entire list is being created again or
#emptied = e.g. is set to all zeros.
num = 0
while num < trials:
board_c = board.clone() # create new board for every iteration
mc_trial(board_c, player) # play a full game for every iteration
mc_update_scores(scores, board_c, player) # update score for every
#iteration after the game is played.
num +=1

Syntax error for else and elif (Can't determine if structure issue)

I'm very new to python and I've been working on a basic calculator within python for the last few hours (rhetorical I know, given what python has built in, but it's part of my learning process), I've run into an error I can't seem to fix, generally I'm able to get my scripts on their feet and running with the assistance of a couple of Google searches but this one has me stumped. I'm getting a syntax error where I have an else, and while at first I was pretty sure it was a structure issue, rewriting the script didn't fix anything, vague I know, so here's the script (I've marked the spot with a comment) :
def Calculator():
tempnums = [] #stores nums only
tempfuncs = [] #stores funcs only
tmpfuncs = {} #stores funcs only
times = lambda multiply: tempnums[0]*tempnums[1]
div = lambda divide: tempnums[0]%tempnums[1]
plus = lambda add: tempnums[0]+tempnums[1]
minus = lambda subtract:tempnums[0]-tempnums[1]
done = 0
varnum = 0
xtimes = 0
divtimes = 0
plustimes = 0
mintimes = 0
while done == 0: #USER INPUT PROCESS
varnum = varnum + 1
tempint = input() #nums
exec("num%d = tempint" % (varnum))
function = raw_input() #functions
if function != "=":
if function == 'x':
if x not in tmpfuncs:
xtimes = xtimes + 1
tmpfuncs[x] = times
else:
xtimes = xtimes + 1
exec("tmpfuncs[x%d] = times" % (xtimes)
else: #ERROR COMES HERE
if function == '//':
if dv not in tmpfuncs:
divtimes = divtimes + 1
tmpfuncs[dv] = div
else:
divtimes = divtimes + 1
exec("tmpfuncs[dv%d] = div" % (divtimes)
if function == '+':
if pls not in tmpfuncs:
plustimes = plustimes + 1
tmpfuncs[pls] = plus
else:
plustimes = plustimes + 1
exec("tmpfuncs[pls%d] = plus" % (plustimes)
if function == '-':
if mn not in tmpfuncs:
mintimes = mintimes + 1
tmpfuncs[mn] = minus
else:
mintimes = mintimes + 1
exec("tmpfuncs[mn%d] = minus" % (mintimes)
else: #user has selected to calculate input
done = 1
for i in range(1, varnum + 1):
exec("tempnums.append(num%d)" % (i)) #adding nums to a list with dynamic var names
print tmpfuncs
#next we'll make it so that tempnums[0] is the changing result as we use tempnums 0 and 1 to calculate the answer, deleting one as we go until there is only zero
Calculator()
Calculator()
I'm hoping this is legible as I'm posting from mobile (as a matter of fact I'm writing this from mobile as well).
The line above the else is missing a closing parens:
exec("tmpfuncs[x%d] = times" % (xtimes)
should be
exec("tmpfuncs[x%d] = times" % (xtimes))
The same error occurs in many other of your exec lines. Also, I suggest you consider restructuring your code so you do not need to use exec at all.

Django querysets indexes

I was wondering if using indexes on a model was possible:
class Buildings(models.Model):
island = models.ForeignKey(Island)
townhall = models.IntegerField(default=1)
lumberjack = models.IntegerField(default=0)
stonequarry = models.IntegerField(default=0)
ironmine = models.IntegerField(default=0)
[...]
a=Buildings.objects.get(somecondition)
print a.townhall # 1
a[1] +=1
print a.townhall # 2
Currently it throws
"TypeError: 'Buildings' object is
unindexable"
The reason why I'd like to do something like this is that using indexes would simplify parts of code like this:
if queue.kind_id == 0: buildings.townhall += 1
elif queue.kind_id == 1: buildings.lumberjack += 1
elif queue.kind_id == 2: buildings.stonequarry += 1
elif queue.kind_id == 3: buildings.ironmine += 1
elif queue.kind_id == 4: buildings.factory += 1
elif queue.kind_id == 5: buildings.shipyard += 1
elif queue.kind_id == 6: buildings.university += 1
to this:
buildings[queue.kind_id] +=1
The get() method doesn't return a queryset, only a single instance/object of the model class. If you want want to retrieve more than one object (=a queryset) use filter() instead!
a=Buildings.objects.filter(...)
I am not sure what you are trying to use the lumberjack, townhall etc attributes for...
I think you could do something like:
buildings_list = ['townhall', 'lumberjack', ....]
attr = buildings_list[queue.kind_id]
setattr(buildings, attr, getattr(buildings, attr) + 1)
But I am not sure what you are trying to do and if you are using django's models in the way they are inteded to be used...