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,
Here’s a much more Pythonic version of the code you’ve written – hopefully the comments explain the code well enough to understand.
Output:
The output actually happens to be printed in reverse order, because there is no guarantee that a dictionary’s keys will be printed in any particular order. However, you will notice that the numbers correspond where the largest number is the most significant bit. That’s why we had to do the funny business of indexing
ruleDictatlen(rule)-1-i.