Is there is a simple, pythonic way of rounding to the nearest whole number without using floating point? I'd like to do the following but with integer arithmetic:
skip = int(round(1.0 * total / surplus))
==============
#John: Floating point is not reproducible across platforms. If you want your code to pass tests across different platforms then you need to avoid floating point (or add some hacky espilon stuff to your tests and hope it works). The above may be simple enough that it would be the same on most/all platforms, but I'd rather not make that determination as it is easier to avoid floating point altogether. How is that "not in the spirit of Python"?
You can do this quite simply:
(n + d // 2) // d, where n is the dividend and d is the divisor.
Alternatives like (((n << 1) // d) + 1) >> 1 or the equivalent (((n * 2) // d) + 1) // 2 may be SLOWER in recent CPythons, where an int is implemented like the old long.
The simple method does 3 variable accesses, 1 constant load, and 3 integer operations. The complicated methods do 2 variable accesses, 3 constant loads, and 4 integer operations. Integer operations are likely to take time which depends on the sizes of the numbers involved. Variable accesses of function locals don't involve "lookups".
If you are really desparate for speed, do benchmarks. Otherwise, KISS.
skip = (((total << 1) // surplus) + 1) >> 1
Shifting things left by one bit effectively multiplies by two, shifting things right by one bit divides by two rounding down. Adding one in the middle makes it so that "rounding down" is actually rounding up if the result would have been above a .5 decimal part.
It's basically the same as if you wrote...
skip = int((1.0*total/surplus) + 0.5)
except with everything multplied by 2, and then later divided by 2, which is something you can do with integer arithmetic (since bit shifts don't require floating point).
TL;DR:
q, r = divmod(total, surplus)
skip = q if q % 2 == 0 and 2*r == surplus else q + (2*r // surplus) # rounds to nearest integer; half to nearest even
This solution:
rounds to the nearest integer as demanded by OP
works for both positive and negative integers
rounds 0.5 fractional parts to nearest even integer (rnd(0.5)=0, rnd(1.5)=2) which matches the behavior of python's round function used by OP
sticks to integer arithmetic as demanded by OP (see documentation of divmod)
Full story
Inspired by zhmyh's answer answer, which is
q, r = divmod(total, surplus)
skip = q + int(bool(r)) # rounds to next greater integer (always ceiling)
, I came up with the following solution (UPDATE: that only works for non-negative total and surplus, as pointed out in the comments):
q, r = divmod(total, surplus)
skip = q + int(2 * r >= surplus) # rounds to nearest integer (floor or ceiling) if total and surplus are non-negative
Since the OP asked for rounding to the nearest whole number, zhmhs's solution is in fact slightly incorrect, because it always rounds to the next greater whole number, while my solution works as demanded works for non-negative total and surplus only. A correct solution that also works for negative numbers is:
q, r = divmod(total, surplus)
skip = q + (2 * r // surplus) # rounds to nearest integer (positive: half away from zero, negative: half toward zero)
Please note though that if 2 * r == surplus, it will basically perform ceiling for both positive and negative results, e.g. ceil(-1.5) == -1 whereas ceil(1.5) == 2. This is still correct behavior in terms of rounding to the nearest integer (because of equal distance to next lower and next greater integer) but it is asymmetrical in reference to zero. To also fix this, that is, round half away from zero, we can add a boolean condition:
q, r = divmod(total, surplus)
skip = q if q < 0 and 2*r == surplus else q + (2*r // surplus) # rounds to nearest integer; half away from zero
And even better, to round half to nearest even like python's round function used by the OP:
q, r = divmod(total, surplus)
skip = q if q % 2 == 0 and 2*r == surplus else q + (2*r // surplus) # rounds to nearest integer; half to nearest even
In case you wonder how divmod is defined: According to its documentation
For integers, the result is the same as (a // b, a % b).
We therefore stick with integer arithmetic, as demanded by the OP.
Yet another funny way:
q, r = divmod(total, surplus)
skip = q + int(bool(r))
Simply take care of the rounding rule before you ever divide. For the simplest round-half-up:
if total % surplus < surplus / 2:
return total / surplus
else:
return (total / surplus) + 1
Tweak a little bit if you need to do a proper round-to-even.
The question is the rounding strategy you are after.
Here are several that I came up with - note that integer floor and ceiling are cases, but in "round to nearest" there are many strategies. The IEEE 754 and the most professional and industrial and even elegant way of doing it is Round To Nearest Even. I've never seen a single example anywhere of doing this for integer arithmetic. You cannot go through float as the 53-bit mantissa may cause precision issues and it already applies round-to-nearest-even mode if desiring to do a different rounding strategy. The correct techniques should always stay in the integer domain
def roundNegInf(n, d): #floor
return n // d
def roundPosInf(n, d): #ceil
return (n + d + -1*(d >= 0)) // d
def roundTowardsZero(n, d):
return (n + ((d + -1*(d >=0)) if (n < 0) ^ (d < 0) else 0)) // d
def roundAwayFromZero(n, d):
return (n + (0 if (n < 0) ^ (d < 0) else (d + -1*(d >= 0)))) // d
def roundNearestPosInf(n, d):
#return (((n << 1) // d) + 1) >> 1
#return (((n * 2) // d) + 1) // 2
q, r = divmod(n, d)
return q + (2 * r <= d if d < 0 else 2 * r >= d)
def roundNearestNegInf(n, d):
q, r = divmod(n, d)
return q + (2 * r < d if d < 0 else 2 * r > d)
def roundNearestEven(n, d): #round only when for positive numbers guard, round, sticky are 11X or 1X1
q, r = divmod(n, d)
return q + (q & 1) * (2 * r == d) + ((2 * r < d) if d < 0 else (2 * r > d))
def roundNearestToZero(n, d):
q, r = divmod(n, d)
return q + (q < 0) * (2 * r == d) + ((2 * r < d) if d < 0 else (2 * r > d))
def roundNearestAwayZero(n, d):
q, r = divmod(n, d)
return q + (q >= 0) * (2 * r == d) + ((2 * r < d) if d < 0 else (2 * r > d))
def testRounding():
pairs = ((1, 2), (-1, 2), (1, -2), (-1, -2), (3, 2), (-3, 2), (3, -2), (-3, -2),
(1, 3), (-1, 3), (1, -3), (-1, -3), (2, 3), (-2, 3), (2, -3), (-2, -3))
funcs = (roundNegInf, roundPosInf, roundTowardsZero, roundAwayFromZero,
roundNearestPosInf, roundNearestNegInf,
roundNearestToZero, roundNearestAwayZero, roundNearestEven)
res = [[f(*p) for p in pairs] for f in funcs]
expected = [[0, -1, -1, 0, 1, -2, -2, 1, 0, -1, -1, 0, 0, -1, -1, 0],
[1, 0, 0, 1, 2, -1, -1, 2, 1, 0, 0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, -1, -1, 1, 2, -2, -2, 2, 1, -1, -1, 1, 1, -1, -1, 1],
[1, 0, 0, 1, 2, -1, -1, 2, 0, 0, 0, 0, 1, -1, -1, 1],
[0, -1, -1, 0, 1, -2, -2, 1, 0, 0, 0, 0, 1, -1, -1, 1],
[0, 0, 0, 0, 1, -1, -1, 1, 0, 0, 0, 0, 1, -1, -1, 1],
[1, -1, -1, 1, 2, -2, -2, 2, 0, 0, 0, 0, 1, -1, -1, 1],
[0, 0, 0, 0, 2, -2, -2, 2, 0, 0, 0, 0, 1, -1, -1, 1]
]
assert(all([x == y for x, y in zip(res, expected)]))
This should work too:
def rint(n):
return (int(n+.5) if n > 0 else int(n-.5))
Related
I wonder what is the best algorithm to sort binary array with least swaps? (having array eg [0,0,0,1,0,1,0] to become [0,0,0,0,0,1,1]).
I implemented some bubble sorts but wonder what is the optimisation for those?
My code is in python, but any language is welcomed, if anyone has a solution for the least swaps that would really improve my program and i would really appreciate!!
If you really want to do it using swaps, you can start from both ends and swap the 1s you find on the left side going forward with the 0s you find on the right side going backward.
A = [0,0,0,1,0,1,0]
left1s = (i for i,b in enumerate(A) if b==1)
right0s = (len(A)-j for j,b in enumerate(reversed(A),1) if b==0)
swapCount = 0
for i,j in zip(left1s,right0s):
if i>=j:break
A[i],A[j] = A[j],A[i]
swapCount += 1
print(A) # [0, 0, 0, 0, 0, 1, 1]
print(swapCount,"swaps") # 1 swaps
Note that the same logic can be written without the use of iterators and zip:
A = [0,0,0,1,0,1,0]
swaps = 0
f,b = 0,len(A)-1 # forward and backward indexes
while f<b: # until forward meets backward
if A[f]==0: f += 1 # skip 0s forward
elif A[b]==1: b -= 1 # skip 1s backward
else: swaps,A[f],A[b] = swaps+1,A[b],A[f] # swap misplaced bits
print(A) # [0, 0, 0, 0, 0, 1, 1]
print(swaps,"swaps") # 1 swaps
If you don't want to use .sort() or similar stuff I can think of that solution:
arr = [0,0,0,1,0,1,0]
print([0] * arr.count(0) + [1] * arr.count(1))
Which ends up in [0, 0, 0, 0, 0, 1, 1]
Edit:
l = len(arr)
z = arr.count(0)
print([0]*z + [1] * (l - z))
seems to be faster with timeit.timeit
You don't need to sort a binary array, especially with python's small integer interning.
The count of ones is given by
ones = sum(lst)
The count of zeros is the length minutes that:
zeros = len(lst) - ones
You can construct the right list with
[0] * zeros + [1] * ones
Many languages have their own implementation.
Example for javascript:
[0,0,0,1,0,1,0].sort();
returns
[ 0, 0, 0, 0, 0, 1, 1 ]
Edited: adding my own implementation on javascript.
The strategy was navigate from the begin and stop when found 1, and then navigate from the end to found 0 to swap.
It's one of multiple possible implementations.
function sortBinaryArray(binArr){
let i = 0;
let j = binArr.length;
let swapCount = 0;
while(i < j){
if(binArr[i] === 0) {
// found 0 on position i. Its sorted until now.
i++;
continue;
}
// Found 1 on posittion i. Search from the end for 0 to swap
j--;
while(i < j){
if (binArr[j] === 0) {
// Found position to swap
binArr[i] = 0;
binArr[j] = 1;
i++;
swapCount++;
break;
}
j--
}
}
console.log('swapCount='+swapCount);
}
var myArr = [0,0,0,1,0,1,0];
sortBinaryArray(myArr);
console.log(myArr)
output:
swapCount=1
Array(7) [ 0, 0, 0, 0, 0, 1, 1 ]
The following code allows me to persist the complete tic-tac-toe state as a single integer by converting the numpy array to a binary string. Each cell can be 0, 1 or 2 and therefore keeps 2 bits to represent them and then I concatenate them somehow.
import numpy as np
def convert_to_int(state):
binary = "0b"
for x in range(0, state.shape[0]):
for y in range(0, state.shape[1]):
binary += format(state[x, y].item(), '02b')
return int(binary, 0)
def convert_to_numpy(state):
cells = []
binary_string = "{0:b}".format(state).zfill(18)
for i in range(0, len(binary_string), 2):
cells.append(int(binary_string[i: i + 2], 2))
return np.array(cells).reshape((3, 3))
input_state = np.array((
(1, 2, 1),
(0, 0, 0),
(0, 0, 0)),
dtype="int32")
state_as_int = convert_to_int(input_state)
output_state = convert_to_numpy(state_as_int)
print(state_as_int)
print(output_state)
102400
[[1 2 1]
[0 0 0]
[0 0 0]]
How can I simplify the code. Is there a way to use only binary literals and bitwise operators without using string conversion?
Thank you for asking this question. I have been ignoring numpy, and this problem is an excuse to learn.
This answer uses shifting to convert to integer and vice versa.
import numpy as np
def convert_to_int(state):
a = 0
for num in state.reshape(9):
a = a + num
a = a << 2
return a
def convert_state_to_numpy(state):
cells = []
for i in range(9) :
state >>= 2
cells.insert(0,(3 & state))
return np.array(cells).reshape((3,3))
input_state = np.array((
(1, 2, 1),
(0, 0, 0),
(0, 0, 0)),
dtype="int32")
state_as_int = convert_to_int(input_state)
output_state = convert_state_to_numpy(state_as_int)
print(hex(state_as_int))
print(output_state)
This was a fun problem. Here's what I came up with:
import numpy as np
def convert_to_int(state):
binary = 0b0
for x in range(3):
for y in range(3):
binary <<= 2
binary += state[x, y].item()
return binary
def convert_to_numpy(state):
return np.array([(state & (2**(2*i + 1) + 2**(2*i))) >> 2*i for i in range(8, -1, -1)]).reshape(3, 3)
This should avoid the string conversion, and is hopefully a tad bit faster (though I didn't do any benchmarks).
I wonder if there's away to store numbers of any base in python, since you could store this as a 9 bit number in base 3...
Instead of each cell as a 32bit integer you could use two integers and store the positions as bit flags. Say for example:
Os = 0b000100000
Xs = 0b100000001
X _ _
_ _ O
_ _ X
I was intrigued by a previous comment about using base 3 numbers. Since your original question was looking for a way to compress a 3x3 array into a single integer, I will assume that you want to reduce the size of the data. The following code takes your array which may be viewed as a 9 digit base 3 number and converts it to 15 bit integer. This number is stored as an array of 2 bytes. This may be beyond the scope of your original question but, i think, it follows the spirit of the question.
import numpy as np
def encode_state(state):
a=0
for i,num in enumerate(state.reshape(9)) :
a = a + 3**i * int(num)
return a.to_bytes(2,'big')
def decode_state(byte):
encoded_value = int.from_bytes(byte,'big')
b = [0 for i in range(9)]
for i in range(9) :
num = (encoded_value // 3**i) % 3
b[i] = num
return np.array(b).reshape(3,3)
input_state = np.array((
(2, 2, 2),
(1, 2, 2),
(2, 1, 0)),
dtype="int32")
state_as_byte = encode_state(input_state)
output_state = decode_state(state_as_byte)
print (''.join('{:02x}'.format(x) for x in state_as_byte))
print(output_state)
I'm currently trying to randomize a list of 0s and 1s which should give a random order of zeros and ones with the following constraints:
1/3 of the items have to be 1s (respectively 2/3 are 0s)
No more than two 1s should occur consecutively
No more than four zeros should occur consecutively
I have worked on an option, but it did not exactly turn out to be what I need. Here's my option:
for prevItem, nextItem in enumerate(WordV[: -1]):
if nextItem == WordV[prevItem+1] and WordV[prevItem+1] == WordV[prevItem+2] and nextItem ==1:
WordV[prevItem+2] = 0
if nextItem == WordV[prevItem+1] and WordV[prevItem+1] == WordV[prevItem+2] and WordV[prevItem+2] == WordV[prevItem+3] and WordV[prevItem+3] == WordV[prevItem+4] and nextItem == 0:
WordV[prevItem+2] = 1
# Check the number of ones & zeros
print(WordV)
ones= WordV.count(1)
zeros= WordV.count(0)
print(ones, zeros)
Currently, the number of ones and zeros does not add up to a proportion of 1/3 to 2/3 because the constraints replace numbers. The WordV list is a list containing 24 ones and 48 zeros that is shuffled randomly (with random.shuffle(WordV)).
Is there a smarter (and more correct) way to integrate the constraints into the code?
import numpy as np
def consecutive(data, stepsize=0):
return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
def check(list_to_check):
groups = consecutive(list_to_check)
for group in groups:
if group[0] == 1 and group.size > 2:
return True
if group[0] == 0 and group.size > 4:
return True
wordv = np.array([1]*24+[0]*48)
while check(wordv):
np.random.shuffle(wordv)
wordv will contain something like:
array([0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1,
0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1,
0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0])
The consecutive function will split the data in groups containing the same element:
[ins] In [32]: consecutive([1,1,1,0,0,1])
Out[32]: [array([1, 1, 1]), array([0, 0]), array([1])]
The check will check both conditions you specified and we will shuffle the list until we meet the conditions
You could try an optimization approach: Start with the list holding the elements in the right proportion, then keep swapping random elements until you get the desired results. In each turn, check the number of too-long streaks of 0s or 1s and always keep the better one of the original or the mutated list.
import itertools, random
def penalty(lst):
return sum(1 for k, g in itertools.groupby(lst)
if k == 0 and len(list(g)) > 4 or k == 1 and len(list(g)) > 2)
def constrained_shuffle(lst):
# penalty of original list
p = penalty(lst)
while p > 0:
# randomly swap two elements, get new penalty
a, b = random.randrange(len(lst)), random.randrange(len(lst))
lst[a], lst[b] = lst[b], lst[a]
p2 = penalty(lst)
if p2 > p:
# worse than before, swap back
lst[a], lst[b] = lst[b], lst[a]
else:
p = p2
lst = [0] * 20 + [1] * 10
random.shuffle(lst)
constrained_shuffle(lst)
print(lst)
For 200 0s and 100 1s this will take a few hundred to a few thousand iterations until it finds a valid list, which is okay. For lists with thousands of elements this is rather too slow, but could probably be improved by memorizing the positions of the too-long streaks and preferrably swapping elements within those.
About the "randomness" of the approach: Of course, it is less random than just repeatedly generating a new shuffled list until one fits the constraints, but I don't see how this will create a bias for or against certain lists, as long as those satisfy the constraints. I did a short test, repeatedly generating shuffled lists and counting how often each variant appears:
counts = collections.Counter()
for _ in range(10000):
lst = [0] * 10 + [1] * 5
random.shuffle(lst)
constrained_shuffle(lst)
counts[tuple(lst)] += 1
print(collections.Counter(counts.values()).most_common())
[(7, 197), (6, 168), (8, 158), (9, 157), (5, 150), (10, 98), (4, 92),
(11, 81), (12, 49), (3, 49), (13, 43), (14, 23), (2, 20), (15, 10),
(1, 8), (16, 4), (17, 3), (18, 1)]
So, yes, maybe there are a few lists that are more likely than others (one appeared 18 times, three 17 times, and most others 5-9 times). For 100,000 iterations, the "more likely" lists appear ~50% more often than the others, but still only about 120 times out of those 100,000 iterations, so I'd think that this is not too much of a problem.
Without the initial random.shuffle(lst) there are more lists what appear much more often than the average, so this should not be skipped.
I don't really know python, so I'll give you pseudocode:
int length;
int[] onesAndZeros = new int[length];
for(int i: onesAndZeros) { // generate a random list
i = random(0, 1);
}
int zeroCount() { // correct the ratio
int c;
for(int i: onesAndZeros) {
if(i == 0) {
c++;
}
}
return c;
}
int wantedZeros;
if(zeroCount() / (length - zeroCount()) != 2) { // you should probably check a small interval, but this answer is already long
int a = 2*(length - zeroCount()) - zeroCount(); // I will include the math if necessary
wantedZeros = zeroCount() + a;
}
while(zeroCount() != wantedZeros) {
boolean isLess = zeroCount < wantedZeros;
if(isLess) {
onesAndZeros[random(0, length - 1)] = 0;
} else {
onesAndZeros[random(0, length - 1)] = 0;
}
}
string isCorrect() { // fix the 2 1s and 4 0s
for(int i = 0; i < length; i++) {
if(onesAndZeros[i] == 0 &&
onesAndZeros[i + 1] == 0 &&
onesAndZeros[i + 2] == 0 &&
onesAndZeros[i + 3] == 0 &&
onesAndZeros[i + 4] == 0) { // be sure not to go out of bounds!
return "0" + i;
} else
if(onesAndZeros[i] == 1 &&
onesAndZeros[i + 1] == 1 &&
onesAndZeros[i + 2] == 1) {
return "1" + i;
} else {
return "a";
}
}
}
void fix(int type, int idx) {
if(type == 0) {
onesAndZeros[idx + 4] = 1;
} else {
onesAndZeros[idx + 2] = 0;
}
}
string corr = isCorrect();
while(length(corr) >= 2) { // note: this step will screw up the ones/zeros ratio a bit, if you want to restore it, consider running the last 2 steps again
if(corr[0] == '0') {
fix(0, toInt(removeFirstChar(corr)));
} else {
fix(1, toInt(removeFirstChar(corr)));
}
}
// done!
I'm well aware that this can be greatly optimized and cleaned up, depending on the language. But this is more of a solid base to build upon.
I am trying to implement the divide-and-conquer algorithm for polynomial multiplication. Here is the pseudocode given in the lecture notes:
where A, B are lists of coefficients of each polynomial, n is the size of the problem (degree - 1) and a_l, b_l are indices of the coefficients of interest.
Here is my attempt at implementing it using Python3:
def poly_mult_dc_naive(A, B, n, a, b):
n = int(n)
a = int(a)
b = int(b)
C = [None] * int(2*n - 1)
if n == 1:
C[0] = A[a] * B[b]
return C[0]
C[0:n-1] = poly_mult_dc_naive(A, B, n//2, a, b)
C[n:2*n-1] = poly_mult_dc_naive(A, B, n//2, a + (n // 2), b + (n // 2))
W = poly_mult_dc_naive(A, B, n/2, a, b + (n // 2))
V = poly_mult_dc_naive(A, B, n/2, a + n/2, b)
C[n // 2:n + (n // 2) - 1] += W + V
return C
However I'm getting strange results. For example let A = [1,2,3,4] B = [4,3,2,1] I get:
[4, None, 8, 3, 6, 12, None, 16, 9, 12, 2, None, 4, 1, 2, None, 8, 3, 4, None, None]
Correct answer is [4, 11, 20, 30, 20, 11, 4]
Could someone please point out where I've gone wrong and how it could be done?
Quick update: I think I've managed to debug my code my using a numpy array for C instead of a list. Here is the updated version:
import numpy as np
def poly_mult_dc_naive(A, B, n: int, a: int, b: int):
C = np.zeros(2*n - 1, dtype=int) # here I changed it from list to np array
if n == 1:
C[0] = A[a] * B[b]
return C[0]
C[0:n-1] = poly_mult_dc_naive(A, B, n//2, a, b)
C[n:2*n-1] = poly_mult_dc_naive(A, B, n//2, a + (n // 2), b + (n // 2))
W = poly_mult_dc_naive(A, B, n//2, a, b + (n // 2))
V = poly_mult_dc_naive(A, B, n/2, a + (n//2), b)
C[(n // 2) : (3*n // 2) - 1] += W + V
return C
BONUS QUESTION: Does anyone know of a better way I could keep the arguments n, a, and b as int types?
I just feel like having to write:
n = int(n)
a = int(a)
b = int(b)
might not be the most elegant way.
There should be no need to coerce n,a,b from float to int. Just use // 2 integer division everywhere (i.e. in the W,V lines). That will "keep" ints as ints.
The line C[n // 2:n + (n // 2) - 1] badly needs parenthesizing, it misreads very easily. I'd write C[(n//2) : (3*n//2)-1]
But I seriously recommend you use numpy vectors, not Python lists. Adding, multiplying etc. are vectorized.
I am searching for the most pythonic way to check, whether one or more elements in a list are even multiples of a predefined number with a predefined tolerance. An example is given below:
myNumber=3.5
myList=[0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8,8.5,9,9.5]
myTolerance=0.5
myResult=[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0]
Any suggestions are very appreciated.
How about
from numpy import mod, floor
withinTolAbove=[int(mod(number, myNumber) <= myTolerance and
mod(floor(number / myNumber), 2) == 0) for number in myList]
withinTolBelow=[int(mod(number + myTolerance, myNumber) <= myTolerance and
mod(floor((number + myTolerance) / myNumber), 2) == 0) for number in myList]
myResult=[max(i1, i2) * int(number > myTolerance) for i1, i2, number in zip(withinTolAbove, withinTolBelow, myList)]
The first part determines if the division is within the tolerance of an integer and the second part figures out if this integer is divisible by 2.
How about
print print([int(abs(x - round(x / myNumber) * myNumber) <= myTolerance and round(x / myNumber) > 1.5) for x in myList])
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]