关于函数的几个问题

2024-03-28 17:55:20 发布

您现在位置:Python中文网/ 问答频道 /正文

def get_party_stats(families, table_size=6):

    """To calculate the number of attendees and tables needed.

    Args:
        families(list): a list of members.
        table_size(int): table size of 6.

    Returns:
        mixed: people count & table count.

    Examples:

        >>> get_party_stats([['Jan'], ['Jen', 'Jess'], ['Jem', 'Jack',
        'Janis']])
        '(6, 3)'
    """
    table_num = 0
    people_num = 0

    for people in families:
        table_num += -(-len(people)//table_size)
        people_num += len(people)
    return people_num, table_num

如果len(people)只是3,那么如何让people_num返回6。对于table_num,在-(-len(people)//table_size)中有负号,这有什么意义?有没有其他方法来计算与会者和桌子的数量,用一些简单的例子?非常感谢。你知道吗


Tags: oftosizegetlenpartydefstats
1条回答
网友
1楼 · 发布于 2024-03-28 17:55:20

由于对每个族的大小求和,people_num将显示为len(['Jan']) + len(['Jen', 'Jess']) + len(['Jem', 'Jack', 'Janis']) = 1 + 2 + 3 = 6。你知道吗

-(-len(people)//table_size)这个词有点狡猾,但是你会意识到它的作用,注意到a // b == floor(a / b)。整数除法c = a // b的定义使得c是最大的整数,使得c <= a / b(注意这里/表示浮点除法)。这使得abs(a) // abs(b) != abs(a // b)a / b < 0时生效,但这正是您在计算函数中所需的表数时所需要的。你知道吗

以下结果可以说明:

 -1 // 6 == -1           1 // 6 == 0
 -2 // 6 == -1           2 // 6 == 0 
      ...                    ...
 -6 // 6 == -1           6 // 6 == 1 
 -7 // 6 == -2           7 // 6 == 1 
 -8 // 6 == -2           8 // 6 == 1
      ...                    ...
-12 // 6 == -2          12 // 6 == 2 
-13 // 6 == -3          13 // 6 == 2 

在给定people的情况下,另一种(可能不那么优雅的)计算表数的方法是1 + (len(people) - 1) // table_size。你知道吗

最后,使用列表理解,整个函数可以缩短很多:

def get_party_stats(families, table_size=6):
    return (sum([len(f) for f in families]),
            sum([-(-len(f) // table_size) for f in families]))

相关问题 更多 >