Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test #10

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
304 changes: 304 additions & 0 deletions Day_6/.ipynb_checkpoints/Day_6_slides-checkpoint.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Q&A\n",
"\n",
"# checkup\n",
"<div class=\"incremental\">\n",
"- `.get()`?\n",
"- What can be a key in a dictionary?\n",
"- What can be a value in a dictionary?\n",
"- What does `.format()` do?\n",
"- Instead of `file_handle = open(file, mode)` we can use?\n",
"- How do you add an element to a list?\n",
"- What is a traceback?\n",
"- What kind of exception occurs when you access an index in a list that doesn’t exist?\n",
"- How do you delete an element in a list?\n",
"- How do you convert a list to a string?\n",
"</div>\n",
"\n",
"<div class=\"incremental\">\n",
"- `enumerate()`?\n",
" - `help(enumerate)`\n",
"\n",
" ~~~ {.sourceCode}\n",
" class enumerate(object)\n",
" | enumerate(iterable[, start]) -> iterator for index, value of iterable\n",
" | \n",
" | Return an enumerate object. iterable must be another object that supports\n",
" | iteration. The enumerate object yields pairs containing a count (from\n",
" | start, which defaults to zero) and a value yielded by the iterable argument.\n",
" | enumerate is useful for obtaining an indexed list:\n",
" | (0, seq[0]), (1, seq[1]), (2, seq[2]), ...\n",
" ~~~\n",
"\n",
" - Example:\n",
"\n",
" ~~~ {.sourceCode}\n",
" >>> courses = [\"Info202\", \"Info206\", \"Info203\", \"Info205\"]\n",
" >>> list(enumerate(courses))\n",
" [(0, 'Info202'), (1, 'Info206'), (2, 'Info203'), (3, 'Info205')]\n",
" >>> \n",
" >>> for n, course in enumerate(courses):\n",
" ... print(\"Idx: {}\\tClass: {}\".format(n, course))\n",
" ... \n",
" Idx: 0 Class: Info202\n",
" Idx: 1 Class: Info206\n",
" Idx: 2 Class: Info203\n",
" Idx: 3 Class: Info205 \n",
" ~~~\n",
"\n",
"- `.get()`?\n",
" - `help(dict.get)`\n",
"\n",
" ~~~ {.sourceCode}\n",
" get(...)\n",
" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.\n",
" ~~~\n",
" \n",
"# Stuff we didn't get to yesterday.\n",
"\n",
"- `zip()`?\n",
" - `help(zip)`\n",
"\n",
" ```bash\n",
" class zip(object)\n",
" | zip(iter1 [,iter2 [...]]) --> zip object\n",
" | \n",
" | Return a zip object whose .__next__() method returns a tuple where\n",
" | the i-th element comes from the i-th iterable argument. The .__next__()\n",
" | method continues until the shortest iterable in the argument sequence\n",
" | is exhausted and then it raises StopIteration.\n",
" ```\n",
"\n",
" - Example:\n",
"\n",
" ```bash\n",
" >>> courses = [\"Info202\", \"Info206\", \"Info203\", \"Info205\"]\n",
" >>> profs = [\"David Bamman\", \"Paul Laskowski\", \"Jenna Burrell\", \"Deirdre Mulligan\"]\n",
" >>> \n",
" >>> for course, prof in zip(courses, profs):\n",
" ... print(\"{} is taught by {}\".format(course, prof))\n",
" ... \n",
" Info202 is taught by David Bamman\n",
" Info206 is taught by Paul Laskowski\n",
" Info203 is taught by Jenna Burrell\n",
" Info205 is taught by Deirdre Mulligan\n",
" ```\n",
"\n",
"- pattern: `[(b, a) for a, b in lst]`\n",
"\n",
" ```bash\n",
" >>> profs_courses = list(zip(courses, profs))\n",
" >>> profs_courses\n",
" [('Info202', 'David Bamman'), ('Info206', 'Paul Laskowski'), ('Info203', 'Jenna Burrell'), ('Info205', 'Deirdre Mulligan')]\n",
" >>> profs_courses = [(prof, course) for course, prof in profs_courses]\n",
" >>> profs_courses\n",
" [('David Bamman', 'Info202'), ('Paul Laskowski', 'Info206'), ('Jenna Burrell', 'Info203'), ('Deirdre Mulligan', 'Info205')]\n",
" ```\n",
"\n",
"- `.setdefault()`?\n",
" - `help(dict.setdefault)`\n",
"\n",
" ```bash\n",
" setdefault(...)\n",
" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D\n",
" ```\n",
"\n",
" - Example:\n",
" \n",
" \n",
"```python\n",
" with open('pledge.txt', 'r') as fin: # Get the pledge.txt open\n",
" text = fin.read()\n",
"\n",
" words = [w.lower() for w in text.strip().split()] # Get the words lowercase\n",
"\n",
"\n",
" # Create a dictionery to log the words for each letter used\n",
"\n",
" letter_d = dict()\n",
" for word in words:\n",
" initial_letter = word[0]\n",
" letter_d.setdefault(initial_letter, []).append(word)\n",
"\n",
"\n",
" # Define top as the ten most frequent initial letters\n",
"\n",
" top = sorted([(len(words), initial_letter) for initial_letter, words in\n",
" letter_d.items()], reverse=True)[:10]\n",
"\n",
"\n",
" # Print the top most frequent nicely formatted, with the words for the most\n",
" # common listed out\n",
"\n",
" for count, initial_letter in top:\n",
" print(\"{} : {} times\".format(initial_letter, count))\n",
" if top.index((count, initial_letter)) == 0:\n",
" print(\"\\t\", \", \".join(letter_d[initial_letter]))\n",
"\n",
" ```\n",
"\n",
"- `defauldict`\n",
" - Example:\n",
" \n",
" ```python\n",
" >>> from collections import defaultdict\n",
" >>> d = defaultdict(list)\n",
" >>> d[\"Daniel\"].extend([\"fairness\", \"criticism\", \"appeal\"])\n",
" >>> d[\"Daniel\"]\n",
" ['fairness', 'criticism', 'appeal']\n",
" >>> d[\"Daniel\"].append(\"human dignity\")\n",
" >>> d[\"Daniel\"]\n",
" ['fairness', 'criticism', 'appeal', 'human dignity']\n",
" ```\n",
"\n",
"- `Counter`\n",
"\n",
" - Example:\n",
" \n",
" ```python\n",
" >>> from collections import Counter\n",
" >>> text = \"A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.\"\n",
" >>> c = Counter(text.split())\n",
" >>> c\n",
" Counter({'is': 3, 'are': 3, 'to': 2, 'or': 2, 'as': 2, 'dictionary': 2, 'stored': 2, 'Counter': 2, 'counts.': 1, 'a': 1, 'Counts': 1, 'dict': 1, 'counting': 1, 'A': 1, 'unordered': 1, 'class': 1, 'integer': 1, 'It': 1, 'value': 1, 'any': 1, 'The': 1, 'multisets': 1, 'in': 1, 'other': 1, 'an': 1, 'and': 1, 'collection': 1, 'keys': 1, 'for': 1, 'where': 1, 'their': 1, 'similar': 1, 'counts': 1, 'subclass': 1, 'allowed': 1, 'hashable': 1, 'be': 1, 'values.': 1, 'including': 1, 'elements': 1, 'languages.': 1, 'objects.': 1, 'zero': 1, 'negative': 1, 'bags': 1})\n",
" >>> c['dictionary']\n",
" 2\n",
" >>> c['information']\n",
" 0\n",
" ```\n",
"------------------\n",
"\n",
"## sorting\n",
"- <https://developers.google.com/edu/python/sorting>\n",
"\n",
"```python\n",
"a = [5, 1, 4, 3]\n",
"print(sorted(a)) # [1, 3, 4, 5]\n",
"print(a) # [5, 1, 4, 3]\n",
"\n",
"strs = ['aa', 'BB', 'zz', 'CC']\n",
"print(sorted(strs)) # ['BB', 'CC', 'aa', 'zz'] (case sensitive)\n",
"print(sorted(strs, reverse=True)) # ['zz', 'aa', 'CC', 'BB']\n",
"\n",
"\n",
"strs = ['ccc', 'aaaa', 'd', 'bb']\n",
"print(sorted(strs, key=len)) # ['d', 'bb', 'ccc', 'aaaa']\n",
"\n",
"\n",
"# \"key\" argument specifying str.lower function to use for sorting\n",
"\n",
"print(sorted(strs, key=str.lower)) # ['aa', 'BB', 'CC', 'zz']\n",
"\n",
"\n",
"# Say we have a list of strings we want to sort by the last letter of the\n",
"# string.\n",
"\n",
"strs = ['xc', 'zb', 'yd', 'wa']\n",
"\n",
"\n",
"# Write a little function that takes a string, and returns its last letter.\n",
"# This will be the key function (takes in 1 value, returns 1 value).\n",
"\n",
"def fun1(s):\n",
" return s[-1]\n",
"\n",
"\n",
"# Now pass key=MyFn to sorted() to sort by the last letter:\n",
"\n",
"print(sorted(strs, key=fun1)) # ['wa', 'zb', 'xc', 'yd']\n",
"```\n",
"\n",
"- <https://wiki.python.org/moin/HowTo/Sorting>\n",
"\n",
"- `itemgetter`\n",
" - Example:\n",
"\n",
" ```bash\n",
" from operator import itemgetter\n",
"\n",
" student_tuples = [\n",
" ('john', 'B', 9),\n",
" ('jane', 'A', 12),\n",
" ('dave', 'B', 10)]\n",
"\n",
" print(sorted(student_tuples, key=itemgetter(2)))\n",
"\n",
" # Alternatively w/ lambda\n",
" print(sorted(student_tuples, key=lambda x: x[2]))\n",
"\n",
" print(sorted(student_tuples, key=itemgetter(1, 2)))\n",
"\n",
" # Alternatively w/ lambda\n",
" print(sorted(student_tuples, key=lambda x: (x[1], x[2])))\n",
" ```\n",
"\n",
"- `__getitem__`\n",
" - Example:\n",
"\n",
" ```bash\n",
" >>> students = ['dave', 'john', 'jane']\n",
" >>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}\n",
" >>> sorted(students, key=newgrades.__getitem__)\n",
" ['jane', 'dave', 'john']\n",
" ```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Final Lab"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"# OOP - Object-oriented programming\n",
"\n",
"# Classes\n",
"- base class: Student\n",
" - 2 Student attributes\n",
" - 1 Student method\n",
" - 2 subclasses\n",
" - 1 attribute each\n",
" - 1 method each\n",
" - instantiate 2 instances per subclass\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
2 changes: 1 addition & 1 deletion Day_6/Day_6_slides.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
"version": "3.7.3"
}
},
"nbformat": 4,
Expand Down
68 changes: 68 additions & 0 deletions myFile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
print ("this is my file")

