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