0% found this document useful (0 votes)
28 views6 pages

Qwertyu

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

Qwertyu

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

def range_of_list_abs():

Built-in Function Problem """Return the difference between the largest and
smallest absolute values in a list."""
1. Create the sequence [0, 3, 6, 9, ... N]. What is the x = [4, 3, -9, 21, 0]
problem if N is very large? # Your code here
Is there a better way if N is very large?
2. Find the difference between the biggest and def list_to_sequence_dict():
smallest values in the list """Create a dictionary where the key is the ordinal
[4, 3, -9, 21, 0] of the object in the list
3. The same as 2. but use the absolute values in the and the value is the object itself. For example: {0 :
list. 'Zero', 1 : 'One', ...}"""
4.Convert a list: x = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six',
['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
'Seven', 'Eight', 'Nine'] d = {}
To a dictionary: # Your code here
{ return d
0 : 'Zero',
1 : 'One', def is_same(a, b):
2 : 'Two', """Return True is the two items are the same."""
3 : 'Three', # Your code here
4 : 'Four', pass
5 : 'Five',
6 : 'Six', #=========== Tests ===================
7 : 'Seven', def test_create_sequence():
8 : 'Eight', assert create_sequence(12) == [0, 3, 6, 9, 12]
9 : 'Nine',
}
def test_range_of_list():
5. I have two list a and b. Is there a way that I can tell
assert range_of_list() == 30
if they are the same
list? For example in the following case they are the
def test_range_of_list_abs():
same list:
assert range_of_list_abs() == 21
a = [1, 2, 3]
b=a
def test_list_to_sequence_dict():
And any change to b be will be 'seen' by a.
expected = {
However in this case a and b are not the same list in
0 : 'Zero',
the sense that any change
1 : 'One',
to b be will NOT be 'seen' by a.
2 : 'Two',
a = [1, 2, 3]
3 : 'Three',
b = [1, 2, 3]
4 : 'Four',
5 : 'Five',
def create_sequence(N):
6 : 'Six',
"""Create the 3x table up to and including N."""
7 : 'Seven',
# Your code here
8 : 'Eight',
pass
9 : 'Nine',
}
def range_of_list():
assert list_to_sequence_dict() == expected
"""Return the difference between the largest and
smallest values in a list."""
def test_is_same():
x = [4, 3, -9, 21, 0]
a = [1, 2, 3]
# Your code here
b=a
assert is_same(a, b)
b = [1, 2, 3] def test_range_of_list():
assert not is_same(a, b) assert range_of_list() == 30

def main(): def test_range_of_list_abs():


return pytest.main(__file__) assert range_of_list_abs() == 21

if __name__ == '__main__': def test_list_to_sequence_dict():


sys.exit(main()) expected = {
0 : 'Zero',
1 : 'One',
Built-in Function Sol’n 2 : 'Two',
def create_sequence(N): 3 : 'Three',
"""Create the 3x table up to and including N.""" 4 : 'Four',
return range(0, N + 3, 3) 5 : 'Five',
6 : 'Six',
def range_of_list(): 7 : 'Seven',
"""Return the difference between the largest and 8 : 'Eight',
smallest values in a list.""" 9 : 'Nine',
x = [4, 3, -9, 21, 0] }
return max(x) - min(x) assert list_to_sequence_dict() == expected

def range_of_list_abs(): def test_is_same():


"""Return the difference between the largest and a = [1, 2, 3]
smallest absolute values in a list.""" b=a
x = [4, 3, -9, 21, 0] assert is_same(a, b)
abs_x = [abs(value) for value in x] b = [1, 2, 3]
return max(abs_x) - min(abs_x) assert not is_same(a, b)

def list_to_sequence_dict():
"""Create a dictionary where the key is the ordinal
of the object in the list
and the value is the object itself. For example: {0 :
'Zero', 1 : 'One', ...}"""
x = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine']
d = {}
for index, value in enumerate(x):
d[index] = value
return d

def is_same(a, b):


"""Return True is the two items are the same."""
# This is the same as:
# return a is b
return id(a) == id(b)

#=========== Tests ===================


