python - Some questions on a function -


def get_party_stats(families, table_size=6):      """to calculate number of attendees , tables needed.      args:         families(list): 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      people in families:         table_num += -(-len(people)//table_size)         people_num += len(people)     return people_num, table_num 

how people_num return 6, if len(people) 3. table_num, having negative signs in -(-len(people)//table_size), achieve? there way count number of attendees , tables, using simple examples? thank you.

since sum on sizes of each family people_num come out len(['jan']) + len(['jen', 'jess']) + len(['jem', 'jack', 'janis']) = 1 + 2 + 3 = 6.

the -(-len(people)//table_size) term bit sneaky realize noting a // b == floor(a / b). integer division c = // b defined such c biggest integer number such c <= / b (note / means float-division here). makes abs(a) // abs(b) != abs(a // b) when a / b < 0 want when calculating number of tables necessary in function.

the following results may illustrate that:

 -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  

another (maybe less elegant) way of calculating number of tables necessary given people 1 + (len(people) - 1) // table_size.

finally, whole function made lot shorter using list-comprehensions:

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

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -