wolfram-mathematica - Mathematica 中的字符串验证

标签 wolfram-mathematica

我有一个想要优化的字符串验证函数。该字符串的长度为 2n,由 01 组成,例如 str="100001"。我想测试一下:

1) 字符串中奇数索引位置的 1 的数量(必须不少于 1)是否等于偶数索引位置的数量

2) 是否对于每个 StringTake[str,2*i]i 都从 1 运行到 n-1,字符串中奇数索引位置中 1 的数量不等于偶数索引位置中的 1 数量。

总之,我想测试位置2n是否是第一次奇数索引位置中1的数量该字符串等于均匀索引位置中的字符串。

"100001"101101 是一个很好的字符串,但不是 100100100000 也不是 000000

非常感谢。

最佳答案

此代码不会测试无效字符串(字符不是“0”或“1”,长度不均匀)。

goodString[str_String] := Module[
  {digits, cumdiffs, pos},
  digits = Transpose[Partition[
    IntegerDigits[ToExpression[str], 10, StringLength[str]], 2]];
  cumdiffs = Subtract @@ Accumulate /@ digits;
  pos = Position[cumdiffs, 0, 1, 1];
  Length[pos] == 1 && pos[[1, 1]] == Length[cumdiffs]
]

你的例子:

goodString /@ {"100001" , "101101", "100100", "100000", "000000"}

输出[302]= {真、真、假、假、假}

可能有更快的方法,例如与 NestList.此外,如果速度是一个大问题并且字符串可能很长,您可以在预处理中拆分 IntegerDigits[ToExpression[...]] 并在其余部分使用 Compile。

丹尼尔·利希特布劳 沃尔夫拉姆研究

关于wolfram-mathematica - Mathematica 中的字符串验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5146944/

相关文章:

wolfram-mathematica - 对 Manipulate 语句中的表达式求值

wolfram-mathematica - 从大表达式中提取与模式匹配的表达式

wolfram-mathematica - LevelScheme 中的直方图

string - 将字符串 hour :minutes:sec. 毫秒转换为秒

wolfram-mathematica - Mathematica 中的奇怪 Sin[x] 图

wolfram-mathematica - 在 Mathematica 中读取 UTF-8 编码的文本文件

wolfram-mathematica - Mathematica 中的交 fork 列表

java - 坚持一些角度算术

wolfram-mathematica - 轮廓图 : Styling contour lines

python-3.x - 等效代码,不同结果(Python、Mathematica)