Index Error: list index out of ranged (python 3.2) - python-3.2

Me and my friends are working on a project at school and we understand why the error comes up but we can not see where we made that error. We are sure that we have counted it right and we know that in an index it starts at 0 but it is still wrong. Our task is to create a game that moves players around a 7x7 grid but we have to insert some game messages from outside of the code that we are storing in the same file. P.S we are allowed to ask for help.
Here is the code Please help!:
import random
counter1 = 0
counter2 = 0
print("***********************************BOARD GAME**********************************")
print(" ")
print("***********************************GAME RULES**********************************")
print(" ")
print("----------------------------Game is for 2 players only-------------------------")
print(" ")
print(">The game board is a 10x5 board going up to 49")
print(" ")
print("40 41 42 43 44 45 46 47 48 49")
print("39 38 37 36 35 34 33 32 31 30")
print("20 21 22 23 24 25 26 27 28 29")
print("19 18 17 16 15 14 13 12 11 10")
print("0 1 2 3 4 5 6 7 8 9 ")
print(" ")
print(">The objective is to be the first player to reach space 49")
print(" ")
print(">There are 2 die, if you roll the same number twice, you will go back the number of spaces you rolled")
print(" ")
print(">If you land on spaces 27, 31 and 47, you will go back to space 24")
print(" ")
print(">Press ENTER to play")
input()
print("**********************************START GAME***********************************")
input()
print("Starting positions for both players = 0")
print(" ")
newfile=open("Game Messages.txt","r")
print(newfile.readlines()[0])
dice1 = random.randint(1,6)
print("dice 1 =",dice1)
dice2 = random.randint(1,6)
print("dice 2 =",dice2)
dicetotal = dice1 + dice2
print("dice total =",dicetotal)
if dice1 == dice2:
counter1 = counter1 - dicetotal
print(newfile.readlines()[1]) #This is one of the lines that is coming up as an error
else:
counter1 = counter1 + dicetotal
print("P1 space =",counter1)
if counter1 == 47:
counter1 = 24
print(newfile.readlines()[2])
if counter1 == 27:
counter1 = 24
print(newfile.readlines()[3])
if counter1 == 31:
counter1 = 24
print(newfile.readlines()[4])
if counter1 >= 49:
print(newfile.readlines()[5])
print("end game end game end game end game end game end game end game end game end game")
print("Press ENTER to exit the game")
exit()
input()
input()
newfile.close
newfile = open("Game Messages.txt.","r")
print(newfile.readlines()[6])
dice1 = random.randint(1,6)
print("dice 1 =",dice1)
dice2 = random.randint(1,6)
print("dice 2 =",dice2)
dicetotal = dice1 + dice2
print("dice total =",dicetotal)
if dice1 == dice2:
counter2 = counter2 - dicetotal
print(newfile.readlines()[7]) #This is one of the lines that is coming up as an error
else:
counter2 = counter2 + dicetotal
print("P2 space =",counter2)
if counter2 == 47:
counter2 = 24
print(newfile.readlines()[8])
if counter2 == 27:
counter2 = 24
print(newfile.readlines()[9])
if counter2 == 31:
counter2 = 24
print(newfile.readlines()[10])
if counter2 >= 49:
print(newfile.readlines()[11])
print("end game end game end game end game end game end game end game end game end game")
print("Press ENTER to exit the game")
exit()
input()
input()
newfile.close

