我正在寻找一种Pythonic方法来计算正整数的二进制表示中的尾随零的数量n(这将表示其中最高功率2除以n没有余数).
简单的解决方案:
def CountZeros(n):
c = 0
while (n % 2) == 0:
n /= 2
c += 1
return c
Run Code Online (Sandbox Code Playgroud)
但为了以更加Pythonic的方式做到这一点,我认为我可以利用:
bin(n)[2:],给出二进制表示 nbin(n)[:1:-1],它给出了反向二进制表示 n所以我的问题可以简化为计算字符串中尾随零的数量.
有没有单一陈述方式来做到这一点?
我的最终目标是用于计算最高功率的Pythonic方法,2其中n没有余数,所以任何方法不是通过计算字符串中的尾随零来实现这一点也是值得赞赏的.
如何计算字符串向量中的尾随零.例如,如果我的字符串向量是:
x = c('0000','1200','1301','X230','9900')
Run Code Online (Sandbox Code Playgroud)
答案应该是
> numZeros
[1] 4 2 0 1 2
Run Code Online (Sandbox Code Playgroud)
我不想使用多个,ifelse因为我认为应该存在更优雅和更快的解决方案.我尝试使用模数,就像这样
y = as.integer(x)
numZeros = (!(y%%10000))+(!(y%%1000))+(!(y%%100))+(!(y%%10))
Run Code Online (Sandbox Code Playgroud)
但这需要两个条件才能成真.
然后使用stringr包并创建了一个解决方案,但它非常冗长.
library(stringr)
numZeros =
4*str_detect(x,"0000") +
3*str_detect(x,"[1-9 A-Z]000") +
2*str_detect(x,"[1-9 A-Z]{2}00") +
str_detect(x,"[1-9 A-Z]{3}0")
Run Code Online (Sandbox Code Playgroud)
另外,我无法通过查看定义来弄清楚是否str_detect使用.ifelsestr_detect