Assertion Failing, even if the output value (or string, in this case) and the assertion is exactly same

4 次查看(过去 30 天)
Hello Community,
The execution of my code, is showing "Error using assert, Assertion failed". Even though the output value and the compared value are exactly the same.
This is what i am trying to display:
res = sprintf("%s won by %g runs",a(1),(c_1-d_1))
and %s and % g are giving me the same values i.e. India and 31 in this case.
this is the assertion command:
assert( isequal(res,"India won by 31 runs") )
  2 个评论
Dyuman Joshi
Dyuman Joshi 2023-8-18
I believe you are trying to solve Cody Problem #56538. The assertion seems to be working here.
res = sprintf("%s won by %g runs","India",250+307-235-291)
res = "India won by 31 runs"
assert( isequal(res,"India won by 31 runs") )
Can you attach your code? or a sample of it? So I can reproduce the error and see what's wrong.
Shubham Shubham
Shubham Shubham 2023-8-18
Yes it is infact the Cody Problem #56538.
function res = reportresult(s1,s2)
pat = digitsPattern;
a = split(s1,pat);
b = split(s2,pat);
c = double(extract(s1,pat))
d = double(extract(s2,pat))
wickets_1 = extractAfter(s1,'/');
wickets_1 = double(extract(wickets_1,pat));
wickets_2 = extractBetween(s2,'/','d');
c_1 = sum(c) - sum(double(wickets_1));
d_1 = sum(d)-sum(double(wickets_2));
if c_1 > d_1
res = sprintf("%s won by %g runs",a(1),c_1-d_1)
end
I have tailored this code just for the case below:
s1 = "India 250 & 307";
s2 = "Australia 235 & 291"
res = reportresult(s1,s2);
assert(isequal(res,"India won by 31 runs"))

请先登录,再进行评论。

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-8-18
The problem is there is an extra space after India, thus the strings are not equal and the assertion fails -
s1 = "India 250 & 307";
s2 = "Australia 235 & 291";
pat = digitsPattern;
%Extra space
a = split(s1,pat)
a = 3×1 string array
"India " " & " ""
b = split(s2,pat);
c = double(extract(s1,pat));
d = double(extract(s2,pat));
wickets_1 = extractAfter(s1,'/');
wickets_1 = double(extract(wickets_1,pat));
wickets_2 = extractBetween(s2,'/','d');
c_1 = sum(c) - sum(double(wickets_1));
d_1 = sum(d)-sum(double(wickets_2));
%Extra space
if c_1 > d_1
res = sprintf("%s won by %g runs",a(1),c_1-d_1)
end
res = "India won by 31 runs"
You can use deblank to remove trailling whitespace characters from the string -
a = deblank(a)
a = 3×1 string array
"India" " &" ""
if c_1 > d_1
res = sprintf("%s won by %g runs",a(1),c_1-d_1)
end
res = "India won by 31 runs"

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by