这里是围棋测试等价,但测试失败
package wc
import (
"regexp"
"strings"
)
type Histogram map[string]int
func WordCount(input string) Histogram {
histogram := make(map[string]int)
re := regexp.MustCompile("[^a-zA-Z0-9 ]*")
input = re.ReplaceAllString(input, "")
for _, word := range strings.Split(input, " ") {
if word == "" {
continue
}
histogram[strings.ToLower(word)]++
}
return histogram
}
此代码通过或失败测试非确定性一个字计数功能。有时由于未匹配预期地图和实际地图而失败。但是,两者的内容完全相同。我认为地图比较存在一些问题。我不知道我该如何修复它。请有人帮助我!
下面是测试套件代码
package wc
import (
"fmt"
"testing"
)
var testCases = []struct {
description string
input string
output Histogram
}{
{
description: "a single word",
input: "word",
output: Histogram{"word": 1},
},
{
description: "one of each",
input: "one of each",
output: Histogram{"one": 1, "of": 1, "each": 1},
},
{
description: "multiple occurrences",
input: "one fish two fish red fish blue fish",
output: Histogram{"one": 1, "fish": 4, "two": 1, "red": 1, "blue": 1},
},
{
description: "ignore punctuation",
input: "car : carpet as java : javascript!!&@$%^&",
output: Histogram{"car": 1, "carpet": 1, "as": 1, "java": 1, "javascript": 1},
},
{
description: "including numbers",
input: "testing, 1, 2 testing",
output: Histogram{"testing": 2, "1": 1, "2": 1},
},
{
description: "normalises case",
input: "go Go GO",
output: Histogram{"go": 3},
},
}
func TestWordCount(t *testing.T) {
for _, tt := range testCases {
expected := fmt.Sprintf("%v", tt.output)
actual := fmt.Sprintf("%v", WordCount(tt.input))
if expected != actual {
t.Fatalf("%s\n\tExpected: %v\n\tGot: %v", tt.description, expected, actual)
} else {
t.Logf("PASS: %s - WordCount(%s)", tt.description, tt.input)
}
}
}
下面是失败情况的例子:
1.
Expected: map[two:1 red:1 blue:1 one:1 fish:4]
Got: map[one:1 fish:4 two:1 red:1 blue:1]
2.
Expected: map[one:1 fish:4 two:1 red:1 blue:1]
Got: map[red:1 blue:1 one:1 fish:4 two:1]
3.
Expected: map[java:1 javascript:1 car:1 carpet:1 as:1]
Got: map[javascript:1 car:1 carpet:1 as:1 java:1]
...
其他信息在这里:
http://exercism.io/submissions/cf94f4732fd97335be2e755f
我试过这个,但它不起作用(我得到了与上面相同的结果)。我不知道为什么。 –
我知道如何以手动方式解决此问题。不过,我想讨论一下这个问题。为什么'!reflect.DeepEqual'方法不适用于这个问题? –
@ChangHunLee糟糕,我不好,你必须比较映射'!reflect.DeepEqual(tt.output,WordCount(tt.input))'而不是'expected'和'actual'(它们是字符串)。 –