# 46 python problems

My answers to: 46 problems

```    # 1.
def max(num,num2):
''' (number) -> number
return largest of two numbers
'''
largest = 0
temp = 0
if num > num2:
temp = num
else:
temp = num2
if temp > largest:
largest = temp
return  largest

ans = max(-4,7)
print(ans)

# 2.
def largest_of_three(a, b, c):
''' (number) -> number
return the largest of a, b, c
'''
largest = 0
if (a > b) and (a > c):
largest = a
elif (b > a) and (b > c):
largest = b
else:
largest = c
return largest

ans = largest_of_three(-4, 4, 7)
print(ans)

# 3
def leng(str):
'''(str) -> integer
return the length of a string
'''
count = 0
for x in str:
count += 1
return count

ans = leng('there')
print(ans)

# 4
def is_vowel(str):
'''(str) -> bool
return str True or False
'''
vowels ='aeiou'
str = str.lower()
return  str in vowels

ans = is_vowel('R')
ans2 = is_vowel('e')
print(ans, ans2)

# 5
def translate(str):
'''(str) -> str
return modified string
'''
vowels = 'aeiou '
strng = ''
for x in str:
if x not in vowels:
x = x +'o' + x
strng = strng + x
else:
strng = strng + x

return strng

ans = translate('this is fun')
print(ans)

# 6
def sum(lst):
'''(list) -> number
return a sum of a list
'''
num = 0
for x in range(0, len(lst)):
num += lst[x]
return num

def multiply(lst):
'''(list) -> number
return a sum of a list
'''
num = 1
for x in range(0, len(lst)):
num *= lst[x]
return num

lst =[1, 2, 3, 4]
ans = sum(lst)
ans2 = multiply(lst)
print(ans, ans2)

# 7
def reverse(str):
''' (str) -> str
return reversed string
'''
str2 = ''
ln = len(str)
for x in range( ln-1, -1, -1):
str2 =str2 + str[x]
return  str2

str = 'I am testing'
ans = reverse(str)
print(ans)

# 8
def is_palindrome(str):
'''(str) -> str
return bool if str is a palindrome
'''
half_str = len(str) // 2
rear_str = ''
front_str = ''

for x in range( half_str - 1, -1, -1):
rear_str += str[x]
rear_str = rear_str[::-1]
for x in range(0,half_str):
front_str += str[x]

return  rear_str == front_str

ans = reverse(str)
print(ans)

print(ans)

# 9
def is_member(lst, a):
'''(list,str) -> bool
return whether str is a member of lst
'''
x = 0
while x <= len(lst) - 1:
if lst[x] == a:
return True
x += 1
continue
return False

lst =['a', 'c', 'f', 'g']
str = 'g'
ans = is_member(lst, str)
print(ans)

# 10
def overlapping(lst,lst2):
'''(lists) -> bool
return True if they have at least
one member in common
'''
for x in range(0, len(lst)):
for y in range(0, len(lst2)):
if lst[x] == lst2[y]:
return True
return False

list_one =[1, 2, 3, 4]
list_two = [5, 6, 7, 8]

ans = overlapping(list_one, list_two)
print(ans)

# 11
def generate_n_chars(char, n):
''' (str, int) -> str
return n number of characters
'''
str = ''
for x in range(n):
str += char
return  str

ans = generate_n_chars('w', 6)
print(ans)

# 12
def histogram(a, b, c):
'''(ints) -> str
return a histogram using three inputs
'''
count = 0
strng =''
while True:
lst = [a, b, c]
for x in range(0,len(lst)):
n = lst[x]
for y in range(n):
strng += 'x'
print(strng)
strng =''
count +=1
if count == 3:
exit()

ans = histogram(2, 3, 4)
print(ans)

# 13
def in_list(the_lst):
'''(list) -> number
return the largest number in a list
'''
num = 0
for x in range(0, len(the_lst)):
if the_lst[x] > num:
num = the_lst[x]
return  num

ans = in_list([5, 8, -2, 40, 1, 38])
print(ans)

# 14
def map(lst):
'''(list) -> list
return a mapped list
'''
map_list = []
for word in lst:
leng = len(word)
map_list.append(leng)
return map_list

word_list = ['one', 'four', 'seven']
ans = map(word_list)
print(ans)

# 15
def find_longest_word(lst):
'''(list) -> int
return length of the longest
word in the list
'''
num = 0
for word in lst:
if len(word) > num:
num = len(word)
return num

lst = ['are','there', 'longer', 'alphabets', 'than', 'this']
ans = find_longest_word(lst)
print(ans)

# 16
def filter_long_words(lst, n):
'''(list) -> list
return a filtered list
'''
filtered_list = []
for word in lst:
if len(word) > n:
filtered_list.append(word)
return filtered_list

lst = ['an', 'answer', 'racket', 'a', 'modal']
ans = filter_long_words(lst, 4)
print(ans)

# 17
def is_phrase_palindrome(str):
'''(str) -> str
return true if palindrome
'''
filtered_str = ''
for letter in str:
if letter.isalpha():
filtered_str += letter
str = filtered_str.lower()

reverse_str = str[:: -1]
half_len =len(str) // 2
r_str = ''
f_str =''
for x in range(0, half_len):
r_str += reverse_str[x]
for y in range(0, half_len):
f_str += str[y]

return  r_str == f_str

is_or_not_pal = "Dammit, I'm mad"
ans = is_phrase_palindrome(is_or_not_pal)
print(ans)

# 18
def panagram(strng):
'''(str) -> bool
return whether the string is a panagram
'''
sett = set()
strng = strng.lower()
for letter in strng:
if letter.isalpha():
return len(sett) == 26

strng = 'The quick brown fox jumps over the lazy dog'
ans = panagram(strng)
print(ans)

# 19

for n in range(99, 0, -1):
print (n, 'bottles of beer on the wall,',n,'bottles of beer.\n',
'Take one down, pass it around,',n - 1, 'bottles of beer on the wall.')

# 20
def translate(lst):
'''(list) -> list
return a list of translated words
'''
dict = {'christmas': 'jul', 'day': 'dag'}

lst2 =[]
for word in lst:
lst2.append(dict[word])
return  lst2

eng_list = ['christmas', 'day']
ans = translate(eng_list)
print(ans)

# 21
def char_freq(str):
'''(str) -> dict
return a dictionary representing
frequency distribution.
'''
dict ={}
count = 0
store =''
for y in range(len(str)):
for letter in str:
if letter == str[y] and letter not in store:
count += 1
if count == 0:
continue
store += str[y]
dict[str[y]] = count
count  = 0
return dict

chars = "abbabcbdbabdbdbabababcbcbab"
ans = char_freq(chars)
print(ans)

# 22

def caeser_cipher(str):
'''(str) -> str
return encoded or decoded text
'''
key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}

coded = ''
for letter in str:
if letter.isalpha():
letter = key[letter]
coded += letter
return coded

text = "We advance at three o'clock"
ans = caeser_cipher(text)
print(ans)

# 23
def correct(str):
'''(str) -> str
return a corrected string
'''
import  re

match = re.sub(r'  ',' ',str)
match2 = re.sub(r'\.(?=[A-Z])', '. ', match)
return match2

strng = 'One fine  day we  walked to the  farm.It was  Wednesday.'
ans = correct(strng)
print(ans)

# 24
def make_3g_form(lst):
'''(list) -> list
return a modified list
'''
output = []
ies = 'ies'
es = 'es'
s ='s'
for word in lst:
if word.endswith('y'):
word = word.replace(word[-1], ies)
output.append(word)
elif word.endswith('s') or  word.endswith('o')\
or word.endswith('ch') or word.endswith('sh')\
or word.endswith('x') or word.endswith('z'):
word = word + es
output.append(word)
else:
word = word + s
output.append(word)

return  output

verb_list=['try', 'brush', 'move', 'hug', 'fizz']
ans = make_3g_form(verb_list)
print(ans)

# 25
def make_ing_form(lst):
'''(list) -> list
return a modified list
'''
output = []
ing = 'ing'
for word in lst:
if word.endswith('ie'):
word = word.replace(word[-2:], 'y') + ing
output.append(word)
elif word.endswith('e'):
word = word.replace(word[-1], ing)
output.append(word)
else:
word = word + ing
output.append(word)

return  output

verb_list=['try', 'brush', 'move', 'fizz', 'lie']
ans = make_ing_form(verb_list)
print(ans)

# 26
from functools import reduce
def reduce_func(lst):
'''(list) -> number
return the maximum number in the list
'''
f = lambda a,b: a if (a > b) else b
maximum = reduce(f, lst)
return maximum

num_list = [47,11,42,102,13]
ans = reduce_func(num_list)
print(ans)

# reduce is a function and may be called directly

f = lambda a,b: a if (a > b) else b
maximum = reduce(f, [47,11,42,102,13])
print(maximum)

# 27
target_list = ['here', 'there', 'and', 'everywhere']
def mapping(lst):
'''(list) -> list
return a list of word lengths
'''
output = []
for word in lst:
output.append(len(word))
return output

ans = mapping(target_list)
print(ans)

ans =list(map((lambda x: len(x)), target_list))
print(ans)

ans = [len(x) for x in target_list]
print(ans)

# 28
def find_longest_word(lst):
'''(list( -> str
return longest word in the list
using high order functions
'''
f = lambda a,b: a if (len(a) > len(b)) else b
max_word = reduce(f, lst)
return max_word

word_list = ['one', 'four', 'seventeen', 'twenty']
ans = find_longest_word(word_list)
print(ans)

#29
def filter_long_words(lst, n):
'''(list) -> list
return a list of words filtered
by length n
'''
f = list(filter(lambda x: len(x) >= n, word_list2))
return  f

word_list2 = ['filter', 'my', 'list', 'nevertheless']
ans = filter_long_words(word_list2, 6)
print(ans)

#30
# This took a LOT of research! so I added a bit of fluff.
def translate(lst):
'''(list) -> list
return a list of translated words.
'''
return dict[lst]

dict = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"år"}

strng = 'happy new year'
strng_2_list = list(strng.split())
ans = list(map(translate, strng_2_list))
ans = ' '.join(str(x) for x in ans)
print(ans)

# 31
# Home-made map, filter and reduce

y =[3, 4, 7]

def my_map(lst):
doubled = []
for x in lst:
x *= 3
doubled.append(x)
return doubled

ans = my_map(y)
print(ans)

def my_filter(lst):
filtered = []
for x in range(0, len(lst)):
a = lst[x]
if a < 7:
filtered.append(a)
return filtered

ans = my_filter(y)
print(ans)

def my_reduce(lst):
a = lst[0]
for x in range(1, len(lst)):
b = lst[x]
a /= b
return a

ans = my_reduce(y)
print(ans)

# 32
def is_phrase_palindrome(str):
'''(str) -> str
return true if palindrome
'''
filtered_str = ''
for letter in str:
if letter.isalpha():
filtered_str += letter
str = filtered_str.lower()

reverse_str = str[:: -1]
half_len =len(str) // 2
r_str = ''
f_str =''
for x in range(0, half_len):
r_str += reverse_str[x]
for y in range(0, half_len):
f_str += str[y]

return  r_str == f_str

def palindrome_printer():
f = open('palindrome.txt', 'r')
for line in f:
line = line.strip('\n')
if is_phrase_palindrome(line):
print(line)

ans = palindrome_printer()
print(ans)

# 33
def semordnilap():
f = open('semordnilap.txt','r')
word_store = []
sorted_in_pairs = []
for line in f:
line = line.strip().split()
for word in line:
word_store.append(word)
for x in range(0, len(word_store)):
candidate = word_store[x]
target = candidate[::-1]
if target in word_store:
sorted_in_pairs.append((target,candidate))
# remove duplicates
for x in sorted_in_pairs:
for y in sorted_in_pairs:
if x[0] == y[1]:
sorted_in_pairs.remove(x)
print(len(sorted_in_pairs))
return (sorted_in_pairs)

ans = semordnilap()
print(ans)
# 34

def char_freq_table():
'''(text file) -> histogram
generate a histogram based on a text file
'''
store = ''
dict = {}
input_text = input('Enter a text file: ')
file = open(input_text, 'r')
for line in file:
line = line.strip()
for letter in line:
if letter.isalpha():
store += letter

for letter in store:
counter = store.count(letter)
dict[letter] = counter
store.replace(letter, '')

for entry in dict:
yield(entry, 'x' * dict[entry])

for x in char_freq_table():
print(x)

# 35 Trying install pyttsx.....

# 36
'''
A hapax legomenon (often abbreviated to hapax) is a word
which occurs only onc in either the written record of
a language, the works of an author, or in a single
text. Define a function that given the file name
of a text will return all its hapaxes.
Make sure your program ignores capitalization.'''

def hapax():
'''(text file) -> histogram
generate a histogram based on a text file
'''
store = []
store2 = []
#input_text = input('Enter a text file: ')
file = open('hapax_test.txt', 'r')
for line in file:
line = line.lower()
line = line.strip().split()
for word in line:
if word.isalpha():
store.append(word)

for x in range (0, len(store)):
candidate = store[x]
if store.count(candidate) == 1:
store2.append(candidate)
return store2

ans = hapax()
print(ans)

# 37
'''Write a program that given a text file will create a new text file
in which all the lines from the original file are numbered
1 to n (where n is the number of lines in the file'''

file1 = open('words.txt')
lst = []
for line in file1:
line = line.strip('\n')
lst.append(line)

#number the list which creates a tuple
lst = list(enumerate(lst))

#clean up for presentation and write to txt file
file2 = open('numbered_lines.txt', 'w')
for tuple in lst:
tuple = str(tuple)
tuple = tuple.strip('()')
tuple = tuple.strip("'")
num = tuple.find(' ')
print(tuple,num)
first = tuple[:num + 1]
second = tuple[num + 2:]
print(first, second)
tuple = first + second
file2.write(tuple +'\n')

# 37a
'''One liner from the much smarter and more Pythonic son Richard'''

open('richwords.txt', "w").writelines([", ".join([str(x), str(y)]) for\
x, y in enumerate(open('words.txt').readlines())])

# 38
fname = 'words.txt'
fh = open(fname)
lst = []
count = 0
total = 0
for line in fh:
line = line.rstrip('\n').split()
for word in line:
lst.append(word)
count += 1
for x in range(0, len(lst)):
total += len(lst[x])

av = float(total / count)

print('Average word length: ',av)

# 39
import random

counter = 0
name = input('What is your name? ')
print('Well, ' + name + ', I am thinking of a number between 1 and 20')
num = random.randrange(0,20)
num = float(num)
while True:
name_num = input('Take a guess: ')
name_num = float(name_num)
counter += 1
if name_num == num:
print('Good job '+ name + '! You guessed my number in ' + str(counter) + ' guesses!')
break
elif name_num < num:
print('Too low, go again.')
continue
else:
print('Too high, try again')
continue

# 40
'''>>> import anagram
Colour word anagram: onwbr
Guess the colour word!
black
Guess the colour word!
brown
Correct!
'''
import random
def anagram(word):
""" Generate all of the anagrams of a word. """
if len(word) < 2:
yield word
else:
for i, letter in enumerate(word):
if not letter in word[:i]: #avoid duplicating earlier words
for j in anagram(word[:i]+word[i+1:]):
yield j+letter

if __name__ == "__main__":

word_list =['white', 'orange', 'green', 'purple', 'amber', 'apricot', 'beige', 'bronze',
'crimson', 'violet', 'indigo', 'magenta', 'maroon', 'ochre', 'lavender' ]

pick = random.randrange(0, len(word_list))
word = word_list[pick]

colour_word = anagram(word)

print(next(colour_word))
while True:
guess = input('Guess the colour word:')
if guess == word:
print('Correct!')
exit()
else:
print('Incorrect, try again :')
continue

# 41
import random
def lingo(guess):
'''(str)  -> list
return a marked list
'''
candidates = ['tiger', 'horse', 'mouse', 'skunk', 'sloth', 'stoat']
x = random.randrange(0, len(candidates))
strng = candidates[x]
#strng = 'reeta'

guess = list(guess)
for x in range(0, len(strng)):
if guess[x]in strng:
guess[x] = '(' + guess[x]+ ')'

for x in range(0, len(strng)):
if strng[x] == guess[x].strip('()'):
guess[x] = '['+ guess[x].strip('()') + ']'

tmp = (guess[0])
count = 0
for x in range(0, len(guess)):
temp = guess[x]
if not '[' in guess[x]:
break
else:
count += 1
if count == 5:
return print('Correct!!')

return  guess

while True:
global strng
guess = input('Guess: ')
# pass to function lingo for checking
ans = lingo(guess)
# out comes the answer
print('Clue: ', ans)
if ans == print('Correct!!'):
exit()

# 42

def check(line,n, title_lst):
'''(list,index,list) -> bool
checking for non-sentence-ending
characters
'''
if line[n + 2].islower() and line[n + 2].isalpha():
return False
elif line[n+1] == ' ' and line[n + 2] == line.isupper()\
and line[n + 2] == line.isalnum():
return True
elif line[n+1].isalpha() or line[n+1].isnumeric():
return False
elif line[n+1] == ' ' and (line[n-2:n] in title_lst\
or line[n-3:n] in title_lst):
return False
elif  not ' ' in line[n-1:n+2]:
return False
elif '.' in line[n+1] or ',' in line[n+1]:
return False
else:
return True

def sentence_splitter():
'''(file) -> str
open and return a split text file
'''
line2 = ''
line_starter = 0
splitter = 0
indexes = []
title_lst = ['Mr', 'Mrs', 'Dr', 'Jr']
f = open('sentence.txt','r' )
for line in f:
chk_len = len(line)
# collect indexes of '.!?'
indexes = [n for (n,e) in enumerate(line) if e == '.']
indexes2 = [n for (n,e) in enumerate(line) if e == '?']
indexes3 = [n for (n,e) in enumerate(line) if e == '!']
indexes = indexes + indexes2 + indexes3
indexes = sorted(indexes)
print(indexes)

# select indexes one by one
for x in range(0, len(indexes)):
splitter = indexes[x]
if splitter == len(line)-1:
line2 += line[line_starter + 1:splitter + 1].lstrip()
print(line2)
exit()
# Sort splitter index, return lowest index
truth = check(line,splitter,title_lst)

if truth:
if line_starter == 0:
line2 += line[line_starter:splitter + 1].strip() + '\n'
else:
line2 += line[line_starter + 1:splitter + 1].strip() + '\n'
line_starter = splitter

# end of sentence check
len_line = len(line) - 1
if splitter == len_line:
line2 += line[line_starter+1:splitter + 1].strip() + '\n'
print(line2)
exit()
else:
if line_starter == 0: # start of sentence
line2 += line[line_starter:splitter + 1].lstrip()
line_starter = splitter
else:
line2 += line[line_starter + 1:splitter + 1].lstrip()
# start of slice
line_starter = splitter

ans = sentence_splitter()
print(ans)

# 43
'''
Create a dictionary of (sorted word, list of word).
All the words that are in the same list are
anagrams of each other.
'''
from collections import defaultdict

def get_words(file):
f= open(file)
for word in f:
yield word.rstrip()

def get_anagrams(source):
d = defaultdict(list)
for word in source:
key = "".join(sorted(word))
d[key].append(word)
return d

def print_anagrams(word_source):
d = get_anagrams(word_source)
for key, anagrams in d.items():
if len(anagrams) > 1:
print(key, anagrams)

word_source = get_words('unixdict.txt')
print_anagrams(word_source)

# 44

def bracketed(num):
import random
a ='['
b = ']'
c = int(num)
lst =[]
sett = set()
# randomize the brackets
for x in range(1,c + 1):
lst.append(random.sample(sett,2))
# convert to string for display purposes.
strng = ''
for item in lst:
for items in item:
strng += items
print(strng)
# iterate in blocks to check True/False
for i in range(0, len(strng), 2):
slice = strng[i:i+2]
if slice[0] == a and slice[1] == b:
continue
else:
return  False
return  True

n = input('Enter amount of brackets: ' )
ans = bracketed(n)
print('Result: ', ans)

# 45
import random
import copy
def poke45(file):
f = open(file, 'r')
lst = []
lst2 = []
count = 1
total = 0
list_out =[]
temp = []
for line in f:         # create list of text file content
line = line.strip('\n')
line = line.split()
for word in line:
lst.append(word)
temp = copy.deepcopy(lst)

for x in range(0, len(lst)):
lst = temp
candidate = lst[x]     # select starting word
lst2.append(candidate) # place in lst2 (list)
trail = candidate[-1]  # select trailing letter
lst =lst[1:]           # list minus the selected word

while True:
if candidate == lst[-1]:
break
if lst[x].startswith(trail): # lst[x] now the second word of the original list
count += 1               # rinse and repeat......
candidate = lst[x]
lst2.append(lst[x])
trail = lst[x][-1]
del lst[x]
x = 0
else:
x += 1
if x == len(lst):
if count > total:
total = count
list_out = lst2
lst2 = []
count = 0
break

return (total, list_out )

ans = poke45('pokemon.txt')
print(ans)

#46
'''An alternade is a word in which its letters, taken alternatively in a strict sequence,
and used in the same order as the original word, make up at least two other words.
All letters must be used, but the smaller words are not necessarily of the same length. For example,
a word with seven letters where every second letter is used will produce a four-letter word and a
three-letter word. Here are two examples:

"board": makes "bad" and "or".
"waists": makes "wit" and "ass".

Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt.
write a program that goes through each word in the list and tries to make
two smaller words using every second letter. The smaller words must also be
members of the list. Print the words to the screen in the above fashion.
'''
line = open('unixdict.txt', 'r')
lst =[]
for lines in line:
lines = lines.strip('\n')
lst.append(lines)

strng2 = ''
strng3 = ''

for word in lst:
for x in range(0, len(word), 2):
strng2 += word[x]

for x in range(1, len(word), 2):
strng3 += word[x]

if strng2 in lst and strng3 in lst:
print('"{0}": makes "{1}" and "{2}"'.format(word, strng2, strng3))
print()
strng2 = ''
strng3 = ''
```