Convert 4-bit integer into Boolean list - python

I have an integer of which I know that it's between 0 and 15, i.e., can be expressed in 4 bits. I would like to get the bit representation of that array as a Boolean array, i.e.,
0: [False, False, False, False],
1: [True, False, False, False],
2: [False, True, False, False],
# [...]
15: [True, True, True, True]
How can I best achieve that?

Through formatting as binary:
def int_to_bool_list(num):
bin_string = format(num, '04b')
return [x == '1' for x in bin_string[::-1]]
or bitwise and:
def int_to_bool_list(num):
return [bool(num & (1<<n)) for n in range(4)]
The first function requires that the bin_string contents be reversed (with [::-1]) because string formatting formats the number the way we read it - most significant bit first, whereas the question asked for the bits in least significant bit first order.

With list comprehension:
my_int = 3
[b == '1' for b in bin(my_int)[2:].rjust(4)[::-1]] # Convert, pad and reverse
output:
[True, True, False, False]
1 2 4 8 = 3

Try that:
Bitmasks = []
Bitmasks.append(int("0001", 2))
Bitmasks.append(int("0010", 2))
Bitmasks.append(int("0100", 2))
Bitmasks.append(int("1000", 2))
myNumber = 12
Bools = []
for bm in Bitmasks:
Bools.append(myNumber|bm==myNumber)

R = 16
list = []
print bin(R)[2:]
for i in bin(R)[2:]:
if (i=="1"):
list.append(True)
else:
list.append(False)
print list
output-click here
[True, False, False, False, False]

x = 7
strBin = str(bin(x))
lsBoolVal = [i == '1' for i in strBin[2:].zfill(4)]

Related

Finding identical consecutive entries in a list and finding how many consecutive entries there are

I have a list of Boolean values such as
bool_list = [True, True, False, False, True, True, True, True, True, False]
and I need to make a list of lists in a way as such [[a,b],[c,d],...] where the first entry in the lists (e.g. a and c) are the index number of the first True in bool_list where there are 2 or more consecutive True entries (a=0 and c=4 in this case) and second entry in the lists (e.g. b and d) are the number of consecutive True entries in bool_list (b=2 and d=4 in this case). How do I write a code to solve that without importing anything new. Thanks :).
A generator based implementation with only built-ins:
def gen(bl):
count = true_start = 0
for i, b in enumerate(bl):
if b:
if not count:
true_start = i
count += 1
elif count > 1:
yield (true_start, count)
count = 0
if count:
yield (true_start, count)
>>> bool_list = [True, True, False, False, True, True, True, True, True, False]
>>> list(gen(bool_list))
[(0, 2), (4, 5)]

Moving window sum on a boollean array, with steps.

I'm struggling with creating a moving window sum function that calculates the number of True values in a given numpy Boolean array my_array, with a window size of n and in jumping steps of s.
For example, consider array my_array = [True, True, False, False, True, False, True]
the sum of a moving window of size n = 2 and with steps s = 2 should yield result = [2, 0, 1, 1], notice that the last window contains only one value.
I was trying my luck with itertools but to no avail.
Any help would be kindly appreciated.
Since you tagged numpy:
my_array = [True, True, False, False, True, False, True]
n = 2
s = 2
result = np.convolve(my_array, np.ones(n, ), mode='valid')[::s]
Straight forward.
Following code should do.
def fun(arr, n, s):
res = []
for i in range(0, len(arr), s):
res.append(sum(arr[i:i+n]))
return res
my_array = [True, True, False, False, True, False, True]
print(fun(my_array, 2, 2))

boolean sat check my code

I am getting a wrong answer for my code
n is the number of variables
and formula is a list containing clauses
Given a SAT instance with 'n' variables and clauses encoded in list 'formula',
returns 'satisfiable' if the instance is satisfiable, and 'unsatisfiable'
otherwise. Each element of 'formula' represents a clause and is a list of
integers where an integer i indicates that the literal Xi is present in the
clause and an integer -i indicates that the literal ~Xi is present in the
clause. For example, a clause "X1 v ~X11 v X7" is represented with the list
[1, -11, 7].
import itertools
n = 4
formula = [[1, -2, 3], [-1, 3], [-3], [2, 3]]
booleanValues = [True,False] * n
allorderings = set(itertools.permutations(booleanValues, n)) #create possible combinations of variables that can check if formula is satisfiable or not
print(allorderings)
for potential in allorderings:
l = [] #boolean value for each variable / different combination for each iteration
for i in potential:
l.append(i)
#possible = [False]*n
aclause = []
for clause in formula:
something = []
#clause is [1,2,3]
for item in clause:
if item > 0:
something.append(l[item-1])
else:
item = item * -1
x = l[item-1]
if x == True:
x = False
else:
x = True
something.append(x)
counter = 0
cal = False
for thingsinclause in something:
if counter == 0:
cal = thingsinclause
counter = counter + 1
else:
cal = cal and thingsinclause
counter = counter + 1
aclause.append(cal)
counter2 = 0
formcheck = False
for checkformula in aclause:
if counter2 == 0:
formcheck = checkformula
counter2 = counter2 + 1
else:
formcheck = formcheck or checkformula
print("this combination works", checkformula)
Here is a corrected version:
import itertools
n = 4
formula = [[1, -2, 3], [-1, 3], [-3], [2, 3]]
allorderings = itertools.product ([False, True], repeat = n)
for potential in allorderings:
print ("Initial values:", potential)
allclauses = []
for clause in formula:
curclause = []
for item in clause:
x = potential[abs (item) - 1]
curclause.append (x if item > 0 else not x)
cal = any (curclause)
allclauses.append (cal)
print ("Clauses:", allclauses)
formcheck = all (allclauses)
print ("This combination works:", formcheck)
Points to consider:
Instead of introducing some complex — and also wrong — logic to find the conjunction and disjunction, you can use any and all. That's cleaner and less prone to bugs.
The natural object to loop over is itertools.product([False, True], repeat = n), that is, the set [False, True] of possible boolean values raised to the power of n. In other words, the Cartesian product of n copies of [False, True]. Here is the documentation for itertools.product.
I introduced a bit more output to see how things are going. Here is the output I get with Python3 (Python2 adds parentheses but prints essentially the same):
Initial values: (False, False, False, False)
Clauses: [True, True, True, False]
This combination works: False
Initial values: (False, False, False, True)
Clauses: [True, True, True, False]
This combination works: False
Initial values: (False, False, True, False)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (False, False, True, True)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (False, True, False, False)
Clauses: [False, True, True, True]
This combination works: False
Initial values: (False, True, False, True)
Clauses: [False, True, True, True]
This combination works: False
Initial values: (False, True, True, False)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (False, True, True, True)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (True, False, False, False)
Clauses: [True, False, True, False]
This combination works: False
Initial values: (True, False, False, True)
Clauses: [True, False, True, False]
This combination works: False
Initial values: (True, False, True, False)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (True, False, True, True)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (True, True, False, False)
Clauses: [True, False, True, True]
This combination works: False
Initial values: (True, True, False, True)
Clauses: [True, False, True, True]
This combination works: False
Initial values: (True, True, True, False)
Clauses: [True, True, False, True]
This combination works: False
Initial values: (True, True, True, True)
Clauses: [True, True, False, True]
This combination works: False

How to construct logical expression for advanced slicing

I am trying to figure out a cleaner way of doing the following:
import numpy
a = np.array([1,2,4,5,1,4,2,1])
cut = a == (1 or 2)
print cut
[ True False False False True False False True]
The above is of course a simplified example. The expression (1 or 2) can be large or complicated. As a start, I would like to generalize this thusly:
cutexp = (1 or 2)
cut = a == cutexp
Maybe, cutexp can be turned into a function or something but I'm not sure where to start looking.
You could also try numpy.in1d. Say
>>> a = np.array([1,2,4,5,1,4,2,1])
>>> b = np.array([1,2]) # Your test array
>>> np.in1d(a,b)
array([ True, True, False, False, True, False, True, True], dtype=bool)
>>> (a == 2) | (a == 1)
array([ True, True, False, False, True, False, True, True], dtype=bool)

Bitmask parsing in python using only standard library

I want to parse an integer that is unpack()ed using the struct module to a list of truth values.
My current approach is this:
>>> [bool(int(_)) for _ in ("%8s" % str(bin(235)).split("b")[1]).replace(" ","0")]
[True, True, True, False, True, False, True, True]
It does the job, but is quite horribly convoluted. Anyone have an elegant and pythonesque way of doing the same?
Please note that above is just for an example and the bitmasks are not necessarily just 8 bits long, but the solution should work for an bitmask of arbitrary length (in practice it might be ok to just work with multiples of 4)
Arithmetic done elegantly, without C-style proceduralism:
size = 8
[bool(235 & (1 << size - i - 1)) for i in xrange(size)]
How about:
>>> masklen = 8
>>> [bool(int(i)) for i in str(bin(235))[2:].rjust(masklen, '0')]
[True, True, True, False, True, False, True, True]
So if you skip pack step and just use the integer:
def bitboollist(v,n=0):
l = []
t = v
while t != 0:
l.append(bool(t % 2))
t = t / 2
l.reverse()
if len(l) == 0:
l = [False]
if n > len(l):
l = [False]*(n-len(l)) + l
return l
using that on an example 1234 yields:
>>> bitboollist(1234)
[True, False, False, True, True, False, True, False, False, True, False]
>>> bitboollist(1234,n=16)
[False, False, False, False, False, True, False, False, True, True, False, True, False, False, True, False]

Categories