フィルターのクリア

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

8 ビュー (過去 30 日間)
Luqas Lundahl
Luqas Lundahl 2022 年 4 月 13 日
コメント済み: Luqas Lundahl 2022 年 4 月 13 日
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?

採用された回答

David Hill
David Hill 2022 年 4 月 13 日
x='racecar';
isequal(x,flip(x));
  3 件のコメント
David Hill
David Hill 2022 年 4 月 13 日
編集済み: David Hill 2022 年 4 月 13 日
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 2022 年 4 月 13 日
thank you!

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2022 年 4 月 13 日
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', ''}

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by