Skip to content

Commit 78bc489

Browse files
committed
cleaning up code and updating README
1 parent 8278a96 commit 78bc489

File tree

9 files changed

+90
-65
lines changed

9 files changed

+90
-65
lines changed

README.md

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,33 @@
11
# Py-Problems
22

3-
Misc riddles, games, and problems modeled using python.
3+
A collection of riddles, games, and problems modeled using python.
44

55
## [Soduko Solver](./projects/soduko_solver/)
66

77
Solves soduko puzzles using recursion.
88

99
## [100 Prisoner Problem](./projects//prisoner_problem/)
1010

11-
Tests probabilities for different strategies to solve the 100 Prisoner Problem.
11+
Each of 100 prisoner has to find their own number in one of 100 drawers, but may open only 50 of the drawers.
12+
This program tests probabilities for different strategies to solve the [100 Prisoner Problem](https://en.wikipedia.org/wiki/100_prisoners_problem).
13+
14+
<img
15+
src="./images/100_prisoner.jpg"
16+
alt="100 prisoners problem screenshot"
17+
title="100 prisoners problem screenshot"
18+
style="display: inline-block; margin: 1rem auto; max-width: 600px">
19+
20+
## [Collatz Conjecture (3n + 1 problem)](./projects/collatz_conjecture/)
21+
22+
Given a set of integers, this program calculates the sequence of numbers (steps) for each integer following the rules of [Collatz Conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture):
23+
24+
* If the previous term is even, the next term is one half of the previous term (*n / 2*).
25+
* If the previous term is odd, the next term is 3 times the previous term plus 1 (*3n + 1*).
26+
27+
The results are displayed on a graph.
28+
29+
<img
30+
src="./images/Collatz_Conjecture.jpg"
31+
alt="Collatz Conjecture screenshot"
32+
title="Collatz Conjecture screenshot"
33+
style="display: inline-block; margin: 1rem auto; max-width: 600px">

images/100_prisoner.jpg

61.3 KB
Loading

images/Collatz_Conjecture.jpg

86.8 KB
Loading
Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1-
# Collatz Conjecture
1+
# Collatz Conjecture (3n + 1 problem)
22

3-
Reference [Wikipedia](https://en.wikipedia.org/wiki/Collatz_conjecture)
3+
Reference [Wikipedia](https://en.wikipedia.org/wiki/Collatz_conjecture)
4+
This program was inspired by watching a [Youtube video](https://www.youtube.com/watch?v=094y1Z2wpJg&t=319s) from Veritasium about Collatz Conjecture, and implements a function to ouput the steps for a given set of integers and plot the results to a graph.
5+
6+
## Problem
7+
8+
This problem concerns any sequences of integers in which each term is obtained from the previous term as follows:
9+
10+
* If the previous term is even, the next term is one half of the previous term (*n / 2*).
11+
* If the previous term is odd, the next term is 3 times the previous term plus 1 (*3n + 1*).
12+
13+
The conjecture is that these sequences always reach 1, no matter which positive integer is chosen to start the sequence.

projects/collatz_conjecture/main.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
def n(num: int) -> list:
44
_n = [num]
5-
# print(num)
65
while num > 1:
76
if num % 2:
87
# num is odd
@@ -16,12 +15,13 @@ def n(num: int) -> list:
1615
if __name__ == "__main__":
1716
y = []
1817
p = plt
19-
for x in range(3,40):
18+
for x in range(4,41,2):
2019
z = n(x)
2120
if max(z) > 1:
2221
y.append(z)
2322
p.plot(z)
24-
print(x)
2523

26-
p.ylabel('some numbers')
24+
p.title("Collatz Conjecture", loc="center")
25+
p.ylabel('Step Value')
26+
p.xlabel('Step Count')
2727
p.show()

projects/prisoner_problem/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# 100 Prisoners Problem
2-
Reference the [Wikipedia](https://en.wikipedia.org/wiki/100_prisoners_problem#:~:text=The%20100%20prisoners%20problem%20is,cannot%20communicate%20with%20other%20prisoners.) page.
2+
Reference the [Wikipedia](https://en.wikipedia.org/wiki/100_prisoners_problem) page.
33
This program was inspired by watching a [Youtube video](https://www.youtube.com/watch?v=iSNsgj1OCLA) from Veritasium about the 100 Prisoner Problem, and tests the probabilities of the Loop Strategy described below.
44

55
## Problem

projects/prisoner_problem/main.py

Lines changed: 31 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -24,99 +24,90 @@ def init_boxes() -> list[int]:
2424
# on the outside of the box/drawer.
2525
return boxes
2626

27-
def loop_strategy(*args) -> list[bool]:
27+
def loop_strategy(boxes: list, prisoners: int = 100, attempts: int = 50) -> int:
2828
"""
2929
Loop strategy for the 100 Prisoners Problem.
3030
Should result in a success rate of greather than 30% for all
3131
prisoners to find their number.
3232
"""
3333

34-
boxes = init_boxes()
35-
prisoners_free = []
36-
for player_number in list(range(100)):
37-
box_number = player_number
38-
for _ in range(50):
39-
if boxes[box_number] == player_number:
34+
# boxes = init_boxes()
35+
prisoners_free = 0
36+
for prisoner_number in list(range(prisoners)):
37+
box_number = prisoner_number
38+
for _ in range(attempts):
39+
if boxes[box_number] == prisoner_number:
4040
# Prisoner found their number within 50 attempts
41-
prisoners_free.append(True)
41+
prisoners_free += 1
4242
break
4343
box_number = boxes[box_number]
44-
else:
45-
# Prisoner failed find their number
46-
prisoners_free.append(False)
4744

4845
return prisoners_free
4946

50-
def random_strategy(*args) -> list[bool]:
47+
def random_strategy(boxes: list, prisoners: int = 100, attempts: int = 50) -> int:
5148
"""
5249
Random strategy for the 100 Prisoners Problem.
5350
Should result in a less then 0% success rate for all prisoners
5451
to find their number.
5552
"""
5653

57-
boxes = init_boxes()
58-
prisoners_free = []
59-
for player_number in list(range(100)):
54+
# boxes = init_boxes()
55+
prisoners_free = 0
56+
for prisoner_number in list(range(prisoners)):
6057
unchecked_boxes = boxes[:]
6158

62-
for _ in range(50):
59+
for _ in range(attempts):
6360
box_number = random.randint(0, len(unchecked_boxes) - 1)
64-
prisoner_number = unchecked_boxes.pop(box_number)
61+
number_in_box = unchecked_boxes.pop(box_number)
6562

66-
if player_number == prisoner_number:
63+
if prisoner_number == number_in_box:
6764
# Prisoner found their number within 50 attempts
68-
prisoners_free.append(True)
65+
prisoners_free += 1
6966
break
70-
else:
71-
# Prisoner failed find their number
72-
prisoners_free.append(False)
67+
7368
return prisoners_free
7469

7570

7671
if __name__ == "__main__":
7772
# Run the strategy multiple times and print the average success rate.
78-
ITERATIONS = 50_000
73+
PRISONER_COUNT = 100
74+
ITERATIONS = 10_000
7975
print('########## 100 Prisoner Problem ##########')
76+
loop_results = []
77+
random_results = []
8078

81-
print("Running Loop Strategy...")
82-
with multiprocessing.Pool() as pool:
83-
loop_results = pool.map(loop_strategy, range(ITERATIONS))
79+
for _ in track(range(ITERATIONS)):
80+
boxes = init_boxes()
81+
loop_results.append(loop_strategy(boxes[:]))
82+
random_results.append(random_strategy(boxes[:]))
8483

85-
print("Running Random Strategy...")
86-
with multiprocessing.Pool() as pool:
87-
random_results = pool.map(random_strategy, range(ITERATIONS))
84+
loop_group_success_count = sum(results == PRISONER_COUNT for results in loop_results)
85+
loop_free_prisoner_count = sum(results for results in loop_results)
8886

89-
print("Tabulating Loop Strategy Results...")
90-
loop_group_success_count = sum(all(results) for results in loop_results)
91-
loop_free_prisoner_count = sum(sum(results) for results in loop_results)
87+
random_group_success_count = sum(results == PRISONER_COUNT for results in random_results)
88+
random_free_prisoner_count = sum(results for results in random_results)
9289

93-
print("Tabulating Random Strategy Results...\n")
94-
random_group_success_count = sum(all(results) for results in random_results)
95-
random_free_prisoner_count = sum(sum(results) for results in random_results)
96-
total_prisoners = ITERATIONS * 100
90+
total_prisoners = ITERATIONS * PRISONER_COUNT
9791

9892
console = Console()
9993
table = Table()
100-
table.title = f"Results: 100 Prisoner Problem\n{ITERATIONS:,} Iterations"
94+
table.title = f"\nResults: 100 Prisoner Problem\n{ITERATIONS:,} Iterations : {total_prisoners:,} Prisoners"
10195
table.add_column("Strategy")
10296
table.add_column("Group\nSuccess Count", justify="right")
10397
table.add_column("Group\nSuccess Rate", justify="right")
104-
table.add_column("Total\nPrisoners", justify="right")
10598
table.add_column("Free\nPrisoners", justify="right")
10699
table.add_column("Individual\nSuccess Rate", justify="right")
107100
table.add_row(
108101
"Loop",
109102
f"{loop_group_success_count:,}",
110103
f"{(loop_group_success_count / ITERATIONS):.2%}",
111-
f"{total_prisoners:,}",
112104
f"{loop_free_prisoner_count:,}",
113105
f"{(loop_free_prisoner_count / total_prisoners):.2%}"
114106
)
115107
table.add_row(
116108
"Random",
117109
f"{random_group_success_count:,}",
118110
f"{(random_group_success_count / ITERATIONS):.2%}",
119-
f"{total_prisoners:,}",
120111
f"{random_free_prisoner_count:,}",
121112
f"{(random_free_prisoner_count / total_prisoners):.2%}"
122113
)

projects/soduko_solver/main.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
from soduko_solver import Soduko_Solver
3+
4+
if __name__ == "__main__":
5+
6+
grid = [[3, 6, 0, 4, 5, 1, 7, 2, 0],
7+
[0, 0, 0, 0, 0, 2, 0, 0, 4],
8+
[4, 0, 2, 6, 3, 7, 0, 0, 0],
9+
[0, 0, 1, 0, 0, 0, 5, 0, 0],
10+
[0, 0, 4, 5, 1, 8, 2, 0, 3],
11+
[0, 0, 0, 0, 9, 0, 4, 6, 0],
12+
[2, 0, 0, 0, 7, 0, 0, 5, 0],
13+
[0, 7, 0, 1, 0, 0, 3, 0, 2],
14+
[0, 0, 5, 0, 0, 0, 0, 0, 7]]
15+
16+
game = Soduko_Solver(grid)
17+
18+
game.solve()

projects/soduko_solver/soduko.py

Lines changed: 0 additions & 16 deletions
This file was deleted.

0 commit comments

Comments
 (0)