Intermediate Python

http://book.pythontips.com/en/latest/index.html

Map Function

In [2]:
a = [1,2,3,4,5,6,7,8,9,10]
list(map(lambda x: x*2, a))
Out[2]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Filter

In [85]:
nums = range(-5,5)
odds = list(filter(lambda x: x % 2 == 1, nums))
print(odds)
[-5, -3, -1, 1, 3]

Lambdas

In [4]:
add = lambda x,y: x + y
print(add(10,5))
15

Crypto

In [18]:
from hashlib import *
h8 = sha256("hello".encode('utf-8'))
print(h8.name)
print(h8.block_size)
print(h8.hexdigest())
print(h8.digest_size)

h16 = sha256("hello".encode('utf-16'))
print(h16.name)
print(h16.block_size)
print(h16.hexdigest())
print(h16.digest_size)

with open('testfile.txt','r') as f:
    testfile = f.read()

with open('testfile2.txt','r') as f:
    testfile2 = f.read()
    
testfile.encode('utf-8')
hashFile = sha256(testfile.encode('utf-8'))
print(hashFile.hexdigest())

testfile.encode('utf-8')
hashFile = sha256(testfile2.encode('utf-8'))
print(hashFile.hexdigest())
sha256
64
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
32
sha256
64
59ee1f6b483cce7e5e1c7a10c1fd65395e18cb04f48a00ee386b8b3e4202e7be
32
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
e2cc3e2c114e8ce66c762c6e2232d435193a58e7fff9ede1a7c8a7397bf58f44

*args and **kwargs

In [19]:
def test_var_args(f_arg, *argv):
    print('first normal arg: ', f_arg)
    for arg in argv:
        print('another arg through *argv:', arg)

test_var_args('nick', 'argshere', 12345, 'works w/ numbers')
first normal arg:  nick
another arg through *argv: argshere
another arg through *argv: 12345
another arg through *argv: works w/ numbers
In [20]:
def say_hi(**kwargs):
    for k,v in kwargs.items():
        print('{0} = {1}'.format(k,v))
say_hi(name="nikoli", age=30, hi=99)
age = 30
hi = 99
name = nikoli
In [21]:
def test_args_kwargs(arg1, arg2, arg3):
    print('arg1:', arg1)
    print('arg2:', arg2)
    print('arg3:', arg3)
    
tup = ('two',3,5)

kwargs = {"arg3":3,"arg2":"two","arg1":5}

test_args_kwargs(*tup)
print('---')
test_args_kwargs(**kwargs)
arg1: two
arg2: 3
arg3: 5
---
arg1: 5
arg2: two
arg3: 3
In [ ]: