【问题标题】:Creating random, non recurrent groups of undetermined size from a list从列表中创建大小未定的随机、非重复组
【发布时间】:2021-03-13 18:01:02
【问题描述】:

我想创建一个程序,用户可以在其中输入他们想要的组的最大大小。这些组由提交表单中的名称列表组成。这个想法是有多个轮次,其中名称以请求的最大组大小配对,并且每轮都不会创建先前形成的组。此外,任何人都不应被排除在外,因此不能以 1 人为一组。

我有两个问题:首先:如果我有一个包含 10 个名称的列表并且我输入我想要 3 人的最大大小组,我会得到 3 组 3 人和 1 人中的 1 人,但它应该是 3, 3, 2, 2. 我使用了在这里找到的两个不同的函数,但都存在相同的问题。

其次,我不知道如何确保在新一轮中不会有上一轮的任何组。

我对编程很陌生,所以欢迎任何提示。 这是我拥有的第一个功能:

members = group_size()

def teams(amount, size):
    for i in range(0, len(amount), size):
        yield amount[i:i + size]

participants = Row_list_names
random.shuffle(participants)

print("These are your groups:")
print(list(teams(participants, members)))

这是第二个:

members = group_size()
participants = Row_list_names
random.shuffle(participants)
for i in range(len(participants) // members + 1):
    print('Group {} consists of:'.format(i+1)) 
    group = participants[i*members:i*members + members]
    for participant in group:
        print(participant)

group_size() 返回一个整数,表示组中应该有多少人。

【问题讨论】:

    标签: python-3.x list random unique


    【解决方案1】:

    对于第二个问题,洗牌应该可以很好地解决问题。

    对于第一个问题,函数正在按照您的指示进行操作:您向前跳过并将列表切成块,其中恰好包含 member 参与者。您不会注意到最后一个切片超出范围,因为 python 对此很宽容:

    >>> l = [0,1,2,3,4]
    >>> l[:40]
    [0, 1, 2, 3, 4]
    

    重点是并非所有组的大小都应相同:

    from math import ceil
    from math import floor
    
    def split_groups(group_size, part):
        # first compute the number of groups given the requested size
        group_num = ceil(len(part) / group_size)
        print(f"group_num {group_num}")
        # compute a fractional length of the groups
        group_size_frac = len(part) / group_num
        print(f"group_size_frac {group_size_frac}")
    
        total_assigned = 0
    
        for i in range(group_num):
            # get the start and end indexes using the fractional length
            start = floor(i * group_size_frac)
            end = floor((i + 1) * group_size_frac)
            group = part[start:end]
            print(f"start {start} end {end} -> {group}")
            print(f"number of participants in this group {len(group)}")
    
            total_assigned += len(group)
    
        # check that we assigned all of the participants
        assert total_assigned == len(part)
    

    我没有测试任何边缘情况,但通过运行快速检查

    for group_size in range(1, 5):
        for num_participants in range(10, 50):
            part = list(range(num_participants))
            split_groups(group_size, part)
    

    显示每个参与者都被分配到一个组。

    加入你之前做的洗牌,你有随机组。

    干杯!

    【讨论】:

      猜你喜欢
      • 2013-07-05
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      相关资源
      最近更新 更多