Wolfram mathematica Mathematica中的字符串验证

Wolfram mathematica Mathematica中的字符串验证,wolfram-mathematica,Wolfram Mathematica,我想优化一个字符串验证函数。字符串长度为2n,由0和1组成,例如str=“100001”。我想测试: 1) 字符串中奇数索引位置的1的数量(必须不小于1)是否等于均匀索引位置的数量 2) 无论对于每个StringTake[str,2*i],i从1运行到n-1,字符串中奇数索引位置的1的数量不等于均匀索引位置的数量 总之,我想测试位置2n是否是第一次字符串中奇数索引位置的1的数量是否等于均匀索引位置的数量 “100001”和101101是一个好字符串,但不是100100,100000或000000

我想优化一个字符串验证函数。字符串长度为
2n
,由
0
1
组成,例如
str=“100001”
。我想测试:

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

2) 无论对于每个
StringTake[str,2*i]
i
1
运行到
n-1
,字符串中奇数索引位置的
1
的数量不等于均匀索引位置的数量

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

“100001”和
101101
是一个好字符串,但不是
100100
100000
000000


非常感谢。

此代码不测试无效字符串(字符不是“0”或“1”,长度不是偶数)

你的例子:

goodString /@ {"100001" , "101101", "100100", "100000", "000000"}
Out[302]={True,True,False,False,False}

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

丹尼尔·利奇布劳 Wolfram Research

(为学童代码道歉,这是我第一次在Mathematica中使用字符串,所以我留下了我的thinking-as-I-Got,还有一些注释掉的调试/跟踪值)

测试:

validatestr/@{"100001","101101","100100","100000","000000"}
{{“100001”,真},{“101101”,真},{“100100”,假},{“100000”, False},{“000000”,False}

在[428]中(本地)的求值过程中:=MapThread::mptc:MapThread的位置{2,1}和{2,2}处对象的不兼容尺寸[不相等,{0,0,0},{0,0}];维度为{3}和{2}.>>


(本地)Out[432]={“0000001”,False}

对“000011”@belisarius的结果应该是False,因为1的数量在第一个偶数和第一个奇数条目中是相同的。我的代码错误的情况(可能是特殊情况)是“00”。声明为真,但违反了我们至少需要一个1的规则。我发布了评论,然后意识到是这样的。但是忘了删除评论。对不起,谢谢
charcountsvec[s_String, c_String] := Table[
   If[StringTake[s, {i, i}] == c, 1, 0]
   , {i, 1, StringLength[s]}
];

oddchars[s_String] := StringTake[s, {1, -1, 2}]; (*pick out odd chars*)    
evenchars[s_String] := StringTake[s, {2, -1, 2}];

validatestr[str_String] :=     
 Block[{evencounts, oddcounts, answer1, answer2 (*, odds, evens*)},
  evencounts = Accumulate@charcountsvec[(*evens=*)evenchars[str], "1"];
  oddcounts = Accumulate@charcountsvec[(*odds=*)oddchars[str], "1"];
  (*my interpretation of "number of 1's in odd positions the same as in even positions"*)      
  answer1 = Last[oddcounts] == Last[evencounts]; 
  (*my interpretation of "for every..string...whether number of 1's in even/odd positions is not equal"*)      
  answer2 = Fold[And, True, 
    MapThread[Unequal, {Most[oddcounts], Most[evencounts]}]];

  {str, And[answer1, answer2](*,odds,evens,oddcounts,evencounts,answer1,answer2*)}
  ];
validatestr/@{"100001","101101","100100","100000","000000"}
validatestr["0000001"](*odd length string pukes, and returns False*)