-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindrome.py
46 lines (38 loc) · 1.3 KB
/
palindrome.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Palindrome
# A string is a palindrome when it is the same when read backwards.
# For example, the string "bob" is a palindrome. So is "abba".
# But the string "abcd" is not a palindrome, because "abcd" != "dcba".
# Write a function named palindrome that takes a single string as its parameter.
# Your function should return True if the string is a palindrome, and False otherwise.
def palindrome(s):
anagram_s = []
i = -1
for y in s:
anagram_s.append(s[i])
i = i - 1
if anagram_s == list(s):
return True
else:
return False
#Solutions PythonPrinciples
# iterative solution:
# keep chopping off the head and tail of the string,
# and compare the two. If they are not equal, it's
# not a palindrome. Stop when the string gets too short.
def palindrome(string):
while len(string) > 1:
head = string[0]
tail = string[-1]
string = string[1:-1]
if head != tail:
return False
return True
# # recursive solution: equivalent to the above.
# def palindrome(string):
# if len(string) < 2:
# return True
# return string[0] == string[-1] and palindrome(string[1:-1])
# # smarter solution:
# # check if reversing the string gives the same string.
# def palindrome(string):
# return string == string[::-1]