Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
115 views

Python Question Set

The document provides tasks and instructions for a programming workshop. It includes: 1) Converting functions to use list comprehensions instead of loops and append. 2) Writing an efficient O(n log n) function to find common elements between two lists using a transform-and-conquer approach. 3) Writing an efficient O(n log n) function to find all pairs in a list that sum to a given value using a transform-and-conquer approach.

Uploaded by

Alireza Kafaei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Python Question Set

The document provides tasks and instructions for a programming workshop. It includes: 1) Converting functions to use list comprehensions instead of loops and append. 2) Writing an efficient O(n log n) function to find common elements between two lists using a transform-and-conquer approach. 3) Writing an efficient O(n log n) function to find all pairs in a list that sum to a given value using a transform-and-conquer approach.

Uploaded by

Alireza Kafaei
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

FIT1045/1053 Algorithms and Programming Fundamentals in

Python – Workshop 09.

Objectives
After this workshop, you should be able to:
ˆ Understand how to use basic list comprehensions.
ˆ Apply Transform and Conquer to solve problems.
MARKS: Marks for this workshop will be marked manually.

Task 1: List Comprehensions


Part A: Convert the Code
List comprehensions is a Pythonic concept where you are able to effectively create lists to replace sequential
statements that involves loops. They are simple one-liners that can be used to replace the filter() and map()
methods which might be hard to comprehend.

Convert each of the functions code-snippets into List Comprehensions.

Not Assessed: For each of the functions, write how map() and filter() can be used instead of list compre-
hensions to have the same functionality.
def convert_temp(temps):
"""
Input: Given a list of temperatures in fahrenheit.
Output: A list of values converted all to celsius.

>>> convert_temp([90.0, 50.9, 84.6, 100.3])


[32.22222222222222, 10.499999999999998, 29.222222222222218, 37.94444444444444]
"""
new_temps = []
for temp in temps:
new_temps.append((temp-32)/1.8)
return new_temps

def square_odds(lst):
"""
Input: A sequence of numbers.
Output: A list with all of the odd numbers squared.

>>> square_odds([1, 2, 3, 4, 5, 6, 7])


[1, 9, 25, 49]
"""
odd_lst = []
for n in range(len(lst)):
if lst[n] % 2 != 0:
odd_lst.append(n**2)
return odd_lst

1
def only_numbers(in_str):
"""
Input: A string that has letters and numbers.
Output: A list numbers with all the letters removed
and numbers converted to integers.
"""
>>> only_numbers(‘abcdef12345’)
[1, 2, 3, 4, 5]
>>> only_numbers(‘c4t,d0g,b14d,fI5h’)
[4, 0, 1, 4, 5]
numbers = []
for c in in_str:
if c.isdigit():
numbers.append(int(c))
return numbers

def fizz_buzz(num): # Optional: Not Assessed


"""
Input: An integer (num) that represents the length in list.
Output: A list that from 0 to num (inclusive) that
if the current number is divisible by 3, the element
should say "FIZZ", if divisible by 5, the number should
say BUZZ, if divisible by both 3 and 5 should say FIZZBUZZ,
if neither the element append the number.

>>> fizz_buzz(5)
[0, 1, 2, ‘FIZZ’, 4, ‘BUZZ’]
>>> fizz_buzz(15)
[0, 1, 2, ‘FIZZ’, 4, ‘BUZZ’, ‘FIZZ’, 7, 8, ‘FIZZ’, ‘BUZZ’,
11, ‘FIZZ’, 13, 14, ‘FIZZBUZZ’]
"""
ret_lst = []
for i in range(0, num+1):
str_builder = ‘’
if i % 3 == 0 and i != 0:
str_builder += ‘FIZZ’
if i % 5 == 0 and i != 0:
str_builder += ‘BUZZ’
if str_builder != ‘’
ret_lst.append(str_builder)
else:
ret_lst.append(i)
return ret_lst

2
Task 2: Transform-and-conquer
Part A: Common list elements
Write a function common(a, b) that computes the list of elements common to two input lists a and b in worst-
case time O(nlog(n)) in terms of the combined input size n = n1 + n2 where n1 = len(a) and n2 = len(b).
The detailed input/output specification is for the function is as follows.
def common(a, b):
"""
Input: two lists, ‘a’, ‘b’, each without duplicate
elements.
Output: list of all elements ‘x’ such that
‘x’ in ‘a’ and ‘x’ in ‘b’.
>>> common([5, 46, -25, 3], [2, -1, 10])
[]
>>> c = common([8, 5, 27, -2, 10], [-3, 5, -27, 10])
>>> set(c) == {5, 10}
True
"""
As a warm-up, start by writing a simple brute force implementation in a function ‘common bf(a, b)’ and
analyse its worst-case time complexity.

Now use the transform-and-conquer paradigm to develop the more efficient O(nlogn) implementation.

Hint: Given a suitable transformation, could you solve the problem by adapting the linear-time merge algorithm
that we introduced as part of mergesort?

Task 3: Transform-and-conquer
Part A: Pairs of sum
Write a function pairs of sum(lst, s) that find all pairs of integers in an input list that sum to a specific
value and that has a worst-case time complexity of O(nlogn) where n is the size of the input list.

The detailed input/output specification of the function is as follows.


def pairs_of_sum(lst, s):
"""
Input: list of unique integers (lst),
integer (s)
Output: list containing all pairs (x, y) of elements
of lst such that x < y and x + y = s

>>> pairs_of_sum([7, 1, 25, 10], 5)


[]
>>> pairs_of_sum([7, 1, 25, 10], 32)
[(7, 25)]
>>> pairs = pairs_of_sum([-2, 4, 0, 11, 7, 13], 11)
>>> set(pairs) == {(0, 11), (4, 7), (-2, 13)}
True
"""
Hints: Can you transform the problem to a simpler version where you always have s=0?
How can you solve this simpler problem efficiently? Can you transform it to an instance of the above problem
of finding common elements of two lists? How can you transform a solution to the simpler problem back to a
solution to the original problem?

Check the time complexity of all the transformations involved to make sure that your algorithm satisfies the
overall time complexity requirement.

You might also like