如何检查1后面是否总是有0 [英] How do I check if 1 is always followed by a 0

查看:55
本文介绍了如何检查1后面是否总是有0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中,我找不到关于如何确定数字列表中某位置的总跟1后面是否总有0的解决方案>.不必是直接的追随者.

In Python, I cannot find a solution as to how to determine whether there is always a 0 following a 1 somewhere in a list of numbers, to form a pair 10. It doesn't have to be direct follower.

为清楚起见,我的意思是列表",具体来说就是二进制数().

For clarity, I mean "list" as in (sort of) binary number, to be specific,

1100  #pass
1001  #fail
1010  #pass
0101  #fail

11110000  #pass
11100001  #fail

11100100  #pass

在0es之前必须始终有相等的1es. 预先感谢.

There must be always an equal number of 1es before 0es. Thanks in advance.

推荐答案

这里是NumPy方法,具有附带的实用程序功能,可将字符串转换为数组.

Here is a NumPy method, with accompanying utility function to convert the strings into arrays.

import numpy as np

def nums_str_to_ndarr(str_in: str) -> np.ndarray:
    return np.fromiter(str_in, dtype=int, count=len(str_in))


def valid_ones_arr(nums_arr: np.ndarray) -> bool:
    nums_arr[nums_arr == 0] = -1
    nums_arr = np.cumsum(nums_arr)
    return np.all(nums_arr >= 0) and (nums_arr[-1] == 0)

在寻找更好的解决方案时,我将其用作基准/标准.当然,我们都欢迎您这样做:)

I will be using it as a benchmark/standard while looking for a better solution. You are of course all welcome to do the same :)

这篇关于如何检查1后面是否总是有0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