Midterm Review

Exercise 1: Use appropriate string and list syntax to do the following:

  • Create a list of every square number between 1 and 100.
  • Create the string "2, 4, 6, 8, ..., 100" (all even numbers between 2 and 100 separated by commas).
  • Turn the a string that consists of words (separated by exactly one space) into a list of words in lowercase.

(solution below)

.

.

.

.

.

.

.

.

.

.

In [1]:
s = "Here is our TEST strinG"

print([i**2 for i in range(1,11)])
print(', '.join([str(i) for i in range(2,102,2)]))
print(s.lower().split(' '))
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100
['here', 'is', 'our', 'test', 'string']

Exercise 2: Write a filter_list() function. This takes in two parameters: a list and a function. The function should return True or False for every element in the list. Return a new list consisting of only the elements of the list that return True with the function (in the same order).

Then, use lambda expressions and your filter function to do the following things:

  • Remove all odd numbers from a list of integers
  • Remove all strings that don't match the regular expression [a-z]{4}\d{3} from a list of strings
  • Randomly remove elements with 50\% probability of any list. That is, flip a coin for each element and remove it if it is tails.

(solution below)

.

.

.

.

.

.

.

.

.

.

In [2]:
import re, random

def filter_list(l, f):
    return [x for x in l if f(x)]

l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l2 = ["abcd123", "invalid", "ucla000"]

print(filter_list(l1, lambda x : x % 2 == 0))
print(filter_list(l2, lambda x : re.search(r'[a-z]{4}\d{3}', x) != None))
print(filter_list(l1, lambda x : random.randint(0,1) == 1))
[2, 4, 6, 8, 10]
['abcd123', 'ucla000']
[1, 3, 5, 8, 9, 10]

Exercise 3: Make a Queue class. A queue is a data structure where you have two main methods: push() and pop(). Items are added to the queue with push() and returned one at a time in the same order with pop(). Once an item has been popped from a queue it will never be returned again. We also want to be able to iterate through our queue. If we completely loop through it, we will deplete it so that it is empty again.

(solution below)

.

.

.

.

.

.

.

.

.

.

In [3]:
class Queue:
    def __init__(self):
        self.data = []

    def push(self, item):
        self.data.append(item)

    def pop(self):
        return self.data.pop(0)

    def __iter__(self):
        return self

    def __next__(self):
        if len(self.data) == 0:
            raise StopIteration()
        else:
            return self.pop()

q = Queue()
q.push(1)
q.push(2)
q.push(3)
print(q.pop())
for e in q:
    print(e)
1
2
3

Exercise 4: Use regular expressions to write a function validate that tests if a password (as a string) has all of the following:

  • At least eight characters
  • No whitespace
  • A lower case letter
  • A capital letter
  • A number
  • One of the symbols !@#$%^&*()

(solution below)

.

.

.

.

.

.

.

.

.

.

In [4]:
def validate(password):
    if not re.match(r'^[^\s]{8}[^\s]*$', password):
        return False
    if not re.search(r'[a-z]', password):
        return False
    if not re.search(r'[A-Z]', password):
        return False
    if not re.search(r'[0-9]', password):
        return False
    if not re.search(r'[!@#$%^&*()]', password):
        return False

    return True

print(validate('SecurePassword1#'))
print(validate('Short1@'))
print(validate('Space Password1!'))
print(validate('ONLY_UPPER1!'))
print(validate('all_lowercase1!'))
print(validate('NoNumbers!'))
print(validate('NoSymbols5'))
True
False
False
False
False
False
False