-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounting_Quastion1.qmd
92 lines (72 loc) · 2.5 KB
/
counting_Quastion1.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
---
title: A counting question
format: gfm
warning: false
toc: true
---
# Question
In how many ways can we divide five different books among three people (the people are different) so that each person gets at least one book?
## python Answer
```{python}
import numpy as np
import copy
# Initialization
ketab = ['a', 'b', 'c', 'd', 'e']
Sett = {'a', 'b', 'c', 'd', 'e'}
Persons = ['one', 'two', 'three']
Result = []
# Generate initial combinations
for i in range(5):
for j in range(5):
if i == j:
continue
for k in range(5):
if k == j or k == i:
continue
# Assign books to persons
ashkhas = {'one': {ketab[i]}, 'two': {ketab[j]}, 'three': {ketab[k]}}
tempSet = {ketab[i], ketab[j], ketab[k]}
Notassign = Sett.difference(tempSet)
for person in Persons:
ashkhas_copy = copy.deepcopy(ashkhas)
ashkhas_copy[person].update(Notassign)
Result.append(copy.deepcopy(ashkhas_copy))
tempList = list(Notassign)
Person_temp = [p for p in Persons if p != person]
ashkhas2 = copy.deepcopy(ashkhas)
ashkhas2[Person_temp[0]].add(tempList[0])
ashkhas2[Person_temp[1]].add(tempList[1])
Result.append(copy.deepcopy(ashkhas2))
ashkhas3 = copy.deepcopy(ashkhas)
ashkhas3[Person_temp[1]].add(tempList[0])
ashkhas3[Person_temp[0]].add(tempList[1])
Result.append(copy.deepcopy(ashkhas3))
# Deduplicate results
Result2 = Result.copy()
len(Result2)
while True:
n = len(Result2)
RangeList = list(range(n))
to_remove = set()
for i in RangeList:
for j in RangeList:
if i >= j:
continue
x = Result2[i]
y = Result2[j]
# Calculate differences
num1 = x[Persons[0]].difference(y[Persons[0]])
num2 = x[Persons[1]].difference(y[Persons[1]])
num3 = x[Persons[2]].difference(y[Persons[2]])
res = len(num1) + len(num2) + len(num3)
if res == 0:
to_remove.add(j)
# Remove duplicates
Result2 = [r for idx, r in enumerate(Result2) if idx not in to_remove]
# Terminate loop if no changes
if len(to_remove) == 0:
break
print("""
The answer to the number of possible ways to distribute five different books among three people varies:
""", len(Result2))
```