Search code examples
pythonpermutationprobability

Python Converting Permutation of a Sequence to Smaller Code Block


in my college probability course they wanted us to write a code about 7 people to get right dinner for i in [0, 7] in this condition my code works and finds the right amount of possibilities but I think there should be an easier way of doing it with functions since this creates a pattern. How can I do it?

lst is the permutations of "0123456" sequence:

lst = [['0', '1', '2', '3', '4', '5', '6']
       ['0', '1', '2', '3', '4', '6', '5']...


counts = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}
for j in lst:
    if j[0] != '0' and j[1] != '1' and j[2] != '2' and j[3] != '3' and j[4] != '4' and j[5] != '5' and j[6] != '6':
        counts[0] += combination(7, 0)
for j in lst:
    if j[0] == '0' and j[1] != '1' and j[2] != '2' and j[3] != '3' and j[4] != '4' and j[5] != '5' and j[6] != '6':
        counts[1] += combination(7, 1)
for j in lst:
    if j[0] == '0' and j[1] == '1' and j[2] != '2' and j[3] != '3' and j[4] != '4' and j[5] != '5' and j[6] != '6':
        counts[2] += combination(7, 2)
...
for j in lst:
    if j[0] == '0' and j[1] == '1' and j[2] == '2' and j[3] == '3' and j[4] == '4' and j[5] == '5' and j[6] == '6':
        counts[7] += combination(7, 7)

Solution

  • In this code fragment, I don't exactly know what your works are. The code above might be simply written like this in Python and programming perspective:

    lst = [['0', '1', '2', '3', '4', '5', '6']
           ['0', '1', '2', '3', '4', '6', '5']
           ...
           ]
    normal_list = ['0', '1', '2', '3', '4', '5', '6']
    counts = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0}
    for j in lst:
        count = len([index for index, item in enumerate(j) if item == normal_list[index]])
        break_point = len([index for index, item in enumerate(j[:count]) if item == normal_list[index]])
        if count == break_point:  # means you have == before the break point and != afterwards.
            counts[count] += combination(7, count)