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)
中有负号,这有什么意义?有没有其他方法来计算与会者和桌子的数量,用一些简单的例子?非常感谢。你知道吗
由于对每个族的大小求和,
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
时生效,但这正是您在计算函数中所需的表数时所需要的。你知道吗以下结果可以说明:
在给定
people
的情况下,另一种(可能不那么优雅的)计算表数的方法是1 + (len(people) - 1) // table_size
。你知道吗最后,使用列表理解,整个函数可以缩短很多:
相关问题 更多 >
编程相关推荐