Python defining multimodal function - python

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)

Related

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()

How to pick largest element from list?

I wrote a program to count grades and the students' names and I want to implement a feature that shows the highest grade and the respective student. The whole program works except for this part, since I'm not sure how to pick the element with the highest value since it comes with a string attached.
I'll leave the entire program down but the part that I'm refering to is this:
mediafinal = []
elif resposta.upper() == 'N':
resposta = input('Check best student and grade? (Y/N):')
if resposta.upper() == 'Y':
print('Best student and grade is: ', max(mediafinal))
break
The rest of the code
media1 = []
media2 = []
media3 = []
mediafinal = []
nomes = []
while True:
resposta = input('Pretende introduzir um aluno? (Y/N): ')
if resposta.upper() == 'Y':
nome = (input('Indique o nome do aluno: '))
nomes.append(nome)
nota1 = eval((input(f'Indique a nota do primeiro teste {nome}: ')))
nota2 = eval((input(f'Indique a nota do segundo teste {nome}: ')))
m1 = ((nota1 + nota2)/2)
infoaluno1 = []
infoaluno1.extend([nome, m1])
media1.append(infoaluno1)
print(f'O nome e média do primeiro período do aluno é: {nome} {m1}')
nota3 = eval((input(f'Indique a nota do terceiro teste {nome}: ')))
nota4 = eval((input(f'Indique a nota do quarto teste {nome}: ')))
m2 = ((nota3 + nota4) / 2)
infoaluno2 = []
infoaluno2.extend([nome, m2])
media2.append(infoaluno2)
print(f'O nome e média do segundo período do aluno é: {nome} {m2}')
nota5 = eval((input(f'Indique a nota do quinto teste {nome}: ')))
nota6 = eval((input(f'Indique a nota do sexto teste {nome}: ')))
m3 = ((nota5 + nota6) / 2)
infoaluno3 = []
infoaluno3.extend([nome, m3])
media3.append(infoaluno3)
print(f'O nome e média do terceiro período do aluno é: {nome} {m3}')
mf = ((m1 + m2 + m3)/3)
mediafinal.extend([nome, mf])
print(f'Classificação final do aluno: {nome} {mf}')
elif resposta.upper() == 'N':
resposta = input('Pretende verificar o melhor aluno e nota? (Y/N):')
if resposta.upper() == 'Y':
print('O melhor aluno é:', max(mediafinal))
break
elif resposta.upper() == 'N':
print('Ok!')
break
The problem is much much MUCH simpler if you have a list of tuples instead of alternating strings and numbers:
mediafinal.extend([nome, mf])
should be:
mediafinal.append((mf, nome))
Then your max call just works out of the box like this:
mf, nome = max(mediafinal)
print('Best student and grade is: ', nome, mf)
Note that putting the score (mf) first in the tuple means that max will pick based on that. You could change the ordering, but then you need to tell max to make its selection based on the 2nd element:
mediafinal.append((nome, mf))
...
nome, mf = max(mediafinal, key=lambda m: m[1])
So without changing any of your code logic, and just fixing the max() line, I would have it as:
max(a, key=lambda el: el[1])

sum(map()) function not working as expected

