How do i compare different employees on bases of pay in the following code:
import random
class employee:
def __init__(self, pay, age):
self.pay = pay
self.age = age
employee_num = 0
for i in range(5):
employee_num = employee(random.randint(20000, 50000),random.randint(18, 59))
#create different employee numbers and make the pay and age of these employee_num random
# compairing different employee numbers on base of pay in order from least to most
print('printing highest earner employee number here')
#delete all employee classes here
or can I make a list with this data to access it easier?
CodePudding user response:
import random
class Employee: # Convention capitalize class names
def __init__(self, pay, age):
self.pay = pay
self.age = age
employees = []
for i in range(5):
employees.append( Employee(random.randint(20000, 50000),
random.randint(18, 59)))
# create different employee numbers and make the pay and age of these
# employee_num random
# compairing different employee numbers on base of pay in order from least to most
print('printing highest earner employee number here')
for person in employees:
print(person.pay)
print('Now process from least to most pay.')
# Mutate the employees list ordered by lowest of highest pay.
employees.sort(key=lambda employee: employee.pay)
for person in employees:
print(person.pay)
# delete all employee classes here
Output
printing highest earner employee number here
28717
48714
25406
33588
23827
Now process from least to most pay.
23827
25406
28717
33588
48714
CodePudding user response:
you're assigning the employee_num
5 times. what does it mean?
to sort a list with your order you can do this:
employee_list = [employee(random.randint(20000, 50000), random.randint(18, 59)) for i in range(5)]
employee_list.sort(key=lambda e: e.pay) #this will sort the list with the employee.pay ascending
or you can override the relation operators for your class and use them:
class employee:
def __init__(self, pay, age):
self.pay = pay
self.age = age
def __gt__(self, a):
return self.pay > a.pay
def __lt__(self, a):
return self.pay < a.pay
...
employee_list.sort()