python - 支付员工

标签 python python-3.x algorithm

举例来说,我想给一些员工一些钱。每个员工必须得到 $a 到 $b 美元。第一个员工得到 $a,每个后续员工得到的 $k 比最后一个多,直到该金额超过 $b,在这种情况下,该员工获得 $b,此后每个后续员工得到的 $k 比最后一个少,直到该金额低于 $b $a 在这种情况下,员工将获得 $a 并且所有 n 名员工都将继续循环。我想将总支出返还给所有员工

我目前拥有的:

#!/bin/python3
import os
import sys

def payEmp(n, a, b, k):
    totalPayOut = 0
    currentPay = 0
    increase = True
    for i in range(n):
        if increase == True:
            if currentPay < a:
                currentPay += a
            else:
                currentPay += k
                if currentPay >= b:
                    totalPayOut += b
                    increase = False
                else:
                    totalPayOut += currentPay
        else:
            currentPay -= k
            if currentPay <= a:
                totalPayOut += a
                increase = True
            else:
                totalPayOut += currentPay

    return totalPayOut



if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        nabk = input().split()

        n = int(nabk[0])

        a = int(nabk[1])

        b = int(nabk[2])

        k = int(nabk[3])

        result = payEmp(n, a, b, k)

        fptr.write(str(result) + '\n')

    fptr.close()

最佳答案

我可能会使用生成器函数来创建支出:

def pay(n,a,b,k):
    p = a # start with a
    c = 0
    while c < n: # loop until enough values generated
        # upcounting payments
        while p <= b and c < n:  # do this until enough or payment reached b
            yield p
            c += 1
            if p != b:
                p = min(b,p+k) # increase as long as not reached, prevent overshooting      
            else: # we reached and yielded b so we are done
                break # we just yielded b - less payment from now on
        p -= k  # we already yielded b - so we add k again
        # downcounting payments
        while p >= a and c < n:  # do this until enough or payment reached a again
            yield p
            c += 1
            if p != a:
                p = max(a,p-k) # decrease as long as not reached, prevent undershooting
            else: # we just yielded a, were done going down, back up from now on
                p = a+k
                break # we just printed a, more pay from here on

pays = list(pay(15,2,9,2))
print(pays,sum(pays))

输出:

[2, 4, 6, 8, 9, 7, 5, 3, 2, 4, 6, 8, 9, 7, 5] 85

关于python - 支付员工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50009692/

相关文章:

algorithm - 处理间隔的数据结构

algorithm - 瓦片的成对匹配

python - 在非常大的数据集上在 python 中生成 n 选择 2 种组合

python - 如何解析 'ImmutableDenseNDimArray' 对象没有属性 'could_extract_minus_sign' ?

Python3 字典值被覆盖

python-3.x - 首先解构/解包,然后在 Clojure 中休息

java - 任何用于 smoosh 方法的 O(n) 算法?

python - 我可以有一个嵌套 numba 对象数组吗?

python - 在 Python 中读取原始二进制图像

python - 使用 AWS 创建 Alexa 对话技能