Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
smhuda
GitHub Repository: smhuda/python-pcep-notes
Path: blob/main/Module 4.ipynb
77 views
Kernel: Python 3

Datastructures

  • mutable (elements can change over time)

  • immutable (elements cannot change)

Category:

  • FIFO (First in First out)

  • LIFO (Last in First out)

Type:

  • list is mutable

  • tuple is immutable

  • dictionary is mutable

  • set is mutable

a = list((1,2,3,4,5)) dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Appending

a.append(6) a
[2, 3, 4, 5, 6, 6]

Tuples

b = tuple((1,2,3,4,5)) print(b)
(1, 2, 3, 4, 5)
b.count(8)
0
b.index(3)
2
c = {'a':1,'b':2,'c':3} print (c)
{'a': 1, 'b': 2, 'c': 3}
c.get('b')
2
c.values()
dict_values([1, 2, 3])
c.keys()
dict_keys(['a', 'b', 'c'])

For Loop

for key in c: print(key, c[key])
a 1 b 2 c 3
d = {'a':[1,2,3],'b':[4,5,6],'c':[7,8,9]} print (d)
{'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}
e = [{'a':1},{'b':2},{'c':3}] print (e)
[{'a': 1}, {'b': 2}, {'c': 3}]
f = set((1,1,2,2,3,4,4,5,5)) print (f)
{1, 2, 3, 4, 5}
f.add(6) print(f)
{1, 2, 3, 4, 5, 6}
popped = f.pop() popped, f
(5, {6})

String functions

-upper()
-lower()
-capitalize()
-split()
-join()
-len()

Character functions

-chr()
-ord()

Upper case conversion

a_string = "pcEp exAm is Cool tO haVe" a_string.upper()
'PCEP EXAM IS COOL TO HAVE'
a_string
'pcEp exAm is Cool tO haVe'

Lower case conversion

a_string.lower()
'pcep exam is cool to have'

Capitalize first letter conversion

a_string.capitalize()
'Pcep exam is cool to have'

Splitting with a 'character/symbol'

a_string.split(' ')
['pcEp', 'exAm', 'is', 'Cool', 'tO', 'haVe']
a_string.split('p')
['', 'cE', ' exAm is Cool tO haVe']
b_string = "This is another string"
'-'.join([a_string, b_string])
'pcEp exAm is Cool tO haVe-This is another string'
len(a_string)
25
u = 'a'
ord(u)
97
ord('a') + 2
99
i = 112 chr(i)
'p'
chr(ord('p') + 4)
't'

Function and Generators

  • Function -> serious memory impact

  • Generators -> they minimize memory impact

Results:

  • return -> give back the processes results

  • yield -> give back one value at a time

  • Par and arg:

  • arg -> position and order matters

  • par -> like keyword arguments

def generate(number): a = list() for i in range(number): a.append(i) return a print(generate(59))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58]
def generate(number): a = list() for i in range(number): yield i print(generate(10000000))
<generator object generate at 0x7ff97003fa50>
print(None)
None
def return_none(whatever): print(whatever) a = return_none("This is whatever") a is None
This is whatever
True
def sum(a, b): return a + b sum(1,5)
6
def general(*args, **kwargs): pass general(1,b = 10)
def general(*args, **kwargs): print(args) print(kwargs)
general(1,c=11)
(1,) {'c': 11}
def general(a=10,b=11): print(a) print(b)
general(1,2)
1 2
list(generate(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a = 10 def a_function(a=11): print(a) a_function()
11

Fibonacci Series

def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n - 2) fibonacci(10)
55

Exceptions

try: raise SystemExit except Exception as e: print("This was the problem: {}".format(e))
An exception has occurred, use %tb to see the full traceback. SystemExit
/Users/smhuda/opt/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3445: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
try: raise ValueError("Value wrong") except ValueError as e: print("This was a value error") except: print("This never ecxecutes")
This was a value error
try: raise TypeError("Value wrong") except ValueError as e: print("This was a value error") except: print("This never ecxecutes")
This never ecxecutes