How to limit append elements count in list - python

An interesting problem that I'm trying to solve:
I need to limit count of employees I'm taking to expedition ( numbers in my code below )
employee.txt example part:
30;electrical engineer;1;70
31;scientist;0;100
32;doctor;0;42
33;scientist;1;47
34;mechanic;0;63
I have the total number of each of them by gender and profession.
There is my code:
manager = 1
cook = 3
electrical_engineer = 4
computers_specialist = 5
doctor = 5
mechanic = 8
scientist = 14
expedition_total = 40
female_min = 21
male_min = 12
def total_resist_count():
with open('employee.txt', 'r') as employee_list:
total_count = 0
female_count = 0
male_count = 0
expedition = []
for employee in employee_list.readlines():
employee_data = employee.rstrip().split(';')
if int(employee_data[3]) >= 60:
total_count += 1
if int(employee_data[2] == '0') and int(employee_data[3]) >= 60:
female_count += 1
if int(employee_data[2] == '1') and int(employee_data[3]) >= 60:
male_count += 1
print('Stress-resistant colonists: ', total_count)
print('--------- Female colonists: ', female_count)
print('----------- Male colonists: ', male_count)
print('--------------------------')
print('Mars expedition list: ')
pprint(expedition)
if __name__ == '__main__':
total_resist_count()
OUTPUT:
Stress-resistant colonists: 90
--------- Female colonists: 48
----------- Male colonists: 42
Mars expedition list:
[]
And I need to add each of experts count to expedition ( limited to var's in code - 40 in total )
I try:
if int(employee_data[2] == '0') and int(employee_data[3]) >= 60:
expedition.append(employee_data)
female_count += 1
And:
if int(employee_data[2] == '0') and int(employee_data[3]) >= 60:
female_count += 1
for female_employee in range(total_count - male_min):
expedition.append(female_employee)
1) But I'm get full list of employees who have employee_data[2] == '0' and
employee_data[3]) >= 60 ( obviously )
2) I get a duplicating numbers
How I can limit new list append to the numbers I needed ?
Appreciate any advices and pointing to mistakes

try:
manager = 1
cook = 3
electrical_engineer = 4
computers_specialist = 5
doctor = 5
mechanic = 8
scientist = 14
expedition_total = 40
female_min = 21
male_min = 12
def total_resist_count():
with open('employee.txt', 'r') as employee_list:
total_count = 0
female_count = 0
male_count = 0
expedition = []
for employee in employee_list.readlines():
employee_data = employee.rstrip().split(';')
if int(employee_data[2] == 0) and int(employee_data[3]) >= 60:
female_count += 1
total_count += 1
expedition.append(employee_data)
elif int(employee_data[2] == 1) and int(employee_data[3]) >= 60:
male_count += 1
total_count += 1
expedition.append(employee_data)
print('Stress-resistant colonists: ', total_count)
print('--------- Female colonists: ', female_count)
print('----------- Male colonists: ', male_count)
print('--------------------------')
print('Mars expedition list: ')
print(expedition)
if __name__ == '__main__':
total_resist_count()
If you need more specific parameters, add them in the conditional statements. Like if you need a minimum/maximum amount of a certain type of employee, just check if the running total of this type of employee is within the bounds and if it is, then append or ignore accordingly.
if you have a maximum amount of people you can take (40), use:
manager = 1
cook = 3
electrical_engineer = 4
computers_specialist = 5
doctor = 5
mechanic = 8
scientist = 14
expedition_total = 40
female_min = 21
male_min = 12
total_count = 0
female_count = 0
male_count = 0
expedition = []
def total_resist_count():
global total_count
global female_count
global male_count
global expedition
with open('employee.txt', 'r') as employee_list:
while len(expedition) < total_count:
for employee in employee_list.readlines():
employee_data = employee.rstrip().split(';')
if int(employee_data[2] == '0') and int(employee_data[3]) >= 60:
female_count += 1
total_count += 1
expedition.append(employee_data)
elif int(employee_data[2] == '1') and int(employee_data[3]) >= 60:
male_count += 1
total_count += 1
expedition.append(employee_data)
print('Stress-resistant colonists: ', total_count)
print('--------- Female colonists: ', female_count)
print('----------- Male colonists: ', male_count)
print('--------------------------')
print('Mars expedition list: ')
print(expedition)
if __name__ == '__main__':
total_resist_count()

