Some string manipulation functions…and some miscellaneous ones…

A function to return the word representation of an integer input:

def word(n):
"""
pre: n +ve integer
pre: n <= 1000
returns: n in words (English)
"""
wdList = ["one", "two", "three", "four", "five", "six", "seven", "eight", \
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", \
"sixteen", "seventeen", "eighteen", "nineteen", "twenty"]
wdListTens = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", \
"seventy", "eighty", "ninety"]
if n <= 20:
wd = wdList[n - 1]
elif n < 100:
wdTens = wdListTens[n/10 -1]
remTen = n % 10
if remTen != 0:
wdOnes = wdList[n % 10 -1]
else:
wdOnes = ''
wd = wdTens + wdOnes
elif n < 1000:
wdHundreds = wdList[n/100 - 1] + 'hundred'
rem = n % 100
if rem == 0:
wd = wdHundreds
else:
wd = wdHundreds + 'and' + word(rem)
elif n == 1000:
wd = "onethousand"
return wd[/sourcecode]
A palindrome test:
[sourcecode language='python']def is_palindrome(string):
"""
pre: string any valid string
returns: true if string a palindrome, false otherwise
"""
x = len(string)
for i in range(x/2):
if string[i] != string[x - (i + 1)]:
return False
return True[/sourcecode]
Permutations of a word:
[sourcecode language='python']def permutations(word):
"""
pre: word a string, len(word)>=1
returns: a list of all permutations of the word
"""
if len(word)==1:
return [word]
else:
result=[]
for i in range(len(word)):
rem = word[:i] + word[i+1:]
for bit in permutations(rem):
result.append(word[i:i+1] + bit)
return result

Converts an integer to a binary string representation:

def binary(n):
"""
pre: n +ve integer
returns: binary str repr of n
"""
result = ''
while (n > 0):
result = str(n % 2) + result
n = n/2
return result

### Like this:

Like Loading...

Your is_palindrome is a good one to prove you understand the concept of how to figure out if a string is a palindrome. However, you can make it a bit smaller.

def is_palindrome(string):

if string == string[::-1]:

return True

return False

Sorry for the formatting. Not sure how to do a code wrapper on your website. ðŸ˜¦