I719 Fundamentals of Python/lists

From ICO wiki
Revision as of 20:33, 9 March 2017 by Eroman (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Actions on iterables

You should know how to solve these problems for the test!

You do not need to use a specific way, but you must understand the imperative way.

TASK 1

Write a function that makes all characters in a list uppercase!

call it with the following list, and print the result

['cat', 'dog']

Solution: Imperative

You must know how to do this solution

def uppercase_list(l):
    result = []
    for i in l:
        result.append(i.upper())
    return result

Solution: Functional

def uppercase_list(l):
    return list(map(lambda i: i.upper(), l))

Solution: Modern

def uppercase_list(l):
    return [i.upper() for i in l]

TASK 2

Write a function that makes all character in the values of a dict uppercase!

call it with the following dict and print the results.

{'cat': 'kass', 'dog': 'koer'}

Solution: Imperative

You need to understand how this solution works

def uppercase_dict_values(d):
    result = {}
    for k, v in d.items():
        result[k] = v.upper()
    return result

Solution: Modern

def uppercase_dict_values(d):
    return {k: v.upper() for k, v in d.items()}

TASK 3

write a function that filters out numbers divisible by 3 and 5
call it with range(0, 30)

Solution: Imperative

def exclude_divisible_by_3_and_5(l):
    result = []
    for i in l:
        if not (i % 3 == 0 or i % 5 == 0):
            result.append(i)
    return result

Solution: Functional

def is_not_divisible_by_3_and_5(n):
    if not (n % 3 == 0 or n % 5 == 0):
        return True
    else:
        return False

def exclude_divisible_by_3_and_5(l):
    result = filter(is_not_divisible_by_3_and_5, l)
    return list(result)

Slicing

In [1]: a = "Hello World"

In [2]: a[:2]
Out[2]: 'He'

In [3]: a[2:]
Out[3]: 'llo World'

In [4]: a[-2:]
Out[4]: 'ld'

In [5]: a[:-2]
Out[5]: 'Hello Wor'

In [6]: a[:-2:2]
Out[6]: 'HloWr'

In [7]: a[::2]
Out[7]: 'HloWrd'

In [8]: a[::-1]
Out[8]: 'dlroW olleH'

TASK 4

write a function that sorts numbers in a list by the smallest digit of the integer.
i.e.

my_list = [11, 10, 9, 177, 199]
my_sort_function(my_list)
[10, 11, 177, 9, 199]

Solution

def reverse_digit_order(n):
    """Revere the order of the digits in a number"""
    return str(n)[::-1]


def sort_list_by_smallest_digit(l):
    return sorted(l, key=reverse_digit_order)