Python - list index out of range - genetic algorithm - python

I'm having problems with my code and I know this problem is simple but I just can't figure it out how to solve it, I'll really appreciate if someone could tell me what I'm doing wrong:
import random
from math import *
def create_population(dim,pn):
t = log(factorial(dim**2),2)
b = int(t+1)
d = ""
indarray = []
bits_array=[]
#print("bits usados: ",b)
for x in range(pn):
for y in range(b) :
if random.randint(0,400000) %2:
d = "1"+d
else:
d="0"+d
num=int(d,2)%factorial(dim**2)
bits_array.append(d)
indarray.append(num)
#print("\n index #",len(indarray),": ",num)
d=""
return indarray,dim,bits_array,b
def i2ms(index,b):
squares=[]
a=init_a(b)
i=0
t=b
b = (b**2)-1
for i in range(len(index)):
s=""
cont = 1
while(index[i]>0):
c = factorial(b)
ind =(index[i]/c)
s = s+str(a[int(ind)])+" "
del a[(int(ind))]
index[i] = index[i]%c
b-=1
cont +=1
for i in range(len(a)):
s = s+str(a[i])+" "
squares.append(s)
a = init_a(t)
b = t
b = (b**2)-1
s=""
return squares
def init_a(b):
a=[]
for i in range(b**2):
a.append(i+1)
return a
def score(squares):
scores=[]
print("\n")
for i in range(len(squares)):
r = squares[i]
r = r.split(' ')
n = int(sqrt(len(r)))
nd = r
goal = n * (n * n + 1) / 2;
nd.reverse()
m = [[nd.pop() for i in range(n)] for j in range(n)]
#print ("Cubo #",i+1,": \n")
#for i in range(n):
#print(m[i],'\n')
min_sum,max_sum= 0,0
minn = 1
maxx = n * n
for i in range (n):
min_sum += minn
minn += 1
max_sum += maxx
maxx += 1
min_b,max_b = abs(goal - min_sum), abs(goal - max_sum)
if min_sum < max_sum:
final_b = max_sum
else:
final_b = min_sum
total_cases = 2 * n + 2
bias = total_cases * final_b
fitness = bias
#print ("Max score: ",fitness)
for i in range(n):
s =0
for j in range(n):
s +=int(m[i][j])
fitness -= abs(goal-s)
for j in range(n):
s=0
for i in range(n):
s += int(m[i][j])
fitness -= abs(goal-s)
s = 0
if n%2 == 1:
for i in range(n):
s+= int(m[i][i])
fitness -= abs(goal-s)
m.reverse()
s = 0
for i in range(n):
s+= int(m[i][i])
fitness -= abs(goal-s)
#print("Actual score: ",fitness,"\n")
scores.append(int(fitness))
#print("goal",goal)
return scores,bias
def breed(popul,score,breed_size,b):#popul= la poblacion , score : sus notas ind, breed_size, tamaño de poblacion que esco
#escogeremos, b numero de bites;
#Calculamos las medidas de la poblacion a "mergear"
print(popul)
print(score)
maxx = max(score)
#Acomodamos los cubos(en binario) con su respectivo score
breed_pop=[]
new_pop=[]
for y in range(breed_size):
for z in score:
if score[z] == maxx:
breed_pop.append(popul[z])
del score[z]
del popul[z]
maxx= max(score)
print(breed_pop)
if breed_pop>breed_size:
breed_pop.pop()
print(breed_pop)
##sorted(pop_dict.values())
if __name__ == '__main__':
#Dar Dimensiones y determinar la poblacion inicial
print("dimensiones?")
n = input()
print("poblacion?")
pn = input()
print("breed size?")
p= int(input())
##g = input()
#Pasar los datos de dim y pob por el metodo de create_population, devuelve una lista con los index del cubo y su dimensiones
ind,b,bits_a,bitsn= create_population(int(n),int(pn))
#Convertimos cada uno de esos indices a un cubo magico con i2ms, devuelve un array de cubos magicos
squares = i2ms(ind,b)
'''print("\n")
for i in range(len(squares)):
print("Cubo #",i+1,": " , squares[i])
#Pasamos cada cubo por score, nos dara el puntaje de cada cubo, devuelve una lista con los scores y el puntaje maximo
'''
scores,perfect = score(squares)
breed(bits_a,scores,p,bitsn)
'''for y in range(len(scores)):
print(scores[y],"/",perfect)
'''
I'm using dimension = 3, population =10, and breed_size=4 but I keep getting:
if score[z] ==max
IndexError: list index out of range
Edit:
Traceback(most recent call last):
File "squaresolver.py",line 156 in
breed(bits:a,scores,p,bitsn)
File "squaresolver.py", line 125, in breed
if score[z] == maxx:
IndexError: list index out of range