Related

Is it possible to Automatically update dataset with each basketball simulation python

I've learnt how to simulate s many games as I want, but the problem is, I want the dataset(mean median mode) updated for each team after every game... total score of each team for every game and combined total. I had a lot of errors with the traditional sum / len concept because it wants a dataset manually imported.
import random
import time
import math
michigan = 0
kansas = 0
seconds = 2400
michiganw = 0
kansasw = 0
while True:
michigan = 0
kansas = 0
seconds = 2400
if kansasw == 10:
print("Kansas Wins", kansasw)
print("Michigan Wins", michiganw)
("Kansas 100 Wins")
print("Kansas Game Score", kansasgamescore)
break
elif michiganw == 10:
print("Michigan Wins", michiganw)
print("Kansas Wins", kansasw)
print("Michigan 100 Wins")
print("Kansas Game Score", kansasgamescore)
break
for i in range(150):
Goblinsi = random.randint(0, 24) #kansas or michigan shot attempt
if Goblinsi <= 8: #kansas scores
kansas = kansas + 2
Goblinsii = random.randint(0, 4)
if Goblinsii == 4: #1pt extra for 3 point fg
kansas = kansas + 1
seconds = seconds - 20
elif Goblinsii < 4:
seconds = seconds - 20
else:
seconds = seconds - 20
if Goblinsi >= 16: #michigan scores
michigan = michigan + 2
Goblinsii = random.randint(0, 4)
if Goblinsii == 4: #1pt extra for 3 point fg
michigan = michigan + 1
seconds = seconds - 20
elif Goblinsii < 4:
seconds = seconds - 20
if seconds == 0: #free throws
kansas = kansas + 10
michigan = michigan + 10
if michigan > kansas:
print("Michigan Win!")
print("Final Score")
print("Michigan", michigan)
print("Kansas", kansas)
#I want this to be the point the mean, median, mode are calculated and listed*
print("Next Game")
michiganw = michiganw + 1
michigan = 0
kansas = 0
seconds = 2400
continue
elif michigan < kansas:
print("Kansas Win!")
print("Final Score")
print("Michigan", michigan)
print("Kansas", kansas)
#I want this to be the point the mean, median, mode are calculated and listed*
print("Play Again")
kansasw = kansasw + 1
michigan = 0
kansas = 0
seconds = 2400
continue
elif michigan == kansas:
Goblinsi = random.randint(0, 12)
if Goblinsi >= 7:
kansas = kansas + 1
print("Kansas Win")
print("Final Score")
print("Michigan", michigan)
print("Kansas", kansas)
michigan = 0
kansas = 0
seconds = 2400
kansasw = kansasw + 1
continue
elif Goblinsi <= 6:
michigan = michigan + 1
print("Michigan Win")
print("Final Score")
print("Michigan", michigan)
print("Kansas", kansas)
michigan = 0
kansas = 0
seconds = 2400
michiganw = michiganw + 1
continue

Can't figure out NameError

