1

I want my function to divide a random list of students into groups according to a given size (Z). Student(X,Y) is a function that removes all students in group X that are also in group Y, but that is unimportant for this question.

A given input can be random_teams(S,T,[6,5,4]) With this function I want to create groups of size 6, 5 and 4. Thus I want to iterate over this list. Nevertheless, it only returns a list with 6 elements, and does not give me a list with the remaining 5 and 4.

def random_teams(X,Y,Z):
    l = random.sample(student(X,Y), len(student(X,Y)))
    for i in Z:
        return l[:i]
        l = l[i:]
  • 6
    `return` causes a function to immediately terminate, and no statements appearing after it will execute. Did you intend to use `yield` instead? – Kevin Feb 03 '16 at 21:11
  • when I replace 'return' by 'yield' I get the following –  Feb 03 '16 at 21:16
  • 1
    What are you expecting the output of `random_teams` to be? A list? A generator? – Brendan Abel Feb 03 '16 at 21:17
  • You need to call `list(random_teams(...)` or iterate over, `for samp in random_teams(...`....http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python, there are also easier ways. `[l[:i] for i in Z]` – Padraic Cunningham Feb 03 '16 at 21:18

1 Answers1

0

Something like this will work:

from random import shuffle

#Assuming X and Y each to be a list of students

def random_teams(X,Y,Z):
    #call your student() function here, and return 2 lists, X and Y
    #X,Y = student(X,Y)

    allStudents = X + Y
    numStudents = sum(Z)

    assert len(allStudents) == numStudents, "Mismatch in number of students"

    shuffle(allStudents) # remove this line if you dont want random ordering

    groups = []

    for size in Z:
        tempGroup = []
        for i in range(size):
            tempGroup.append(allStudents.pop())
        groups.append(tempGroup)


random_teams(["mary", "john", "jason"],["ali", "simon","jane","james"],[1,3,3])

That will give the following as output:

[['jason'], ['james', 'simon', 'john'], ['mary', 'ali', 'jane']]
Simon
  • 9,762
  • 15
  • 62
  • 119