ELEX 4653 Lab 2

The purpose of this lab is to practice using container classes, functions and exceptions.

Version 2, April 28, 2018.

Instructions:

  • Modify this notebook by adding the Python code described below.

  • Test your code using the menu item Cell ► Run All

  • When there are no errors shown at the bottom of the page and you see the message "you may save and submit this file", you can submit the notebook (the .ipynb file) to the appropriate dropbox on the course web site.

Set the string variable myid to your BCIT ID ("A00...").

In [1]:
myid="A00123456"

Write a function myfun() that takes a list argument and returns a list. Your function should create a new list by concatenating the first two and the last two elements of the argument. This list should then be sorted in reverse (decreasing) order. Hint: you can use the sort() method to sort your list in reverse (decreasing) order. Note that sort() does not return a value, it sorts the list it's applied do.

In [2]:
def myfun(l):
    l = l[:2]+l[-2:]
    l.sort(reverse=True)
    return l

Set the variable myatoms to a 4-entry dictionary. The key for each entry should be a string with the name of the element (e.g. 'Hydrogen'). The value of each element should be a 2-element tuple containing an integer equal to the atomic number (e.g. 1) and a string equal to the element's symbol (e.g. 'H'). Your dictionary should include only the elements whose atomic numbers correspond to the last four digits of your BCIT ID (use 'Neon', atomic number 10, symbol 'Ne' for the digit 0).

In [3]:
myatoms={'Lithium':(3,'Li'),'Beryllium':(4,'Be'), 'Boron':(5,'B'), 'Carbon':(6,'C')}

name=('Neon', 'Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 
      'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine')
sym=['Ne', 'H','He','Li','Be','B','C','N','O','F']

Write a function, atomlist(), that takes an atom dictionary (not necessarily yours) as an argument and returns a list of tuples containing:(name, atomic number, symbol). Hint: iterating over a dictionary returns the keys.

In [4]:
def atomlist(d):
    l=[]
    for a in d:
        # print(a)
        l.append((a,d[a][0],d[a][1]))
    return l

Write a function atomsort that takes one argument that is list of 3-tuples and returns this same list. Your function should sort the list by decreasing value of the middle element of each tuple (atomic number in this example). You will probably want to use a lambda expression for sort()'s key argument. Note that sort() does not return a value -- it modifies the object it's applied to.

In [5]:
def atomsort(l):
    l.sort(reverse=True,key=lambda x: x[1])
    return l

print(atomsort(atomlist(myatoms)))
[('Carbon', 6, 'C'), ('Boron', 5, 'B'), ('Beryllium', 4, 'Be'), ('Lithium', 3, 'Li')]

Set the three elements of a tuple myfuncs equal to the built-in Python functions that:

  • returns the sum of an iterable argument
  • inserts the string values of its arguments into the string it's applied to
  • returns the magnitude of a complex argument

Note that your list should contain function objects, not strings.

In [6]:
myfuncs=(sum, format, abs)

Write a function called freq() that takes a string argument and returns a dictionary. The dictionary should contain one key for each letter that appears in the argument and the value should be the number of times the letter appears in the argument.

In [7]:
def freq(s):
    d={}
    for c in s:
        if c in d:
            d[c] += 1
        else:
            d[c] = 1
    return d

Optional:

Write a recursive function called revlist that takes a list argument and returns a list containing the same elements but in reverse order. Your may only use the len function and the [] and + operators. You may not use a slice with a negative step value.

In [8]:
def revlist(l):
    if len(l) == 1:
        return l
    else:
        return l[-1:]+revlist(l[:-1])
In [9]:
# lab validation code; do not modify

def labcheck():
    # check myid
    assert len(myid) == 9 and all([c.isdigit() for c in myid[1:]]), \
        "your BCIT ID (myid) is not in the right format"

    # check myfun()
    from random import randint
    n=randint(2,8)
    s=[chr(randint(ord('a'),ord('z'))) for i in range(n)]
    a=myfun(s)
    assert len(a)==4 and \
        all([a[i]>=a[i+1] for i in range(0,3)]) and \
        all([s[i] in a for i in (0,1,n-1,n-2)])

    # check myatoms{}
    from codecs import decode
    namex=('Arba', 'Ulqebtra', 'Uryvhz', 'Yvguvhz', 'Orelyyvhz', 'Obeba', 
           'Pneoba', 'Avgebtra', 'Bkltra', 'Syhbevar')
    symx=('Ar', 'U', 'Ur', 'Yv', 'Or', 'O', 'P', 'A', 'B', 'S')
    num=[10,1,2,3,4,5,6,7,8,9]
    n=[int(c) for c in myid[-4:]]
    l={decode(namex[i],'rot13'):(num[i],decode(symx[i],'rot13')) for i in n}
    for e in myatoms:
        assert myatoms[e][0]%10 in n, \
            "{} isn't in the last 4 digits of your BCIT ID ({})".format(
            myatoms[e][0]%10, myid)
        assert myatoms[e] == l[e], "shouldn't {} be {}?".format( 
            e, l[e])

    # check atomlist()
    n=[randint(0,9) for i in range(randint(2,10))]
    l={decode(namex[i],'rot13'):(num[i],decode(symx[i],'rot13')) for i in n}
    a=atomlist(l)
    assert len(a) == len(l) and all([l[i[0]] == (i[1],i[2]) for i in a])

    # check atomsort()
    atomsort(a)
    assert all([a[i][1] >= a[i+1][1] for i in range(len(l)-1)])

    # check myfuncs()
    import hashlib
    assert tuple((hashlib.md5(f.__name__.encode('utf8')).hexdigest() 
               for f in myfuncs)) == (
        '1d623b89683f9ce4e074de1676d12416',
        '1ddcb92ade31c8fbd370001f9b29a7d9',
        'f9ac6b05beccb0fc5837b6a7fef4c1d3')

    # check freq()
    import random
    c=[chr(randint(ord('a'),ord('z'))) for i in range(randint(6,12))]
    c=list(set(c))
    nc=len(c)
    n=[randint(1,10) for i in range(nc)]
    s=list(''.join([n*c for n,c in zip(n,c)]))
    random.shuffle(s)
    s=''.join(s)
    f=freq(s)
    assert len(f) == nc and all([f[c[i]] == n[i] for i in range(nc)])

    # check revlist()
    try:
        l=[randint(1,100) for i in range(randint(10,20))]
        assert revlist(l) == l[::-1]
        print("revlist() output is correct")
    except:
        pass

    print("All tests passed -- you may save and submit this lab.")
    
labcheck()
revlist() output is correct
All tests passed -- you may save and submit this lab.