Filter löschen
Filter löschen

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

8 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

David Hill
David Hill am 13 Apr. 2022
x='racecar';
isequal(x,flip(x));
  3 Kommentare
David Hill
David Hill am 13 Apr. 2022
Bearbeitet: David Hill am 13 Apr. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Steven Lord
Steven Lord am 13 Apr. 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', ''}

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by