Effacer les filtres
Effacer les filtres

write a function called palindrome that takes one input argument a char vector and recursively determine whether that argument is a palindrome you are not allowed to use loops not built in function like srtcmp etc. the function returns true or false

10 vues (au cours des 30 derniers jours)
function ok=palindrome(txt)
iflength(txt)<=1
ok=true;
else
ok=(txt(1)==txt(end)&&palindrome(txt(2:end-1)));
end
end
hi,
It shows error in else statment in the above program, kindly give me a solution to solve the above problem.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 21 Oct 2020
Modifié(e) : Ameer Hamza le 21 Oct 2020
There should be a space between if keyword and the condition
if length(txt)<=1
%^ insert a space here
Apart from that, the logic is correct, but you just have a misplaced bracket. Following is correct
ok=(txt(1)==txt(end))&&palindrome(txt(2:end-1));

Plus de réponses (3)

Sandeep Kumar Patel
Sandeep Kumar Patel le 13 Avr 2022
Modifié(e) : DGM le 10 Jan 2024
If we apply the edits recommended by @Ameer Hamza, we get this:
function ok=palindrome(txt)
if length(txt)<=1 % added space
ok = true;
else
ok = (txt(1)==txt(end)) && palindrome(txt(2:end-1));
% close parentheses --^
end
end
  1 commentaire
DGM
DGM le 10 Jan 2024
Editor's note: I added the comments here so that readers know the two lone characters that were actually changed.

Connectez-vous pour commenter.


Black Woods
Black Woods le 12 Déc 2022
function ans=palindrome(v)
if v(1)==v(end)
ans=true;
if length(v)==1 || length(v)==2
return
else
palindrome(v(2:length(v)-1));
end
else
ans=false;
end
end

Tarun Sangwan
Tarun Sangwan le 27 Mar 2024
function p = palindrome(n)
if length(n)/2<1
p = 2
else
p = n(1) == n(end)
p = [p palindrome(n(2:end-1))]
end
p = ~ismember(0,p)

Catégories

En savoir plus sur Simulink Environment Customization dans Help Center et File Exchange

Produits


Version

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by