You don't need "score[z]" when you do "for z in score", z is not an index, is a value of the score list.
You can just do
if z == maxx

As you delete things in a list, you end up with index problems using range(len). If you have a list and then delete an item in it, you end up with a list whose length is now one less. This leads to IndexErrors as you try to access up to the original len(list).
Perhaps think of copying the original and working with that.

Related

Connect 4 add element from User in LIST PYTHON

I have created the matrix, but when the data entered by the user is added the board loses the initial structure
I need the board to continue printing in the same format as when the game starts.
This is the code:
tablero = []
NUM_FILAS = 6
NUM_COLUM = 7
jugador = 1
for fila in range(NUM_FILAS):
filas = []
for j in range(NUM_COLUM):
filas.append([])
tablero.append(filas)
print("\nJueguemos CONECTA 4\n")
for i in range(6):
for j in range(7):
print(tablero[i][j], end=" ")
print()
while True:
usuario = input('Jugador, elige una columna: ')
if usuario.isdigit():
usuario = int(usuario)
for pos in tablero:
if usuario == 1:
tablero.append([jugador])
print(tablero)
break
else:
print('El juego solo funciona con numeros')

vec.append not working, it tells me the list is still empty

My first post here, im working on a proyect and i need to append the data from CARGAR(n, vec) into the vec, i tried append but it doesnt work! I need help. Did i miss something?
I randomly select the times and i make an average called suma_t, then i make a variable called carrera with a str version of all the data.
import random
def mostrar_menu():
print("-------------------------------------------------------------------------")
print(" MENU ")
print("1. Cargar ")
print("2. Listar ")
print("-------------------------------------------------------------------------")
def validar_positivo():
n = int(input("Cuantos corredores hay?: "))
while n <= 0:
print("ERROR! Numero invalido")
return n
def cargar(n, vec):
for i in range(n):
numero = str(i+1)
nombre = str(input("Ingrese el nombre del corredor " + numero + ": "))
tiempo_1 = random.randint(0, 60)
tiempo_2 = random.randint(0, 60)
tiempo_3 = random.randint(0, 60)
suma_t = tiempo_1 + tiempo_2 + tiempo_3
tiempo_t = suma_t/3
print("Su tiempo promedio es de", tiempo_t)
carrera = str(nombre), str(tiempo_1), str(tiempo_2), str(tiempo_3), str(tiempo_t)
vec.append(carrera)
main()
def ordenar(vec):
n = len(vec)
for i in range(0, n-1):
for j in range(i+1, n):
if vec[i].tiempo_t < vec[j].tiempo_t:
vec[i], vec[j] = vec[j], vec[i]
def main():
vec = []
a = 0
while a != 3:
mostrar_menu()
a = int(input("Ingrese su opcion: "))
if a == 1:
n = validar_positivo()
cargar(n, vec)
if a == 2:
ordenar(vec)
if not vec:
print("Llene la lista")
else:
print(vec)
if a == 3:
print("Adios!")
if __name__ == "__main__":
main()

Python defining multimodal function

