-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhomework1.py
212 lines (171 loc) · 8.14 KB
/
homework1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# PPHA 30537
# Spring 2024
# Homework 1
# Uchenna Offorjebe
# MadeByUche
# Due date: Sunday April 7th before midnight
# Write your answers in the space between the questions, and commit/push only this file to your repo.
# Note that there can be a difference between giving a "minimally" right answer, and a really good
# answer, so it can pay to put thought into your work.
#############
# Part 1: Introductory Python (to be done without defining functions or classes)
# Question 1.1: Using a for loop, write code that takes in any list of objects, then prints out:
# "The value at position __ is __" for every element in the loop, where the first blank is the
# index location and the second blank the object at that index location.
my_list = [1, 2, 3, 4, 5]
for i, item in enumerate(my_list):
print(f'The value at position {i} is {item}')
# Question 1.2: A palindrome is a word or phrase that is the same both forwards and backwards. Write
# code that takes a variable of any string, then tests to see whether it qualifies as a palindrome.
# Make sure it counts the word "radar" and the phrase "A man, a plan, a canal, Panama!", while
# rejecting the word "Microsoft" and the phrase "This isn't a palindrome". Print the results of these
# four tests.
# Code here inspired by: https://www.geeksforgeeks.org/create-a-random-password-generator-using-python/
string1 = "civic"
string2 = "radar"
string3 = "A man, a plan, a canal, Panama!"
string4 = "Microsoft"
# Civic
if string1 == string1[::-1]:
print("This is a palindrome")
else:
print("This isn't a palindrome")
# Radar
if string2 == string2[::-1]:
print("This is a palindrome")
else:
print("This isn't a palindrome")
# Panama
anum_string3 = ''.join(char for char in string3.lower() if char.isalnum())
if anum_string3.lower() == anum_string3.lower()[::-1]:
print("This is a palindrome")
else:
print("This isn't a palindrome")
# Microsoft
if string4 == string4[::-1]:
print("This is a palindrome")
else:
print("This isn't a palindrome")
# Question 1.3: The code below pauses to wait for user input, before assigning the user input to the
# variable. Beginning with the given code, check to see if the answer given is an available
# vegetable. If it is, print that the user can have the vegetable and end the bit of code. If
# they input something unrecognized by our list, tell the user they made an invalid choice and make
# them pick again. Repeat until they pick a valid vegetable.
# Code here inspired by: https://www.geeksforgeeks.org/create-a-random-password-generator-using-python/
available_vegetables = ['carrot', 'kale', 'broccoli', 'pepper']
choice = input('Please pick a vegetable I have available: ')
while True:
if choice.lower() in available_vegetables:
print(f'Sure, you can have {choice}!')
break
else:
print(f'Sorry, I do not have {choice}.')
choice = input('Please pick a vegetable I have available: ')
# Question 1.4: Write a list comprehension that starts with any list of strings and returns a new
# list that contains each string in all lower-case letters, unless the modified string begins with
# the letter "a" or "b", in which case it should drop it from the result.
list1 = ['A','B','C','D','E','F','G','H']
list2 = [j.lower() for j in list1 if not j.lower().startswith(('a','b'))]
print(list1)
print(list2)
# Question 1.5: Beginning with the two lists below, write a single dictionary comprehension that
# turns them into the following dictionary: {'IL':'Illinois', 'IN':'Indiana', 'MI':'Michigan', 'WI':'Wisconsin'}
short_names = ['IL', 'IN', 'MI', 'WI']
long_names = ['Illinois', 'Indiana', 'Michigan', 'Wisconsin']
states_dict ={short_names[i]: long_names[i] for i in range(len(short_names))}
print(states_dict)
#############
# Part 2: Functions and classes (must be answered using functions\classes)
# Question 2.1: Write a function that takes two numbers as arguments, then
# sums them together. If the sum is greater than 10, return the string
# "big", if it is equal to 10, return "just right", and if it is less than
# 10, return "small". Apply the function to each tuple of values in the
# following list, with the end result being another list holding the strings
# your function generates (e.g. ["big", "big", "small"]).
start_list = [(10, 0), (100, 6), (0, 0), (-15, -100), (5, 4)]
def func_one(a, b):
num = a + b
if num > 10:
return 'big'
elif num == 10:
return 'just right'
else:
return 'small'
add_num = [func_one(a,b) for a,b in start_list]
print(add_num)
# Question 2.2: The following code is fully-functional, but uses a global
# variable and a local variable. Re-write it to work the same, but using one
# argument and no global variable. Use no more than two lines of comments to
# explain why this new way is preferable to the old way.
def my_func(a = 10):
a = a
b = 40
return a + b
x = my_func()
print(x)
# Question 2.3: Write a function that can generate a random password from
# upper-case and lower-case letters, numbers, and special characters
# (!@#$%^&*). It should have an argument for password length, and should
# check to make sure the length is between 8 and 16, or else print a
# warning to the user and exit. Your function should also have a keyword
# argument named "special_chars" that defaults to True. If the function
# is called with the keyword argument set to False instead, then the
# random values chosen should not include special characters. Create a
# second similar keyword argument for numbers. Use one of the two
# libraries below in your solution:
# Code here inspired by: https://www.geeksforgeeks.org/create-a-random-password-generator-using-python/
import random
def mypassword(length, num=True, chars=True):
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
special = '!@#$%^&*'
# Length between 8 and 16
if length < 8 or length > 16:
return 'Your password must be between 8 and 16 characters.'
# Has number, special, and lower/upper case
check = upper + lower + digits + special
password = ''.join(random.choice(check) for _ in range(length))
return password
print(mypassword(8))
print(mypassword(5))
print(mypassword(16))
# Question 2.4: Create a class named MovieDatabase that takes one argument
# when an instance is created which stores the name of the person creating
# the database (in this case, you) as an attribute. Then give it two methods:
#
# The first, named add_movie, that requires three arguments when called:
# one for the name of a movie, one for the genera of the movie (e.g. comedy,
# drama), and one for the rating you personally give the movie on a scale
# from 0 (worst) to 5 (best). Store those the details of the movie in the
# instance.
#
# The second, named what_to_watch, which randomly picks one movie in the
# instance of the database. Tell the user what to watch tonight,
# courtesy of the name of the name you put in as the creator, using a
# print statement that gives all of the info stored about that movie.
# Make sure it does not crash if called before any movies are in the
# database.
#
# Finally, create one instance of your new class, and add four movies to
# it. Call your what_to_watch method once at the end.
# Code inspired by: https://plugins.jetbrains.com/plugin/16630-introduction-to-python
import random
class MovieDatabase():
def __init__(self, name):
self.name = name
self.moviedb = []
def add_movie(self, movie_name, genre, rating):
movie_info = {'movie_name': movie_name, 'genre': genre, 'rating': rating}
self.moviedb.append(movie_info)
def what_to_watch(self):
if not self.moviedb:
return "It seems as though our database is empty =( "
movie = random.choice(self.moviedb)
return f"{self.name} suggests that you watch '{movie['movie_name']}'. Its genre is {movie['genre']} and they rated it at {movie['rating']} out of 5."
lets_watch = MovieDatabase("Uche")
lets_watch.add_movie("Dune", "Sci-Fi", 2)
lets_watch.add_movie("Cloud Atlas", "Drama/Sci-Fi", 3.5)
lets_watch.add_movie("Steve Jobs", "Biopic", 4)
lets_watch.add_movie("Oppenheimer", "Biopic", 5)
print(lets_watch.what_to_watch())