Lab1 Answer Key

Strings

Given a string s, return a string made of all the alphabetic chars of s followed by all the non-alphabetic chars of s. Solve with one or two loops.

"a12bc$" -> "abc12$"
"123123A" -> "A123123"
"$$x$" -> "x$$$"
def alpha_first(s):
    alpha = ''
    non_alpha = ''
    for ch in s:
        if ch.isalpha():
            alpha += ch
        else:
            non_alpha += ch

    return alpha + non_alpha
    # -instead of "else" could use "if not ch.isalpha()"
    # -could have one result, loop1 adds alpha, then loop2
    # adds non-alpha

Try writing some unit tests to validate your code!

import unittest

class TestSuite(unittest.TestCase):
    def BasicTest(self): # rename this
        pass # your test logic goes here

if __name__ == '__main__':
    unittest.main()

Fun with Dicts 1

Suppose we have a "dates" list of 'yyyy-mm-dd' date strings corresponding to earthquake events, like this:

['2022-03-14', '2020-03-01', '2021-12-31', '2022-02-01']

We want to count how many events there are for each month, ignoring the year and day. Write code to build and return a counts dict with an int key for each month, e.g. 12 is December, and its value is the number of events for that month. For the above list, the counts dict would be:

{
    3: 2,
    12: 1,
    2: 1
}
def month_count(dates):
    counts = {}
    for date in dates:
        # Could use .find() to locate dashes
        # but in fact they are at 4 and 7
        mo_str = date[5:7]
        mo = int(mo_str)
        # Then its straight dict-count algo
        if mo not in counts:
            counts[mo] = 0
        counts[mo] += 1
    return count

Fun with Dicts 2

Suppose we have a dict with int keys and string values, like this:

{
    100: 'radish',
    200: 'apple',
    101: 'radish',
    202: 'pear',
    201: 'donut',
    102: 'radish',
    203: 'pear',
    103: 'grape',
    205: 'pear'
}

We'll say a key/value pair is "special" when a key and that key + 1 have the same value. In the example above, key 100 is special because it and the key 101 have the value, 'radish'. The key 101 is also special, sharing the same value with 102. Finally, the key 202 is special with the same value as 203.

Given an input dict structured like the example above, compute and return a list of all the special key values in increasing order. For the example above, the result would be [100, 101, 202]

def the_special(d):
    result = []
    for k in d.keys():
        k2 = k + 1   # "next" key number
        if k2 in d:  # in there with same value? 
            if d[k] == d[k2]:
                result.append(k)
    return sorted(result)

Cryptocurrency gone Haywire

Suppose you create a joke crypto currency called "foolz", but then it accidentally becomes super popular and now you have all this data to organize. Typical.

You have a text file representing foolz transactions. The text data looks like this with words separated by commas:

t26691,w45307,w87755
t77340,w23001,w45307,w55820
...

The first word on each line is a foolz transaction id, followed by one or more wallet ids involved in that transaction (treating each id as a string). Any of these ids may occur again on later lines.

In the foolz_errand() function, read in all the lines to build a dict using wallet ids as the keys. The basic file-reading code is provided as a starting point. For each wallet id, build a list of all the transaction ids that appeared on a line with that wallet id. Do not include duplicates in the list of transaction ids. The resulting dict looks like this:

{
    'w45309': ['t26691', 't77340', ...],
    'w87755': ['t99800;, 't26691', ...],
    ...
}

Once all the data is read in, print out all the wallet ids in sorted order, one per line. For each wallet id, print out all its transaction ids in sorted order, one per line, indented by one space, like this:

w45309
  t26691
  t30001
  t34500
...
w45406
  t10045
  t11920
...
def foolz_errand(filename):
    wallets = {}
    with open(filename) as f:
        for line in f:
            line = line.strip()
            parts = line.split(',')
            tid = parts[0]
            for wid in parts[1:]
                if wid not in wallets:
                    wallets[wid] = []
                tids = wallets[wid]
                if tid not in tids:
                    tids.append(tid)

    # printing code
    for wid in sorted(wallets.keys()):
        print(wid)
        tids = wallets[wid]
        for tid in sorted(tids):
            print(' ' + tid)