I need no create a function that can tell if:
There´s no mode
There´s 1 mode
And if is multimodal list
I got the first 2 points cover:
lista = [1,2,2,3,3,4]
contador = {}
for i in lista:
cuenta = lista.count(i)
contador[i] = cuenta
maximo =(0)
moda = [0]
for i in contador:
if(contador[i]>maximo):
maximo = contador[i]
moda = i
freq = contador[i]
if maximo == 1:
print("There is no mode")
else:
print ("Mode is: %d, with a frequency of: %d" % (moda, freq))
But I´m struggling to find a way to define if a list is multimodal. I thought of first defining which frequency is the highest and then check contador to take out all frequencies below but it doesn´t seem to work:
for i in contador:
if contador[i] < max:
delete = [i]
del contador[delete]
Any ideas on how to do it?
Thank you
well for multimodial you need to check the max frequency and count the frequency count. if it is 1 then mean no mode, more then 1 and exactly 1 then there is 1 mode and i frequency count is more than 1 and has multiple value has same count then it is multimodial
lista = [1,2,3,3,4]
res = {}
for i in lista:
if i not in res.keys():
res[i]=1
else:
res[i]+=1
freq = res.values()
max_freq = max(freq)
if max_freq==1:
print('no mode')
else:
key = ''
if list(freq).count(max_freq)==1:
for k, v in res.items():
if v==max_freq:
print('mode is {}, frequency is {}'.format(k, max_freq))
break
else:
print('multimodeal')
for k, v in res.items():
if v==max_freq:
print('mode is {}, frequency is {}'.format(k, max_freq))
The simplest modification to your existing code would be something like:
maximo = 0
moda = []
for i in contador:
if(contador[i] > maximo):
maximo = i
freq = contador[i]
moda = []
if(contador[i]==freq):
moda.append(i)
And change the final print to:
print ("Mode is: %s, with a frequency of: %d" % (moda, freq))
The whole thing simplified with library functions:
from collections import Counter
lista = [1, 2, 2, 3, 3, 4]
contador = Counter(lista)
# get the second part (the count) from the first element of the first most common element
freq = contador.most_common(1)[0][1]
# get all the x's for which the count is freq
moda = [x for x, c in contador.items() if c == freq]
if freq == 1:
print("There is no mode")
else:
print("Mode is: %s, with a frequency of: %d" % (moda, freq))
def moda(x):
input_string = input("Lista de numeros separados por un espacio: ")
lista = input_string.split()
contador = {}
for i in lista:
cuenta = lista.count(i)
contador[i] = cuenta
maximo =(0)
for i in contador:
if(contador[i]>maximo):
maximo = contador[i]
modas = {}
for i in contador:
if contador[i] == maximo:
modas[i] = contador[i]
if maximo == 1:
return("No hay modas")
elif len(modas)>1:
return ("Las modas y sus frecuencias son:")
return (modas)
else:
return ("la moda y su frecuencia es:")
return (modas)

How to pass a variable from a function to another function?

