Back to CS 106A Homepage
Written by Brahm Capoor & Juliette Woodrow
October 14th, 2019
s[1:6]s[:2] or s[0:2]s[6:9]s[6:] or s[6:10]s[6] or s[6:7]s[:] or s[0:10] (or just
s)
def defront(s):
if len(s) >= 2:
return s[2:]
return s
def x_end(s):
found = s.find('x')
if found != -1:
return s[found:]
return ''
def pre_colon(s):
colon = s.find(':')
if colon != -1:
return s[:colon]
return s
def at_word(s):
at1 = s.find('@')
if at1 != -1:
at2 = s.find('@', at1 + 1)
if at2 != -1:
return s[at1 + 1:at2]
return ''
def contains_email(line):
"""
This function checks to see if an email address is present in a given line of a message.
It checks for the '@' symbol. If one is present, it checks that it is part of an email address,
meaning it must have at least one character before and after it. If an email address is found,
the function returns True and it returns False otherwise.
"""
at_location = line.find('@')
if at_location == -1:
return False
if line[at_location - 1] == ' ' or line[at_location + 1] == ' ':
return False
return True
def contains_phone_number(line):
"""
This function searches a given line of a message for a 10 digit sequence of numbers to check if a phone
number is present. If a phone number is present, it returns True and it returns False otherwise.
"""
for idx in range(len(line)):
if line[idx].isdigit():
possible_phone_number = line[idx:idx + 10]
if len(possible_phone_number) == 10 and possible_phone_number.isdigit():
return True
return False
def is_message_valid(filename):
"""
This function searches a file for an email address or phone number using the helper methods defined above.
If the file contains a phone number or email address, it is considered invalid and the function should
return False. If it contains neither a phone number or email address, the message is valid and should
return True.
>>> is_message_valid('100284.txt')
True
>>> is_message_valid('100282.txt')
True
>>> is_message_valid('100280.txt')
False
"""
with open(filename, 'r') as f:
for line in f:
if contains_email(line):
return False
if contains_phone_number(line):
return False
return True
Download a solution PyCharm project here.