29

Python 101 language features and functional programming

Embed Size (px)

DESCRIPTION

Presentation reviles the syntax solution for common encountered programming challenges, gives insight in to python datatypes, and explains core design principles behind the program

Citation preview

Page 1: Python 101 language features and functional programming
Page 2: Python 101 language features and functional programming
Page 3: Python 101 language features and functional programming

SHOCKING

Page 4: Python 101 language features and functional programming
Page 5: Python 101 language features and functional programming

Reverse String – JavaScriptvar s = "This is the simple text object";

var r = "";for (var i = s.length - 1; i >= 0 ;

i--) {r += s[i];

}function reverse (s) {

return (s === '''') ? : reverse(s.substr(1)) + s.charAt(0);}

Page 6: Python 101 language features and functional programming

Reverse String – Java

String s = "This is the test";System.out.println(new StringBuilder(s).reverse().toString());

Page 7: Python 101 language features and functional programming

Reverse String – PHP

echo strrev("Hello World");

Page 8: Python 101 language features and functional programming

Reverse String – Python

s[::-1]

Page 9: Python 101 language features and functional programming

Find element in array

var zipCodes = (['90001','90002','90003']);

if ( zipCodes.indexOf('9005') > -1 ) { console.log("found") ;} else {

console.log("not Found");}

JavaScript

Page 10: Python 101 language features and functional programming

Find element in array

HashMap<Integer,String> cities = new HashMap<Integer, String>();cities.put(9000,"Gent");cities.put(9400,"Aalst");

String city = cities.get(9400);System.out.println(city);

Java

Page 11: Python 101 language features and functional programming

Find element in arrayPHP

$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;$key = array_search('red', $array); // $key = 1;

$os = array("Mac", "NT", "Irix", "Linux");

if (in_array("Irix", $os)) {    echo "Got Irix";}

Page 12: Python 101 language features and functional programming

Find element in array

element in data

Python

Page 13: Python 101 language features and functional programming
Page 14: Python 101 language features and functional programming

Design Principles• Borrow ideas whenever it make sense• As simple as possible , not simpler (Einstein)• Do one thing well (Unix)• Don’t fret abut performance (fix it later)• Don’t bother user with details• Error shouldn’t pass silently

Page 15: Python 101 language features and functional programming

Numbers

i = 45f = 3.14l = 23Lc = 2 + 4j

oct(78)hex(78)bin(-3)

a=int('01100000',2)b=int('00100110',2)bin(a&b) # '0b100000'bin(a|b)# '0b1100110'bin(a^b) # '0b1000110'

Page 16: Python 101 language features and functional programming

Data Structure - String

s = " The snake is LONG, 7 miles "

len(s)s.count("is")s.endswith("miles ")s.swapcase()s.strip()s.index("7", 5, 22)

Operations:

"A" + "b"

"snake" in s

"kilo meters" not in s / not "kilo meters" in s

s * 2

Page 17: Python 101 language features and functional programming

Data Structure – List (Array)

l = [ 3, 4, 0, 0, 5, 2, 1]k = [ 1, 2, 3, 4,5]

len(l)l.count(0)l.remove(0)l.index(4)l.append(55)

Operations:k + ll * 23 not in k / not 3 in k

0 1 2 3 4 5+---+---+---+---+---+---+| a | b | c | d | e | f |+---+---+---+---+---+---+ -6 -5 -4 -3 -2 -1

Page 18: Python 101 language features and functional programming

Data Structure – Dictionary http://svn.python.org/view/python/trunk/Objects/dictobject.c?view=markup&pathrev=53656a = dict(one=1, two=2, three=3)b = {'one': 1, 'two': 2, 'three': 3}c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))d = dict([('two', 2), ('one', 1), ('three', 3)])e = dict({'three': 3, 'one': 1, 'two': 2})

>>> a == b == c == d == e

d.items()d.keys()d.values()

Operations:

d.update(d2)

one in b

1 in a.values()

Page 19: Python 101 language features and functional programming

Data Structure – Tuple (Immutable)

t = ("a", "b", "c", "d")

t.count()t.index()

Operations:t * 2t + t"a" in t "a" not in t

Page 20: Python 101 language features and functional programming

Data Structure – Set (Immutable)

a = set([1,2,3]) b = set([2,3,4])

a.union(b)a.intersection(b)a.difference(b)

Operations:1 in s5 not in s

Page 21: Python 101 language features and functional programming

Files / Picklef = open("D:/foo.txt", "wb")

f.write("My python is longer than yours. ")

f.close()

import pickle

output = [1,2 "a", "b", "c"]

f = open('data.pk’, 'wb')

pickle.dump(output, f)

f.close()

pickle.load(open('data.pk', 'rb'))

Page 22: Python 101 language features and functional programming
Page 23: Python 101 language features and functional programming

Comprehension / Generator (Haskell)

simplifies process of iterationswords = 'The quick brown fox jumps over the lazy dog'.split()

[[word.upper(), word.lower(), len(word)] for word in words]

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

[[row[i] for row in matrix] for i in range(4)] # list comprehension

g = ([ row[i] for row in matrix ] for i in range(4)) # generator

Page 24: Python 101 language features and functional programming

Functions and F.Programming

def f1():return "function One!"

def f2():return "function Two!"

d = {"one" : f1, "two" : f2}

d["one"]()d["two"]()

Page 25: Python 101 language features and functional programming

FUNCTIONAL PROGRAMMINGIterators

http://www.youtube.com/watch?v=Ta1bAMOMFOIhttp://ua.pycon.org/static/talks/kachayev/#/28

Your Father:x = [1, 2, 3]

y = ["a", "b", "c"]

[(i,j) for i in x for j in y]

The Dude:x = [1, 2, 3]

y = ["a", "b", "c"]

t = zip(x,y)

dict(zip(x,y))

Iterators:it = iter(t)

dict(it)

Page 26: Python 101 language features and functional programming

FUNCTIONAL PROGRAMMING (LiSP)

"Lazy programmer is good programmer“ map(), filter(), reduce(), enumerate()

def up(x): return

x.upper()

map(up, ["a", "test"])

def even(x): if (x % 2) == 0:

return x

filter(even, [1, 2, 3, 4, 5, 6, 7, 8])

import operator

reduce(operator.add, [1,2,3])

for item in enumerate(["a", "b","c"]) print item

Page 27: Python 101 language features and functional programming

Lamb-daaaaahttp://www.youtube.com/watch?v=_WZwp16c4vk

Page 28: Python 101 language features and functional programming

FUNCTIONAL PROGRAMMINGhttp://ua.pycon.org/static/talks/kachayev/#/28

f = lambda x: x * 2f(2)

g = lambda x, y: x + yg(2,2)

lambs = [lambda x: x ** 2,

lambda x: x ** 3, lambda x: x ** 4]

for f in lambs: f(3)

Page 29: Python 101 language features and functional programming

Lambda + F.P. Functionsmap(lambda x: x.upper(), ["a", "test"])

filter(lambda x: (x % 2) == 0, [1,2,3,4,5,6,7,8])

[x for x in 'abracadabra' if x not in 'abc']{x for x in 'abracadabra' if x not in 'abc'}

sorted(d.items(), key=lambda i: i[1])pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]pairs.sort(key=lambda pair: pair[1])