Last active
March 31, 2018 19:33
-
-
Save rohit-jamuar/41aba8a9cfe66f39258b8731efd1a24a to your computer and use it in GitHub Desktop.
Generate n-bit gray codes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| ''' | |
| python3 gray_code_gen.py 5 | |
| ''' | |
| def gray_code(n): | |
| #Generate n-bit gray-codes (starting from 0000..(n times)) | |
| def __gray_codes_rec1(): | |
| if len(CODE_SEQ) == MAX_SEQ_LEN: | |
| return CODE_SEQ | |
| current = CODE_SEQ[-1] | |
| i = len(current)-1 | |
| while i >= 0: | |
| if current[i] == '1': | |
| temp = current[:i]+ '0' + current[i+1:] | |
| if temp not in FOUND: | |
| CODE_SEQ.append(temp) | |
| FOUND.add(temp) | |
| break | |
| if current[i] == '0': | |
| temp = current[:i] + '1' + current[i+1:] | |
| if temp not in FOUND: | |
| CODE_SEQ.append(temp) | |
| FOUND.add(temp) | |
| break | |
| i -= 1 | |
| return __gray_codes_rec1() | |
| def __gray_codes_rec2(n): | |
| #This one exploits the property of gray-codes | |
| if n == 1: | |
| return ['0', '1'] | |
| fwd = __gray_codes_rec2(n-1) | |
| gray_codes_current_level = list() | |
| i = 0 | |
| while i < len(fwd): | |
| gray_codes_current_level.append('0' + fwd[i]) | |
| i += 1 | |
| i = len(fwd) - 1 | |
| while i >= 0: | |
| gray_codes_current_level.append('1' + fwd[i]) | |
| i -= 1 | |
| return gray_codes_current_level | |
| if n > 0: | |
| if n > 9: | |
| return __gray_codes_rec2(n) | |
| else: | |
| START, MAX_SEQ_LEN = '0'*n, 2**n | |
| CODE_SEQ, FOUND = [START], {START} | |
| return __gray_codes_rec1() | |
| if __name__=='__main__': | |
| from sys import argv | |
| print(gray_code(int(argv[1]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment