get_ipython().
ast_node_interactivity = All instances removed from list…
'all' def remove(list, value):
Functions listcopy = list[:]
function -> even_numbers parameter -> en_list while value in listcopy:
def even_numbers(en_list): listcopy.remove(value)
evens = [] return listcopy
for number in en_list: remove([3,2,3,4,3], 3)
if number%2==0: [2, 4]
evens = evens + [number] def num_blts(bacon_strips, lettuce_leaves,
return evens tomato_slices):
even_numbers([3,5,4,1,8]) B = bacon_strips // 10
[4, 8] L = lettuce_leaves//3
def is_palindrome(palindrome): T = tomato_slices//6
return palindrome == palindrome[::-1] BLT = min (B, L, T)
is_palindrome("radar") return BLT
True num_blts(20, 33, 18) # should return 2
num_blts(53, 8, 11) # should return 1
List Options:
mylist = ["chocolate chip", "rocky road",
2
"moose tracks", "cherry garcia"] 1
mylist.append("peach") add "peach" Try statements
mylist.remove("moose tracks") count = 0
remove "moose tracks" mylist = [4.2, "peanut butter", 8, -1]
mylist.pop(3) remove element 3 for element in mylist:
mylist.sort() puts list in ASCIIbetical order try:
mylist.sort(key = str.lower) if element <= 0:
puts list in "normal" alphabetical order print("Non-positive number
mylist.sort(key = str.lower, reverse = True) found.")
puts list in opposite alphabetical order elif element < 3:
mylist.sort(reverse = True) count = count + 1
def next_in_line(nil_lst, nil_num): except:
copylist = nil_lst[:] print(f'Non-numeric value found')
copylist.pop(0) print(f"The total postive integers less
copylist.append(nil_num) than 3 is {count}")
return copylist Dictionaries
next_in_line([1,2,3,4],5) d = {'hello': 'squrge', 'goodbye': 'fillo',
[2, 3, 4, 5] 'peace': 'woosht'}
def smallest_two(st_lst): d[‘peace’] ‘woosht’
listcopy = st_lst[:] d['potato chips']='kloojboos'
listcopy.sort()
adding to dictionary
return listcopy[0], listcopy[1]
d.keys() ['hello', 'goodbye', 'peace', 'potato chips']
alist = [3,7,2,9,3]
d.values() ['squrge', 'fillo', 'woosht', 'kloojboos']
(2, 3)
d.items() [('hello', 'squrge'), ('goodbye', 'fillo'),
One instance removed from list…
def remove(list, value): ('peace', 'woosht'), ('potato chips', 'kloojboos')]
if value in list: phone_book = {"Luke":"313-987-1981",
listcopy = list[:] "Han":"929-921-5561",
listcopy.remove(value) "Leia":"313-220-1497", "Darth":
return listcopy "224-433-7810"}
else: for key in phone_book:
return "NA" if phone_book[key][0:3]=='313':
print(key, phone_book[key])
remove([1,2,3,4,5], 3)
Luke 313-987-1981
[1, 2, 4, 5]
Leia 313-220-1497
Counts states
s = ['Sarah', 'Emmanuel', 'Reyna', for element in states:
'Travis', 'Travis', 'Sarah'] print(states[element]['capital'])
d = {} Montgomery
for name in s: Juneau
if name in d: for state in states:
d[name] += 1 print(f"The abbreviation for {state} is
else: {states[state]['abbrev']}.")
d[name] = 1 The abbreviation for Alabama is AL.
d f = open("president_states.txt", "r")
{'Sarah': 2, 'Emmanuel': 1, 'Reyna': 1, 'Travis': 2} states = {}
Data from files for line in f:
f = open(‘file’, ‘r’) linelist = line.rstrip()
f.close() state, capital, abbrev, name =
mystring = " abc \t \n" linelist.split(",")
mystring.rstrip() ' abc’ if state not in states:
states[state] = {'capital':
mystring.lstrip() 'abc \t \n’
capital, 'abbrev': abbrev, 'numpres': 1}
mystring.strip() ‘abc’
else:
mystring2 = mystring.rstrip("\n")
states[state]['numpres'] =
mystring2 ' abc \t ' states[state]['numpres'] + 1
closing_prices = {"AAPL": [170, 166, 164, f.close()
169], "TSLA":[888, 843, 857, 881], for state in states:
"DIS":[151,152, 150, 150]} print(f'The capital of {state} is
closing_prices["DIS"] -> [151,152, 150, 150] {states[state]["capital"]} and it has had
min(closing_prices["DIS"]) -> 150 {states[state]["numpres"]}')
The capital of Virginia is Richmond and it has had 8
students = [{'id': 87654321, 'homework':
[10,9,9,10,7,8], 'exams': [91,86,92] }, presidents.
{'id': 12345678, 'homework': APIs
[9,9,9,8,8,10], 'exams': [87,90,89] },] import requests
for student in students: Whole string
student[“student_avg”] = http://www.omdbapi.com/?apikey=18d02f0a&s=ghostbusters
sum(student[“homework”]/len(student site = 'http://www.omdbapi.com/'
[“homework”]) movie = input("Give a movie to search
for:")
weather = {"wind" : {"speed" : 13.0, parameters = {'apikey':'18d02f0a',
"crosswind" : 5.0 }, 's':movie}
"sky" : {"type": "overcast", r = requests.get(site, parameters)
"cover": "clouds"}, r.url # no parentheses
"temperature" : {"current": 23, movie_data = r.json()
"range": [12,25]} movie_data
}
weather["sky"]["type"] -> ‘overcast’ site = "https://opentdb.com/api.php"
amount = 1
weather["temperature"]["range"][1] -> 25
question_difficulty = input("Choose the
f = open('states2.txt', 'r') question difficulty (easy, medium, hard)")
states = {} question_type = input("Choose the question
for line in f: type (multiple choice or T/F)")
line = line.rstrip()
state, capital, abbrev =
line.split(",")
states[state] = {'capital': capital,
'abbrev':abbrev}
f.close()
parameters = {'amount': amount, text_yes = "Coleman Fleming,
'difficulty':question_difficulty,
[email protected], 77 Primrose Ave.,
'type':question_type} Patchogue, NY 11772"
r = requests.get(site, parameters) text_no = "Coleman Fleming, 77 Primrose
mydata = r.json() Ave., Patchogue, NY 11772"
results = mydata['results'][0] regex = '\w+@\w+\.[a-z]+' regex for email address
print(f"{results['question']} \n regex_c = re.compile(regex) compile regex
{results['correct_answer']} \n match = regex_c.search(text_yes) search for match
{results['incorrect_answers']}") if match: if there was a match
print(match.group())
site =
[email protected]"https://deckofcardsapi.com/api/deck/new/shuffle/"
interested = ["Nathanael Armstrong,
shuffle = 1
[email protected]",
parameters = {'deck_count': shuffle}
"Luther Camacho, 847-612-9812",
r = requests.get(site, parameters)
"Morgan Shields,
[email protected]",
shuffle_data = r.json()
"Dana Andersen, 770-981-0084",
deck_id = shuffle_data['deck_id']
"Valeria Schmitt, 617-552-0707",
shuffle_data
"Leland Woodard,
[email protected]"]
regex = "[2-9]\d\d-\d\d\d-\d\d\d\d"
site2 =
f'https://deckofcardsapi.com/api/deck/{deck_id}/draw/' new_list = []
numbercards = int(input('How many cards regex_c = re.compile(regex)
would you like to draw?')) for string in interested:
parameters2 = {'count': numbercards} match = regex_c.search(string)
d = requests.get(site2, parameters2) if match:
card_data = d.json() number = (match.group())
card_data['cards'] new_list.append(number)
for card in card_data['cards']: new_list
print(card['value']) ['847-612-9812', '770-981-0084', '617-552-0707']
print(card['suit']) Can match groups in a regex…
text_yes = "Coleman Fleming,
Common regex:
[email protected], 77 Primrose Ave.,
$12.34 = “\$(0|[1-9]\d*)\.\d\d” Patchogue, NY 11772"
[email protected] = "\w+@\w+\.\w+" grouped_regex = '\w+@(\w+.[a-z]+)'
grouped_regex_c = re.compile(grouped_regex)
(A, A-, B+, B, B-, C+, C, C-, D+, D, D-, F) =
match = grouped_regex_c.search(text_yes)
“A-?|[B-D][-\+]?|F”
if match:
Curse word = “[A-Za-z]*\*+[a-z]*” print(match.group(1))
book, boom, cook = “[bc]oo[mk]” matches the regex in the first set of parentheses
phone_number = “[2-9]\d\d-\d\d\d-\d\d\d\d” gmail.com
if match:
Using regular expressions in Python print(match.group())
import re still matches the whole regular expression
Create regular expression
[email protected]Convert the string to a python-recognized regex object
with re.compile()
Search text for a match with your compiled regex with
.search()
Return the match with .group()
Putting together regular expressions and files def has_duplicates(alist):
d = {}
for element in alist:
import re if element in d:
d[element] += 1
login_re = else:
d[element] = 1
for element in d:
'(\d\d\d\d-\d\d-\d\d)T(\d\d:\d\d) Login if d[element]>1:
return True
successful' else:
return False
login_re_c = re.compile(login_re) def odd3(a, b):
alist = []
f = open("logins.txt", 'r') for number in range(a,b+1):
for line in f: if number%2==1:
alist.append(number)
match_obj = login_re_c.search(line) if number%3!=0:
alist.remove(number)
if match_obj: return sum(alist)
date = match_obj.group(1) def merge_d(dict1, dict2):
time = match_obj.group(2) newdictionary = {}
for value in dict1:
print(f'Successful login on {date} newdictionary[value] = dict1[value]
for value in dict2:
at {time}') newdictionary[value] = dict2[value]
Successful login on 2020-09-05 at 11:24 return newdictionary
Successful login on 2020-09-06 at 09:17 def rev_stack(alist):
newlist = []
When there may be more than one match in a string while alist:
number = alist.pop(-1)
text4 = """Prices are going up faster than newlist.append(number)
they have in 40 years, cutting into return print(newlist)
profits. def harshad(positive_number):
mysum = 0
But Tyson Foods (TSN: 88.82) saw its string = str(positive_number)
for digit in string:
profits soar by double digits last quarter. number = int(digit)
In other news, Joe Rogan's podcast will mysum += number
return positive_number%mysum == 0
remain on Spotify
(SPOT: 157.31) following controversies over def is_prime(num):
for i in range(2,num):
COVID misinformation. And finally, Alcoa if num % i == 0:
return False
Corporation (AA: 90.07) plans to announce return True
its first d = {}
for num in range(1,20):
quarter 2022 financial results on d[str(num)]= is_prime(num)
Wednesday.""" Look at where list is supposed to be
track_list = ["1001,Jin,The Astronaut", "1002,Taylor
regex ='[A-Z]+:' # Step 1 Swift,Bejeweled", "1002,Taylor Swift,Question...?",
regex_c = re.compile(regex) #Step 2 "1003,Drake,Rich Flex", "1004,BTS,Yet to Come"]
track_d = {}
match_all_list = regex_c.findall(text4) for string in track_list:
date, name, song = string.split(",")
#Steps 3 and 4 combined if date not in track_d:
track_d[date] = {"name": name, "tracks": [song]}
match_all_list else:
track_d[date]['tracks'].append(song)
['TSN:', 'SPOT:', 'AA:']
text6 = """Download Class 28 Worksheet f = open("strikes.txt", "r")
strikes_ex = {}
RegularExpressions2.ipynb and the file for line in f:
line = line.strip()
logins.txt. Move both to your course folder airport, date, type_fire = line.split(",")
and open the worksheet in Jupyter Lab. A if airport not in strikes_ex:
strikes_ex[airport] = [{'date': date, 'type of fire':
reference that may help: it's a regex type_fire}]
else:
cheatsheet where the topics that we'll strikes_ex[airport].append({'date': date, 'type of
cover in this course are highlighted with fire': type_fire})
red boxes: regex_cheatsheet.pdf.""" def take_three(mylist):
newlist = mylist[:]
regex = "(\w+)\.(\w+)" newlist.sort(reverse = True)
regex_c = re.compile(regex) return newlist[1:4]
def award_data(awards):
filelist = regex_c.findall(text6) d = {}
filelist for element in awards:
winner_list = element.split(",")
[('RegularExpressions2', 'ipynb'), school = winner_list[0]
award = winner_list[1]
('logins', 'txt'), winners = winner_list[2:]
('regex_cheatsheet', 'pdf')] if school in d:
d[school][award] = winners
else:
d[school] = {award:winners}
return d
SELECT Id, ContactName, ContactTitle connection.close()
From Supplier # Put a question mark in the query to stand in for a variable, then a
Where ContactTitle <> "Marketing Manager"; tuple with one entry for each ?
<> means not or unequal cust_id = input("Enter a customer ID.")
SELECT FirstName, LastName, HireDate min_amt = float(input("Enter the minimum order
amount you'd like to return."))
From Employee
query = """
Where Title = "Sales Representative";
SELECT *
FROM OrderData
SELECT id, CustomerId, ShipCountry WHERE customerID = ? AND TotalDue > ?;
FROM Orders """
Where ShipCountry in connection = sqlite3.connect('coke.db')
("Brazil","Mexico","Argentina","Venezuela") result = connection.execute(query,
; (cust_id,min_amt))
When using a list, use “in” for row in result:
SELECT FirstName, LastName, print(row)
FirstName || " "|| LastName as FullName Tuple Variables
From Employee; connection = sqlite3.connect('coke.db')
New column -> column1 || " " || column2 as newname cust_name = input("Enter all or part of a
SELECT id, ProductName customer name: ")
From Product result = connection.execute("SELECT * FROM
Where ProductName like '%queso%'; Customer WHERE Contact LIKE ?;",
Name has string in it, use “like” and “% %” ('%'+cust_name+'%',))
for row in result:
SELECT Country, City, count(*)
print(row)
FROM Customer connection.close()
GROUP BY Country, City;
OR
Total number of customers per country and city.
connection = sqlite3.connect('coke.db')
Select count(*)
cust_name = input("Enter all or part of a
From orders
Where ShippedDate like '%2013-03%'; customer name: ")
Count the number of orders shipped in March of 2013 query = """SELECT * FROM Customer WHERE
Select product.Id, Product.ProductName, Contact LIKE ?;"""
supplier.CompanyName, Category.CategoryName result = connection.execute(query,
From product JOIN Supplier ('%'+cust_name+'%',))
On product.SupplierId = supplier.Id for row in result:
Join Category
On product.CategoryId = Category.Id print(row)
Order by product.Id; connection.close()
Like Operator
Select Category.CategoryName, count(*) as
NumProd fish = ['trout', 'mackerel', 'sole',
From Product Join Category 'walleye']
On product.CategoryId = Category.Id for species in fish:
Group by CategoryName print(f"The word {species} has
Order by NumProd DESC; {len(species)} letters.")
Loop that loops by index
SELECT employees.first_name, for index in range(len(fish)):
employees.last_name, employees.department_id,
print(f"The word {fish[index]} has
departments.depart_name
From employees LEFT JOIN departments {len(fish[index])} letters.")
On employees.department_id = While loop
departments.department_id; index = 0
List the names and department ID for all employees, along while index < len(fish):
with the department name "if it's known." print(f"The word {fish[index]} has
Wants all employees even if some missing - LEFT JOIN {len(fish[index])} letters.")
import sqlite3 index +=1
connection = sqlite3.connect('coke.db') Returns sum of 1-digit, 2-digit, 3-digit
result = connection.execute('SELECT * From def twosums(integer_list):
OrderData;') list1 = []
for row in result: list2 = []
print(row) list3 = []
connection.close() for number in integer_list:
Basics of connecting a database if number < 10:
cust_id = input("Enter a customer ID. ") list1.append(number)
connection = sqlite3.connect('coke.db') elif 10 <= number <= 99:
result = connection.execute('SELECT * FROM list2.append(number)
OrderData WHERE customerID = ?;', (cust_id,)) else:
for row in result: list3.append(number)
print(row) return sum(list1), sum(list2), sum(list3)
owners
Best_grade that takes dictionary and returns highest Interleave lists
{'name':"Wanda", 'grades':[98,72,83]} def interleave_lists(first, second):
returns {'name':"Wanda", 'best grade':98} smaller = min(len(first), len(second))
def best_grade(mydict): newlist = []
d = {}
d['name'] = mydict['name'] for index in range(smaller):
d['grades'] = max(mydict['grades']) newlist.append(first[index])
return d newlist.append(second[index])
If letter in word in sentence, return True newlist += first[smaller:]
def numtimes(string, letter): newlist += second[smaller:]
string = string.lower() return newlist
boolean = [] Flip problem
if string: def flip_d(d):
wordlist = string.split(" ") newd = {}
for word in wordlist: for key, value in d.items():
boolean.append(letter in word) if value not in newd:
return boolean newd[value] = [key]
If string in sentence, return sentence else:
import re newd[value].append(key)
def first_sen(s, w): return newd
regex = f'([A-Z][A-Za-z ]*{w}[A-Za-z ]*\.)' Rock, paper, scissors
regex_c = re.compile(regex) def calc_score(round):
match = regex_c.search(s) a, b, t = (0,0,0) #track number
if match: for match in round:
return match.group() if (match[0] == "P" and match[1] ==
else: "R") | (match[0] == "S" and match[1] ==
return "" "P") | (match[0] == "R" and match[1] ==
Fraction list "S"):
def min_max_fractions(flist): a += 1
num, denom = flist[0].split("/") elif match[0] == match[1]:
num = int(num) t += 1
denom = int(denom)
else: #otherwise Benson wins
minval = num/denom b += 1
minfrac = flist[0]
maxval = num/denom if a > b:
maxfrac = flist[0] return "Abigail"
elif b > a:
for fraction in flist:
return "Benson"
num, denom = fraction.split("/")
num = int(num) else:
denom = int(denom) return "Tie"
Games
val = num/denom
if val < minval:
d = {}
minval = val for element in games:
minfrac = fraction game = element[0]
if val > maxval: friend = element[1]
maxval = val amt = float(element[2])
maxfrac = fraction if friend not in d:
d[friend] = {'games':[game],
return (minfrac, maxfrac) 'amount spent':amt}
File name owner else:
import re d[friend]['games'].append(game)
f = open("files.txt", "r") d[friend]['amount spent'] += amt
regex = '([\w ]+)[,:]? \w+\.[Xx][Ll][Ss][Xx]?' When Boolean, initialize variable
regex_c = re.compile(regex) mylist = [2, 4, 4, 2, 2, 3]
owners = [] double2 = False
for line in f: for index in range(len(mylist)-1):
match_obj = regex_c.search(line) if mylist[index] == mylist[index+1] ==
if match_obj: 2:
name = match_obj.group(1) double2 = True
owners.append(name) double2
Time regex = "(0\d|1\d|2[0-3]):[0-5]\d"