migrate to git.charlotte.sh
This commit is contained in:
commit
fbd588721e
412 changed files with 13750 additions and 0 deletions
48
python-csi160/json-api-lab/main.py
Normal file
48
python-csi160/json-api-lab/main.py
Normal file
|
@ -0,0 +1,48 @@
|
|||
# 4/4/2025 - Charlotte Croce
|
||||
# JSON API LAB
|
||||
#
|
||||
# this program uses the Coinbase API to get a dictionary of currencies and their prices
|
||||
# the user can search for a currency by symbol and get its name and price
|
||||
#
|
||||
import requests
|
||||
|
||||
API_URL = "https://api.coinbase.com/v2/currencies"
|
||||
response = requests.get(API_URL)
|
||||
|
||||
# Parse the JSON response
|
||||
response_data = response.json()
|
||||
|
||||
# create dictionary with currency symbol as key and name as value
|
||||
currency_dict = {currency['id']: currency['name'] for currency in response_data['data']}
|
||||
|
||||
# not included in the dictionary because it is many seperate requests
|
||||
# and takes a while to process
|
||||
def get_currency_price(symbol):
|
||||
price_url = f"https://api.coinbase.com/v2/prices/{symbol}-USD/spot"
|
||||
try:
|
||||
price_response = requests.get(price_url)
|
||||
price_data = price_response.json()
|
||||
return price_data['data']['amount']
|
||||
except (requests.exceptions.RequestException, KeyError, ValueError):
|
||||
return "Price unavailable"
|
||||
|
||||
|
||||
def display_list():
|
||||
# ':<10' creates a 10 character wide column
|
||||
print(f"{'Symbol':<10} {'Name':<10}")
|
||||
for symbol, name in currency_dict.items():
|
||||
print(f"{symbol:<10} {name:<10}")
|
||||
|
||||
while True:
|
||||
# Prompt user for currency symbol
|
||||
symbol = input("Enter currency symbol ('l' to list currencies')('q' to quit): ").upper()
|
||||
if symbol == 'Q':
|
||||
break
|
||||
# if user enter's 'l' Display currencies as table
|
||||
if symbol == 'L':
|
||||
display_list()
|
||||
# Check if symbol is in dictionary
|
||||
if symbol in currency_dict:
|
||||
print(f"\n{currency_dict[symbol]}\n1{symbol} = ${get_currency_price(symbol)}USD\n")
|
||||
else:
|
||||
print(f"{symbol} not found")
|
1
python-csi160/json-api-lab/requirements.txt
Normal file
1
python-csi160/json-api-lab/requirements.txt
Normal file
|
@ -0,0 +1 @@
|
|||
requests
|
14
python-csi160/midterm/part1.py
Normal file
14
python-csi160/midterm/part1.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
"""
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Basic Function Write a function named exactly "calculate_discounted_price" which receives 2 parameters: price(float)
|
||||
and discount(float) in percentage, and returns the final price after applying the discount.
|
||||
|
||||
Example:
|
||||
print(calculate_discounted_price(100, 10)) # Output: 90.0
|
||||
print(calculate_discounted_price(50, 50)) # Output: 25.0
|
||||
"""
|
||||
def calculate_discounted_price(price, discount):
|
||||
return price - (price * discount * .01)
|
||||
|
||||
print(calculate_discounted_price(100,10))
|
||||
print(calculate_discounted_price(50,50))
|
62
python-csi160/midterm/part10.py
Normal file
62
python-csi160/midterm/part10.py
Normal file
|
@ -0,0 +1,62 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
This is a bonus question, and it might hard. It is not mandatory to solve it. You can skip it if you want.
|
||||
Spiral Matrix is a matrix of size 'n x n' filled with numbers from 1 to (n*n) in a spiral order.
|
||||
Write a function 'spiral_matrix' that receives an integer 'n' as parameter and returns a list of lists representing the spiral matrix.
|
||||
Examples of Spiral Matrix:
|
||||
n = 1
|
||||
[[1]]
|
||||
n = 2
|
||||
[[1, 2],
|
||||
[4, 3]]
|
||||
n = 3
|
||||
[[1, 2, 3],
|
||||
[8, 9, 4],
|
||||
[7, 6, 5]]
|
||||
n = 4
|
||||
[[1, 2, 3, 4],
|
||||
[12, 13, 14, 5],
|
||||
[11, 16, 15, 6],
|
||||
[10, 9, 8, 7]]
|
||||
|
||||
Example:
|
||||
print(spiral_matrix(3))
|
||||
# Output:
|
||||
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
|
||||
'''
|
||||
|
||||
def spiral_matrix(n):
|
||||
# create an empty n x n matrix filled with zeros
|
||||
matrix = [[0 for i in range(n)] for j in range(n)]
|
||||
|
||||
counter = 1
|
||||
row = 0
|
||||
col = 0
|
||||
|
||||
for i in range(1, n*n):
|
||||
while col < n - i:
|
||||
matrix[row][col] = counter
|
||||
counter += 1
|
||||
col += 1
|
||||
|
||||
while row < n - i:
|
||||
matrix[row][col] = counter
|
||||
counter += 1
|
||||
row += 1
|
||||
|
||||
while col > 0 + (i - 1):
|
||||
matrix[row][col] = counter
|
||||
counter += 1
|
||||
col -= 1
|
||||
|
||||
while row > 0 + i:
|
||||
matrix[row][col] = counter
|
||||
counter += 1
|
||||
row -= 1
|
||||
|
||||
matrix[row][col] = counter
|
||||
return matrix
|
||||
|
||||
print(spiral_matrix(5))
|
||||
# Output:
|
||||
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
|
15
python-csi160/midterm/part2.py
Normal file
15
python-csi160/midterm/part2.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Write a function named exactly 'divide_and_remainder' and receive a parameter 'num' and a base 'b' and returns a tuple
|
||||
where: he first element is the result of integer division, and the second element is the remainder.
|
||||
|
||||
Example:
|
||||
print(divide_and_remainder(10, 3)) # Output: (3, 1)
|
||||
print(divide_and_remainder(10, 2)) # Output: (5, 0)
|
||||
'''
|
||||
|
||||
def divide_and_remainder(num, b):
|
||||
return (num // b, num % b)
|
||||
|
||||
print(divide_and_remainder(10, 3)) # Output: (3, 1)
|
||||
print(divide_and_remainder(10, 2)) # Output: (5, 0)
|
26
python-csi160/midterm/part3.py
Normal file
26
python-csi160/midterm/part3.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
This question can be challenging, so leave it to the end if you are running out of time.
|
||||
Lucas Sequence Write a function 'lucas' which receives an integer 'n' as parameter and returns the 'n-th' element of the
|
||||
lucas sequence. The Lucas sequence is a series of numbers in which each number is the sum of the two preceding just
|
||||
like fibonacci, but the first two numbers are 2 and 1, instead of 0 and 1. So the sequence goes like this:
|
||||
2, 1, 3, 4, 7, 11, 18, 29...
|
||||
|
||||
Do not use recursion to solve this problem.
|
||||
|
||||
Examples:
|
||||
lucas(0) # returns 2
|
||||
lucas(1) # returns 1
|
||||
lucas(2) # returns 3
|
||||
lucas(5) # returns 11
|
||||
'''
|
||||
def lucas(n):
|
||||
lucas_numbers = [2, 1]
|
||||
for i in range(2, n + 1):
|
||||
lucas_numbers.append(lucas_numbers[i - 1] + lucas_numbers[i - 2])
|
||||
return lucas_numbers[n]
|
||||
|
||||
print(lucas(0)) # returns 2
|
||||
print(lucas(1)) # returns 1
|
||||
print(lucas(2)) # returns 3
|
||||
print(lucas(5)) # returns 11
|
19
python-csi160/midterm/part4.py
Normal file
19
python-csi160/midterm/part4.py
Normal file
|
@ -0,0 +1,19 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Write a function named exactly "last2" which receives a list of elements as parameter and then return the second element
|
||||
from the end to the beginning of the list. If the list has less than two elements, the function should return None.
|
||||
|
||||
Example:
|
||||
print(last2(['red', 'blue', 'green', 'yellow'])) # Output: green
|
||||
print(last2([0,1])) # Output: 0
|
||||
print(last2([0])) # Output: None
|
||||
'''
|
||||
def last2(lst):
|
||||
if len(lst) < 2:
|
||||
return None
|
||||
else:
|
||||
return lst[-2]
|
||||
|
||||
print(last2(['red', 'blue', 'green', 'yellow'])) # Output: green
|
||||
print(last2([0,1])) # Output: 0
|
||||
print(last2([0])) # Output: None
|
22
python-csi160/midterm/part5.py
Normal file
22
python-csi160/midterm/part5.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Write a function named exactly "median" which receives a list of element as parameter and returns the median value of
|
||||
the list. The median is the value separating the higher half from the lower half of a data sample. If the list has an
|
||||
even number of elements, the function should return the average of the two middle elements. You should not modify the
|
||||
original list, but you can sort in a copy of the list.
|
||||
|
||||
Example:
|
||||
median([1, 2, 3, 4, 5]) # returns: 3
|
||||
median([1, 2, 3, 4, 5, 6]) # returns: 3.5
|
||||
'''
|
||||
def median(numbers):
|
||||
sortedNums = sorted(numbers)
|
||||
length = len(sortedNums)
|
||||
mid = length // 2
|
||||
if length % 2 == 0: # even number-> avg of middle two
|
||||
return (sortedNums[mid - 1] + sortedNums[mid]) / 2
|
||||
else: # odd number-> middle element
|
||||
return sortedNums[mid]
|
||||
|
||||
print(median([1, 3, 2, 4, 5])) # returns: 3
|
||||
print(median([1, 2, 3, 4, 5, 6])) # returns: 3.5
|
37
python-csi160/midterm/part6.py
Normal file
37
python-csi160/midterm/part6.py
Normal file
|
@ -0,0 +1,37 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
You are building a music playlist system. Write a function named 'manage_playlist' which receives 3 paramenters: a
|
||||
list of song names, a new song name to be added to the end of the playlist, and a song name to be searched in the
|
||||
playlist. It should return the index of the searched song in the updated playlist (or None if the song is not found).
|
||||
|
||||
Example:
|
||||
playlist = ['Dream On', 'Bohemian Rhapsody', 'Stairway to Heaven']
|
||||
print(manage_playlist(playlist, 'Hotel California', 'Bohemian Rhapsody')) # Output: 1
|
||||
print(playlist) # Output: ['Dream On', 'Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California']
|
||||
|
||||
playlist = ['Imagine', 'Confortably Numb']
|
||||
print(manage_playlist(playlist, 'Wish You Were Here', 'Wish You Were Here')) # Output: 2
|
||||
print(playlist) # Output: ['Imagine', 'Confortably Numb', 'Wish You Were Here']
|
||||
|
||||
playlist = ['Imagine', 'Confortably Numb']
|
||||
print(manage_playlist(playlist, 'Wish You Were Here', 'Smoking on the Water')) # Output: None
|
||||
print(playlist) # Output: ['Imagine', 'Confortably Numb', 'Wish You Were Here']
|
||||
'''
|
||||
def manage_playlist(playlist, new_song, search_song):
|
||||
playlist.append(new_song)
|
||||
for i in range(len(playlist)):
|
||||
if playlist[i] == search_song:
|
||||
return i
|
||||
return None
|
||||
|
||||
playlist = ['Dream On', 'Bohemian Rhapsody', 'Stairway to Heaven']
|
||||
print(manage_playlist(playlist, 'Hotel California', 'Bohemian Rhapsody')) # Output: 1
|
||||
print(playlist) # Output: ['Dream On', 'Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California']
|
||||
|
||||
playlist = ['Imagine', 'Confortably Numb']
|
||||
print(manage_playlist(playlist, 'Wish You Were Here', 'Wish You Were Here')) # Output: 2
|
||||
print(playlist) # Output: ['Imagine', 'Confortably Numb', 'Wish You Were Here']
|
||||
|
||||
playlist = ['Imagine', 'Confortably Numb']
|
||||
print(manage_playlist(playlist, 'Wish You Were Here', 'Smoking on the Water')) # Output: None
|
||||
print(playlist) # Output: ['Imagine', 'Confortably Numb', 'Wish You Were Here']
|
24
python-csi160/midterm/part7.py
Normal file
24
python-csi160/midterm/part7.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Write a function named 'split_full_name' which receives a parameter 'full_name' with 2 or more surnames and returns a
|
||||
tuple with the last name and the first name. The full name will be a string with the following format:
|
||||
"first_name middle1 middle2 ... lastname" where middle1, middle2, ... are optional middle names and the last word is the
|
||||
last name. The function should return a tuple with the last name and the first name. If the full name has only one
|
||||
word, the function should return a tuple with the word as the last name and an empty string as the first name.
|
||||
|
||||
Example:
|
||||
print(split_full_name("John Doe")) # Output: ('Doe', 'John')
|
||||
print(split_full_name("John Doe Smith")) # Output: ('Smith', 'John')
|
||||
print(split_full_name("John")) # Output: ('John', '')
|
||||
print(split_full_name("John Doe Smith Lee")) # Output: ('Lee', 'John')
|
||||
'''
|
||||
def split_full_name(full_name):
|
||||
namelist = full_name.split(" ")
|
||||
if len(namelist) < 2:
|
||||
return (namelist[0], '')
|
||||
return (namelist[-1], namelist[0])
|
||||
|
||||
print(split_full_name("John Doe")) # Output: ('Doe', 'John')
|
||||
print(split_full_name("John Doe Smith")) # Output: ('Smith', 'John')
|
||||
print(split_full_name("John")) # Output: ('John', '')
|
||||
print(split_full_name("John Doe Smith Lee")) # Output: ('Lee', 'John')
|
21
python-csi160/midterm/part8.py
Normal file
21
python-csi160/midterm/part8.py
Normal file
|
@ -0,0 +1,21 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Write a function named 'countdown' which receives a parameter 'n' and returns a list with the countdown from 'n' to 0
|
||||
both included. If 'n' is less than 0, the function should return an empty list.
|
||||
|
||||
Example:
|
||||
print(countdown(5)) # Output: [5, 4, 3, 2, 1, 0]
|
||||
print(countdown(0)) # Output: [0]
|
||||
print(countdown(-1)) # Output: []
|
||||
print(countdown(10)) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
|
||||
'''
|
||||
def countdown(n):
|
||||
lst = []
|
||||
for i in range(n, -1, -1):
|
||||
lst.append(i)
|
||||
return lst
|
||||
|
||||
print(countdown(5)) # Output: [5, 4, 3, 2, 1, 0]
|
||||
print(countdown(0)) # Output: [0]
|
||||
print(countdown(-1)) # Output: []
|
||||
print(countdown(10)) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
|
38
python-csi160/midterm/part9.py
Normal file
38
python-csi160/midterm/part9.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
'''
|
||||
Do not use AI! You can schedule to try again if you have a bad grade!
|
||||
Write a functon named 'above_main_diagonal' which receives a square matrix as parameter and returns the sum of the
|
||||
elements above the main diagonal. The main diagonal is the one that goes from the top-left to the bottom-right of the
|
||||
matrix. A number is characterized as above the main diagonal if its row index is less than its column index. The matrix
|
||||
will always have at least one element.
|
||||
|
||||
Example:
|
||||
matrix = [[1, 1, 1],
|
||||
[1, 1, 1],
|
||||
[1, 1, 1]]
|
||||
print(above_main_diagonal(matrix)) # Output: 3. It will sum 1+1+1
|
||||
|
||||
matrix = [[1, 2, 3, 4],
|
||||
[5, 6, 7, 8],
|
||||
[9, 10, 11, 12],
|
||||
[13, 14, 15, 16]]
|
||||
print(above_main_diagonal(matrix)) # Output: 36. It will sum 2+3+4+7+8+12
|
||||
'''
|
||||
def above_main_diagonal(matrix):
|
||||
sum = 0
|
||||
for row in range(len(matrix)):
|
||||
for col in range(len(matrix[0])):
|
||||
if row < col:
|
||||
sum += matrix[row][col]
|
||||
return sum
|
||||
|
||||
|
||||
matrix = [[1, 1, 1],
|
||||
[1, 1, 1],
|
||||
[1, 1, 1]]
|
||||
print(above_main_diagonal(matrix)) # Output: 3. It will sum 1+1+1
|
||||
|
||||
matrix = [[1, 2, 3, 4],
|
||||
[5, 6, 7, 8],
|
||||
[9, 10, 11, 12],
|
||||
[13, 14, 15, 16]]
|
||||
print(above_main_diagonal(matrix)) # Output: 36. It will sum 2+3+4+7+8+12
|
17
python-csi160/ollama/ollama.py
Normal file
17
python-csi160/ollama/ollama.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
# in a seperate terminal:
|
||||
# ollama run gemma2
|
||||
|
||||
import requests
|
||||
|
||||
prompt = "Why the sky is blue?"
|
||||
|
||||
data = {
|
||||
"model": "gemma2:2b",
|
||||
"prompt": prompt,
|
||||
"stream": False
|
||||
}
|
||||
|
||||
response = requests.post("http://localhost:11434/api/generate", json=data)
|
||||
json_response = response.json()
|
||||
message = json_response["response"]
|
||||
print(message)
|
389
python-csi160/password-manager/password-manager.py
Normal file
389
python-csi160/password-manager/password-manager.py
Normal file
|
@ -0,0 +1,389 @@
|
|||
import pickle
|
||||
import sys
|
||||
import random
|
||||
import string
|
||||
|
||||
# The password list - We start with it populated for testing purposes
|
||||
entries = {'yahoo': {'username': 'johndoe', 'password': 'cus#u%S tu', 'url': 'https://www.yahoo.com'},
|
||||
'google': {'username': 'johndoe', 'password': '`q$$( #tABCD^ %fu#*W t', 'url': 'https://www.google.com'}}
|
||||
|
||||
# The password file name to store the data to
|
||||
password_file_name = "PasswordFile.pickle"
|
||||
|
||||
# The encryption key for the caesar cypher
|
||||
encryption_key = 16
|
||||
|
||||
menu_text = """
|
||||
What would you like to do:
|
||||
1. Open password file
|
||||
2. Add an entry
|
||||
3. Lookup an entry
|
||||
4. Save password file
|
||||
5. Quit program
|
||||
6. Print dictionary for testing
|
||||
7. Delete an entry
|
||||
8. Edit an entry
|
||||
Please enter a number (1-8)"""
|
||||
|
||||
def password_encrypt(unencrypted_message, key):
|
||||
"""Returns an encrypted message using a caesar cypher
|
||||
|
||||
:param unencryptedMessage (string)
|
||||
:param key (int) The offset to be used for the caesar cypher
|
||||
:return (string) The encrypted message
|
||||
"""
|
||||
result_string = ''
|
||||
min_limit = 32
|
||||
max_limit = 126
|
||||
for character in unencrypted_message:
|
||||
value = ord(character) - min_limit + key
|
||||
value = value % (max_limit - min_limit + 1)
|
||||
value = value + min_limit
|
||||
result_string = result_string + chr(value)
|
||||
return result_string
|
||||
|
||||
def password_decrypt(encrypted_message, key):
|
||||
"""Returns a decrypted message.
|
||||
:param encrypted_message (string):
|
||||
:param key (int) The offset that was used to encrypt the message
|
||||
:return (string): The decrypted message
|
||||
"""
|
||||
return password_encrypt(encrypted_message, -key)
|
||||
|
||||
def load_password_file():
|
||||
"""Loads a password file. The file must be in the same directory as the .py file
|
||||
"""
|
||||
global entries, encryption_key
|
||||
try:
|
||||
entries, encryption_key = pickle.load(open(password_file_name, "rb"))
|
||||
print(f"Password file '{password_file_name}' loaded successfully!")
|
||||
except FileNotFoundError:
|
||||
print(f"File '{password_file_name}' not found. Starting with an empty dictionary.")
|
||||
entries = {}
|
||||
except Exception as e:
|
||||
print(f"Error loading file: {e}")
|
||||
|
||||
def save_password_file():
|
||||
"""Saves a password file. The file will be created if it doesn't exist.
|
||||
"""
|
||||
try:
|
||||
pickle.dump((entries, encryption_key), open(password_file_name, "wb"))
|
||||
print(f"Password file '{password_file_name}' saved successfully!")
|
||||
except Exception as e:
|
||||
print(f"Error saving file: {e}")
|
||||
|
||||
def generate_random_password(length=12):
|
||||
"""Generates a random password that meets complexity requirements.
|
||||
|
||||
The generated password will:
|
||||
- Be at least 8 characters long (default 12)
|
||||
- Contain at least one uppercase letter
|
||||
- Contain at least one lowercase letter
|
||||
- Contain at least one digit
|
||||
- Contain at least one special character
|
||||
|
||||
:param length (int): Length of the password to generate (minimum 8)
|
||||
:return (string): A randomly generated password meeting all requirements
|
||||
"""
|
||||
if length < 8:
|
||||
length = 8 # Enforce minimum length
|
||||
|
||||
# Define character sets
|
||||
uppercase_letters = string.ascii_uppercase
|
||||
lowercase_letters = string.ascii_lowercase
|
||||
digits = string.digits
|
||||
special_chars = "!@#$%^&*()-_=+[]{}|;:,.<>?"
|
||||
|
||||
# Ensure we have at least one of each required character type
|
||||
password = [
|
||||
random.choice(uppercase_letters),
|
||||
random.choice(lowercase_letters),
|
||||
random.choice(digits),
|
||||
random.choice(special_chars)
|
||||
]
|
||||
|
||||
# Fill the rest with random characters from all allowed sets
|
||||
all_chars = uppercase_letters + lowercase_letters + digits + special_chars
|
||||
for _ in range(length - 4):
|
||||
password.append(random.choice(all_chars))
|
||||
|
||||
# Shuffle the password
|
||||
random.shuffle(password)
|
||||
|
||||
# Convert list to string
|
||||
return ''.join(password)
|
||||
|
||||
def check_password_complexity(password):
|
||||
"""Checks if a password meets complexity requirements.
|
||||
|
||||
Requirements:
|
||||
- At least 8 characters long
|
||||
- Contains at least one uppercase letter
|
||||
- Contains at least one lowercase letter
|
||||
- Contains at least one digit
|
||||
- Contains at least one special character
|
||||
|
||||
:param password (string): The password to check
|
||||
:return (tuple): (bool, string) - True if the password meets all requirements,
|
||||
False otherwise, and a message explaining the result
|
||||
"""
|
||||
# Check length
|
||||
if len(password) < 8:
|
||||
return False, "Password must be at least 8 characters long."
|
||||
|
||||
# Check for uppercase letter
|
||||
if not any(char.isupper() for char in password):
|
||||
return False, "Password must contain at least one uppercase letter."
|
||||
|
||||
# Check for lowercase letter
|
||||
if not any(char.islower() for char in password):
|
||||
return False, "Password must contain at least one lowercase letter."
|
||||
|
||||
# Check for digit
|
||||
if not any(char.isdigit() for char in password):
|
||||
return False, "Password must contain at least one digit."
|
||||
|
||||
# Check for special character
|
||||
special_chars = "!@#$%^&*()-_+=<>?/[]{}|\\~`"
|
||||
if not any(char in special_chars for char in password):
|
||||
return False, "Password must contain at least one special character."
|
||||
|
||||
return True, "Password meets all complexity requirements."
|
||||
|
||||
def add_entry():
|
||||
"""Adds an entry with an entry title, username, password and url
|
||||
Includes all user interface interactions to get the necessary information from the user
|
||||
"""
|
||||
try:
|
||||
entry_title = input("Enter entry title: ")
|
||||
username = input("Enter username: ")
|
||||
|
||||
# Explain password requirements
|
||||
print("\nPassword requirements:")
|
||||
print("- At least 8 characters long")
|
||||
print("- Contains at least one uppercase letter")
|
||||
print("- Contains at least one lowercase letter")
|
||||
print("- Contains at least one digit")
|
||||
print("- Contains at least one special character\n")
|
||||
|
||||
# Ask if user wants to generate a random password
|
||||
gen_password = input("Would you like to generate a random password? (y/n): ")
|
||||
|
||||
if gen_password.lower() == 'y':
|
||||
# Ask for desired password length
|
||||
try:
|
||||
length = int(input("Enter desired password length (minimum 8, default 12): ") or "12")
|
||||
if length < 8:
|
||||
print("Password length must be at least 8. Setting to 8.")
|
||||
length = 8
|
||||
except ValueError:
|
||||
print("Invalid input. Using default length of 12.")
|
||||
length = 12
|
||||
|
||||
# Generate the password
|
||||
password = generate_random_password(length)
|
||||
print(f"Generated password: {password}")
|
||||
is_valid = True
|
||||
else:
|
||||
# Get and validate manual password
|
||||
print("Enter your password manually:")
|
||||
while True:
|
||||
password = input("Enter password: ")
|
||||
is_valid, message = check_password_complexity(password)
|
||||
if is_valid:
|
||||
print(message)
|
||||
break
|
||||
else:
|
||||
print(message)
|
||||
print("Please try again with a stronger password.")
|
||||
|
||||
url = input("Enter URL: ")
|
||||
|
||||
# Encrypt the password
|
||||
encrypted_password = password_encrypt(password, encryption_key)
|
||||
|
||||
# Add the new entry to the entries dictionary
|
||||
entries[entry_title] = {
|
||||
'username': username,
|
||||
'password': encrypted_password,
|
||||
'url': url
|
||||
}
|
||||
|
||||
print(f"Entry '{entry_title}' added successfully!")
|
||||
except Exception as e:
|
||||
print(f"Error adding entry: {e}")
|
||||
|
||||
def print_entry():
|
||||
"""Asks the user for the name of the entry and prints all related information in a pretty format.
|
||||
Includes all information about an entry.
|
||||
"""
|
||||
try:
|
||||
print("Which entry do you want to lookup the information for?")
|
||||
for key in entries:
|
||||
print(key)
|
||||
|
||||
entry = input('Enter entry name: ')
|
||||
|
||||
# Check if the entry exists
|
||||
if entry in entries:
|
||||
entry_data = entries[entry]
|
||||
|
||||
# Decrypt the password
|
||||
decrypted_password = password_decrypt(entry_data['password'], encryption_key)
|
||||
|
||||
# Print the entry information
|
||||
print("\n--- Entry Information ---")
|
||||
print(f"Entry: {entry}")
|
||||
print(f"Username: {entry_data['username']}")
|
||||
print(f"Password: {decrypted_password}")
|
||||
print(f"URL: {entry_data['url']}")
|
||||
print("------------------------\n")
|
||||
else:
|
||||
print(f"Entry '{entry}' not found!")
|
||||
except KeyError:
|
||||
print(f"Error: The entry does not exist or has incomplete data.")
|
||||
except Exception as e:
|
||||
print(f"Error looking up entry: {e}")
|
||||
|
||||
def delete_entry():
|
||||
"""Deletes an entry from the password manager.
|
||||
Asks the user for the entry name to delete and removes it if it exists.
|
||||
|
||||
This is additional feature #1.
|
||||
"""
|
||||
try:
|
||||
print("Which entry do you want to delete?")
|
||||
for key in entries:
|
||||
print(key)
|
||||
|
||||
entry = input('Enter entry name: ')
|
||||
|
||||
# Check if the entry exists
|
||||
if entry in entries:
|
||||
# Ask for confirmation
|
||||
confirm = input(f"Are you sure you want to delete '{entry}'? (y/n): ")
|
||||
if confirm.lower() == 'y':
|
||||
# Remove the entry
|
||||
del entries[entry]
|
||||
print(f"Entry '{entry}' deleted successfully!")
|
||||
else:
|
||||
print("Deletion cancelled.")
|
||||
else:
|
||||
print(f"Entry '{entry}' not found!")
|
||||
except Exception as e:
|
||||
print(f"Error deleting entry: {e}")
|
||||
|
||||
def edit_entry():
|
||||
"""Allows the user to edit an existing entry in the password manager.
|
||||
The user can update the username, password, and/or URL.
|
||||
|
||||
This is additional feature #2.
|
||||
"""
|
||||
try:
|
||||
print("Which entry do you want to edit?")
|
||||
for key in entries:
|
||||
print(key)
|
||||
|
||||
entry = input('Enter entry name: ')
|
||||
|
||||
# Check if the entry exists
|
||||
if entry in entries:
|
||||
entry_data = entries[entry]
|
||||
print(f"\nEditing entry: {entry}")
|
||||
|
||||
# Get current values for reference
|
||||
current_username = entry_data['username']
|
||||
current_url = entry_data['url']
|
||||
|
||||
# Update username
|
||||
new_username = input(f"Enter new username (current: {current_username}) or press Enter to keep current: ")
|
||||
if new_username:
|
||||
entry_data['username'] = new_username
|
||||
|
||||
# Update password
|
||||
update_password = input("Do you want to update the password? (y/n): ")
|
||||
if update_password.lower() == 'y':
|
||||
# Explain password requirements
|
||||
print("\nPassword requirements:")
|
||||
print("- At least 8 characters long")
|
||||
print("- Contains at least one uppercase letter")
|
||||
print("- Contains at least one lowercase letter")
|
||||
print("- Contains at least one digit")
|
||||
print("- Contains at least one special character (!@#$%^&*()-_+=<>?/[]{}|\\~`)\n")
|
||||
|
||||
# Ask if user wants to generate a random password
|
||||
gen_password = input("Would you like to generate a random password? (y/n): ")
|
||||
|
||||
if gen_password.lower() == 'y':
|
||||
# Ask for desired password length
|
||||
try:
|
||||
length = int(input("Enter desired password length (minimum 8, default 12): ") or "12")
|
||||
if length < 8:
|
||||
print("Password length must be at least 8. Setting to 8.")
|
||||
length = 8
|
||||
except ValueError:
|
||||
print("Invalid input. Using default length of 12.")
|
||||
length = 12
|
||||
|
||||
# Generate the password
|
||||
new_password = generate_random_password(length)
|
||||
print(f"Generated password: {new_password}")
|
||||
|
||||
# Encrypt the new password
|
||||
entry_data['password'] = password_encrypt(new_password, encryption_key)
|
||||
else:
|
||||
# Get and validate new password manually
|
||||
while True:
|
||||
new_password = input("Enter new password: ")
|
||||
is_valid, message = check_password_complexity(new_password)
|
||||
if is_valid:
|
||||
print(message)
|
||||
# Encrypt the new password
|
||||
entry_data['password'] = password_encrypt(new_password, encryption_key)
|
||||
break
|
||||
else:
|
||||
print(message)
|
||||
print("Please try again with a stronger password.")
|
||||
|
||||
# Update URL
|
||||
new_url = input(f"Enter new URL (current: {current_url}) or press Enter to keep current: ")
|
||||
if new_url:
|
||||
entry_data['url'] = new_url
|
||||
|
||||
print(f"Entry '{entry}' updated successfully!")
|
||||
else:
|
||||
print(f"Entry '{entry}' not found!")
|
||||
except Exception as e:
|
||||
print(f"Error editing entry: {e}")
|
||||
|
||||
def end_program():
|
||||
"""Exits the program.
|
||||
"""
|
||||
sys.exit()
|
||||
|
||||
def print_dictionary():
|
||||
"""Prints the current entries dictionary.
|
||||
For testing purposes only.
|
||||
"""
|
||||
print(entries)
|
||||
|
||||
# Menu dictionary mapping user choices to functions
|
||||
menu_dict = {'1': load_password_file,
|
||||
'2': add_entry,
|
||||
'3': print_entry,
|
||||
'4': save_password_file,
|
||||
'5': end_program,
|
||||
'6': print_dictionary,
|
||||
'7': delete_entry,
|
||||
'8': edit_entry}
|
||||
|
||||
# Main program loop
|
||||
while True:
|
||||
try:
|
||||
user_choice = input(menu_text)
|
||||
if user_choice in menu_dict and menu_dict[user_choice]:
|
||||
menu_dict[user_choice]()
|
||||
else:
|
||||
print('Not a valid choice')
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
14
python-csi160/week01/firstprogram.py
Normal file
14
python-csi160/week01/firstprogram.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
|
||||
# this program says hello and asks for name, age
|
||||
|
||||
|
||||
print('Hello world!')
|
||||
print('What is your name?')
|
||||
myName = input()
|
||||
print('It is good to meet you, ' + myName)
|
||||
print('The length of your name is:')
|
||||
print(len(myName))
|
||||
print('What is your age?')
|
||||
myAge = input()
|
||||
print('You will be ' + str(int(myAge) + 1) + ' in a year.')
|
||||
|
6
python-csi160/week01/pycharm_install.md
Normal file
6
python-csi160/week01/pycharm_install.md
Normal file
|
@ -0,0 +1,6 @@
|
|||
Install from here:
|
||||
https://www.jetbrains.com/pycharm/download
|
||||
|
||||
Get license from here:
|
||||
https://www.jetbrains.com/community/education
|
||||
|
10
python-csi160/week02/Week-2Practice-Problems/part1.py
Normal file
10
python-csi160/week02/Week-2Practice-Problems/part1.py
Normal file
|
@ -0,0 +1,10 @@
|
|||
# This program reads two numbers and prints their sum:
|
||||
a = int(input('Enter first number: '))
|
||||
b = int(input('Enter second number: '))
|
||||
c = int(input('Enter third number: '))
|
||||
|
||||
print(a + b + c)
|
||||
|
||||
# Can you change it so it can read and sum three numbers?
|
||||
|
||||
|
5
python-csi160/week02/Week-2Practice-Problems/part2.py
Normal file
5
python-csi160/week02/Week-2Practice-Problems/part2.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
# Get the user's name
|
||||
name = input('Enter your name:\n')
|
||||
|
||||
# Print hello statement
|
||||
print("Hello, " + name + "!")
|
7
python-csi160/week02/Week-2Practice-Problems/part3.py
Normal file
7
python-csi160/week02/Week-2Practice-Problems/part3.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
# Read an integer:
|
||||
number = int(input('Enter a number:\n'))
|
||||
|
||||
# Print output for next and previous that matches the instructions
|
||||
|
||||
print("The next number for the number " + str(number) + " is " + str(number + 1))
|
||||
print("The previous number for the number " + str(number) + " is " + str(number - 1))
|
7
python-csi160/week02/Week-2Practice-Problems/part4.py
Normal file
7
python-csi160/week02/Week-2Practice-Problems/part4.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
# Read the numbers b and h like this:
|
||||
base = float(input('Enter Base: '))
|
||||
height = float(input('Enter Height: '))
|
||||
|
||||
# Print the result with print()
|
||||
area = 0.5 * (base * height)
|
||||
print(area)
|
7
python-csi160/week02/Week-2Practice-Problems/part5.py
Normal file
7
python-csi160/week02/Week-2Practice-Problems/part5.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
# Read the numbers like this:
|
||||
num_students = int(input("Number of students: "))
|
||||
num_apples = int(input("Number of apples: "))
|
||||
|
||||
# Print the result with print()
|
||||
print(num_apples // num_students)
|
||||
print(num_apples % num_students)
|
9
python-csi160/week02/Week-2Practice-Problems/part6.py
Normal file
9
python-csi160/week02/Week-2Practice-Problems/part6.py
Normal file
|
@ -0,0 +1,9 @@
|
|||
# Read an integer:
|
||||
seconds_past_midnight = int(input())
|
||||
|
||||
|
||||
full_hours_past_midnight = (seconds_past_midnight // 3600) % 24
|
||||
full_minutes_past_midnight = (seconds_past_midnight // 60) % 1440
|
||||
|
||||
print (full_hours_past_midnight, full_minutes_past_midnight)
|
||||
|
11
python-csi160/week02/Week-2Practice-Problems/part7.py
Normal file
11
python-csi160/week02/Week-2Practice-Problems/part7.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
# Input the data
|
||||
cupcake_dollars = int(input())
|
||||
cupcake_cents = int(input())
|
||||
num_cupcakes = int(input())
|
||||
|
||||
# Your code here
|
||||
|
||||
total_cost_cents = (((cupcake_dollars * 100) + cupcake_cents) * num_cupcakes)
|
||||
total_cost_dollars = total_cost_cents // 100
|
||||
total_cost_cents = total_cost_cents % 100
|
||||
print(total_cost_dollars, total_cost_cents)
|
61
python-csi160/week02/croce_week02_lab.py
Normal file
61
python-csi160/week02/croce_week02_lab.py
Normal file
|
@ -0,0 +1,61 @@
|
|||
"""
|
||||
Author: Charlotte Croce
|
||||
Class: CSI160
|
||||
Assignment: Week 2: Lab - Conversation with a Computer
|
||||
Due Date: 1/27/25
|
||||
|
||||
Certification of Authenticity:
|
||||
I certify that this is entirely my own work, except where I have given
|
||||
fully-documented references to the work of others. I understand the definition
|
||||
and consequences of plagiarism and acknowledge that the assessor of this
|
||||
assignment may, for the purpose of assessing this assignment:
|
||||
- Reproduce this assignment and provide a copy to another member of academic
|
||||
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
|
||||
- service (which may then retain a copy of this assignment on its database for
|
||||
- the purpose of future plagiarism checking)
|
||||
"""
|
||||
|
||||
|
||||
"""
|
||||
Write a program that has a conversation with the user. The program must ask for strings, integers and floats as input.
|
||||
The program must ask for at least 4 different inputs from the user. The program must reuse atleast 4 of these inputs in what it displays on the screen.
|
||||
The program must perform at least 2 arithmetic operations on the numbers the user inputs. Please turn in your .py file.
|
||||
"""
|
||||
|
||||
print("hello! i am a robot. beep beep")
|
||||
# ask for name
|
||||
name = input("what is your name?")
|
||||
# say hi and ask for favorite color
|
||||
favorite_color = input("hello " + name + ", what is your favorite color?")
|
||||
# ask if user likes ice cream
|
||||
user_likes_icecream = input("mine too, do you like Ice Cream?")
|
||||
# answer differently based on whether user answers 'yes' or not
|
||||
if(user_likes_icecream.lower() == "yes"):
|
||||
print("me too!")
|
||||
else:
|
||||
print("okay, not for everyone")
|
||||
# ask for age
|
||||
age = int(input(name + ", how old are you?"))
|
||||
# ask for number of siblings
|
||||
siblings = int(input("...and how many siblings do you have?"))
|
||||
# display how many kids you a part of; ask if favorite color is shared by anyone in the house
|
||||
is_favorite_color_of_house = input("that means you are one of " + str(siblings + 1) + " kid(s). is " + favorite_color + " the favorite color of anyone else in your house?")
|
||||
# answer differently based on whether user answers 'yes' or not
|
||||
if(is_favorite_color_of_house.lower() == "yes"):
|
||||
print("good you can agree")
|
||||
else:
|
||||
print("too bad")
|
||||
# ask for parent's age
|
||||
parent_age = int(input('how old is one of your parents?'))
|
||||
# respond with age of parents when they had the user
|
||||
print("that means they were likely " + str(parent_age - age) + " when they had you")
|
||||
# ask for GPA
|
||||
gpa = float(input("what is your GPA[4-point scale]?"))
|
||||
# answer differently based on the GPA value entered
|
||||
if(gpa >= 3.5):
|
||||
print("great job!")
|
||||
elif(gpa >= 2.5):
|
||||
print("keep it up!")
|
||||
else:
|
||||
print("time to study more!")
|
||||
print("goodbye!")
|
5
python-csi160/week03/Week-3Practice-Problems/part1.py
Normal file
5
python-csi160/week03/Week-3Practice-Problems/part1.py
Normal file
|
@ -0,0 +1,5 @@
|
|||
number = int(input('Enter a two digit number: '))
|
||||
|
||||
# Print the two digits of the number seperated by a space
|
||||
|
||||
print((number // 10),(number % 10))
|
7
python-csi160/week03/Week-3Practice-Problems/part2.py
Normal file
7
python-csi160/week03/Week-3Practice-Problems/part2.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
# Read an integer:
|
||||
number = int(input('Enter a two digit number: '))
|
||||
|
||||
# Print the digits reversed
|
||||
|
||||
|
||||
print(str(number % 10) + str(number // 10))
|
7
python-csi160/week03/Week-3Practice-Problems/part3.py
Normal file
7
python-csi160/week03/Week-3Practice-Problems/part3.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
# Read an integer:
|
||||
number = int(input('Enter a 3 digit number: '))
|
||||
|
||||
# Print the sum of the digits:
|
||||
|
||||
a = ((number // 100) + (number % 100 // 10) + (number % 10))
|
||||
print(a)
|
46
python-csi160/week03/Week-3Practice-Problems/part4.py
Normal file
46
python-csi160/week03/Week-3Practice-Problems/part4.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
def days_to_hours(days):
|
||||
""" Converts days to hours
|
||||
|
||||
Arguments:
|
||||
days (int): number of days as an integer
|
||||
|
||||
Return:
|
||||
number of hours (int)
|
||||
|
||||
Assumptions:
|
||||
days must be an int
|
||||
"""
|
||||
return days * 24
|
||||
|
||||
print('Days to hours:', days_to_hours(3))
|
||||
hours = days_to_hours(2)
|
||||
|
||||
|
||||
def days_to_minutes(days):
|
||||
""" Converts days to minutes
|
||||
|
||||
Arguments:
|
||||
days (int): number of days as an integer
|
||||
|
||||
Return:
|
||||
number of minutes (int)
|
||||
|
||||
Assumptions:
|
||||
days must be an int
|
||||
"""
|
||||
return days_to_hours(days) * 60
|
||||
|
||||
|
||||
def days_to_seconds(days):
|
||||
""" Converts days to seconds
|
||||
|
||||
Arguments:
|
||||
days (int): number of days as an integer
|
||||
|
||||
Return:
|
||||
number of seconds (int)
|
||||
|
||||
Assumptions:
|
||||
days must be an int
|
||||
"""
|
||||
return days_to_minutes(days) * 60
|
14
python-csi160/week03/Week-3Practice-Problems/part5.py
Normal file
14
python-csi160/week03/Week-3Practice-Problems/part5.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
def celsius_to_fahrenheit(temperature_in_celcius):
|
||||
"""This function converts a number from Celcius to Fahrenheit
|
||||
|
||||
Arguments:
|
||||
temperature_in_celcius (float): The remperature to convert
|
||||
|
||||
Returns:
|
||||
float: The temperature in Fahrenheit
|
||||
|
||||
Assumptions:
|
||||
Assumes that temperature_in_celcius is a float
|
||||
|
||||
"""
|
||||
return (temperature_in_celcius * 1.8) + 32
|
13
python-csi160/week03/Week-3Practice-Problems/part6.py
Normal file
13
python-csi160/week03/Week-3Practice-Problems/part6.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
from math import pi # This lets you refer to pi in your code
|
||||
|
||||
|
||||
def volume_cone(radius, height):
|
||||
"""Computes volume of a cone
|
||||
|
||||
:param radius: positive float
|
||||
|
||||
:param height: positive float
|
||||
|
||||
:return: volume of given cone
|
||||
"""
|
||||
return 1/3 * pi * (radius*radius) * height
|
87
python-csi160/week03/croce_week03_lab.py
Normal file
87
python-csi160/week03/croce_week03_lab.py
Normal file
|
@ -0,0 +1,87 @@
|
|||
"""
|
||||
|
||||
Author: Charlotte Croce
|
||||
Class: CSI 160
|
||||
Assignment: Week 3 Lab
|
||||
Due Date: 2/3/25
|
||||
|
||||
Certification of Authenticity:
|
||||
I certify that this is entirely my own work, except where I have given
|
||||
fully-documented references to the work of others. I understand the definition
|
||||
and consequences of plagiarism and acknowledge that the assessor of this
|
||||
assignment may, for the purpose of assessing this assignment:
|
||||
- Reproduce this assignment and provide a copy to another member of academic
|
||||
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
|
||||
- service (which may then retain a copy of this assignment on its database for
|
||||
- the purpose of future plagiarism checking)
|
||||
"""
|
||||
|
||||
from math import pi
|
||||
|
||||
|
||||
def fahrenheit_to_celcius(temperature_in_fahrenheit):
|
||||
"""This function converts a number from Fahrenheit to Celcius
|
||||
|
||||
:param temperature_in_fahrenheit (float): The temperature to convert
|
||||
|
||||
:return (float): The temperature in Fahrenheit
|
||||
|
||||
Assumptions: temperature_in_fahrenheit is a float
|
||||
|
||||
"""
|
||||
try:
|
||||
return round(((temperature_in_fahrenheit - 32) * 5 / 9), 2)
|
||||
except TypeError:
|
||||
print("invalid input: input floats please")
|
||||
return
|
||||
|
||||
celcius_temp = float(input("---\n1. temp in fahrenheit: "))
|
||||
print("1. coverted to celcius:", fahrenheit_to_celcius(celcius_temp))
|
||||
|
||||
|
||||
def cylinder_volume(radius, height):
|
||||
"""Computes volume of a cylinder
|
||||
|
||||
:param radius: positive float
|
||||
|
||||
:param height: positive float
|
||||
|
||||
:return: volume of cylinder
|
||||
|
||||
Assumptions: inputs are floats
|
||||
"""
|
||||
try:
|
||||
return round((pi * (radius*radius) * height), 2)
|
||||
except TypeError:
|
||||
print("invalid input: input floats please")
|
||||
return
|
||||
|
||||
cylinder_radius = float(input("---\n2. cylinder radius: "))
|
||||
cylinder_height = float(input("2. cylinder height: "))
|
||||
print("2. cylinder volume:", cylinder_volume(cylinder_radius, cylinder_height))
|
||||
|
||||
|
||||
def surface_area_rectangular_prism(length, width, height):
|
||||
"""Computes surface area of a rectangular prism
|
||||
|
||||
:param length: positive float
|
||||
|
||||
:param width: positive float
|
||||
|
||||
:param height: positive float
|
||||
|
||||
:return: surface area of a rectangular prism
|
||||
|
||||
Assumptions: inputs are floats
|
||||
"""
|
||||
try:
|
||||
return round((2 * ((length*width)+(length*height)+(width*height))), 2)
|
||||
except TypeError:
|
||||
print("invalid input: input floats please")
|
||||
return
|
||||
|
||||
rectangular_prism_length = float(input("---\n3. rectangular prism length: "))
|
||||
rectangular_prism_width = float(input("3. rectangular prism width: "))
|
||||
rectangular_prism_height = float(input("3. rectangular prism height: "))
|
||||
print("3. rectangular prism surface area:", surface_area_rectangular_prism(rectangular_prism_length,rectangular_prism_width,rectangular_prism_height))
|
||||
|
8
python-csi160/week04/Week-4Practice-Problems/part1.py
Normal file
8
python-csi160/week04/Week-4Practice-Problems/part1.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
number = int(input('Enter an integer: '))
|
||||
|
||||
# Determine odd or even
|
||||
|
||||
if number % 2 == 0:
|
||||
print("even")
|
||||
else:
|
||||
print("odd")
|
26
python-csi160/week04/Week-4Practice-Problems/part10.py
Normal file
26
python-csi160/week04/Week-4Practice-Problems/part10.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
def is_legal_bishop_move(initial_x, initial_y, final_x, final_y):
|
||||
"""Returns True / False whether a given move is a legal move for the Bishop.
|
||||
|
||||
This function assumes that there are no other pieces on the board.
|
||||
|
||||
:param initial_x: (int) Horizontal 1-8
|
||||
:param initial_y: (int) Vertical 1-8
|
||||
:param final_x: (int) Horizontal 1-8
|
||||
:param final_y: (int) Vertical 1-8
|
||||
:return: (bool) True / False if it is a legal move
|
||||
"""
|
||||
# Complete this function
|
||||
if initial_x == final_x and initial_y == final_y:
|
||||
return False
|
||||
return abs(initial_x - final_x) == abs(initial_y - final_y)
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('(4, 4, 3, 5) It is', is_legal_bishop_move(4, 4, 3, 5), 'that this is a legal move')
|
||||
print('(1, 4, 4, 7) It is', is_legal_bishop_move(1, 4, 4, 7), 'that this is a legal move')
|
||||
print('(5, 4, 2, 1) It is', is_legal_bishop_move(5, 4, 2, 1), 'that this is a legal move')
|
||||
print('(5, 4, 1, 1) It is', is_legal_bishop_move(5, 4, 1, 1), 'that this is a legal move')
|
||||
print('(5, 4, 6, 4) It is', is_legal_bishop_move(5, 4, 6, 4), 'that this is a legal move')
|
||||
print('(1, 1, 1, 1) It is', is_legal_bishop_move(1, 1, 1, 1), 'that this is a legal move')
|
||||
|
||||
|
12
python-csi160/week04/Week-4Practice-Problems/part2.py
Normal file
12
python-csi160/week04/Week-4Practice-Problems/part2.py
Normal file
|
@ -0,0 +1,12 @@
|
|||
|
||||
number1 = int(input('Enter an integer: '))
|
||||
number2 = int(input('Enter an integer: '))
|
||||
|
||||
|
||||
# Print the smaller number
|
||||
|
||||
|
||||
if number1 < number2:
|
||||
print(number1)
|
||||
else:
|
||||
print(number2)
|
9
python-csi160/week04/Week-4Practice-Problems/part3.py
Normal file
9
python-csi160/week04/Week-4Practice-Problems/part3.py
Normal file
|
@ -0,0 +1,9 @@
|
|||
num = int(input('Enter a number: '))
|
||||
|
||||
# Print out result
|
||||
if num > 0:
|
||||
print("1")
|
||||
elif num < 0:
|
||||
print("-1")
|
||||
else:
|
||||
print("0")
|
7
python-csi160/week04/Week-4Practice-Problems/part4.py
Normal file
7
python-csi160/week04/Week-4Practice-Problems/part4.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
year = int(input('Enter the year: '))
|
||||
|
||||
# Prints Yes or No based on if year is in the 21st century
|
||||
if year >= 2001 and year <= 2100:
|
||||
print("YES")
|
||||
else:
|
||||
print("NO")
|
16
python-csi160/week04/Week-4Practice-Problems/part5.py
Normal file
16
python-csi160/week04/Week-4Practice-Problems/part5.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
def one_positive(num1, num2):
|
||||
"""Given two non-zero integers, returns True if exactly one of
|
||||
them is positive and returns False otherwise.
|
||||
|
||||
:param num1: non-zero integer
|
||||
:param num2: non-zero integer
|
||||
:return: True / False
|
||||
"""
|
||||
# Complete this function
|
||||
return (num1 > 0) ^ (num2 > 0)
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('(5, 7) It is', one_positive(5, 7), 'that only one of these numbers is positive')
|
||||
print('(-5, -7) It is', one_positive(-5, -7), 'that only one of these numbers is positive')
|
||||
print('(5, -7) It is', one_positive(5, -7), 'that only one of these numbers is positive')
|
27
python-csi160/week04/Week-4Practice-Problems/part6.py
Normal file
27
python-csi160/week04/Week-4Practice-Problems/part6.py
Normal file
|
@ -0,0 +1,27 @@
|
|||
def ascending_digits(num):
|
||||
"""Given a three-digit integer X consisting of three different digits,
|
||||
returns True if its three digits are going in an ascending
|
||||
order from left to right and returns False otherwise.
|
||||
|
||||
:param num: three digit integer
|
||||
:return: True / False
|
||||
"""
|
||||
# Complete this function
|
||||
# Hint: assign variables for each digit first
|
||||
# then build the comparison
|
||||
|
||||
a = num // 100
|
||||
b = num % 100 // 10
|
||||
c = num % 10
|
||||
|
||||
ascending=False
|
||||
if a < b and b < c:
|
||||
ascending = True
|
||||
|
||||
return ascending
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('(136) It is', ascending_digits(136), 'that the digits are ascending')
|
||||
print('(462) It is', ascending_digits(462), 'that the digits are ascending')
|
||||
print('(823) It is', ascending_digits(823), 'that the digits are ascending')
|
20
python-csi160/week04/Week-4Practice-Problems/part7.py
Normal file
20
python-csi160/week04/Week-4Practice-Problems/part7.py
Normal file
|
@ -0,0 +1,20 @@
|
|||
month = int(input('Enter the month: '))
|
||||
|
||||
|
||||
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
|
||||
print("31")
|
||||
elif month == 4 or month == 6 or month == 9 or month == 11:
|
||||
print("30")
|
||||
else:
|
||||
print("28")
|
||||
|
||||
'''
|
||||
month = month.lower()
|
||||
|
||||
if month == "january" or month == "march" or month == "may" or month == "july" or month == "august" or month == "october" or month == "december":
|
||||
print("31")
|
||||
elif month == "april" or month == "june" or month == "september" or month == "november":
|
||||
print("30")
|
||||
else:
|
||||
print("28")
|
||||
'''
|
18
python-csi160/week04/Week-4Practice-Problems/part8.py
Normal file
18
python-csi160/week04/Week-4Practice-Problems/part8.py
Normal file
|
@ -0,0 +1,18 @@
|
|||
def is_legal_rook_move(initial_x, initial_y, final_x, final_y):
|
||||
"""Returns True / False whether a given move is a legal move for the Rook.
|
||||
|
||||
This function assumes that there are no other pieces on the board.
|
||||
|
||||
:param initial_x: (int) Horizontal 1-8
|
||||
:param initial_y: (int) Vertical 1-8
|
||||
:param final_x: (int) Horizontal 1-8
|
||||
:param final_y: (int) Vertical 1-8
|
||||
:return: (bool) True / False if it is a legal move
|
||||
"""
|
||||
# Complete this function
|
||||
return (initial_x != final_x) ^ (initial_y != final_y)
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('(4, 4, 5, 5) It is', is_legal_rook_move(4, 4, 5, 5), 'that this is a legal move')
|
||||
print('(1, 4, 6, 4) It is', is_legal_rook_move(1, 4, 6, 4), 'that this is a legal move')
|
||||
print('(1, 4, 1, 7) It is', is_legal_rook_move(1, 4, 1, 7), 'that this is a legal move')
|
24
python-csi160/week04/Week-4Practice-Problems/part9.py
Normal file
24
python-csi160/week04/Week-4Practice-Problems/part9.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
def is_legal_king_move(initial_x, initial_y, final_x, final_y):
|
||||
"""Returns True / False whether a given move is a legal move for the King.
|
||||
|
||||
This function assumes that there are no other pieces on the board.
|
||||
|
||||
:param initial_x: (int) Horizontal 1-8
|
||||
:param initial_y: (int) Vertical 1-8
|
||||
:param final_x: (int) Horizontal 1-8
|
||||
:param final_y: (int) Vertical 1-8
|
||||
:return: (bool) True / False if it is a legal move
|
||||
"""
|
||||
# Complete this function
|
||||
|
||||
if initial_x == final_x and initial_y == final_y:
|
||||
return False
|
||||
return abs(initial_x - final_x) <= 1 and abs(initial_y - final_y) <= 1
|
||||
|
||||
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('(4, 4, 5, 5) It is', is_legal_king_move(4, 4, 5, 5), 'that this is a legal move')
|
||||
print('(1, 4, 6, 4) It is', is_legal_king_move(1, 4, 6, 4), 'that this is a legal move')
|
||||
print('(1, 4, 1, 3) It is', is_legal_king_move(1, 4, 1, 3), 'that this is a legal move')
|
14
python-csi160/week04/week04_labs/croce_week04_lab_01.py
Normal file
14
python-csi160/week04/week04_labs/croce_week04_lab_01.py
Normal file
|
@ -0,0 +1,14 @@
|
|||
|
||||
#1. Implement a voting test. The user enters their age and then the program prints either,
|
||||
# “You must be 18 to vote” or “You are of voting age”.
|
||||
|
||||
def voting_test():
|
||||
age = int(input("age: "))
|
||||
if age >= 18:
|
||||
print("You are of voting age")
|
||||
else:
|
||||
print("You must be 18 to vote")
|
||||
|
||||
|
||||
voting_test()
|
||||
|
25
python-csi160/week04/week04_labs/croce_week04_lab_02.py
Normal file
25
python-csi160/week04/week04_labs/croce_week04_lab_02.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
|
||||
#2. Ask the user to enter a grade percentage. Convert the grade into a letter
|
||||
# grade using the official Champlain College grading scale. For instance, if the user
|
||||
# types 99 then print A+.
|
||||
|
||||
def grade_to_letter():
|
||||
grade = int(input("GPA (100pt scale): "))
|
||||
if grade >= 97: letter = "A+"
|
||||
elif grade >= 93: letter = "A"
|
||||
elif grade >= 90: letter = "A-"
|
||||
elif grade >= 87: letter = "B+"
|
||||
elif grade >= 83: letter = "B"
|
||||
elif grade >= 80: letter = "B-"
|
||||
elif grade >= 77: letter = "C+"
|
||||
elif grade >= 73: letter = "C"
|
||||
elif grade >= 70: letter = "C-"
|
||||
elif grade >= 67: letter = "C+"
|
||||
elif grade >= 63: letter = "C"
|
||||
elif grade >= 60: letter = "C-"
|
||||
else: letter = "F"
|
||||
print(letter)
|
||||
|
||||
|
||||
grade_to_letter()
|
||||
|
16
python-csi160/week04/week04_labs/croce_week04_lab_03.py
Normal file
16
python-csi160/week04/week04_labs/croce_week04_lab_03.py
Normal file
|
@ -0,0 +1,16 @@
|
|||
|
||||
# 3. Write a program that asks for two numbers. If the sum of the numbers is greater than
|
||||
# 100, print "They add up to a big number" if it is less than/equal to 100 than print "They add up to ____".
|
||||
|
||||
def add_to_big_number():
|
||||
num1 = int(input("num1: "))
|
||||
num2 = int(input("num2: "))
|
||||
sum = num1 + num2
|
||||
if sum > 100:
|
||||
print("They add up to a big number")
|
||||
else:
|
||||
print("They add up to " + str(sum))
|
||||
|
||||
|
||||
add_to_big_number()
|
||||
|
17
python-csi160/week04/week04_labs/croce_week04_lab_04.py
Normal file
17
python-csi160/week04/week04_labs/croce_week04_lab_04.py
Normal file
|
@ -0,0 +1,17 @@
|
|||
|
||||
#4. Implement a random number guessing game. The computer will pick a number at random from
|
||||
# 0-9, the user will be asked to guess the number. Inform the user if they get the answer correct.
|
||||
|
||||
from random import randint
|
||||
|
||||
def random_number_game():
|
||||
num = randint(0,9)
|
||||
guess = int(input("random number guess(0-9): "))
|
||||
if guess == num:
|
||||
print("correct! you win")
|
||||
else:
|
||||
print("incorrect, the anser was", num)
|
||||
|
||||
|
||||
random_number_game()
|
||||
|
13
python-csi160/week04/week04_labs/croce_week04_lab_05.py
Normal file
13
python-csi160/week04/week04_labs/croce_week04_lab_05.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
|
||||
# 5. Write a function to compute whether a given year is a leap year in the Hebrew calendar.
|
||||
|
||||
def is_hebrew_leap_year(year):
|
||||
year_of_cycle = year % 19
|
||||
if year_of_cycle in (3, 6, 8, 11, 14, 17, 19):
|
||||
print(str(year) + " is year number " + str(year_of_cycle) + " of the cycle and is therefore a leap year.")
|
||||
else:
|
||||
print(str(year) + " is year number " + str(year_of_cycle) + " of the cycle and is therefore NOT a leap year.")
|
||||
|
||||
|
||||
is_hebrew_leap_year(5779)
|
||||
is_hebrew_leap_year(5780)
|
85
python-csi160/week04/week04_labs/croce_week04_labs_ALL.py
Normal file
85
python-csi160/week04/week04_labs/croce_week04_labs_ALL.py
Normal file
|
@ -0,0 +1,85 @@
|
|||
|
||||
#1. Implement a voting test. The user enters their age and then the program prints either,
|
||||
# “You must be 18 to vote” or “You are of voting age”.
|
||||
|
||||
def voting_test():
|
||||
age = int(input("age: "))
|
||||
if age >= 18:
|
||||
print("You are of voting age")
|
||||
else:
|
||||
print("You must be 18 to vote")
|
||||
|
||||
|
||||
voting_test()
|
||||
|
||||
|
||||
#2. Ask the user to enter a grade percentage. Convert the grade into a letter
|
||||
# grade using the official Champlain College grading scale. For instance, if the user
|
||||
# types 99 then print A+.
|
||||
|
||||
def grade_to_letter():
|
||||
grade = int(input("GPA (100pt scale): "))
|
||||
if grade >= 97: letter = "A+"
|
||||
elif grade >= 93: letter = "A"
|
||||
elif grade >= 90: letter = "A-"
|
||||
elif grade >= 87: letter = "B+"
|
||||
elif grade >= 83: letter = "B"
|
||||
elif grade >= 80: letter = "B-"
|
||||
elif grade >= 77: letter = "C+"
|
||||
elif grade >= 73: letter = "C"
|
||||
elif grade >= 70: letter = "C-"
|
||||
elif grade >= 67: letter = "C+"
|
||||
elif grade >= 63: letter = "C"
|
||||
elif grade >= 60: letter = "C-"
|
||||
else: letter = "F"
|
||||
print(letter)
|
||||
|
||||
|
||||
grade_to_letter()
|
||||
|
||||
|
||||
# 3. Write a program that asks for two numbers. If the sum of the numbers is greater than
|
||||
# 100, print "They add up to a big number" if it is less than/equal to 100 than print "They add up to ____".
|
||||
|
||||
def add_to_big_number():
|
||||
num1 = int(input("num1: "))
|
||||
num2 = int(input("num2: "))
|
||||
sum = num1 + num2
|
||||
if sum > 100:
|
||||
print("They add up to a big number")
|
||||
else:
|
||||
print("They add up to " + str(sum))
|
||||
|
||||
|
||||
add_to_big_number()
|
||||
|
||||
|
||||
#4. Implement a random number guessing game. The computer will pick a number at random from
|
||||
# 0-9, the user will be asked to guess the number. Inform the user if they get the answer correct.
|
||||
|
||||
from random import randint
|
||||
|
||||
def random_number_game():
|
||||
num = randint(0,9)
|
||||
guess = int(input("random number guess(0-9): "))
|
||||
if guess == num:
|
||||
print("correct! you win")
|
||||
else:
|
||||
print("incorrect, the anser was", num)
|
||||
|
||||
|
||||
random_number_game()
|
||||
|
||||
|
||||
# 5. Write a function to compute whether a given year is a leap year in the Hebrew calendar.
|
||||
|
||||
def is_hebrew_leap_year(year):
|
||||
year_of_cycle = year % 19
|
||||
if year_of_cycle in (3, 6, 8, 11, 14, 17, 19):
|
||||
print(str(year) + " is year number " + str(year_of_cycle) + " of the cycle and is therefore a leap year.")
|
||||
else:
|
||||
print(str(year) + " is year number " + str(year_of_cycle) + " of the cycle and is therefore NOT a leap year.")
|
||||
|
||||
|
||||
is_hebrew_leap_year(5779)
|
||||
is_hebrew_leap_year(5780)
|
104
python-csi160/week05/croce_week5_lab.py
Normal file
104
python-csi160/week05/croce_week5_lab.py
Normal file
|
@ -0,0 +1,104 @@
|
|||
# Charlotte Croce
|
||||
# CSI 160: week5 lab
|
||||
# 2/13/2025
|
||||
|
||||
import math
|
||||
|
||||
def number_of_zeros(grades):
|
||||
"""Given a list of grades, determines the number of grades that are 0%
|
||||
|
||||
params:
|
||||
grades (list of floats) - The grades to search. Example [75, 82.5, 97, 0, 87.5]
|
||||
|
||||
return (int) - the number of 0% grades
|
||||
"""
|
||||
count = 0
|
||||
for grade in grades:
|
||||
if grade == 0:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def median(numbers):
|
||||
"""Find the median of the given list of numbers.
|
||||
|
||||
How to find the median:
|
||||
https://www.mathsisfun.com/median.html
|
||||
|
||||
Note: Write your own implementation and do not use any libraries. You will need to sort the list.
|
||||
|
||||
params:
|
||||
numbers (list) A list containing either int or float elements
|
||||
|
||||
return (numeric) The median value as either an int or float
|
||||
"""
|
||||
numbers.sort()
|
||||
length = len(numbers)
|
||||
middle = length // 2
|
||||
if length % 2 == 0: # even number-> avg of middle two
|
||||
return (numbers[middle - 1] + numbers[middle]) / 2
|
||||
else: # odd number-> middle element
|
||||
return numbers[middle]
|
||||
|
||||
|
||||
def top_quartile(grades):
|
||||
"""Return the top 25% of the grades in the supplied list of grades. Round up when determining how many grades to include in the top 25%.
|
||||
|
||||
Hint: You will need to sort the list of grades
|
||||
|
||||
params:
|
||||
grades (list of floats) Example [75, 82.5, 97, 0, 87.5]
|
||||
|
||||
return (list of floats) - The top 25%
|
||||
"""
|
||||
grades.sort()
|
||||
quarter = math.ceil(len(grades) / 4)
|
||||
return grades[-quarter:]
|
||||
|
||||
|
||||
def domain_name_extractor(url):
|
||||
"""Given a url, return the domain name
|
||||
|
||||
You will need to utilize the .find method to complete this https://docs.python.org/3/library/stdtypes.html#str.find
|
||||
|
||||
Hint: Find the starting point of the domain name, then find the end point.
|
||||
params:
|
||||
url (string) the url to search. Example: https://docs.python.org/3/library
|
||||
|
||||
return (string) The domain name or IP address. Example: docs.python.org
|
||||
"""
|
||||
start_index = url.find('//') + 2 # find the start of the domain name after http(s)://
|
||||
end_index = url.find('/', start_index) # starting search from start_index
|
||||
if end_index == -1: # no '/' found after domain name, or it's the last character
|
||||
return url[start_index:]
|
||||
return url[start_index:end_index]
|
||||
|
||||
def test_number_of_zeros():
|
||||
print('Running number_of_zeros tests:')
|
||||
print('Test 1 passed -', number_of_zeros([75.0, 0.0, 97.0, 0.0, 87.5]) == 2)
|
||||
print('Test 2 passed -', number_of_zeros([]) == 0)
|
||||
|
||||
def test_median():
|
||||
print('Running median tests:')
|
||||
print('Test 1 passed -', median([10, 5, 8, 4, -1]) == 5)
|
||||
print('Test 2 passed -', median([10, 8, 4, -1]) == 6)
|
||||
|
||||
def test_top_quartile():
|
||||
print('Running top_quartile tests:')
|
||||
print('Test 1 passed -', top_quartile([97, 92.5, 84, 79, 67]) == [92.5, 97])
|
||||
print('Test 2 passed -', top_quartile([92.5, 86, 89, 75]) == [92.5])
|
||||
|
||||
def test_domain_name_extractor():
|
||||
print('Running domain_name_extractor tests:')
|
||||
print('Test 1 passed -', domain_name_extractor('https://champlain.instructure.com/courses/8933') == 'champlain.instructure.com')
|
||||
print('Test 2 passed -', domain_name_extractor('ftp://champlain.edu/myfile.pdf') == 'champlain.edu')
|
||||
|
||||
print('Running Unit Tests\n')
|
||||
test_number_of_zeros()
|
||||
print()
|
||||
test_median()
|
||||
print()
|
||||
test_top_quartile()
|
||||
print()
|
||||
test_domain_name_extractor()
|
||||
|
10
python-csi160/week05/week-5Practice-Problems/part1.py
Normal file
10
python-csi160/week05/week-5Practice-Problems/part1.py
Normal file
|
@ -0,0 +1,10 @@
|
|||
def first_element(list_to_search):
|
||||
"""Returns the first element of the supplied list. Returns None if the list was empty"""
|
||||
if len(list_to_search) == 0:
|
||||
return None
|
||||
return list_to_search[0]
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('[4, 2, 15, 5] The first_element returns', first_element([4, 2, 15, 5]))
|
||||
print('[] The first_element returns', first_element([]))
|
10
python-csi160/week05/week-5Practice-Problems/part2.py
Normal file
10
python-csi160/week05/week-5Practice-Problems/part2.py
Normal file
|
@ -0,0 +1,10 @@
|
|||
def second_element(list_to_search):
|
||||
"""Returns the second element of the supplied list. Returns None if list contains less than 2 elements"""
|
||||
if len(list_to_search) < 2:
|
||||
return None
|
||||
return list_to_search[1]
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('[4, 2, 15, 5] The second_element returns', second_element([4, 2, 15, 5]))
|
||||
print('[3] The second_element returns', second_element([3]))
|
11
python-csi160/week05/week-5Practice-Problems/part3.py
Normal file
11
python-csi160/week05/week-5Practice-Problems/part3.py
Normal file
|
@ -0,0 +1,11 @@
|
|||
def last_element(list_to_search):
|
||||
"""Returns the last element of the supplied list.
|
||||
Returns None if the list is empty"""
|
||||
if len(list_to_search) == 0:
|
||||
return None
|
||||
return list_to_search[-1]
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('[4, 2, 15, 5] The last_element returns', last_element([4, 2, 15, 5]))
|
||||
print('[] The last_element returns', last_element([]))
|
13
python-csi160/week05/week-5Practice-Problems/part4.py
Normal file
13
python-csi160/week05/week-5Practice-Problems/part4.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
def area_code(phone_number):
|
||||
""" Given a phone number in the format: 802-555-1212
|
||||
extract the first 3 characters and return this as a string
|
||||
|
||||
:param phone_number: (str) Must be formatted "XXX-XXX-XXXX"
|
||||
:return: (str) 3 digit area_code
|
||||
"""
|
||||
return phone_number[:3]
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('"802-555-1212" area_code returns', area_code("802-555-1212"))
|
||||
print('"410-617-3452" area_code returns', area_code("410-617-3452"))
|
12
python-csi160/week05/week-5Practice-Problems/part5.py
Normal file
12
python-csi160/week05/week-5Practice-Problems/part5.py
Normal file
|
@ -0,0 +1,12 @@
|
|||
def last_four_digits(phone_number):
|
||||
""" Returns the last 4 digits of a phone number as a string
|
||||
|
||||
:param phone_number: (str) May be formatted "XXX-XXX-XXXX" or "1-XXX-XXX-XXXX"
|
||||
:return: (str) last four digits
|
||||
"""
|
||||
return phone_number[-4:]
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('"802-555-1212" last_four_digits returns', last_four_digits("802-555-1212"))
|
||||
print('"1-410-617-3452" last_four_digits returns', last_four_digits("410-617-3452"))
|
13
python-csi160/week05/week-5Practice-Problems/part6.py
Normal file
13
python-csi160/week05/week-5Practice-Problems/part6.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
def first_last_name(full_name):
|
||||
""" Returns a tuple with the first and last name.
|
||||
|
||||
:param full_name: (str) Contains a first and last name seperated by a space.
|
||||
There is only a single space in the full_name.
|
||||
:return: (tuple) Tuple containing first and last names
|
||||
"""
|
||||
return tuple(full_name.split(" "))
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('"Billie Holiday" first_last_name returns', first_last_name("Billie Holiday"))
|
||||
print('"James Brown" first_last_name returns', first_last_name("James Brown"))
|
15
python-csi160/week05/week-5Practice-Problems/part7.py
Normal file
15
python-csi160/week05/week-5Practice-Problems/part7.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
def second_smallest(numbers):
|
||||
"""Returns the second smallest number
|
||||
|
||||
:param numbers: (list) List of numbers of at least size 2
|
||||
:return: (int or float) The second smallest number
|
||||
"""
|
||||
numbers.sort()
|
||||
return numbers[1]
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('[6, 3, 9, 2, 1] second_smallest returns', second_smallest([6, 3, 9, 2, 1]))
|
||||
print('[23, 23.25, 23.5, 23] second_smallest returns', second_smallest([23, 23.25, 23.5, 23]))
|
||||
|
||||
|
24
python-csi160/week05/week-5Practice-Problems/part8.py
Normal file
24
python-csi160/week05/week-5Practice-Problems/part8.py
Normal file
|
@ -0,0 +1,24 @@
|
|||
def area_code(phone_number):
|
||||
"""Returns the area code of the supplied phone number.
|
||||
|
||||
params:
|
||||
phone_number (string) in the format:
|
||||
1-XXX-XXX-XXXX
|
||||
XXX-XXX-XXXX
|
||||
(XXX)-XXX-XXXX
|
||||
return: (string) The area code
|
||||
"""
|
||||
if phone_number[0] == '(':
|
||||
return phone_number[1:4]
|
||||
elif phone_number[0] == '1':
|
||||
return phone_number[2:5]
|
||||
else:
|
||||
return phone_number[:3]
|
||||
|
||||
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('"1-617-555-1212" area_code returns', area_code("1-617-555-1212"))
|
||||
print('"802-999-1212" area_code returns', area_code("802-999-1212"))
|
||||
print('"(802)-999-1212" area_code returns', area_code("(802)-999-1212"))
|
150
python-csi160/week06/croce_week6_lab.py
Normal file
150
python-csi160/week06/croce_week6_lab.py
Normal file
|
@ -0,0 +1,150 @@
|
|||
# Charlotte Croce
|
||||
# CSI 160
|
||||
# Week 6: Lab - Loops
|
||||
# 2/17/25
|
||||
|
||||
# 1. Area Codes
|
||||
# Given a list of phone numbers that are missing the area code,
|
||||
# append the area code to the phone numbers in the list and return the result list.
|
||||
|
||||
def add_area_code(phone_numbers, area_code):
|
||||
"""Returns a list of phone numbers with the area code added.
|
||||
Given a list of phone numbers that are missing the area code,
|
||||
append the area code to the phone numbers in the list and return the result list.
|
||||
|
||||
:param phone_numbers: (list) A list of phone numbers (strings) that do not have the area code
|
||||
Example: ['555-1212']
|
||||
:param area_code: (str) The area code to add Example: '802'
|
||||
:return: (list) A list of phone numbers with the area code Example: ['802-555-1212']
|
||||
"""
|
||||
phone_numbers_with_area = phone_numbers.copy()
|
||||
for i in range(len(phone_numbers_with_area)):
|
||||
phone_numbers_with_area[i] = area_code + '-' + phone_numbers[i]
|
||||
return phone_numbers_with_area
|
||||
|
||||
# example usage
|
||||
phone_numbers = ['555-1212', '999-0738']
|
||||
with_area_code = add_area_code(phone_numbers, '802')
|
||||
print(with_area_code)
|
||||
|
||||
################################################################
|
||||
# 2. Print even numbers
|
||||
# Complete the following function to print the even numbers of a list, one per line.
|
||||
|
||||
def print_even(numbers):
|
||||
"""Prints the even numbers in a list, one per line
|
||||
|
||||
:param numbers: (list) list of integers
|
||||
:return: None
|
||||
"""
|
||||
for number in numbers:
|
||||
if number % 2 == 0:
|
||||
print(number)
|
||||
|
||||
print_even([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
|
||||
|
||||
|
||||
################################################################
|
||||
# 3. Guessing Game
|
||||
# Extend your guessing game from earlier. Write a program that picks a random number from 1-100. Then ask the user to guess a number.
|
||||
# Tell the user if the answer is higher or lower than the number they guessed, or if they got the correct answer.
|
||||
# Allow them to guess again if they got the guess incorrect. They should be able to guess numbers an infinite number
|
||||
# of times until they get the correct answer, at which point your loop will end.
|
||||
|
||||
# To generate a number from 1-100 you will need the following code at the beginning of your program:
|
||||
|
||||
from random import randint
|
||||
|
||||
def guessing_game():
|
||||
"""Plays a guessing game where the user guesses a number between 1 and 100
|
||||
|
||||
:return: None
|
||||
"""
|
||||
randomNum = randint(1, 100)
|
||||
while True:
|
||||
guess = int(input("Guess a number 1-100: "))
|
||||
if guess < randomNum:
|
||||
print("Higher")
|
||||
elif guess > randomNum:
|
||||
print("Lower")
|
||||
else:
|
||||
print("Correct!")
|
||||
break
|
||||
|
||||
guessing_game()
|
||||
|
||||
################################################################
|
||||
#4. Backpack of Stuff
|
||||
#Complete the following code. Fill in the two sections of code identified in the comments.
|
||||
|
||||
import sys
|
||||
|
||||
def backpack_of_stuff():
|
||||
"""Allows user to add and check items in a backpack
|
||||
|
||||
:return: None
|
||||
"""
|
||||
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
|
||||
|
||||
while True:
|
||||
print("Would you like to:")
|
||||
print("1. Add an item to the backpack?")
|
||||
print("2. Check if an item is in the backpack?")
|
||||
print("3. Quit")
|
||||
userChoice = input()
|
||||
|
||||
if(userChoice == "1"):
|
||||
print("What item do you want to add to the backpack?")
|
||||
itemToAdd = input()
|
||||
itemsInBackpack.append(itemToAdd)
|
||||
|
||||
if(userChoice == "2"):
|
||||
print("What item do you want to check to see if it is in the backpack?")
|
||||
itemToCheck = input()
|
||||
if itemToCheck in itemsInBackpack:
|
||||
print("yes, this item is in backpack")
|
||||
else:
|
||||
print("no, this item is not in backpack")
|
||||
|
||||
if(userChoice == "3"):
|
||||
#sys.exit()
|
||||
break
|
||||
|
||||
backpack_of_stuff()
|
||||
|
||||
################################################################
|
||||
# 5. Comma Code
|
||||
# Say you have a list value like this:
|
||||
|
||||
# listToPrint = ['apples', 'bananas', 'tofu', 'cats']
|
||||
#Write a program that prints a list with all the items separated by a comma and a space,
|
||||
# with and inserted before the last item. For example, the above list would print 'apples, bananas, tofu, and cats'.
|
||||
# But your program should be able to work with any list not just the one shown above.
|
||||
# Because of this, you will need to use a loop in case the list to print is shorter or longer than the above list.
|
||||
# Do not modify the list by inserting 'and' into the list and do not simply print the entire list
|
||||
# (you must loop through printing each item individually). This problem is trickier than it appears at first glance.
|
||||
|
||||
def comma_code(listToPrint):
|
||||
"""Prints a list with all the items separated by a comma and a space, with 'and' inserted before the last item
|
||||
|
||||
:param listToPrint: (list) A list of strings
|
||||
:return: None
|
||||
"""
|
||||
|
||||
# cases for list being 2, 1, or 0 elements
|
||||
if len(listToPrint) == 0:
|
||||
print("List is empty")
|
||||
return
|
||||
elif len(listToPrint) == 1:
|
||||
print(listToPrint[0])
|
||||
return
|
||||
elif len(listToPrint) == 2:
|
||||
print(listToPrint[0] + " and " + listToPrint[1])
|
||||
return
|
||||
|
||||
else:
|
||||
for i in range(len(listToPrint) - 1): # loop through all but last element
|
||||
print(listToPrint[i], end=", ")
|
||||
print("and " + listToPrint[-1]) #print final element of list
|
||||
|
||||
comma_code(['apples', 'bananas', 'tofu', 'cats', 'dogs'])
|
7
python-csi160/week06/week6practiceproblems/part1.py
Normal file
7
python-csi160/week06/week6practiceproblems/part1.py
Normal file
|
@ -0,0 +1,7 @@
|
|||
#1 initialize the loop
|
||||
x = int(input('What number do you want to start at? '))
|
||||
|
||||
# Print countdown using while loop with one number per line
|
||||
while x > 0:
|
||||
print(x)
|
||||
x -= 1
|
8
python-csi160/week06/week6practiceproblems/part2.py
Normal file
8
python-csi160/week06/week6practiceproblems/part2.py
Normal file
|
@ -0,0 +1,8 @@
|
|||
a = int(input('What number do you want to start at? '))
|
||||
b = int(input('What number do you want to end at? '))
|
||||
|
||||
# Print all numbers from a to b inclusively. Assume (a ≤ b)
|
||||
|
||||
while a <= b:
|
||||
print(a)
|
||||
a += 1
|
18
python-csi160/week06/week6practiceproblems/part3.py
Normal file
18
python-csi160/week06/week6practiceproblems/part3.py
Normal file
|
@ -0,0 +1,18 @@
|
|||
def all_squares(n):
|
||||
"""Returns a list that contains all the squares of positive integers
|
||||
where the square is less than or equal to N, in ascending order.
|
||||
|
||||
:param n: (int) Upper bound
|
||||
:return: (list) List of squares
|
||||
"""
|
||||
squares = []
|
||||
i = 1
|
||||
while i * i <= n:
|
||||
squares.append(i * i)
|
||||
i += 1
|
||||
return squares
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('all_squares(50) returns:', all_squares(50))
|
||||
print('all_squares(9) returns:', all_squares(9))
|
21
python-csi160/week06/week6practiceproblems/part4.py
Normal file
21
python-csi160/week06/week6practiceproblems/part4.py
Normal file
|
@ -0,0 +1,21 @@
|
|||
def introductions(names):
|
||||
"""Prints introductions.
|
||||
|
||||
An introduction is 'Hello' followed by a space and a name.
|
||||
Include a newline after each introduction.
|
||||
Example:
|
||||
'Hello Josh'
|
||||
|
||||
Important: Your function should use print() and not have a return statement
|
||||
|
||||
:param names: (list) First Names as strings
|
||||
:return: None
|
||||
"""
|
||||
for name in names:
|
||||
print("Hello", name)
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
sample_names = input('Enter the names separated by a comma and a space: ').split(', ')
|
||||
introductions(sample_names)
|
||||
|
25
python-csi160/week06/week6practiceproblems/part5.py
Normal file
25
python-csi160/week06/week6practiceproblems/part5.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
def num_distinct_elements(numbers):
|
||||
"""Determine the number of distinct elements in the list
|
||||
|
||||
:param numbers: (list) A list of numbers (int or float)
|
||||
:return: (int) Number of distinct elements
|
||||
"""
|
||||
# Use the function sorted() to temporarily sort the numbers
|
||||
# into ascending order or use the method .sort() to permanently
|
||||
# sort the list in ascending order.
|
||||
numbers.sort()
|
||||
unique_numbers = 1
|
||||
for i in range(1, len(numbers)):
|
||||
if numbers[i] != numbers[i - 1]:
|
||||
unique_numbers += 1
|
||||
return unique_numbers
|
||||
|
||||
|
||||
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
test1 = [2, 5, 5, 7,2, 9.5, 2, 4]
|
||||
print(f'num_distinct_elements({test1}) returns:', num_distinct_elements(test1))
|
||||
test2 = [2, 1, 1, 7, 1, 9.5, 2, 1]
|
||||
print(f'num_distinct_elements({test2}) returns:', num_distinct_elements(test2))
|
||||
|
15
python-csi160/week06/week6practiceproblems/part6.py
Normal file
15
python-csi160/week06/week6practiceproblems/part6.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
def fibonacci(n):
|
||||
"""Return the nth Fibonacci number.
|
||||
|
||||
param n: (int) position to determine fibonacci of
|
||||
return: (int) value at position n
|
||||
"""
|
||||
|
||||
fib_numbers = [0, 1]
|
||||
for i in range(2, n + 1):
|
||||
fib_numbers.append(fib_numbers[i - 1] + fib_numbers[i - 2])
|
||||
return fib_numbers[n]
|
||||
|
||||
# Leave this part for easily testing your function
|
||||
print('fibonacci(6) returns:', fibonacci(6), 'expected 8')
|
||||
print('fibonacci(3) returns:', fibonacci(3), 'expected 2')
|
133
python-csi160/week07/tictactoe.py
Normal file
133
python-csi160/week07/tictactoe.py
Normal file
|
@ -0,0 +1,133 @@
|
|||
import os
|
||||
import time
|
||||
|
||||
# Constants in are named in all caps (PEP8 Standard)
|
||||
PLAYER_X = 'X'
|
||||
PLAYER_O = 'O'
|
||||
EMPTY = ' '
|
||||
TIE_GAME = 'tie'
|
||||
BOARD_SIZE = 3
|
||||
|
||||
current_player = PLAYER_X # Player X goes first
|
||||
|
||||
# Builds an EMPTY board
|
||||
board = [[EMPTY,EMPTY,EMPTY],
|
||||
[EMPTY,EMPTY,EMPTY],
|
||||
[EMPTY,EMPTY,EMPTY]]
|
||||
|
||||
|
||||
def print_board():
|
||||
# Clear the screen
|
||||
os.system('cls' if os.name == 'nt' else 'clear')
|
||||
|
||||
"""Prints the board to the console"""
|
||||
print(' 0 1 2')
|
||||
print(' -------------')
|
||||
for i, row in enumerate(board):
|
||||
print(i, end="")
|
||||
for square in row:
|
||||
print(' | ' + square, end="")
|
||||
print(' |')
|
||||
print(' -------------')
|
||||
|
||||
|
||||
|
||||
def is_empty(row, col):
|
||||
"""Returns True/False if a square is EMPTY
|
||||
|
||||
params row, col: (int) The row and Column to Check
|
||||
return: (boolean) If the row is EMPTY
|
||||
"""
|
||||
return board[row][col] == EMPTY
|
||||
|
||||
|
||||
def move(player, row, col):
|
||||
"""Makes a game move
|
||||
|
||||
If a move is legal, moves the player to the row and col
|
||||
and returns True. If a move is illegal, no move is made
|
||||
and returns False. Hint: Should make use of is_empty()
|
||||
|
||||
param player: Either PLAYER_X or PLAYER_O
|
||||
param row, col: (int) The row and Column to move to
|
||||
return: (boolean) Success of the move
|
||||
"""
|
||||
if is_empty(row, col):
|
||||
board[row][col] = player
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def determine_winner():
|
||||
"""Determine if there is a winner
|
||||
|
||||
return: Returns None if there is no winner.
|
||||
Returns PLAYER_O or PLAYER_X if one of them won.
|
||||
Returns 'tie' if noone wins
|
||||
"""
|
||||
# Step 1: Check the horizontals looking for a winner.
|
||||
# If so return winner.
|
||||
for row in board:
|
||||
if row[0] == row[1] == row[2] != EMPTY:
|
||||
return row[0]
|
||||
# Step 2: Check the verticals looking for a winner
|
||||
# If so return winner.
|
||||
for col in range(BOARD_SIZE):
|
||||
if board[0][col] == board[1][col] == board[2][col] != EMPTY:
|
||||
return board[0][col]
|
||||
# Step 3: Check the diagonals looking for a winner
|
||||
# If so return winner.
|
||||
if board[0][0] == board[1][1] == board[2][2] != EMPTY:
|
||||
return board[0][0]
|
||||
if board[0][2] == board[1][1] == board[2][0] != EMPTY:
|
||||
return board[0][2]
|
||||
# Step 4: Check to see if there are empty squares.
|
||||
# If there are empty squares, return None because
|
||||
# noone has won the game yet
|
||||
# If there are no empty squares return TIE_GAME
|
||||
# because we didn't find a winner and all moves are made
|
||||
for row in board:
|
||||
for col in row:
|
||||
if col == EMPTY:
|
||||
return None
|
||||
return TIE_GAME
|
||||
|
||||
|
||||
|
||||
while True:
|
||||
print()
|
||||
print_board()
|
||||
print()
|
||||
print('It is', current_player, 'turn')
|
||||
row = int(input('What is the row (0-3)? '))
|
||||
col = int(input('What is the col (0-3)? '))
|
||||
|
||||
# Make sure the move is legal, if so make the move
|
||||
if is_empty(row, col):
|
||||
move(current_player, row, col)
|
||||
else:
|
||||
print('That is not a legal move!')
|
||||
time.sleep(2)
|
||||
continue
|
||||
|
||||
# Check if there is a winner
|
||||
winner = determine_winner()
|
||||
if winner in (PLAYER_O, PLAYER_X):
|
||||
print_board()
|
||||
print('Congratulations', winner,'!!! You won!')
|
||||
print('But you are all winners')
|
||||
break
|
||||
|
||||
if winner == TIE_GAME:
|
||||
print_board()
|
||||
print("It's a tie!!!")
|
||||
break
|
||||
|
||||
# Let the other player have a turn
|
||||
if current_player == PLAYER_O:
|
||||
current_player = PLAYER_X
|
||||
else:
|
||||
current_player = PLAYER_O
|
||||
|
||||
|
1768
python-csi160/week10/alice.py
Normal file
1768
python-csi160/week10/alice.py
Normal file
File diff suppressed because it is too large
Load diff
39
python-csi160/week10/part1.py
Normal file
39
python-csi160/week10/part1.py
Normal file
|
@ -0,0 +1,39 @@
|
|||
|
||||
# Step 1. Create dictionary called 'user'
|
||||
# with the following keys: 'name' and 'location'
|
||||
# Set the name to 'John Doe'
|
||||
# Set the location to 'Burlington, VT'
|
||||
|
||||
user = {
|
||||
'name': 'John Doe',
|
||||
'location': 'Burlington, VT'
|
||||
}
|
||||
|
||||
# Step 2. Ask the user for the user's age
|
||||
# and create a key/value pair in user to store this
|
||||
# called 'age'
|
||||
try:
|
||||
age = input(f"How old is {user['name']}? ")
|
||||
except KeyError:
|
||||
print('"name" not defined as a key in Step 1')
|
||||
else:
|
||||
user['age'] = int(age)
|
||||
print(f"{user['name']} is {user['age']} years old.")
|
||||
|
||||
|
||||
# Step 3
|
||||
# Create keys "first_name" and "last_name"
|
||||
# Use .split() to seperate name into firstname and last_name
|
||||
# Remove the key "name" from the dictionary
|
||||
|
||||
first_name, last_name = user['name'].split()
|
||||
user['first_name'] = first_name
|
||||
user['last_name'] = last_name
|
||||
del user['name']
|
||||
print(f"First name: {user['first_name']}")
|
||||
print(f"Last name: {user['last_name']}")
|
||||
|
||||
|
||||
# For testing (do not delete)
|
||||
print('Printing "user":')
|
||||
print(user)
|
25
python-csi160/week10/part2.py
Normal file
25
python-csi160/week10/part2.py
Normal file
|
@ -0,0 +1,25 @@
|
|||
def synonym_lookup(word_pairs, word_to_lookup):
|
||||
"""Returns synonym for the word to word_to_lookup
|
||||
|
||||
Complete this function by using a dictionary. For each synonym pair,
|
||||
you should add both words as keys to your dictionary with the value being the other word.
|
||||
|
||||
params:
|
||||
word_pairs (tuple of tuples): Example: (('Hello', 'Hi'), ('Goodbye','Bye'))
|
||||
word_to_lookup (string): The word to find a synonym for
|
||||
return (string): The synonym for the word_to_lookup
|
||||
"""
|
||||
synonym_dict = {}
|
||||
|
||||
# Create a dictionary with both words in each pair
|
||||
for word1, word2 in word_pairs:
|
||||
synonym_dict[word1] = word2
|
||||
synonym_dict[word2] = word1
|
||||
|
||||
# Return the synonym
|
||||
return synonym_dict.get(word_to_lookup, None)
|
||||
|
||||
|
||||
example_word_pairs = (('Hello', 'Hi'), ('Goodbye','Bye'), ('Snake', 'Serpent'))
|
||||
|
||||
print(f'A synonym for "Serpent" is {synonym_lookup(example_word_pairs, "Serpent")}. (Snake expected)')
|
38
python-csi160/week10/part3.py
Normal file
38
python-csi160/week10/part3.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
final_election_results = {}
|
||||
|
||||
def record_candidate_votes(election_results, candidate, num_votes, precinct):
|
||||
"""Records votes for a particular candidate in one precinct in the election_results.
|
||||
|
||||
The precinct is not used for the function currently.
|
||||
|
||||
Optional tip: Using method .get() can allow you to avoid needing a if or try statement
|
||||
|
||||
params:
|
||||
election_results (dict): Dictionary to be modified by recording the votes for a candidate in a precinct
|
||||
cadidate (string): The name of a candidate. Used as the 'key' in the election_results dictionary.
|
||||
num_votes (int): The number of votes to add to the candidate's total
|
||||
"""
|
||||
if candidate in election_results:
|
||||
# If candidate exists, add to the existing total
|
||||
election_results[candidate] += num_votes
|
||||
else:
|
||||
# If candidate doesn't exist, create a new entry
|
||||
election_results[candidate] = num_votes
|
||||
|
||||
|
||||
|
||||
# This section is for testing purposes, do not modify
|
||||
# FYI: These numbers are made up for example purposes only
|
||||
record_candidate_votes(final_election_results,'Miro Weinberger', 100, 'Ward 1')
|
||||
record_candidate_votes(final_election_results,'Max Tracy', 140, 'Ward 1')
|
||||
record_candidate_votes(final_election_results,'Ali Dieng', 27, 'Ward 1')
|
||||
record_candidate_votes(final_election_results,'Miro Weinberger', 50, 'Ward 2')
|
||||
record_candidate_votes(final_election_results,'Max Tracy', 150, 'Ward 2')
|
||||
record_candidate_votes(final_election_results,'Ali Dieng', 35, 'Ward 2')
|
||||
record_candidate_votes(final_election_results,'Miro Weinberger', 100, 'Ward 3')
|
||||
record_candidate_votes(final_election_results,'Max Tracy', 100, 'Ward 3')
|
||||
record_candidate_votes(final_election_results,'Ali Dieng', 56, 'Ward 3')
|
||||
record_candidate_votes(final_election_results,'Miro Weinberger', 320, 'Ward 4')
|
||||
record_candidate_votes(final_election_results,'Max Tracy', 213, 'Ward 4')
|
||||
record_candidate_votes(final_election_results,'Ali Dieng', 175, 'Ward 4')
|
||||
print(final_election_results)
|
45
python-csi160/week10/part4.py
Normal file
45
python-csi160/week10/part4.py
Normal file
|
@ -0,0 +1,45 @@
|
|||
import string
|
||||
from alice import alice_text
|
||||
|
||||
def word_frequency(text):
|
||||
"""Generates a word frequency dictionary for the supplied text. All punctuation is stripped and the case is converted to lowercase.
|
||||
|
||||
Example dictionary: {'the': 2, 'cat': 1, 'bit': 1, 'dog': 1}
|
||||
|
||||
param text: (string) The text to be analyzed
|
||||
return: (dict) Word frequency dictionary
|
||||
"""
|
||||
# Strip Punctuation
|
||||
for character in string.punctuation:
|
||||
text = text.replace(character, "")
|
||||
|
||||
# Convert to lower case
|
||||
text = text.lower()
|
||||
|
||||
# Generate a list of all of the words
|
||||
words = text.split()
|
||||
|
||||
word_frequency = {}
|
||||
for word in words:
|
||||
if word in word_frequency:
|
||||
word_frequency[word] += 1
|
||||
else:
|
||||
word_frequency[word] = 1
|
||||
return word_frequency
|
||||
|
||||
|
||||
# Code for testing purposes. Do not modify
|
||||
short_sentence = "The silly cat is the silly face."
|
||||
print(f'Analyzing word frequency of "{short_sentence}"')
|
||||
print(word_frequency("The silly cat is the silly face."))
|
||||
|
||||
print()
|
||||
try:
|
||||
print('In Alice and Wonderland,')
|
||||
alice_freq = word_frequency(alice_text)
|
||||
print(f'The word Alice occurs {alice_freq["alice"]} times')
|
||||
print(f'The word melancholy occurs {alice_freq["melancholy"]} times')
|
||||
print(f'{len(alice_freq)} different words are used in the book.')
|
||||
except Exception as e:
|
||||
print('Exception raised when analyzing Alice in Wonderland:')
|
||||
print(e)
|
Loading…
Add table
Add a link
Reference in a new issue