Borrar filtros
Borrar filtros

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

8 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

David Hill
David Hill el 13 de Abr. de 2022
x='racecar';
isequal(x,flip(x));
  3 comentarios
David Hill
David Hill el 13 de Abr. de 2022
Editada: David Hill el 13 de Abr. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Steven Lord
Steven Lord el 13 de Abr. de 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', ''}

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by