0% found this document useful (0 votes)
22 views7 pages

Coding Functions and Techniques Guide

The document contains various Python functions and examples demonstrating list manipulation, string handling, and regular expressions. It includes functions for removing items from lists, checking for palindromes, and counting occurrences of names, as well as examples of using APIs and handling data from files. Additionally, it showcases the use of dictionaries, error handling, and regular expressions for pattern matching.

Uploaded by

delatoav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views7 pages

Coding Functions and Techniques Guide

The document contains various Python functions and examples demonstrating list manipulation, string handling, and regular expressions. It includes functions for removing items from lists, checking for palindromes, and counting occurrences of names, as well as examples of using APIs and handling data from files. Additionally, it showcases the use of dictionaries, error handling, and regular expressions for pattern matching.

Uploaded by

delatoav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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): [Link](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
[Link]("peach") add "peach" Try statements
[Link]("moose tracks") count = 0
remove "moose tracks" mylist = [4.2, "peanut butter", 8, -1]
[Link](3) remove element 3 for element in mylist:
[Link]() puts list in ASCIIbetical order try:
[Link](key = [Link]) if element <= 0:
puts list in "normal" alphabetical order print("Non-positive number
[Link](key = [Link], reverse = True) found.")
puts list in opposite alphabetical order elif element < 3:
[Link](reverse = True) count = count + 1
def next_in_line(nil_lst, nil_num): except:
copylist = nil_lst[:] print(f'Non-numeric value found')
[Link](0) print(f"The total postive integers less
[Link](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'
[Link]()
adding to dictionary
return listcopy[0], listcopy[1]
[Link]() ['hello', 'goodbye', 'peace', 'potato chips']
alist = [3,7,2,9,3]
[Link]() ['squrge', 'fillo', 'woosht', 'kloojboos']
(2, 3)
[Link]() [('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",
[Link](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 = [Link]()
[Link]() state, capital, abbrev, name =
mystring = " abc \t \n" [Link](",")
[Link]() ' abc’ if state not in states:
states[state] = {'capital':
[Link]() 'abc \t \n’
capital, 'abbrev': abbrev, 'numpres': 1}
[Link]() ‘abc’
else:
mystring2 = [Link]("\n")
states[state]['numpres'] =
mystring2 ' abc \t ' states[state]['numpres'] + 1
closing_prices = {"AAPL": [170, 166, 164, [Link]()
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”] = [Link]

sum(student[“homework”]/len(student site = '[Link]


[“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 = [Link](site, parameters)
"cover": "clouds"}, [Link] # no parentheses
"temperature" : {"current": 23, movie_data = [Link]()
"range": [12,25]} movie_data
}
weather["sky"]["type"] -> ‘overcast’ site = "[Link]
amount = 1
weather["temperature"]["range"][1] -> 25
question_difficulty = input("Choose the
f = open('[Link]', 'r') question difficulty (easy, medium, hard)")
states = {} question_type = input("Choose the question
for line in f: type (multiple choice or T/F)")
line = [Link]()
state, capital, abbrev =
[Link](",")
states[state] = {'capital': capital,
'abbrev':abbrev}
[Link]()
parameters = {'amount': amount, text_yes = "Coleman Fleming,
'difficulty':question_difficulty, fleming@[Link], 77 Primrose Ave.,
'type':question_type} Patchogue, NY 11772"
r = [Link](site, parameters) text_no = "Coleman Fleming, 77 Primrose
mydata = [Link]() Ave., Patchogue, NY 11772"
results = mydata['results'][0] regex = '\w+@\w+\.[a-z]+' regex for email address
print(f"{results['question']} \n regex_c = [Link](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([Link]())
site = fleming@[Link]
"[Link]
interested = ["Nathanael Armstrong,
shuffle = 1
armstrong2517@[Link]",
parameters = {'deck_count': shuffle}
"Luther Camacho, 847-612-9812",
r = [Link](site, parameters)
"Morgan Shields, mpossible@[Link]",
shuffle_data = [Link]()
"Dana Andersen, 770-981-0084",
deck_id = shuffle_data['deck_id']
"Valeria Schmitt, 617-552-0707",
shuffle_data
"Leland Woodard, leelo@[Link]"]
regex = "[2-9]\d\d-\d\d\d-\d\d\d\d"
site2 =
f'[Link] new_list = []
numbercards = int(input('How many cards regex_c = [Link](regex)
would you like to draw?')) for string in interested:
parameters2 = {'count': numbercards} match = regex_c.search(string)
d = [Link](site2, parameters2) if match:
card_data = [Link]() number = ([Link]())
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: fleming@[Link], 77 Primrose Ave.,
$12.34 = “\$(0|[1-9]\d*)\.\d\d” Patchogue, NY 11772"
student@[Link] = "\w+@\w+\.\w+" grouped_regex = '\w+@(\w+.[a-z]+)'
grouped_regex_c = [Link](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([Link](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” [Link]
if match:
Using regular expressions in Python print([Link]())
import re still matches the whole regular expression
Create regular expression fleming@[Link]
Convert the string to a python-recognized regex object
with [Link]()
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 = [Link](login_re) def odd3(a, b):
alist = []
f = open("[Link]", 'r') for number in range(a,b+1):
for line in f: if number%2==1:
[Link](number)
match_obj = login_re_c.search(line) if number%3!=0:
[Link](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 = [Link](-1)
text4 = """Prices are going up faster than [Link](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 = [Link](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 = [Link](",")
#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("[Link]", "r")
strikes_ex = {}
[Link] and the file for line in f:
line = [Link]()
[Link]. Move both to your course folder airport, date, type_fire = [Link](",")
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+)" [Link](reverse = True)
regex_c = [Link](regex) return newlist[1:4]
def award_data(awards):
filelist = regex_c.findall(text6) d = {}
filelist for element in awards:
winner_list = [Link](",")
[('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 [Link]()
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 = [Link]('[Link]')
("Brazil","Mexico","Argentina","Venezuela") result = [Link](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 = [Link]('[Link]')
New column -> column1 || " " || column2 as newname cust_name = input("Enter all or part of a
SELECT id, ProductName customer name: ")
From Product result = [Link]("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 [Link]()
GROUP BY Country, City;
OR
Total number of customers per country and city.
connection = [Link]('[Link]')
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 [Link], [Link], Contact LIKE ?;"""
[Link], [Link] result = [Link](query,
From product JOIN Supplier ('%'+cust_name+'%',))
On [Link] = [Link] for row in result:
Join Category
On [Link] = [Link] print(row)
Order by [Link]; [Link]()
Like Operator
Select [Link], count(*) as
NumProd fish = ['trout', 'mackerel', 'sole',
From Product Join Category 'walleye']
On [Link] = [Link] 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 = [Link]('[Link]') Returns sum of 1-digit, 2-digit, 3-digit
result = [Link]('SELECT * From def twosums(integer_list):
OrderData;') list1 = []
for row in result: list2 = []
print(row) list3 = []
[Link]() for number in integer_list:
Basics of connecting a database if number < 10:
cust_id = input("Enter a customer ID. ") [Link](number)
connection = [Link]('[Link]') elif 10 <= number <= 99:
result = [Link]('SELECT * FROM [Link](number)
OrderData WHERE customerID = ?;', (cust_id,)) else:
for row in result: [Link](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']) [Link](first[index])
return d [Link](second[index])
If letter in word in sentence, return True newlist += first[smaller:]
def numtimes(string, letter): newlist += second[smaller:]
string = [Link]() return newlist
boolean = [] Flip problem
if string: def flip_d(d):
wordlist = [Link](" ") newd = {}
for word in wordlist: for key, value in [Link]():
[Link](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 = [Link](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 [Link]() 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 = [Link]("/")
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("[Link]", "r") d[friend]['amount spent'] += amt
regex = '([\w ]+)[,:]? \w+\.[Xx][Ll][Ss][Xx]?' When Boolean, initialize variable
regex_c = [Link](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
[Link](name) double2
Time regex = "(0\d|1\d|2[0-3]):[0-5]\d"

You might also like