Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 81cd29b

Browse files
author
Amogh Singhal
authored
Merge pull request devAmoghS#2 from luiz-surian/master
Add josephus_improved_v3.py
2 parents a6331e3 + 0b83476 commit 81cd29b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎josephus_improved_v3.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# The effective time complexity of this improved version is O(1).
2+
# For the problem statement, refer `josephus.py`
3+
4+
def josephus_v3(soldiers):
5+
# Convert to binary.
6+
binary = bin(soldiers)
7+
# Get the first digit and put it as last.
8+
shift = '0b' + binary[3::] + binary[2:3:]
9+
# Convert to decimal.
10+
return int(shift, 2)
11+
12+
winning = josephus_v3(soldiers=41)
13+
print(winning) #Winning Soldier: 19
14+
15+
winning = josephus_v3(soldiers=100)
16+
print(winning) #Winning Soldier: 73
17+
18+
winning = josephus_v3(soldiers=1000)
19+
print(winning) #Winning Soldier: 977
20+
21+
# Testing:
22+
test_josephus = {
23+
1: 1,
24+
2: 1,
25+
3: 3,
26+
4: 1,
27+
5: 3,
28+
6: 5,
29+
7: 7,
30+
8: 1,
31+
9: 3,
32+
10: 5,
33+
11: 7,
34+
12: 9,
35+
13: 11,
36+
16: 1,
37+
41: 19
38+
}
39+
for soldiers, expected_winner in test_josephus.items():
40+
assert josephus_v3(soldiers=soldiers) == expected_winner

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /