Solutions for list and file exercises

Ex 1: Build in functions on lists

No solution for this exercise - Just try it out.

Ex 1.1: Is it a tuple or a list?

 1# Ex 1.1: Is it a tuple or a list? 
 2
 3# 1.
 4('Claus', 51, 0, 'clbo@kea.dk', '31011970-1313')
 5#2
 6['Bmw', 'Toyota', 'Hyundai', 'Skoda', 'Fiat', 'Volvo']
 7#3 
 8['Claus', 'Henning', 'Torben', 'Carl', 'Tine']
 9#4
10[‘Hello’, ‘World’, ‘Huston’, ‘we’, ‘are’, ‘here’]
11#5
12('Rolling Stones', 'Goats Head Soup', '31 August 1973', '46:56')
13#6
14[(40.730610, -73.935242, 'New York City', 'NY', 'USA'), (31.739847, 65.755920, 'Kandahar', 'Kandahar Province', 'Afghanistan')]

Ex 2: Sort a Text

1def sort_cons(s):
2    for i in ['a', 'e', 'i', 'o', 'u', 'y', ' ']:
3        s = s.lower().replace(i,'')
4    
5    return sorted(s)
6
7print(sort_cons('Hello world'))

Ex 3: Sort a list

 1# sort a list
 2
 3# Create a list of strings with names in it. (l = [‘Claus’, ‘Ib’, ‘Per’])
 4 names = [‘Claus’, ‘Ib’, ‘Per’]
 5
 6# Sort this list by using the sorted() build in function.
 7sorted_names = sorted(names)
 8
 9#  Sort the list in reversed order.
10sorted_names_reversed = sorted(names, reverse=True)
11
12# Sort the list on the lenght of the name.
13length = sorted(names, key=len)
14
15# Sort the list based on the last letter in the name.
16def last(s):
17    return s[-1]
18
19sorted(names, key=last)
20
21#  Sort the list with the names where the letter ‘a’ is in the name first.
22def a_in(s):
23    if 'a' in s.lower():
24        return True
25    return False
26
27sorted(names, key=a_in)

Ex 4: Text editor plugin simulation

 1
 2# Ex 4: Text editor plugin simulation
 3
 4s = 'This is just a sample text that could have been a million times longer.\n\nYours Johnny'
 5
 6s = s.replace('\n\n', '') # we do not coult line breaks in these exercises, so therefor they are removed
 7# Count the number of characters including blank spaces
 8len(s)
 9# Count the number of characters excluding blank spaces
10
11# Count the number of words.
12
13

Ex 4: Files

 1# Create a file and call it lyrics.txt (it does not need to have any content)
 2
 3open('lyrics.txt', 'w')
 4
 5# Create a new file and call it songs.docx and in this file write 3 lines of text to it.
 6
 7f = open('songs.docx' 'w')
 8f.writeline('Hello')
 9f.writeline('World')
10f.writeline('And you')
11
12#open and read the content and write it to your terminal window. 
13* you should use both the read(), readline(), and readlines() methods for this. (so 3 times the same output).
14
15f = open('songs.docx', 'r')
16print(f.read())
17
18f = open('songs.docx', 'r')
19line = f.readline()
20while line:
21    print(line)
22    line = f.readline()
23
24
25f = open('songs.docx', 'r')
26for i in f.readlines():
27    print(i)

Ex 5: Sort a list of tuples

 1# 1. Based on this list of tuples: [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3, 1)]
 2
 3lt = [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3,1)]
 4
 5# 2. Sort the list so the result looks like this: [(2, 1), (3, 1), (10, 1), (1, 2), (2, 2), (2, 2), (3, 2), (10, 4), (1, 5)] 
 6
 7def last_then_first(x):
 8    return (x[1], x[0])
 9
10sorted(lt, key=last_then_first)

List & Tuples exercises

