Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I have a question...
#1
Is is possible to do something like splitting a group? Like if I wanted to deal cards equally to 2 players (26 cards for a person) how is that possible to code?
Reply
#2
Depending on what you mean by "group" there are many ways this can be done. What have you tried?
Reply
#3
I mean like that:
group = ['a', 'b', 'c', 'd', 'e', 'f']
I have 2 more groups: x and y.
x = []
y = []
I want elements of 'group' go to x and y equally (so 3 to x and 3 to y) and for that to be random.
Reply
#4
You have a list, not a group. How would you like to divide the elements in the list? In the end, what should be in x and what in y?
Reply
#5
Is this Homework?

import random


def random_group(sequence, groups=2):
    # preparing nested list for results
    result = [[] for _ in range(groups)]
    # copy sequence, to prevent modification
    # of the original list
    data = sequence.copy()
    # shuffle the data
    random.shuffle(data)

    # iterate until data is empty
    # bool(empty_list) -> False
    while data:
        # pop the objects and append them to the result
        for index in range(groups):
            # if the list `data` is empty,
            # the call to pop() raises an IndexError
            try:
                result[index].append(data.pop())
            except IndexError:
                # ignoring the IndexError
                # data is here empty and
                # the while-loop stops because
                # bool(data) is False
                pass

    return result


groups = ["a", "b", "c", "d", "e", "f"]
x, y = list(random_group(groups))
Larz60+ likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020