x = 15
y = 3
z = "this is a string"
print ("x/y = ", x/y)
print (z)

a = "hello"
b = "world"
c = "again"
print (a, b, c)

for i in range (0, 50, 5):
print (i)

myList = [1,2,3,4,5]

for i in myList:
print (i)

def myPrint (words):
print (words, ", ok.")
myPrint ("are you")

##Recusion is good for repeating complex codes, but for loop is clearer.
def myRecursiveFunction(start, vList, step):
if len(vList) > start + step:
print(vList[step])
vList.pop()
myRecursiveFunction(start, vList, step)

while(x>0):
print(x)
x = x-1

#August 4, Sunday
aList = [1,2,3, "pop", "sunday"]

# for item in aList:
# print(item)
# if item == "sunday":
# print ("yay")

# def my_cool_function(param1, param2, param3, param4, param5, param6)

# add # for every line of a paragraph, use short cut command /

import sys
def main():
print(sys.argv, type(sys.argv))
print(len(sys.argv))
print(sys.argv[0])
print(sys.argv[1])

# '__main__' is the name of the scope in which top-level code executes.
# Basically you have two ways of using a Python module: Run it directly as a script, or import it.
# When a module is run as a script, its __name__ is set to __main__

def argument_test():
print(sys.argv, type(sys.argv))
print(len(sys.argv))
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2], type(sys.argv[2]))

if __name__ == '__main__':
argument_test()