Actually the problem is getting the file contents from Game Messages.txt.
So, first the whole file contents need to be converted into list.
Please follow this procedure in your program first
with open('Game Messages.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.
my_list = data.splitlines()
print(my_list) # It will give whole file contents as an array
# E.g.: ['game message1', 'game message2', 'game message3', 'game message4', 'game message5']
print(my_list[3]) # It will display game message 4
So in your program instead of
if dice1 == dice2:
counter2 -= dicetotal
print(newfile.readlines()[7]) # This is one of the lines that is coming up as an error
else:
counter2 += dicetotal
it will be
if dice1 == dice2:
counter2 -= dicetotal
print(my_list[3]) #You need to give exact line number, in case 4th means it #will be my_list[3] as array index starts with 0 only
else:
counter2 += dicetotal

Related

finding minimum values from a cut table Lua 5.1.5

I have a Lua script that turns a table into segments:
function tablecut(t, n)
local result = {}
local j = 0
for i = 1, #t do
if (i-1) % n == 0 then
j = j + 1
result[j] = {}
end
result[j][#result[j]+1] = t[i]
end
return result
end
output = tablecut({'15', '62', '14', '91', '33', '55', '29', '4'}, 4)
for i = 1, #output do
for j = 1, #output[i] do
io.write(tostring(output[i][j])..' ')
end
print()
end
output:
15 62 14 91
33 55 29 4
And I am trying to find the minima from the cut lists so the output would look like this:
15 62 14 91
min = 14
33 55 29 4
min = 4
Edit: If its of any importance this is how I got it to work on Lua 5.3 but there is no table.move function on Lua 5.1. I can't remember how my thought function worked when I wrote this code.
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
Indicies = {}
Answers = {}
function chunks(lst, size)
local i = 1
local count = 0
return function()
if i > #lst then return end
local chunk = table.move(lst, i, i + size -1, 1, {})
i = i + size
count = count + 1
return count, chunk
end
end
local a = {91,52,19,59,38,29,58,11,717,91,456,49,30,62,43,8,17,15,26,22,13,10,2,23} --Test list
for i, chunk in chunks(a, 4) do
x=math.min(a)
print(string.format("#%d: %s", i, table.concat(chunk, ",")))
table.sort(chunk)
print(math.min(chunk[1]))
table.insert(Answers, chunk[1])
table.insert(Indicies, (indexOf(a, chunk[1])))
Output:
#1: 91,52,19,59
19
#2: 38,29,58,11
11
#3: 717,91,456,49
49
your table cut function could be simplified, and your output for loop needs you use an iterator if you want to get an output simply like you do in your 5.3 script.
function cuttable(t,n)
local binned = {}
for i=1,#t,n do
local bin = {}
for j=1,n do
table.insert(bin, t[i + ((j - 1) % n)])
end
table.insert(binned, bin)
end
return binned
end
For the for loop, we can use ipairs on the output of cuttable keeping things pretty simple, then we just do the same steps of concat then sort and print out our results.
for k, bin in ipairs(cuttable(a,4)) do
local output = "#" .. k .. ":" .. table.concat(bin, ",")
table.sort(bin)
print(output)
print(bin[1])
end
Output
#1:91,52,19,59
19
#2:38,29,58,11
11
#3:717,91,456,49
49
#4:30,62,43,8
8
#5:17,15,26,22
15
#6:13,10,2,23
2
One way to implement the cutting would be using a for loop & unpack. I have handled the case of the length not being divisible by 4 after the for loop to (1) maximize performance (check doesn't need to be done every iteration) and (2) be able to directly pass the values to math.min, which doesn't accept nils.
for i = 1, math.floor(#t / 4), 4 do
print(unpack(t, i, i+4))
print("min = " .. math.min(unpack(t, i, i+4)))
end
-- If #t is not divisible by 4, deal with the remaining elements
local remaining = #t % 4
if remaining > 0 then
print(unpack(t, #t - remaining, remaining))
print("min = " .. math.min(unpack(t, #t - remaining, remaining)))
end

I am trying to make videos of 59 mins and 59 secs, but the video created is always of smaller duration

I want to create videos for multiple cameras stored in MySQL database. At intervals of every 1 hour the duration of video should be 59 mins and 59 secs. The videos should be then uploaded to azure blob storage.
However, every time a video is created, it is of a smaller duration (for example, 44 or 45 mins). I am not getting any errors. What am I doing wrong? any suggestion will be of great help. Thank You.
from threading import Thread
import threading
import cv2
import pymysql
import time
import datetime
import os
from azure.storage.blob import BlockBlobService, PublicAccess
def accessCamera(user_id, location_id, user_name, cursor):
fix_path = '/home/****/****/'
container_name = user_name
block_blob_service = BlockBlobService(account_name='******', account_key='*****+*****+****+/******')
try:
block_blob_service.create_container(container_name)
except:
pass
block_blob_service.set_container_acl(container_name, public_access=PublicAccess.Container)
cursor.execute('SELECT * FROM xxxxx where user_id = ' + str(user_id) + ' and location_id = ' + str(location_id) + '')
cameras = cursor.fetchall()
camera = {}
counter = 0
out = {}
hour = str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H'))
for x in cameras:
try:
os.makedirs(fix_path + x['ip_address'] + '_' + str(x['rtsp_port']) + '/videos/')
except:
pass
rtsp_stream_link = 'rtsp://' + x['username'] + ':' + x['password'] + '#' + x['ip_address'] + ':'
+ str(x['rtsp_port']) + '/stream=1'
out[counter] = cv2.VideoWriter(fix_path + x['ip_address'] + '_' + str(x['rtsp_port']) +
'/videos/' + str(hour) + '.avi',cv2.VideoWriter_fourcc(*'DIVX'), 1, (1920,1080))
camera[counter] = cv2.VideoCapture(rtsp_stream_link)
counter = counter + 1
print(" #==================================================")
print(" #-- Loaded Cameras Now Saving Video for Location " + str(location_id) + " - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print(" #==================================================")
framecount = 0
while True:
counter = 0
for x in cameras:
check,frame=camera[counter].read()
if check == True:
out[counter].write(frame)
else:
continue
minutes = str(datetime.datetime.fromtimestamp(time.time()).strftime('%M'))
if int(minutes) == 59 and framecount >= 3599:
out[counter].release()
block_blob_service.create_blob_from_path(container_name, fixpath + x['ip_address'] + '_'
+ str(x['rtsp_port']) + '/videos/' + hour + '.avi', x['ip_address'] + '_' + x['rtsp_port'] +
'/videos/' + hour + '.avi')
print("#==================================================")
print("#-- Video Saved - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print("#==================================================")
threading.Thread._stop(self)
exit(1)
counter = counter + 1
framecount = framecount + 1
#===========================================================================
# -- Main function
#===========================================================================
if __name__ == '__main__':
print("Time - " + str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
flag = 1
while True:
if (str(datetime.datetime.fromtimestamp(time.time()).strftime('%S')) == '54' and
str(datetime.datetime.fromtimestamp(time.time()).strftime('%M')) == '59') or flag == 1:
print("#======================================================")
print("#-- Get All Users and Locations to create Threads - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print("#======================================================")
db = pymysql.connect('xxxxxxx', 'xxxxxx', 'password', 'xxxxxx')
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor1 = db.cursor(pymysql.cursors.DictCursor)
cursor.execute('select locations.id,locations.user_id,users.username from locations inner
join users on users.id = locations.user_id')
user = cursor.fetchall()
for x in user:
thread = threading.Thread(target=accessCamera,args=
(int(x['user_id']),int(x['id']),x['username'],cursor1,))
print(" #==================================================")
print(' #-- Thread created for location ' + str(x['id']) + ' - ' +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
print(" #==================================================")
thread.daemon = True
thread.start()
time.sleep(1)
flag = 0
# print(" #==================================================")
# print(" #-- Sleeping Current Thread for 1 minutes - " +
str(datetime.datetime.fromtimestamp(time.time()).strftime('%d-%m-%Y_%H-%M-%S')))
# print(" #==================================================")

Lua math.floor return wrong value

.There is my code:
for k,v in pairs(result) do
result[k] = math.floor(v*1000)/1000
if k == 215 then
print(v, math.floor(v*1000))
end
end
for k,v in pairs(extra) do
extra[k] = math.floor(v*1000)/1000
end
Where
result[215] = 113
But when I run it by C++ Lua-Tinker, I get the print:
113, 112999
It's very confusing!
Thank to Egor Skriptunoff, I got the answer.
There is an exmple:
local num1 = 100 + 1300/100
print(num1, math.floor(num1))
local num2 = (1 + 13/100) * 100
print(num2, math.floor(num2))
And the result is:
113 113
113 112
Actually, the num2 = 112.9999999999999..., because of the 13/100.But when use 'print' to show it, there is a round action:
local a=112.99999999999 --(the count of 9 is 11)
print(a)
local b=112.999999999999 --(the count of 9 is 12)
print(b)
the result is:
112.99999999999
113

formatting strings in lua in a pattern

I want to make a script that takes any number, counts up to them and returns them in a format.
so like this
for i = 1,9 do
print(i)
end
will return
1
2
3
4
5
6
7
8
9
however I want it to print like this
1 2 3
4 5 6
7 8 9
and I want it to work even with things more than 9 so things like 20 would be like this
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20
I'm sure it can be done using the string library in lua but I am not sure how to use that library.
Any help?
function f(n,per_line)
per_line = per_line or 3
for i = 1,n do
io.write(i,'\t')
if i % per_line == 0 then io.write('\n') end
end
end
f(9)
f(20)
The for loop takes an optional third step:
for i = 1, 9, 3 do
print(string.format("%d %d %d", i, i + 1, i + 2))
end
I can think of 2 ways to do this:
local NUMBER = 20
local str = {}
for i=1,NUMBER-3,3 do
table.insert(str,i.." "..i+1 .." "..i+2)
end
local left = {}
for i=NUMBER-NUMBER%3+1,NUMBER do
table.insert(left,i)
end
str = table.concat(str,"\n").."\n"..table.concat(left," ")
And another one using gsub:
local NUMBER = 20
local str = {}
for i=1,NUMBER do
str[i] = i
end
-- Makes "1 2 3 4 ..."
str = table.concat(str," ")
-- Divides it per 3 numbers
-- "%d+ %d+ %d+" matches 3 numbers divided by spaces
-- (You can replace the spaces (including in concat) with "\t")
-- The (...) capture allows us to get those numbers as %1
-- The "%s?" at the end is to remove any trailing whitespace
-- (Else each line would be "N N N " instead of "N N N")
-- (Using the '?' as the last triplet might not have a space)
-- ^ e.g. NUMBER = 6 would make it end with "4 5 6"
-- The "%1\n" just gets us our numbers back and adds a newline
str = str:gsub("(%d+ %d+ %d+)%s?","%1\n")
print(str)
I've benchmarked both code snippets. The upper one is a tiny bit faster, although the difference is almost nothing:
Benchmarked using 10000 interations
NUMBER 20 20 20 100 100
Upper 256 ms 276 ms 260 ms 1129 ms 1114 ms
Lower 284 ms 280 ms 282 ms 1266 ms 1228 ms
Use a temporary table to contain the values until you print them:
local temp = {}
local cols = 3
for i = 1,9 do
if #temp == cols then
print(table.unpack(temp))
temp = {}
end
temp[#temp + 1] = i
end
--Last minute check for leftovers
if #temp > 0 then
print(table.unpack(temp))
end
temp = nil

Select Diagonal Elements of a Matrix in MATLAB

Consider the following matrix in MATLAB:
01 02 03 04 05 06 07
08 09 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49
I have to generate directional variograms for such 7 x 7 windows(moving) of an image. I will use nlfilter for the process but for developing the function to calculate variograms I am not able to decide how to select elements in the window. For example when I consider the central value 25, in EW direction I have to consider only 25, 26, 27 and 28; in NE direction I have to consider only 25, 19, 13 and 07 when the lag chosen is 1. Is there any standard command to do so?
You can also do it like this:
A = eye(5);
v = A(1:size(A,1)+1:end);
resulting in
v = [1 1 1 1 1]
You can write a function to get these elements yourself easily:
A = [01 02 03 04 05 06 07
08 09 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
36 37 38 39 40 41 42
43 44 45 46 47 48 49];
c = (size(A)+1)/2;
EW = A(c(1),c(2):end)
NE = diag(A(c(1):-1:1,c(2):end))
Just write this code in a function (preferably an m-file), perform your operation and pass the result back.
The diag function returns the diagonal elements of a matrix (or returns a diagonal matrix when passed a vector).
This is Generic matrix solution (not for MATLAB)
suppose matrix AxB =
[01 AA 03 04 05 06 07
08 09 AA 11 12 13 AA
AA 16 17 AA 19 AA 21
22 AA 24 25 AA 27 28
AA 30 AA 32 33 34 35
36 AA 38 AA 40 41 42
43 44 AA 46 AA 48 49];
in this matrix we want to search continuously 3 times appearence of AA diagonally.
Solution:-
step 1
for whole matrix we have to create 4 seperate for loops to search the appearence of AA continuously 3 times
i am adding method through which a user can search all loop and can find the item.
local function check_win( matrx_table)
local counter = 1
local term = "AA"
local D = 1
-- for horizontal check for win---
for i = 1, no_rows, 1 do
for j= 1, no_Columns, 1 do
if((j+1) <= no_Columns) then
if(table_mXn[i][j] == term and table_mXn[i][j+1] == term)then
counter = counter + 1;
else
counter = 1
end
if(counter == 3)then
return counter
end
end
end
end
counter = 1
-- for vertical check for win--
for i = 1, no_Columns, 1 do
for j= no_rows, 1, -1 do
if((j-1) >= 1) then
if(table_mXn[j][i] == term and table_mXn[j-1][i] == term)then
counter = counter + 1;
else
counter = 1
end
if(counter == 3)then
return counter
end
end
end
end
counter = 1
D = 1
-- for diagonol left half check for win in figure loop 1--
for m = 1, no_rows, 1 do
D = 1
for i =m, no_rows,1 do
if(i+1 <= no_rows and D+1 <= no_Columns)then
if(table_mXn[i][D] == term and table_mXn[i+1][D+1] == term)then
counter = counter + 1;
print("hhhhh")
else
counter = 1
end
if(counter == 3)then
return counter
end
D = D + 1
end
end
end
counter = 1
D = 1
-- for diagonol right half check for win in figure loop 2--
for m = 1, no_rows, 1 do
D = m
for i =1, no_rows,1 do
if(i+1 <= no_rows and D+1 <= no_Columns)then
if(table_mXn[i][D] == term and table_mXn[i+1][D+1] == term)then
counter = counter + 1;
print("hhhhh")
else
counter = 1
end
if(counter == 3)then
return counter
end
D = D + 1
end
end
end
counter = 1
D = 1
-- for diagonol left half check for win in figure loop 3--
for m = 1, no_rows, 1 do
D = no_Columns
for i =m, no_rows,1 do
if(i+1 <= no_rows and D-1 >= 1)then
if(table_mXn[i][D] == term and table_mXn[i+1][D-1] == term)then
counter = counter + 1;
print("hhhhh")
else
counter = 1
end
if(counter == 3)then
return counter
end
D = D - 1
end
end
end
counter = 1
D = 1
-- for diagonol left half check for win in figure loop 4--
for m = no_Columns, 1, -1 do
D = m
for i =1, no_rows,1 do
if(i+1 <= no_rows and D-1 >= 1)then
if(table_mXn[i][D] == term and table_mXn[i+1][D-1] == term)then
counter = counter + 1;
print("hhhhh")
else
counter = 1
end
if(counter == 3)then
return counter
end
D = D - 1
end
end
end
end
now you can call this method any where in class and can check in that matrix the searchable item is available or not in repeatedly order Horizontally, Vertically and diagonally.

Resources