List1.py

  1# Copyright 2010 Google Inc.
  2# Licensed under the Apache License, Version 2.0
  3# http://www.apache.org/licenses/LICENSE-2.0
  4
  5# Basic list exercises
  6# Fill in the code for the functions below. main() is already set up
  7# to call the functions with a few different inputs,
  8# printing 'OK' when each function is correct.
  9# The starter code for each function includes a 'return'
 10# which is just a placeholder for your code.
 11# It's ok if you do not complete all the functions, and there
 12# are some additional functions to try in list2.py.
 13
 14# A. match_ends
 15# Given a list of strings, return the count of the number of
 16# strings where the string length is 2 or more and the first
 17# and last chars of the string are the same.
 18# Note: python does not have a ++ operator, but += works.
 19def match_ends(words):
 20    count = 0
 21    for w in words:
 22        if len(w) > 1 and w[0] == w[-1]:
 23            count += 1
 24    return count
 25
 26
 27# B. front_x
 28# Given a list of strings, return a list with the strings
 29# in sorted order, except group all the strings that begin with 'x' first.
 30# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
 31# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
 32# Hint: this can be done by making 2 lists and sorting each of them
 33# before combining them.
 34def front_x(words):
 35    x = []
 36    y = []
 37    for w in words:
 38        if w[0] == 'x':
 39            x.append(w)
 40        else:
 41            y.append(w)
 42    return sorted(x) + sorted(y)
 43
 44
 45
 46# C. sort_last
 47# Given a list of non-empty tuples, return a list sorted in increasing
 48# order by the last element in each tuple.
 49# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
 50# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
 51# Hint: use a custom key= function to extract the last element form each tuple.
 52
 53
 54
 55def sort_last(tuples):
 56    def last_element(t):
 57        return t[-1]
 58
 59    return sorted(tuples, key=last_element)
 60
 61
 62
 63# Simple provided test() function used in main() to print
 64# what each function returns vs. what it's supposed to return.
 65def test(got, expected):
 66  if got == expected:
 67    prefix = ' OK '
 68  else:
 69    prefix = '  X '
 70  print (f'{prefix} got: {got} expected: {expected}')
 71
 72
 73# Calls the above functions with interesting inputs.
 74def main():
 75  print ('match_ends')
 76  test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
 77  test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
 78  test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
 79
 80  print()
 81  print ('front_x')
 82  test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
 83       ['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
 84  test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
 85       ['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
 86  test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
 87       ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])
 88
 89       
 90  print()
 91  print ('sort_last')
 92  test(sort_last([(1, 3), (3, 2), (2, 1)]),
 93       [(2, 1), (3, 2), (1, 3)])
 94  test(sort_last([(2, 3), (1, 2), (3, 1)]),
 95       [(3, 1), (1, 2), (2, 3)])
 96  test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
 97       [(2, 2), (1, 3), (3, 4, 5), (1, 7)])
 98
 99
100main()

List2.py

 1
 2# Copyright 2010 Google Inc.
 3# Licensed under the Apache License, Version 2.0
 4# http://www.apache.org/licenses/LICENSE-2.0
 5
 6# Additional basic list exercises
 7
 8# D. Given a list of numbers, return a list where
 9# all adjacent == elements have been reduced to a single element,
10# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
11# modify the passed in list.
12
13
14def remove_adjacent(nums):
15    
16    """
17    # solution 1
18    result = []
19    for n in nums:
20        if n not in result:
21            result.append(n)
22    return result
23    """
24    
25    # solution 2 (set)
26    num_set = set(nums)
27    return list(num_set)
28
29# E. Given two lists sorted in increasing order, create and return a merged
30# list of all the elements in sorted order. You may modify the passed in lists.
31# Ideally, the solution should work in "linear" time, making a single
32# pass of both lists.
33def linear_merge(list1, list2):
34    # +++your code here+++
35    while len(list1) != 0 and len(list2) != 0:
36
37   return
38
39# Note: the solution above is kind of cute, but unforunately list.pop(0)
40# is not constant time with the standard python list implementation, so
41# the above is not strictly linear time.
42# An alternate approach uses pop(-1) to remove the endmost elements
43# from each list, building a solution list which is backwards.
44# Then use reversed() to put the result back in the correct order. That
45# solution works in linear time, but is more ugly.
46
47
48# Simple provided test() function used in main() to print
49# what each function returns vs. what it's supposed to return.
50def test(got, expected):
51    if got == expected:
52        prefix = ' OK '
53    else:
54        prefix = '  X '
55    print (f'{prefix} got: {got} expected: {expected}')
56
57
58# Calls the above functions with interesting inputs.
59def main():
60    print()
61    print('remove_adjacent')
62    test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
63    test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
64    test(remove_adjacent([]), [])
65
66    print()
67    print('linear_merge')
68    test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']),
69         ['aa', 'bb', 'cc', 'xx', 'zz'])
70    test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
71         ['aa', 'bb', 'cc', 'xx', 'zz'])
72    test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
73         ['aa', 'aa', 'aa', 'bb', 'bb'])
74
75
76main()