I am trying to build a cost model using mostly if statements but I keep getting the error:
NameError: name 'spread_1' is not defined.
I am a beginner with python so I don't know if I've done something incorrect. Please help.
#water depth of project site in metres
water_depth = 100
#platform wells require jackups
pl = 1
#1-2 complexity required LWIV
ss_simple = 1
#3-4 complexity requires rig
ss_complex = 0
#day rates
vjackup = 75000
jackup = 90000
vsemi = 170000
semi = 300000
lwiv = 200000
#determining vessel spread for platform wells
if pl >= 1:
if water_depth == range(0, 50):
spread_1 = vjackup * 24.1
elif water_depth == range(51, 150):
spread_1 = jackup * 24.1
elif pl == 0:
spread_1 = 0
You should replace the == with in at the
if water_depth == range(0, 50):
and
elif water_depth == range(51, 150):
making your block of code:
if pl >= 1:
if water_depth == range(0, 50):
spread_1 = vjackup * 24.1
elif water_depth == range(51, 150):
spread_1 = jackup * 24.1
elif pl == 0:
spread_1 = 0
into
if pl >= 1:
if water_depth in range(0, 50):
spread_1 = vjackup * 24.1
elif water_depth in range(51, 150):
spread_1 = jackup * 24.1
elif pl == 0:
spread_1 = 0
But it would be more practical to use extreme equality operators in your case:
if pl >= 1:
if 0 <= water_depth < 50:
spread_1 = vjackup * 24.1
elif 51 <= water_depth < 150:
spread_1 = jackup * 24.1
elif pl == 0:
spread_1 = 0
Do note that the range() function omits the end value, so range(0, 50)'s last value would be 49, not 50.

How to sum specific integer values of Python List

I'm trying to sum integer values from the list using sum function. Unfortunately, it is adding all the values of the list but not those which I need from the user.
Here is my code:
tourist_attractions = []
distance = []
entry_cost = []
for i in range(3):
tourist_attractions.append (input("Enter Tourist place: "))
tourist_distance =(int(input("Enter distance: ")))
if tourist_distance > 50:
print("Invalid Entry")
continue
if tourist_distance <= 50:
distance.append(tourist_distance)
cost = (float(input("Enter cost: ")))
if cost > 100:
print("cost must be between 1-100")
continue
if cost > 0 or cost <= 100:
entry_cost.append(cost)
print()
for line in tourist_attractions:
print("Place:", line)
for line in distance:
print("Distance:", line)
for line in entry_cost:
print("Cost:", line)
print()
number_of_places_to_visit = int(input("Total number of places to visit: "))
x = 1
while x <= number_of_places_to_visit:
select_tourist_place = input("select tourist place, 0-3: ")
x = x + 1
if select_tourist_place == "0":
print(tourist_attractions[0], distance[0], entry_cost[0])
elif select_tourist_place == "1":
print(tourist_attractions[1], distance[1], entry_cost[1])
elif select_tourist_place == "2":
print(tourist_attractions[2], distance[2], entry_cost[2])
elif select_tourist_place == "3":
print(tourist_attractions[3], distance[3], entry_cost[3])
elif select_tourist_place == "4":
print(tourist_attractions[4], distance[4], entry_cost[4])
print("total cost: " , sum(entry_cost))
Result I am getting:
Enter Tourist place: London
Enter distance: 25
Enter cost: 15
Enter Tourist place: Manchester
Enter distance: 30
Enter cost: 15
Enter Tourist place: Scotland
Enter distance: 50
Enter cost: 20
Place: London
Place: Manchester
Place: Scotland
Distance: 25
Distance: 30
Distance: 50
Cost: 15.0
Cost: 15.0
Cost: 20.0
Total number of places to visit: 2
select tourist place, 0-3: 0
London 25 15.0
select tourist place, 0-5: 1
Manchester 30 15.0
total cost: 50.0
>>>
I can understand, at the moment it is summing up all the appended list of entry_cost and giving me the total of 50 which should be 15 from London and 15 from Manchester. Any help?
print("total cost: " , sum(entry_cost))
definitely states your are iterating over ALL entry costs. You would want to store the selected indices and sum over the entries of those indices.

how to return value from if condition inside loop and use it in first of loop python

