Effacer les filtres
Effacer les filtres

How to create a function that checks if a word is a palindrome?

3 vues (au cours des 30 derniers jours)
Luqas Lundahl
Luqas Lundahl le 13 Avr 2022
Commenté : Luqas Lundahl le 13 Avr 2022
Hello!
I want to create a function that checks if a word is a palindrome (a word that is the same when its read left to right as it is right to left)
function P=palindrome(V)
P=palindrome(V(2:end-1));
if V(1)==V(end)
P=palindrome(V(2:end));
P=true;
elseif numel(V)==1
P=false;
end
end
I keep getting errors that i dont have enough input arguments. Any fixes?

Réponse acceptée

David Hill
David Hill le 13 Avr 2022
x='racecar';
isequal(x,flip(x));
  3 commentaires
David Hill
David Hill le 13 Avr 2022
Modifié(e) : David Hill le 13 Avr 2022
function P=palindrome(V)
if numel(V)==1||isempty(V)
P=1;
elseif V(1)==V(end)
P=palindrome(V(2:end-1));
else
P=0;
end
Luqas Lundahl
Luqas Lundahl le 13 Avr 2022
thank you!

Connectez-vous pour commenter.

Plus de réponses (1)

Steven Lord
Steven Lord le 13 Avr 2022
A recursive approach, like you've tried to implement, can work but one important aspect of recursion is the base case. This is the case for which you don't recursively call the function. Let's look at your function and think about how it works.
function P=palindrome(V)
P=palindrome(V(2:end-1));
So you (the user) calls the palindrome function.
The palindrome function extracts the part of the input without the first and last element then palindrome (the function) calls palindrome.
The palindrome function extracts the part of the input without the first and last element then palindrome (the function) calls palindrome.
The palindrome function extracts the part of the input without the first and last element then palindrome (the function) calls palindrome.
...
What's your base case? When does this chain of palindrome calling palindrome stop?
I suggest you take a few examples and work through them manually with pencil and paper. Write out the steps you perform to and what tests or decisions you make during the process of identifying whether or not these words or phrases are palindromes. From that see if you can identify a base case that you can detect to break out of the calling chain.
candidates = {'racecar', 'racebar', 'abba', 'palindrome', 'q', ''}

Catégories

En savoir plus sur Image Processing Toolbox dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by