Problem Statement
Suppose you have a string \$S\$ which has length \$N\$ and is indexed from \$0\$ to \$N−1\$. String \$R\$ is the reverse of the string \$S\$. The string \$S\$ is funny if the condition \$|S_i−S_{i−1}|=|R_i−R_{i−1}|\$ is true for every \$i\$ from \$1\$ to \$N−1\$.
(Note: Given a string \$str\$, \$str_i\$ denotes the ascii value of the \$i\$th character (0-indexed) of \$str\$. \$|x|\$ denotes the absolute value of an integer \$x\$)
Example
is_funny("acxz")
returns True
is_funny("bcxz")
returns False
Solution
def is_palindrome(ary):
return ary == ary[::-1]
def create_difference_list(s):
res = []
for i in range(1, len(s)):
res.append(abs(ord(s[i]) - ord(s[i-1])))
return res
def is_happystr(s):
return is_palindrome(create_difference_list(s))
Notes
- Have used slow version of palindrome check assuming string is not going to be too long. Hope it doesn't affect performance that much.
- Approached problem via functional style, could have done all the computation in the same loop but is it a good practice?