Palindrome¶
A “palindrome” is a word that is the same forwards as it is backwards. For example, “kayak” spelled backwards is “kayak”. In this simple version of a palindrome check, we’re going to do two things:
Make a reversed version of the word
Compare the reversed word with the original word
And that’s it. Some things you should know beforehand:
“string” is the variable type that stores words
A “function” takes in a variable and gives some value back (the return value)
This function should take in a word (a “string” variable)
This function should return “true” or “false” (a “boolean” variable)
The result should depend on whether or not the word is a palindrome
These examples should return “true” and then “false” with the example words
#include <iostream>
#include <string>
using namespace std;
bool palindrome(string word){
string reversed = word;
reverse(reversed.begin(), reversed.end());
return (word == reversed);
}
int main(){
cout << boolalpha;
cout << palindrome("kayak") << endl;
cout << palindrome("notpalindrome") << endl;
return 0;
}
using System;
class Program{
static bool palindrome(string word){
char[] arr = word.ToCharArray();
Array.Reverse(arr);
string reversed = new string(arr);
return (word == reversed);
}
static void Main(string[] args){
System.Console.WriteLine(palindrome("kayak"));
System.Console.WriteLine(palindrome("notpalindrome"));
}
}
public class palindromeBeginner {
public static boolean palindrome(String word){
String reversed = new StringBuilder(word).reverse().toString();
return(word.equals(reversed));
}
public static void main(String[] args) {
System.out.println(palindrome("kayak"));
System.out.println(palindrome("notpalindrome"));
}
}
function palindrome(word){
var reversed = word.split("").reverse().join("");
return (word === reversed);
}
console.log(palindrome("kayak"));
console.log(palindrome("notpalindrome"));
def palindrome(word):
reversed = word[::-1]
return word == reversed
print(palindrome("kayak"))
print(palindrome("notpalindrome"))
func palindrome(_ word: String) -> Bool{
let reversed = String(word.reversed())
return word == reversed
}
print(palindrome("kayak"))
print(palindrome("notpalindrome"))
Notes¶
In C++, the syntax to make a function is:
returnType functionName(parameterType parameterName){//codereturn someReturnTypeObject;}The parameter parts of this is what is used to refer to the given word.
The other terms should explain themselves.
C++ has a handy reverse function that reverses a set of data. To use it with
a string, the syntax is reverse(string.begin(), string.end());.
Checking whether the words are equivelant with == works in C++, and returns
a “boolean”, either true or false.
The boolalpha passed to cout makes boolean outputs true
or false instead of 1 or 0.
To use the “Array” class to use the reverse function, the import statement
using System; should be used.
To reverse the string, first make a new array of characters and assign an
array of the word with the syntax word.ToCharArray(). Next, the reverse
function is used with the syntax Array.Reverse(array); where Array is
the class Array and array is your array. Then, make a new string variable
and convert the array to a string with the syntax string(array) where array
is your array.
After that, the strings can be compared with the == sign, returning true
or false.
There is one difficult line here, and that’s the one reversing the string. The
string class in java doesn’t have many useful functions, so sometimes the
StringBuilder class is used instead. So to break this line down:
String reversed = new StringBuilder(word).reverse().toString();
The reversed variable, a string, should be assigned a string. We make a new
StringBuilder variable because it has a reverse function, and it can take the
input string. The initialization is with StringBuilder(word). Then, .reverse()
reverses this StringBuilder word. Then, .toString() turns it back to a string,
and it is then assigned to the variable.
Once we have the reversed word, the == operator doesn’t work in Java for
comparing values because string types are handled differently (are “immutable”),
so the syntax string1.equals(string2) is used instead for strings.
There is one hard line here, the var reversed = word.split("").reverse().join("");
line. This line reverses the string, and it works like this:
Make the string an array of characters with
.split("")Reverse this array of characters with
.reverse()Make the array a string again with
.join("")
This is done because the string class does not have a reverse function, unlike the “Array” class.
Note
A note on comparison: === and !== should always be used instead of
== and != because they check for values and types. The second set
tries to convert types if they are not the same, and this is inconsistent
at best and can cause unpredictable behavior.
The syntax for a python function is:
def functionName(parameters)://codereturn stuffNotice the indent after the def line. Python is reliant on that to know
when the definition of the function stops.
So there’s a “reverse the string” line and a “compare strings” line. The second
line explains itself; compare the strings with ==. But the first line shows
one of Python’s quirks. The syntax [::-1] is part of Python’s “slice” syntax
that can manipulate an array. The syntax for this is:
array[start : stop : step]
array is your array. start is where the function should start from in the array,
and stop is where it should stop. step is the one we care about here - this tells
the function which items we want in the resulting array. If the value is 1, it returns
the original array. If the value is 2, it returns the array with every other object.
If the value is -1, however, it returns the reverse of the array, and that is what we
want. This works for things other than strings as well.
Lastly, we can leave start and stop blank to go over the entire array, and so we
have [::-1].
With swift, a function has the syntax:
func functionName(_ parameterName: parameterType) -> returnType{//codereturn someReturnTypeObject}The underscore (“_”) is so we don’t have to type function(parameter: var) when calling it,
just function(var).
Using let instead of var when making a variable is more efficient, but it means the
variable is always constant. Since we don’t need to change the reversed word later, let
is used.
The syntax to reverse a string is string.reverse(), but this returns a collection type,
so to convert back to a string the syntax String(collection) is used, resulting in
String(word.reversed()) when assigning to the variable.
== compares strings correctly in Swift, so that value is returned as a bool, a
true or false value.
For harder practice, try treating the strings as Arrays and reversing those with a loop instead of using a built-in function.
Also see the advanced version that ignores punctuation: Palindrome (No Punctuation).