I have a for loop to create paid number like 040-050 here is the code
start_num = 40
end_num = 50
painumreturn = ''
count = 0
for painum in range(start_num, end_num):
if not painumreturn:
painumbe = painum
else:
painumbe = painumreturn
painumber = str(painumbe).zfill(3)
if painumber == '044':
if count == 2:
painumreturn = ''
count == 0
painumber = int(painumbe) +1
else:
painumreturn = painumber
count = count +1
print(count)
print(painumber)
#output
040
041
042
043
1
044
2
044
45
047
048
049
it should from here to continue the first make the 45 with out 045 and it jump from 046 so this is the right out but
2
044
045
046
047
048
049
Do you mean something like this?
# intialize varibales:
start = 40
end = 50
# iterate over given range:
for number in range(start, end):
# skip values less than 44:
if number < 44:
continue
# use zfill to format number:
formatted_number = str(number)
formatted_number = formatted_number.zfill(3)
# print result:
print(formatted_number)
Output:
044
045
046
047
048
049
If you're happy storing your result as a list, you can use list comprehension to complete your task in one line.
numbers = [str(num).zfill(3) for num in range(start, stop) if num >= 44]
#['044', '045', '046', '047', '048', '049']
print(*numbers, sep='\n')
#044
#045
#046
#047
#048
#049
Skip all items that a condition satisfies:
start_num = 40
end_num = 50
for painum in range(start_num, end_num):
if painum < 44:
continue
print(f"{painum:03.0f}")
Only do something for items that a condition satisfies:
start_num = 40
end_num = 50
for painum in range(start_num, end_num):
if painum >= 44:
print(f"{painum:03.0f}")
Printing one element twice:
start_num = 40
end_num = 50
painumreturn = ''
for p in range(start_num, end_num):
if p == 44:
print(f"{p:03.0f}")
painumreturn = f"{p:03.0f}"
print(f"{p:03.0f}")
output:
040
041
042
043
044
044
045
046
047
048
049
This is the solution:
start_num = 40
end_num = 50
painumreturn = ''
count = 0
for painum in range(start_num, end_num):
if not painumreturn:
painumbe = painum
else:
painumbe = painumreturn
painumber = str(painumbe).zfill(3)
if painumber == '044':
if count == 1:
painumreturn = ''
count == 0
else:
painumreturn = painumber
count = count +1
print(painumber)
output:
040
041
042
043
044
044
046
047
048
049
Thanks!
Best regards.

Need to show positive bills and negative bills

Some of the vars are in Portuguese sorry. I am trying to show how much of which type of money bills you will and will not get on a atm:
example:
IN: $123,45
OUT:1 OF $100 BILL, 0 OF $50 BILL, 1 OF $20 BILL, 0 OF $10 BILL and etc.
This is what I did so far but I can't do the bill that will not come on the atm.
r = 0
print('='*20)
print('{:^20}'.format('CAIXA ELETRÔNICO'))
print('{:^20}'.format(' Banco do Romeu '))
print('='*20)
caixa = float(input('Qual serĂ¡ o valor sacado? '))
total = caixa
ced = 100
totalced = 0
while True:
if total >= ced:
total = total - ced
totalced += 1
else:
if totalced > 0:
print(f'{totalced} notas(s) de R${ced}')
elif ced == 100:
ced = 50
elif ced == 50:
ced = 20
elif ced == 20:
ced = 10
elif ced == 10:
ced = 5
elif ced == 5:
ced = 2
elif ced == 2:
ced = 1
elif ced == 1:
ced = 0.50
elif ced == 0.50:
ced = 0.25
elif ced == 0.25:
ced = 0.10
elif ced == 0.10:
ced = 0.05
elif ced == 0.05:
ced = 0.01
totalced = 0
if total == 0:
break
You can do a greedy approach and try to subtract the highest value bill and keep a count of how many times you subtracted from each bill. For example:
423,45
You start with $100, you can subtract it 4 times. You're left with 23,45.
Then you go on to $50. You can't subtract $50 from 23,45 so you go to the next highest bill, $20.
You can subtract one $20 from 23,45 and you're left with ,45.
You keep on going and keep count until you can't subtract anymore. Then you print out the count of subtractions from each bill. Hope that makes sense!
You can subtract value from initial value.
variable valor is the initial value
valor = 162
cells = []
money = [100, 50, 20, 10, 5, 2]
for _ in money:
while True:
if valor >= _:
if valor - _ < money[-1] or (valor % _) % money[-1] != 0:
if valor == _:
cells.append(_)
break
valor -= _
cells.append(_)
else:
break
print(cells)
>>> [100, 50, 10, 2]

Categories