Sorry if my English is bad but it is not my native language
I'm starting my programming studies in Python, And I need to make this code for my class.
Basically consists of a checklist of the workers of a company to calculate their salary, applying some discounts and bonuses. In Option 4 of the menu, I must show all registered ID's with their final salary
I need to put the variable Sueldo Descontado Which is in the function Def Calcular_Sueldo() within the function Def Liquidaciones_Rut
Someone told me to define it as a class and add it to the registry List [] but I don't know how to do this :/
PS: If I define the variable SueldoDescontado as global Prints the same value for all ID's :/
I hope someone can help me
Heres my code
Lista = [] #<----- Array
Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio',
'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre',
'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio',
'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre',
'ENERO', 'FEBRERO', 'MARZO', 'ABRIL', 'MAYO', 'JUNIO', 'JULIO',
'AGOSTO', 'SEPTIEMBRE', 'OCTUBRE', 'NOVIEMBRE', 'DICIEMBRE']
Rank = ['novato', 'experto', 'supervisor', 'administrativo',
'Novato', 'Experto', 'Supervisor', 'Administrativo',
'NOVATO', 'EXPERTO', 'SUPERVISOR', 'ADMINISTRATIVO']
SistemaSalud = ['a', 'b', 'c',
'A', 'B', 'C']
class Trabajador: #Class <----
Mes = ''
Año = 0
Rut = ''
Nombre = ''
Categoria = ''
DiasOff = 0
AFP = ''
SSalud = ''
SueldoBruto = 0
SueldoDescontado = 0
def Ingresar_Datos():
Elementos = int(input('Ingrese cantidad de trabajadores que desea agregar: \n')) #<--- How many people do you want to add
for Trabajadores in range(Elementos):
dato = Trabajador()
while True:
Nombre = input("Ingrese un nombre: ") #<--- Name
if vacio(Nombre):
print ('No puede dejar el campo vacio')
else:
dato.Nombre = Nombre
break
while True:
Rut = input('Ingrese Rut: ') # <---- ID Number
if vacio(Rut):
print ('No puede dejar el campo vacio')
else:
dato.Rut = Rut
break
while True:
Mes = input('Ingrese mes: ') # <---- Month when start at work
if vacio(Mes):
print ('No puede dejar el campo vacio')
elif Mes in Mess:
dato.Mes = Mes
break
else:
print('Mes invalido')
while True:
Año = input('Ingrese año: ') # <---- Year when start at work
if vacio(Año):
print ('No puede dejar el campo vacio')
else:
dato.Año = Año
break
while True:
AFP = input('Ingrese AFP: ') # <---- NVM just a company name can be put here, not relevant
if vacio(AFP):
print ('No puede dejar el campo vacio')
else:
dato.AFP = AFP
break
while True:
SSalud = input('Sistema de salud A B o C\nDigite opcion: ') # <---- System Health, Here is A, B or C, This make a discount%
if vacio(SSalud):
print ('No puede dejar el campo vacio')
elif SSalud in SistemaSalud:
dato.SSalud = SSalud
break
else:
print ('::::::::::::::::::::ERROR Opcion Invalida::::::::::::::::::::')
while True:
Categoria = input('Categoria; Novato, Supervisor, Experto o Administrativo: ') # <---- Worker rank, Expert have a 2xBonus for 0 days off
if vacio(Categoria):
print ('No puede dejar el campo vacio')
elif Categoria in Rank:
dato.Categoria = Categoria
break
else:
print ('::::::::::::::::::::ERROR Categoria invalida::::::::::::::::::::')
while True:
DiasOff = input('Ingrese cantidad de dias de ausencia: ') #<------ Days of absence, 0 days have a bonus$
if dato.DiasOff < 0 or dato.DiasOff > 30:
print ('Dias de ausencia no puede ser negativo o mayor a 30')
else:
dato.DiasOff = DiasOff
break
while True:
try:
SueldoBruto = int(input('Ingrese sueldo bruto: ')) # <------- Gross Salary
if dato.SueldoBruto < 0:
print ('El monto del sueldo bruto no puede ser negativo')
else:
dato.SueldoBruto = SueldoBruto
break
except ValueError:
print('error')
print("------------------------------------------------")
Lista.append(dato)
def vacio(x):
if x and x.strip():
return False
return True
def Calcular_Sueldo():
Bono = 50000 #<-------- Bonus for 0 Days of absence
for Trabajadores in Lista:
print('Nombre trabajador: ',Trabajadores.Nombre,'\n')
if Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('Experto') or Trabajadores.DiasOff == '0' and Trabajadores.Categoria == ('EXPERTO'):
SueldoBono = Trabajadores.SueldoBruto + Bono*2 #<-------- There is if 0 days absence and rank experto, 2xBonus
print('Sueldo bruto + Bono (Experto) por 0 faltas: ',SueldoBono)
elif Trabajadores.DiasOff == '0': #<-------- Bonus for 0 Days of absence, nvm about rank here
SueldoBono = Trabajadores.SueldoBruto + Bono
print('Sueldo bruto + Bono por 0 faltas: ',SueldoBono)
else:
SueldoBono = Trabajadores.SueldoBruto #<-------- No bonus for days absence
print('Tiene faltas/ausencia, no tiene derecho a Bono: ',SueldoBono)
DctoAFP = SueldoBono - (SueldoBono * 0.1) #<-------- This makes a 10% descuento for AFP, the nvm'company name
print('Sueldo bruto + Recorte del 10% por AFP ',Trabajadores.AFP,': ',DctoAFP)
if Trabajadores.SSalud == 'a' or Trabajadores.SSalud == 'A': #<-------- If Sistem Health is A, make a 5,7% discount
DctoSalud = (DctoAFP/100) * 5.7
print('Recorte del sistema de salud A: ',DctoSalud)
SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
print('Total a pagar: ',SueldoDescontado)
if Trabajadores.SSalud == 'b' or Trabajadores.SSalud == 'B': #<-------- If Sistem Health is B, make a 6.1% discount
DctoSalud = (DctoAFP/100) * 6.1
print('Recorte del sistema de salud B: ',DctoSalud)
SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
print('Total a pagar: ',SueldoDescontado)
if Trabajadores.SSalud == 'c' or Trabajadores.SSalud == 'C': #<-------- If Sistem Health is C, make a 6.5% discount
DctoSalud = (DctoAFP/100) * 6.5
print('Recorte del sistema de salud C: ',DctoSalud)
SueldoDescontado = DctoAFP - DctoSalud #<-------------------------- This Variable --------- !"#$"!#%!"#%!#"%"#$%$"#----------
print('Total a pagar: ',SueldoDescontado)
print('--------------------------------------')
def Liquidaciones_Rut(): #<------- Here I need to print all the ID's number's with his Final Salary (SueldoDescontado)
for Trabajadores in Lista:
print('Rut: ',Trabajadores.Rut,'Total a pagar: $',SueldoDescontado) #<----- To here --------- !"#$"!#%!"#%!#"%"#$%$"#----------
def Listar_Empleados(): #<------------------ Here just print the names of all workers
for Trabajadores in Lista:
print("Empleados registrados: ", Trabajadores.Nombre)
opcion = 7
while (opcion != 6):
print(' ========== Administracion NovaVision ========== ')
print('Menu')
print('1.- Ingresar Datos') #<-------------------------- Enter Data
print('2.- Calcular Sueldo') #<-------------------------- Calculate Salary
print('3.- Listar Empleados') #<----------------------------- List employees (by his name)
print('4.- Mostrar Liquidaciones por RUT') # <--------- List numbers ID with his Respective Salary
print('5.- Salir')
opcion = int(input('Ingrese su opcion: '))
if (opcion == 1):
Ingresar_Datos()
elif (opcion == 2):
Calcular_Sueldo()
elif (opcion == 3):
Listar_Empleados()
elif (opcion == 4):
Liquidaciones_Rut()
elif (opcion == 5):
print('Saliendo .. ')
else:
print ('Opcion no valida')
Small example
class Trabajador:
def __init__(self, number, month, year):
self.number = number
self.month = month
self.year = year
Mess = ['enero', 'febrero', 'marzo', 'abril','mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']
T1 = Trabajador(10, Mess[0] , 1979)
print (T1.number)
print (T1.month)
print (T1.year)
__init method is class constructor,but read the link I gave you
Run this from command line in Linux
python example1.py
You will get
10
enero
1979