def test_create_sequence():
assert create_sequence(12) == [0, 3, 6, 9, 12]
[2, 'B'],
Tuples Problem [3, 'C'],
============== ]
a='A' In the case of uneven length lists choose then
b='B' truncate to the shortest, so given:
c='C' [
x = list() [1, 2, 3],
add a, b, c into x ['A', 'B'],
print the length of x ]
selecting from lists We would expect:
==================== [
Given the list [1, 'A'],
x = ['A', 'B', 'C'] [2, 'B'],
return the first item ]
return the last item Hint: There is a builtin function that can help you.
return the x reversed using indexing peak_to_peak()
selecting first items ==============
======================= Create a function that returns the peak-to-peak
Given the following: value of the values in a list.
x = [('A','x'), ('B','y'), ('C','z')] Hint: There are a couple of builtin functions that can
return ['A','B','C'] help you.
add 5 to values Challenges: What to do when the list is empty?
================= If the list contains non-numeric values?
Given the following: list rotation
x = [1, 10, 20] =============
return a list with 5 added to the numbers i.e. [6, 15, Rotate a list by taking the value from one end a
25] putting it on the other end.
divisible by 5 Create two functions rotate_left() and rotate_right()
================== that modify a list in
Given the following: place as follows, given the list ['A', 'B', 'C']:
x = [1, 10, 15, 3, 12, 15, 25, 50] rotate_left() changes it to ['B', 'C', 'A']
return a list with only numbers divisible by 5 (% rotate_right() changes it to ['C', 'A', 'B']
modulo operator)
merge_lists More: The solution has two failing tests, fix the
=================== solution so that the tests pass.
given the lists:
x = ['A', 'B', 'C'] def create_list():
y = ['x', 'y', 'z'] """Create a list."""
create the following list: a ='A'
[('A','x'), ('B','y'), ('C','z')] b ='B'
transpose() c ='C'
=========== # Your code goes here
Create a function that takes a list of lists and returns
the transpose. So given: def select_first_item():
[ """Return first item."""
[1, 2, 3], x = ['A', 'B', 'C']
['A', 'B', 'C'], # Your code goes here
]
We would expect: def select_last_item():
[ """Return last item."""
[1, 'A'], x = ['A', 'B', 'C']
# Your code goes here
Tuples Sol’n
def select_reversed(): def create_list():
"""Return list reversed.""" """Create a list."""
x = ['A', 'B', 'C'] a ='A'
# Your code goes here b ='B'
c ='C'
def select_first_items(): x = list()
"""Select first item on each list.""" x.append(a)
x = [('A','x'), ('B','y'), ('C','z')] x.append(b)
# Your code goes here x.append(c)
return x
def add_5_to_values():
"""Return the list with 5 added to each value.""" def select_first_item():
x = [1, 10, 20] """Return first item."""
# Your code goes here x = ['A', 'B', 'C']
return x[0]
def get_divisble_by_5():
"""Return elements that are divisble by 5.""" def select_last_item():
x = [1, 10, 15, 3, 12, 15, 25, 50] """Return first item."""
# Your code goes here x = ['A', 'B', 'C']
return x[-1]
def merge_lists():
"""Returns pairs from each list.""" def select_reversed():
x = ['A', 'B', 'C'] """Return list reversed."""
y = ['x', 'y', 'z'] x = ['A', 'B', 'C']
# Your code goes here return x[::-1]

def transpose(list_of_lists): def select_first_items():


"""Transpose a list of lists.""" """Select first item on each list."""
# Your code goes here x = [('A','x'), ('B','y'), ('C','z')]
pass return [v[0] for v in x]

def peak_to_peak(alist): def add_5_to_values():


"""Return the peak to peak value of a list.""" """Return the list with 5 added to each value."""
pass x = [1, 10, 20]
return [v + 5 for v in x]
def rotate_left(alist):
"""Rotates a list to the left so that the first item def get_divisble_by_5():
appears at the end.""" """Return elements that are divisble by 5."""
pass x = [1, 10, 15, 3, 12, 15, 25, 50]
return [v for v in x if v % 5 == 0]
def rotate_right(alist):
"""Rotates a list to the right so that the last item def merge_lists():
appears at the beginning.""" """Returns pairs from each list."""
Pass x = ['A', 'B', 'C']
y = ['x', 'y', 'z']
return list(zip(x, y))
def transpose_hard(list_of_lists):
"""Transpose a list of lists, the hard way."""
height = len(list_of_lists)
width = min([len(l) for l in list_of_lists])
result = []
for w in range(width):
result.append([list_of_lists[h][w] for h in
range(height)])
return result

def transpose_easy(list_of_lists):
"""Transpose a list of lists."""
# Gotcha: zip returns a list of tuples, we want a list
of lists
return [list(v) for v in zip(*list_of_lists)]

transpose = transpose_hard

def peak_to_peak(alist):
"""Return the peak to peak value of a list."""
return max(alist) - min(alist)

def rotate_left(alist):
"""Rotates a list to the left so that the first item
appears at the end."""
if len(alist):
alist.append(alist.pop(0))

def rotate_right(alist):
"""Rotates a list to the right so that the last item
appears at the beginning."""
if len(alist):
alist.insert(0, alist.pop())
return [a_string[i:i+4] for i in
String Problem range(0,len(a_string),4)]
"""With this string:
'monty pythons flying circus'
Create a function that returns a sorted string with no def test_no_duplicates():
duplicate characters s = 'monty pythons flying circus'
(keep any whitespace): assert no_duplicates(s) == ' cfghilmnoprstuy'
Example: ' cfghilmnoprstuy'
Create a function that returns the words in reverse
order: def test_reversed_words():
Example: ['circus', 'flying', 'pythons', 'monty'] s = 'monty pythons flying circus'
Create a function that returns a list of 4 character assert reversed_words(s) == ['circus', 'flying',
strings: 'pythons', 'monty']
Example: ['mont', 'y py', 'thon', 's fl', 'ying', ' cir',
'cus']
def test_four_char_strings():
String Sol’n s = 'monty pythons flying circus'
assert four_char_strings(s) == ['mont', 'y py',
def no_duplicates(a_string): 'thon', 's fl', 'ying', ' cir', 'cus']
# set(a_string) will remove duplicates
# sorted(sequence) will create a sorted list of
sequence
# ''.join(sequence) will create a single string out of
a sequence of strings
# This can all be done in one line
return ''.join(sorted(set(a_string)))

def reversed_words(a_string):
# a_string.split() will create a list of words
# reversed(sequence) will create a reversed
sequence iterator
# list(iterator) will iterate across the sequence and
create a list of those objects
# This can all be done in one line
return list(reversed(a_string.split()))

def four_char_strings(a_string):
# The key to this puzzle is to build it up in stages
# Note that:
# range(0,len(a_string),4)
# Gives: [0, 4, 8, 12, 16, 20, 24]
# And a_string[0:4]
# Gives 'mont'
# And a_string[4:8]
# Gives 'y py'
# And so on so a_string[i:i+4] seems useful
# This can all be done in one line

You might also like