提交 47a213b5 编写于 作者: C Corey Schafer

Added Python code snippets

上级 df2e19b2
.DS_Store
# Video Scripts
s.txt
script.txt
class Employee:
"""A sample Employee class"""
def __init__(self, first, last):
self.first = first
self.last = last
print('Created Employee: {} - {}'.format(self.fullname, self.email))
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('John', 'Smith')
import os
os.chdir('/path/to/files/')
# Am I in the correct directory?
# print(os.getcwd())
# print(dir(os))
# Print all the current file names
for f in os.listdir():
# If .DS_Store file is created, ignore it
if f == '.DS_Store':
continue
file_name, file_ext = os.path.splitext(f)
# print(file_name)
# One way to do this
f_title, f_course, f_number = file_name.split('-')
# print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))
# Need to remove whitespace
f_title = f_title.strip()
f_course = f_course.strip()
# f_number = f_number.strip()
# Want to remove the number sign?
# f_number = f_number.strip()[1:]
# One thing I noticed about this output is that if it was sorted by filename
# then the 1 and 10 would be next to each other. How do we fix this? One way we can fix this is to pad
# the numbers. So instead of 1, we'll make it 01. If we had hundreds of files then this would maybe need to be 001.
# We can do this in Python with zfill
f_number = f_number.strip()[1:].zfill(2)
# print('{}-{}-{}{}'.format(f_number, f_course, f_title, file_ext))
# You have the power to reformat in any way you see fit
print('{}-{}{}'.format(f_number, f_title.strip(), file_ext.strip()))
new_name = '{}-{}{}'.format(file_num, file_title, file_ext)
os.rename(fn, new_name)
# print(len(os.listdir()))
function html_tag(tag){
function wrap_text(msg){
console.log('<' + tag +'>' + msg + '</' + tag + '>')
}
return wrap_text
}
print_h1 = html_tag('h1')
print_h1('Test Headline!')
print_h1('Another Headline!')
print_p = html_tag('p')
print_p('Test Paragraph!')
\ No newline at end of file
# Closures
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
def log_func(*args):
logging.info(
'Running "{}" with arguments {}'.format(func.__name__, args))
print(func(*args))
return log_func
def add(x, y):
return x+y
def sub(x, y):
return x-y
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3)
add_logger(4, 5)
sub_logger(10, 5)
sub_logger(20, 10)
INFO:root:Running "add" with arguments (3, 3)
INFO:root:Running "add" with arguments (4, 5)
INFO:root:Running "sub" with arguments (10, 5)
INFO:root:Running "sub" with arguments (20, 10)
import datetime
import pytz
# Naive
# d = datetime.date(2001, 9, 11)
tday = datetime.date.today()
# weekday() - Monday is 0 and Sunday is 6
# print(tday)
# isoweekday() - Monday is 1 and Sunday is 7
# print(tday)
# datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
tdelta = datetime.timedelta(hours=12)
# print(tday + tdelta)
# date2 = date1 + timedelta
# timedelta = date1 + date2
bday = datetime.date(2016, 9, 24)
till_bday = bday - tday
# print(till_bday.days)
t = datetime.time(9, 30, 45, 100000)
# dt = datetime.datetime.today()
# dtnow = datetime.datetime.now()
# print(dir(datetime.datetime))
# print(dt)
# print(dtnow)
dt = datetime.datetime(2016, 7, 24, 12, 30, 45, tzinfo=pytz.UTC)
# print(dir(dt))
dt_utcnow = datetime.datetime.now(tz=pytz.UTC)
# print(dt_utcnow)
dt_utcnow2 = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
# print(dt_utcnow2)
# dt_mtn = dt_utcnow.astimezone(pytz.timezone('US/Mountain'))
# print(dt_mtn)
dt_mtn = datetime.datetime.now()
mtn_tz = pytz.timezone('US/Mountain')
dt_mtn = mtn_tz.localize(dt_mtn)
# print(dt_mtn)
dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))
# print(dt_east)
print(dt_mtn.strftime('%B %d, %Y'))
dt_str = 'July 24, 2016'
dt = datetime.datetime.strptime(dt_str, '%B %d, %Y')
print(dt)
# strftime - Datetime to String
# strptime - String to Datetime
# Decorators
from functools import wraps
def my_logger(orig_func):
import logging
logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO)
@wraps(orig_func)
def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)
return wrapper
def my_timer(orig_func):
import time
@wraps(orig_func)
def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result
return wrapper
import time
@my_logger
@my_timer
def display_info(name, age):
time.sleep(1)
print('display_info ran with arguments ({}, {})'.format(name, age))
display_info('Tom', 22)
class decorator_class(object):
def __init__(self, original_function):
self.original_function = original_function
def __call__(self, *args, **kwargs):
print('call method before {}'.format(self.original_function.__name__))
self.original_function(*args, **kwargs)
# Practical Examples
def my_logger(orig_func):
import logging
logging.basicConfig(filename='{}.log'.format(orig_func.__name__), level=logging.INFO)
def wrapper(*args, **kwargs):
logging.info(
'Ran with args: {}, and kwargs: {}'.format(args, kwargs))
return orig_func(*args, **kwargs)
return wrapper
def my_timer(orig_func):
import time
def wrapper(*args, **kwargs):
t1 = time.time()
result = orig_func(*args, **kwargs)
t2 = time.time() - t1
print('{} ran in: {} sec'.format(orig_func.__name__, t2))
return result
return wrapper
import time
\ No newline at end of file
# Duck Typing and Easier to ask forgiveness than permission (EAFP)
class Duck:
def quack(self):
print('Quack, quack')
def fly(self):
print('Flap, Flap!')
class Person:
def quack(self):
print("I'm Quacking Like a Duck!")
def fly(self):
print("I'm Flapping my Arms!")
def quack_and_fly(thing):
pass
# Not Duck-Typed (Non-Pythonic)
# if isinstance(thing, Duck):
# thing.quack()
# thing.fly()
# else:
# print('This has to be a Duck!')
# LBYL (Non-Pythonic)
# if hasattr(thing, 'quack'):
# if callable(thing.quack):
# thing.quack()
# if hasattr(thing, 'fly'):
# if callable(thing.fly):
# thing.fly()
# try:
# thing.quack()
# thing.fly()
# thing.bark()
# except AttributeError as e:
# print(e)
d = Duck()
print(type(dir(d)))
#BlueBook code decryption
import sys
def sieve(n):
x = [1] * n
x[1] = 0
for i in range(2,n/2):
j = 2 * i
while j < n:
x[j]=0
j = j+i
return x
def prime(n,x):
i = 1
j = 1
while j <= n:
if x[i] == 1:
j = j + 1
i = i + 1
return i - 1
x=sieve(10000)
code = [1206,301,384,5]
key =[1,1,2,2,]
sys.stdout.write("".join(chr(i) for i in [73,83,66,78,32,61,32]))
for i in range (0,4):
sys.stdout.write(str(prime(code[i],x)-key[i]))
print
\ No newline at end of file
Currupt File!
\ No newline at end of file
try:
f = open('curruptfile.txt')
# if f.name == 'currupt_file.txt':
# raise Exception
except IOError as e:
print('First!')
except Exception as e:
print('Second')
else:
print(f.read())
f.close()
finally:
print("Executing Finally...")
print('End of program')
Test File Contents!
\ No newline at end of file
def find_index(to_search, target):
for i, value in enumerate(to_search):
if value == target:
break
else:
return -1
return i
my_list = ['Corey', 'Rick', 'John']
index_location = find_index(my_list, 'Steve')
print 'Location of target is index: {}'.format(index_location)
\ No newline at end of file
i = 1
while i <= 5:
print i
i += 1
if i == 3:
break
else:
print 'Hit the While/Else Statement!'
\ No newline at end of file
from pympler import summary, muppy
import psutil
import resource
import os
import sys
def memory_usage_psutil():
# return the memory usage in MB
process = psutil.Process(os.getpid())
mem = process.get_memory_info()[0] / float(2 ** 20)
return mem
def memory_usage_resource():
rusage_denom = 1024.
if sys.platform == 'darwin':
# ... it seems that in OSX the output is different units ...
rusage_denom = rusage_denom * rusage_denom
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rusage_denom
return mem
import mem_profile
import random
import time
names = ['John', 'Corey', 'Adam', 'Steve', 'Rick', 'Thomas']
majors = ['Math', 'Engineering', 'CompSci', 'Arts', 'Business']
print 'Memory (Before): {}Mb'.format(mem_profile.memory_usage_psutil())
def people_list(num_people):
result = []
for i in xrange(num_people):
person = {
'id': i,
'name': random.choice(names),
'major': random.choice(majors)
}
result.append(person)
return result
def people_generator(num_people):
for i in xrange(num_people):
person = {
'id': i,
'name': random.choice(names),
'major': random.choice(majors)
}
yield person
# t1 = time.clock()
# people = people_list(1000000)
# t2 = time.clock()
t1 = time.clock()
people = people_generator(1000000)
t2 = time.clock()
print 'Memory (After) : {}Mb'.format(mem_profile.memory_usage_psutil())
print 'Took {} Seconds'.format(t2-t1)
\ No newline at end of file
# def square_numbers(nums):
# for i in nums:
# yield (i*i)
# my_nums = square_numbers([1,2,3,4,5])
my_nums = (x*x for x in [1,2,3,4,5])
print list(my_nums) # [1, 4, 9, 16, 25]
# for num in my_nums:
# print num
\ No newline at end of file
nums = [1,2,3,4,5,6,7,8,9,10]
# I want 'n' for each 'n' in nums
my_list = []
for n in nums:
my_list.append(n)
print my_list
print [n for n in nums]
# I want 'n*n' for each 'n' in nums
# my_list = []
# for n in nums:
# my_list.append(n*n)
# print my_list
# Using a map + lambda
# my_list = map(lambda n: n*n, nums)
# print my_list
# I want 'n' for each 'n' in nums if 'n' is even
# my_list = []
# for n in nums:
# if n%2 == 0:
# my_list.append(n)
# print my_list
# Using a filter + lambda
# my_list = filter(lambda n: n%2 == 0, nums)
# print my_list
# I want a (letter, num) pair for each letter in 'abcd' and each number in '0123'
# my_list = []
# for letter in 'abcd':
# for num in range(4):
# my_list.append((letter,num))
# print my_list
# Dictionary Comprehensions
names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heros = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']
# print zip(names, heros)
# I want a dict{'name': 'hero'} for each name,hero in zip(names, heros)
# my_dict = {}
# for name, hero in zip(names, heros):
# my_dict[name] = hero
# print my_dict
# If name not equal to Peter
# Set Comprehensions
# nums = [1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9]
# my_set = set()
# for n in nums:
# my_set.add(n)
# print my_set
# Generator Expressions
# I want to yield 'n*n' for each 'n' in nums
nums = [1,2,3,4,5,6,7,8,9,10]
# def gen_func(nums):
# for n in nums:
# yield n*n
# my_gen = gen_func(nums)
# for i in my_gen:
# print i
\ No newline at end of file
from collections import namedtuple
# list / tuple
color = (55,155,255)
# dictionary
color = {'red': 55, 'green': 155, 'blue': 255}
# namedtuple
Color = namedtuple('Color', ['red', 'green', 'blue'])
color = Color(blue=55,green=155,red=255)
from collections import namedtuple
Color = namedtuple('Color', ['red', 'green', 'blue'])
color = Color(55,155,255)
white = Color(255,255,255)
print color.blue
\ No newline at end of file
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
print(Employee.raise_amt)
print(emp_1.raise_amt)
print(emp_2.raise_amt)
# emp_str_1 = 'John-Doe-70000'
# emp_str_2 = 'Steve-Smith-30000'
# emp_str_3 = 'Jane-Doe-90000'
# first, last, pay = emp_str_1.split('-')
# new_emp_1 = Employee(first, last, pay)
# new_emp_1 = Employee.from_string(emp_str_1)
# print(new_emp_1.email)
# print(new_emp_1.pay)
# import datetime
# my_date = datetime.date(2016, 7, 10)
# print(Employee.is_workday(my_date))
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
dev_1 = Employee('Corey', 'Schafer', 50000)
dev_2 = Employee('Test', 'Employee', 60000)
print(dev_1.email)
print(dev_2.email)
# print(dev_1.raise_amt)
# dev_1.apply_raise()
# print(dev_1.raise_amt)
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
def __repr__(self):
return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay)
def __str__(self):
return '{} - {}'.format(self.fullname(), self.email)
def __add__(self, other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname())
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'Employee', 60000)
# print(emp_1 + emp_2)
print(len(emp_1))
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('John', 'Smith')
print(emp_1.first)
print(emp_1.email)
print(emp_1.fullname)
'''
LEGB
Local, Enclosing, Global, Built-in
'''
for a in range(2):
x = 'global {}'.format(a)
def outer():
# x = 'outer x'
for b in range(3):
x = 'outer {}'.format(b)
def inner():
# x = 'inner x'
for c in range(4):
x = 'inner {}'.format(c)
print(x)
print(a, b, c)
inner()
print(x)
print(a, b)
outer()
print(x)
print(a)
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# -10,-9,-8,-7,-6,-5,-4,-3,-2,-1
# list[start:end:step]
# print my_list[::-1]
sample_url = 'http://coreyms.com'
print sample_url
# Reverse the url
# print sample_url[::-1]
# # Get the top level domain
# print sample_url[-4:]
# # Print the url without the http://
# print sample_url[7:]
# # Print the url without the http:// or the top level domain
print sample_url[7:-4]
import datetime
import pytz
a = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
b = str(a)
print 'str(a): {}'.format(str(a))
print 'str(b): {}'.format(str(b))
print
print 'repr(a): {}'.format(repr(a))
print 'repr(b): {}'.format(repr(b))
print
\ No newline at end of file
a = [1,2,3,4]
b = 'sample string'
print str(a)
print repr(a)
print str(b)
print repr(b)
\ No newline at end of file
person = {'name': 'Jenn', 'age': 23}
# sentence = 'My name is ' + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
# print(sentence)
# sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])
# print(sentence)
# sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
# print(sentence)
# tag = 'h1'
# text = 'This is a headline'
# sentence = '<{0}>{1}</{0}>'.format(tag, text)
# print(sentence)
sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
print(sentence)
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person('Jack', '33')
sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1)
print(sentence)
# sentence = 'My name is {name} and I am {age} years old.'.format(name='Jenn', age='30')
# print(sentence)
# sentence = 'My name is {name} and I am {age} years old.'.format(**person)
# print(sentence)
# for i in range(1, 11):
# sentence = 'The value is {}'.format(i)
# print(sentence)
# pi = 3.14159265
# sentence = 'Pi is equal to {}'.format(pi)
# print(sentence)
sentence = '1 MB is equal to {} bytes'.format(1000**2)
print(sentence)
import datetime
my_date = datetime.datetime(2016, 9, 24, 12, 30, 45)
# print(my_date)
# March 01, 2016
sentence = '{:%B %d, %Y}'.format(my_date)
print(sentence)
# March 01, 2016 fell on a Tuesday and was the 061 day of the year.
sentence = '{:%B %d, %Y} fell on a {} and was the {} day of the year'.format(my_date)
print(sentence)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册