46 Python Problems

From http://www.ling.gu.se/~lager/python_exercises.html

Files Code and Result

poblem19.py

problem1.py

problem2.py

problem3.py

problem4.py

problem5.py

problem6.py

problem7.py

problem8.py

problem9.py

problem10.py

problem11.py

problem12.py

problem13.py

problem14.py

problem15.py

problem16.py

problem17.py

problem18.py

problem20.py

problem21.py

problem22.py

problem23.py

problem24.py

problem25.py

problem26.py

problem27.py

problem28.py

problem29.py

problem30.py

problem31.py

problem32.py

problem33.py

problem34.py

problem36.py

problem37.py

problem38.py

problem42.py

problem43.py

problem44.py

problem45.py

problem46.py

problem45.py

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)

Result

(9, ['baltoy', 'yamask', 'kangaskhan', 'nosepass', 'sableye', 'emboar', 'registeel', 'landorus', 'scolipede', 'emolga'])