List index out of range that I can't see - python

I do understand what that error means but can someone explain what am I doing wrong with this particular code? Basically, path = [A,B,C,D] and I am just creating [4][4] (final) 2-dimensional array, that swaps the neighboring indices. The swaping begins with the last element and the element before that and goes to the beginning of the list as loop goes. So at the end I should get [[A,B,D,C][A,C,B,D],[B,A,C,D],[D,B,C,A]]
t = -1
s = 1
y = []
final = []
path = self.path #path = [A,B,C,D]
for x in path:
y.append(path)
if s < 4: #Just ensuring to not get out of range
y[-s],y[-s-1] = y[-s-1],y[-s]
else:
y[-1],y[0] = y[0],y[-1]
final.append(y)
y = [] # So I won't create multi-dimensional list
Error: list index out of range

Here's a piece of code that works and is readable:
path= ['A','B','C','D']
final= []
for index in range(len(path)):
row= path[:] # copy the original list
row[index-1],row[index]= row[index],row[index-1] # swap 2 elements
final.insert(0, row) # insert at the start so the order is as expected
print(final)

Because here your y becomes [[A, B, C, D]]not [A, B, C, D]. So it has only one element.

Related

Trouble Comparing Items in List

I have some code that inputs the current market price into a list, and then compares the last two values in that list (in theory). When the market goes up, it prints to the terminal market is up, when down, market is down. However, my code is always printing market is down (I have checked and the market is indeed up between scrapes). What am I doing wrong? I have a sneaking suspicion I don't understand list indexing.
Code:
tickers = ['^N225']
for ticker in tickers:
ticker_yahoo = yf.Ticker(ticker)
data = ticker_yahoo.history()
last_quote = data['Close'].iloc[-1]
L = float(last_quote)
M = trunc(L)
f = open('market.txt', 'a')
f.write(str(L))
f.write('\n')
f.write(str(L))
print(M)
list = []
list.append(M)
N = list[-1]
O = list[0]
if N > O:
print("Market is up")
else:
print("Market is down")
time.sleep(10)```
May be I'm missing something,
It looks like you are appending a float (M) to an empty list (list)
so list[0] and list[-1] are both M.
If M is a list (?)
using "append" insert a single element so you generate a list of list with a single list element
list = []
other = [1,2,3,4]
list.append(other) # [[1, 2, 3, 4]]
print(list[0]) # [1,2,3,4]
print(list[-1]) # [1,2,3,4]
# you should prefer
list = []
other = [1,2,3,4]
list.extend(other)
print(list[0]) # 1
print(list[-1]) # 4
# expected ?
print(list[-2]) # 3
simply why not making comparison on M items (if M is a list)

Compare each element of a list in existing order with elements of a second list in order as long as items in lists are equal

Compare each element of a list in existing order with elements of a second list in existing order as long as items in lists are equal. Stop if they're not equal and give me as result the index and name of the last match.
I thought it's straightforward with a while loop but it seems like this has to be approached with a for-loop.
My List one I want to compare:
nk_script_file_path
['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
My second list I want to compare it to:
node_filepath
['P:', 'Projects', '2019_projects', '1910_My_Project', '02_Production_OUT', '01_OFX', '01_Comp', '00_Nuke', '040_ALY', '040_ALY_040_HROTERRORBLADE', '040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov', '040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov']
What I've tried
nk_script_file_path = r"P:/Projects/2019_projects/1910_My_Project/01_Production_IN/01_OFX/01_Comp/00_SO/relink_test_v001.nk".split("/")
node_filepath = r"P:/Projects/2019_projects/1910_My_Project/02_Production_OUT/01_OFX/01_Comp/00_S=/040_ALY/040_ALY_040_HROTERRORBLADE/040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov/040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov".split("/")
# Compare file paths
path_object = 0
while nk_script_file_path in node_filepath:
path_object += 1
print path_object
print node_filepath[path_object]
Result I'm looking for:
"3"
or
"1910_My_Project"
You can use zip() with enumerate() to find first index where's difference. In this example if no difference is found, value of i is equal to -1:
lst1 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '01_Production_IN', '01_OFX', '01_Comp', '00_Nuke', 'relink_test_v001.nk']
lst2 = ['P:', 'Projects', '2019_projects', '1910_My_Project', '02_Production_OUT', '01_OFX', '01_Comp', '00_Nuke', '040_ALY', '040_ALY_040_HROTERRORBLADE', '040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov', '040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov']
for i, (a, b) in enumerate(zip(lst1, lst2)):
if a != b:
break
else:
i = -1
print('First difference is at index:', i)
Prints:
First difference is at index: 4
nk_script_file_path= r"P:/Projects/2019_projects/1910_My_Project/01_Production_IN/01_OFX/01_Comp/00_SO/relink_test_v001.nk".split("/")
node_filepath = r"P:/Projects/2019_projects/1910_My_Project/02_Production_OUT/01_OFX/01_Comp/00_S=/040_ALY/040_ALY_040_HROTERRORBLADE/040_ALY_040_HROTERRORBLADE_prev_Gamma22_apcs_mov/040_ALY_040_HROTERRORBLADE_prev_v14_Gamma22_apcs.mov".split("/")
j = 0
for i in nk_script_file_path:
if i != node_filepath[j] :
j = j-1
break
else:
j += 1
print(nk_script_file_path[j])
print(j)

How to add a number to a concatenative pair of coordinates within a sublist consecutively?

I have the following list of coordinates:
coords=[[(1,2),(3,4),(5,6)], [(7,8),(9,10)], [(11,12),(13,14),(15,16),(17,18)]]
Now I to converted it to a following list using the
[m for n in coords for m in zip(n, n[1:])]
coords=[((1,2),(3,4)), ((3,4),(5,6)), ((7,8),(9,10)), ((11,12),(13,14)), ((13,14),(15,16)), ((15,16),(17,18))]
so now I like to add a constant value (does not matter the value) to the first set (x+a,y+a) coordinates from previous list such as the following:
coords=[((1,2),(3,4)), ((3+a,4+a),(5,6)), ((7,8),(9,10)), ((11,12),(13,14)), ((13+a,14+a),(15,16)), ((15+a,16+a),(17,18))]
My intention is make the shared coordinates slightly different so that they have not intersected.
This code will do it:
x = [m if i == 0 else ((m[0][0] + a, m[0][1] + a), m[1]) for n in coords for i, m in enumerate(zip(n, n[1:]))]
Explanation:
in coords you have items like ((1,2),(3,4)), ((3+a,4+a),(5,6)), you should add a to all first tuples in item except first group
for i, m in enumerate(zip(n, n[1:])) returns item in format index_of_item, item
m if i == 0 else ((m[0][0] + a, m[0][1] + a), m[1])
Don't modify tuple for first element, else add a to first tuple of 2
I would have done something like
_ = None # temp value
a = 11111 # the number you want to add
result=[]
for i,j in coords:
if i == _: # if the past value is the same as the new one
_i = (i[0]+a,i[1]+a)
result1.append((_i, j)) # modify the new one
else:
result.append((i,j))
_=j # set the current value to temp
So you create a temp variable then compare it with the new one, if the new variable is equal to the new one you add.

How to handle index of out range and invalid syntax for a sample with binary values in a list of lists in Pytjon? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The following is my sample that consists of binary values 0 and 1
sample = [['0100','0101','0101''],['011','100','001','001'],['001','001','001']]
For any number of elements in the list and any number of elements in the list of lists I need to do the following:
A. Convert it into a list of lists such that the corresponding elements of each list are strung together in a list of lists
column = [['000','111','000','0111'],['0100','1000','1011'],['000','000','111']
B. Create a counter(nn) to count length of each element and divide by (nn-1)
nn = [[3,3,3,3],[4,4,4],[3,3,3]]
nn - 1 = [[2,2,2,2],[3,3,3,3],[2,2,2]]
d = nn-1
div = nn/d
C. Need to calculate a parameter for pi. Here is a link showing how this can be done for a list https://eval.in/672980.
I have tried to write the code for the same. I hit the following errors:
A. l += seq_list[j][i]
IndexError: list index out of range.
I am certain that i,j and k are all in the correct range.
B. counters = [Counter(sub_list) for sub_list in column]
^
SyntaxError: invalid syntax
Why is it invalid syntax?
Any ideas on how to correct the errors? I tried different ways to do the same, but I am unable to do so.
#Tranposing. Moving along the columns only
column = []
for k in range(len(seq_list)):
for i in range(len(seq_list[k][0])): #Length of the row
l = ""
for j in range(len(seq_list[k])): #Length of the column
l += seq_list[j][i]
column.append(l)
print "\n Making the columns as a list: " + str(column)
#Creating a separate list where -/? will not be part of the sequence
tt = ["".join(y for y in x if y in {'0','1'}) for x in column]
#Creating a counter that stores n/n-1 values
counters = [Counter(sub_list) for sub_list in tt]
nn =[]
d = []
for counter in counters:
binary_count = sum((val for key, val in counter.items() if key in "01"))
nn.append(binary_count)
d = [i - 1 for i in nn]
div = [int(b) / int(m) for b,m in zip(nn, d)]
I think this should work for you:
seq_list = [['0100','0101','0101'],['011','100','001','001'],['001','001','001']]
results = []
for k in range(len(seq_list)):
column_list = [[] for i in range(len(seq_list[k][0]))]
for seq in seq_list[k]:
for i, nuc in enumerate(seq):
column_list[i].append(nuc)
tt = ["".join(y for y in x if y in {'0','1'}) for x in column_list]
results.append(tt)
### Creating a counter that stores n/n-1 values
BINARY = {'0','1'}
counts = [[sum(c in BASES for c in s) for s in pair] for pair in results]
countsminusone1 = [[(sum(c in BINARY for c in s)-1) for s in pair] for pair in results]
countsminusone = [[1 if x <= 0 else x for x in pair] for pair in countsminusone1]
bananasplit = [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(counts, countsminusone)]

Out of range issue within a loop

I try to make a script allowing to loop through a list (tmpList = openFiles(cop_node)). This list contains 5 other sublists of 206 components.
The last 200 components of the sublists are string numbers ( a line of 200 string numbers for each component separated with a space character).
I need to loop through the main list and create a new list of 5 components, each new component containing the 200*200 values in float.
My actual code is try to add a second loop to an older code working with the equivalent of one sublist. But python return an error "Index out of range"
def valuesFiles(cop_node):
tmpList = openFiles(cop_node)
valueList = []
valueListStr = []*len(tmpList)
for j in range (len(tmpList)):
tmpList = openFiles(cop_node)[j][6:]
tmpList.reverse()
for i in range (len(tmpList)):
splitList = tmpList[i].split(' ')
valueListStr[j].extend(splitList)
#valueList.append(float(valueListStr[j][i]))
return(valueList)
valueListStr = []*len(tmpList) does not do what you think it does, if you want a list of lists use a list comp with range:
valueListStr = [[] for _ in range(len(tmpList))]
That will create a list of lists:
In [9]: valueListStr = [] * i
In [10]: valueListStr
Out[10]: []
In [11]: valueListStr = [[] for _ in range(i)]
In [12]: valueListStr
Out[12]: [[], [], [], []]
So why you get an error is because of valueListStr[j].extend(splitList), you cannot index an empty list.
You don't actually seem to return the list anywhere so I presume you actually want to actually return it, you can also just create lists inside the loop as needed, you can also just loop over tmpList and openFiles(cop_node):
def valuesFiles(cop_node):
valueListStr = []
for j in openFiles(cop_node):
tmpList = j[6:]
tmpList.reverse()
tmp = []
for s in tmpList:
tmp.extend(s.split(' '))
valueListStr.append(tmp)
return valueListStr
Which using itertools.chain can become:
from itertools import chain
def values_files(cop_node):
return [list(chain(*(s.split(' ') for s in reversed(sub[6:]))))
for sub in openFiles(cop_node)]
def valuesFiles(cop_node):
valueListStr = []
for j in openFiles(cop_node):
tmpList = j[6:]
tmpList.reverse()
tmp = []
for s in tmpList:
tmp.extend(s.split(' '))
valueListStr.append(tmp)
return valueListStr
After little modification I get it to work as excepted :
def valuesFiles(cop_node):
valueList = []
for j in range (len(openFiles(cop_node))):
tmpList = openFiles(cop_node)[j][6:]
tmpList.reverse()
tmpStr =[]
for s in tmpList:
tmpStr.extend(s.split(' '))
tmp = []
for t in tmpStr:
tmp.append(float(t))
valueList.append(tmp)
return(valueList)
I don't understand why but the first loop statement didn't work. At the end the I had empty lists like so : [[],[],[],[],[]] . That's why I changed the beginning. Finally I converted the strings to floats.

Categories