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 2 3 4 5 6 7 8 9 10 11 12 13 14 | # Ex 1.1: Is it a tuple or a list?
# 1.
('Claus', 51, 0, 'clbo@kea.dk', '31011970-1313')
#2
['Bmw', 'Toyota', 'Hyundai', 'Skoda', 'Fiat', 'Volvo']
#3
['Claus', 'Henning', 'Torben', 'Carl', 'Tine']
#4
[‘Hello’, ‘World’, ‘Huston’, ‘we’, ‘are’, ‘here’]
#5
('Rolling Stones', 'Goats Head Soup', '31 August 1973', '46:56')
#6
[(40.730610, -73.935242, 'New York City', 'NY', 'USA'), (31.739847, 65.755920, 'Kandahar', 'Kandahar Province', 'Afghanistan')]
|
Ex 2: Sort a Text
1 2 3 4 5 6 7 | def sort_cons(s):
for i in ['a', 'e', 'i', 'o', 'u', 'y', ' ']:
s = s.lower().replace(i,'')
return sorted(s)
print(sort_cons('Hello world'))
|
Ex 3: Sort a list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # sort a list
# Create a list of strings with names in it. (l = [‘Claus’, ‘Ib’, ‘Per’])
names = [‘Claus’, ‘Ib’, ‘Per’]
# Sort this list by using the sorted() build in function.
sorted_names = sorted(names)
# Sort the list in reversed order.
sorted_names_reversed = sorted(names, reverse=True)
# Sort the list on the lenght of the name.
length = sorted(names, key=len)
# Sort the list based on the last letter in the name.
def last(s):
return s[-1]
sorted(names, key=last)
# Sort the list with the names where the letter ‘a’ is in the name first.
def a_in(s):
if 'a' in s.lower():
return True
return False
sorted(names, key=a_in)
|
Ex 4: Text editor plugin simulation
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Ex 4: Text editor plugin simulation
s = 'This is just a sample text that could have been a million times longer.\n\nYours Johnny'
s = s.replace('\n\n', '') # we do not coult line breaks in these exercises, so therefor they are removed
# Count the number of characters including blank spaces
len(s)
# Count the number of characters excluding blank spaces
# Count the number of words.
|
Ex 4: Files
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # Create a file and call it lyrics.txt (it does not need to have any content)
open('lyrics.txt', 'w')
# Create a new file and call it songs.docx and in this file write 3 lines of text to it.
f = open('songs.docx' 'w')
f.writeline('Hello')
f.writeline('World')
f.writeline('And you')
#open and read the content and write it to your terminal window.
* you should use both the read(), readline(), and readlines() methods for this. (so 3 times the same output).
f = open('songs.docx', 'r')
print(f.read())
f = open('songs.docx', 'r')
line = f.readline()
while line:
print(line)
line = f.readline()
f = open('songs.docx', 'r')
for i in f.readlines():
print(i)
|
Ex 5: Sort a list of tuples
1 2 3 4 5 6 7 8 9 10 | # 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)]
lt = [(1,2),(2,2),(3,2),(2,1),(2,2),(1,5), (10,4), (10, 1), (3,1)]
# 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)]
def last_then_first(x):
return (x[1], x[0])
sorted(lt, key=last_then_first)
|
List & Tuples exercises
List1.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | # Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Basic list exercises
# Fill in the code for the functions below. main() is already set up
# to call the functions with a few different inputs,
# printing 'OK' when each function is correct.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# It's ok if you do not complete all the functions, and there
# are some additional functions to try in list2.py.
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
count = 0
for w in words:
if len(w) > 1 and w[0] == w[-1]:
count += 1
return count
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
x = []
y = []
for w in words:
if w[0] == 'x':
x.append(w)
else:
y.append(w)
return sorted(x) + sorted(y)
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
def last_element(t):
return t[-1]
return sorted(tuples, key=last_element)
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print (f'{prefix} got: {got} expected: {expected}')
# Calls the above functions with interesting inputs.
def main():
print ('match_ends')
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
print()
print ('front_x')
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])
print()
print ('sort_last')
test(sort_last([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(sort_last([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
main()
|
List2.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Additional basic list exercises
# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.
def remove_adjacent(nums):
"""
# solution 1
result = []
for n in nums:
if n not in result:
result.append(n)
return result
"""
# solution 2 (set)
num_set = set(nums)
return list(num_set)
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ideally, the solution should work in "linear" time, making a single
# pass of both lists.
def linear_merge(list1, list2):
# +++your code here+++
while len(list1) != 0 and len(list2) != 0:
return
# Note: the solution above is kind of cute, but unforunately list.pop(0)
# is not constant time with the standard python list implementation, so
# the above is not strictly linear time.
# An alternate approach uses pop(-1) to remove the endmost elements
# from each list, building a solution list which is backwards.
# Then use reversed() to put the result back in the correct order. That
# solution works in linear time, but is more ugly.
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print (f'{prefix} got: {got} expected: {expected}')
# Calls the above functions with interesting inputs.
def main():
print()
print('remove_adjacent')
test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3])
test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3])
test(remove_adjacent([]), [])
print()
print('linear_merge')
test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']),
['aa', 'bb', 'cc', 'xx', 'zz'])
test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']),
['aa', 'bb', 'cc', 'xx', 'zz'])
test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']),
['aa', 'aa', 'aa', 'bb', 'bb'])
main()
|