Exercise 1: Use appropriate string and list syntax to do the following:
(solution below)
.
.
.
.
.
.
.
.
.
.
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(' '))
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:
[a-z]{4}\d{3}
from a list of strings(solution below)
.
.
.
.
.
.
.
.
.
.
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))
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)
.
.
.
.
.
.
.
.
.
.
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)
Exercise 4: Use regular expressions to write a function validate
that tests if a password (as a string) has all of the following:
(solution below)
.
.
.
.
.
.
.
.
.
.
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'))