Rayleigh–Ritz method for FEM code

I´m trying to generate a code to model a finite elements analysis based on the following equation, using the Rayleigh Ritz Method.
-d/dx(adu/dx)+ c u - q
with U(0)=1 and adu/dx=0
i´ve got this far in the code but when it tries to integrate a TypeError: unsupported operand type(s) for /: 'int' and 'function' appears.
L = 1.0
n = 4
dx = L/n
dofpe = 2 # Grados de libertad por elemento, por ahora solo programado 2
Uo=1 #condicion esccencial
Qo=0 #condicion natural
coords = np.linspace(0,L,n+1)
elementos = np.zeros((n,dofpe),dtype=int)
for i in range(n):
elementos[i,0] = int(i)
elementos[i,1] = int(i+1)
def basis(xbar,i,he):
"""Returns the ith basis funciton at x
xbar - local element coordinate
i - basis function index
he - width of each element
"""
if i == 0: return 1 - xbar/he
if i == 1: return xbar/he
return -1 # Este seria un codigo de error, toca mejorar
def dbasis(xbar,i,he):
"""Returns the ith basis funciton at x
xbar - local element coordinate
i - basis funciton index
he - width of each element
"""
if i == 0: return -1/he
if i == 1: return 1/he
return -1 # Este seria un codigo de error, toca mejorar
def a():
return 1
def c():
return 1
def q():
return 1
xvec = np.linspace(0,1,10)
basisv = np.vectorize(basis)
plt.plot(xvec,basisv(xvec,0,1))
dbasisv = np.vectorize(dbasis)
plt.plot(xvec,dbasisv(xvec,0,1))
K = np.zeros((n+1,n+1))
for e in range(n): # loop over elements
dx = coords[elementos[e,1]] - coords[elementos[e,0]]
for i in range(dofpe): # loop over basis i
for j in range(dofpe): # loop over basis j
def fun(x,i,j,dx,a,c):
return a*dbasis(x,i,dx)*dbasis(x,j,dx)+ c*basis(x,i,dx)*basis(x,j,dx)
kij=scipy.integrate.quad(fun,coords[elementos[e,0]],coords[elementos[e,1]],args=(i,j,a,c,dx))
K[elementos[e,i],elementos[e,j]] +=kij
F = np.zeros((n+1))
for e in range(n):
dx = coords[elementos[e,1]] - coords[elementos[e,0]]
for i in range(dofpe):
def l(x,i,dx,q):
return q*basis(x,i,dx)
fij=scipy.integrate.quad(l,coords[elementos[e,0]],coords[elementos[e,1]],args=(i,dx,q))
F[elementos[e,i]] += fij
I don´t know why, does any one knows how to fix it?

Categories