Class practice: strings, lists & numbers

These were copied and slightly modified from Paul Waddell’s Urban Informatics and Visualization. All credit goes to him, all mistakes are mine.

Exercises | String & List

Reversing numbers

Write code that reverses even numbers from 0 to 100 (including 100) and print the result.

In [33]:
end = 100001
In [34]:
%%timeit
a = list(range(end))
b = a[::-2]
#print(b)
2.62 ms ± 74.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [35]:
%%timeit
a = []
for i in range(end):
    if i % 2 ==0:
        a.append(i)
b = a[::-1]
#print(b)
8.61 ms ± 332 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [36]:
%%timeit
a = list(range(end-1, -1, -2))
#print(a)
725 µs ± 12.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

List manipulations

We have two lists, a and b, a=[10,20,30] b=[30,60,90]. Write code that give us the following outputs: [LIST]

  1. [[10,20,30],[30,60,90]]
  2. [10,20,30,30,60,90]
  3. [10,20,60,90] (first two of a, last two of b)
  4. [20,40,60] (the element-wise differences between b and a)
In [51]:
n = 100_000
a=list(range(n))
b=list(range(n))

In [56]:
import dis
dis.dis("pd = [b[i]-a[i] for i in range(0,len(a))]")
  1           0 LOAD_CONST               0 (<code object <listcomp> at 0x106ec2a50, file "<dis>", line 1>)
              2 LOAD_CONST               1 ('<listcomp>')
              4 MAKE_FUNCTION            0
              6 LOAD_NAME                0 (range)
              8 LOAD_CONST               2 (0)
             10 LOAD_NAME                1 (len)
             12 LOAD_NAME                2 (a)
             14 CALL_FUNCTION            1
             16 CALL_FUNCTION            2
             18 GET_ITER
             20 CALL_FUNCTION            1
             22 STORE_NAME               3 (pd)
             24 LOAD_CONST               3 (None)
             26 RETURN_VALUE
In [59]:
dis.dis("""
l = []
for i in range(len(a)):
  l.append(b[i] - a[i])
""")
  2           0 BUILD_LIST               0
              2 STORE_NAME               0 (l)

  3           4 SETUP_LOOP              42 (to 48)
              6 LOAD_NAME                1 (range)
              8 LOAD_NAME                2 (len)
             10 LOAD_NAME                3 (a)
             12 CALL_FUNCTION            1
             14 CALL_FUNCTION            1
             16 GET_ITER
        >>   18 FOR_ITER                26 (to 46)
             20 STORE_NAME               4 (i)

  4          22 LOAD_NAME                0 (l)
             24 LOAD_ATTR                5 (append)
             26 LOAD_NAME                6 (b)
             28 LOAD_NAME                4 (i)
             30 BINARY_SUBSCR
             32 LOAD_NAME                3 (a)
             34 LOAD_NAME                4 (i)
             36 BINARY_SUBSCR
             38 BINARY_SUBTRACT
             40 CALL_FUNCTION            1
             42 POP_TOP
             44 JUMP_ABSOLUTE           18
        >>   46 POP_BLOCK
        >>   48 LOAD_CONST               0 (None)
             50 RETURN_VALUE
In [55]:
[x for x in range(10) if x%2==0]
Out[55]:
[0, 2, 4, 6, 8]

List insertions

Write code that add the name “Norah” to the following list, after the name “Michael”.

Make sure your code continues to do the right thing if more names are added to the list, or if the list is reordered, or if you need to find Jessica instead of Michael (or anyone else on the list).

names: Akshara, Anna, Aqshems, Chester, Echo, James, Jessica, Matthew, Michael, Philip, Sarah

In [65]:
names = ["Akshara", "Anna", "Aqshems", "Chester", "Echo", "James", "Jessica", "Matthew", "Michael", "Philip", "Sarah"]

def add_after(name_list, name_to_add, name_to_after):
    """Add a name to a list, at the specified position.

    Adds....
    ....

    """
    names = name_list
    for i, name in enumerate(names):
        if name == name_to_after:
            names.insert(i+1,name_to_add)
            break
    return names

print(add_after(names, "Norah", "Michael"))
print(add_after(names, "Lance", "Jessica"))
print(names)
['Akshara', 'Anna', 'Aqshems', 'Chester', 'Echo', 'James', 'Jessica', 'Matthew', 'Michael', 'Norah', 'Philip', 'Sarah']
['Akshara', 'Anna', 'Aqshems', 'Chester', 'Echo', 'James', 'Jessica', 'Lance', 'Matthew', 'Michael', 'Norah', 'Philip', 'Sarah']
['Akshara', 'Anna', 'Aqshems', 'Chester', 'Echo', 'James', 'Jessica', 'Lance', 'Matthew', 'Michael', 'Norah', 'Philip', 'Sarah']
In [66]:
name = ["Akshara", "Anna", "Aqshems", "Chester", "Echo", "James", "Jessica", "Matthew", "Michael", "Philip", "Sarah"]
name.insert(name.index('Michael')+1,"Norah")
name
Out[66]:
['Akshara',
 'Anna',
 'Aqshems',
 'Chester',
 'Echo',
 'James',
 'Jessica',
 'Matthew',
 'Michael',
 'Norah',
 'Philip',
 'Sarah']

Maximizing a sum

Find a list in the following list (G) whose sum of its elements is the highest.

G = [[13,9,8], [14,6,12], [10,13,11], [7,18,9]]

In [23]:
# Type your code here

Cars and brown trucks

Write code that prints all colors in the list and the word ‘car’, one per line, unless the color is brown, when you should print ‘truck’ instead:

colors = ['red', 'black', 'gray', 'brown', 'blue', 'white']
In [8]:
# Type your code here

Numbers

Reversing numbers

Write a function nums_reversed that takes in an integer n and returns a string containing the numbers 1 through n including n in reverse order, separated by spaces. For example:

>>> nums_reversed(5)
'5 4 3 2 1'
In [ ]:
# Type your code here

Divisibility

Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 1000 and 1200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.

Hint: Consider using range(#begin, #end).

In [ ]:
# Type your code here

Write the same program but this time use while loop instead of for loop

In [ ]:
# Type your code here

Double trouble

Write a function double100 that takes in a list of integers and returns True only if the list has two 100s next to each other.

>>> double100([100, 2, 3, 100])
False
>>> double100([2, 3, 100, 100, 5])
True
In [ ]:
# Type your code here