来自codewars的超市队列编程问题

Supermarket queue programming problem from codewars

问题如下: 超市的自助收银台需要排队。您的任务是编写一个函数来计算所有客户结账所需的总时间!

输入: customers:代表队列的正整数数组。每个整数代表一个客户,它的值是他们结账所需的时间。 n: 正整数,结账次数。

输出: 函数应该return一个整数,需要的总时间 我的密码是

import math
def empty(seq):
    is_empty=True
    for i in seq:
        if i>0:
            is_empty=False
            break
    return is_empty
def checks(cust,n):
    if len(cust)==0:
        return 0
    if n==1:
        sum=0
        for i in cust:
            sum+=i
        return sum
    elif len(cust)<=n:
        return max(cust)
def queue_time(customers, n):
    if len(customers)==0 or n==1 or len(customers)<=n:
            return checks(customers,n)
    main_sum=0
    tills=[0]*n
    leng=len(customers)
    if leng>n:
        for i in range(n):
            tills[i]=customers[i]
    t_len=len(tills)
    main_loop=t_len
    while(main_loop<leng and not empty(tills)):
        least=min(tills)
        if least==0:
            least = min(i for i in tills if i > 0)
        for inner in range(t_len):
            if tills[inner]>0:
                tills[inner]-=least
        main_sum+=least
        if main_loop<leng:
            for fill_zero in range(t_len):
                if tills[fill_zero]==0:
                    tills[fill_zero]=customers[main_loop]
                    main_loop+=1
    return main_sum
print(queue_time([2,2,3,3,4,4], 2)) #should equal 9 but the result is 5 !

输出应该等于 9 但我的是 5

一个有用的方法是使用 python 标准库中的 collections.deque 数据结构,它可以很容易地用作队列(或堆栈)。

from collections import deque

def supermarket_queue(customers, n):
    queue = deque(customers)
    total_time = 0
    workers =[0 for _ in range(n)]
    while True:
        for i in range(n): # loop over self-checkouts
            if workers[i] == 0: # check for free self-checkout
                if queue:
                    workers[i] = queue.popleft()
            if workers[i] > 0: # checkout has work to do
                # reduce amount of work
                workers[i] -= 1
        # for live updates (i.e. debugging)
        print(f"t: {total_time}, checkouts: {workers}")
        # check for customers or busy self-checkouts
        if queue or any([w > 0 for w in workers]):
            # add one timestep
            total_time += 1
        else:
            # no customers waiting, no checkouts busy
            break
    return total_time

您实际上可以使用 0 个导入和 5 行代码来完成此操作。
您创建可用收银机列表,遍历客户结帐时间, 添加到第一个索引并 运行 在列表中排序,因此最大的整数(到结帐的最长时间)是最后一个索引。
每次迭代然后将下一个结账时间添加到第一个索引,因为它是下一个可用时间等等。
然后简单地 return 列表中最大的数字。

def queue_time(customers, n):
    tills = [0]*n
    for i in customers:
      tills[0] += i
      tills.sort()
    return max(tills)