I am working on going from o-string binary to Unicode, part of this process requires converting Raised Position to Binary. I can't seem to be able to get it done. The doc test will explain what needs to be performed.
I have provided my code below but it is nowhere close to getting the correct answer.
def raisedpos_to_binary(s): ''' (str) -> str Convert a string representing a braille character in raised-position representation into the binary representation. TODO: For students to complete.
>>> raisedpos_to_binary('')
'00000000'
>>> raisedpos_to_binary('142536')
'11111100'
>>> raisedpos_to_binary('14253678')
'11111111'
>>> raisedpos_to_binary('123')
'11100000'
>>> raisedpos_to_binary('125')
'11001000'
'''
res = ''
lowest_value = '00000000'
for i, c in enumerate(s):
if c == i:
lowest_value = lowest_value.replace('0', '1')
return lowest_value
Looks like you can create a set (converted to integers) of the single digits and then produce '1' or '0' iterating over a range of 1..8, eg:
def raisedpos_to_binary(digits):
raised = {int(digit) for digit in digits}
return ''.join('1' if n in raised else '0' for n in range(1, 9))
Tests:
for test in ['', '142536', '14253678', '123', '125']:
print(test, '->', raised_pos_to_binary(test))
Gives you:
-> 00000000
142536 -> 11111100
14253678 -> 11111111
123 -> 11100000
125 -> 11001000
So in full, your module should contain:
def raisedpos_to_binary(digits):
"""
>>> raisedpos_to_binary('')
'00000000'
>>> raisedpos_to_binary('142536')
'11111100'
>>> raisedpos_to_binary('14253678')
'11111111'
>>> raisedpos_to_binary('123')
'11100000'
>>> raisedpos_to_binary('125')
'11001000'
"""
raised = {int(digit) for digit in digits}
return ''.join('1' if n in raised else '0' for n in range(1, 9))
if __name__ == '__main__':
import doctest
doctest.testmod()
Then run your script using:
python your_script.py -v