You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importitertools# predicate functiondeftestFunction(x):
returnx<40multiple10= [10,20,30,40,50,60,70,80,90,100]
print(list(itertools.dropwhile(testFunction, multiple10))) # drops value untill predicate function returns True print(list(itertools.takewhile(testFunction, multiple10))) # takes value untill predicate function returns True
[40, 50, 60, 70, 80, 90, 100]
[10, 20, 30]
Functions
print(filter.__doc__) # documentation can be obtained from __doc__
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
defmyFunction(agr1, arg2=None):
"""myFunction(arg1, arg2=None) --> prints the args passedParameters: arg1: 1st arg. arg2: 2nd arg.Defaults to None. """print(arg1, arg2)
print(myFunction.__doc__)
myFunction(arg1, arg2=None) --> prints the args passed
Parameters:
arg1: 1st arg.
arg2: 2nd arg.Defaults to None.
Variable number arguments
defaddition(*numbers):
# numbers data type - tuplereturnsum(numbers)
print(addition(1,4))
print(addition(4,123,10))
print(addition(*[32,1234,23]))
fromcollectionsimportdefaultdictfruits= ['apple', 'pear', 'orange', 'banana',
'apple', 'grape', 'banana', 'banana']
# intializes initial value to int default value 0fruitCounter=defaultdict(int)
# intializes initial value to 100# fruitCounter = defaultdict(lambda: 100)# Count the elements in the listforfruitinfruits:
fruitCounter[fruit] +=1# print the resultfor (k, v) infruitCounter.items():
print(k+": "+str(v))
fromcollectionsimportCounter# list of students in class 1class1= ["Bob", "James", "Chad", "Darcy", "Penny", "Hannah""Kevin", "James", "Melanie", "Becky", "Steve", "Frank"]
# list of students in class 2class2= ["Bill", "Barry", "Cindy", "Debbie", "Frank",
"Gabby", "Kelly", "James", "Joe", "Sam", "Tara", "Ziggy"]
# Create a Counter for class1 and class2c1=Counter(class1)
c2=Counter(class2)
# How many students in class 1 named James?print(c1["James"])
# How many students are in class 1?print(sum(c1.values()), "students in class 1")
# Combine the two classesc1.update(class2)
print(sum(c1.values()), "students in class 1 and 2")
# What's the most common name in the two classes?print(c1.most_common(3))
# Separate the classes againc1.subtract(class2)
print(c1.most_common(1))
# What's common between the two classes?print(c1&c2)
2
11 students in class 1
23 students in class 1 and 2
[('James', 3), ('Frank', 2), ('Bob', 1)]
[('James', 2)]
Counter({'James': 1, 'Frank': 1})
Collections - ordered dict
fromcollectionsimportOrderedDict# list of sport teams with wins and lossessportTeams= [("Royals", (18, 12)), ("Rockets", (24, 6)),
("Cardinals", (20, 10)), ("Dragons", (22, 8)),
("Kings", (15, 15)), ("Chargers", (20, 10)),
("Jets", (16, 14)), ("Warriors", (25, 5))]
# sort the teams by number of winssortedTeams=sorted(sportTeams, key=lambdat: t[1][0], reverse=True)
# create an ordered dictionary of the teamsteams=OrderedDict(sortedTeams)
print(teams)
# Use popitem to remove the top itemtm, wl=teams.popitem(False)
print("Top team: ", tm, wl)
# What are next the top 4 teams?fori, teaminenumerate(teams, start=1):
print(i, team)
ifi==4:
break# test for equalitya=OrderedDict({"a": 1, "b": 2, "c": 3})
b=OrderedDict({"a": 1, "c": 3, "b": 2})
print("Equality test: ", a==b)
importcollectionsimportstring# initialize a deque with lowercase lettersd=collections.deque(string.ascii_lowercase)
# deques support the len() functionprint("Item count: "+str(len(d)))
# deques can be iterated overforelemind:
print(elem.upper(), end=",")
# manipulate items from either endd.pop()
d.popleft()
d.append(2)
d.appendleft(1)
print("\n\nAfter poping and appending - {0}".format(d))
# rotate the dequeprint("\nBefore rotating - {0}".format(d))
d.rotate(1)
print("\nAfter rotating by 1 - {0}".format(d))
fromenumimportEnum, unique, auto@unique#value should be uniqueclassFruit(Enum):
APPLE=1BANANA=2ORANGE=3TOMATO=4PEAR=auto()
# enums have human-readable values and typesprint(Fruit.APPLE)
print(type(Fruit.APPLE))
print(repr(Fruit.APPLE))
# enums have name and value propertiesprint(Fruit.APPLE.name, Fruit.APPLE.value)
# print the auto-generated valueprint(Fruit.PEAR.value)
# enums are hashable - can be used as keysmyFruits= {}
myFruits[Fruit.BANANA] ="Come Mr. Tally-man"print(myFruits[Fruit.BANANA])
Fruit.APPLE
<enum 'Fruit'>
<Fruit.APPLE: 1>
APPLE 1
5
Come Mr. Tally-man
Class - Strings
#customize string representations of objectsclassPerson():
def__init__(self):
self.fname="Joe"self.lname="Marini"self.age=25# use __repr__ to create a string useful for debuggingdef__repr__(self):
return"<Person Class - fname:{0}, lname:{1}, age{2}>".format(self.fname, self.lname, self.age)
# use str for a more human-readable stringdef__str__(self):
return"Person ({0} {1} is {2})".format(self.fname, self.lname, self.age)
# use bytes to convert the informal string to a bytes objectdef__bytes__(self):
returnbytes(self.__str__().encode('utf-8'))
# create a new Person objectcls1=Person()
# use different Python functions to convert it to a stringprint(repr(cls1))
print(str(cls1))
print("Formatted: {0}".format(cls1))
print(bytes(cls1))
<Person Class - fname:Joe, lname:Marini, age25>
Person (Joe Marini is 25)
Formatted: Person (Joe Marini is 25)
b'Person (Joe Marini is 25)'
Class - Class Attribute Functions
Attribute Function
Called When
Description
object.getattribute(Self, attr)
object.attr
is called every time when a attribute is requested (default behaviour)
object.getattr(Self, attr)
object.attr
is called only when the attribyte cannot be found on the object
object.setattr(self, attr, val)
object.attr = val
is called when a attribute is set
object.delattr(Self)
del object.attr
is called when a attribute is deleted
object.dir(self)
dir(object)
when dir(object) is called
# customize string representations of objectsclassmyColor():
def__init__(self):
self.red=50self.green=75self.blue=100# use getattr to dynamically return a valuedef__getattr__(self, attr):
ifattr=="rgbcolor":
return (self.red, self.green, self.blue)
elifattr=="hexcolor":
return"#{0:02x}{1:02x}{2:02x}".format(self.red, self.green, self.blue)
else:
raiseAttributeError# use setattr to dynamically return a valuedef__setattr__(self, attr, val):
ifattr=="rgbcolor":
self.red=val[0]
self.green=val[1]
self.blue=val[2]
else:
super().__setattr__(attr, val)
# use dir to list the available propertiesdef__dir__(self):
return ("red", "green", "blue", "rgbolor", "hexcolor")
# create an instance of myColorcls1=myColor()
# print the value of a computed attributeprint(cls1.rgbcolor)
print(cls1.hexcolor)
# set the value of a computed attributecls1.rgbcolor= (125, 200, 86)
print("\nAfter changing {0}".format(cls1.rgbcolor))
print(cls1.hexcolor)
# access a regular attributeprint(cls1.red)
# list the available attributesprint("dir - list all attributes {0}".format(dir(cls1)))
(50, 75, 100)
#324b64
After changing (125, 200, 86)
#7dc856
125
dir - list all attributes ['blue', 'green', 'hexcolor', 'red', 'rgbolor']
Class - Comparision
# Use special methods to compare objects to each otherclassEmployee():
def__init__(self, fname, lname, level, yrsService):
self.fname=fnameself.lname=lnameself.level=levelself.seniority=yrsService# implement comparison functions by emp leveldef__ge__(self, other):
ifself.level==other.level:
returnself.seniority>=other.seniorityreturnself.level>=other.leveldef__gt__(self, other):
ifself.level==other.level:
returnself.seniority>other.seniorityreturnself.level>other.leveldef__lt__(self, other):
ifself.level==other.level:
returnself.seniority<other.seniorityreturnself.level<other.leveldef__le__(self, other):
ifself.level==other.level:
returnself.seniority<=other.seniorityreturnself.level<=other.leveldef__eq__(self, other):
returnself.level==other.level# define some employeesdept= []
dept.append(Employee("Tim", "Sims", 5, 9))
dept.append(Employee("John", "Doe", 4, 12))
dept.append(Employee("Jane", "Smith", 6, 6))
dept.append(Employee("Rebecca", "Robinson", 5, 13))
dept.append(Employee("Tyler", "Durden", 5, 12))
# Who's more senior?print(bool(dept[0] >dept[2]))
print(bool(dept[4] <dept[3]))
# sort the itemsemps=sorted(dept)
print("Employees sorted by level, seniority : {0}".format([emp.fnameforempinemps]))
General information about program execution results
WARNING
logging.warning()
Something unexpected, or an approaching problem
ERROR
logging.error()
Unable to perform a specific operation due to problem
CRITICAL
logging.critical()
Program may not be able to continue, serious error
By default only level after warning will be logged but it can be altered by specifing logging.basicConfig(level=logging.DEBUG)
importlogging# Use basicConfig to configure logging# this is only executed once, subsequent calls to# basicConfig will have no effectlogging.basicConfig(level=logging.DEBUG,
filemode="w",
filename="output.log")
# Try out each of the log levelslogging.debug("This is a debug-level log message")
logging.info("This is an info-level log message")
logging.warning("This is a warning-level message")
logging.error("This is an error-level message")
logging.critical("This is a critical-level message")
# Output formatted string to the loglogging.info("Here's a {} variable and an int: {}".format("string", 10))
Comprehensions - List
# define two lists of numbersevens= [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
odds= [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Perform a mapping and filter function on a listevenSquared=list(
map(lambdae: e**2, filter(lambdae: e>4ande<16, evens)))
print("Without List comprehension {0}".format(evenSquared))
# Limit the items operated on with a predicate conditionoddSquared= [e**2foreinoddsife>3ande<17]
print("With List comprehension {0}".format(oddSquared))
Without List comprehension [36, 64, 100, 144, 196]
WIth List comprehension [25, 49, 81, 121, 169, 225]
Comprehensions - Dict
# define a list of temperature valuesctemps= [0, 12, 34, 100]
# Use a comprehension to build a dictionarytempDict= {t: (t*9/5) +32fortinctempsift<100}
print(tempDict)
print(tempDict[12])
# Merge two dictionaries with a comprehensionteam1= {"Jones": 24, "Jameson": 18, "Smith": 58, "Burns": 7}
team2= {"White": 12, "Macke": 88, "Perce": 4}
newTeam= {k: vforteamin (team1, team2) fork, vinteam.items()}
print(newTeam)
# define a list of temperature data pointsctemps= [5, 10, 12, 14, 10, 23, 41, 30, 12, 24, 12, 18, 29]
# build a set of unique Fahrenheit temperaturesftemps1= [(t*9/5) +32fortinctemps]
ftemps2= {(t*9/5) +32fortinctemps}
print(ftemps1)
print(ftemps2)
# build a set from an input sourcesTemp="The quick brown fox jumped over the lazy dog"chars= {c.upper() forcinsTempifnotc.isspace()}
print(chars)