我在reddit遇到了一个编程问题(看一下问题的链接)
这是 Python 中的解决方案之一:
s="112213"
k=2
result=0
for i in range(len(s)):
num_seen = 0
window = {}
for ind in range(i, len(s)):
if not s[ind] in window:
num_seen += 1
window[s[ind]] = 1
else:
window[s[ind]] += 1
if window[s[ind]] == k:
num_seen -= 1
if num_seen == 0:
result +=1
elif window[s[ind]] > k:
break
print(result)
Run Code Online (Sandbox Code Playgroud)
我已经尝试将此解决方案移植到 Raku 中,这是我的代码:
my @s=<1 1 2 2 1 3>;
my $k=2;
my $res=0;
for ^@s {
my $seen = 0;
my %window;
for @s[$_..*] {
if $^a == %window.keys.none {
$seen++;
%window{$^a} = 1;}
else {
%window{$^a} += 1;}
if %window{$^a} == $k {
$seen--;
if $seen == 0 {
$res++;} }
elsif %window{$^a} > $k {
last;}}}
say $res;
Run Code Online (Sandbox Code Playgroud)
它给出了这个错误:
Use of an uninitialized value of type Any in a numeric context in a block at ... line 13
如何解决?
我不觉得那是MRE。它有太多问题让我无法解决。相反,我所做的是从原始 Python 开始并对其进行翻译。我将添加一些评论:
my \s="112213" .comb; # .comb to simulate Python string[n] indexing.
my \k=2;
my $result=0; # result is mutated so give it a sigil
for ^s -> \i { # don't use $^foo vars with for loops
my $num_seen = 0;
my \window = {}
for i..s-1 -> \ind {
if s[ind] == window.keys.none { # usefully indent code!
$num_seen += 1;
window{s[ind]} = 1
} else {
window{s[ind]} += 1
}
if window{s[ind]} == k {
$num_seen -= 1;
if $num_seen == 0 {
$result +=1
}
} elsif window{s[ind]} > k {
last
}
}
}
print($result)
Run Code Online (Sandbox Code Playgroud)
显示4.
我并不是说这在 Raku 中是一个很好的解决方案。这只是一个相对机械的翻译。希望它有帮助。
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |