Skip to content

Commit 6e484d8

Browse files
committed
*iterating_through_submasks.py is added in dynamic_programming
1 parent ac5b41c commit 6e484d8

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
You are given a bitmask m and you want to efficiently iterate through all of
3+
its submasks. The mask s is submask of m if only bits that were included in
4+
bitmask are set
5+
'''
6+
7+
def list_of_submasks(mask)->list:
8+
9+
"""
10+
Args:
11+
mask : number which shows mask ( always integer > 0, zero does not have any submasks )
12+
13+
Returns:
14+
all_submasks : the list of submasks of mask (mask s is called submask of mask
15+
m if only bits that were included in original mask are set
16+
17+
Raises:
18+
AssertionError: mask not positive integer
19+
20+
>>> list_of_submasks(15)
21+
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
22+
>>> list_of_submasks(13)
23+
[13, 12, 9, 8, 5, 4, 1]
24+
25+
"""
26+
27+
fmt = "n needs to be positive integer, your input {}"
28+
assert isinstance(mask, int) and mask > 0, fmt.format(mask)
29+
30+
'''
31+
first submask iterated will be mask itself then operation will be performed
32+
to get other submasks till we reach empty submask that is zero ( zero is not
33+
included in final submasks list )
34+
'''
35+
all_submasks = []
36+
submask = mask
37+
38+
while submask:
39+
all_submasks.append(submask)
40+
submask = (submask-1) & mask
41+
42+
return all_submasks
43+
44+
if __name__ == '__main__':
45+
import doctest
46+
doctest.testmod()

0 commit comments

Comments
 (0)