HW1
py
keyboard_arrow_up
School
University of Pennsylvania *
*We aren’t endorsed by this school
Course
MISC
Subject
Mathematics
Date
Jan 9, 2024
Type
py
Pages
7
Uploaded by ColonelPencilSandpiper19
# HW1
# REMINDER: The work in this assignment must be your own original work and must be completed alone.
import math
def get_path(file_name):
"""
Returns a string with the absolute path of a given file_name located in the
same directory as this script
# Do not modify this function in any way
>>> get_path('words.txt') # HW1.py and words.txt located in HW1 folder
'G:\My Drive\CMPSC132\HW1\words.txt'
"""
import os
target_path = os.path.join(os.path.dirname(__file__), file_name)
return target_path
def rectangle(perimeter,area):
"""
>>> rectangle(14, 10)
5
>>> rectangle(12, 5)
5
>>> rectangle(25, 25)
False
>>> rectangle(50, 100)
20
>>> rectangle(11, 5)
False
>>> rectangle(11, 4)
False
"""
# i am trying to solve the question by using 2 equations given in the question
# i have used simple algebra to get two roots of the length l1 and l2
# if i take l1 as my lenght, the corresponding breadth is l2 and vice versa.
if math.sqrt(((perimeter**2)-(16*area)))>0:
l1= (perimeter+(math.sqrt(((perimeter**2)-(16*area)))))/4
l2= (perimeter-(math.sqrt(((perimeter**2)-(16*area)))))/4
if (l1.is_integer() and l2.is_integer()):
longest= l1
if l2>l1:
longest=l2
return int(longest)
else:
return False
return False
def to_decimal(oct_num):
"""
>>> to_decimal(237) 159
>>> to_decimal(35) 29
>>> to_decimal(600) 384
>>> to_decimal(420)
272
"""
copy=oct_num
if isinstance(copy,int):
while copy>=10:
if 0<=(copy%10)<=7:
copy=copy//10
else:
return False
if 1<=copy<=7:
counter=0
decimal_num=0
while oct_num>0:
decimal_num+=(oct_num%10)*(8**(counter))
oct_num=oct_num//10
counter+=1
return decimal_num
else:
return False
else:
return False
def has_hoagie(num):
"""
>>> has_hoagie(737) True
>>> has_hoagie(35) False
>>> has_hoagie(-6060) True
>>> has_hoagie(-111) True
>>> has_hoagie(6945) False
"""
# i defined the function which checks if the input has a hogie and only takes positive num values.
def has_hoagie_checker(num):
while num>0:
x=num%1000
first= x%10
last=x//100
if first==last:
return True
num=num//10
return False
if num>100 or num<-100:
if num>0:
return has_hoagie_checker(num)
elif num<0:
num= num*(-1)
return has_hoagie_checker(num)
else:
return False
def is_identical(num_1, num_2):
"""
>>> is_identical(51111315, 51315)
True
>>> is_identical(7006600, 7706000)
True
>>> is_identical(135, 765) False
>>> is_identical(2023, 20) False
"""
def remove_duplicates(num):
output_num=0
counter=0
while num>0:
if num%10 != (num//10)%10:
output_num+=((num%10)*(10**counter))
num=num//10
counter+=1
else:
output_num+=0
num=num//10
return output_num
if remove_duplicates(num_1)==remove_duplicates(num_2):
return True
else:
return False
def hailstone(num):
"""
>>> hailstone(10)
[10, 5, 16, 8, 4, 2, 1]
>>> hailstone(1)
[1]
>>> hailstone(27)
[27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526,
263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184,
92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]
>>> hailstone(7)
[7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
>>> hailstone(19)
[19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
"""
hailstone=[num]
while num!=1:
if num%2==0:
num=int(num/2)
hailstone+=[num]
else:
num=((3*num)+1)
hailstone+=[num]
return hailstone
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
def overloaded_add(d, key, value):
"""
Adds the key value pair to the dictionary. If the key is already in the dictionary, the value is made a list and the new value is appended to it.
>>> d = {"Alice": "Engineer"}
>>> overloaded_add(d, "Bob", "Manager")
>>> overloaded_add(d, "Alice", "Sales")
>>> d == {"Alice": ["Engineer", "Sales"], "Bob": "Manager"}
True
"""
if key in d:
if isinstance(d[key],list):
d[key]+=[value]
else:
d[key]=[d[key],value]
else:
d[key]=value
def by_department(d):
"""
>>> employees = {
... 1: {'name': 'John Doe', 'position': 'Manager', 'department': 'Sales'},
... 2: {'position': 'Budget Advisor', 'name': 'Sara Miller', 'department': 'Finance'},
... 3: {'name': 'Jane Smith', 'position': 'Engineer', 'department': 'Engineering'},
... 4: {'name': 'Bob Johnson', 'department': 'Finance', 'position': 'Analyst'},
... 5: {'position': 'Senior Developer', 'department': 'Engineering', 'name': 'Clark Wayne'}
... }
>>> by_department(employees)
{'Sales': [{'emp_id': 1, 'name': 'John Doe', 'position': 'Manager'}], 'Finance': [{'emp_id': 2, 'name': 'Sara Miller', 'position': 'Budget Advisor'}, {'emp_id': 4, 'name': 'Bob Johnson', 'position': 'Analyst'}], 'Engineering': [{'emp_id': 3, 'name': 'Jane Smith', 'position': 'Engineer'}, {'emp_id': 5, 'name':
'Clark Wayne', 'position': 'Senior Developer'}]}
"""
output_d={}
for key in d:
lst_dict={}
lst_dict["emp_id"]=key
lst_dict["name"]=d[key]["name"]
lst_dict["position"]=d[key]["position"]
if d[key]["department"] in output_d:
output_d[d[key]["department"]]+=[lst_dict]
else:
output_d[d[key]["department"]]=[lst_dict]
return output_d
def successors(file_name):
"""
>>> expected = {'.': ['We', 'Maybe'], 'We': ['came'], 'came': ['to'], 'to':
['learn', 'have', 'make'], 'learn': [',', 'how'], ',': ['eat'], 'eat': ['some'], 'some': ['pizza'], 'pizza': ['and', 'too'], 'and': ['to'], 'have': ['fun'], 'fun': ['.'], 'Maybe': ['to'], 'how': ['to'], 'make': ['pizza'], 'too': ['!']}
>>> returnedDict = successors('items.txt')
>>> expected == returnedDict
True
>>> returnedDict['.']
['We', 'Maybe']
>>> returnedDict['to']
['learn', 'have', 'make']
>>> returnedDict['fun']
['.']
>>> returnedDict[',']
['eat']
"""
file_path = get_path(file_name)
with open(file_path, 'r') as file: contents = file.read()
contents=contents.split()
for t in range(len(contents)):
if not contents[t].isalnum():
contents[t]=list(contents[t])
for j in range(len(contents[t])):
if not contents[t][j].isalnum():
contents[t][j]=" "+contents[t][j]+" "
contents[t]="".join(contents[t])
contents=" ".join(contents)
contents=contents.split()
d={".":[contents[0]]}
for i in range(len(contents)-1):
if contents[i] in d:
if not contents[i+1] in d[contents[i]]:
d[contents[i]]+= [contents[i+1]]
else:
d[contents[i]]= [contents[i+1]]
return d
def addToTrie(trie, word):
"""
The following dictionary represents the trie of the words "A", "I", "Apple":
{'a' : {'word' : True, 'p' : {'p' : {'l' : {'e' : {'word' : True}}}}, 'i' : {'word' : True}}}}
>>> trie_dict = {'a' : {'word' : True, 'p' : {'p' : {'l' : {'e' : {'word' :
True}}}}, 'i' : {'word' : True}}} >>> addToTrie(trie_dict, 'art')
>>> trie_dict
{'a': {'word': True, 'p': {'p': {'l': {'e': {'word': True}}}}, 'i': {'word': True}, 'r': {'t': {'word': True}}}}
>>> addToTrie(trie_dict, 'moon') >>> trie_dict
{'a': {'word': True, 'p': {'p': {'l': {'e': {'word': True}}}}, 'i': {'word': True}, 'r': {'t': {'word': True}}}, 'm': {'o': {'o': {'n': {'word': True}}}}}
"""
d=trie
for letter in word:
if not letter in d:
d[letter]={}
d=d[letter]
else:
d=d[letter]
d["word"]=True
return None
def createDictionaryTrie(file_name):
""" >>> trie = createDictionaryTrie("words.txt")
>>> trie == {'b': {'a': {'l': {'l': {'word': True}}, 't': {'s': {'word': True}}}, 'i': {'r': {'d': {'word': True}},\
'n': {'word': True}}, 'o': {'y': {'word': True}}}, 't': {'o': {'y': {'s': {'word': True}}},\
'r': {'e': {'a': {'t': {'word': True}}, 'e': {'word': True}}}}}
True
"""
file_path = get_path(file_name)
with open(file_path, 'r') as file: contents = file.read()
contents= contents.split()
trie={}
for word in contents:
word=word.lower()
addToTrie(trie,word)
return trie
def wordExists(trie, word):
"""
>>> trie_dict = {'a' : {'word' : True, 'p' : {'p' : {'l' : {'e' : {'word' :
True}}}}, 'i' : {'word' : True}}} >>> wordExists(trie_dict, 'armor')
False
>>> wordExists(trie_dict, 'apple')
True
>>> wordExists(trie_dict, 'apples')
False
>>> wordExists(trie_dict, 'a')
True
>>> wordExists(trie_dict, 'as')
False
>>> wordExists(trie_dict, 'tt')
False
"""
d=trie
for letter in word:
if letter in d:
d=d[letter]
else:
return False
return True
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
def run_tests():
import doctest
# Run start tests in all docstrings
# doctest.testmod(verbose=True)
# Run start tests per function - Uncomment the next line to run doctest by function. Replace rectangle with the name of the function you want to test
doctest.run_docstring_examples(wordExists, globals(), name='HW1',verbose=True) if __name__ == "__main__":
run_tests()