-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindrome.py
More file actions
77 lines (55 loc) · 1.37 KB
/
palindrome.py
File metadata and controls
77 lines (55 loc) · 1.37 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def is_palindrome_v1(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v1('noon')
True
>>> is_palindrome_v1('racecar')
True
>>> is_palindrome_v1('dented')
False
"""
return reverse(s) == s
def reverse(s):
""" (str) -> str
Return a reversed version of s.
>>> reverse('hello')
"olleh'
>>> reverse('a')
'a'
"""
rev = ''
# For each character in s, add that char to the beginning of rev
for ch in s:
rev = ch + rev
return rev
def is_palindrome_v2(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v2('noon')
True
>>> is_palindrome_v2('racecar')
True
>>> is_palindrome_v2('dented')
False
"""
#The number of chars in s.
n = len(s)
# Compare the first half of s to the reverse of the second half.
# Omit the middle character of an odd length string.
return s[:n // 2] == reverse(s[n - n // 2:])
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v3('noon')
True
>>> is_palindrome_v3('racecar')
True
>>> is_palindrome_v3('dented')
False
"""
i = 0
j = len(s) - 1
while i < j and s[i] == s[j]:
i = i + 1
j = j - 1
return j <= i