Index out of range error Python greedy method - python

Hello I am currently getting an index out of range error from the following code: (I will post the code first and then the error)
Main File:
import Knapsack_Test
size = 10
W = 2*size
knapsack = Knapsack_Test.Knapsack_Test()
for i in range(1, 10):
knapsack.greedy_knapsack_test(size, W)
size = size + 10*i
W = 2*size
Class File (Only the greedy function):
def greedy_knap(self, v, w, W):
knap_array = []
for i in range(1, len(v)):
#The index out of range error occurs here:
knap_array[i] = [v[i],w[i]]
sort_order = self.sort.merge_sort(knap_array)
weight = 0
value = 0
knap_sac= []
n = len(knap_array)
j = 0
profit = 0
while weight < W and j < n:
if weight + knap_array[i][1] <= W:
knap_sac.append(knap_array[i])
weight = weight + knap_array[i][1]
profit = profit + knap_array[i][0]
j = j + 1
return profit
The test File (for greedy function):
def greedy_knapsack_test(self, size, W):
v = []
w = []
for i in range(1,size):
v.append(random.randint(1,1000))
for i in range(1,size):
w.append(random.randint(1,1000))
start = time.time()
self.knapsack.greedy_knap(v, w, W)
end = time.time() - start
return end
The Error:
Traceback (most recent call last):
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Main.py", line 10, in <module>
knapsack.greedy_knapsack_test(size, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\Knapsack_Test.py", line 31, in greedy_knapsack_test
self.knapsack.greedy_knap(v, w, W)
File "\\minerfiles.mst.edu\dfs\users\asadmb\Desktop\Programming 3\KnapsackClass.py", line 30, in greedy_knap
knap_array[i] = [v[i],w[i]]
IndexError: list assignment index out of range

knap_array = []
for i in range(1, len(v)): #The index out of range error occurs here:
knap_array.append([v[i],w[i]])
you can't create list element by referencing them.

Related

Cant figure out this error -> IndexError: list index out of range

So i have been working on this code for a while and i cant fin a solution to this problem and i was wondering if anyone in here could help me solve this? The problem is supposed to be in the method "hent_celle" where it takes in a coordinate from a grid and returns the object that is in that position.
The error is:
Traceback (most recent call last):
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 105, in <module>
print(testobjekt._sett_naboer(2,1))
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 64, in
_sett_naboer nabo_u_kol = self.hent_celle(rad+1,kol)
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 43, in hent_celle
return self._rutenett[rad][kol] IndexError: list index out of range
And the code is:
from random import randint
from celle import Celle
class Rutenett:
def init(self,rader,kolonner):
self._ant_rader = int(rader)
self._ant_kolonner = int(kolonner) self._rutenett = []
def _lag_tom_rad(self):
liste = []
for x in range(self._ant_kolonner):
liste.append(None)
return liste
def _lag_tomt_rutenett(self):
liste2 = []
for x in range(self._ant_rader):
liste_ = self._lag_tom_rad()
liste2.append(liste_)
self._rutenett = liste2
def lag_celle(self,rad,kol):
celle = Celle()
tilfeldig_tall = randint(0,100)
if tilfeldig_tall <= 33:
celle.sett_levende()
return celle
else:
return celle
def fyll_med_tilfeldige_celler(self):
for x in self._rutenett:
for y in x:
rad = int(self._rutenett.index(x))
kol = int(x.index(y))
self._rutenett[rad][kol] = self.lag_celle(rad,kol)
def hent_celle(self,rad,kol):
if rad > self._ant_rader or kol > self._ant_kolonner or rad < 0 or kol < 0:
return None
else:
return self._rutenett[rad][kol]
def tegn_rutenett(self):
for x in self._rutenett:
for y in x:
print(y.hent_status_tegn(), end="")
def hent_alle_celler(self):
liste = []
for x in self._rutenett:
for y in x:
liste.append(y)
return liste
def _sett_naboer(self,rad,kol):
cellen = self.hent_celle(rad,kol)
# lik linje
nabo_v_rad = self.hent_celle(rad,kol-1)
nabo_h_rad = self.hent_celle(rad,kol+1)
# under
nabo_u_kol = self.hent_celle(rad+1,kol)
nabo_u_kol_h = self.hent_celle(rad+1,kol+1)
nabo_u_kol_v = self.hent_celle(rad+1,kol-1)
# over
nabo_o_kol = self.hent_celle(rad-1,kol)
nabo_o_kol_h = self.hent_celle(rad-1,kol+1)
nabo_o_kol_v = self.hent_celle(rad-1,kol-1)
liste = [nabo_v_rad,nabo_h_rad,nabo_u_kol_h,nabo_u_kol_v,nabo_o_kol,nabo_o_kol_h,nabo_o_kol_v]
#print(liste)
#print(nabo_o_kol_h)
for x in liste:
if x == None:
pass
else:
cellen._naboer.append(x)
return cellen._naboer
def antall_levende(self):
teller = 0
for x in self._rutenett:
for y in x:
if y._status == "doed":
pass
else:
teller +=1
return teller
testobjekt = Rutenett(3,3)
testobjekt._lag_tomt_rutenett()
testobjekt.fyll_med_tilfeldige_celler()
print(testobjekt._sett_naboer(2,1))
I just cant figure out why the list index is out of range
Pyhton list indexes start at 0, which means a list with 10 elements will use indices 0-9. Assuming self._ant_rader and self._ant_kolonner are the number of rows and columns, then rad and kol would need to be less than those values and cannot be the same value, or you get an index out of bounds error.
Fixed version of the method:
def hent_celle(self,rad,kol):
if rad >= self._ant_rader or kol >= self._ant_kolonner or rad < 0 or kol < 0:
return None
else:
return self._rutenett[rad][kol]
As you can see, the > has been replaced with >= instead. This means indices which are out of bounds will return None.

IndexError: index -1 is out of bounds for axis 0 with size 0

I get an index -1 is out of bounds for axis 0 with size 0 error from scipy when trying to implement a text generator with ngrams.
Traceback (most recent call last):
File "C:\Users\hp\PycharmProjects\N-gram poems\trigram_model.py", line 125, in <module>
generate()
File "C:\Users\hp\PycharmProjects\N-gram poems\trigram_model.py", line 118, in generate
singleverse(int(c))
File "C:\Users\hp\PycharmProjects\N-gram poems\trigram_model.py", line 80, in singleverse
result = stats.multinomial.rvs(1, word_probabilities)
File "C:\Users\hp\PycharmProjects\N-gram poems\venv\lib\site-packages\scipy\stats\_multivariate.py", line 3242, in rvs
n, p, npcond = self._process_parameters(n, p)
File "C:\Users\hp\PycharmProjects\N-gram poems\venv\lib\site-packages\scipy\stats\_multivariate.py", line 3036, in _process_parameters
p[..., -1] = 1. - p[..., :-1].sum(axis=-1)
IndexError: index -1 is out of bounds for axis 0 with size 0
It's in a for loop and when the error occurs changes each time. Some times it does not occur at all. It mostly occur close to the end of the program.
This is the code where the error occurs:
def singleverse(num):
TrTrigrams = [((filtered_tokens[i], filtered_tokens[i + 1]), filtered_tokens[i + 2]) for i in
range(len(filtered_tokens) - 2)]
TrTrigramCFD = nltk.ConditionalFreqDist(TrTrigrams)
TrTrigramPbs = nltk.ConditionalProbDist(TrTrigramCFD, nltk.MLEProbDist)
rand = random.choice(random_choice_list)
start_word = ('<s>', rand)
data = []
for i in range(10):
probable_words = list(TrTrigramPbs[start_word].samples())
word_probabilities = [TrTrigramPbs[start_word].prob(word) for word in probable_words]
result = stats.multinomial.rvs(1, word_probabilities)
index_of_probable_word = list(result).index(1)
start_word = (start_word[1], (probable_words[index_of_probable_word]))
data.append(start_word[1])
line = []
for i in data:
if i != "<s>" and i != "</s>":
line.append(i)
poem_line = ' '.join([str(i) for i in line]).capitalize()
print(poem_line)
def generate():
"""Generates the final poem with user input of structure."""
print("What structure do you want?(e.g., 3 x 4, 2 x 4, 2 x 5): ")
while True:
try:
x, y, z = input().split()
except:
print("Enter the structure as shown above.")
continue
break
while True:
try:
for stanza in range(1):
for first_verse in range(1):
b = random.randint(7, 12)
firstverse(int(b))
for verse in range(int(z) - 1):
a = random.randint(7, 12)
singleverse(int(a))
print('\n')
for stanza in range(int(x) - 1):
for verse in range(int(z)):
c = random.randint(7, 12)
singleverse(int(c))
print('\n')
except KeyError:
print("This was not a valid seed word please try again.")
continue
break
generate()

TypeError: int object is not iterable when trying to use a list of prime numbers

So I have been writing a function to generate a key as a tuple using randomly generated prime numbers, and when I try to run the code it generates the error(s),
PS C:\Users\cinna\workspace\project4> py rsa.py S
Traceback (most recent call last):
File "C:\Users\cinna\workspace\project4\rsa.py", line 104, in <module>
_main()
File "C:\Users\cinna\workspace\project4\rsa.py", line 91, in _main
n, e, d = keygen(25, 100)
File "C:\Users\cinna\workspace\project4\rsa.py", line 10, in keygen
primes = _primes(lo, hi)
File "C:\Users\cinna\workspace\project4\rsa.py", line 69, in _primes
primes += p
TypeError: 'int' object is not iterable
Edit: Here is my code for keygen(), _primes() and main(). Thanks for the patience, still learning StackOverflow etiquette.
def keygen(lo, hi):
primes = _primes(lo, hi)
for i in range(lo, hi):
if _primes(i):
ptemp = stdrandom.uniformInt(0, len(primes))
qtemp = stdrandom.uniformInt(0, len(primes))
p = primes[ptemp]
q = primes[qtemp]
n = p * q
m = (p - 1) * (q - 1)
while True:
e = stdrandom.uniformInt(2, m)
if e % m == 0 and m % e != 0:
break
d = 0
for a in range(1, m):
if (e * a) % m == 1:
d = a
break
return n, e, d
def _primes(lo, hi):
primes = []
for p in range(lo, hi + 1):
j = 2
f = 1
while(j * j <= p):
if(p % j == 0):
f = 0
break
j = j + 1
if(f == 1):
primes += p
return primes
def _main():
x = ord(sys.argv[1])
n, e, d = keygen(25, 100)
encrypted = encrypt(x, n, e)
stdio.writef('encrypt(%c) = %d\n', x, encrypted)
decrypted = decrypt(encrypted, n, d)
stdio.writef('decrypt(%d) = %c\n', encrypted, decrypted)
width = bitLength(x)
stdio.writef('bitLength(%d) = %d\n', x, width)
xBinary = dec2bin(x, width)
stdio.writef('dec2bin(%d) = %s\n', x, xBinary)
stdio.writef('bin2dec(%s) = %d\n', xBinary, bin2dec(xBinary))
if __name__ == '__main__':
_main()
The problem is this expression:primes += p
You can use that operator, but it works like this:
[1,2,3,4] = [1,2,3,4] + x
Now x has to be a list so that this expression works. It just concatenates to lists together.
You are trying to append an int to a list, which is illegal. You can append a list to a list. Try doing primes += [p] or primes.append(p).

How to avoid out of memory python?

I'm new to python and ubuntu. i got killed after running python code. The file I'm using for the code is around 2.7 GB and I have 16 GB RAM with one tera hard ... what should I do to avoid this problem because I'm searching and found it seems to be out of memory problem
I used this command
free -mh
I got
total used free shared buff/cache available
Mem: 15G 2.5G 9.7G 148M 3.3G 12G
Swap: 4.0G 2.0G 2.0G
the code link I tried Link
import numpy as np
import matplotlib.pyplot as plt
class ProcessData(object):
def data_process(self, folder):
'''
:folder: data file path
:rtype: dict pair distance
MAX id number
'''
distance = dict()
max_pt = 0
with open(folder, 'r') as data:
for line in data:
i, j, dis = line.strip().split()
i, j, dis = int(i), int(j), float(dis)
distance[(i, j)] = dis
distance[(j, i)] = dis
max_pt = max(i, j, max_pt)
for num in range(1, max_pt + 1):
distance[(num, num)] = 0
return distance, max_pt
def entropy(self, distance, maxid, factor):
'''
:distance: dict with pair: dist
:factor: impact factor
:maxid: max elem number
:rtype: entropy H in data field
'''
potential = dict()
for i in range(1, maxid + 1):
tmp = 0
for j in range(1, maxid + 1):
tmp += np.exp(-pow(distance[(i, j)] / factor, 2))
potential[i] = tmp
z = sum(potential.values())
H = 0
for i in range(1, maxid + 1):
x = potential[i] / z
H += x * np.log(x)
return -H
def threshold(self, dist, max_id):
'''
:rtype: factor value makes H smallest
'''
entro = 10.0
# given data:
# 0.02139999999999999 7.203581306901208
# 0.02149999999999999 7.203577254067677
# 0.02159999999999999 7.203577734107922
# generate data:
# 0.367020, 6.943842
# 0.368959, 6.943840
# 0.370898, 6.943841
scape = np.linspace(0.330, 0.430, 50)
# 通用数据使用以下一行
# scape = np.linspace(0.001, 1.001, 100)
for factor in scape:
value = self.entropy(dist, max_id, factor)
print('factor: {0:.6f}, entropy: {1:.8f}'.format(factor, value))
# plt.scatter(factor, value, c='r', s=1)
if value and value < entro:
entro, thresh = value, factor
thresh = 3 * thresh / pow(2, 0.5)
"""
plt.xlabel(r'$\sigma$')
plt.ylabel(r'H')
plt.savefig('./images/Entropy test.png')
plt.close()
"""
print('current: ', entro, thresh)
# given data: 7.203577254067677 0.04560838738653229
# generate data: 6.943840312796875 0.7828967189629044
return thresh
def CutOff(self, distance, max_id, threshold):
'''
:rtype: list with Cut-off kernel values by desc
'''
cut_off = dict()
for i in range(1, max_id + 1):
tmp = 0
for j in range(1, max_id + 1):
gap = distance[(i, j)] - threshold
tmp += 0 if gap >= 0 else 1
cut_off[i] = tmp
sorted_cutoff = sorted(cut_off.items(), key=lambda k:k[1], reverse=True)
return sorted_cutoff
def Guasse(self, distance, max_id, threshold):
'''
:rtype: list with Gaussian kernel values by desc
'''
guasse = dict()
for i in range(1, max_id + 1):
tmp = 0
for j in range(1, max_id + 1):
tmp += np.exp(-pow((distance[(i, j)] / threshold), 2))
guasse[i] = tmp
sorted_guasse = sorted(guasse.items(), key=lambda k:k[1], reverse=True)
return sorted_guasse
def min_distance(self, distance, srt_dens, maxid):
'''
:srt_dens: desc sorted list with density values (point, density)
:rtype: min distance dict
min number dict
'''
min_distance = dict()
min_number = dict()
h_dens = srt_dens[0][0]
min_number[h_dens] = 0
max_dist = -1
for i in range(1, maxid + 1):
max_dist = max(distance[(h_dens, i)], max_dist)
min_distance[h_dens] = max_dist
for j in range(1, len(srt_dens)):
min_dist, min_num = 1, 0
current_num = srt_dens[j][0]
for k in srt_dens[0:j]:
current_dist = distance[(current_num, k[0])]
if current_dist < min_dist:
min_dist, min_num = current_dist, k[0]
min_distance[srt_dens[j][0]] = min_dist
min_number[current_num] = min_num
return min_distance, min_number
def make_pair(self, srt_dens, min_dist, maxid):
'''
:rtype: pair dict with {point: [density, min dist]}
refer factor dict with {point: density * dist}
'''
pair_dict = dict()
dens_dict = dict()
refer_dict = dict()
# convert list to dict
for elem in srt_dens:
dens_dict[elem[0]] = elem[1]
if len(dens_dict) == maxid:
for key in dens_dict.keys():
pair_dict[key] = [dens_dict[key], min_dist[key]]
refer_dict[key] = dens_dict[key] * min_dist[key]
else:
return print('missing %d value', maxid - dens_dict)
return pair_dict, refer_dict
def show_pair_info(self, pair, threshold):
show_dict = dict()
for p in pair.values():
show_dict[p[0]] = p[1]
tmp = sorted(show_dict.items())
dens, mdis = zip(*tmp)
plt.scatter(dens, mdis)
plt.xlabel(r'$\rho$')
plt.ylabel(r'$\delta$')
plt.title(r'$d_c=$' + str(threshold))
plt.savefig('./images/Decision Graph Cutoff test.png')
plt.close()
I tried to figure by using fil-profile and got a problem with line 11 which indicate this data_process
An issue could be f.readlines() as it creates a complete list.
So if COOR_DATA is very large then you should only create memory for one line at a time, so try changing:
with open(COOR_DATA, 'r', encoding='utf-8') as f:
lines = f.readlines()
coords = dict()
for line in lines:
To:
with open(COOR_DATA, 'r', encoding='utf-8') as f:
coords = dict()
for line in f:
See https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

my string index is out of range in this cipher code

def cipherText():
text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key = int(input("Enter numerical key--"))
word = str(input("Type word to be ciphered--"))
i = 0
k = 0
n = len(word)
print(n)
while n >= 0:
letter = word[i]
i = i + 1
while k <= 25:
textLetter = text[k]
if textLetter == letter:
givenLetter = letter
if k < (25 - key):
cipherLength = k + key
else:
cipherLength = k + key - 25
print(text[cipherLength])
k = k + 1
n = n - 1
cipherText()
WHEN I RUN THIS FOLLOWING MESSAGE POPS OUT:
Traceback (most recent call last): File "main.py", line 23, in
cipherText() File "main.py", line 10, in cipherText
letter=word[i] IndexError: string index out of range
You need to modify condition while n>=0:, as list starts with 0th index.
this line,
while n>=0:
should be,
while n-1>=0:

Categories

Resources