-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraycode.py
More file actions
48 lines (36 loc) · 982 Bytes
/
graycode.py
File metadata and controls
48 lines (36 loc) · 982 Bytes
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
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python
# coding: utf-8
# helper function
def padding(n:int):
s = ''
for i in range(n):
s = s + '0'
return s
def binaryGen(n:int):
"""
Generating n digit binary numbers
"""
binaryNo = [padding(n-len(bin(i)[2:]))+bin(i)[2:] for i in range(2**n)]
return binaryNo
def conv_grayCode(inp_s:str):
"""
Converting binary no to corresponding Gray code (Reflector Code)
"""
ans = inp_s[0]
for i in range(1,len(inp_s)):
ans = ans + str(int((int(inp_s[i]) and not int(inp_s[i-1])) or (int(inp_s[i-1]) and not int(inp_s[i]))))
# print(ans)
return ans
def decTobin(n):
"""
Converting any number from base 10 to binary number i.e. base 2
ex. decTobin(9) = 1001, decTobin(5) = 0101
"""
return (bin(n).replace("0b",""))
def binTodec(s):
tot = 0
i = 0
for k in s[::-1]:
tot = tot + int(k)*(2**i)
i = i + 1
return (tot)