如何选择一系列数字乘以小时工资

时间:2014-04-07 22:06:19

标签: python

我正在阅读一份包含员工信息的文件。名字,姓氏,工作小时数,小时工资。我需要计算正常工资,所以每小时工资*小时数在0到40之间。此外,时间半长在41到45之间,包括在内。我的问题是如何才能使用0到40之间的小时来获得正常工资?这是我目前的代码:

def main():
print()
print("This program will compute payroll.")
print("Written by Josh Sollenberger.")
print()

filename = input("Please enter the emplyee file name: ")
infile = open(filename, 'r')
print()
for line in infile:
    first,last,hours,wage = line.split(',')
    while int(hours) >= 0 and int(hours) <= 40:
        regPay = float(wage)*hours
    print(first,last,hours,wage,regPay)

main()的

这告诉我在分配之前我引用了regPay。

2 个答案:

答案 0 :(得分:2)

我以前使用minmax

完成了这项工作
regPay = float(wage) * min(int(hours),40)
# min(hours,40) will return hours, unless hours > 40 then it will return 40
OTpay = float(wage) * OVERTIMERATE * max(int(hours)-40,0)
# max(hours-40,0) will return hours-40, unless hours <= 40 then it will return 0

它告诉您在分配之前引用regPay的原因是因为您只有在regPay = float(wage)*hours时才到达regPay行(int(hours)}在0到40之间。如果它是> = 41,它永远不会进入那里!

令人难以置信的是,这段代码的版本永远不会是:

OVERTIMERATE = 1.5 # maybe 2?
first,last,hours,wage = line.split(',')
hours, wage = int(hours), float(wage) # Decimal is better here, but...
OTpay, regPay = 0,0 # initialize
while hours > 40:
    hours -= 1
    OTpay += wage*OVERTIMERATE
while hours > 0:
    hours -= 1
    regPay += wage

编辑评论

reg_hours = min(int(hours), 40)
timeandhalf_hours = min(max(int(hours)-reg_hours),0),5)
doubletime_hours = max(int(hours) - (reg_hours + timeandhalf_hours), 0)

regPay = float(wage) * reg_hours
timeandhalfPay = float(wage) * 1.5 * timeandhalf_hours
doubletime_hours = float(wage) * 2 * doubletime_hours

再次长篇:

total_pay = 0
hours = int(hours)
wage = float(wage)

for i in range(1,hours+1):
    if i <= 40:
        total_pay += wage
    elif i <= 45:
        total_pay += wage * 1.5
    else:
        total_pay += wage * 2

答案 1 :(得分:0)

以下是我如何解决问题的完整版本:

for line in infile: 
    first, last, hours, wage = line.split(',')
    hours, wage = int(hours), float(wage)
    if hours > 0: 
        regHours = min(hours, 40) # limit to 40
        otHours = max(hours - 40, 0)
        otHours = min(otHours, 5) # limit to 5
        dblHours = max(hours - 45, 0) # no limit
        regPay = regHours * wage
        otPay = otHours * wage * 1.5
        dblPay = dblHours * wage * 2
    else:
        regPay = 0
        otPay = 0
        dblPay = 0
    totalPay = regPay + otPay + dblPay

    print(first, last, hours, wage, totalPay)

一些快速的结果:

('chris', 'a', 50, 10.0, 575.0)
('chris', 'b', 41, 10.0, 415.0)
('chris', 'c', 35, 10.0, 350.0)