DOR'S CODING SCHOOL Learn To Program Workbook EBOOK Python Problems – Functions, Variables Questions Problem 1 Create a variable. Store your name in that variable. Print the variable. Problem 2 Ask user for his name. Print only the name. Problem 3 Ask user for his name. Print “Hello” and the name of the user. Problem 4 Ask a user for his name. Print it using f-strings: https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/ Problem 5 Create a variable ‘a’ and store the value 5. Create a variable ‘b’ and store the value of ‘a’. Change the value of ‘a’ to 10. Print the variable ‘a’ and ‘b’. Problem 6 Ask user for a title of a movie. Convert the first letters in every word of the title of the movie in upper case. Print it. Hint: See how title() method works (click here!) Problem 7 Ask user for a title of a movie. Convert every word of the title of the movie in upper case. Print it. Hint: See how upper() method works (click here!) 2 Python Problems – Functions, Variables Problem 8 Ask user for a title of a movie. Convert every word of the title of the movie in lower case. Print it. Hint: See how lower() method works (click here!) Problem 9 Create a variable that holds the value “ whitespace and print it. Hi everyone “. Remove the Hint: See how strip() method works (click here!) Problem 10 Create a variable that holds the value “,,,,,rrtthh.....coding....rrr“. Remove the extra characters and print only coding. Hint: See how strip() method works (click here!) Problem 11 Create a variable that holds the value “I love coding“. Replace the word coding by Python. Print it. Hint: See how replace() method works (click here!) Problem 12 Ask user for two integers. Sum them and print the result. Problem 13 Ask user for two float numbers. Sum them and print the result. Problem 14 Ask user for two integers. Subtract them and print the result. 3 Python Problems – Functions, Variables Problem 15 Ask user for two integers. Multiply them and print the result. Problem 16 Ask user for two integers. Divide them and print the result. Problem 17 Ask user for two numbers. Divide them and print the result with no decimal places. Hint: See how round() method works (click here!) Problem 18 Ask user for two numbers. Multiply them. Print the result with only 2 decimal places. Hint: See how to do it (click here!) 4 Python Problems – Functions, Variables Solutions Problem 1 name = "Giovanna" print(name) Problem 2 name = input("What's your name? ") print(name) Problem 3 name = input("What's your name? ") print(“Hello, “ + name) Problem 4 answer = input("What's your name? ") print(f"hello, {answer}") Problem 5 a=5 b=a a = 10 print(a) print(b) You should see a = 10 and b = 5. 5 Python Problems – Functions, Variables Problem 6 movie = input("What's your favorite movie? ") print(movie.title()) Problem 7 movie = input("What's your favorite movie? ") print(movie.upper()) Problem 8 movie = input("What's your favorite movie? ") print(movie.lower()) Problem 9 var = " Hi everyone " print(movie.strip()) Problem 10 var = “,,,,,rrtthh.....coding....rrr“ print(movie.strip(“,.rth”)) Problem 11 var = “I love coding“ print(movie.replace(“coding”, “Python”)) 6 Python Problems – Functions, Variables Problem 12 x= input("x: ") y= input("y: ") sum = int(x) + int(y) print(sum) Problem 13 x= input("x: ") y= input("y: ") sum = float(x) + float(y) print(sum) Problem 14 x= input("x: ") y= input("y: ") result = int(x) - int(y) print(result) Problem 15 x= input("x: ") y= input("y: ") result = int(x) * int(y) print(result) 7 Python Problems – Functions, Variables Problem 16 x= input("x: ") y= input("y: ") result = int(x) / int(y) print(result) Problem 17 x= input("x: ") y= input("y: ") result = int(x) / int(y) print(round(result)) Problem 18 x= input("x: ") y= input("y: ") result = int(x) * int(y) print(“{:.2f}”.format(result)) 8 Python Problems – Functions, Variables Questions Problem 1 Create a function that prints hello. Call the function. Problem 2 Write a program to create a function that takes two arguments, name and age, and print their value. Problem 3 Create a function that returns double the input. Call the function multiple times with different values. Print the result of each function call. Problem 4 Ask user for two integers in the main function. Create a function that sum them and return the result. Print the result in the main function. Problem 5 Ask user for two float numbers in the main function. Create a function that sum them and return the result. Print the result in the main function. Problem 6 Ask user for two integers in the main function. Create a function that subtract them and return the result. Print the result in the main function. Problem 7 Ask user for two integers in the main function. Create a function that multiply them and return the result. Print the result in the main function. 2 Python Problems – Functions, Variables Problem 8 Ask user for two integers in the main function. Create a function that divides the two integers and return the result. Print the result in the main function. Problem 9 Ask user for two numbers in the main function. Create a function that divides them and return the result. Print the result with no decimal places in the main function. Hint: See how round() method works (click here!) Problem 10 Ask user for two numbers in the main function. Create a function that divides the two numbers and return the result. Print the result with only 2 decimal places in the main function. Hint: See how to do it (click here!) Problem 11 Ask the user for a message. Write a function to return the message in upper case. Print the result. Problem 12 In this problem, we will convert the value that the user will give to us from miles to kilometers. Ask the user for a number that represents the miles. Write a function to return the kilometers that this number of miles represents. Print the result. Hint: 1 mile = 1.60934 kilometers 3 Python Problems – Functions, Variables Solutions Problem 1 def hello(): print("hello") hello() Problem 2 # demo is the function name def demo(name, age): # print value print(name, age) # call function demo("Ben", 25) Problem 3 def double(n): return n*2 print(double(2)) print(double(4)) print(double(6)) 4 Python Problems – Functions, Variables Problem 4 def func(x,y): sum = int(x) + int(y) return sum x= input("x: ") y= input("y: ") result = func(x,y) print(result) Problem 5 def func(x,y): sum = float(x) + float(y) return sum x= input("x: ") y= input("y: ") result = func(x,y) print(result) Problem 6 def func(x,y): result = int(x) - int(y) return result x= input("x: ") y= input("y: ") result = func(x,y) print(result) 5 Python Problems – Functions, Variables Problem 7 def func(x,y): result = int(x) * int(y) return result x= input("x: ") y= input("y: ") result = funct(x,y) print(result) Problem 8 def func(x,y): result = int(x) / int(y) return result x= input("x: ") y= input("y: ") result = func(x,y) print(result) Problem 9 def func(x,y): result = int(x) / int(y) return result x= input("x: ") y= input("y: ") result = func(x,y) print(round(result)) 6 Python Problems – Functions, Variables Problem 10 def func(x,y): result = int(x) * int(y) return result x= input("x: ") y= input("y: ") result = func(x,y) print(“{:.2f}”.format(result)) Problem 11 def uppercase(txt): return txt.upper() txt = input("Message: ") print(uppercase(txt)) Problem 12 def convert(miles): return miles * 1.60934 miles= input("Miles: ") print(f”Kilometers: {convert(miles)}”) 7 Python Problems – Conditionals Questions Problem 1 Ask the user for two integer inputs and print which one of them is the largest. Problem 2 Ask the user for two integer inputs. Print YES if they are equal, NO otherwise. Problem 3 Ask the user for two integer inputs. Write a function to return the sum of the two integers values but if two values are the same, then return triple their sum. Print the result. Problem 4 Ask the user for two integer inputs. Write a function to return True if one of them is 30 or if their sum is 30. Print the result. Problem 5 Ask the user for two integer inputs. Write a program to check if each integer is in the range 100…200 inclusive. Problem 6 Call a function with two integers. The function should check which number is nearest to the value 100 among them. Return 0 if the two numbers are equal. Problem 7 Write a function to check if two integers have the same last digit. 2 Python Problems – Conditionals Problem 8 Write a function to compute the sum of two integers. However, if the sum is in the range 10…20 inclusive return 30. Problem 9 Write a function that accepts two integers and return True if either one is 5 or their sum or difference is 5. Problem 10 Create an integer and store it in a variable. Print if the integer is even or odd. Problem 11 Create a string. Print the first letter. Problem 12 Create a string. Print the last letter. Problem 13 Create a string. Print the string without the first letter. Problem 14 Create a string. Print the string without the last letter. Problem 15 Create a string with the value apple. Print ppl. 3 Python Problems – Conditionals Problem 16 Create a string with the value “apple banana”. Split the string into two variables (fruits). Print them. Hint: check the split() method (click here!) Problem 17 Create a string with the value “apple,banana”. Split the string into two variables (fruits). Print them. Hint: check the split() method (click here!) Problem 18 Ask the user for a word. If the word contains the letter “a”, print “There is letter a”. Otherwise, print “There is not letter a”. Hint: check the in operator (click here!) Problem 19 Ask the user for a word. If the word contains the letter “a” (it can be in lower or upper case), print “There is letter a”. Otherwise, print “There is not letter a”. Hint: check the in operator (click here!) Problem 20 Ask the user for a message. If the message contains the word “hello” (it can be in lower or upper case), print “Hello you”. Otherwise, print “No hello”. Hint: check the in operator (click here!) 4 Python Problems – Conditionals Solutions Problem 1 # Prompt user for x x = int(input("x: ")) # Prompt user for y y = int(input ("y: ")) if x < y: print("x is less than y") elif x > y: print("x is greater than y") else: print("x is equal to y") Problem 2 # Prompt user for x x = int(input("x: ")) # Prompt user for y y = int(input ("y: ")) if x == y: print("YES") else: print("NO") 5 Python Problems – Conditionals Problem 3 #Definition of function def check_nums(x,y): if x == y: return (x+y)*3 else: return x+y # Prompt user for x x = int(input("x: ")) # Prompt user for y y = int(input ("y: ")) #Call the function print(check_nums(x,y)) Problem 4 #Definition of function def check_nums(x,y): if x == 30 or y == 30 or x+y == 30: return True return False # Prompt user for x x = int(input("x: ")) # Prompt user for y y = int(input ("y: ")) #Call the function print(check_nums(x,y)) 6 Python Problems – Conditionals Problem 5 #Definition of function def check_nums(x,y): if (x >= 100 and x <= 200) or (y >= 100 and y <= 200): return True return False # Prompt user for x, y x = int(input("x: ")) y = int(input ("y: ")) #Call the function print(check_nums(x,y)) Problem 6 def get_nearest(x,y): val = abs(x - 100) val2 = abs(y - 100) if val < val2: return x elif val > val2: return y else: return 0 # Prompt user for x, y x = int(input("x: ")) y = int(input ("y: ")) print(get_nearest(x,y)) 7 Python Problems – Conditionals Problem 7 def last_digit(x,y): return abs(x % 10) == abs(y % 10) # Prompt user for x x = int(input("x: ")) y = int(input ("y: ")) # Call the function print(last_digit(x,y)) Problem 8 def test(x,y): sum = x + y if sum >= 10 and sum <= 20: return 30 else: return sum # Prompt user for y x = int(input("x: ")) # Prompt user for y y = int(input ("y: ")) # Call the function print(test(x,y)) 8 Python Problems – Conditionals Problem 9 def test(x,y): sum = x + y diff = abs(x - y) if sum ==5 or diff == 5 or x == 5 or y ==5: return True return False # Prompt user for y x = int(input("x: ")) # Prompt user for y y = int(input ("y: ")) print(test(x,y)) Problem 10 num = 21 if num % 2 == 0: print("even") else: print("odd") Problem 11 text = "coding" print(text[0]) 9 Python Problems – Conditionals Problem 12 text = "codingasdasdasdasda" print(text[len(text)-1]) Problem 13 text = "coding" print(text[1:]) Problem 14 text = "coding" print(text[0:len(text)-1]) Problem 15 text = "apple" print(text[1:4]) Problem 16 text = "apple banana" print(text.split()) Problem 17 text = "apple,banana" print(text.split(“,”)) 10 Python Problems – Conditionals Problem 18 word = input(“Word: “) if “a” in word: print(“There is letter a”) else: print(“There is not letter a”) Problem 19 word = input(“Word: “) if “a” in word.lower(): print(“There is letter a”) else: print(“There is not letter a”) Problem 20 message = input(“Message: “) if “hello” in message.lower(): print(“Hello you”) else: print(“No hello”) 11 Python Problems - Loops Questions Problem 1 Print the values from 1 to 100 using a for loop. Problem 2 Print from 0 to 100, printing only the even numbers. Use a for loop. Problem 3 Sum numbers from 1 to 100. Print the result. (The result is 5050). Problem 4 Add 1 + 3 + 5 + … + 99. Print the result. Problem 5 Loop from 100 to 1. Print the values. Use a for loop. (The result is 2500) Problem 6 Add all the numbers from 99 + 97 + 95 + … + 1. Use a for loop.(The result is 2500) Problem 7 Print numbers from 100 to 0 (backwards) using a for loop. Problem 8 Print numbers from 1 to 100 using a while loop. 2 Python Problems - Loops Problem 9 Print the following sequence of numbers: 0, 2, 4, 6 .... 98, 100 using a while loop. Problem 10 Print numbers from 100 to 0 (backward) using a while loop. Problem 11 Create a function that prints hello as many times as you want (with an input). Call this function with the number of times you want to print hello. Problem 12 Create a function that returns double the input. Call the function multiple times with different values. Print the result of each function call. Problem 13 Print “cough” 3 times in 3 ways: 1. Using 3 print statements 2. Using a loop 3. Using a function Problem 14 Ask the user for an integer input which will be stored in a variable called “change”. Use a while loop to determine how many quarters will be given as “change”. Example: 76 as change uses 3 quarters. 29 as change uses 1 quarter. Problem 15 Keep asking a user for a positive value. This loop should break (look up the break keyword in W3Schools) when the user input is positive. Keep looping until the user inputs a positive value. 3 Python Problems - Loops Problem 16 Loop through values from 1 to 100 inclusive. Check the conditions: 1. 2. 3. 4. If the current number is divisible by 3, print Fizz. If the current number is divisible by 5, print Buzz. If the current number is divisible by both 3 and 5, print FizzBuzz. Else, print the number. Problem 17 Create a long string. Print two letters at a time with overlapping letters. Example: “apple” should print: “ap” “pp” “pl” “le” Problem 18 Create a long string. Print two letters at a time, without overlapping letters. “appleb” should become: “ap” “pl” “eb” Problem 19 Create a string. Print three letters at a time. Problem 20 Create two strings. Concatenate the second to the first. 4 Python Problems - Loops Problem 21 Add numbers from 1 to 100 using a while loop. Print the result (Should give you 5050). Problem 22 Create an integer. Count the number of digits. Problem 23 Create a long number. Print the first two digits. Problem 24 Create the following pattern: * ** *** **** Problem 25 Write a code to make the following pattern (using nested for loops): 1 22 333 4444 5 Python Problems - Loops Problem 26 Write a code to make the following pattern (using nested for loops): 1 23 456 7 8 9 10 Problem 27 Ask users for an integer. Call a function that sums the digits in this integer. Print the result. Problem 28 Create a function that sums every other digit. Problem 29 Ask user for a character. If the character is a letter in upper case, print “True”. Otherwise, print “False”. Hint: check the isupper() method (click here!) 6 Python Problems - Loops Solutions Problem 1 for i in range(1, 101): print(i) Problem 2 for i in range(0, 101, 2): print(i) Problem 3 sum = 0 for i in range(1, 11): sum = sum + i print(sum) Problem 4 sum = 0 for i in range(1, 100, 2): sum += i print(sum) Problem 5 for i in range(100, 0, -1): print(i) 7 Python Problems - Loops Problem 6 sum = 0 for i in range(99, 0, -2): sum += i print(sum) Problem 7 for i in range(100,-1,-1): print(i) Problem 8 i =1 while (i <= 100): print(i) i += 1 Problem 9 i =0 while (i <= 100): print(i) i += 2 Problem 10 i = 100 while (i >= 0): print(i) i -= 1 8 Python Problems - Loops Problem 11 def hello(n): for i in range(n): print("hello") hello(5) Problem 12 def double(n): return n*2 print(double(2)) print(double(4)) print(double(6)) Problem 13 #Using 3 print statements print("cough") print("cough") print("cough") #Using a loop for i in range(3): print("cough") #Using a function def cough(n): for i in range(n): print("cough") cough(3) 9 Python Problems - Loops Problem 14 x = input("x: ") count_quarters = 0 while (float(x) >= 25): x -= 25 count_quarters += 1 print(count_quarters) Problem 15 while True: x = input("x: ") if int(x) >= 0: break Problem 16 for i in range(1, 101): if (i % 3 == 0 and i % 5 == 0): print("FIZZBUZZ") elif (i % 3 == 0): print("FIZZ") elif (i % 5 == 0): print("BUZZ") else: print(i) Problem 17 text = "applebanana" 10 Python Problems - Loops for i in range(0, len(text)-1): print(text[i:i+2]) Problem 18 text = "applefab" for i in range(0, len(text)-1, 2): print(text[i:i+2]) Problem 19 text = "applebananas" for i in range(0, len(text)-1, 3): print(text[i:i+3]) Problem 20 text1 = "banana" text2 = "apple" #text1 = text1 + text2 text1 += text2 print(text1) 11 Python Problems - Loops Problem 21 counter = 0 sum = 0 while (counter <= 100): sum+= counter counter += 1 print(sum) Problem 22 num = 231231231 counter = 0 while num > 0: num = num // 10 counter += 1 print(counter) Problem 23 num = 23423323 print(num // pow(10, 6)) Problem 24 # Prompt user for number of rows num_rows = input("Number of rows: ") for row in range(1, int(num_rows)): for col in range(1, row+1): print("*", end="") print() 12 Python Problems - Loops Problem 25 num_rows = input("Number of rows: ") for row in range(1, int(num_rows)): for col in range(1, row+1): print(row, end="") print() Problem 26 num_rows = input("Number of rows: ") k=1 for row in range(1, int(num_rows)): for col in range(1, row+1): print(k, end="") k += 1 print() Problem 27 def get_sum_digits(x): sum = 0 while(x != 0): sum += x % 10 x //= 10 return sum x = input("x: ") print(get_sum_digits(int(x))) 13 Python Problems - Loops Problem 28 def get_sum_digits(x): sum = 0 isAlternateDigit = False while(x != 0): if isAlternateDigit: sum += x % 10 isAlternateDigit = not isAlternateDigit x //= 10 return sum # Prompt user for x x = input("x: ") print(get_sum_digits(int(x))) Problem 29 char = input(“Character: “) if char.isupper(): print(True) else: print(False) 14 Python Problems - Loops Questions Problem 1 Create a list. Loop through the list using: For each loop (similar to the first https://www.w3schools.com/python/python_for_loops.asp). example in: For loop printing the index of the list (use the range function) For loop printing the value using the index (use the range function) Problem 2 Create an empty list. Append a number to this list. Print the list. Problem 3 Create a list. Append values 1 to 100 to this list. Print the final list. Problem 4 Create a list. Append values 1, 3, 5, … + 99 to list. Problem 5 Create a list of strings (with more than 4 letters). Print the 3rd letter of the 2nd string. Problem 6 Create a list with multiple numbers. Print the number in reverse order using a loop. Problem 7 Create a list called even. Create another list called odd. Loop through the values from 1 to 100. If the number is even, add it to the even list. If the number is odd, add it to the odd list. 2 Python Problems - Loops Problem 8 Create and print a dictionary. Problem 9 Create a dictionary. Print its keys and values without a loop. Problem 10 Create a dictionary. Loop over its keys and values using the .items() function. Problem 11 Create a dictionary. Print the value of a particular key. Problem 12 Create a dictionary. Add a key and value to the dictionary. Print the result. Problem 13 Create a list of strings that contains the name Rodrigo. Check if Rodrigo is in the list. If he is, print Found, otherwise Not Found. Use the function in. Problem 14 Create a dictionary with names and phone numbers. Ask user for a name. If name in the dictionary, print their phone number. Problem 15 Create a list of dictionaries. Print it. 3 Python Problems - Loops Problem 16 Create a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. Print the dictionary. Problem 17 Create a dictionary. Loop through the dictionary (using a for loop). Print the keys. Problem 18 Create a dictionary. Loop through the dictionary (using a for loop). Print the values. 4 Python Problems - Loops Solutions Problem 1 x = [10, 9, 5, 3, 2] #for each loop for val in x: print(val) #loop through the list index for i in range(len(x)): print(i) #loop through the values of the list, using the index for i in range(len(x)): print(x[i]) Problem 2 x = [] x.append(10) print(x) Problem 3 x = [] for i in range(1, 101): x.append(i) print(x) 5 Python Problems - Loops Problem 4 x = [] for i in range(1, 100, 2): x.append(i) sum = 0 for val in x: sum += val print(sum) Problem 5 x = ["apple", "banana", "watermellon", "lemon"] print(x[1][2]) Problem 6 x = [9, 3, 5, 3, 2, 1, 0] for i in range(len(x)-1, -1, -1): print(x[i]) 6 Python Problems - Loops Problem 7 even = [] odd = [] for i in range(1, 10): if i % 2 == 0: even.append(i) else: odd.append(i) print(even) print(odd) Problem 8 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) Problem 9 car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(car.values()) print(car.keys()) 7 Python Problems - Loops Problem 10 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x, y in thisdict.items(): print(x, y) Problem 11 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["model"]) print(thisdict["year"]) Problem 12 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) 8 Python Problems - Loops Problem 13 names = ["Bill", "Charlie", "Fred", "George", "Ginny", "Percy", "Rodrigo"] if "Rodrigo" in names: print("Found") else: print("Not found") Problem 14 people = { "Brian": "+1-617-495-1000", "David": "+1-949-468-2750" } name = input("Name: ") if name in people: print(f"Number: {people[name]}") Problem 15 person1 = { "name": "Rodrigo", "age": 28 } person2 = { "name": "Giovanna", "age": 22 } l = [person1, person2] print(l) 9 Python Problems - Loops Problem 16 d=dict() for x in range(1,16): d[x]=x**2 print(d) Problem 17 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for key in thisdict: print(key) Problem 18 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for key in thisdict: print(thisdict[key]) 10 Python Problems - Exceptions Questions Problem 1 Ask the user for a number. If the user does not type in a number, prompt the user again. If the user gives a number, calculate the double. Problem 2 Ask the user for a number. Multiply the number by 5. If the user does not give you a number, prompt the user again. Problem 3 Ask the user for two numbers separated by a comma. If the user does not type in the correct format, prompt the user again. If the user gives two numbers separated by a comma, get the two numbers, and calculate their sum. Problem 4 Create a list (for example fruits = [“apple”, “banana”, “orange”]). Ask the user for a fruit. If the user does not type in a fruit that exists in the list, prompt the user again. If the user gives an existing fruit, print “We have this fruit!”. Problem 5 Create a dictionary (for example fruits = {“apple”:1 , “banana”: 3, “orange”: 2}). Ask the user for a fruit. If the user does not type in a fruit that exists in the dictionary, prompt the user again. If the user gives an existing fruit, print the quantity of this fruit (the value of the fruit in the dictionary). 2 Python Problems - Exceptions Solutions Problem 1 while True: number = input("Number: ") try: double = int(number) * 2 print(double) break except: pass Problem 2 while True: number = input("Number: ") try: result = int(number) * 5 print(result) break except: pass 3 Python Problems - Exceptions Problem 3 while True: numbers = input("Numbers: ") try: number1, number2 = numbers.split(“,”) result = int(number1) + int(number1) print(result) break except: pass Problem 4 fruits = ["apple", "banana", "orange"] while True: fruit = input("fruit: ") try: if fruit in fruits: print("We have this fruit!") break except: pass 4 Python Problems - Exceptions Problem 5 fruits = {"apple":1 , "banana": 3, "orange": 2} while True: fruit = input("fruit: ") try: if fruit in fruits: print(fruits[fruit]) break except: pass 5 Python Problems - Libraries Questions Problem 1 Ask the user for two integers. Write a Python program to generate a random number between two of these integers (inclusive). Use random.randint() (click here!) Problem 2 Create a list with 3 elements. Write a Python program to print a random element from this list. Use random.choice() (click here!) Problem 3 Ask the user for one integer. Calculate the square root of that number. Use the math.sqrt() (click here!) Problem 4 Call the program from the terminal with arguments. Print the arguments. Problem 5 Call the program from the terminal with arguments. Print “Hello, world” if there are arguments. Else, print “Hello” with the value of the argument. Problem 6 Call the program from the terminal with one number as an argument. If there are no arguments, print “Missing command-line argument”. If the argument is not a number, print “Command-line argument is not a number”. If the command-line argument is a number, print the double of it. 2 Python Problems - Libraries Solutions Problem 1 import random x = input("x: ") y = input("y: ") random_number = random.randint(int(x), int(y)) print(random_number) Problem 2 import random fruits = ["apple", "banana", "orange"] random_element = random.choice(fruits) print(random_element) Problem 3 import math number = input("Number: ") root = math.sqrt(int(number)) print(root) 3 Python Problems - Libraries Problem 4 from sys import argv for arg in argv: print(arg) print(len(argv)) Problem 5 from sys import argv if len(argv) == 2: print(f"hello, {argv[1]}") else: print("hello, world") Problem 6 import sys if len(sys.argv) != 2: sys.exit("Missing command-line argument") try: double = int(sys.argv[1]) * 2 print(double) except: sys.exit("Command-line argument is not a number") 4 Python Problems – Conditionals Questions Problem 1 Create a function that returns double the input. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Problem 2 Ask user for two integers in the main function. Create a function that sum them and return the result. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Problem 3 Ask user for two float numbers in the main function. Create a function that sum them and return the result. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Problem 4 Ask user for two integers in the main function. Create a function that subtract them and return the result. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Problem 5 Ask user for two integers in the main function. Create a function that multiply them and return the result. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Problem 6 Ask user for two integers in the main function. Create a function that divides the two integers and return the result. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. 2 Python Problems – Conditionals Problem 7 In this problem, we will convert the value that the user will give to us from miles to kilometers. Ask the user for a number that represents the miles. Write a function to return the kilometers that this number of miles represents. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Hint: 1 mile = 1.60934 kilometers Problem 8 Ask users for an integer. Call a function that sums the digits in this integer. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. Problem 9 Create a function that sums every other digit. Then, create a new file with “test_” in the beginning of the name of the file. Test the function. 3 Python Problems – Conditionals Solutions Problem 1 problem1.py def double(n): return n*2 test_problem1.py from problem1 import double def test_double(): assert double(2) == 4 assert double(3) == 6 Problem 2 problem2.py def func(x,y): sum = int(x) + int(y) return sum test_problem2.py from problem2 import func def test_func(): assert func(2,3) == 5 assert func(10,100) == 110 4 Python Problems – Conditionals Problem 3 problem3.py def func(x,y): sum = float(x) + float(y) return sum test_problem3.py from problem3 import func def test_func(): assert func(2.3,5) == 7.3 assert func(10.7,9.3) == 20.0 Problem 4 problem4.py def func(x,y): result = int(x) - int(y) return result test_problem4.py from problem4 import func def test_func(): assert func(5,3) == 2 assert func(10,20) == -10 5 Python Problems – Conditionals Problem 5 problem5.py def func(x,y): result = int(x) * int(y) return result test_problem5.py from problem5 import func def test_func(): assert func(5,3) == 15 assert func(10,20) == 200 Problem 6 problem6.py def func(x,y): result = int(x) / int(y) return result test_problem6.py from problem6 import func def test_func(): assert func(10,2) == 5 assert func(20,10) == 2 6 Python Problems – Conditionals Problem 7 problem7.py def convert(miles): return miles * 1.60934 test_problem7.py from problem7 import convert def test_convert(): assert convert(10) == 16.0934 assert convert(2) == 3.21868 Problem 8 problem8.py def get_sum_digits(x): sum = 0 while(x != 0): sum += x % 10 x //= 10 return sum test_problem8.py from problem8 import get_sum_digits def test_get_sum_digits(): assert get_sum_digits(12345) == 15 assert get_sum_digits(445566) == 30 7 Python Problems – Conditionals Problem 9 problem9.py def get_sum_digits(x): sum = 0 isAlternateDigit = False while(x != 0): if isAlternateDigit: sum += x % 10 isAlternateDigit = not isAlternateDigit x //= 10 return sum test_problem9.py from problem9 import get_sum_digits def test_get_sum_digits(): assert get_sum_digits(12345) == 6 assert get_sum_digits(445566) == 15 8 Python Problems – File I/O Questions Problem 1 Create a file called days.txt with days of the week, one at each line. Open the file and read its content. days.txt file: January Problem 2 Create a file called days.txt with days of the week, one at each line. Open the file and read the first line. days.txt file: January Problem 3 Create a file called numbers.txt. Write numbers 1 to 100, at each line. Example of numbers.txt file: 1 2 3 ... 99 100 2 Python Problems – File I/O Problem 4 Open the file numbers.txt and read the first line. Use with open() as syntax. Problem 5 Create a spreadsheet file and put 10 of your favorite desserts in the first column. Download file with .csv extension. Open CSV file. Print the elements of the file. Example of desserts.csv file: cheesecake cookie ice-cream ... tiramisu chocolate Problem 6 Create a spreadsheet file and put 10 of your favorite desserts in the first column (with some repetitive ones). Download file with .csv extension. Open CSV file. Count the number of desserts, put result in a dictionary and print it. Problem 7 Create a spreadsheet file and put 10 of your favorite desserts in the first column (with some repetitive ones). In the first row of the column put the title of the column as dessert. Download file with .csv extension. Open CSV file. Print each dessert using the name of the column. 3 Python Problems – File I/O Solutions Problem 1 days_file = open('days.txt','r') print(days_file.read()) days_file.close() Problem 2 days_file = open('days.txt','r') print(days_file.readline(), end="") days_file.close() Problem 3 num_files = open('numbers.txt','w') for i in range(1, 101): num_files.write(f"{str(i)}\n") num_files.close() Problem 4 with open("numbers.txt", "r") as file: print(file.readline()) 4 Python Problems – File I/O Problem 5 import csv with open("desserts.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row[0]) Problem 6 import csv desserts_count = dict() with open("desserts.csv", "r") as file: reader = csv.reader(file) for row in reader: current_dessert = row[0] if current_dessert in desserts_count: desserts_count[current_dessert] += 1 else: desserts_count[current_dessert] = 1 print(desserts_count) 5 Python Problems – File I/O Problem 7 import csv desserts_count = dict() with open("desserts.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(row['dessert']) 6 Python Problems – Regular Expressions Questions Problem 1 Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9). Problem 2 Write a Python program that matches a string that has an a followed by zero or more b's. Problem 3 Write a Python program that matches a string that has an a followed by one or more b's. Problem 4 Write a Python program that matches a string that has an a followed by three 'b'. Problem 5 Write a Python program that matches a string that has an a followed by two to three 'b'. Problem 6 Write a Python program to find sequences of lowercase letters joined with a underscore. Problem 7 Write a Python program that matches a word at the beginning of a string. 2 Python Problems – Regular Expressions Problem 8 Write a Python program that matches a word containing 'z'. Problem 9 Write a Python program to search some literals strings in a string. Go to the editor Sample text : 'The quick brown fox jumps over the lazy dog.' Searched words : 'fox', 'dog', 'horse'. Problem 10 Write a Python program to find the substrings within a string. Sample text : 'Python exercises, PHP exercises, C# exercises' Pattern : 'exercises' Note: There are two instances of exercises in the input string. Problem 11 Write a Python program to extract year, month, and date from an URL. Problem 12 Write a Python program to find all words starting with 'a' or 'e' in each string. 3 Python Problems – Regular Expressions Solutions Problem 1 import re def is_allowed_specific_char(string): s = re.search(r'[^a-zA-Z0-9.]', string) return not bool(s) print(is_allowed_specific_char("ABCDEFabcdef123450")) print(is_allowed_specific_char("*&%@#!}{")) Problem 2 import re def text_match(text): if re.search(r'ab*?', text): return 'Found a match!' else: return('Not matched!') print(text_match("ac")) print(text_match("abc")) print(text_match("abbc")) 4 Python Problems – Regular Expressions Problem 3 import re def text_match(text): if re.search(r'ab+?', text): return 'Found a match!' else: return('Not matched!') print(text_match("ac")) print(text_match("abc")) print(text_match("abbc")) Problem 4 import re def text_match(text): if re.search(r'ab{3}?', text): return 'Found a match!' else: return('Not matched!') print(text_match("abbb")) print(text_match("aabbbbbc")) 5 Python Problems – Regular Expressions Problem 5 import re def text_match(text): if re.search(r'ab{2,3}?', text): return 'Found a match!' else: return('Not matched!') print(text_match("abbb")) print(text_match("aabbbbbc")) Problem 6 import re def text_match(text): if re.search(r' ^[a-z]+_[a-z]+$', text): return 'Found a match!' else: return('Not matched!') print(text_match("aab_cbbbc")) print(text_match("aab_Abbbc")) print(text_match("Aaab_abbbc")) 6 Python Problems – Regular Expressions Problem 7 import re def text_match(text): if re.search(r' ^\W+', text): return 'Found a match!' else: return('Not matched!') print(text_match("The quick brown fox jumps over the lazy dog.")) print(text_match(" The quick brown fox jumps over the lazy dog.")) Problem 8 import re def text_match(text): if re.search(r' ^\w*z.\w*', text): return 'Found a match!' else: return('Not matched!') print(text_match("The quick brown fox jumps over the lazy dog.")) print(text_match("Python Exercises.")) 7 Python Problems – Regular Expressions Problem 9 import re patterns = [ 'fox', 'dog', 'horse' ] text = 'The quick brown fox jumps over the lazy dog.' for pattern in patterns: print('Searching for "%s" in "%s" ->' % (pattern, text),) if re.search(pattern, text): print('Matched!') else: print('Not Matched!') Problem 10 import re text = 'Python exercises, PHP exercises, C# exercises' pattern = 'exercises' for match in re.findall(pattern, text): print('Found "%s"' % match) 8 Python Problems – Regular Expressions Problem 11 import re def extract_date(url): return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url) url1= "https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odellbeckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/" print(extract_date(url1)) Problem 12 import re # Input. text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly." #find all the words starting with 'a' or 'e' list = re.findall("[ae]\w+", text) # Print result. print(list) 9 Python Problems – Regular Expressions Questions Problem 1 Write a Python program to create a Vehicle class with max_speed and mileage instance attributes. Problem 2 Create a child class Bus that will inherit all of the variables and methods of the Vehicle class (Vehicle class create on Problem 1). Problem 3 Create a Bus class that inherits from the Vehicle class. Give the capacity argument of Bus.seating_capacity() a default value of 50. Hint: The Vehicle class is the following: class Vehicle: def __init__(self, name, max_speed, mileage): self.name = name self.max_speed = max_speed self.mileage = mileage def seating_capacity(self, capacity): return f"The seating capacity of a {self.name} is {capacity} passengers" 2 Python Problems – Regular Expressions Problem 4 Define a class attribute”color” with a default value white. I.e., Every Vehicle should be white. Use the following code for this exercise. class Vehicle: def __init__(self, name, max_speed, mileage): self.name = name self.max_speed = max_speed self.mileage = mileage class Bus(Vehicle): pass class Car(Vehicle): pass Problem 5 Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will become the final amount = total fare + 10% of the total fare. Note: The bus seating capacity is 50. so the final fare amount should be 5500. You need to override the fare() method of a Vehicle class in Bus class. Use the following code for your parent Vehicle class. We need to access the parent class from inside a method of a child class. 3 Python Problems – Regular Expressions class Vehicle: def __init__(self, name, mileage, capacity): self.name = name self.mileage = mileage self.capacity = capacity def fare(self): return self.capacity * 100 class Bus(Vehicle): pass School_bus = Bus("School Volvo", 12, 50) print("Total Bus fare is:", School_bus.fare()) 4 Python Problems – Regular Expressions Solutions Problem 1 class Vehicle: def __init__(self, max_speed, mileage): self.max_speed = max_speed self.mileage = mileage modelX = Vehicle(240, 18) print(modelX.max_speed, modelX.mileage) Problem 2 class Vehicle: def __init__(self, name, max_speed, mileage): self.name = name self.max_speed = max_speed self.mileage = mileage class Bus(Vehicle): pass School_bus = Bus("School Volvo", 180, 12) print("Vehicle Name:", School_bus.name, "Mileage:", School_bus.mileage) "Speed:", School_bus.max_speed, 5 Python Problems – Regular Expressions Problem 3 class Vehicle: def __init__(self, name, max_speed, mileage): self.name = name self.max_speed = max_speed self.mileage = mileage def seating_capacity(self, capacity): return f"The seating capacity of a {self.name} is {capacity} passengers" class Bus(Vehicle): # assign default value to capacity def seating_capacity(self, capacity=50): return super().seating_capacity(capacity=50) School_bus = Bus("School Volvo", 180, 12) print(School_bus.seating_capacity()) 6 Python Problems – Regular Expressions Problem 4 class Vehicle: # Class attribute color = "White" def __init__(self, name, max_speed, mileage): self.name = name self.max_speed = max_speed self.mileage = mileage class Bus(Vehicle): pass class Car(Vehicle): pass School_bus = Bus("School Volvo", 180, 12) print(School_bus.color, School_bus.name, "Mileage:", School_bus.mileage) "Speed:", School_bus.max_speed, car = Car("Audi Q5", 240, 18) print(car.color, car.name, "Speed:", car.max_speed, "Mileage:", car.mileage) 7 Python Problems – Regular Expressions Problem 5 class Vehicle: def __init__(self, name, mileage, capacity): self.name = name self.mileage = mileage self.capacity = capacity def fare(self): amount = super().fare() amount += amount * 10 / 100 return amount class Bus(Vehicle): pass School_bus = Bus("School Volvo", 12, 50) print("Total Bus fare is:", School_bus.fare()) 8 DOR'S CODING SCHOOL Learn To Program Workbook EBOOK Syllabus 2 Syllabus Topic Weeks 1 Scratch 2 3 4 5 C Language 6 7 Arrays 8 9 Algorithms 10 11 Memory 12 13 Data Structure 14 15 Python 16 17 Content Watch Scratch lecture (Lecture 0 video) Watch Dor’s Coding School Scratch Intro video Do MIT PDFs Watch Soccer Tips video Start Soccer Project Finish Soccer Project Watch our solution. Watch C lecture (Lecture 1 video) Watch Dor's Coding School C problems Finish Dor's C problems (each problem under 3 minutes) Finish Lab 1 Finish Cash Finish Mario Finish Credit (if more advanced) Watch Arrays lecture (Lecture 2 video) Watch Dor’s Array Video (each problem under 4 minutes) Finish Lab 2 Finish Runoff Finish Caesar or Substitution (if more comfortable) Watch Algorithms lecture (Lecture 3 video) Watch Dor’s Algorithms video Finish Lab 3 Finish Plurality Finish Runoff Watch Memory lecture (Lecture 4 video) Watch Dor’s Memory Video (each problem under 4 minutes) Finish Lab 4 Finish Filter Finish Recover Watch Data Structure lecture (Lecture 5 video) Watch Dor’s Memory Video (each problem under 5 minutes) Start Speller Watch Python Lecture (Lecture 6 video) Watch Scratch to Python Dor’s Videos (each problem under 2 min) Do Warmup1 and String1 on CodingBat Finish Hello and Mario Do Warmup1 and String1 on CodingBat Finish Hello and Mario Syllabus 18 19 Python 20 21 22 23 24 SQL 25 26 27 28 Flask 29 30 31 32 HTML, CSS 33 34 Python 35 36 Django 37 SQL, Models and Migrations 38 39 40 3 Do Logic1 and List1 on CodingBat Finish Cash Do Warmup2 and String2 on CodingBat Finish Credit Finish Readability Do all CodingBat problems (except for List 2 and Logic 2) in under 90 minutes. Watch Python Advanced Videos. Do all problems under 4 minutes. Finish Lab 6 Finish DNA Watch SQL lecture Do all SQL Bolt problems Finish Lab 7 Finish Movies Finish Fiftyville Watch HTML, CSS and Javascript video Watch Dor’s Video Finish Lab 8 Finish Problem Set 8 Watch Flask Video Watch Dor’s To Do Video Finish Lab 9 Finish Finance Start final project Keep working on final project Finish Final Project Watch HTML/CSS Lecture Sololearn Responsive Web Design Sololearn HTML Sololearn CSS Watch Python Lecture Start Search Finish Search Watch Django Lecture Start Wiki Watch Python Lecture Finish Wiki Watch SQL lecture Start Commerce Continue Commerce Finish Commerce Syllabus 41 JavaScript 42 43 React-Redux 44 45 46 Market Yourself 47 48-53 4 Watch Javascript Sololearn Javascript Finish Javascript Sololearn React/Redux Watch and Do by yourself React To Do Start Network Continue Network Finish Network Watch course How To Market Yourself as a Self-Taught Developer Watch Git Plan Final Project Finish Final Project Checklist – Soccer (Problem Set 0) Problem Set 0 – Soccer Game Requirements • Your project must have at least two sprites, at least one of which must resemble something other than a cat. • Your project must have at least three scripts total (i.e., not necessarily three per sprite). • Your project must use at least one condition, one loop, and one variable. • Your project must use at least one sound. • Your project should be more complex than most of those demonstrated in lecture (many of which, though instructive, were quite short) but it can be less complex than Ivy’s Hardest Game. As such, your project should probably use a few dozen puzzle pieces overall. Welcome Page Background color always changing Since it is changing continuously, this is a forever loop. The only reason why this loop ends is when you click to Start the game. So, to make this background color always change you should use: 2 Checklist – Soccer (Problem Set 0) Character moving/dancing Since it is changing continuously, this is a forever loop. The property that is always changing is the costume. If you look on Scratch, you will find 13 costumes to this character. So, to make this character always change position you should use: Ball up and down Since it is changing continuously, this is a forever loop. The only reason why this loop ends is when you click to Start the game. To make the ball go up and down use the ‘change by y’ block. So, you should use something like this: 3 Checklist – Soccer (Problem Set 0) At this point, the project that we created looks like this: Game Page How to Kick You are going to use a Sensing block in the ball that is going to set where the ball should go depending on each character that is close to it. For example, if the key D is pressed and the character is Ben, the ball should move 30 steps to the right. This is going to be a forever loop. Look at the example below: 4 Checklist – Soccer (Problem Set 0) How to score goal Create a red line to go over the goal. The line is in the image below: Make this line invisible by using the set ghost effect. Use the forever loop to check if the ball touched the line. If they touched, the goal was scored. At this point, our project looks like this: 5 Checklist – Soccer (Problem Set 0) End of the game In the background you can create a forever loop to make the game working. And you can create one if condition to set when this game is going to finish. For example, after someone scores a goal, you can finish the game and switch the background to another one, creating this way a Congratulations Page. At this point, our project looks like this: 6 How To Use The Debug50 How To Use The Debug50 In CS50 IDE, you can use a powerful tool, developed by CS50’s staff, called debug50 to help you to debug programs. This debugger is a program that will run your code step-by-step and let you look at variables and other information while your code is running. How To Run The Debugger? The first thing you have to do is adding a breakpoint, or indicator for a line of code where the debugger should pause our program. The image below has an example of what you should do if your code was written in C Language: 2 How To Use The Debug50 The image below has an example of what you should do if your code was written in Python: To start the debug50, you have to run in your terminal the following command: C language: make name_of_your_program debug50 ./name_of_your_program Python: debug50 name_of_your_program.py The example below we have a program in C Language and we are trying to run it using the debug50. Check how you should do it: The example below we have a program in Python and we are trying to run it using the debug50. Check how you should do it: 3 How To Use The Debug50 If you forget to put a breakpoint in your code, the terminal will return you a message explaining to do it, like we can see in the image below: Tools In Debug50 1. Breakpoints: the debugger show to us the breakpoint that we put in the code. You can check this by the green arrows in the image below. 4 How To Use The Debug50 2. Local variables: the debugger show to us the variables used in the code and its type and current values. You can check this by the green arrows in the image below. 3. Resume: it is the blue triangle pointed by the yellow arrow in the image below. When you click in the button, the debug50 will run your code until it hits the next breakpoint. 4. Step Over: it is the curved arrow pointed by the yellow arrow in the image below. When you click this button the debug50 is going to skip over a block of code. This is used, for example, when you use the strlen function from string.h library in C Language. 5 How To Use The Debug50 5. Step Into: it is the down arrow pointed by the yellow arrow in the image below. When you click in the button, the debug50 is going to move through your code slowly one line at a time. 6. Step Out: it is the button pointed by the yellow arrow in the image below. When you click on this button, the debug50 is going to run your code step out of a function (other than main). This is one button that is rarely used. 6 How To Use The Debug50 7. Deactivate All Breakpoints: it is the circle pointed by the yellow arrow in the image below. When you click this button, the debug50 clears all the breakpoint that you set in your program. 7 31 Programming Fundamental Problems – C Language Questions Problem 1 Ask user for two integer inputs and print which one of them is the largest. Problem 2 Print numbers from 1 to 100 in C using for loops. Problem 3 Print the following sequence of number: 0 + 2 + 4 + 6 .... 98 + 100 using for loops. Problem 4 Print numbers from 100 to 0 (backwards) using for loops. Problem 5 Print numbers from 1 to 100 using a while loop. Problem 6 Print the following sequence of number: 0 + 2 + 4 + 6 .... 98 + 100 using while loops. Problem 7 Print numbers from 100 to 0 (backwards) using while loops. Problem 8 Ask user for two integer inputs. Print YES if they are equal, NO otherwise. 2 31 Programming Fundamental Problems – C Language Problem 9 Create a function that prints Hello. Problem 10 Create a function that prints Hello as many times as you want. Problem 11 Create a function that returns the double of a number. Call the function multiple times. Print the result. Problem 12 Print “cough” in 3 ways: 1. Using 3 printf statements 2. Using a loop 3. Using a function Problem 13 Ask user for two integer inputs. Write a C function to return the sum of the two given integer values but if two values are the same, then return triple their sum. Print the result. Problem 14 Ask user for two integer inputs. Write a C function to compute return True if one of them is 30 or if their sum is 30. Print the result. Problem 15 Sum the numbers from 1 to 10. Print the result. 3 31 Programming Fundamental Problems – C Language Problem 16 Write a C program to check if two integers are in the range 100…200 inclusive. Problem 17 Ask user for integer input. Print if input is even or odd. Note: use the remainder. Problem 18 Ask user for integer input which will be our “change”. Use a while loop to determine how many quarters will be given as “change”. Example: 76 as changes uses 3 quarters. 29 as change uses 1 quarter. Problem 19 Create a function that keeps asking a user for a positive value. This function should return the user input only if it is positive. Use do…while. Keep looping until user inputs positive value. Return the number to main and print it. Problem 20 Write a C program to check which number nearest to the value 100 among two given integers. Return 0 if the two numbers are equal. Problem 21 Write a C program to check if two given integers have the same last digit. Problem 22 Write a C program to compute the sum of the two given integers. If the sum is in the range 10…20 inclusive return 30. 4 31 Programming Fundamental Problems – C Language Problem 23 Write a C program that accept two integers and return True if either one is 5 or their sum or difference is 5. Problem 24 Loop through values from 1 to 50 inclusive. Check the conditions: āŖ āŖ āŖ āŖ If the current number is divisible by 3, print Fizz. If the current number is divisible by 5, print Buzz. If the current number is divisible by both 3 and 5, print FizzBuzz. Else, print the number. Problem 25 Write a program in C to display the the following pattern using an asterisk. The pattern will be : * ** *** **** Problem 26 Write a program in C to make such a pattern like right angle triangle with a number which will repeat a number in a row. The pattern like: 1 22 333 4444 5 31 Programming Fundamental Problems – C Language Problem 27 Write a program in C to make such a pattern like right angle triangle with a number which will repeat a number in a row. The pattern like: 1 23 456 7 8 9 10 Problem 28 Create a C function to get how many digits a credit card has. Problem 29 Ask user for an integer. Call a function that sums the digits in this integer. Print the result. Problem 30 Create a C function that sum every other digit. Problem 31 Grab the fist two digits of 23032243 in two different ways. 6 31 Programming Fundamental Problems – C Language Solutions Problem 1 #include <cs50.h> #include <stdio.h> int main(void) { // Prompt user for x int x = get_int("x: "); // Prompt user for y int y = get_int("y: "); // Compare x and y if (x < y) { printf("x is less than y\n"); } else if (x > y) { printf("x is greater than y\n"); } else { printf("x is equal to y\n"); } } 7 31 Programming Fundamental Problems – C Language Problem 2 #include <stdio.h> int main(void) { for (int i = 0; i < 101; i++) { printf("%d\n", i); } } Problem 3 #include <stdio.h> int main(void) { for (int i = 0; i < 101; i+=2) { printf("%i\n", i); } } 8 31 Programming Fundamental Problems – C Language Problem 4 #include <stdio.h> int main(void) { for (int i = 100; i >= 0; i-=1) { printf("%i\n", i); } } Problem 5 #include <stdio.h> int main(void) { int counter = 0; while (counter <= 100) { printf("%i\n", counter); counter += 1; } } 9 31 Programming Fundamental Problems – C Language Problem 6 #include <stdio.h> int main(void) { int counter = 0; while (counter <= 100) { printf("%i\n", counter); counter += 2; } } Problem 7 #include <stdio.h> int main(void) { int counter = 100; while (counter >= 0) { printf("%i\n", counter); counter -= 1; } } 10 31 Programming Fundamental Problems – C Language Problem 8 #include <cs50.h> #include <stdio.h> int main(void) { // Prompt user for x int x = get_int("x: "); // Prompt user for y int y = get_int("y: "); // Compare x and y if (x == y) { printf("YES\n"); } else { printf("NO\n"); } } 11 31 Programming Fundamental Problems – C Language Problem 9 #include <stdio.h> void say_hello(void); int main(void) { say_hello(); } void say_hello() { printf("hello\n"); } Problem 10 #include <stdio.h> void say_hello(int x); int main(void) { say_hello(4); } 12 31 Programming Fundamental Problems – C Language void say_hello(int x) { for (int i = 0; i < x; i++) { printf("Hello\n"); } } Problem 11 #include <stdio.h> int double_num(int x); int main(void) { int result = double_num(4); printf("%i\n", result); printf("%i\n", double_num(5)); printf("%i\n", double_num(6)); printf("%i\n", double_num(7)); } int double_num(int x) { return 2*x; } 13 31 Programming Fundamental Problems – C Language Problem 12 #include <stdio.h> void cough(int x); int main(void) { printf("Cough\n"); printf("Cough\n"); printf("Cough\n"); for (int i = 0; i < 3; i ++) { printf("Cough\n"); } cough(3); } void cough(int x) { for (int i = 0; i < 3; i ++) { printf("Cough\n"); } } 14 31 Programming Fundamental Problems – C Language Problem 13 #include <cs50.h> #include <stdio.h> int test(int x, int y); int main(void) { int a = get_int("What is the first number?\n"); int b = get_int("What is the second number?\n"); int result = test(a, b); printf("The result is %d\n", result); } int test(int x, int y) { if (x == y) { return 3*(x+y); } else { return x + y; } } 15 31 Programming Fundamental Problems – C Language Problem 14 #include <cs50.h> #include <stdio.h> int test(int x, int y); int main(void){ int a = get_int("What is the first number?\n"); int b = get_int("What is the second number?\n"); int result = test(a, b); printf("The result is %d\n", result); } int test(int x, int y) { return x == 30 || y == 30 || (x + y == 30); } Problem 15 #include <stdio.h> int main(void){ int sum = 0; for (int j = 1; j <= 10; j++) { sum = sum + j; } printf("\nThe Sum is : %d\n", sum); } 16 31 Programming Fundamental Problems – C Language Problem 16 #include <stdio.h> int test(int x, int y); int main(void) { printf("%d\n",test(100, 199)); printf("%d\n",test(250, 300)); printf("%d\n",test(105, 190)); } int test(int x, int y) { return (x >= 100 && x <= 200) || (y >= 100 && y <= 200); } Problem 17 #include <cs50.h> #include <stdio.h> int main(void) { // Prompt user for integer int n = get_int("n: "); 17 31 Programming Fundamental Problems – C Language // Check parity of integer if (n % 2 == 0) { printf("even\n"); } else { printf("odd\n"); } } Problem 18 #include <cs50.h> #include <stdio.h> int main(void) { int x = get_int("What's your change?\n"); int count_of_quarters = 0; while (x >= 25) { x -= 25; count_of_quarters += 1; } printf("%d\n", count_of_quarters); } 18 31 Programming Fundamental Problems – C Language Problem 19 #include <cs50.h> #include <stdio.h> int get_positive_int(void); int main(void) { int i = get_positive_int(); printf("%i\n", i); } // Prompt user for positive integer int get_positive_int(void) { int n; do { n = get_int("Positive Integer: "); } while (n); return n; } 19 31 Programming Fundamental Problems – C Language Problem 20 #include <stdlib.h> #include <stdio.h> int test(int x, int y); int main(void) { printf("%d\n",test(78, 95)); printf("%d\n",test(95, 95)); printf("%d\n",test(99, 70)); } int test(int x, int y) { int val = abs(x - 100); int val2 = abs(y - 100); if (val == val2) { return 0; } else { if (val < val2) { return x; } 20 31 Programming Fundamental Problems – C Language else { return y; } } } Problem 21 #include <stdlib.h> #include <stdio.h> int test(int x, int y); int main(void) { printf("%d\n",test(123, 456)); printf("%d\n",test(12, 512)); printf("%d\n",test(7, 87)); printf("%d\n",test(12, 45)); } int test(int x, int y) { return abs(x % 10) == abs(y % 10); } 21 31 Programming Fundamental Problems – C Language Problem 22 #include <stdlib.h> #include <stdio.h> int test(int x, int y); int main(void) { printf("%d\n",test(123, 456)); printf("%d\n",test(12, 512)); printf("%d\n",test(7, 87)); printf("%d\n",test(12, 45)); } int test(int x, int y) { if (a + b >= 10 && a + b <= 20) { return 30; } else { return a + b; } } 22 31 Programming Fundamental Problems – C Language Problem 23 #include <stdlib.h> #include <stdio.h> int test(int x, int y); int main(void) { printf("%d\n",test(5, 4)); printf("%d\n",test(4, 3)); printf("%d\n",test(1, 4)); } int test(int x, int y) { return x == 5 || y == 5 || x + y == 5 || abs(x - y) == 5; } Problem 24 #include <stdio.h> int main(void){ for (int i = 0; i <= 50; i++) { if (i % 3 == 0 && i % 5 == 0) 23 31 Programming Fundamental Problems – C Language { printf("Fizzbuzz\n"); } else if (i % 3 == 0) { printf("Fizz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else { printf("%d\n", i); } } } Problem 25 #include <cs50.h> #include <stdio.h> int main(void) { int rows = get_int("Input no. of rows:\n"); for(int i=1;i<=rows;i++) { 24 31 Programming Fundamental Problems – C Language for(int j=1;j<=i;j++) { printf("*\n"); } } } Problem 26 #include <cs50.h> #include <stdio.h> int main(void) { int rows = get_int("Input number of rows : "); for(int i = 1;i <= rows; i++) { for(int j = 1;j <= i;j++) { printf("%d",i); } printf("\n"); } } 25 31 Programming Fundamental Problems – C Language Problem 27 #include <cs50.h> #include <stdio.h> int main(void) { int k=1; rows = get_int("Input number of rows :\n "); for(int i=1;i<=rows;i++) { for(int j=1;j<=i;j++) { printf("%d ",k); k++; } printf("\n"); } } Problem 28 #include <cs50.h> #include <stdio.h> int get_num_digits(long card_num); 26 31 Programming Fundamental Problems – C Language int main(void) { int num = get_int("What's your number? \n"); int num_digits = get_num_digits(num); printf("Your number has %d digits\n", num_digits); } int get_num_digits(long card_num) { int count = 0; while (card_num != 0) { card_num /= 10; count += 1; } return count; } Problem 29 #include <cs50.h> #include <stdio.h> int sum_digits(long card_num); 27 31 Programming Fundamental Problems – C Language int main(void) { int num = get_int("What's your number? \n"); int num_digits = sum_digits(num); printf("Your number sum of digits is %d\n", num_digits); } int sum_digits(long card_num) { int sum = 0; while (card_num > 0) { sum += (card_num % 10) card_num /= 10; } return sum; } Problem 30 #include <cs50.h> #include <stdio.h> int sum_every_other_digit(long card_num); 28 31 Programming Fundamental Problems – C Language int main(void) { int num = get_int("What's your number? \n"); int num_digits = sum_every_other_digit(num); printf("Sum of every other digit is %d\n", num_digits); } int sum_every_other_digit(long card_num) { int isAlternateDigit = false; int sum = 0; while (card_num > 0) { if (isAlternateDigit) { sum += (card_num % 10) } isAlternateDigit = !isAlternateDigit; card_num /= 10; } return sum; } Problem 31 #include <math.h> #include <stdio.h> 29 31 Programming Fundamental Problems – C Language int main(void) { int num = 23032234; int first_two_digits1 = 23032234 / 1000000; int first_two_digits2 = 23032234 / pow(10, 6); } 30 12 Arrays Problems – C Language Questions Problem 1 Create an array with 10 elements. Print the elements of the array Problem 2 Create an array with 10 elements. Sum the value of all elements. Print the result. Problem 3 Create an array with 10 elements. Calculate the average of them. Print the result. Problem 4 Create a character variable. Print its ASCII value. Problem 5 Ask user for their name. Print every single character of their name. Problem 6 Ask user for their name. Print every single ASCII number of letters in their name. Problem 7 Ask user for their name with all letters in lowercase. Print how far each letter is from 'a' in ASCII table. 2 12 Arrays Problems – C Language Problem 8 Ask user for an string input. Capitalize all letter without using isLower() or toUpper(). Problem 9 Ask user for an string input. Capitalize all letter using isLower() or toUpper(). Problem 10 Cryptography is the art of scrambling, or hiding information. One way of doing that is to add a number to the ASCII value to letters of a string. Example: ORIGINAL String: I L O V E Y O U ASCII: 73 76 79 86 69 89 79 85 Adding +1 AFTER CRYPTOGRAPHY ASCII 74 77 80 87 70 90 80 86 STRING J M P W F Z P V Store the variable ILOVEYOU in a string. Add 1 to each letter. Print the encrypted message (JMPWFZPV). 3 12 Arrays Problems – C Language Problem 11 Create a program that prints the second argument if the command line if number of arguments is 2. Print hello world otherwise. Problem 12 Print all letters of the second argument from the command line if the number of arguments equals 2. Solutions 4 12 Arrays Problems – C Language Problem 1 #include <stdio.h> int main(void) { int a[10] = {8, 4, 2, 1, 4, 9, 6, 7, 8, 9}; for (int i = 0; i < 10; i++) { printf("%d\n", a[i]); } } Problem 2 #include <stdio.h> int main(void) { int a[10] = {8, 4, 2, 1, 4, 9, 6, 7, 8, 9}; int sum = 0; for (int i = 0; i < 10; i++) { sum += a[i]; } printf("%d\n", sum); } 5 12 Arrays Problems – C Language Problem 3 #include <stdio.h> int main(void) { int a[10] = {8, 4, 2, 1, 4, 9, 6, 7, 8, 9}; int sum = 0; for (int i = 0; i < 10; i++) { sum += a[i]; } float average = (float) sum / 10; printf("%0.2f\n", average); } Problem 4 #include <stdio.h> int main(void) { char c = 'a'; printf("%i\n", c); } Problem 5 6 12 Arrays Problems – C Language #include <stdio.h> #include <cs50.h> #include <string.h> int main(void) { string s = get_string("Input: \n"); for (int i = 0; i < strlen(s); i++) { printf("%c", s[i]); } printf("\n"); } Problem 6 #include <stdio.h> #include <cs50.h> #include <string.h> int main(void) { string s = get_string("Input: \n"); for (int i = 0; i < strlen(s); i++) { printf("%i", s[i]); } printf("\n"); } Problem 7 7 12 Arrays Problems – C Language #include <stdio.h> #include <cs50.h> #include <string.h> int main(void) { string s = get_string("Input: \n"); for (int i = 0; i < strlen(s); i++) { printf("%i", s[i] - 'a'); } printf("\n"); } Problem 8 #include <stdio.h> #include <cs50.h> #include <string.h> int main(void) { string s = get_string("Before: "); printf("After: "); for (int i = 0, n = strlen(s); i < n; i++) { if (s[i] >= 'a' && s[i] <= 'z') { 8 12 Arrays Problems – C Language printf("%c", s[i] - 32); } else { printf("%c", s[i]); } } printf("\n"); } Problem 9 #include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> int main(void) { string s = get_string("Before: "); printf("After: "); for (int i = 0, n = strlen(s); i < n; i++) { if (islower(s[i])) { printf("%c", toupper(s[i])); } else 9 12 Arrays Problems – C Language { printf("%c", s[i]); } } printf("\n"); } Problem 10 #include <stdio.h> #include <cs50.h> #include <ctype.h> int main(void) { string s = "ILOVEYOU"; printf("After: "); for (int i = 0, n = strlen(s); i < n; i++) { printf("%c", s[i] + 1); } } Problem 11 #include <stdio.h> #include <cs50.h> int main(int argc, string argv[]) 10 12 Arrays Problems – C Language { if (argc == 2) { printf("hello, %s\n", argv[1]); } else { printf("hello, world\n"); } } Problem 12 #include <stdio.h> #include <cs50.h> #include <string.h> int main(int argc, string argv[]) { if (argc == 2) { for (int i = 0, n = strlen(argv[1]); i < n; i++) { printf("%c\n", argv[1][i]); } } } 11 3 Problems of Structs – C Language Questions Problem 1 Create a struct called student with two properties: name and student_id. Initialize those properties. Print them. Problem 2 Create an array of student structs (same from problem1). Initialize each one of them. Print the name and student_id of one of them. Problem 3 Implement Bubble Sort with an array of 6 elements. 2 3 Problems of Structs – C Language Solutions Problem 1 #include <cs50.h> #include <stdio.h> #include <string.h> typedef struct { string name; int student_id; } student; int main(void) { student p1; p1.name = "RODRIGO"; p1.student_id = 4; printf("%d\n", p1.student_id); printf("%s\n", p1.name); } 3 3 Problems of Structs – C Language Problem 2 #include <cs50.h> #include <stdio.h> #include <string.h> typedef struct { string name; int student_id; } student; int main(void) { student students[3]; students[0].name = "RODRIGO"; students[0].student_id = 4; students[1].name = "ELLA"; students[1].student_id = 5; students[2].name = "MARLENE"; students[2].student_id = 6; printf("%d\n", students[0].student_id); printf("%s\n", students[2].name); } 4 3 Problems of Structs – C Language Problem 3 #include <stdio.h> #include <cs50.h> int main() { int array[6] = {5, 4, 2, 1, 10, 3}; for (int i = 0 ; i < 5; i++) { for (int j = 0 ; j < 6 - i - 1; j++) { if (array[j] > array[j+1]) /* For decreasing order use '<' instead of '>' */ { int swap = array[j]; array[j] = array[j+1]; array[j+1] = swap; } } } printf("Sorted list in ascending order:\n"); for (int i = 0; i < 6; i++) printf("%d\n", array[i]); return 0; } 5 10 Problems of Data Structures – C Language Questions Problem 1 Create a struct with int properties of a car. Put struct in a variable called audi. Create a pointer called ptr that points to this struct. Print the same property using: a) (*ptr).propertyName b) ptr->propertyName c) audi.propertyName Problem 2 Create a linked list with 3 nodes. Problem 3 Using the linked list from last problem, print the values of the nodes in a linked list. Problem 4 Using linked list from last problem, insert node at the front of a linked list. Problem 5 Using linked list from last problem, delete node from the front of a linked list. Problem 6 Using linked list from previous problem, free them from memory. Problem 7 Create a person struct that has as properties: a) Two pointers to two other "person" structs 2 10 Problems of Data Structures – C Language b) A char array with two elements called alleles Then create a person with two parents (which are also person structs). Print one of the parent’s alleles. Problem 8 Using the struct from last problem. Free them from memory. Problem 9 Create an array of 5 pointers. The pointers point to a LinkedList Node. Create a new node. Make the pointer at index 0 point to the new node. Problem 10 Create an array of 5 pointers. The pointers point to a LinkedList Node. Create a new node. Make the pointer at index 0 point to this new node. Create a second new node. Add this second node at index 0 as well (before node you created previously). 3 10 Problems of Data Structures – C Language Solutions Problem 1 #include <stdio.h> typedef struct{ int km; int kph; int kg; } car; int main(void){ car audi = {12000, 230, 760}; car *ptr = &audi; printf("%d\n", (*ptr).km); printf("%d\n", ptr->km); printf("%d\n", audi.km); } 4 10 Problems of Data Structures – C Language Problem 2 #include <stdio.h> #include <stdlib.h> // Represents a node typedef struct node { int number; struct node *next; } node; int main(void) { // List of size 0, initially not pointing to anything node *list = NULL; // Add number to list node *n = malloc(sizeof(node)); if (n == NULL) { return 1; } n->number = 1; n->next = NULL; // We create our first node, store the value 1 in it, and leave the next // pointer to point to nothing. Then, our list variable can point to it. 5 10 Problems of Data Structures – C Language list = n; // Add number to list n = malloc(sizeof(node)); if (n == NULL) { return 1; } n->number = 2; n->next = NULL; // Now, we go our first node that list points to, and sets the next pointer // on it to point to our new node, adding it to the end of the list: list->next = n; // Add number to list n = malloc(sizeof(node)); if (n == NULL) { return 1; } n->number = 3; n->next = NULL; // We can follow multiple nodes with this syntax, using the next pointer // over and over, to add our third new node to the end of the list: list->next->next = n; } 6 10 Problems of Data Structures – C Language Problem 3 #include <stdio.h> #include <stdlib.h> // Represents a node typedef struct node { int number; struct node *next; } node; int main(void) { // List of size 0, initially not pointing to anything node *list = NULL; // Add number to list node *n = malloc(sizeof(node)); n->number = 1; n->next = NULL; // We create our first node, store the value 1 in it, and leave the next // pointer to point to nothing. Then, our list variable can point to it. list = n; // Add number to list n = malloc(sizeof(node)); 7 10 Problems of Data Structures – C Language n->number = 2; n->next = NULL; // Now, we go our first node that list points to, and sets the next pointer // on it to point to our new node, adding it to the end of the list: list->next = n; // Add number to list n = malloc(sizeof(node)); n->number = 3; n->next = NULL; // We can follow multiple nodes with this syntax, using the next pointer // over and over, to add our third new node to the end of the list: list->next->next = n; node * temp = list; while (temp != NULL) { printf("%d\n", temp->number); temp = temp->next; } } 8 10 Problems of Data Structures – C Language Problem 4 #include <stdio.h> #include <stdlib.h> // Represents a node typedef struct node { int number; struct node *next; } node; int main(void) { // List of size 0, initially not pointing to anything node *list = NULL; // Add number to list node *n = malloc(sizeof(node)); n->number = 1; n->next = NULL; // We create our first node, store the value 1 in it, and leave the next // pointer to point to nothing. Then, our list variable can point to it. list = n; // Add number to list n = malloc(sizeof(node)); 9 10 Problems of Data Structures – C Language n->number = 2; n->next = NULL; // Now, we go our first node that list points to, and sets the next pointer // on it to point to our new node, adding it to the end of the list: list->next = n; // Add number to list n = malloc(sizeof(node)); n->number = 3; n->next = list; // We can follow multiple nodes with this syntax, using the next pointer // over and over, to add our third new node to the end of the list: list = n; } Problem 5 #include <stdio.h> #include <stdlib.h> // Represents a node typedef struct node { int number; struct node *next; } node; 10 10 Problems of Data Structures – C Language void printLL(node * temp); int main(void) { // List of size 0, initially not pointing to anything node *list = NULL; // Add number to list node *n = malloc(sizeof(node)); n->number = 1; n->next = NULL; // We create our first node, store the value 1 in it, and leave the next // pointer to point to nothing. Then, our list variable can point to it. list = n; // Add number to list n = malloc(sizeof(node)); n->number = 2; n->next = NULL; // Now, we go our first node that list points to, and sets the next pointer // on it to point to our new node, adding it to the end of the list: list->next = n; // Add number to list n = malloc(sizeof(node)); 11 10 Problems of Data Structures – C Language n->number = 3; n->next = NULL; // We can follow multiple nodes with this syntax, using the next pointer // over and over, to add our third new node to the end of the list: list->next->next = n; node *toDelete = list; list = list->next; free(toDelete); node * temp = list; while (temp != NULL) { printf("%d\n", temp->number); temp = temp->next; } } Problem 6 #include <stdio.h> #include <stdlib.h> // Represents a node typedef struct node { int number; struct node *next; 12 10 Problems of Data Structures – C Language } node; void freelist(node *temp); int main(void) { // List of size 0, initially not pointing to anything node *list = NULL; // Add number to list node *n = malloc(sizeof(node)); n->number = 1; n->next = NULL; // We create our first node, store the value 1 in it, and leave the next // pointer to point to nothing. Then, our list variable can point to it. list = n; // Add number to list n = malloc(sizeof(node)); n->number = 2; n->next = NULL; // Now, we go our first node that list points to, and sets the next pointer // on it to point to our new node, adding it to the end of the list: list->next = n; // Add number to list 13 10 Problems of Data Structures – C Language n = malloc(sizeof(node)); n->number = 3; n->next = NULL; // We can follow multiple nodes with this syntax, using the next pointer // over and over, to add our third new node to the end of the list: list->next->next = n; freelist(list); } void freelist(node *temp) { if (temp == NULL) { return; } freelist(temp->next); free(temp); } Problem 7 #include <stdio.h> #include <stdlib.h> typedef struct person 14 10 Problems of Data Structures – C Language { struct person *parents[2]; char alleles[2]; } person; int main(void){ person *p1 = malloc(sizeof(person)); p1->alleles[0] = 'A'; p1->alleles[1] = 'O'; p1->parents[0] = NULL; p1->parents[1] = NULL; person *p2 = malloc(sizeof(person)); p2->alleles[0] = 'A'; p2->alleles[1] = 'B'; p2->parents[0] = NULL; p2->parents[1] = NULL; person *child = malloc(sizeof(person)); child->alleles[0] = 'A'; child->alleles[1] = 'A'; child->parents[0] = p1; child->parents[1] = p2; printf("%c\n", child->parents[1]->alleles[1]); 15 10 Problems of Data Structures – C Language } Problem 8 #include <stdio.h> #include <stdlib.h> typedef struct person { struct person *parents[2]; char alleles[2]; } person; void free_family(person *p); int main(void){ person *p1 = malloc(sizeof(person)); p1->alleles[0] = 'A'; p1->alleles[1] = 'O'; p1->parents[0] = NULL; p1->parents[1] = NULL; person *p2 = malloc(sizeof(person)); p2->alleles[0] = 'A'; p2->alleles[1] = 'B'; 16 10 Problems of Data Structures – C Language p2->parents[0] = NULL; p2->parents[1] = NULL; person *child = malloc(sizeof(person)); child->alleles[0] = 'A'; child->alleles[1] = 'A'; child->parents[0] = p1; child->parents[1] = p2; free_family(child); } // Free `p` and all ancestors of `p`. void free_family(person *p) { // TODO: Handle base case if (p == NULL) { return; } // TODO: Free parents free_family(p->parents[0]); free_family(p->parents[1]); // TODO: Free child free(p); } 17 10 Problems of Data Structures – C Language Problem 9 #include <stdlib.h> #include <stdio.h> // Represents a node in a hash table typedef struct node { int x; struct node *next; } node; int main(void) { // Hash table node *table[5]; //Create space for a node node *temp = malloc(sizeof(node)); //Set next field of temp to NULL temp->next = NULL; //Set pointer at 0 to node table[0] = temp; } 18 10 Problems of Data Structures – C Language Problem 10 #include <stdlib.h> #include <stdio.h> // Represents a node in a hash table typedef struct node { int x; struct node *next; } node; int main(void) { // Hash table node *table[5]; //Create space for a node node *temp1 = malloc(sizeof(node)); //Set next field of temp to NULL temp1->next = NULL; //Set pointer at 0 to node table[0] = temp1; node *temp2 = malloc(sizeof(node)); temp2->next = temp1; table[0] = temp2; } 19 6 Problems of C Pointers – C Language Questions Problem 1 Create an integer. Print the address of an integer. Problem 2 Create an integer. Grab the address of the integer and dereference it (you should see an integer). Problem 3 Create an integer. Create a pointer to the integer. Print the address of the pointer. Print the address of the integer (using the pointer). Print the value of the integer (using the pointer). Problem 4 Create a function that swaps two integers. Swap by first passes the addresses of the integers. Then swap them pack by passing as arguments pointers to the integers. Problem 5 Crete an integer. Create a pointer to that integer. Create a function that takes the pointer as input and adds one to the integer. Problem 6 Create a char pointer to a string with three characters. Print each character using pointer arithmetic. Problem 7 Ask user for input. Copy the string. 2 6 Problems of C Pointers – C Language Solutions Problem 1 #include <stdio.h> int main() { int num = 5; printf("%p\n", &num); } Problem 2 #include <stdio.h> int main() { int num = 5; printf("%d\n", *&num); } Problem 3 #include <stdio.h> int main() { int num = 5; int *ptr = &num; printf("%p\n", &ptr); printf("%p\n", ptr); printf("%d\n", *ptr); } 3 6 Problems of C Pointers – C Language Problem 4 #include <stdio.h> void swap(int *x, int *y); int main() { int a = 3; int b = 4; swap(&a, &b); printf("First swap"); printf("%d\n", a); printf("%d\n", b); int *r = &a; int *s = &b; swap(r, s); printf("Swap back"); printf("%d\n", a); printf("%d\n", b); } void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } 4 6 Problems of C Pointers – C Language Problem 5 #include <stdio.h> void addOne(int* ptr) { *ptr = *ptr + 1 // adding 1 to *ptr } int main() { int i = 10; int *p = &i; addOne(p); printf("%d", *p); // 11 return 0; } Problem 6 #include <stdio.h> int main(void) { char *s = "HI!"; printf("%c\n", *s); printf("%c\n", *(s+1)); printf("%c\n", *(s+2)); } 5 6 Problems of C Pointers – C Language Problem 7 #include <cs50.h> #include <ctype.h> #include <stdio.h> #include <string.h> int main(void) { char *s = get_string("s: "); char *t = malloc(strlen(s) + 1); for (int i = 0, n = strlen(s); i < n + 1; i++) { t[i] = s[i]; } t[0] = toupper(t[0]); printf("s: %s\n", s); printf("t: %s\n", t); } 6 Python and Scratch Correlating Scratch with Python Introduction Operators 2 Python and Scratch 3 Python and Scratch Loops 4 Python and Scratch Conditionals 5 Python and Scratch Lists 6 Python and Scratch Functions 7 Python and Scratch 8 30 Programming Fundamental Problems – Python Questions Problem 1 Create a list. Loop through the list using: 1. For each 2. For index 3. For loop value with index Problem 2 Print the values from 1 to 100. Problem 3 Print from 0 to 100, only the even numbers. Use for loops. Problem 4 Sum numbers from 1 to 100. Problem 5 Add 1 + 3 + 5 + … + 99 Problem 6 Loop from 100 to 1. Print the values. Problem 7 Add all the numbers from 99 + 97 + 95 + … + 1 Problem 8 Create an integer. Print if the integer is even or odd. 2 30 Programming Fundamental Problems – Python Problem 9 Create two integers. Check if they have the same last digit. Print YES if they are the same. Print NO if they are not the same. Problem 10 Loop through values from 1 to 100 inclusive. Check the conditions: āŖ āŖ āŖ āŖ If the current number is divisible by 3, print Fizz. If the current number is divisible by 5, print Buzz. If the current number is divisible by both 3 and 5, print FizzBuzz. Else, print the number. Problem 11 Repeat problem 1, but with a string. Problem 12 Create a string. Print the first letter. Problem 13 Create a string. Print the last letter. Problem 14 Create a string. Print the string without the first letter. Problem 15 Create a string. Print the string without the last letter. Problem 16 Create a string with value apple. Print ppl. 3 30 Programming Fundamental Problems – Python Problem 17 Create a long string. Print two letters at a time. Problem 18 Create a long string. Print two letters at a time, without overlapping letters. Problem 19 Create a string. Print three letters at a time. Problem 20 Create two strings. Concatenate the second with the first. Problem 21 Create an empty list. Append a number to this list. Problem 22 Create a list. Add values 1 to 100. Problem 23 Create a list. Add values 1 + 3 + 5 + … + 99 to list. Loop through the list and add all numbers inside of it. Problem 24 Add numbers from 1 to 100 using a while loop. Problem 25 Create an integer. Count the number of digits. 4 30 Programming Fundamental Problems – Python Problem 26 Create a long number. Grab the first two digits. Problem 27 Create the following pattern: * ** *** **** Problem 28 Create a list of strings (with more than 4 letters). Print the 3rd letter of the 2nd string. Problem 29 Create a list with multiple numbers. Print the number in reverse order using a loop. Problem 30 Create a list called even. Create another list called odd. Loop through the values from 1 to 100. If number is even, add it to even list. If number is odd, add it to odd list. 5 30 Programming Fundamental Problems – Python Solutions Problem 1 x = [10, 9, 5, 3, 2] #for each loop for val in x: print(val) #loop through the list index for i in range(len(x)): print(i) #loop through the values of the list #using the index for i in range(len(x)): print(x[i]) Problem 2 for i in range(1, 101): print(i) Problem 3 for i in range(0, 101, 2): print(i) 6 30 Programming Fundamental Problems – Python Problem 4 sum = 0 for i in range(1, 11): sum = sum + i print(sum) Problem 5 sum = 0 for i in range(1, 100, 2): sum += i print(sum) Problem 6 for i in range(100, 0, -1): print(i) Problem 7 sum = 0 for i in range(99, 0, -2): sum += i print(sum) 7 30 Programming Fundamental Problems – Python Problem 8 num = 21 if num % 2 == 0: print("even") else: print("odd") Problem 9 num1 = 13 num2 = 13 if (num1 % 10) == (num2 % 10): print("YES") else: print("NO") Problem 10 for i in range(1, 101): if (i % 3 == 0 and i % 5 == 0): print("FIZZBUZZ") elif (i % 3 == 0): print("FIZZ") elif (i % 5 == 0): print("BUZZ") else: print(i) 8 30 Programming Fundamental Problems – Python Problem 11 text = "coding" #for each loop for char in text: print(char) #printing index for index in range(len(text)): print(index) #print the letters using the index with for loop for i in range(len(text)): print(text[i]) Problem 12 text = "coding" print(text[0]) Problem 13 text = "codingasdasdasdasda" print(text[len(text)-1]) Problem 14 text = "coding" print(text[1:]) 9 30 Programming Fundamental Problems – Python Problem 15 text = "coding" print(text[0:len(text)-1]) Problem 16 text = "apple" print(text[1:4]) Problem 17 text = "applebanana" for i in range(0, len(text)-1): print(text[i:i+2]) Problem 18 text = "applefab" for i in range(0, len(text)-1, 2): print(text[i:i+2]) Problem 19 text = "applebananas" for i in range(0, len(text)-1, 3): print(text[i:i+3]) 10 30 Programming Fundamental Problems – Python Problem 20 text1 = "banana" text2 = "apple" #text1 = text1 + text2 text1 += text2 print(text1) Problem 21 x = [] x.append(10) print(x) Problem 22 x = [] for i in range(1, 101): x.append(i) print(x) Problem 23 x = [] for i in range(1, 100, 2): x.append(i) sum = 0 for val in x: sum += val print(sum) 11 30 Programming Fundamental Problems – Python Problem 24 counter = 0 sum = 0 while (counter <= 100): sum+= counter counter += 1 print(sum) Problem 25 num = 231231231 counter = 0 while num > 0: num = num // 10 counter += 1 print(counter) Problem 26 num = 23423323 print(num // pow(10, 6)) Problem 27 for row in range(1, 5): for col in range(1, row+1): print("*", end="") print() 12 30 Programming Fundamental Problems – Python Problem 28 x = ["apple", "banana", "watermellon", "lemon"] print(x[1][2]) Problem 29 x = [9, 3, 5, 3, 2, 1, 0] for i in range(len(x)-1, -1, -1): print(x[i]) Problem 30 even = [] odd = [] for i in range(1, 10): if i % 2 == 0: even.append(i) else: odd.append(i) print(even) print(odd) 13 CodingBat Warmup 1 - Python Questions sleep_in The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. sleep_in(False, False) → True sleep_in(True, False) → False sleep_in(False, True) → True monkey_trouble We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble. monkey_trouble(True, True) → True monkey_trouble(False, False) → True monkey_trouble(True, False) → False sum_double Given two int values, return their sum. Unless the two values are the same, then return double their sum. sum_double(1, 2) → 3 sum_double(3, 2) → 5 sum_double(2, 2) → 8 2 CodingBat Warmup 1 - Python diff21 Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. diff21(19) → 2 diff21(10) → 11 diff21(21) → 0 parrot_trouble We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble. parrot_trouble(True, 6) → True parrot_trouble(True, 7) → False parrot_trouble(False, 6) → False makes10 Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. makes10(9, 10) → True makes10(9, 9) → False makes10(1, 9) → True near_hundred Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number. 3 CodingBat Warmup 1 - Python near_hundred(93) → True near_hundred(90) → True near_hundred(89) → False pos_neg Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. pos_neg(1, -1, False) → True pos_neg(-1, 1, False) → True pos_neg(-4, -5, True) → True not_string Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. not_string('candy') → 'not candy' not_string('x') → 'not x' not_string('not bad') → 'not bad' missing_char Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive). missing_char('kitten', 1) → 'ktten' missing_char('kitten', 0) → 'itten' missing_char('kitten', 4) → 'kittn' 4 CodingBat Warmup 1 - Python front_back Given a string, return a new string where the first and last chars have been exchanged. front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' front3 Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. front3('Java') → 'JavJavJav' front3('Chocolate') → 'ChoChoCho' front3('abc') → 'abcabcabc' 5 CodingBat Warmup 1 - Python Solutions sleep_in def sleep_in(weekday,vacation): if not weekday or vacation: return True else: return False monkey_trouble def monkey_trouble(a_smile,b_smile): if a_smile and b_smile: return True if not a_smile and not b_smile: return False sum_double def sum_double(a,b): if a == b: return 2 * (a + b) else: return a + b diff21 def diff21(n): 6 CodingBat Warmup 1 - Python if n > 21: return 2 * abs(n - 21) else: return abs(n - 21) parrot_trouble def parrot_trouble(talking,hour): if talking and (hour < 7 or hour > 20): return True else: return False makes10 def makes10(a,b): if (a + b == 10) or a == 10 or b == 10: return True else: return False near_hundred def near_hundred(n): if abs(n - 100) <= 10 or abs(n - 200) <= 10: return True else: return False 7 CodingBat Warmup 1 - Python pos_neg def pos_neg(a,b,negative): if (a < 0 and b < 0) and negative is True: return True elif negative is True: return False elif (a > 0 and b < 0) or (a < 0 and b > 0): return True else: return False not_string def not_string(str): if len(str) >= 3 and str[:3] == “not”: return str return “not” + str missing_char def missing_char(str,n): front = str[:n] back = str[n+1:] return front + back 8 CodingBat Warmup 1 - Python front_back def front_back(str): if len(str) <= 1: return str mid = str[1: len(str)-1] return str[len(str)-1] + mid + str[0] front3 def front3(str): front_end = 3 if len(str) < front_end: front_end = len(str) front = str[:front_end] return front + front + front 9 CodingBat String 1 - Python Questions hello_name Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!". hello_name('Bob') → 'Hello Bob!' hello_name('Alice') → 'Hello Alice!' hello_name('X') → 'Hello X!' make_abba Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi". make_abba('Hi', 'Bye') → 'HiByeByeHi' make_abba('Yo', 'Alice') → 'YoAliceAliceYo' make_abba('What', 'Up') → 'WhatUpUpWhat' make_tags The web is built with HTML strings like "<i>Yay</i>" which draws Yay as italic text. In this example, the "i" tag makes <i> and </i> which surround the word "Yay". Given tag and word strings, create the HTML string with tags around the word, e.g. "<i>Yay</i>". make_tags('i', 'Yay') → '<i>Yay</i>' make_tags('i', 'Hello') → '<i>Hello</i>' make_tags('cite', 'Yay') → '<cite>Yay</cite>' 2 CodingBat String 1 - Python make_out_word Given an "out" string length 4, such as "<<>>", and a word, return a new string where the word is in the middle of the out string, e.g. "<<word>>". make_out_word('<<>>', 'Yay') → '<<Yay>>' make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>' make_out_word('[[]]', 'word') → '[[word]]' extra_end Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2. extra_end('Hello') → 'lololo' extra_end('ab') → 'ababab' extra_end('Hi') → 'HiHiHi' first_two Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "". first_two('Hello') → 'He' first_two('abcdefg') → 'ab' first_two('ab') → 'ab' 3 CodingBat String 1 - Python first_half Given a string of even length, return the first half. So the string "WooHoo" yields "Woo". first_half('WooHoo') → 'Woo' first_half('HelloThere') → 'Hello' first_half('abcdef') → 'abc' without_end Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2. without_end('Hello') → 'ell' without_end('java') → 'av' without_end('coding') → 'odin' combo_string Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length 0). combo_string('Hello', 'hi') → 'hiHellohi' combo_string('hi', 'Hello') → 'hiHellohi' combo_string('aaa', 'b') → 'baaab' 4 CodingBat String 1 - Python non_start Given 2 strings, return their concatenation, except omit the first char of each. The strings will be at least length 1. non_start('Hello', 'There') → 'ellohere' non_start('java', 'code') → 'avaode' non_start('shotl', 'java') → 'hotlava' left2 Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2. left2('Hello') → 'lloHe' left2('java') → 'vaja' left2('Hi') → 'Hi' 5 CodingBat String 1 - Python Solutions hello_name def hello_name(name): word = “Hello” word = word + name + “!” return word make_abba def make_abba(a,b): return a + b + b + a make_tags def make_tags(tag,word): word1 = “<” + tag + “>” word2 = word word3 = “</” + tag + “/>” finalW = word1 + word2 + word3 return finalW make_out_word def make_out_word(out,word): size = len(out)//2 pal = out[0:size] + word + out[size:] return pal 6 CodingBat String 1 - Python extra_end def extra_end(str): syl = len(str) - 2 word =3 * str[syl:] return word first_two def first_two(str): if len(str) < 2: return str else: return str[0:2] first_half def first_half(str): size = len(str) / 2 word = “” word = str[0:size] return word without_end def without_end(str): word = str[1:len(str)-1] return word 7 CodingBat String 1 - Python combo_string def combo_string(str): if len(a) > len(b): long = a short = b else: long = b short = a word = short + long + short return word non_start def non_start(a,b): word1 = a[1: ] word1 = b[1: ] fWord = word1 + word2 return fWord left2 def left2(str): syl = str[0:2] word = str[2: ] + syl return fWord 8 CodingBat Logic 1 - Python Questions cigar_party When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise. cigar_party(30, False) → False cigar_party(50, False) → True cigar_party(70, True) → True date_fashion You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise, the result is 1 (maybe). date_fashion(5, 10) → 2 date_fashion(5, 2) → 0 date_fashion(5, 5) → 1 squirrel_play 2 CodingBat Logic 1 - Python The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise. squirrel_play(70, False) → True squirrel_play(95, False) → False squirrel_play(95, True) → True caught_speeding You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. caught_speeding(60, False) → 0 caught_speeding(65, False) → 1 caught_speeding(65, True) → 0 sorta_sum Given 2 ints, a and b, return their sum. However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20. sorta_sum(3, 4) → 7 sorta_sum(9, 4) → 20 sorta_sum(10, 11) → 21 alarm_clock 3 CodingBat Logic 1 - Python Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off". alarm_clock(1, False) → '7:00' alarm_clock(5, False) → '7:00' alarm_clock(0, False) → '10:00' love6 The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number. love6(6, 4) → True love6(4, 5) → False love6(1, 5) → True in1to10 Given a number n, return True if n is in the range 1..10, inclusive. Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10. in1to10(5, False) → True in1to10(11, False) → False in1to10(11, True) → True near_ten 4 CodingBat Logic 1 - Python Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. near_ten(12) → True near_ten(17) → False near_ten(19) → True Solutions 5 CodingBat Logic 1 - Python cigar_party def cigar_party(cigars, is_weekend): if is_weekend == True: return cigars >= 40 else: return cigars >= 40 and cigars <= 60 date_fashion def date_fashion(you, date): if you <= 2 or date <= 2: return 0 elif you >= 8 or date >= 8: return 2 else: return 1 squirrel_play def squirrel_play(temp, is_summer): if temp >= 60: if is_summer: if temp <= 100: return True else: return False else: 6 CodingBat Logic 1 - Python if temp <= 90: return True else: return False else: return False caught_speeding def caught_speeding(speed, is_birthday): if is_birthday: speed -= 5 if speed <= 60: return 0 return 1 if 61 <= speed <= 80 else 2 sorta_sum def sorta_sum(a, b): sum = a + b if 10 <= sum <= 19: return 20 else: return sum alarm_clock 7 CodingBat Logic 1 - Python def alarm_clock(day, vacation): week_day = day not in (0, 6) if vacation: if week_day: return '10:00' else: return 'off' else: if week_day: return '7:00' else: return '10:00' love6 def love6(a, b): if (a == 6 or b == 6 or (a+b) == 6 or abs(a-b) == 6): return True else: return False in1to10 def in1to10(n, outside_mode): if outside_mode: return n <= 1 or n >= 10 return 1 <= n <= 10 near_ten 8 CodingBat Logic 1 - Python def near_ten(num): num_mod_10 = num % 10 return num_mod_10 <= 2 or num_mod_10 >= 8 9 CodingBat List 1 - Python Questions first_last6 Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. first_last6([1, 2, 6]) → True first_last6([6, 1, 2, 3]) → True first_last6([13, 6, 1, 2, 3]) → False same_first_last Given an array of ints, return True if the array is length 1 or more, and the first element and the last element are equal. same_first_last([1, 2, 3]) → False same_first_last([1, 2, 3, 1]) → True same_first_last([1, 2, 1]) → True make_pi Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}. make_pi() → [3, 1, 4] common_end Given 2 arrays of ints, a and b, return True if they have the same first element or they have the same last element. Both arrays will be length 1 or more. common_end([1, 2, 3], [7, 3]) → True common_end([1, 2, 3], [7, 3, 2]) → False common_end([1, 2, 3], [1, 3]) → True 2 CodingBat List 1 - Python sum3 Given an array of ints length 3, return the sum of all the elements. sum3([1, 2, 3]) → 6 sum3([5, 11, 2]) → 18 sum3([7, 0, 0]) → 7 rotate_left3 Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] reverse3 Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}. reverse3([1, 2, 3]) → [3, 2, 1] reverse3([5, 11, 9]) → [9, 11, 5] reverse3([7, 0, 0]) → [0, 0, 7] 3 CodingBat List 1 - Python max_end3 Given an array of ints length 3, figure out which is larger, the first or last element in the array, and set all the other elements to be that value. Return the changed array. max_end3([1, 2, 3]) → [3, 3, 3] max_end3([11, 5, 9]) → [11, 11, 11] max_end3([2, 11, 3]) → [3, 3, 3] sum2 Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0. sum2([1, 2, 3]) → 3 sum2([1, 1]) → 2 sum2([1, 1, 1, 1]) → 2 middle_way Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their middle elements. middle_way([1, 2, 3], [4, 5, 6]) → [2, 5] middle_way([7, 7, 7], [3, 8, 0]) → [7, 8] middle_way([5, 2, 9], [1, 4, 5]) → [2, 4] 4 CodingBat List 1 - Python make_ends Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more. make_ends([1, 2, 3]) → [1, 3] make_ends([1, 2, 3, 4]) → [1, 4] make_ends([7, 4, 6, 2]) → [7, 2] has23 Given an int array length 2, return True if it contains a 2 or a 3. has23([2, 5]) → True has23([4, 3]) → True has23([4, 5]) → False 5 CodingBat List 1 - Python Solutions first_last6 def first_last6(nums): if nums[0] == 6 or nums[len(nums)-1] == 6: return True else: return False same_first_last def same_first_last(nums): if len(nums) >= 1 and nums[0] == nums[-1]: return True else: return False make_pi def make_pi(): return [3,1,4] common_end def common_end(a,b): if a[0] == b[0] or a[len(a) - 1] == b[len(b) - 1]: return True else: return False 6 CodingBat List 1 - Python sum3 def sum3(nums): return nums[0] + nums[1] + nums[2] rotate_left3 def rotate_left3(nums): return [nums[1], nums[len(nums)-1], nums[0]] reverse3 def reverse3(nums): return [nums[len(nums)-1], nums[1], nums[0]] max_end3 def max_end3(nums): if nums[0] > nums[-1]: return [nums[0], nums[0], nums[0]] else: return [nums[-1], nums[-1], nums[-1]] sum2 def sum2(nums): if len(nums) == 0: return 0 elif len(nums) < 2: return nums[0] else: return nums[0] + nums[1] 7 CodingBat List 1 - Python middle_way def middle_way(a,b): return [a[1], b[1]] make_ends def make_ends(nums): return [nums[0], nums[len(nums)-1]] has23 def has23(a,b): if (nums[0] == 2 or nums[1] == 2) or (nums[0] == 3 or nums[1] == 3): return True else: return False 8 CodingBat Warmup 2 - Python Questions string_times Given a string and a non-negative int n, return a larger string that is n copies of the original string. string_times('Hi', 2) → 'HiHi' string_times('Hi', 3) → 'HiHiHi' string_times('Hi', 1) → 'Hi' front_times Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front; front_times('Chocolate', 2) → 'ChoCho' front_times('Chocolate', 3) → 'ChoChoCho' front_times('Abc', 3) → 'AbcAbcAbc' string_bits Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". string_bits('Hello') → 'Hlo' string_bits('Hi') → 'H' string_bits('Heeololeo') → 'Hello' 2 CodingBat Warmup 2 - Python string_splosion Given a non-empty string like "Code" return a string like "CCoCodCode". string_splosion('Code') → 'CCoCodCode' string_splosion('abc') → 'aababc' string_splosion('ab') → 'aab' last2 Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring). last2('hixxhi') → 1 last2('xaxxaxaxx') → 1 last2('axxxaaxx') → 2 array_count9 Given an array of ints, return the number of 9's in the array. array_count9([1, 2, 9]) → 1 array_count9([1, 9, 9]) → 2 array_count9([1, 9, 9, 3, 9]) → 3 3 CodingBat Warmup 2 - Python array_front9 Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4. array_front9([1, 2, 9, 3, 4]) → True array_front9([1, 2, 3, 4, 9]) → False array_front9([1, 2, 3, 4, 5]) → False array123 Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere. array123([1, 1, 2, 3, 1]) → True array123([1, 1, 2, 4, 1]) → False array123([1, 1, 2, 1, 2, 3]) → True string_match Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. string_match('xxcaazz', 'xxbaaz') → 3 string_match('abc', 'abc') → 2 string_match('abc', 'axc') → 0 4 CodingBat Warmup 2 - Python Solutions string_times def string_times(str,n): return n * str front_times def front_times(str,n): if len(str) < 3: return n * str else: return n * str[0:3] string_bits def string_bits(str): word = “” for i in range(len(str)): if i % 2 == 0: word += str[i:i+1] return word string_splosion def string_splosion(str): word = “” for i in range(1, len(str)+1): word += str[0:i] return word 5 CodingBat Warmup 2 - Python last2 def last2(str): word = “” count = 0 for i in range(len(str)-2): if str[i:i+2] == word count += 1 return count array_count9 def array_count9(nums): count = 0 for i in nums: if i == 9: return count array_front9 def array_front9(nums): end = len(nums) if end > 4: end = 4 for i in range(end): if nums[i] == 9: return True return False 6 CodingBat Warmup 2 - Python array123 def array123(nums): for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3: return True return False string_match def string_match(a,b): count = 0 for i in range(len(a)-1): if a[i:i+2] == b[i:i+2]: count += 1 return count 7 CodingBat String 2 - Python Questions double_char Given a string, return a string where for every char in the original, there are two chars. double_char('The') → 'TThhee' double_char('AAbb') → 'AAAAbbbb' double_char('Hi-There') → 'HHii--TThheerree' count_hi Return the number of times that the string "hi" appears anywhere in the given string. count_hi('abc hi ho') → 1 count_hi('ABChi hi') → 2 count_hi('hihi') → 2 cat_dog Return True if the string "cat" and "dog" appear the same number of times in the given string. cat_dog('catdog') → True cat_dog('catcat') → False cat_dog('1cat1cadodog') → True count_code 2 CodingBat String 2 - Python Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count. count_code('aaacodebbb') → 1 count_code('codexxcode') → 2 count_code('cozexxcope') → 2 end_other Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. end_other('Hiabc', 'abc') → True end_other('AbC', 'HiaBc') → True end_other('abc', 'abXabc') → True xyz_there Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. xyz_there('abcxyz') → True xyz_there('abc.xyz') → False xyz_there('xyz.abc') → True Solutions 3 CodingBat String 2 - Python double_char def double_char(str): word = "" for i in str: word += i + i return word count_hi def count_hi(str): count = 0 for i in range(len(str)-1): if str[i:i+2] == "hi": count+=1 return count cat_dog def cat_dog(str): countCat = 0 countDog = 0 for i in range(len(str)-2): if(str[i:i+3] =="cat"): countCat+=1 if(str[i:i+3] =="dog"): countDog+=1 return (countCat == countDog) count_code 4 CodingBat String 2 - Python def count_code(str): count = 0 if(len(str)<4): return 0 else: for i in range(len(str)-3): if(str[i:i+1] == "c" and str[i+1:i+2] == "o" and str[i+3:i+4] == "e"): count+=1 return count end_other def end_other(a, b): word1 = a.lower() word2 = b.lower() if(len(word1)<len(word2)): small = word1 big = word2 else: small = word2 big = word1 if(big[len(big)-len(small):] == small): return True else: return False xyz_there 5 CodingBat String 2 - Python def xyz_there(str): word = "xyz" for i in range(len(str)-2): if (str[i:i+3] == word and str[i-1:i] != "."): return True return False 6 CodingBat Lists 2 - Python Questions count_evens Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. count_evens([2, 1, 2, 3, 4]) → 3 count_evens([2, 2, 0]) → 3 count_evens([1, 3, 5]) → 0 big_diff Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. big_diff([10, 3, 5, 6]) → 7 big_diff([7, 2, 10, 9]) → 8 big_diff([2, 10, 7, 2]) → 8 centered_average Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. centered_average([1, 2, 3, 4, 100]) → 3 centered_average([1, 1, 5, 5, 10, 8, 7]) → 5 centered_average([-10, -4, -2, -4, -2, 0]) → -3 sum13 2 CodingBat Lists 2 - Python Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count. sum13([1, 2, 2, 1]) → 6 sum13([1, 1]) → 2 sum13([1, 2, 2, 1, 13]) → 6 sum67 Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers. sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4 has22 Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False 3 CodingBat Lists 2 - Python Solutions count_evens def count_evens(nums): count = 0 for i in range(len(nums)): if nums[i] % 2 == 0: count += 1 return count bid_diff def big_diff(nums): return max(nums) - min(nums) centered_average def centered_average(nums): nums.sort() count = 0 total = 0 for i in range(1, len(nums) - 1): count += 1 total += nums[i] return total / count 4 CodingBat Lists 2 - Python sum13 def sum13(nums): total = 0 skip = False if len(nums) == 0: return 0 else: for i in range(len(nums)): if nums[i] == 13: skip = True elif skip: skip = False else: total += nums[i] return total sum67 def sum67(nums): total = 0 skip = False for i in range(len(nums)): if nums[i] == 6: skip = True elif nums[i] == 7 and skip: skip = False 5 CodingBat Lists 2 - Python elif not skip: total += nums[i] return total has22 def has22(nums): has2 = False for i in range(len(nums)): if has2 and nums[i] == 2: return True elif nums[i] == 2: has2 = True else: has2 = False return False 6 CodingBat Logic 2 - Python Questions make_bricks We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. make_bricks(3, 1, 8) → True make_bricks(3, 1, 9) → False make_bricks(3, 2, 10) → True lone_sum Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(3, 3, 3) → 0 lucky_sum Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. lucky_sum(1, 2, 3) → 6 lucky_sum(1, 2, 13) → 3 lucky_sum(1, 13, 3) → 1 2 CodingBat Logic 2 - Python no_teen_sum Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main no_teen_sum(). no_teen_sum(1, 2, 3) → 6 no_teen_sum(2, 13, 1) → 3 no_teen_sum(2, 1, 14) → 3 round_sum For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum(). round_sum(16, 17, 18) → 60 round_sum(12, 13, 14) → 30 round_sum(6, 4, 4) → 10 3 CodingBat Logic 2 - Python close_far Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number. close_far(1, 2, 10) → True close_far(1, 2, 3) → False close_far(4, 1, 3) → True make_chocolate We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done. make_chocolate(4, 1, 9) → 4 make_chocolate(4, 1, 10) → -1 make_chocolate(4, 1, 7) → 2 4 CodingBat Logic 2 - Python Solutions make_bricks def make_bricks(small, big, goal): big_needed = min(big, goal // 5) return goal - (big_needed * 5) <= small lone_sum def lone_sum(a, b, c): sum = 0 if a not in [b,c]: sum += a if b not in [a,c]: sum += b if c not in [a,b]: sum += c return sum lucky_sum def lucky_sum(a, b, c): sum = 0 for n in (a, b, c): if n != 13: sum += n else: break return sum 5 CodingBat Logic 2 - Python no_teen_sum def no_teen_sum(a, b, c): nums = (a, b, c) sum = 0 for i in range(len(nums)): sum += fix_teen(nums[i]) return sum def fix_teen(n): if n != 15 and n!= 16 and 13 <= n <= 19: return 0 else: return n round_sum def round_sum(a, b, c): return round10(a)+round10(b)+round10(c) def round10(num): return (num+5)/10*10 6 CodingBat Logic 2 - Python close_far def close_far(a, b, c): ab_diff = abs(a - b) ac_diff = abs(a - c) bc_diff = abs(b - c) if (ab_diff <= 1 and ac_diff >= 2 and bc_diff >= 2) != (ac_diff <= 1 and ab_diff >= 2 and bc_diff >= 2): return True else: return False make_chocolate def make_chocolate(small, big, goal): if goal >= 5 * big: remainder = goal - 5 * big else: remainder = goal % 5 if remainder <= small: return remainder return -1 7 19 Problems of Python Advanced Questions Problem 0 Ask a user for his name. Print it using f-strings: https://www.geeksforgeeks.org/formatted-string-literals-f-strings-python/ Problem 1 Create and print a dictionary. Problem 2 Create a dictionary. Print its keys and values without a loop. Problem 3 Create a dictionary. Loop over its keys and values using the .items() function. Problem 4 Create a dictionary. Print the value of a particular key. Problem 5 Create a dictionary. Add a key and value to the dictionary. Print the result. Problem 6 Create a list of strings that contains the name Rodrigo. Check if Rodrigo is in the list. If he is, print Found, otherwise Not Found. Use the function in. Problem 7 Create a dictionary with names and phone numbers. Ask user for a name. If name in the dictionary, print their phone number. 2 19 Problems of Python Advanced Problem 8 Create a list of dictionaries. Print it. Problem 9 Create a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. Print the dictionary. Problem 10 Call the program from the terminal with arguments. Print the arguments. Problem 11 Call the program from the terminal with arguments. Print “Hello, world” if there are arguments. Else, print “Hello” with the value of the argument. Problem 12 Create a file called days.txt with days of the week, one at each line. Open the file and read its content. days.txt file: January Problem 13 Create a file called days.txt with days of the week, one at each line. Open the file and read the first line. days.txt file: January 3 19 Problems of Python Advanced Problem 14 Create a file called numbers.txt. Write numbers 1 to 100, at each line. Example of numbers.txt file: 1 2 3 ... 99 100 Problem 15 Open the file numbers.txt and read the first line. Use with open() as syntax. Problem 16 Create a spreadsheet file and put 10 of your favorite desserts in the first column. Download file with .csv extension. Open CSV file. Print the elements of the file. Example of desserts.csv file: cheesecake cookie ice-cream ... tiramisu chocolate 4 19 Problems of Python Advanced Problem 17 Create a spreadsheet file and put 10 of your favorite desserts in the first column (with some repetitive ones). Download file with .csv extension. Open CSV file. Count the number of desserts, put result in a dictionary and print it. Problem 18 Create a spreadsheet file and put 10 of your favorite desserts in the first column (with some repetitive ones). In the first row of the column put the title of the column as dessert. Download file with .csv extension. Open CSV file. Print each dessert using the name of the column. 5 19 Problems of Python Advanced Solutions Problem 0 answer = input("What's your name? ") print(f"hello, {answer}") Problem 1 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) Problem 2 car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(car.values()) print(car.keys()) 6 19 Problems of Python Advanced Problem 3 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x, y in thisdict.items(): print(x, y) Problem 4 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict["model"]) print(thisdict["year"]) Problem 5 thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) 7 19 Problems of Python Advanced Problem 6 names = ["Bill", "Charlie", "Fred", "George", "Ginny", "Percy", "Rodrigo"] if "Rodrigo" in names: print("Found") else: print("Not found") Problem 7 people = { "Brian": "+1-617-495-1000", "David": "+1-949-468-2750" } name = input("Name: ") if name in people: print(f"Number: {people[name]}") Problem 8 person1 = { "name": "Rodrigo", "age": 28 } person2 = { "name": "Giovanna", "age": 22 } l = [person1, person2] print(l) 8 19 Problems of Python Advanced Problem 9 d=dict() for x in range(1,16): d[x]=x**2 print(d) Problem 10 from sys import argv for arg in argv: print(arg) print(len(argv)) Problem 11 from sys import argv if len(argv) == 2: print(f"hello, {argv[1]}") else: print("hello, world") Problem 12 days_file = open('days.txt','r') print(days_file.read()) days_file.close() 9 19 Problems of Python Advanced Problem 13 days_file = open('days.txt','r') print(days_file.readline(), end="") days_file.close() Problem 14 num_files = open('numbers.txt','w') for i in range(1, 101): num_files.write(f"{str(i)}\n") num_files.close() Problem 15 with open("numbers.txt", "r") as file: print(file.readline()) Problem 16 import csv with open("desserts.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row[0]) 10 19 Problems of Python Advanced Problem 17 import csv desserts_count = dict() with open("desserts.csv", "r") as file: reader = csv.reader(file) for row in reader: current_dessert = row[0] if current_dessert in desserts_count: desserts_count[current_dessert] += 1 else: desserts_count[current_dessert] = 1 print(desserts_count) Problem 18 import csv desserts_count = dict() with open("desserts.csv", "r") as file: reader = csv.DictReader(file) for row in reader: print(row['dessert']) 11 SQL Boat Questions Lesson 1: SELECT queries 101 1. 2. 3. 4. 5. Find the title of each film Find the director of each film Find the title and director of each film Find the title and year of each film Find all the information about each film Lesson 2: Queries with constraints (Pt. 1) 1. 2. 3. 4. Find the movie with a row id of 6 Find the movies released in the years between 2000 and 2010 Find the movies not released in the years between 2000 and 2010 Find the first 5 Pixar movies and their release year Lesson 3: Queries with constraints (Pt. 2) 1. 2. 3. 4. Find all the Toy Story movies Find all the movies directed by John Lasseter Find all the movies (and director) not directed by John Lasseter Find all the WALL-* movies Lesson 4: Filtering and sorting Query results 1. 2. 3. 4. List all directors of Pixar movies (alphabetically), without duplicates List the last four Pixar movies released (ordered from most recent to least) List the first five Pixar movies sorted alphabetically List the next five Pixar movies sorted alphabetically Review: Simple SELECT Queries 1. 2. 3. 4. 5. List all the Canadian cities and their populations Order all the cities in the United States by their latitude from north to south List all the cities west of Chicago, ordered from west to east List the two largest cities in Mexico (by population) List the third and fourth largest cities (by population) in the United States and their population 2 SQL Boat Lesson 6: Multi-table queries with JOINs 1. Find the domestic and international sales for each movie 2. Show the sales numbers for each movie that did better internationally rather than domestically 3. List all the movies by their ratings in descending order Lesson 7: OUTER JOINs 1. Find the list of all buildings that have employees 2. Find the list of all buildings and their capacity 3. List all buildings and the distinct employee roles in each building (including empty buildings) Lesson 8: A short note on NULLs 1. Find the name and role of all employees who have not been assigned to a building 2. Find the names of the buildings that hold no employees Lesson 9: Queries with expressions 1. List all movies and their combined sales in millions of dollars 2. List all movies and their ratings in percent 3. List all movies that were released on even number years Lesson 10: Queries with aggregates (Pt. 1) 1. Find the longest time that an employee has been at the studio 2. For each role, find the average number of years employed by employees in that role 3. Find the total number of employee years worked in each building Lesson 11: Queries with aggregates (Pt. 2) 1. Find the number of Artists in the studio (without a HAVING clause) 2. Find the number of Employees of each role in the studio 3. Find the total number of years employed by all Engineers 3 SQL Boat Lesson 12: Order of execution of a Query 1. Find the number of movies each director has directed 2. Find the total domestic and international sales that can be attributed to each director Lesson 13: Inserting rows 1. Add the studio's new production, Toy Story 4 to the list of movies (you can use any director) 2. Toy Story 4 has been released to critical acclaim! It had a rating of 8.7, and made 340 million domestically and 270 million internationally. Add the record to the BoxOffice table. Lesson 14: Updating rows 1. The director for A Bug's Life is incorrect, it was actually directed by John Lasseter 2. The year that Toy Story 2 was released is incorrect, it was actually released in 1999 3. Both the title and director for Toy Story 8 is incorrect! The title should be "Toy Story 3" and it was directed by Lee Unkrich Lesson 15: Deleting rows 1. This database is getting too big, lets remove all movies that were released before 2005. 2. Andrew Stanton has also left the studio, so please remove all movies directed by him. Lesson 16: Creating tables Create a new table named Database with the following columns: – Name A string (text) describing the name of the database – Version A number (floating point) of the latest version of this database – Download_count An integer count of the number of times this database was downloaded 4 SQL Boat Lesson 17: Altering tables 1. Add a column named Aspect_ratio with a FLOAT data type to store the aspectratio each movie was released in. 2. Add another column named Language with a TEXT data type to store the language that the movie was released in. Ensure that the default for this language is English. Lesson 18: Dropping tables 1. We've sadly reached the end of our lessons, lets clean up by removing the Movies table 2. And drop the BoxOffice table as well 5 SQL Boat Solutions Lesson 1: SELECT queries 101 1. SELECT title FROM movies; 2. SELECT director FROM movies; 3. SELECT title, director FROM movies; 4. SELECT title, year FROM movies; 5. SELECT * FROM movies; Lesson 2: Queries with constraints (Pt. 1) 1. SELECT * FROM movies WHERE id = 6; 2. SELECT * FROM movies WHERE year BETWEEN 2000 and 2010; 6 SQL Boat 3. SELECT * FROM movies WHERE year NOT BETWEEN 2000 and 2010; 4. SELECT * FROM movies WHERE id BETWEEN 1 AND 5; Lesson 3: Queries with constraints (Pt. 2) 1. SELECT * FROM movies WHERE title LIKE "%Toy Story%"; 2. SELECT * FROM movies WHERE director = "John Lasseter"; 3. SELECT * FROM movies WHERE director != "John Lasseter"; 4. SELECT * FROM movies WHERE title LIKE "WALL-%"; 7 SQL Boat Lesson 4: Filtering and sorting Query results 1. SELECT DISTINCT director FROM movies ORDER BY director ASC; 2. SELECT * FROM movies ORDER BY year DESC LIMIT 4; 3. SELECT * FROM movies ORDER BY title ASC LIMIT 5; 4. SELECT * FROM movies ORDER BY title ASC LIMIT 5 OFFSET 5; Lesson 5 Review: Simple SELECT Queries 1. SELECT country, population FROM north_american_cities WHERE country = "Canada"; 8 SQL Boat 2. SELECT city FROM north_american_cities WHERE country = "United States" ORDER BY latitude DESC; 3. SELECT city FROM north_american_cities WHERE longitude < ( SELECT longitude FROM north_american_cities WHERE city = "Chicago" ) ORDER BY longitude ASC; 4. SELECT city FROM north_american_cities WHERE country = "Mexico" ORDER BY population DESC LIMIT 2; 5. SELECT city, population FROM north_american_cities WHERE country = "United States" ORDER BY population DESC LIMIT 2 OFFSET 2; 9 SQL Boat Lesson 6: Multi-table queries with JOINs 1. SELECT title, domestic_sales, international_sales FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id; 2. SELECT * FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id WHERE international_sales > domestic_sales; 3. SELECT title, rating FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id ORDER BY rating DESC; Lesson 7: OUTER JOINs 1. SELECT DISTINCT building_name FROM buildings LEFT JOIN employees ON buildings.building_name = employees.building WHERE building IS NOT NULL; 10 SQL Boat 2. SELECT * FROM buildings; 3. SELECT DISTINCT building_name, role FROM buildings LEFT JOIN employees ON buildings.building_name = employees.building; Lesson 8: A short note on NULLs 1. SELECT * FROM employees LEFT JOIN buildings ON employees.building = buildings.building_name WHERE building_name IS NULL; 2. SELECT * FROM buildings LEFT JOIN employees ON buildings.building_name = employees.building WHERE role IS NULL; 11 SQL Boat Lesson 9: Queries with expressions 1. SELECT title, (domestic_sales + international_sales)/1000000 AS sales FROM boxoffice AS b INNER JOIN movies AS m ON m.id = b.movie_id; 2. SELECT title, rating*10 AS ratings_percent FROM boxoffice AS b INNER JOIN movies AS m ON m.id = b.movie_id; 3. SELECT title, year FROM boxoffice AS b INNER JOIN movies AS m ON m.id = b.movie_id WHERE year % 2 = 0 ORDER BY year ASC; Lesson 10: Queries with aggregates (Pt. 1) 1. SELECT MAX(years_employed) AS longest_years FROM employees; 12 SQL Boat 2. SELECT role, AVG(years_employed)AS average_years_employed FROM employees GROUP BY role; 3. SELECT building, SUM(years_employed)AS sum_of_years_employed FROM employees GROUP BY building; Lesson 11: Queries with aggregates (Pt. 2) 1. SELECT COUNT(role) FROM employees WHERE role = 'Artist'; 2. SELECT role, COUNT(name) AS number_of_employees FROM employees GROUP BY role; 13 SQL Boat 3. SELECT role, SUM(years_employed) FROM employees GROUP BY role HAVING role = "Engineer"; Lesson 12: Order of execution of a Query 1. SELECT director, COUNT(*) FROM movies GROUP BY director; 1. SELECT director, SUM(domestic_sales + international_sales) AS total_sales FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id GROUP BY director; Lesson 13: Inserting rows 1. INSERT INTO movies (title, director, year, length_minutes) VALUES ('Toy Story 4', 'Lance Lafontaine', 2984, 15); 14 SQL Boat 2. INSERT INTO boxoffice (movie_id, rating, domestic_sales, international_sales) VALUES (15, 8.7, 340000000, 270000000); Lesson 14: Updating rows 1. UPDATE movies SET director = "John Lasseter" WHERE title = "A Bug's Life"; 2. UPDATE movies SET title = 'Toy Story 3', director = 'Lee Unkrich' WHERE id = ( SELECT id FROM movies WHERE title = 'Toy Story 8' ); Lesson 15: Deleting rows 1. DELETE FROM movies WHERE year < 2005; 2. DELETE FROM movies WHERE director = 'Andrew Stanton'; 15 SQL Boat Lesson 16: Creating tables CREATE TABLE IF NOT EXISTS Database ( Name TEXT, Version FLOAT, Download_count INTEGER ); Lesson 17: Altering tables 1. ALTER TABLE movies ADD aspect_ratio FLOAT; 2. ALTER TABLE movies ADD language TEXT DEFAULT 'English'; Lesson 18: Dropping tables 1. DROP TABLE IF EXISTS movies; 2. DROP TABLE IF EXISTS boxoffice; 16 Build Your First Project - Javascript styles.css h1{ text-align: center; color: #FFD700; margin-top: 50px; } index.html <!DOCTYPE html> <html lang="en"> <head> <script src="index.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link href="styles.css" rel="stylesheet"> <title>First Project</title> </head> <body> <div class="d-flex justify-content-center" style="margin-top:50px"> <button id="hello" class="btn btn-warning">Welcome!</button> <button id="red" class="btn btn-danger">Red</button> <button id="green" class="btn btn-success">Green</button> <button id="blue" class="btn btn-primary">Blue</button> </div> <h1></h1> </body> </html> 2 Build Your First Project - Javascript index.js document.addEventListener('DOMContentLoaded', function(){ //Get the parameters in HTML let sayhello = document.querySelector('h1'); let body = document.querySelector('body'); //Send a "Hello" message when click the button document.querySelector('#hello').onclick = function() { sayhello.innerHTML = 'Hello, you!'; body.style.backgroundColor = 'white'; }; //Change the background color to red when click the button document.querySelector('#red').onclick = function() { body.style.backgroundColor = 'red'; sayhello.innerHTML = ''; }; //Change the background color to green when click the button document.querySelector('#green').onclick = function() { body.style.backgroundColor = 'green'; sayhello.innerHTML = ''; }; //Change the background color to blue when click the button document.querySelector('#blue').onclick = function() { body.style.backgroundColor = 'blue'; sayhello.innerHTML = ''; }; }); 3 TODO - Flask application.py from flask import Flask, redirect, render_template, request app = Flask(__name__) #Create this to have a list of todos todos = [] @app.route("/") def tasks(): return render_template("tasks.html", todos=todos) @app.route("/add", methods=["GET","POST"]) def add(): #GET is a request method used by default #And is used when you want to get a page if request.method == "GET": return render_template("add.html") #POST means you're trying to send data to the server else: #Get the input from the user todo = request.form.get('task') #Add this new task to the todos list todos.append(todo) #Redirect the user to the page that has the todos return redirect("/") 2 TODO - Flask layout.html <!DOCTYPE html> <html lang="en"> <head> <title>Tasks</title> </head> <body> {% block body %} {% endblock %} </body> </html> tasks.html {% extends "layout.html" %} {% block body %} <h1>Tasks</h1> <ul> {% for todo in todos %} <li>{{ todo }}</li> {% endfor %} </ul> <a href="/add">Create a New Task!</a> {% endblock %} 3 TODO - Flask add.html {% extends "layout.html" %} {% block body %} <form action="/add" method="POST"> <input id="task" name="task" type="text" placeholder="Add New Task!"> <input id="submit" type="submit" disabled> </form> <script> document.querySelector('#task').onkeyup = function() { if (document.querySelector('#task').value === ''){ document.querySelector('#submit').disabled = true; } else{ document.querySelector('#submit').disabled = false; } } </script> {% endblock %} 4 Checklist – Search (Project 0) Summary Pages........................................................................................................................................... 3 Query Text.................................................................................................................................. 4 Query Images............................................................................................................................ 5 Query Advanced....................................................................................................................... 6 Appearance ............................................................................................................................... 8 Lucky ........................................................................................................................................... 9 Aesthetics................................................................................................................................ 10 FAQ.............................................................................................................................................. 11 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Search (Project 0) Pages Specification Your website should have at least three pages: one for Google Search, one for Google Image Search, and one for Google Advanced Search. How To Do This? Since the project must have three pages and the distribution code already given to us index.html, you have to create two more HTML files for the Google Image Search and Google Advanced Search. Specification On the Google Search page, there should be links in the upper-right of the page to go to Image Search or Advanced Search. On each of the other two pages, there should be a link in the upper-right to go back to Google Search. How To Do This? To solve this problem, you can use the <ul> tag to create a navbar. This navbar must contain 2 nav-item (in this case you can use the <li> tag) to redirect the site to the other two pages that are not open. For example, the Google search page must have two nav-item to redirect the site to Image Search or Advanced Search, like indicated by the green arrows in the image below. The best way to do this is using the <a> tag, where the “href” is going to set the HTML file you want to redirect when the user clicks in the text. 3 Checklist – Search (Project 0) Query Text Specification On the Google Search page, the user should be able to type in a query, click “Google Search”, and be taken to the Google search results for that page. How To Do This? The code already gives to us the <form> and the action with the corresponding page that we are going find the result. We also have the two <input> tags that creates the text input and the submit button. Note that in the <input type=”text”> we have a property of name=”q” inside. The action added with this name are going to redirect the page to the corresponding result page right after the button submit is clicked. So, in this part you do not need to do anything, the project already give this to us. Specification Like Google’s own, your search bar should be centered with rounded corners. The search button should also be centered and should be beneath the search bar. How To Do This? To do this, it is recommended that you create a CSS file. You can find how to do rounded corners using the CSS tools in this link: https://www.w3schools.com/cssref/css3_pr_border-radius.asp 4 Checklist – Search (Project 0) You can find how to align the elements in the Bootstrap documentation. We suggest you to use the <input type=”submit”> inside a <div> tag to use the Bootstrap class. Look on this link: https://getbootstrap.com/docs/4.0/utilities/flex/ At this point, your project should look like this: Query Images Specification On the Google Image Search page, the user should be able to type in a query, click a search button, and be taken to the Google Image search results for that page. How To Do This? The first thing you have to do is to create a file similar to index.html, but the difference in this case will be the <a> tag, because you have to redirect to Google Search and Google Advanced Search. For the image search you must use de Developer Tools to find how to do this search. You are going to have to use an <input type=”hidden”> tag. 5 Checklist – Search (Project 0) At this point, your project should look like this: Query Advanced On the Google Advanced Search page, the user should be able to provide input for the following four fields (taken from Google’s own advanced search options). Specification Find pages with… “all these words:” How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: 6 Checklist – Search (Project 0) Specification Find pages with… “this exact word or phrase:” How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: Specification Find pages with… “any of these words:” How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: Specification Find pages with… “none of these words:” 7 Checklist – Search (Project 0) How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: Appearance Specification Like Google’s own Advanced Search page, the four options should be stacked vertically, and all the text fields should be left aligned. How To Do This? To stack the four options vertically in the Advanced Search page, you can use one <div> tag for each input. To do all the text fields left aligned, you can add in your CSS file a class setting the margin-left size you want to have in your page. At this point your project should look like this: 8 Checklist – Search (Project 0) Specification Consistent with Google’s own CSS, the “Advanced Search” button should be blue with white text. When the “Advanced Search” button is clicked, the user should be taken to search results page for their given query. How To Do This? To do this part, you can use the Bootstrap documentation about buttons. Look on this link: https://getbootstrap.com/docs/4.0/components/buttons/ Lucky Specification Add an “I’m Feeling Lucky” button to the main Google Search page. Consistent with Google’s own behavior, clicking this link should take users directly to the first Google search result for the query, bypassing the normal results page. How To Do This? On Google Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: 9 Checklist – Search (Project 0) Aesthetics Specification The CSS you write should match Google’s own aesthetics as best as possible. How To Do This? We suggest you check the CSS and Bootstrap documentation. Also, use the Developer Tools to know some interesting properties to be used in your project. For example, if you want to know the margin, background and padding of the original “Google Search” button, you can use the Developer Tools to check that. . 10 Checklist – Search (Project 0) FAQ Question Answer Try searching for "CS50" on Google, then do the same on Google Images and compare the URLs. You will see the only difference between them is an additional parameter called tbm, which Google uses to know it should display the Google Images results instead of the Search results. You need to use this parameter in project0 to redirect to the correct results page. Question Answer To do this you should use margin property of CSS and align elements property, also from CSS. Check the link below: 11 Checklist – Search (Project 0) https://www.w3schools.com/css/css_align.asp Question Answer We already answer that in the Query Advanced section. Question Answer We already answer that in the Query Advanced section. 12 Checklist – Wiki (Project 1) Summary Understanding Util.py............................................................................................................. 3 Convert Markdown to HTML................................................................................................. 4 Entry Page ................................................................................................................................. 5 Hint............................................................................................................................................... 7 Index Page................................................................................................................................. 7 Search......................................................................................................................................... 8 New Page................................................................................................................................. 10 Edit Page ...................................................................................................................................13 Random Page...........................................................................................................................16 FAQ..............................................................................................................................................17 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Wiki (Project 1) Understanding Util.py list_entries() Returns a list of all names of encyclopedia entries. Let us look on how to use this function: allEntries = util.list_entries() Now, let us look on how the information that this function returns come to us (using the debugger): save_entry(title,content) Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. Let us look on how to use this function: util.save_entry(title,content) get_entry(title) Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. Let us look on how to use this function: entry = util.get_entry(title) Now, let us look on how the information that this function returns come to us (using the debugger): 3 Checklist – Wiki (Project 1) Convert Markdown to HTML Specification On each entry’s page, any Markdown content in the entry file should be converted to HTML before being displayed to the user. You may use the pythonmarkdown2 package to perform this conversion, installable via pip3 install markdown2. How To Do This? First you should understand what the python-markdown2 does. You can check the link given to us in the specifications: https://github.com/trentm/python-markdown2 Markdown is a light text markup language, and the entries are written in this language. The problem of this project is that we are using HTML, that is another markup language. How to solve this? The link explains how we are going to do this. But just the link is not enough. The first thing you must do is to import the markdown2 library in ‘views.py’. Then, you are going to do this conversion every time you have to display the page that already exists in the entries folder or every time you create a new page. First, you are going to create a variable to store the ‘Markdown()’ function. This function is going to do the conversion to you. For example: markdown = Markdown() But how am I going to take the markdown content of the entry? To do this, you should use the ‘get_entry’ function, because it retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. Thus, you are going to store in a variable the entry using the ‘get_entry’ function. For example: entry = util.get_entry(entry_name) 4 Checklist – Wiki (Project 1) If the ‘get_entry’ function returns None, you are going to return None in your conversion. If the ‘get_entry’ function does not return None, you are going to create a new variable to store this conversion. In this variable, you are going to use the explanation in the link. Thus, you are going to do the following. html_converted = markdown.convert(entry) It is scary for the first time, but you are going to see that this will save you time! Entry Pages Specification Visiting /wiki/TITLE, where TITLE is the title of an encyclopedia entry, should render a page that displays the contents of that encyclopedia entry. How To Do This? To solve this, you should go to urls.py file and add in the urlpatters a new path. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand the flexible way that they use to create a path (image below): Thus this new path will be something like ‘/wiki/<str: title>’, where the ‘title’ will the title of an encyclopedia entry. Specification The view should get the content of the encyclopedia entry by calling the appropriate util function. How To Do This? To solve this, you should go to views.py file and add a new route. 5 Checklist – Wiki (Project 1) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they use the <str:name> from url in the route (image below): With the ‘title’ in hands, you can call the appropriate util function. In the entry page, you want to display the content of the title. You should use the logic to convert the Mardown to HTML. Specification If an entry is requested that does not exist, the user should be presented with an error page indicating that their requested page was not found. How To Do This? Like explained in the previous bullet point, the ‘get_entry’ retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. Thus, your ‘conversion Markdown to HTML’ returns or the HTML content or None. Knowing that, you should do an if-else condition in your route (views.py file) using the None as this condition. If ‘conversion Markdown to HTML’ returns None, you should display a page indicating that the entry does not exists. You can create a new HTML file to display just this error message and indicate in the route to render that specific page. Specification If the entry does exist, the user should be presented with a page that displays the content of the entry. The title of the page should include the name of the entry. How To Do This? If ‘conversion Markdown to HTML’ does not return None, you should display the entry page. To do this, you should pass as context the title and the conversion to HTML to render the html file. 6 Checklist – Wiki (Project 1) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): Hint Specification By default, when substituting a value in a Django template, Django HTMLescapes the value to avoid outputting unintended HTML. If you want to allow for an HTML string to be outputted, you can do so with the safe filter (as by adding |safe after the variable name you’re substituting). How To Do This? You probably had this issue when trying to render your entry page. If you do not use this ‘save’ property in the HTML file, the compiler will understand that you are passing a string and not a html content. To solve this, use the value of the conversion to html and the safe word together. For example: {{ conversion_html | safe }} Index Page Specification Update index.html such that, instead of merely listing the names of all pages in the encyclopedia, user can click on any entry name to be taken directly to that entry page. How To Do This? 7 Checklist – Wiki (Project 1) To solve this, you should go to ‘index.html’ file and you are going to find basically all done for you. The only thing that you have to add is an <a> tag to solve this ‘click on any entry name to be taken directly to that entry page’. Final Step You should go to ‘layout.html’ and add <a> tag to the user be able to click in ‘Home’ and go to the index page. Search Specification Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. How To Do This? To solve that, you should create a new URL simple path in ‘urls.py’. Like the following image from Lecture Django in CS50 notes. In addition, you should create a new route in ‘views.py’. In there, you should use the ‘list_entries’ function the way that we recommended in the beginning of this checklist. Then, you should get the input from the user in the search box and store in a variable. Since this is a request GET method, you should use, for example: search = request.GET(‘NameOfTheInputOnHTML’) To check if there is an entry with the title that the user wants to search, you should use the ‘get_entry’ function the way that we recommended in the beginning of this checklist. Specification If the query matches the name of an encyclopedia entry, the user should be redirected to that entry’s page. 8 Checklist – Wiki (Project 1) How To Do This? This will occur if the function ‘get_entry’ does not return None. Then, you should render the entry page of this entry searched. Specification If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were ‘Py’, then ‘Python’ should appear in the search results. How To Do This? This will occur if the function ‘get_entry’ returns None. You should create an empty list. Then, you should do an iteration in each entry in the ‘list.entries’ and check if the search is a substring of the entries that already exists. If the search is a substring, you are going to append this entry in the empty list that you created previously. Else, you go to the next iteration. After all, pass as context this new list and render the ‘index.html’ page with this context. This is what your project should return when you seach ‘Py’ in the entries. Specification 9 Checklist – Wiki (Project 1) Clicking on any of the entry names on the search results page should take the user to that entry’s page. How To Do This? Since you are using the index.html file to render the search query, you do not need to do this step, because you already did in the Index section. New Page Specification Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry. How To Do This? You should go to ‘layout.html’ and add <a> tag to the user be able to click in ‘Create New Page’ and go to the create new page. You should create a new URL and new route to display this page. Also, you should create a html file to display the components of your page. After that, in the ‘views.py’ render the page. Specification Users should be able to enter a title for the page and, in a textarea, should be able to enter the Markdown content for the page. How To Do This? In the html file, you are going to use the <form> tag to create the textarea for title and content of the page. You can set how many rows your textarea will display. Look at this link: https://www.w3schools.com/tags/tag_textarea.asp 10 Checklist – Wiki (Project 1) Since you are using form with Django, you must use the syntax explained in Lecture Django in CS50 notes. Look the image below: Inside the form, you should use two <textarea> tags, one for title and other for Markdown content. The title will be the title of your tab (green arrow in the image below) and the Markdown content will be the content displayed in your page (yellow arrow in the image below). Specification Users should be able to click a button to save their new page. How To Do This? After creating the <textarea> tags and before closing the <form> tag, use an <input> tag with ‘type=submit’. You can change the style of this button using Bootstrap for example. See the following link: https://getbootstrap.com/docs/5.0/components/buttons/ At this point, the New Page should be look like: 11 Checklist – Wiki (Project 1) Specification When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message. Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page. How To Do This? Now you are going to work with the ‘views.py’ file. In there, you have to do an if-else condition to check if you are going to work with the POST method or GET method. You can use the following notation: if request.method == ‘POST’: else: The POST method basically will handle the data of the form. Inside this if, you are going to get the information from the form using the following notation, for example: title = request.POST[‘title’] content = request.POST[‘content’] Then, you have to check if the entry already exists. To do this, you can use the ‘get_entry’ function that we explained in the Util section. If the ‘get_entry’ does not return None, you should render a html file saying that this page already exists. Here you are going to do the same way as we explained in the Entry Page section. 12 Checklist – Wiki (Project 1) If the ‘get_entry’ returns None, you are going to call the conversion to HTML function and render the entry page. The GET method basically will handle displaying the ‘New Page’ html file. Thus, inside of the else you are just going to render the ‘New Page’. Edit Page Specification On each entry page, the user should be able to click a link to be taken to a page where the user can edit that entry’s Markdown content in a textarea. How To Do This? You should create a new URL path and a new route. These two files will be like the entry page, but in this case the URL should be like ‘edit/<str: title>/’. To solve this, you can add an <a> tag that redirect the user to this new URL path. You can style that using buttons from Bootstrap. See the following link: https://getbootstrap.com/docs/5.0/components/buttons/ To create a button in your <a> tag you should copy the class from Bootstrap and put inside de <a> tag. For example: <a class=”btn btn-primary” href=’…’> At this point, your entry page should look like this: 13 Checklist – Wiki (Project 1) Specification The textarea should be pre-populated with the existing Markdown content of the page. (i.e., the existing content should be the initial value of the textarea). How To Do This? Now you are going to work with the ‘views.py’ file. In there, you have to do an if-else condition to check if you are going to work with the POST method or GET method. You can use the following notation: if request.method == ‘GET’: else: The GET method basically will handle displaying the ‘Edit Page’ HTML file. To pre-populate with the existing Markdown content of the page, you should use the ‘get_entry’ function. Then, you need to pass the entry name and the entry content as context from ‘views.py’ to ‘edit’ HTML. In the ‘edit’ HTML, you are going to use the <form> tag to create the textarea for title and content of the page. You can set how many rows your textarea will display. Look at this link: https://www.w3schools.com/tags/tag_textarea.asp Since you are using form with Django, you must use the syntax explained in Lecture Django in CS50 notes. Look the image below: So far, the page should look like: 14 Checklist – Wiki (Project 1) Note that the title will be the title of your tab (green arrow in the image below) and the Markdown content will be the content displayed in your page (yellow arrow in the image below). Specification The user should be able to click a button to save the changes made to the entry. How To Do This? Your <input type=”submit”> will be this button to save the changes made to the entry. You can style this input using Bootstrap: https://getbootstrap.com/docs/5.0/components/buttons/ 15 Checklist – Wiki (Project 1) This information will be sent to the backend (‘views.py’). In the route you already have the GET method. Now we are going to work with the POST method. The POST method basically will handle the data of the form. Inside this else, you are going to get the information from the form using the following notation, for example: title = request.POST[‘title’] content = request.POST[‘content’] Then, you must save this entry using the ‘save_entry’ function. Check the ‘Understand util.py’ section. After saving, you should convert this edited entry using the ‘conversion Markdown to HTML’. Specification Once the entry is saved, the user should be redirected back to that entry’s page. How To Do This? This is the last part in the POST method. You are going to render the page with the edited entry. Remember to pass as context the title and the content of the edited entry. Random Page Specification Clicking “Random Page” in the sidebar should take user to a random encyclopedia entry. How To Do This? You should create a new url and new route to display this page. You can use the ‘random library, because there is a function ‘randpm.choice()’ that pick a random entry in the list you pass as input. 16 Checklist – Wiki (Project 1) After that, call the conversion to HTML function and render the page. Final Step You should go to ‘layout.html’ and add <a> tag to the user be able to click in ‘Random Page’ and go to the random page. FAQ Question How To Do This? The reason why the search is not working is because the code didn’t have the {csrf_token}. Check the Search section to know better. Question How To Do This? When you do the iteration in each entry to if the search input is a substring of other entries, you have to make all lower case. To do this, you can use the .lower() Python function to do the comparison. For example: if search.lower() in entry.lower(): 17 Checklist – Wiki (Project 1) Question How To Do This? Check the Edit Page section and you will understand how to do it. Question How To Do This? To solve the formatting of <textarea> tags you should change the properties in styles.css. To solve the markdown conversion, look at Convert Markdown to HTML section and the New Page section. Question How To Do This? 18 Checklist – Wiki (Project 1) Check the Edit Page section and you will understand how to do it. Question How To Do This? To solve this, you should go to ‘index.html’ file and you are going to find basically all done for you. The only thing that you have to add is an <a> tag to solve this ‘click on any entry name to be taken directly to that entry page’. 19 Checklist – Commerce (Project 2) Summary Models........................................................................................................................................................3 Create Listing..........................................................................................................................................3 Active Listings Page .............................................................................................................................6 Listing Page .............................................................................................................................................7 Watchlist ................................................................................................................................................. 18 Categories .............................................................................................................................................. 19 Django Admin Interface.................................................................................................................... 20 FAQ........................................................................................................................................................... 20 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Commerce (Project 2) Models Specification Your application should have at least three class in addition to the User model: one for auction listings, one for bids, and one for comments made on auction listings. It’s up to you to decide what fields each model should have, and what the types of those fields should be. You may have additional class if you would like. How To Do This? To solve this problem, we suggest to first understand what models do. Look at CS50 Web Lecture 4 Notes in the section Django Models: https://cs50.harvard.edu/web/2020/notes/4/ Basically, you can create Django models to work with databases instead of directly using SQL queries. In the Lecture 4, they suggest creating a file called ‘models.py’ where you are going to outline what data you want to store in your application. Then, Django will determine the SQL syntax necessary to store information on each of your class. Thus, before starting the project 2, make sure you really understand the Flight example gave in CS50 Web Lecture 4 Notes. After understanding the Flight example, you will be very comfortable working with models in your project. This models specification will be done while you progress in your project. Let’s go to the next part! Create Listing Specification Users should be able to visit a page to create a new listing. They should be able to specify a title for the listing, a text-based description, and what the starting bid should be. Users should also optionally be able to provide a URL for an image for the listing and/or a category (e.g. Fashion, Toys, Electronics, Home, etc.). 3 Checklist – Commerce (Project 2) How To Do This? Since the new listing information will be stored in the database, you can create a Model to do this. Look at CS50 Web Lecture 4 Notes to have an idea on how to do this: You are going to do something like this in your ‘models.py’, but in your case you should fulfill the requirements for the listing: title, text-based description, starting bid, image by URL and/or category. Check the link below to know better how to create each field for the class: https://docs.djangoproject.com/en/3.0/ref/forms/fields/#built-in-field-classes We suggest creating one model for the listing and one model for the category. Note: remember to create a field for the owner of the listing! After creating your class, you should create an URL path, a route, and a HTML file to create a new listing. In the new HTML file, you should use a <form> tag and have as input the requirements said above. Note: since you are using forms with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look at the image below: Now you are going to work with the ‘views.py’ file. In there, you have to do an if-else condition to check if you are going to work with the POST method or GET method. You can use the following notation: if request.method == ‘POST’: else: 4 Checklist – Commerce (Project 2) The POST method basically will handle the data of the form. Inside of this if, you are going to get the information from the form using the following notation, for example: title = request.POST[‘title’] … category = request.POST[‘category’] You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. The GET method basically will handle displaying the ‘New Listing Page’ html file. Thus, inside of the else you are just going to render the HTML file you already created (the one with the <form> tag). Active Listings Page 5 Checklist – Commerce (Project 2) Specification The default route of your web application should let users view all of the currently active auction listings. For each active listing, this page should display (at minimum) the title, description, current price, and photo (if one exists for the listing). How To Do This? To solve this problem, you should work with the ‘index.html’ file and use the Bootstrap tools to create a nice ‘Active Listings Page’. You may be interested in use <div> tag to separate each listing information in boxes, like the image below: In ‘models.py’ you should create a field in your listing model to set if the listing is active or not. By now, all your listing should be active. Further in the project, you will be able to change this status. In ‘views.py’ you should find a way to display only the active listings. To do this, you should manipulate your class. Look how it works in CS50 Web Lecture 4 Notes. In your case, you should filter by the active field. 6 Checklist – Commerce (Project 2) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): After passing as context this information from ‘views.py’ to the HTML file, you are going to display the title, description, current price, and photo (if one exists for the listing). For example, passing the listing as context in the ‘views.py’: Listings = Listings.objects.filter(active=True) In ‘index.html’, since you are passing multiple listings, you should do an iteration to display all listings at a time. For example: {% for listing in listings %} … {% endfor %} Remember to use the double curly braces to display the information from ‘views.py’ in the HTML file. For example, to display the title of the listing you can use: {{ listing.title }} Listing Page Specification Clicking on a listing should take users to a page specific to that listing. On that page, users should be able to view all details about the listing, including the current price for the listing. How To Do This? To do this, in your ‘index.py’, you should use an <a> tag in each listing in your index. The <a> tag should have as ‘href’ the URL for the listing. This URL for the listing will be like what you did in Wiki Project. Look at greet function in CS50 Web Lecture 3 Notes: 7 Checklist – Commerce (Project 2) Note: in this case you should use <int:listing_id> instead of <str:name>. In this page, you should pass the information from de backend (‘views.py) to the frontend (HTML file). In ‘views.py’ you should find a way to display only the active listings. To do this, you should manipulate your class. Look how it works in CS50 Web Lecture 4 Notes. In your case, you should filter the category model by the listing field and the listing model you should get by the id. If you do not remember how to do this, look at ‘Active Listings Page’ section. Thus, in this page you are going to display the following information: • Name of the listing: you should display the title of the listing. For example: {{ listing.title }} • The image of the listing: it is optional. You are going to display this using the <img> tag and the image is stored in the same way you have the title. For example: {{ listing.image }} • The description of the listing: you can do the same way as you did for name of the listing. • Category of the listing: you can do the same way as you did in name of the listing, but in this case, you should call the category that you passed as context. For example: {{ category.title }} • The current bid: you are going to display the same way as you display the name of the listing. It is up to you decide how many information you want to display from your Listing class. 8 Checklist – Commerce (Project 2) Note: now you know that you are going to have a starting bid and a current bid in your listing. Thus, we recommend creating one field for each of these bids. Specification If the user is signed in, the user should be able to add the item to their “Watchlist.” If the item is already on the watchlist, the user should be able to remove it. How To Do This? In this case you should pass a Boolean saying whether the listing of a particular user is in his watchlist as context in your ‘views.py’. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): It might be useful to use the Python in operator. In the HTML file, you first should check if the user is signed in. To do this, you can do an if-else condition. For example: {% if user.is_authenticated %} … {% else %} … {% endif %} Inside the if user.is_authenticated, you are going to create a condition based on this context that you passed. If this condition is True, you are going to display the logic to remove the listing from the watchlist. If the condition is False, you are going to display the logic to add the listing to the watchlist. For example, the in_watchlist is a Boolean variable that stores whether a listing is in the user’s watchlist: {% if in_watchlist == True %} 9 Checklist – Commerce (Project 2) … {% else %} … {% endif %} Inside these if-else condition, you can display a button, for example. When the user clicks on this button, the user can add or remove the listing to his watchlist. To handle adding the listing in the watchlist, you should create a new URL path and a new route in ‘views.py’. This URL will be like what you did in ‘Listing Page’. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. In the route, you should get the listing by id. With this id you can get the listing in the Listing model and add the user in the watchlist field. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. 10 Checklist – Commerce (Project 2) Remember how you did in ‘Create Listing’ section! To handle the removal of the listing from the watchlist, you should create a new URL path and a new route in ‘views.py’. This URL will be like what you did in ‘Listing Page’. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. In the route, you should get the listing by id. With this id you can get the listing in the Listing model and remove the user in the watchlist field. You can remove checking the .remove property in the following link: https://docs.djangoproject.com/en/3.1/topics/db/queries/ You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. Remember how you did in ‘Create Listing’ section and ‘Adding to Watchlist’! 11 Checklist – Commerce (Project 2) Specification If the user is signed in, the user should be able to bid on the item. The bid must be at least as large as the starting bid, and must be greater than any other bids that have been placed (if any). If the bid doesn’t meet those criteria, the user should be presented with an error. How To Do This? You can create a new model in ‘models.py’ for Bids. In this model should have as fields the offer, the user that gave the bid and the listing (where the offer was made). In the listing HTML file, you should first check if the user is authenticated and if the listing is active. For example, where the listing.active is a Boolean variable that sets whether the listing is active or not: {% if user.is_authenticated and listing.active == True %} … {% else %} … {% endif %} Inside the if user.is_authenticated and listing.active == Ture, you are going to use a <form> tag and have as input the bid of the user. Note: since you are using form with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look the image below: To handle submitting the bid, you should create a new URL. This URL will be like what you did in ‘Listing Page’. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. 12 Checklist – Commerce (Project 2) Then, you should create a new route for the comment. In this route you should get the listing by the id. Look how it works in CS50 Web Lecture 4 Notes. In there, you must do an if condition to check if you are going to work with the POST method. You can use the following notation: if request.method == ‘POST’: The POST method basically will handle the data of the form. Inside this if, you are going to get the information from the form using the following notation, for example: user_bid = request.POST[‘user_bid’] Then, you must check if the user_bid is greater than the starting bid or the current bid. If is not, you should present an error for the user. You can do this by creating a new HTML file for example. If the offer is greater than the current bid or the start bid, you should add this new bid in the model. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() 13 Checklist – Commerce (Project 2) Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. At this point, your project should look like: Specification If the user is signed in and is the one who created the listing, the user should have the ability to “close” the auction from this page, which makes the highest bidder the winner of the auction and makes the listing no longer active. How To Do This? In this case you should pass a Boolean saying whether the particular user is the owner of the listing as context in your ‘views.py’. 14 Checklist – Commerce (Project 2) You can do this by checking if the user is the field that you created in your Listing model to handle storing the owner of each listing. Thus, you should pass as context your Boolean variable. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): In the HTML file, you first should check if the user is signed in. To do this, you can do an if-else condition. For example: {% if user.is_authenticated %} … {% else %} … {% endif %} Inside the if user.is_authenticated, you are going to create a condition based on this context that you passed. If this condition is True, you are going to display the logic to close the bid. Also, you must check if the listing is active or not. For example, the is_owner is a Boolean variable that stores whether the user is the owner of the listing, and the listing.active is a Boolean variable that stores whether the listing is active or not: {% if is_owner == True and listing.active == True%} … {% else %} … {% endif %} Inside this if condition, you can display a button, for example. When the user clicks on this button, the user can close the auction. To handle closing the listing, you should create a new URL path and a new route in ‘views.py’. This URL will be like what you did in Listing Page. Look at greet function in CS50 Web Lecture 3 Notes: 15 Checklist – Commerce (Project 2) Note: in this case you should use <int:listing_id> instead of <str:name>. In the route, you should get the listing by id. With this id you can get the listing in the Listing model and set the active field as False. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. Remember how you did in ‘Create Listing’ section! Specification If a user is signed in on a closed listing page, and the user has won that auction, the page should say so. How To Do This? In this case you should pass a Boolean saying whether the particular user has the current bid in a listing (the one that won the auction) as context in your ‘views.py’. 16 Checklist – Commerce (Project 2) You can do this by checking if the user is the field that you created in your Listing model to handle storing the user that placed the current bid of each listing. Thus, you should pass as context your Boolean variable. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): In the HTML file, you first should check if the user is the buyer of the listing and the listing is not active. For example, the is_winner is a Boolean variable that stores whether the user is the winner of the listing, and the listing.active is a Boolean variable that stores whether the listing is active or not: {% if listing.active == False and is_winner == True %} … {% endif %} Inside the if, you are going to display a message telling the user that he won the auction. Specification Users who are signed in should be able to add comments to the listing page. The listing page should display all comments that have been made on the listing. How To Do This? About the comments, you can create a new model. In this model should have as fields the comment, the user that gave the comment and the listing (where the comment was made). In this section, we must do two things. First receive new comments from the user and second display the comments. 1. Receive new comments from the user: 17 Checklist – Commerce (Project 2) In the listing HTML file, you are going to first check if the user is authenticated. For example: {% if user.is_authenticated %} … {% else %} … {% endif %} Inside the if user.is_authenticated, you are going to use a <form> tag and have as input the comment of the user. Note: since you are using form with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look the image below: To handle submitting the comments, you should create a new URL. This URL will be similar to what you did in Listing Page. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. Then, you should create a new route for the comment. In this route you should get the listing by the id. Look how it works in CS50 Web Lecture 4 Notes. In there, you have to do an if condition to check if you are going to work with the POST method. You can use the following notation: 18 Checklist – Commerce (Project 2) if request.method == ‘POST’: The POST method basically will handle the data of the form. Inside this if, you are going to get the information from the form using the following notation, for example: user_comment = request.POST[‘user_comment’] Then, you should add this information to the Comment model. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can fulfill the model creating a variable to store the model itself. For example: flight = Flight() Then, instead of doing what is in the image above, you can store each field of the model by calling the previous variable and using a dot and the name of the field. For example, if you want to fulfill the origin field in Flight class, you can do the following: flight.origin = “New York” Now, you should do the same idea in your project. 2. Display the comments in the listing: In the listing page route, you should pass as context the comments for that listing. Remember to use the following: comments = Comment.objects.filter(listing=listing) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): 19 Checklist – Commerce (Project 2) Since you are passing multiple listings, you should do an iteration to display all the comments at a <div> tag. For example: {% for comment in comments %} … {% endfor %} Remember to use the double curly braces to display the information from ‘views.py’. For example, to display the comment you can use: {{ comment.user }} Watchlist Specification Users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. Clicking on any of those listings should take the user to that listing’s page. How To Do This? To solve this, first you should pass the user watchlist model to a new HTML file. You can do this by passing as context. Look at greet function on CS50 Web Lecture 3 Notes: In this HTML file you are going to display the listings the same way as you did in the ‘index.html’. 20 Checklist – Commerce (Project 2) Categories Specification Users should be able to visit a page that displays a list of all listing categories. Clicking on the name of any category should take the user to a page that displays all of the active listings in that category. How To Do This? To solve this, first you should pass the category model to a new HTML file. You can do this by passing as context. Look at greet function on CS50 Web Lecture 3 Notes: Then, you are going to the HTML file and can create a <form> tag to display the categories options. Note: since you are using form with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look the image below: The form will be handled in a new route, where you are going to display the specific listings of that category chosen by the user. Thus, in this new route you should get the values from the form. And then, use this category to get the listings. Pass this information to the HTML file. Remember how to do this in the previous sections. In this HTML file you are going to display the listings the same way as you did in the ‘index.html’. Django Admin Interface 21 Checklist – Commerce (Project 2) Specification Via the Django admin interface, a site administrator should be able to view, add, edit, and delete any listings, comments, and bids made on the site. How To Do This? To solve this, you are going to follow the steps explained in the ‘Django Admin’ at the end of CS50 Web Lecture 4 Notes. Just follow the steps! FAQ Specification When should I use the @login_required decorator in my ‘views.py’? How To Do This? You should use this decorator any time you want display the page only if the user is logged in. For example, you can use this @login_required decorator in the watchlist page. Specification How should I create my Category model? How To Do This? Your Category model should have at least two fields. One for the name of the category, and in this case, you are going to use the CharField. The other field should have a relationship with the Listing model. In this case, you should use the ForeignKey field. Specification When should I use the ManyToManyField relationship in ‘models.py’? 22 Checklist – Commerce (Project 2) How To Do This? By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it. You should use the ManyToManyField in the watchlist for example. Because this field will store which users wants to have in the watchlist for each listing. Thus, you are going to be able to store multiple users in each listing. For example, Mary and John want to have the Chocolate listing in the watchlist. Mary wants to have the Cake listing in the watchlist. Daniel wants to have Ice Cream listing in the watchlist. The ManyToManyField will store this information. Specification How To Do This? The Bids model should store the data about the offer, the user that gave the offer and a relation between the bid and the listing where the bid was placed. This relation will be handled by the ForeignKey field. Specification How To Do This? You should create a field in your Listing model to check if the listing is active or not. You can do this by using the BooleanField. Then, in your ‘views.py’ you must filter the listing by this Boolean. For example: listings = Listing.objects.filter(active=True) 23 Checklist – Commerce (Project 2) Specification How To Do This? Since you are receiving the image by it is URL, you can display the image just using the <img> tag and in the property ‘src’ you call the listing image. For example: <img src={{ listing.image }}> Remember to pass as context to the HTML file the Listing model. If you do not know how to do this, check the ‘Listing Page’ section. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): Specification How To Do This? Look on how to do this in the ‘Watchlist’ section. You should pass the watchlist as context from ‘views.py’ to the HTML file. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): 24 Checklist – Commerce (Project 2) 25 TODO - Javascript styles.css h1{ text-align: center; color: gray; } .container-style{ margin-bottom: 50px; margin-left: 50px; margin-right: 50px; margin-top: 50px; } task.html <!DOCTYPE html> <html lang="en"> <head> <!--Defines what the title of the webpage will be--> <!--As displayed in the tab of the browser--> <title>Tasks</title> <!--Explains to the compiler where the javascript file code is--> <script src="tasks.js"></script> <!--Explains to the compiler where the css file is--> <link href="styles.css" rel="stylesheet"> <!--Explains to the compiler where the Bootstrap documentation is--> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"> </head> 2 TODO - Javascript <body> <!--Heading of the page--> <div class="container-style"> <h1>Tasks</h1> </div> <div class="container"> <!--Creates an unordered list to display the tasks--> <!--The javascript code will handle the list items--> <ul id="tasks" class="list-group"></ul> </div> <!--Creates a form to the user inputs a new task--> <div class="container-style"> <form> <!--This input field is to type the new task--> <input id="task" placeholder = "New Task" type="text" class="form-control"> <!--This input field is to create a submit button--> <input id="submit" type="submit" class="btn btn-light"> </form> </div> </body> </html> 3 TODO - Javascript tasks.js document.addEventListener('DOMContentLoaded', () => { //Select the form tag in HTML to be used later const form = document.querySelector('form'); //Select the ul tag in HTML to be used later const ul = document.querySelector('ul'); //Select the submit button in HTML to be used later const submit = document.querySelector('#submit'); //Select the task input in HTML to be used later let newtask = document.querySelector('#task'); //Default action for the submit button when you enter on the page submit.disabled = true; //Listen for input to be typed into the input field newtask.addEventListener('keyup', () => { //When there is nothing typed in the input, turns the submit button disabled if (newtask.value === '') { submit.disabled = true; } //When there is something typed in the input, turns the submit button enable else { submit.disabled = false; } }); 4 TODO - Javascript //When submit the task form.addEventListener('submit', (event) => { //Prevents the default submission of the form which involves //either reloading the current page or redirecting to a new one event.preventDefault(); //We can create HTML elements using the createElement function //Creates an list item on HTML const li = document.createElement('li'); //Add newtask value in list item li.innerHTML = newtask.value; //We can then add HTML those elements to the DOM using the append function //Append the list item to unordered list ul.append(li); //Clear the value of newtask variable and set it to empty newtask.value = ''; //Disable button when there is nothing in newtask submit.disabled = true; }); }); 5 Checklist – Mail (Project 3) Summary Mail Project ............................................................................................................................... 3 Send Mail ................................................................................................................................... 3 Mailbox ....................................................................................................................................... 4 View Email ................................................................................................................................. 7 Archive and Unarchive ........................................................................................................ 10 Reply........................................................................................................................................... 11 CSS............................................................................................................................................. 14 FAQ............................................................................................................................................. 14 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Mail (Project 3) Mail Project The distribution code gives to us all the backend done, so the only files that you are going to work will be the inbox.js, inbox.html and styles.css. Remember that the JavaScript will be written in the inbox.js; the HTML will be written in the inbox.html; and the CSS will be in the styles.css. Send Mail Specification When a user submits the email composition form, add JavaScript code to actually send the email. How To Do This? To solve this bullet point you can create a new function with purpose of submitting the email. You should get the values of recipients, subject, and body from the input that the user gives to the web app. To do this, take a look at this property of JavaScript: https://www.w3schools.com/jsref/met_document_queryselector.asp Specification You’ll likely want to make a POST request to /emails, passing in values for recipients, subject, and body. How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “POST/emails”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. 3 Checklist – Mail (Project 3) Specification Once the email has been sent, load the user’s sent mailbox. How To Do This? To solve this, you should call the function load_mailbox, that is already made to us in the distribution code and sending as input to the function the mailbox ‘sent’. We recommend you use the setTimeout in order to wait the fetch call works. This is interesting to be used because when you use fetch it takes a while to send and receive the information, so the setTimeout will wait this information go and come to render the page. HINT You are going to notice that if you try to send an email your page is not going to be redirected to sent mailbox, but to inbox instead. How to solve this? You should use the preventDefault function because this function will prevent the default of submit to be refreshing the button. Mailbox Specification When a user visits their Inbox, Sent mailbox, or Archive, load the appropriate mailbox. How To Do This? To solve this problem, you are going to work with the load_mailbox function that was already initialized for you in the distribution code. Specification You’ll likely want to make a GET request to /emails/<mailbox> to request the emails for a particular mailbox. 4 Checklist – Mail (Project 3) How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “GET/emails/<str:mailbox>”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. Specification When a mailbox is visited, the application should first query the API for the latest emails in that mailbox. How To Do This? This part is already done for you. If you take a look at mailbox route in views.py, you are going to find on line 95 that the distribution code already returns the email for the frontend in reverse chronological order. Specification When a mailbox is visited, the name of the mailbox should appear at the top of the page (this part is done for you). How To Do This? As the specification already says, this part is done for you. Specification Each email should then be rendered in its own box (e.g. as a <div> with a border) that displays who the email is from, what the subject line is, and the timestamp of the email. 5 Checklist – Mail (Project 3) How To Do This? To do this you should create a new function to render in each email its own box. PS: When you do the fetch call in the load_mailbox, we recommend you remember to call this new function inside. In this function you should do an iteration to work with one email at a time. We recommend you look at forEach JavaScript property. After that, you should get the values of recipient, subject and timestamp that were passed from the backend to the frontend. Store these values in variables. We recommend using the createElement property to create a new tag in the HTML file using JavaScript in order to display this information that you grabbed from the backend. Use the property innerHTML to display this information in the new tag that you created. To complete this task, you have to append the new tag that you created in JavaScript at an existing tag in the HTML file. Specification If the email is unread, it should appear with a white background. If the email has been read, it should appear with a gray background. How To Do This? At this point of the problem, you should create an if-else condition to check if the email was already read. If this is true, use the style.backgroundColor to set the email background as gray. Else, use the same property to set the email background as white. At this point you project should look like this: 6 Checklist – Mail (Project 3) View Email Specification When a user clicks on an email, the user should be taken to a view where they see the content of that email. How To Do This? In the function that you just created to render in each email its own box, you should use the addEventListener function to be triggered when the user clicks in the email box. Specification You’ll likely want to make a GET request to /emails/<email_id> to request the email. How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “GET/emails/100”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. 7 Checklist – Mail (Project 3) Inside the fetch, you can call another function to display the email with the specifications that are in the next bullet point. Specification Your application should show the email’s sender, recipients, subject, timestamp, and body. How To Do This? This part you should do in your function created to display the email. To solve this bullet point, you can grab the current email’s properties by the values that you are grabbing from the fetch call. For example, to grab the sender you can do email.sender and store this value in a variable. To display these values, you should use the property innerHTML in the div tag that you include in your inbox.html. Specification You’ll likely want to add an additional div to inbox.html (in addition to emailsview and compose-view) for displaying the email. Be sure to update your code to hide and show the right views when navigation options are clicked. How To Do This? The first thing you should do is adding a new div tag in inbox.html with an id property. To solve this, look at the function compose_email. You are going to find 3 lines, which the first is the following comment: // Show compose view and hide other views The other 2 lines are the ones that you have to understand. When you use document.querySelector(‘#id’).style.display you are using JavaScript to set if you want to hide or not the components in that id attribute. 8 Checklist – Mail (Project 3) When you set this to ‘none’, you are hiding the components in the HTML of that id attribute. When you set this to ‘block’, you are showing the components in the HTML of that id attribute. Specification See the hint in the Hints section about how to add an event listener to an HTML element that you’ve added to the DOM. How To Do This? In the function that you just created to render in each email its own box, you should use the addEventListener function to be triggered when the user clicks in the email box. Specification Once the email has been clicked on, you should mark the email as read. Recall that you can send a PUT request to /emails/<email_id> to update whether an email is read or not. How To Do This? We recommend creating a new function to mark the email as read. If you take a look at the API in the Mail Project explanation, you are going to find a section called “PUT/emails/<int:email_id>”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. Instead of using ‘archived: true’ in the example that they gave to us, you should use ‘read: true’. 9 Checklist – Mail (Project 3) You are going to have to call this function in the display email function. Remember that you only can set if the email was read or not if you are in the inbox or archive mailbox. At this point your project should look like this: Archive and Unarchive Specification Allow users to archive and unarchive emails that they have received. How To Do This? You should create a new function to solve this issue. Basically, you are going to use the addEventListener to trigger the fetch call after clicking the submit button. In the next bullet points we explain better. Specification When viewing an Inbox email, the user should be presented with a button that lets them archive the email. When viewing an Archive email, the user should be presented with a button that lets them unarchive the email. This requirement does not apply to emails in the Sent mailbox. How To Do This? To solve that you should create a button in your display email function. This button will represent the archive/unarchive. 10 Checklist – Mail (Project 3) Since this requirement does not apply to emails in the Sent mailbox, you are going to call the function that handle with showing the archive button. The same way as you did before for the mark email as read. Specification Recall that you can send a PUT request to /emails/<email_id> to mark an email as archived or unarchived. How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “PUT/emails/<int:email_id>”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. Specification Once an email has been archived or unarchived, load the user’s inbox. How To Do This? After doing the fetch call, remember to call the load_mailbox function to redirect the user to the inbox. We recommend you use the window.location.reload() after redirecting the user to the inbox. Reply Specification Allow users to reply to an email. When viewing an email, the user should be presented with a “Reply” button that lets them reply to the email. 11 Checklist – Mail (Project 3) How To Do This? You can do this by adding a <button> tag in the inbox.html. Specification When the user clicks the “Reply” button, they should be taken to the email composition form. How To Do This? In the function that you created the display email, you are going to use the addEventListener to trigger the compose_email function after clicking the submit button. In the next bullet points we explain better. Basically, the compose_email function just handle with the situation that you are creating a new email to someone. Since this case is a reply, you should create a new function. After creating this function, you should go to compose_email and create an ifelse condition. This will make your compose_email be used in the reply button and in the compose mailbox. Specification Pre-fill the composition form with the recipient field set to whoever sent the original email. How To Do This? You can pre-fill the composition form by grabbing the current email’s properties by the values that you are passing as input in this function. For example, to grab the recipient you can do ‘email.sender’ and store this value in a variable. After that, you can use document.querySelector(‘#compose-recipients’).value and set this value as the same of the variables. 12 Checklist – Mail (Project 3) Specification Pre-fill the subject line. If the original email had a subject line of foo, the new subject line should be Re: foo. (If the subject line already begins with Re: , no need to add it again.) How To Do This? You can pre-fill the composition form by grabbing the current email’s properties by the values that you are passing as input in this function. For example, to grab the subject you can do ‘Re: email.subject’ and store this value in a variable. After that, you can use document.querySelector(‘#compose-subject’).value and set this value as the same of the variables. Specification Pre-fill the body of the email with a line like "On Jan 1 2020, 12:00 AM foo@example.com wrote:" followed by the original text of the email. How To Do This? You can pre-fill the composition form by grabbing the current email’s properties by the values that you are passing as input in this function. For example, to grab the body with the timestamp you can do `On ${email.timestamp} ${email.sender} wrote: ${email.body}.’ and store this value in a variable. After that, you can use document.querySelector(‘#compose-body’).value and set this value as the same of the variables. At this point your project should look like this: 13 Checklist – Mail (Project 3) CSS Specification You have to create your own style for this project. How To Do This? We recommend you use CSS and Bootstrap tools. For example, to create the boxes separating each email, you can use padding and border properties. For example, to make the buttons look nice, you can use the Bootstrap buttons. FAQs Specification How To Do This? If your Javascript changes aren't being reflected in your site, check: https://stackoverflow.com/questions/8392441/stop-chrome-caching-my-js-files 14 Checklist – Mail (Project 3) Specification How To Do This? This issue happens in the function that handles with submitting the email. You are going to notice that if you try to send an email your page is not going to be redirected to Sent mailbox, but to inbox instead. How to solve this? You should use the preventDefault function because this function will prevent the default of submit to be refreshing the button. Specification How To Do This? Replace line number 26 in mail/models.py with: "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), This error is caused because strftime function implementation depends on your operating system. If you are Mac and Linux user, you will not have this problem. If you are windows user, you should change the line 26 in models.py to the following line. "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"), 15 Checklist – Mail (Project 3) Specification How To Do This? When you are testing the ‘send email’ code, remember that you must send an email to someone that is already registered in your backend. Do not forget to create two users in the webapp and then send email to each other. Specification How To Do This? You should listen for an click or submit event on the submit button of the form (#send) rather than form submission. Also remember to use the preventDefault() to prevent form submission. 16 CodingBat Warmup 1 - Python Questions sleep_in The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. sleep_in(False, False) → True sleep_in(True, False) → False sleep_in(False, True) → True monkey_trouble We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble. monkey_trouble(True, True) → True monkey_trouble(False, False) → True monkey_trouble(True, False) → False sum_double Given two int values, return their sum. Unless the two values are the same, then return double their sum. sum_double(1, 2) → 3 sum_double(3, 2) → 5 sum_double(2, 2) → 8 2 CodingBat Warmup 1 - Python diff21 Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. diff21(19) → 2 diff21(10) → 11 diff21(21) → 0 parrot_trouble We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble. parrot_trouble(True, 6) → True parrot_trouble(True, 7) → False parrot_trouble(False, 6) → False makes10 Given 2 ints, a and b, return True if one if them is 10 or if their sum is 10. makes10(9, 10) → True makes10(9, 9) → False makes10(1, 9) → True near_hundred Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number. 3 CodingBat Warmup 1 - Python near_hundred(93) → True near_hundred(90) → True near_hundred(89) → False pos_neg Given 2 int values, return True if one is negative and one is positive. Except if the parameter "negative" is True, then return True only if both are negative. pos_neg(1, -1, False) → True pos_neg(-1, 1, False) → True pos_neg(-4, -5, True) → True not_string Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. not_string('candy') → 'not candy' not_string('x') → 'not x' not_string('not bad') → 'not bad' missing_char Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..len(str)-1 inclusive). missing_char('kitten', 1) → 'ktten' missing_char('kitten', 0) → 'itten' missing_char('kitten', 4) → 'kittn' 4 CodingBat Warmup 1 - Python front_back Given a string, return a new string where the first and last chars have been exchanged. front_back('code') → 'eodc' front_back('a') → 'a' front_back('ab') → 'ba' front3 Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. front3('Java') → 'JavJavJav' front3('Chocolate') → 'ChoChoCho' front3('abc') → 'abcabcabc' 5 CodingBat Warmup 1 - Python Solutions sleep_in def sleep_in(weekday,vacation): if not weekday or vacation: return True else: return False monkey_trouble def monkey_trouble(a_smile,b_smile): if a_smile and b_smile: return True if not a_smile and not b_smile: return False sum_double def sum_double(a,b): if a == b: return 2 * (a + b) else: return a + b diff21 def diff21(n): 6 CodingBat Warmup 1 - Python if n > 21: return 2 * abs(n - 21) else: return abs(n - 21) parrot_trouble def parrot_trouble(talking,hour): if talking and (hour < 7 or hour > 20): return True else: return False makes10 def makes10(a,b): if (a + b == 10) or a == 10 or b == 10: return True else: return False near_hundred def near_hundred(n): if abs(n - 100) <= 10 or abs(n - 200) <= 10: return True else: return False 7 CodingBat Warmup 1 - Python pos_neg def pos_neg(a,b,negative): if (a < 0 and b < 0) and negative is True: return True elif negative is True: return False elif (a > 0 and b < 0) or (a < 0 and b > 0): return True else: return False not_string def not_string(str): if len(str) >= 3 and str[:3] == “not”: return str return “not” + str missing_char def missing_char(str,n): front = str[:n] back = str[n+1:] return front + back 8 CodingBat Warmup 1 - Python front_back def front_back(str): if len(str) <= 1: return str mid = str[1: len(str)-1] return str[len(str)-1] + mid + str[0] front3 def front3(str): front_end = 3 if len(str) < front_end: front_end = len(str) front = str[:front_end] return front + front + front 9 CodingBat Warmup 2 - Python Questions string_times Given a string and a non-negative int n, return a larger string that is n copies of the original string. string_times('Hi', 2) → 'HiHi' string_times('Hi', 3) → 'HiHiHi' string_times('Hi', 1) → 'Hi' front_times Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front; front_times('Chocolate', 2) → 'ChoCho' front_times('Chocolate', 3) → 'ChoChoCho' front_times('Abc', 3) → 'AbcAbcAbc' string_bits Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". string_bits('Hello') → 'Hlo' string_bits('Hi') → 'H' string_bits('Heeololeo') → 'Hello' 2 CodingBat Warmup 2 - Python string_splosion Given a non-empty string like "Code" return a string like "CCoCodCode". string_splosion('Code') → 'CCoCodCode' string_splosion('abc') → 'aababc' string_splosion('ab') → 'aab' last2 Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring). last2('hixxhi') → 1 last2('xaxxaxaxx') → 1 last2('axxxaaxx') → 2 array_count9 Given an array of ints, return the number of 9's in the array. array_count9([1, 2, 9]) → 1 array_count9([1, 9, 9]) → 2 array_count9([1, 9, 9, 3, 9]) → 3 3 CodingBat Warmup 2 - Python array_front9 Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4. array_front9([1, 2, 9, 3, 4]) → True array_front9([1, 2, 3, 4, 9]) → False array_front9([1, 2, 3, 4, 5]) → False array123 Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere. array123([1, 1, 2, 3, 1]) → True array123([1, 1, 2, 4, 1]) → False array123([1, 1, 2, 1, 2, 3]) → True string_match Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. string_match('xxcaazz', 'xxbaaz') → 3 string_match('abc', 'abc') → 2 string_match('abc', 'axc') → 0 4 CodingBat Warmup 2 - Python Solutions string_times def string_times(str,n): return n * str front_times def front_times(str,n): if len(str) < 3: return n * str else: return n * str[0:3] string_bits def string_bits(str): word = “” for i in range(len(str)): if i % 2 == 0: word += str[i:i+1] return word string_splosion def string_splosion(str): word = “” for i in range(1, len(str)+1): word += str[0:i] return word 5 CodingBat Warmup 2 - Python last2 def last2(str): word = “” count = 0 for i in range(len(str)-2): if str[i:i+2] == word count += 1 return count array_count9 def array_count9(nums): count = 0 for i in nums: if i == 9: return count array_front9 def array_front9(nums): end = len(nums) if end > 4: end = 4 for i in range(end): if nums[i] == 9: return True return False 6 CodingBat Warmup 2 - Python array123 def array123(nums): for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3: return True return False string_match def string_match(a,b): count = 0 for i in range(len(a)-1): if a[i:i+2] == b[i:i+2]: count += 1 return count 7 CodingBat String 1 - Python Questions hello_name Given a string name, e.g. "Bob", return a greeting of the form "Hello Bob!". hello_name('Bob') → 'Hello Bob!' hello_name('Alice') → 'Hello Alice!' hello_name('X') → 'Hello X!' make_abba Given two strings, a and b, return the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi". make_abba('Hi', 'Bye') → 'HiByeByeHi' make_abba('Yo', 'Alice') → 'YoAliceAliceYo' make_abba('What', 'Up') → 'WhatUpUpWhat' make_tags The web is built with HTML strings like "<i>Yay</i>" which draws Yay as italic text. In this example, the "i" tag makes <i> and </i> which surround the word "Yay". Given tag and word strings, create the HTML string with tags around the word, e.g. "<i>Yay</i>". make_tags('i', 'Yay') → '<i>Yay</i>' make_tags('i', 'Hello') → '<i>Hello</i>' make_tags('cite', 'Yay') → '<cite>Yay</cite>' 2 CodingBat String 1 - Python make_out_word Given an "out" string length 4, such as "<<>>", and a word, return a new string where the word is in the middle of the out string, e.g. "<<word>>". make_out_word('<<>>', 'Yay') → '<<Yay>>' make_out_word('<<>>', 'WooHoo') → '<<WooHoo>>' make_out_word('[[]]', 'word') → '[[word]]' extra_end Given a string, return a new string made of 3 copies of the last 2 chars of the original string. The string length will be at least 2. extra_end('Hello') → 'lololo' extra_end('ab') → 'ababab' extra_end('Hi') → 'HiHiHi' first_two Given a string, return the string made of its first two chars, so the String "Hello" yields "He". If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "". first_two('Hello') → 'He' first_two('abcdefg') → 'ab' first_two('ab') → 'ab' 3 CodingBat String 1 - Python first_half Given a string of even length, return the first half. So the string "WooHoo" yields "Woo". first_half('WooHoo') → 'Woo' first_half('HelloThere') → 'Hello' first_half('abcdef') → 'abc' without_end Given a string, return a version without the first and last char, so "Hello" yields "ell". The string length will be at least 2. without_end('Hello') → 'ell' without_end('java') → 'av' without_end('coding') → 'odin' combo_string Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length 0). combo_string('Hello', 'hi') → 'hiHellohi' combo_string('hi', 'Hello') → 'hiHellohi' combo_string('aaa', 'b') → 'baaab' 4 CodingBat String 1 - Python non_start Given 2 strings, return their concatenation, except omit the first char of each. The strings will be at least length 1. non_start('Hello', 'There') → 'ellohere' non_start('java', 'code') → 'avaode' non_start('shotl', 'java') → 'hotlava' left2 Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string length will be at least 2. left2('Hello') → 'lloHe' left2('java') → 'vaja' left2('Hi') → 'Hi' 5 CodingBat String 1 - Python Solutions hello_name def hello_name(name): word = “Hello” word = word + name + “!” return word make_abba def make_abba(a,b): return a + b + b + a make_tags def make_tags(tag,word): word1 = “<” + tag + “>” word2 = word word3 = “</” + tag + “/>” finalW = word1 + word2 + word3 return finalW make_out_word def make_out_word(out,word): size = len(out)//2 pal = out[0:size] + word + out[size:] return pal 6 CodingBat String 1 - Python extra_end def extra_end(str): syl = len(str) - 2 word =3 * str[syl:] return word first_two def first_two(str): if len(str) < 2: return str else: return str[0:2] first_half def first_half(str): size = len(str) / 2 word = “” word = str[0:size] return word without_end def without_end(str): word = str[1:len(str)-1] return word 7 CodingBat String 1 - Python combo_string def combo_string(str): if len(a) > len(b): long = a short = b else: long = b short = a word = short + long + short return word non_start def non_start(a,b): word1 = a[1: ] word1 = b[1: ] fWord = word1 + word2 return fWord left2 def left2(str): syl = str[0:2] word = str[2: ] + syl return fWord 8 CodingBat String 2 - Python Questions double_char Given a string, return a string where for every char in the original, there are two chars. double_char('The') → 'TThhee' double_char('AAbb') → 'AAAAbbbb' double_char('Hi-There') → 'HHii--TThheerree' count_hi Return the number of times that the string "hi" appears anywhere in the given string. count_hi('abc hi ho') → 1 count_hi('ABChi hi') → 2 count_hi('hihi') → 2 cat_dog Return True if the string "cat" and "dog" appear the same number of times in the given string. cat_dog('catdog') → True cat_dog('catcat') → False cat_dog('1cat1cadodog') → True count_code 2 CodingBat String 2 - Python Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count. count_code('aaacodebbb') → 1 count_code('codexxcode') → 2 count_code('cozexxcope') → 2 end_other Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive"). Note: s.lower() returns the lowercase version of a string. end_other('Hiabc', 'abc') → True end_other('AbC', 'HiaBc') → True end_other('abc', 'abXabc') → True xyz_there Return True if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not. xyz_there('abcxyz') → True xyz_there('abc.xyz') → False xyz_there('xyz.abc') → True Solutions 3 CodingBat String 2 - Python double_char def double_char(str): word = "" for i in str: word += i + i return word count_hi def count_hi(str): count = 0 for i in range(len(str)-1): if str[i:i+2] == "hi": count+=1 return count cat_dog def cat_dog(str): countCat = 0 countDog = 0 for i in range(len(str)-2): if(str[i:i+3] =="cat"): countCat+=1 if(str[i:i+3] =="dog"): countDog+=1 return (countCat == countDog) count_code 4 CodingBat String 2 - Python def count_code(str): count = 0 if(len(str)<4): return 0 else: for i in range(len(str)-3): if(str[i:i+1] == "c" and str[i+1:i+2] == "o" and str[i+3:i+4] == "e"): count+=1 return count end_other def end_other(a, b): word1 = a.lower() word2 = b.lower() if(len(word1)<len(word2)): small = word1 big = word2 else: small = word2 big = word1 if(big[len(big)-len(small):] == small): return True else: return False xyz_there 5 CodingBat String 2 - Python def xyz_there(str): word = "xyz" for i in range(len(str)-2): if (str[i:i+3] == word and str[i-1:i] != "."): return True return False 6 CodingBat List 1 - Python Questions first_last6 Given an array of ints, return True if 6 appears as either the first or last element in the array. The array will be length 1 or more. first_last6([1, 2, 6]) → True first_last6([6, 1, 2, 3]) → True first_last6([13, 6, 1, 2, 3]) → False same_first_last Given an array of ints, return True if the array is length 1 or more, and the first element and the last element are equal. same_first_last([1, 2, 3]) → False same_first_last([1, 2, 3, 1]) → True same_first_last([1, 2, 1]) → True make_pi Return an int array length 3 containing the first 3 digits of pi, {3, 1, 4}. make_pi() → [3, 1, 4] common_end Given 2 arrays of ints, a and b, return True if they have the same first element or they have the same last element. Both arrays will be length 1 or more. common_end([1, 2, 3], [7, 3]) → True common_end([1, 2, 3], [7, 3, 2]) → False common_end([1, 2, 3], [1, 3]) → True 2 CodingBat List 1 - Python sum3 Given an array of ints length 3, return the sum of all the elements. sum3([1, 2, 3]) → 6 sum3([5, 11, 2]) → 18 sum3([7, 0, 0]) → 7 rotate_left3 Given an array of ints length 3, return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}. rotate_left3([1, 2, 3]) → [2, 3, 1] rotate_left3([5, 11, 9]) → [11, 9, 5] rotate_left3([7, 0, 0]) → [0, 0, 7] reverse3 Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}. reverse3([1, 2, 3]) → [3, 2, 1] reverse3([5, 11, 9]) → [9, 11, 5] reverse3([7, 0, 0]) → [0, 0, 7] 3 CodingBat List 1 - Python max_end3 Given an array of ints length 3, figure out which is larger, the first or last element in the array, and set all the other elements to be that value. Return the changed array. max_end3([1, 2, 3]) → [3, 3, 3] max_end3([11, 5, 9]) → [11, 11, 11] max_end3([2, 11, 3]) → [3, 3, 3] sum2 Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0. sum2([1, 2, 3]) → 3 sum2([1, 1]) → 2 sum2([1, 1, 1, 1]) → 2 middle_way Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their middle elements. middle_way([1, 2, 3], [4, 5, 6]) → [2, 5] middle_way([7, 7, 7], [3, 8, 0]) → [7, 8] middle_way([5, 2, 9], [1, 4, 5]) → [2, 4] 4 CodingBat List 1 - Python make_ends Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more. make_ends([1, 2, 3]) → [1, 3] make_ends([1, 2, 3, 4]) → [1, 4] make_ends([7, 4, 6, 2]) → [7, 2] has23 Given an int array length 2, return True if it contains a 2 or a 3. has23([2, 5]) → True has23([4, 3]) → True has23([4, 5]) → False 5 CodingBat List 1 - Python Solutions first_last6 def first_last6(nums): if nums[0] == 6 or nums[len(nums)-1] == 6: return True else: return False same_first_last def same_first_last(nums): if len(nums) >= 1 and nums[0] == nums[-1]: return True else: return False make_pi def make_pi(): return [3,1,4] common_end def common_end(a,b): if a[0] == b[0] or a[len(a) - 1] == b[len(b) - 1]: return True else: return False 6 CodingBat List 1 - Python sum3 def sum3(nums): return nums[0] + nums[1] + nums[2] rotate_left3 def rotate_left3(nums): return [nums[1], nums[len(nums)-1], nums[0]] reverse3 def reverse3(nums): return [nums[len(nums)-1], nums[1], nums[0]] max_end3 def max_end3(nums): if nums[0] > nums[-1]: return [nums[0], nums[0], nums[0]] else: return [nums[-1], nums[-1], nums[-1]] sum2 def sum2(nums): if len(nums) == 0: return 0 elif len(nums) < 2: return nums[0] else: return nums[0] + nums[1] 7 CodingBat List 1 - Python middle_way def middle_way(a,b): return [a[1], b[1]] make_ends def make_ends(nums): return [nums[0], nums[len(nums)-1]] has23 def has23(a,b): if (nums[0] == 2 or nums[1] == 2) or (nums[0] == 3 or nums[1] == 3): return True else: return False 8 CodingBat Lists 2 - Python Questions count_evens Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1. count_evens([2, 1, 2, 3, 4]) → 3 count_evens([2, 2, 0]) → 3 count_evens([1, 3, 5]) → 0 big_diff Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in min(v1, v2) and max(v1, v2) functions return the smaller or larger of two values. big_diff([10, 3, 5, 6]) → 7 big_diff([7, 2, 10, 9]) → 8 big_diff([2, 10, 7, 2]) → 8 centered_average Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more. centered_average([1, 2, 3, 4, 100]) → 3 centered_average([1, 1, 5, 5, 10, 8, 7]) → 5 centered_average([-10, -4, -2, -4, -2, 0]) → -3 sum13 2 CodingBat Lists 2 - Python Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count. sum13([1, 2, 2, 1]) → 6 sum13([1, 1]) → 2 sum13([1, 2, 2, 1, 13]) → 6 sum67 Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers. sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4 has22 Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False 3 CodingBat Lists 2 - Python Solutions count_evens def count_evens(nums): count = 0 for i in range(len(nums)): if nums[i] % 2 == 0: count += 1 return count bid_diff def big_diff(nums): return max(nums) - min(nums) centered_average def centered_average(nums): nums.sort() count = 0 total = 0 for i in range(1, len(nums) - 1): count += 1 total += nums[i] return total / count 4 CodingBat Lists 2 - Python sum13 def sum13(nums): total = 0 skip = False if len(nums) == 0: return 0 else: for i in range(len(nums)): if nums[i] == 13: skip = True elif skip: skip = False else: total += nums[i] return total sum67 def sum67(nums): total = 0 skip = False for i in range(len(nums)): if nums[i] == 6: skip = True elif nums[i] == 7 and skip: skip = False 5 CodingBat Lists 2 - Python elif not skip: total += nums[i] return total has22 def has22(nums): has2 = False for i in range(len(nums)): if has2 and nums[i] == 2: return True elif nums[i] == 2: has2 = True else: has2 = False return False 6 CodingBat Logic 1 - Python Questions cigar_party When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise. cigar_party(30, False) → False cigar_party(50, False) → True cigar_party(70, True) → True date_fashion You and your date are trying to get a table at a restaurant. The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise, the result is 1 (maybe). date_fashion(5, 10) → 2 date_fashion(5, 2) → 0 date_fashion(5, 5) → 1 squirrel_play 2 CodingBat Logic 1 - Python The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise. squirrel_play(70, False) → True squirrel_play(95, False) → False squirrel_play(95, True) → True caught_speeding You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. caught_speeding(60, False) → 0 caught_speeding(65, False) → 1 caught_speeding(65, True) → 0 sorta_sum Given 2 ints, a and b, return their sum. However, sums in the range 10..19 inclusive, are forbidden, so in that case just return 20. sorta_sum(3, 4) → 7 sorta_sum(9, 4) → 20 sorta_sum(10, 11) → 21 alarm_clock 3 CodingBat Logic 1 - Python Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off". alarm_clock(1, False) → '7:00' alarm_clock(5, False) → '7:00' alarm_clock(0, False) → '10:00' love6 The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number. love6(6, 4) → True love6(4, 5) → False love6(1, 5) → True in1to10 Given a number n, return True if n is in the range 1..10, inclusive. Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10. in1to10(5, False) → True in1to10(11, False) → False in1to10(11, True) → True near_ten 4 CodingBat Logic 1 - Python Given a non-negative number "num", return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. near_ten(12) → True near_ten(17) → False near_ten(19) → True Solutions 5 CodingBat Logic 1 - Python cigar_party def cigar_party(cigars, is_weekend): if is_weekend == True: return cigars >= 40 else: return cigars >= 40 and cigars <= 60 date_fashion def date_fashion(you, date): if you <= 2 or date <= 2: return 0 elif you >= 8 or date >= 8: return 2 else: return 1 squirrel_play def squirrel_play(temp, is_summer): if temp >= 60: if is_summer: if temp <= 100: return True else: return False else: 6 CodingBat Logic 1 - Python if temp <= 90: return True else: return False else: return False caught_speeding def caught_speeding(speed, is_birthday): if is_birthday: speed -= 5 if speed <= 60: return 0 return 1 if 61 <= speed <= 80 else 2 sorta_sum def sorta_sum(a, b): sum = a + b if 10 <= sum <= 19: return 20 else: return sum alarm_clock 7 CodingBat Logic 1 - Python def alarm_clock(day, vacation): week_day = day not in (0, 6) if vacation: if week_day: return '10:00' else: return 'off' else: if week_day: return '7:00' else: return '10:00' love6 def love6(a, b): if (a == 6 or b == 6 or (a+b) == 6 or abs(a-b) == 6): return True else: return False in1to10 def in1to10(n, outside_mode): if outside_mode: return n <= 1 or n >= 10 return 1 <= n <= 10 near_ten 8 CodingBat Logic 1 - Python def near_ten(num): num_mod_10 = num % 10 return num_mod_10 <= 2 or num_mod_10 >= 8 9 CodingBat Logic 2 - Python Questions make_bricks We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. make_bricks(3, 1, 8) → True make_bricks(3, 1, 9) → False make_bricks(3, 2, 10) → True lone_sum Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values, it does not count towards the sum. lone_sum(1, 2, 3) → 6 lone_sum(3, 2, 3) → 2 lone_sum(3, 3, 3) → 0 lucky_sum Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count. lucky_sum(1, 2, 3) → 6 lucky_sum(1, 2, 13) → 3 lucky_sum(1, 13, 3) → 1 2 CodingBat Logic 2 - Python no_teen_sum Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). Define the helper below and at the same indent level as the main no_teen_sum(). no_teen_sum(1, 2, 3) → 6 no_teen_sum(2, 13, 1) → 3 no_teen_sum(2, 1, 14) → 3 round_sum For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum(). round_sum(16, 17, 18) → 60 round_sum(12, 13, 14) → 30 round_sum(6, 4, 4) → 10 3 CodingBat Logic 2 - Python close_far Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number. close_far(1, 2, 10) → True close_far(1, 2, 3) → False close_far(4, 1, 3) → True make_chocolate We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done. make_chocolate(4, 1, 9) → 4 make_chocolate(4, 1, 10) → -1 make_chocolate(4, 1, 7) → 2 4 CodingBat Logic 2 - Python Solutions make_bricks def make_bricks(small, big, goal): big_needed = min(big, goal // 5) return goal - (big_needed * 5) <= small lone_sum def lone_sum(a, b, c): sum = 0 if a not in [b,c]: sum += a if b not in [a,c]: sum += b if c not in [a,b]: sum += c return sum lucky_sum def lucky_sum(a, b, c): sum = 0 for n in (a, b, c): if n != 13: sum += n else: break return sum 5 CodingBat Logic 2 - Python no_teen_sum def no_teen_sum(a, b, c): nums = (a, b, c) sum = 0 for i in range(len(nums)): sum += fix_teen(nums[i]) return sum def fix_teen(n): if n != 15 and n!= 16 and 13 <= n <= 19: return 0 else: return n round_sum def round_sum(a, b, c): return round10(a)+round10(b)+round10(c) def round10(num): return (num+5)/10*10 6 CodingBat Logic 2 - Python close_far def close_far(a, b, c): ab_diff = abs(a - b) ac_diff = abs(a - c) bc_diff = abs(b - c) if (ab_diff <= 1 and ac_diff >= 2 and bc_diff >= 2) != (ac_diff <= 1 and ab_diff >= 2 and bc_diff >= 2): return True else: return False make_chocolate def make_chocolate(small, big, goal): if goal >= 5 * big: remainder = goal - 5 * big else: remainder = goal % 5 if remainder <= small: return remainder return -1 7 SQL Boat Questions Lesson 1: SELECT queries 101 1. 2. 3. 4. 5. Find the title of each film Find the director of each film Find the title and director of each film Find the title and year of each film Find all the information about each film Lesson 2: Queries with constraints (Pt. 1) 1. 2. 3. 4. Find the movie with a row id of 6 Find the movies released in the years between 2000 and 2010 Find the movies not released in the years between 2000 and 2010 Find the first 5 Pixar movies and their release year Lesson 3: Queries with constraints (Pt. 2) 1. 2. 3. 4. Find all the Toy Story movies Find all the movies directed by John Lasseter Find all the movies (and director) not directed by John Lasseter Find all the WALL-* movies Lesson 4: Filtering and sorting Query results 1. 2. 3. 4. List all directors of Pixar movies (alphabetically), without duplicates List the last four Pixar movies released (ordered from most recent to least) List the first five Pixar movies sorted alphabetically List the next five Pixar movies sorted alphabetically Review: Simple SELECT Queries 1. 2. 3. 4. 5. List all the Canadian cities and their populations Order all the cities in the United States by their latitude from north to south List all the cities west of Chicago, ordered from west to east List the two largest cities in Mexico (by population) List the third and fourth largest cities (by population) in the United States and their population 2 SQL Boat Lesson 6: Multi-table queries with JOINs 1. Find the domestic and international sales for each movie 2. Show the sales numbers for each movie that did better internationally rather than domestically 3. List all the movies by their ratings in descending order Lesson 7: OUTER JOINs 1. Find the list of all buildings that have employees 2. Find the list of all buildings and their capacity 3. List all buildings and the distinct employee roles in each building (including empty buildings) Lesson 8: A short note on NULLs 1. Find the name and role of all employees who have not been assigned to a building 2. Find the names of the buildings that hold no employees Lesson 9: Queries with expressions 1. List all movies and their combined sales in millions of dollars 2. List all movies and their ratings in percent 3. List all movies that were released on even number years Lesson 10: Queries with aggregates (Pt. 1) 1. Find the longest time that an employee has been at the studio 2. For each role, find the average number of years employed by employees in that role 3. Find the total number of employee years worked in each building Lesson 11: Queries with aggregates (Pt. 2) 1. Find the number of Artists in the studio (without a HAVING clause) 2. Find the number of Employees of each role in the studio 3. Find the total number of years employed by all Engineers 3 SQL Boat Lesson 12: Order of execution of a Query 1. Find the number of movies each director has directed 2. Find the total domestic and international sales that can be attributed to each director Lesson 13: Inserting rows 1. Add the studio's new production, Toy Story 4 to the list of movies (you can use any director) 2. Toy Story 4 has been released to critical acclaim! It had a rating of 8.7, and made 340 million domestically and 270 million internationally. Add the record to the BoxOffice table. Lesson 14: Updating rows 1. The director for A Bug's Life is incorrect, it was actually directed by John Lasseter 2. The year that Toy Story 2 was released is incorrect, it was actually released in 1999 3. Both the title and director for Toy Story 8 is incorrect! The title should be "Toy Story 3" and it was directed by Lee Unkrich Lesson 15: Deleting rows 1. This database is getting too big, lets remove all movies that were released before 2005. 2. Andrew Stanton has also left the studio, so please remove all movies directed by him. Lesson 16: Creating tables Create a new table named Database with the following columns: – Name A string (text) describing the name of the database – Version A number (floating point) of the latest version of this database – Download_count An integer count of the number of times this database was downloaded 4 SQL Boat Lesson 17: Altering tables 1. Add a column named Aspect_ratio with a FLOAT data type to store the aspectratio each movie was released in. 2. Add another column named Language with a TEXT data type to store the language that the movie was released in. Ensure that the default for this language is English. Lesson 18: Dropping tables 1. We've sadly reached the end of our lessons, lets clean up by removing the Movies table 2. And drop the BoxOffice table as well 5 SQL Boat Solutions Lesson 1: SELECT queries 101 1. SELECT title FROM movies; 2. SELECT director FROM movies; 3. SELECT title, director FROM movies; 4. SELECT title, year FROM movies; 5. SELECT * FROM movies; Lesson 2: Queries with constraints (Pt. 1) 1. SELECT * FROM movies WHERE id = 6; 2. SELECT * FROM movies WHERE year BETWEEN 2000 and 2010; 6 SQL Boat 3. SELECT * FROM movies WHERE year NOT BETWEEN 2000 and 2010; 4. SELECT * FROM movies WHERE id BETWEEN 1 AND 5; Lesson 3: Queries with constraints (Pt. 2) 1. SELECT * FROM movies WHERE title LIKE "%Toy Story%"; 2. SELECT * FROM movies WHERE director = "John Lasseter"; 3. SELECT * FROM movies WHERE director != "John Lasseter"; 4. SELECT * FROM movies WHERE title LIKE "WALL-%"; 7 SQL Boat Lesson 4: Filtering and sorting Query results 1. SELECT DISTINCT director FROM movies ORDER BY director ASC; 2. SELECT * FROM movies ORDER BY year DESC LIMIT 4; 3. SELECT * FROM movies ORDER BY title ASC LIMIT 5; 4. SELECT * FROM movies ORDER BY title ASC LIMIT 5 OFFSET 5; Lesson 5 Review: Simple SELECT Queries 1. SELECT country, population FROM north_american_cities WHERE country = "Canada"; 8 SQL Boat 2. SELECT city FROM north_american_cities WHERE country = "United States" ORDER BY latitude DESC; 3. SELECT city FROM north_american_cities WHERE longitude < ( SELECT longitude FROM north_american_cities WHERE city = "Chicago" ) ORDER BY longitude ASC; 4. SELECT city FROM north_american_cities WHERE country = "Mexico" ORDER BY population DESC LIMIT 2; 5. SELECT city, population FROM north_american_cities WHERE country = "United States" ORDER BY population DESC LIMIT 2 OFFSET 2; 9 SQL Boat Lesson 6: Multi-table queries with JOINs 1. SELECT title, domestic_sales, international_sales FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id; 2. SELECT * FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id WHERE international_sales > domestic_sales; 3. SELECT title, rating FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id ORDER BY rating DESC; Lesson 7: OUTER JOINs 1. SELECT DISTINCT building_name FROM buildings LEFT JOIN employees ON buildings.building_name = employees.building WHERE building IS NOT NULL; 10 SQL Boat 2. SELECT * FROM buildings; 3. SELECT DISTINCT building_name, role FROM buildings LEFT JOIN employees ON buildings.building_name = employees.building; Lesson 8: A short note on NULLs 1. SELECT * FROM employees LEFT JOIN buildings ON employees.building = buildings.building_name WHERE building_name IS NULL; 2. SELECT * FROM buildings LEFT JOIN employees ON buildings.building_name = employees.building WHERE role IS NULL; 11 SQL Boat Lesson 9: Queries with expressions 1. SELECT title, (domestic_sales + international_sales)/1000000 AS sales FROM boxoffice AS b INNER JOIN movies AS m ON m.id = b.movie_id; 2. SELECT title, rating*10 AS ratings_percent FROM boxoffice AS b INNER JOIN movies AS m ON m.id = b.movie_id; 3. SELECT title, year FROM boxoffice AS b INNER JOIN movies AS m ON m.id = b.movie_id WHERE year % 2 = 0 ORDER BY year ASC; Lesson 10: Queries with aggregates (Pt. 1) 1. SELECT MAX(years_employed) AS longest_years FROM employees; 12 SQL Boat 2. SELECT role, AVG(years_employed)AS average_years_employed FROM employees GROUP BY role; 3. SELECT building, SUM(years_employed)AS sum_of_years_employed FROM employees GROUP BY building; Lesson 11: Queries with aggregates (Pt. 2) 1. SELECT COUNT(role) FROM employees WHERE role = 'Artist'; 2. SELECT role, COUNT(name) AS number_of_employees FROM employees GROUP BY role; 13 SQL Boat 3. SELECT role, SUM(years_employed) FROM employees GROUP BY role HAVING role = "Engineer"; Lesson 12: Order of execution of a Query 1. SELECT director, COUNT(*) FROM movies GROUP BY director; 1. SELECT director, SUM(domestic_sales + international_sales) AS total_sales FROM movies INNER JOIN boxoffice ON movies.id = boxoffice.movie_id GROUP BY director; Lesson 13: Inserting rows 1. INSERT INTO movies (title, director, year, length_minutes) VALUES ('Toy Story 4', 'Lance Lafontaine', 2984, 15); 14 SQL Boat 2. INSERT INTO boxoffice (movie_id, rating, domestic_sales, international_sales) VALUES (15, 8.7, 340000000, 270000000); Lesson 14: Updating rows 1. UPDATE movies SET director = "John Lasseter" WHERE title = "A Bug's Life"; 2. UPDATE movies SET title = 'Toy Story 3', director = 'Lee Unkrich' WHERE id = ( SELECT id FROM movies WHERE title = 'Toy Story 8' ); Lesson 15: Deleting rows 1. DELETE FROM movies WHERE year < 2005; 2. DELETE FROM movies WHERE director = 'Andrew Stanton'; 15 SQL Boat Lesson 16: Creating tables CREATE TABLE IF NOT EXISTS Database ( Name TEXT, Version FLOAT, Download_count INTEGER ); Lesson 17: Altering tables 1. ALTER TABLE movies ADD aspect_ratio FLOAT; 2. ALTER TABLE movies ADD language TEXT DEFAULT 'English'; Lesson 18: Dropping tables 1. DROP TABLE IF EXISTS movies; 2. DROP TABLE IF EXISTS boxoffice; 16 Build Your First Project - Javascript styles.css h1{ text-align: center; color: #FFD700; margin-top: 50px; } index.html <!DOCTYPE html> <html lang="en"> <head> <script src="index.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link href="styles.css" rel="stylesheet"> <title>First Project</title> </head> <body> <div class="d-flex justify-content-center" style="margin-top:50px"> <button id="hello" class="btn btn-warning">Welcome!</button> <button id="red" class="btn btn-danger">Red</button> <button id="green" class="btn btn-success">Green</button> <button id="blue" class="btn btn-primary">Blue</button> </div> <h1></h1> </body> </html> 2 Build Your First Project - Javascript index.js document.addEventListener('DOMContentLoaded', function(){ //Get the parameters in HTML let sayhello = document.querySelector('h1'); let body = document.querySelector('body'); //Send a "Hello" message when click the button document.querySelector('#hello').onclick = function() { sayhello.innerHTML = 'Hello, you!'; body.style.backgroundColor = 'white'; }; //Change the background color to red when click the button document.querySelector('#red').onclick = function() { body.style.backgroundColor = 'red'; sayhello.innerHTML = ''; }; //Change the background color to green when click the button document.querySelector('#green').onclick = function() { body.style.backgroundColor = 'green'; sayhello.innerHTML = ''; }; //Change the background color to blue when click the button document.querySelector('#blue').onclick = function() { body.style.backgroundColor = 'blue'; sayhello.innerHTML = ''; }; }); 3 TODO - Flask application.py from flask import Flask, redirect, render_template, request app = Flask(__name__) #Create this to have a list of todos todos = [] @app.route("/") def tasks(): return render_template("tasks.html", todos=todos) @app.route("/add", methods=["GET","POST"]) def add(): #GET is a request method used by default #And is used when you want to get a page if request.method == "GET": return render_template("add.html") #POST means you're trying to send data to the server else: #Get the input from the user todo = request.form.get('task') #Add this new task to the todos list todos.append(todo) #Redirect the user to the page that has the todos return redirect("/") 2 TODO - Flask layout.html <!DOCTYPE html> <html lang="en"> <head> <title>Tasks</title> </head> <body> {% block body %} {% endblock %} </body> </html> tasks.html {% extends "layout.html" %} {% block body %} <h1>Tasks</h1> <ul> {% for todo in todos %} <li>{{ todo }}</li> {% endfor %} </ul> <a href="/add">Create a New Task!</a> {% endblock %} 3 TODO - Flask add.html {% extends "layout.html" %} {% block body %} <form action="/add" method="POST"> <input id="task" name="task" type="text" placeholder="Add New Task!"> <input id="submit" type="submit" disabled> </form> <script> document.querySelector('#task').onkeyup = function() { if (document.querySelector('#task').value === ''){ document.querySelector('#submit').disabled = true; } else{ document.querySelector('#submit').disabled = false; } } </script> {% endblock %} 4 TODO - Javascript styles.css h1{ text-align: center; color: gray; } .container-style{ margin-bottom: 50px; margin-left: 50px; margin-right: 50px; margin-top: 50px; } task.html <!DOCTYPE html> <html lang="en"> <head> <!--Defines what the title of the webpage will be--> <!--As displayed in the tab of the browser--> <title>Tasks</title> <!--Explains to the compiler where the javascript file code is--> <script src="tasks.js"></script> <!--Explains to the compiler where the css file is--> <link href="styles.css" rel="stylesheet"> <!--Explains to the compiler where the Bootstrap documentation is--> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"> </head> 2 TODO - Javascript <body> <!--Heading of the page--> <div class="container-style"> <h1>Tasks</h1> </div> <div class="container"> <!--Creates an unordered list to display the tasks--> <!--The javascript code will handle the list items--> <ul id="tasks" class="list-group"></ul> </div> <!--Creates a form to the user inputs a new task--> <div class="container-style"> <form> <!--This input field is to type the new task--> <input id="task" placeholder = "New Task" type="text" class="form-control"> <!--This input field is to create a submit button--> <input id="submit" type="submit" class="btn btn-light"> </form> </div> </body> </html> 3 TODO - Javascript tasks.js document.addEventListener('DOMContentLoaded', () => { //Select the form tag in HTML to be used later const form = document.querySelector('form'); //Select the ul tag in HTML to be used later const ul = document.querySelector('ul'); //Select the submit button in HTML to be used later const submit = document.querySelector('#submit'); //Select the task input in HTML to be used later let newtask = document.querySelector('#task'); //Default action for the submit button when you enter on the page submit.disabled = true; //Listen for input to be typed into the input field newtask.addEventListener('keyup', () => { //When there is nothing typed in the input, turns the submit button disabled if (newtask.value === '') { submit.disabled = true; } //When there is something typed in the input, turns the submit button enable else { submit.disabled = false; } }); 4 TODO - Javascript //When submit the task form.addEventListener('submit', (event) => { //Prevents the default submission of the form which involves //either reloading the current page or redirecting to a new one event.preventDefault(); //We can create HTML elements using the createElement function //Creates an list item on HTML const li = document.createElement('li'); //Add newtask value in list item li.innerHTML = newtask.value; //We can then add HTML those elements to the DOM using the append function //Append the list item to unordered list ul.append(li); //Clear the value of newtask variable and set it to empty newtask.value = ''; //Disable button when there is nothing in newtask submit.disabled = true; }); }); 5 TODO App Django 1. To start a new Django project, you must open the terminal of your computer (not VS Code terminal), and run: django-admin startproject NAME_OF_YOUR_PROJECT 2. Then, you open VS Code in the project’s folder you just created 3. In VS Code terminal you should create a new app to you project. So, run: python manage.py startapp NAME_OF_YOUR_APP 4. To check if everything is working fine, run: python manage.py runserver 5. If it displays the image above, you’re good to continue and you can close the website. 6. Go to seetings.py and add the new app in your “installed_apps”. Let’s suppose the app is called “tasks”. 7. Go to urls.py (in the same folder of your settings.py) and add the URL pattern to your app. 8. Now, inside the folder of your app (the same folder that exists the views.py file), you should create a new file called urls.py. In there, you’re going to create the URL pattern for the first route of your app. Let’s suppose we are going to create ‘index’ route. 9. After creating the URL for the route, let’s create the function for that route in your views.py. 10. Remember that in the index route you need: a) You need a list that will be global to all your code (create this list before the function index). This list will store all the tasks. b) You need to render the index.html file c) You need to pass your list from Python to HTML 11. Now it’s time to create your index.html inside the templates folder (remember to create a templates folder!) 12. Remember that in the index.html you need: a) There will be a h1 b) There will be an unordered list c) Figure out how you’re going to display all the items of your list inside the unordered list (remember the <li> tag) 13. Now let’s create our second route. First, create the URL pattern in your urls.py 14. Then, create the function for that route in your views.py 15. At this part, we will only work with the GET method, in the future we’re going to work with the POST. 16. Remember that your route right now needs: a) Check if it is a GET method b) You need to render the add.html file 17. Now it’s time to create your add.html inside the templates folder 18. Remember that your add.html file need: a) There will be a h1 b) There will be a form c) There will be two inputs: one for the task (type=”text”) and another for the button (type=”submit”) 19. Now let’s work with the POST method in add function (on views.py). Remember that you will need: a) Get the data from the form and store in a variable b) Add the new task in your tasks list c) Render the index.html file d) You need to pass your list from Python to HTML 20. Finally, include the hyperlink to add page in your index.html Checklist – Search (Project 0) Summary Pages........................................................................................................................................... 3 Query Text.................................................................................................................................. 4 Query Images............................................................................................................................ 5 Query Advanced....................................................................................................................... 6 Appearance ............................................................................................................................... 8 Lucky ........................................................................................................................................... 9 Aesthetics................................................................................................................................ 10 FAQ.............................................................................................................................................. 11 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Search (Project 0) Pages Specification Your website should have at least three pages: one for Google Search, one for Google Image Search, and one for Google Advanced Search. How To Do This? Since the project must have three pages and the distribution code already given to us index.html, you have to create two more HTML files for the Google Image Search and Google Advanced Search. Specification On the Google Search page, there should be links in the upper-right of the page to go to Image Search or Advanced Search. On each of the other two pages, there should be a link in the upper-right to go back to Google Search. How To Do This? To solve this problem, you can use the <ul> tag to create a navbar. This navbar must contain 2 nav-item (in this case you can use the <li> tag) to redirect the site to the other two pages that are not open. For example, the Google search page must have two nav-item to redirect the site to Image Search or Advanced Search, like indicated by the green arrows in the image below. The best way to do this is using the <a> tag, where the “href” is going to set the HTML file you want to redirect when the user clicks in the text. 3 Checklist – Search (Project 0) Query Text Specification On the Google Search page, the user should be able to type in a query, click “Google Search”, and be taken to the Google search results for that page. How To Do This? The code already gives to us the <form> and the action with the corresponding page that we are going find the result. We also have the two <input> tags that creates the text input and the submit button. Note that in the <input type=”text”> we have a property of name=”q” inside. The action added with this name are going to redirect the page to the corresponding result page right after the button submit is clicked. So, in this part you do not need to do anything, the project already give this to us. Specification Like Google’s own, your search bar should be centered with rounded corners. The search button should also be centered and should be beneath the search bar. How To Do This? To do this, it is recommended that you create a CSS file. You can find how to do rounded corners using the CSS tools in this link: https://www.w3schools.com/cssref/css3_pr_border-radius.asp 4 Checklist – Search (Project 0) You can find how to align the elements in the Bootstrap documentation. We suggest you to use the <input type=”submit”> inside a <div> tag to use the Bootstrap class. Look on this link: https://getbootstrap.com/docs/4.0/utilities/flex/ At this point, your project should look like this: Query Images Specification On the Google Image Search page, the user should be able to type in a query, click a search button, and be taken to the Google Image search results for that page. How To Do This? The first thing you have to do is to create a file similar to index.html, but the difference in this case will be the <a> tag, because you have to redirect to Google Search and Google Advanced Search. For the image search you must use de Developer Tools to find how to do this search. You are going to have to use an <input type=”hidden”> tag. 5 Checklist – Search (Project 0) At this point, your project should look like this: Query Advanced On the Google Advanced Search page, the user should be able to provide input for the following four fields (taken from Google’s own advanced search options). Specification Find pages with… “all these words:” How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: 6 Checklist – Search (Project 0) Specification Find pages with… “this exact word or phrase:” How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: Specification Find pages with… “any of these words:” How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: Specification Find pages with… “none of these words:” 7 Checklist – Search (Project 0) How To Do This? On Google Advanced Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: Appearance Specification Like Google’s own Advanced Search page, the four options should be stacked vertically, and all the text fields should be left aligned. How To Do This? To stack the four options vertically in the Advanced Search page, you can use one <div> tag for each input. To do all the text fields left aligned, you can add in your CSS file a class setting the margin-left size you want to have in your page. At this point your project should look like this: 8 Checklist – Search (Project 0) Specification Consistent with Google’s own CSS, the “Advanced Search” button should be blue with white text. When the “Advanced Search” button is clicked, the user should be taken to search results page for their given query. How To Do This? To do this part, you can use the Bootstrap documentation about buttons. Look on this link: https://getbootstrap.com/docs/4.0/components/buttons/ Lucky Specification Add an “I’m Feeling Lucky” button to the main Google Search page. Consistent with Google’s own behavior, clicking this link should take users directly to the first Google search result for the query, bypassing the normal results page. How To Do This? On Google Search page, you should use the <input> tag and add the name property like appears when you check the Developer Tools. The image below shows the trick: 9 Checklist – Search (Project 0) Aesthetics Specification The CSS you write should match Google’s own aesthetics as best as possible. How To Do This? We suggest you check the CSS and Bootstrap documentation. Also, use the Developer Tools to know some interesting properties to be used in your project. For example, if you want to know the margin, background and padding of the original “Google Search” button, you can use the Developer Tools to check that. . 10 Checklist – Search (Project 0) FAQ Question Answer Try searching for "CS50" on Google, then do the same on Google Images and compare the URLs. You will see the only difference between them is an additional parameter called tbm, which Google uses to know it should display the Google Images results instead of the Search results. You need to use this parameter in project0 to redirect to the correct results page. Question Answer To do this you should use margin property of CSS and align elements property, also from CSS. Check the link below: 11 Checklist – Search (Project 0) https://www.w3schools.com/css/css_align.asp Question Answer We already answer that in the Query Advanced section. Question Answer We already answer that in the Query Advanced section. 12 First you must click in the link showed in the image below to authorize CS50: Open the terminal in your VS Code and do the following commands: 1. To start your git: git init 2. To send the code in the right path on GitHub, you have to do the next command replacing branch_given_on_item_3_of_the_project with the name of the branch that the requirements give to you. For example, for Project 0 you are going to use web50/projects/2020/x/search git checkout -b branch_given_on_item_3_of_the_project 3. This command will return you the status of your git, it’s important to check if you are in the right track. You should see a message telling you about which branch you are. git status 4. This command will add all files to submit in the future. git add -A 5. This command will return you the status of your git, it’s important to check if you are in the right track. You should see all the files in green. git status 6. Commit all files and add a message inside the quotation marks git commit -am “some message you want to add” 7. This way you are going to put the files in the correct path on GitHub. Do not forget to change USERNAME in the link below to your username on GitHub. git remote add origin https://github.com/me50/USERNAME.git 8. Push your files to GitHub. After this command check your CS50.me to see if everything went fine. git push origin --all 1. Click on the third icon in your sidebar. When you are there, click on “Initialize Repository”: 2. Add all the files you want to store in your GitHub by clicking on the plus sign (+). You can click on one file at a time: Or you can add all the files at the same time: 3. Once you added the files, there will be a new section for you called “Staged Changes”. Now you can click in the check sign to commit the files: 4. You should add a message to this commit: 5. Click on “Publish Branch”: 6. It will appear this pop up to you where you can select if the repository will be private or public: 7. Now your files are on GitHub! Checklist – Wiki (Project 1) Summary Understanding Util.py............................................................................................................. 3 Convert Markdown to HTML................................................................................................. 4 Entry Page ................................................................................................................................. 5 Hint............................................................................................................................................... 7 Index Page................................................................................................................................. 7 Search......................................................................................................................................... 8 New Page................................................................................................................................. 10 Edit Page ...................................................................................................................................13 Random Page...........................................................................................................................16 FAQ..............................................................................................................................................17 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Wiki (Project 1) Understanding Util.py list_entries() Returns a list of all names of encyclopedia entries. Let us look on how to use this function: allEntries = util.list_entries() Now, let us look on how the information that this function returns come to us (using the debugger): save_entry(title,content) Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. Let us look on how to use this function: util.save_entry(title,content) get_entry(title) Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. Let us look on how to use this function: entry = util.get_entry(title) Now, let us look on how the information that this function returns come to us (using the debugger): 3 Checklist – Wiki (Project 1) Convert Markdown to HTML Specification On each entry’s page, any Markdown content in the entry file should be converted to HTML before being displayed to the user. You may use the pythonmarkdown2 package to perform this conversion, installable via pip3 install markdown2. How To Do This? First you should understand what the python-markdown2 does. You can check the link given to us in the specifications: https://github.com/trentm/python-markdown2 Markdown is a light text markup language, and the entries are written in this language. The problem of this project is that we are using HTML, that is another markup language. How to solve this? The link explains how we are going to do this. But just the link is not enough. The first thing you must do is to import the markdown2 library in ‘views.py’. Then, you are going to do this conversion every time you have to display the page that already exists in the entries folder or every time you create a new page. First, you are going to create a variable to store the ‘Markdown()’ function. This function is going to do the conversion to you. For example: markdown = Markdown() But how am I going to take the markdown content of the entry? To do this, you should use the ‘get_entry’ function, because it retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. Thus, you are going to store in a variable the entry using the ‘get_entry’ function. For example: entry = util.get_entry(entry_name) 4 Checklist – Wiki (Project 1) If the ‘get_entry’ function returns None, you are going to return None in your conversion. If the ‘get_entry’ function does not return None, you are going to create a new variable to store this conversion. In this variable, you are going to use the explanation in the link. Thus, you are going to do the following. html_converted = markdown.convert(entry) It is scary for the first time, but you are going to see that this will save you time! Entry Pages Specification Visiting /wiki/TITLE, where TITLE is the title of an encyclopedia entry, should render a page that displays the contents of that encyclopedia entry. How To Do This? To solve this, you should go to urls.py file and add in the urlpatters a new path. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand the flexible way that they use to create a path (image below): Thus this new path will be something like ‘/wiki/<str: title>’, where the ‘title’ will the title of an encyclopedia entry. Specification The view should get the content of the encyclopedia entry by calling the appropriate util function. How To Do This? To solve this, you should go to views.py file and add a new route. 5 Checklist – Wiki (Project 1) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they use the <str:name> from url in the route (image below): With the ‘title’ in hands, you can call the appropriate util function. In the entry page, you want to display the content of the title. You should use the logic to convert the Mardown to HTML. Specification If an entry is requested that does not exist, the user should be presented with an error page indicating that their requested page was not found. How To Do This? Like explained in the previous bullet point, the ‘get_entry’ retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. Thus, your ‘conversion Markdown to HTML’ returns or the HTML content or None. Knowing that, you should do an if-else condition in your route (views.py file) using the None as this condition. If ‘conversion Markdown to HTML’ returns None, you should display a page indicating that the entry does not exists. You can create a new HTML file to display just this error message and indicate in the route to render that specific page. Specification If the entry does exist, the user should be presented with a page that displays the content of the entry. The title of the page should include the name of the entry. How To Do This? If ‘conversion Markdown to HTML’ does not return None, you should display the entry page. To do this, you should pass as context the title and the conversion to HTML to render the html file. 6 Checklist – Wiki (Project 1) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): Hint Specification By default, when substituting a value in a Django template, Django HTMLescapes the value to avoid outputting unintended HTML. If you want to allow for an HTML string to be outputted, you can do so with the safe filter (as by adding |safe after the variable name you’re substituting). How To Do This? You probably had this issue when trying to render your entry page. If you do not use this ‘save’ property in the HTML file, the compiler will understand that you are passing a string and not a html content. To solve this, use the value of the conversion to html and the safe word together. For example: {{ conversion_html | safe }} Index Page Specification Update index.html such that, instead of merely listing the names of all pages in the encyclopedia, user can click on any entry name to be taken directly to that entry page. How To Do This? 7 Checklist – Wiki (Project 1) To solve this, you should go to ‘index.html’ file and you are going to find basically all done for you. The only thing that you have to add is an <a> tag to solve this ‘click on any entry name to be taken directly to that entry page’. Final Step You should go to ‘layout.html’ and add <a> tag to the user be able to click in ‘Home’ and go to the index page. Search Specification Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. How To Do This? To solve that, you should create a new URL simple path in ‘urls.py’. Like the following image from Lecture Django in CS50 notes. In addition, you should create a new route in ‘views.py’. In there, you should use the ‘list_entries’ function the way that we recommended in the beginning of this checklist. Then, you should get the input from the user in the search box and store in a variable. Since this is a request GET method, you should use, for example: search = request.GET(‘NameOfTheInputOnHTML’) To check if there is an entry with the title that the user wants to search, you should use the ‘get_entry’ function the way that we recommended in the beginning of this checklist. Specification If the query matches the name of an encyclopedia entry, the user should be redirected to that entry’s page. 8 Checklist – Wiki (Project 1) How To Do This? This will occur if the function ‘get_entry’ does not return None. Then, you should render the entry page of this entry searched. Specification If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were ‘Py’, then ‘Python’ should appear in the search results. How To Do This? This will occur if the function ‘get_entry’ returns None. You should create an empty list. Then, you should do an iteration in each entry in the ‘list.entries’ and check if the search is a substring of the entries that already exists. If the search is a substring, you are going to append this entry in the empty list that you created previously. Else, you go to the next iteration. After all, pass as context this new list and render the ‘index.html’ page with this context. This is what your project should return when you seach ‘Py’ in the entries. Specification 9 Checklist – Wiki (Project 1) Clicking on any of the entry names on the search results page should take the user to that entry’s page. How To Do This? Since you are using the index.html file to render the search query, you do not need to do this step, because you already did in the Index section. New Page Specification Clicking “Create New Page” in the sidebar should take the user to a page where they can create a new encyclopedia entry. How To Do This? You should go to ‘layout.html’ and add <a> tag to the user be able to click in ‘Create New Page’ and go to the create new page. You should create a new URL and new route to display this page. Also, you should create a html file to display the components of your page. After that, in the ‘views.py’ render the page. Specification Users should be able to enter a title for the page and, in a textarea, should be able to enter the Markdown content for the page. How To Do This? In the html file, you are going to use the <form> tag to create the textarea for title and content of the page. You can set how many rows your textarea will display. Look at this link: https://www.w3schools.com/tags/tag_textarea.asp 10 Checklist – Wiki (Project 1) Since you are using form with Django, you must use the syntax explained in Lecture Django in CS50 notes. Look the image below: Inside the form, you should use two <textarea> tags, one for title and other for Markdown content. The title will be the title of your tab (green arrow in the image below) and the Markdown content will be the content displayed in your page (yellow arrow in the image below). Specification Users should be able to click a button to save their new page. How To Do This? After creating the <textarea> tags and before closing the <form> tag, use an <input> tag with ‘type=submit’. You can change the style of this button using Bootstrap for example. See the following link: https://getbootstrap.com/docs/5.0/components/buttons/ At this point, the New Page should be look like: 11 Checklist – Wiki (Project 1) Specification When the page is saved, if an encyclopedia entry already exists with the provided title, the user should be presented with an error message. Otherwise, the encyclopedia entry should be saved to disk, and the user should be taken to the new entry’s page. How To Do This? Now you are going to work with the ‘views.py’ file. In there, you have to do an if-else condition to check if you are going to work with the POST method or GET method. You can use the following notation: if request.method == ‘POST’: else: The POST method basically will handle the data of the form. Inside this if, you are going to get the information from the form using the following notation, for example: title = request.POST[‘title’] content = request.POST[‘content’] Then, you have to check if the entry already exists. To do this, you can use the ‘get_entry’ function that we explained in the Util section. If the ‘get_entry’ does not return None, you should render a html file saying that this page already exists. Here you are going to do the same way as we explained in the Entry Page section. 12 Checklist – Wiki (Project 1) If the ‘get_entry’ returns None, you are going to call the conversion to HTML function and render the entry page. The GET method basically will handle displaying the ‘New Page’ html file. Thus, inside of the else you are just going to render the ‘New Page’. Edit Page Specification On each entry page, the user should be able to click a link to be taken to a page where the user can edit that entry’s Markdown content in a textarea. How To Do This? You should create a new URL path and a new route. These two files will be like the entry page, but in this case the URL should be like ‘edit/<str: title>/’. To solve this, you can add an <a> tag that redirect the user to this new URL path. You can style that using buttons from Bootstrap. See the following link: https://getbootstrap.com/docs/5.0/components/buttons/ To create a button in your <a> tag you should copy the class from Bootstrap and put inside de <a> tag. For example: <a class=”btn btn-primary” href=’…’> At this point, your entry page should look like this: 13 Checklist – Wiki (Project 1) Specification The textarea should be pre-populated with the existing Markdown content of the page. (i.e., the existing content should be the initial value of the textarea). How To Do This? Now you are going to work with the ‘views.py’ file. In there, you have to do an if-else condition to check if you are going to work with the POST method or GET method. You can use the following notation: if request.method == ‘GET’: else: The GET method basically will handle displaying the ‘Edit Page’ HTML file. To pre-populate with the existing Markdown content of the page, you should use the ‘get_entry’ function. Then, you need to pass the entry name and the entry content as context from ‘views.py’ to ‘edit’ HTML. In the ‘edit’ HTML, you are going to use the <form> tag to create the textarea for title and content of the page. You can set how many rows your textarea will display. Look at this link: https://www.w3schools.com/tags/tag_textarea.asp Since you are using form with Django, you must use the syntax explained in Lecture Django in CS50 notes. Look the image below: So far, the page should look like: 14 Checklist – Wiki (Project 1) Note that the title will be the title of your tab (green arrow in the image below) and the Markdown content will be the content displayed in your page (yellow arrow in the image below). Specification The user should be able to click a button to save the changes made to the entry. How To Do This? Your <input type=”submit”> will be this button to save the changes made to the entry. You can style this input using Bootstrap: https://getbootstrap.com/docs/5.0/components/buttons/ 15 Checklist – Wiki (Project 1) This information will be sent to the backend (‘views.py’). In the route you already have the GET method. Now we are going to work with the POST method. The POST method basically will handle the data of the form. Inside this else, you are going to get the information from the form using the following notation, for example: title = request.POST[‘title’] content = request.POST[‘content’] Then, you must save this entry using the ‘save_entry’ function. Check the ‘Understand util.py’ section. After saving, you should convert this edited entry using the ‘conversion Markdown to HTML’. Specification Once the entry is saved, the user should be redirected back to that entry’s page. How To Do This? This is the last part in the POST method. You are going to render the page with the edited entry. Remember to pass as context the title and the content of the edited entry. Random Page Specification Clicking “Random Page” in the sidebar should take user to a random encyclopedia entry. How To Do This? You should create a new url and new route to display this page. You can use the ‘random library, because there is a function ‘randpm.choice()’ that pick a random entry in the list you pass as input. 16 Checklist – Wiki (Project 1) After that, call the conversion to HTML function and render the page. Final Step You should go to ‘layout.html’ and add <a> tag to the user be able to click in ‘Random Page’ and go to the random page. FAQ Question How To Do This? The reason why the search is not working is because the code didn’t have the {csrf_token}. Check the Search section to know better. Question How To Do This? When you do the iteration in each entry to if the search input is a substring of other entries, you have to make all lower case. To do this, you can use the .lower() Python function to do the comparison. For example: if search.lower() in entry.lower(): 17 Checklist – Wiki (Project 1) Question How To Do This? Check the Edit Page section and you will understand how to do it. Question How To Do This? To solve the formatting of <textarea> tags you should change the properties in styles.css. To solve the markdown conversion, look at Convert Markdown to HTML section and the New Page section. Question How To Do This? 18 Checklist – Wiki (Project 1) Check the Edit Page section and you will understand how to do it. Question How To Do This? To solve this, you should go to ‘index.html’ file and you are going to find basically all done for you. The only thing that you have to add is an <a> tag to solve this ‘click on any entry name to be taken directly to that entry page’. 19 Checklist – Commerce (Project 2) Summary Models........................................................................................................................................................3 Create Listing..........................................................................................................................................3 Active Listings Page .............................................................................................................................6 Listing Page .............................................................................................................................................7 Watchlist ................................................................................................................................................. 18 Categories .............................................................................................................................................. 19 Django Admin Interface.................................................................................................................... 20 FAQ........................................................................................................................................................... 20 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Commerce (Project 2) Models Specification Your application should have at least three class in addition to the User model: one for auction listings, one for bids, and one for comments made on auction listings. It’s up to you to decide what fields each model should have, and what the types of those fields should be. You may have additional class if you would like. How To Do This? To solve this problem, we suggest to first understand what models do. Look at CS50 Web Lecture 4 Notes in the section Django Models: https://cs50.harvard.edu/web/2020/notes/4/ Basically, you can create Django models to work with databases instead of directly using SQL queries. In the Lecture 4, they suggest creating a file called ‘models.py’ where you are going to outline what data you want to store in your application. Then, Django will determine the SQL syntax necessary to store information on each of your class. Thus, before starting the project 2, make sure you really understand the Flight example gave in CS50 Web Lecture 4 Notes. After understanding the Flight example, you will be very comfortable working with models in your project. This models specification will be done while you progress in your project. Let’s go to the next part! Create Listing Specification Users should be able to visit a page to create a new listing. They should be able to specify a title for the listing, a text-based description, and what the starting bid should be. Users should also optionally be able to provide a URL for an image for the listing and/or a category (e.g. Fashion, Toys, Electronics, Home, etc.). 3 Checklist – Commerce (Project 2) How To Do This? Since the new listing information will be stored in the database, you can create a Model to do this. Look at CS50 Web Lecture 4 Notes to have an idea on how to do this: You are going to do something like this in your ‘models.py’, but in your case you should fulfill the requirements for the listing: title, text-based description, starting bid, image by URL and/or category. Check the link below to know better how to create each field for the class: https://docs.djangoproject.com/en/3.0/ref/forms/fields/#built-in-field-classes We suggest creating one model for the listing and one model for the category. Note: remember to create a field for the owner of the listing! After creating your class, you should create an URL path, a route, and a HTML file to create a new listing. In the new HTML file, you should use a <form> tag and have as input the requirements said above. Note: since you are using forms with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look at the image below: Now you are going to work with the ‘views.py’ file. In there, you have to do an if-else condition to check if you are going to work with the POST method or GET method. You can use the following notation: if request.method == ‘POST’: else: 4 Checklist – Commerce (Project 2) The POST method basically will handle the data of the form. Inside of this if, you are going to get the information from the form using the following notation, for example: title = request.POST[‘title’] … category = request.POST[‘category’] You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. The GET method basically will handle displaying the ‘New Listing Page’ html file. Thus, inside of the else you are just going to render the HTML file you already created (the one with the <form> tag). Active Listings Page 5 Checklist – Commerce (Project 2) Specification The default route of your web application should let users view all of the currently active auction listings. For each active listing, this page should display (at minimum) the title, description, current price, and photo (if one exists for the listing). How To Do This? To solve this problem, you should work with the ‘index.html’ file and use the Bootstrap tools to create a nice ‘Active Listings Page’. You may be interested in use <div> tag to separate each listing information in boxes, like the image below: In ‘models.py’ you should create a field in your listing model to set if the listing is active or not. By now, all your listing should be active. Further in the project, you will be able to change this status. In ‘views.py’ you should find a way to display only the active listings. To do this, you should manipulate your class. Look how it works in CS50 Web Lecture 4 Notes. In your case, you should filter by the active field. 6 Checklist – Commerce (Project 2) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): After passing as context this information from ‘views.py’ to the HTML file, you are going to display the title, description, current price, and photo (if one exists for the listing). For example, passing the listing as context in the ‘views.py’: Listings = Listings.objects.filter(active=True) In ‘index.html’, since you are passing multiple listings, you should do an iteration to display all listings at a time. For example: {% for listing in listings %} … {% endfor %} Remember to use the double curly braces to display the information from ‘views.py’ in the HTML file. For example, to display the title of the listing you can use: {{ listing.title }} Listing Page Specification Clicking on a listing should take users to a page specific to that listing. On that page, users should be able to view all details about the listing, including the current price for the listing. How To Do This? To do this, in your ‘index.py’, you should use an <a> tag in each listing in your index. The <a> tag should have as ‘href’ the URL for the listing. This URL for the listing will be like what you did in Wiki Project. Look at greet function in CS50 Web Lecture 3 Notes: 7 Checklist – Commerce (Project 2) Note: in this case you should use <int:listing_id> instead of <str:name>. In this page, you should pass the information from de backend (‘views.py) to the frontend (HTML file). In ‘views.py’ you should find a way to display only the active listings. To do this, you should manipulate your class. Look how it works in CS50 Web Lecture 4 Notes. In your case, you should filter the category model by the listing field and the listing model you should get by the id. If you do not remember how to do this, look at ‘Active Listings Page’ section. Thus, in this page you are going to display the following information: • Name of the listing: you should display the title of the listing. For example: {{ listing.title }} • The image of the listing: it is optional. You are going to display this using the <img> tag and the image is stored in the same way you have the title. For example: {{ listing.image }} • The description of the listing: you can do the same way as you did for name of the listing. • Category of the listing: you can do the same way as you did in name of the listing, but in this case, you should call the category that you passed as context. For example: {{ category.title }} • The current bid: you are going to display the same way as you display the name of the listing. It is up to you decide how many information you want to display from your Listing class. 8 Checklist – Commerce (Project 2) Note: now you know that you are going to have a starting bid and a current bid in your listing. Thus, we recommend creating one field for each of these bids. Specification If the user is signed in, the user should be able to add the item to their “Watchlist.” If the item is already on the watchlist, the user should be able to remove it. How To Do This? In this case you should pass a Boolean saying whether the listing of a particular user is in his watchlist as context in your ‘views.py’. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): It might be useful to use the Python in operator. In the HTML file, you first should check if the user is signed in. To do this, you can do an if-else condition. For example: {% if user.is_authenticated %} … {% else %} … {% endif %} Inside the if user.is_authenticated, you are going to create a condition based on this context that you passed. If this condition is True, you are going to display the logic to remove the listing from the watchlist. If the condition is False, you are going to display the logic to add the listing to the watchlist. For example, the in_watchlist is a Boolean variable that stores whether a listing is in the user’s watchlist: {% if in_watchlist == True %} 9 Checklist – Commerce (Project 2) … {% else %} … {% endif %} Inside these if-else condition, you can display a button, for example. When the user clicks on this button, the user can add or remove the listing to his watchlist. To handle adding the listing in the watchlist, you should create a new URL path and a new route in ‘views.py’. This URL will be like what you did in ‘Listing Page’. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. In the route, you should get the listing by id. With this id you can get the listing in the Listing model and add the user in the watchlist field. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. 10 Checklist – Commerce (Project 2) Remember how you did in ‘Create Listing’ section! To handle the removal of the listing from the watchlist, you should create a new URL path and a new route in ‘views.py’. This URL will be like what you did in ‘Listing Page’. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. In the route, you should get the listing by id. With this id you can get the listing in the Listing model and remove the user in the watchlist field. You can remove checking the .remove property in the following link: https://docs.djangoproject.com/en/3.1/topics/db/queries/ You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. Remember how you did in ‘Create Listing’ section and ‘Adding to Watchlist’! 11 Checklist – Commerce (Project 2) Specification If the user is signed in, the user should be able to bid on the item. The bid must be at least as large as the starting bid, and must be greater than any other bids that have been placed (if any). If the bid doesn’t meet those criteria, the user should be presented with an error. How To Do This? You can create a new model in ‘models.py’ for Bids. In this model should have as fields the offer, the user that gave the bid and the listing (where the offer was made). In the listing HTML file, you should first check if the user is authenticated and if the listing is active. For example, where the listing.active is a Boolean variable that sets whether the listing is active or not: {% if user.is_authenticated and listing.active == True %} … {% else %} … {% endif %} Inside the if user.is_authenticated and listing.active == Ture, you are going to use a <form> tag and have as input the bid of the user. Note: since you are using form with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look the image below: To handle submitting the bid, you should create a new URL. This URL will be like what you did in ‘Listing Page’. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. 12 Checklist – Commerce (Project 2) Then, you should create a new route for the comment. In this route you should get the listing by the id. Look how it works in CS50 Web Lecture 4 Notes. In there, you must do an if condition to check if you are going to work with the POST method. You can use the following notation: if request.method == ‘POST’: The POST method basically will handle the data of the form. Inside this if, you are going to get the information from the form using the following notation, for example: user_bid = request.POST[‘user_bid’] Then, you must check if the user_bid is greater than the starting bid or the current bid. If is not, you should present an error for the user. You can do this by creating a new HTML file for example. If the offer is greater than the current bid or the start bid, you should add this new bid in the model. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() 13 Checklist – Commerce (Project 2) Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. At this point, your project should look like: Specification If the user is signed in and is the one who created the listing, the user should have the ability to “close” the auction from this page, which makes the highest bidder the winner of the auction and makes the listing no longer active. How To Do This? In this case you should pass a Boolean saying whether the particular user is the owner of the listing as context in your ‘views.py’. 14 Checklist – Commerce (Project 2) You can do this by checking if the user is the field that you created in your Listing model to handle storing the owner of each listing. Thus, you should pass as context your Boolean variable. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): In the HTML file, you first should check if the user is signed in. To do this, you can do an if-else condition. For example: {% if user.is_authenticated %} … {% else %} … {% endif %} Inside the if user.is_authenticated, you are going to create a condition based on this context that you passed. If this condition is True, you are going to display the logic to close the bid. Also, you must check if the listing is active or not. For example, the is_owner is a Boolean variable that stores whether the user is the owner of the listing, and the listing.active is a Boolean variable that stores whether the listing is active or not: {% if is_owner == True and listing.active == True%} … {% else %} … {% endif %} Inside this if condition, you can display a button, for example. When the user clicks on this button, the user can close the auction. To handle closing the listing, you should create a new URL path and a new route in ‘views.py’. This URL will be like what you did in Listing Page. Look at greet function in CS50 Web Lecture 3 Notes: 15 Checklist – Commerce (Project 2) Note: in this case you should use <int:listing_id> instead of <str:name>. In the route, you should get the listing by id. With this id you can get the listing in the Listing model and set the active field as False. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can create the Flight class in views.py by creating a variable to store the model itself. For example: flight = Flight() Then you can store each field of the class using the dot operator. For example, if you want to assign a value to the origin field in the Flight class, you can do the following: flight.origin = “New York” After you’ve set all the fields you call flight.save() and the data will be stored in the database. Remember how you did in ‘Create Listing’ section! Specification If a user is signed in on a closed listing page, and the user has won that auction, the page should say so. How To Do This? In this case you should pass a Boolean saying whether the particular user has the current bid in a listing (the one that won the auction) as context in your ‘views.py’. 16 Checklist – Commerce (Project 2) You can do this by checking if the user is the field that you created in your Listing model to handle storing the user that placed the current bid of each listing. Thus, you should pass as context your Boolean variable. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): In the HTML file, you first should check if the user is the buyer of the listing and the listing is not active. For example, the is_winner is a Boolean variable that stores whether the user is the winner of the listing, and the listing.active is a Boolean variable that stores whether the listing is active or not: {% if listing.active == False and is_winner == True %} … {% endif %} Inside the if, you are going to display a message telling the user that he won the auction. Specification Users who are signed in should be able to add comments to the listing page. The listing page should display all comments that have been made on the listing. How To Do This? About the comments, you can create a new model. In this model should have as fields the comment, the user that gave the comment and the listing (where the comment was made). In this section, we must do two things. First receive new comments from the user and second display the comments. 1. Receive new comments from the user: 17 Checklist – Commerce (Project 2) In the listing HTML file, you are going to first check if the user is authenticated. For example: {% if user.is_authenticated %} … {% else %} … {% endif %} Inside the if user.is_authenticated, you are going to use a <form> tag and have as input the comment of the user. Note: since you are using form with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look the image below: To handle submitting the comments, you should create a new URL. This URL will be similar to what you did in Listing Page. Look at greet function in CS50 Web Lecture 3 Notes: Note: in this case you should use <int:listing_id> instead of <str:name>. Then, you should create a new route for the comment. In this route you should get the listing by the id. Look how it works in CS50 Web Lecture 4 Notes. In there, you have to do an if condition to check if you are going to work with the POST method. You can use the following notation: 18 Checklist – Commerce (Project 2) if request.method == ‘POST’: The POST method basically will handle the data of the form. Inside this if, you are going to get the information from the form using the following notation, for example: user_comment = request.POST[‘user_comment’] Then, you should add this information to the Comment model. You can fulfill the model using the notation explained in the Lecture 4 (all in one line). Look how it is done in CS50 Web Lecture 4 Notes. Or you can fulfill the model creating a variable to store the model itself. For example: flight = Flight() Then, instead of doing what is in the image above, you can store each field of the model by calling the previous variable and using a dot and the name of the field. For example, if you want to fulfill the origin field in Flight class, you can do the following: flight.origin = “New York” Now, you should do the same idea in your project. 2. Display the comments in the listing: In the listing page route, you should pass as context the comments for that listing. Remember to use the following: comments = Comment.objects.filter(listing=listing) Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): 19 Checklist – Commerce (Project 2) Since you are passing multiple listings, you should do an iteration to display all the comments at a <div> tag. For example: {% for comment in comments %} … {% endfor %} Remember to use the double curly braces to display the information from ‘views.py’. For example, to display the comment you can use: {{ comment.user }} Watchlist Specification Users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. Clicking on any of those listings should take the user to that listing’s page. How To Do This? To solve this, first you should pass the user watchlist model to a new HTML file. You can do this by passing as context. Look at greet function on CS50 Web Lecture 3 Notes: In this HTML file you are going to display the listings the same way as you did in the ‘index.html’. 20 Checklist – Commerce (Project 2) Categories Specification Users should be able to visit a page that displays a list of all listing categories. Clicking on the name of any category should take the user to a page that displays all of the active listings in that category. How To Do This? To solve this, first you should pass the category model to a new HTML file. You can do this by passing as context. Look at greet function on CS50 Web Lecture 3 Notes: Then, you are going to the HTML file and can create a <form> tag to display the categories options. Note: since you are using form with Django, you must use the syntax explained in Lecture 3 Django in CS50 notes. Look the image below: The form will be handled in a new route, where you are going to display the specific listings of that category chosen by the user. Thus, in this new route you should get the values from the form. And then, use this category to get the listings. Pass this information to the HTML file. Remember how to do this in the previous sections. In this HTML file you are going to display the listings the same way as you did in the ‘index.html’. Django Admin Interface 21 Checklist – Commerce (Project 2) Specification Via the Django admin interface, a site administrator should be able to view, add, edit, and delete any listings, comments, and bids made on the site. How To Do This? To solve this, you are going to follow the steps explained in the ‘Django Admin’ at the end of CS50 Web Lecture 4 Notes. Just follow the steps! FAQ Specification When should I use the @login_required decorator in my ‘views.py’? How To Do This? You should use this decorator any time you want display the page only if the user is logged in. For example, you can use this @login_required decorator in the watchlist page. Specification How should I create my Category model? How To Do This? Your Category model should have at least two fields. One for the name of the category, and in this case, you are going to use the CharField. The other field should have a relationship with the Listing model. In this case, you should use the ForeignKey field. Specification When should I use the ManyToManyField relationship in ‘models.py’? 22 Checklist – Commerce (Project 2) How To Do This? By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it. You should use the ManyToManyField in the watchlist for example. Because this field will store which users wants to have in the watchlist for each listing. Thus, you are going to be able to store multiple users in each listing. For example, Mary and John want to have the Chocolate listing in the watchlist. Mary wants to have the Cake listing in the watchlist. Daniel wants to have Ice Cream listing in the watchlist. The ManyToManyField will store this information. Specification How To Do This? The Bids model should store the data about the offer, the user that gave the offer and a relation between the bid and the listing where the bid was placed. This relation will be handled by the ForeignKey field. Specification How To Do This? You should create a field in your Listing model to check if the listing is active or not. You can do this by using the BooleanField. Then, in your ‘views.py’ you must filter the listing by this Boolean. For example: listings = Listing.objects.filter(active=True) 23 Checklist – Commerce (Project 2) Specification How To Do This? Since you are receiving the image by it is URL, you can display the image just using the <img> tag and in the property ‘src’ you call the listing image. For example: <img src={{ listing.image }}> Remember to pass as context to the HTML file the Listing model. If you do not know how to do this, check the ‘Listing Page’ section. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): Specification How To Do This? Look on how to do this in the ‘Watchlist’ section. You should pass the watchlist as context from ‘views.py’ to the HTML file. Look at Lecture Django in CS50 notes and check the ‘greet’ function. You should understand how they pass the context from Django to HTML (image below): 24 Checklist – Commerce (Project 2) 25 Checklist – Mail (Project 3) Summary Mail Project ............................................................................................................................... 3 Send Mail ................................................................................................................................... 3 Mailbox ....................................................................................................................................... 4 View Email ................................................................................................................................. 7 Archive and Unarchive ........................................................................................................ 10 Reply........................................................................................................................................... 11 CSS............................................................................................................................................. 14 FAQ............................................................................................................................................. 14 Important Throughout this document there will be blue colored links. These links will help you to solve the project. Right-click and open in a new tab. Disclaimer This is a checklist to help you go through the problem. The following checklist if for educational purposes only. Cheating or any other activities are highly discouraged! 2 Checklist – Mail (Project 3) Mail Project The distribution code gives to us all the backend done, so the only files that you are going to work will be the inbox.js, inbox.html and styles.css. Remember that the JavaScript will be written in the inbox.js; the HTML will be written in the inbox.html; and the CSS will be in the styles.css. Send Mail Specification When a user submits the email composition form, add JavaScript code to actually send the email. How To Do This? To solve this bullet point you can create a new function with purpose of submitting the email. You should get the values of recipients, subject, and body from the input that the user gives to the web app. To do this, take a look at this property of JavaScript: https://www.w3schools.com/jsref/met_document_queryselector.asp Specification You’ll likely want to make a POST request to /emails, passing in values for recipients, subject, and body. How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “POST/emails”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. 3 Checklist – Mail (Project 3) Specification Once the email has been sent, load the user’s sent mailbox. How To Do This? To solve this, you should call the function load_mailbox, that is already made to us in the distribution code and sending as input to the function the mailbox ‘sent’. We recommend you use the setTimeout in order to wait the fetch call works. This is interesting to be used because when you use fetch it takes a while to send and receive the information, so the setTimeout will wait this information go and come to render the page. HINT You are going to notice that if you try to send an email your page is not going to be redirected to sent mailbox, but to inbox instead. How to solve this? You should use the preventDefault function because this function will prevent the default of submit to be refreshing the button. Mailbox Specification When a user visits their Inbox, Sent mailbox, or Archive, load the appropriate mailbox. How To Do This? To solve this problem, you are going to work with the load_mailbox function that was already initialized for you in the distribution code. Specification You’ll likely want to make a GET request to /emails/<mailbox> to request the emails for a particular mailbox. 4 Checklist – Mail (Project 3) How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “GET/emails/<str:mailbox>”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. Specification When a mailbox is visited, the application should first query the API for the latest emails in that mailbox. How To Do This? This part is already done for you. If you take a look at mailbox route in views.py, you are going to find on line 95 that the distribution code already returns the email for the frontend in reverse chronological order. Specification When a mailbox is visited, the name of the mailbox should appear at the top of the page (this part is done for you). How To Do This? As the specification already says, this part is done for you. Specification Each email should then be rendered in its own box (e.g. as a <div> with a border) that displays who the email is from, what the subject line is, and the timestamp of the email. 5 Checklist – Mail (Project 3) How To Do This? To do this you should create a new function to render in each email its own box. PS: When you do the fetch call in the load_mailbox, we recommend you remember to call this new function inside. In this function you should do an iteration to work with one email at a time. We recommend you look at forEach JavaScript property. After that, you should get the values of recipient, subject and timestamp that were passed from the backend to the frontend. Store these values in variables. We recommend using the createElement property to create a new tag in the HTML file using JavaScript in order to display this information that you grabbed from the backend. Use the property innerHTML to display this information in the new tag that you created. To complete this task, you have to append the new tag that you created in JavaScript at an existing tag in the HTML file. Specification If the email is unread, it should appear with a white background. If the email has been read, it should appear with a gray background. How To Do This? At this point of the problem, you should create an if-else condition to check if the email was already read. If this is true, use the style.backgroundColor to set the email background as gray. Else, use the same property to set the email background as white. At this point you project should look like this: 6 Checklist – Mail (Project 3) View Email Specification When a user clicks on an email, the user should be taken to a view where they see the content of that email. How To Do This? In the function that you just created to render in each email its own box, you should use the addEventListener function to be triggered when the user clicks in the email box. Specification You’ll likely want to make a GET request to /emails/<email_id> to request the email. How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “GET/emails/100”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. 7 Checklist – Mail (Project 3) Inside the fetch, you can call another function to display the email with the specifications that are in the next bullet point. Specification Your application should show the email’s sender, recipients, subject, timestamp, and body. How To Do This? This part you should do in your function created to display the email. To solve this bullet point, you can grab the current email’s properties by the values that you are grabbing from the fetch call. For example, to grab the sender you can do email.sender and store this value in a variable. To display these values, you should use the property innerHTML in the div tag that you include in your inbox.html. Specification You’ll likely want to add an additional div to inbox.html (in addition to emailsview and compose-view) for displaying the email. Be sure to update your code to hide and show the right views when navigation options are clicked. How To Do This? The first thing you should do is adding a new div tag in inbox.html with an id property. To solve this, look at the function compose_email. You are going to find 3 lines, which the first is the following comment: // Show compose view and hide other views The other 2 lines are the ones that you have to understand. When you use document.querySelector(‘#id’).style.display you are using JavaScript to set if you want to hide or not the components in that id attribute. 8 Checklist – Mail (Project 3) When you set this to ‘none’, you are hiding the components in the HTML of that id attribute. When you set this to ‘block’, you are showing the components in the HTML of that id attribute. Specification See the hint in the Hints section about how to add an event listener to an HTML element that you’ve added to the DOM. How To Do This? In the function that you just created to render in each email its own box, you should use the addEventListener function to be triggered when the user clicks in the email box. Specification Once the email has been clicked on, you should mark the email as read. Recall that you can send a PUT request to /emails/<email_id> to update whether an email is read or not. How To Do This? We recommend creating a new function to mark the email as read. If you take a look at the API in the Mail Project explanation, you are going to find a section called “PUT/emails/<int:email_id>”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. Instead of using ‘archived: true’ in the example that they gave to us, you should use ‘read: true’. 9 Checklist – Mail (Project 3) You are going to have to call this function in the display email function. Remember that you only can set if the email was read or not if you are in the inbox or archive mailbox. At this point your project should look like this: Archive and Unarchive Specification Allow users to archive and unarchive emails that they have received. How To Do This? You should create a new function to solve this issue. Basically, you are going to use the addEventListener to trigger the fetch call after clicking the submit button. In the next bullet points we explain better. Specification When viewing an Inbox email, the user should be presented with a button that lets them archive the email. When viewing an Archive email, the user should be presented with a button that lets them unarchive the email. This requirement does not apply to emails in the Sent mailbox. How To Do This? To solve that you should create a button in your display email function. This button will represent the archive/unarchive. 10 Checklist – Mail (Project 3) Since this requirement does not apply to emails in the Sent mailbox, you are going to call the function that handle with showing the archive button. The same way as you did before for the mark email as read. Specification Recall that you can send a PUT request to /emails/<email_id> to mark an email as archived or unarchived. How To Do This? If you take a look at the API in the Mail Project explanation, you are going to find a section called “PUT/emails/<int:email_id>”. The CS50’s staff explain how you should send the information that you are receiving from the frontend to the backend. You basically are going to get the JavaScript code that they give to you and make some changes. We recommend you understand what fetch does before starting this part of the project. Specification Once an email has been archived or unarchived, load the user’s inbox. How To Do This? After doing the fetch call, remember to call the load_mailbox function to redirect the user to the inbox. We recommend you use the window.location.reload() after redirecting the user to the inbox. Reply Specification Allow users to reply to an email. When viewing an email, the user should be presented with a “Reply” button that lets them reply to the email. 11 Checklist – Mail (Project 3) How To Do This? You can do this by adding a <button> tag in the inbox.html. Specification When the user clicks the “Reply” button, they should be taken to the email composition form. How To Do This? In the function that you created the display email, you are going to use the addEventListener to trigger the compose_email function after clicking the submit button. In the next bullet points we explain better. Basically, the compose_email function just handle with the situation that you are creating a new email to someone. Since this case is a reply, you should create a new function. After creating this function, you should go to compose_email and create an ifelse condition. This will make your compose_email be used in the reply button and in the compose mailbox. Specification Pre-fill the composition form with the recipient field set to whoever sent the original email. How To Do This? You can pre-fill the composition form by grabbing the current email’s properties by the values that you are passing as input in this function. For example, to grab the recipient you can do ‘email.sender’ and store this value in a variable. After that, you can use document.querySelector(‘#compose-recipients’).value and set this value as the same of the variables. 12 Checklist – Mail (Project 3) Specification Pre-fill the subject line. If the original email had a subject line of foo, the new subject line should be Re: foo. (If the subject line already begins with Re: , no need to add it again.) How To Do This? You can pre-fill the composition form by grabbing the current email’s properties by the values that you are passing as input in this function. For example, to grab the subject you can do ‘Re: email.subject’ and store this value in a variable. After that, you can use document.querySelector(‘#compose-subject’).value and set this value as the same of the variables. Specification Pre-fill the body of the email with a line like "On Jan 1 2020, 12:00 AM foo@example.com wrote:" followed by the original text of the email. How To Do This? You can pre-fill the composition form by grabbing the current email’s properties by the values that you are passing as input in this function. For example, to grab the body with the timestamp you can do `On ${email.timestamp} ${email.sender} wrote: ${email.body}.’ and store this value in a variable. After that, you can use document.querySelector(‘#compose-body’).value and set this value as the same of the variables. At this point your project should look like this: 13 Checklist – Mail (Project 3) CSS Specification You have to create your own style for this project. How To Do This? We recommend you use CSS and Bootstrap tools. For example, to create the boxes separating each email, you can use padding and border properties. For example, to make the buttons look nice, you can use the Bootstrap buttons. FAQs Specification How To Do This? If your Javascript changes aren't being reflected in your site, check: https://stackoverflow.com/questions/8392441/stop-chrome-caching-my-js-files 14 Checklist – Mail (Project 3) Specification How To Do This? This issue happens in the function that handles with submitting the email. You are going to notice that if you try to send an email your page is not going to be redirected to Sent mailbox, but to inbox instead. How to solve this? You should use the preventDefault function because this function will prevent the default of submit to be refreshing the button. Specification How To Do This? Replace line number 26 in mail/models.py with: "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), This error is caused because strftime function implementation depends on your operating system. If you are Mac and Linux user, you will not have this problem. If you are windows user, you should change the line 26 in models.py to the following line. "timestamp": self.timestamp.strftime("%b %#d %Y, %#I:%M %p"), 15 Checklist – Mail (Project 3) Specification How To Do This? When you are testing the ‘send email’ code, remember that you must send an email to someone that is already registered in your backend. Do not forget to create two users in the webapp and then send email to each other. Specification How To Do This? You should listen for an click or submit event on the submit button of the form (#send) rather than form submission. Also remember to use the preventDefault() to prevent form submission. 16