Skip to content

Commit 6f1fc9f

Browse files
One-Xiao-Yikeon
authored andcommitted
It seems to be wrong in algorithms/bit/binary_gap.py (#518)
* It seems to be wrong. * It seems to be wrong. * I haven't read all of them yet, so delete the test section to avoid mistakes in PR. * back * back
1 parent 321d492 commit 6f1fc9f

File tree

3 files changed

+39
-5
lines changed

3 files changed

+39
-5
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ matrix:
1111
- python: 3.6
1212
env: TOX_ENV=py36
1313
- python: 3.7
14-
env: TOX_ENV=py37,coverage
14+
env: TOX_ENV=py37
1515
install:
1616
- pip install -r test_requirements.txt
1717
before_script:

algorithms/arrays/move_zeros.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,19 @@
88
"""
99

1010

11+
# False == 0 is True
1112
def move_zeros(array):
1213
result = []
1314
zeros = 0
1415

1516
for i in array:
16-
if i == 0: # not using `not i` to avoid `False`, `[]`, etc.
17-
zeros += 1
18-
else:
19-
result.append(i)
17+
if i == 0 and type(i) != bool: # not using `not i` to avoid `False`, `[]`, etc.
18+
zeros += 1
19+
else:
20+
result.append(i)
2021

2122
result.extend([0] * zeros)
2223
return result
24+
25+
26+
print(move_zeros([False, 1, 0, 1, 2, 0, 1, 3, "a"]))

algorithms/bit/binary_gap.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@
1313
The second consecutive pair of 1's have distance 1.
1414
The answer is the largest of these two distances, which is 2
1515
"""
16+
17+
18+
# 原方法为 binary_gap,但通过实验发现算法有误,不论是什么数,输出值最多为2。
19+
# 改进方法为binary_gap_improved。
20+
# The original method is binary_gap,
21+
# but the experimental results show that the algorithm seems to be wrong,
22+
# regardless of the number, the output value is up to 2.
23+
# The improved method is binary_gap_improved.
1624
def binary_gap(N):
1725
last = None
1826
ans = 0
@@ -25,3 +33,25 @@ def binary_gap(N):
2533
index = index + 1
2634
N = N >> 1
2735
return ans
36+
37+
38+
def binary_gap_improved(N):
39+
last = None
40+
ans = 0
41+
index = 0
42+
while N != 0:
43+
tes = N & 1
44+
if tes:
45+
if last is not None:
46+
ans = max(ans, index - last + 1)
47+
else:
48+
last = index
49+
else:
50+
last = index + 1
51+
index = index + 1
52+
N = N >> 1
53+
return ans
54+
55+
56+
print(binary_gap(111))
57+
print(binary_gap_improved(111))

0 commit comments

Comments
 (0)