比如说我想给一些员工一些钱。每个员工必须得到$ a到$ b美元。第一个员工获得$ a,每个后续员工获得的金额比上一个多$ k,直到该金额超过$ b,在这种情况下,员工获得$ b,之后每个后续员工获得$ k少于最后一个,直到该金额低于$ 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()
答案 0 :(得分:1)
我可能会使用生成器功能来创建支出:
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
答案 1 :(得分:0)
基于我发布的Haskell解决方案作为对该问题的评论,这是一个使用itertools
库的解决方案,该库使用无限的值列表。
import itertools
def pay(n, a, b, k):
cyc = itertools.cycle([range(a, b+1, k), range(b, a-1, -k)])
chained = itertools.chain.from_iterable(cyc)
return sum(itertools.islice(chained, n))
这是有效的,因为我们使用此算法封装的模式是无限循环模式[range(a, b+1, k), range(b, a-1, -k)]
(从k
到a
行走b
,然后走-k
从b
到a
)。 itertools.chain.from_iterable
来自各个range
迭代器,islice
确保我们只获得n
个结果。
cyc
和chained
是无限系列,islice
正在限制n
学生。