I have a function that returns an 8 digit long binary string for given parameter:
def rule(x):
rule = bin(x)[2:].zfill(8)
return rule
I want to traverse each index of this string and check if it is a zero or a one. I tried to write a code like this:
def rule(x):
rule = bin(x)[2:].zfill(8)
while i < len(rule(x)):
if rule[i] == '0'
ruleList = {i:'OFF'}
elif rule[i] == '1'
ruleList = {i:'ON'}
i = i + 1
return ruleList
This code doesn't work. I am getting "Error: Object is unsubscriptable". What I am attempting to do is write a function that takes the following input, for example:
Input: 30
1. Converts to '00011110' (So far, so good)..
2. Checks if rule(30)[i] is '0' or '1' ('0' in this case where i = 0)
3. Then puts the result in a key value pair, where the index of the
string is the key and the state (on
or off) is the value.
4. The end result would be 'ruleList', where print ruleList
would yield something like this:
{0:'Off',1:'Off',2:'Off',3:'On',4:'On',5:'On',6:'On',7:'Off'}
Can someone help me out? I am new to python and programming in general so this function has proven to be quite challenging. I would like to see some of the more experienced coders solutions to this particular problem.
Thanks,