- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbit_compression.py
More file actions
Latest commit
37 lines (34 loc) · 1.52 KB
/
Copy pathbit_compression.py
File metadata and controls
37 lines (34 loc) · 1.52 KB
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
classCompressedGene:
def__init__(self, gene: str) ->None:
self._compress(gene)
def__str__(self) ->str: # string representation for pretty printing
returnself.decompress()
def_compress(self, gene: str) ->None:
self.bit_string: int=1# start with sentinel
fornucleotideingene.upper():
self.bit_string<<=2# shift left two bits
ifnucleotide=='A': # change last two bits to 00
self.bit_string|=0b00
elifnucleotide=='C': # change last two bits to 01
self.bit_string|=0b01
elifnucleotide=='G': # change last two bits to 10
self.bit_string|=0b10
elifnucleotide=='T': # change last two bits to 11
self.bit_string|=0b11
else:
raiseValueError('Invalid Nucleotide:{}'.format(nucleotide))
defdecompress(self) ->str:
gene: str=''
foriinrange(0, self.bit_string.bit_length() -1, 2): # - 1 to exclude sentinel
bits: int=self.bit_string>>i&0b11# get just 2 relevant bits
ifbits==0b00: # A
gene+='A'
elifbits==0b01: # C
gene+='C'
elifbits==0b10: # G
gene+='G'
elifbits==0b11: # T
gene+='T'
else:
raiseValueError('Invalid bits:{}'.format(bits))
returngene[::-1] # [::-1] reverses string by slicing backward