I am having some trouble with my code. I need to count how many values in the list are lower than 20. The problem is that my list has both str and int values.
I tried the following but it is not working:
from numpy import mean
import sys
mylistidade = []
mylistmen = []
mylistwomen = []
count = sum(map(lambda x : x<20, mylistwomen[1::2]))
for x in range (1, 5):
print(f'----- {x}ª PESSOA -----')
nome = str(input('Nome: ')).strip().title()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F}: ')).upper()
if sexo == 'M' or sexo == 'F':
pass
else:
print('Digite um valor válido no campo Sexo!')
sys.exit()
if sexo == 'M':
mylistmen.append(nome)
mylistmen.append(idade)
else:
mylistwomen.append(nome)
mylistwomen.append(idade)
mylistidade.append(idade)
print(mylistmen)
print(mylistwomen)
print(f'The average age for the group is {mean(mylistidade)}!')
position = mylistmen.index(max(mylistmen[1::2]))
print(f'The oldest man has {max(mylistmen[1::2])} years and it is called', end=' ')
print(f'{mylistmen[position-1]}')
print(f'There is {count} women that has less than 20 years!')
I would like to stick with my solution of sum(map()). Just need some help to figure out what I'm missing.
You have to move count under the for loop
from numpy import mean
import sys
mylistidade = []
mylistmen = []
mylistwomen = []
for x in range (1, 5):
print(f'----- {x}ª PESSOA -----')
nome = str(input('Nome: ')).strip().title()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F}: ')).upper()
if sexo == 'M' or sexo == 'F':
pass
else:
print('Digite um valor válido no campo Sexo!')
sys.exit()
if sexo == 'M':
mylistmen.append(nome)
mylistmen.append(idade)
else:
mylistwomen.append(nome)
mylistwomen.append(idade)
mylistidade.append(idade)
count = sum(map(lambda x : x<20, mylistwomen[1::2]))
print(mylistmen)
print(mylistwomen)
print(f'The average age for the group is {mean(mylistidade)}!')
position = mylistmen.index(max(mylistmen[1::2]))
print(f'The oldest man has {max(mylistmen[1::2])} years and it is called', end=' ')
print(f'{mylistmen[position-1]}')
print(f'There is {count} women that has less than 20 years!')
Try this
count = sum(map(lambda x : x if type(x)== 'int' and x<20, mylistwomen[1::2]))

How to remove a variable in a list a loop as already gone through

My goal here is to create a loop where I get a list ordered by beginning in Inicial and then the item closest to Inicial and then the one closest to the previous one and so on.
The casa_mais_proxima function gives me the closest item in a list to a given item.
I keep getting a list.remove(x): x not in list in grupo.remove(resultado[casa]) and don't know how to change this so that I can remove the items on the list the loop has already gone through.
Inicial = (3,2)
Casas = [(0,1),(1,0),(1,2),(2,3)]
def percurso(Inicial,Casas):
grupo = [Inicial]
grupo.extend(Casas)
resultado = [Inicial]
casas = Casas
for casa in range(len(Casas)):
grupo.remove(resultado[casa])
proxima = casa_mais_proxima(resultado[casa],grupo)
resultado.append(proxima)
return(resultado)
print(percurso(Inicial,Casas))
I think there may be an issue with the other function but i can't spot it
Casas = [(0,1),(1,0),(1,2),(2,3)]
def casa_mais_proxima(P,Casas):
menor_distancia = 0
resultado = []
for elemento in Casas:
if menor_distancia == 0:
menor_distancia = distancia_casas(P,elemento)
if menor_distancia == distancia_casas(P,elemento):
resultado.append(elemento)
if menor_distancia > distancia_casas(P,elemento):
resultado = [elemento]
else:
continue
if len(resultado) == 1:
return resultado
else:
resultado_a = []
for elemento in resultado:
if len(resultado_a) == 0:
resultado_a.append(elemento)
if elemento[0] < resultado_a[0][0]:
resultado_a = [elemento]
if elemento[0] == resultado_a[0][0]:
resultado_a.append(elemento)
else:
continue
if len(resultado_a) == 1:
return resultado_a
else:
resultado_b = []
for elemento in resultado_a:
if len(resultado_b) == 0:
resultado_b.append(elemento)
if elemento[1] < resultado_b[1][1]:
resultado_b = list(elemento)
if elemento[1] == resultado_b[1][1]:
resultado_b.append(elemento)
else:
continue
return resultado_b
print (casa_mais_proxima((1,1),[(0,2),(1,3),(2,1)]))

Python - list index out of range - genetic algorithm

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.

Categories