Python 101 language features and functional programming

926 views
716 views

Published on

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

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
926
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
10
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Python 101 language features and functional programming

  1. 1. SHOCKING
  2. 2. Reverse String – JavaScript var 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); }
  3. 3. Reverse String – Java String s = "This is the test"; System.out.println(new StringBuilder(s).reverse().toString());
  4. 4. Reverse String – PHP echo strrev("Hello World");
  5. 5. Reverse String – Python s[::-1]
  6. 6. Find element in array JavaScript var zipCodes = (['90001','90002','90003']); if ( zipCodes.indexOf('9005') > -1 console.log("found") ; } else { console.log("not Found"); } ) {
  7. 7. Find element in array Java HashMap<Integer,String> cities = cities.put(9000,"Gent"); cities.put(9400,"Aalst"); String city = cities.get(9400); System.out.println(city); new HashMap<Integer, String>();
  8. 8. Find element in array PHP $os = array("Mac", "NT", "Irix", "Linux"); if (in_array("Irix", $os)) { echo "Got Irix"; } $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array); // $key = 1;
  9. 9. Find element in array Python element in data
  10. 10. 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
  11. 11. Numbers i f l c = = = = 45 3.14 23L 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'
  12. 12. 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
  13. 13. Data Structure – List (Array) 0 1 2 3 4 5 +---+---+---+---+---+---+ | a | b | c | d | e | f | +---+---+---+---+---+---+ -6 -5 -4 -3 -2 -1 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+l l*2 3 not in k / not 3 in k
  14. 14. Data Structure – Dictionary http://svn.python.org/view/python/trunk/O a = 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()
  15. 15. Data Structure – Tuple (Immutable) t = ("a", "b", "c", "d") t.count() t.index() Operations: t * 2 t + t "a" in t "a" not in t
  16. 16. 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 s 5 not in s
  17. 17. Files / Pickle f = 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'))
  18. 18. Comprehension / Generator (Haskell) simplifies process of iterations words = '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
  19. 19. Functions and F.Programming def f1(): return "function One!" def f2(): return "function Two!" d = {"one" : f1, "two" : f2} d["one"]() d["two"]()
  20. 20. FUNCTIONAL PROGRAMMING Iterators http://www.youtube.com/watch?v=Ta1bAMOMFOI http://ua.pycon.org/static/talks/kachayev/#/28 Your Father: The Dude: Iterators: x = [1, 2, 3] x = [1, 2, 3] it = iter(t) y = ["a", "b", "c"] y = ["a", "b", "c"] dict(it) [(i,j) for i in x for j in y] t = zip(x,y) dict(zip(x,y))
  21. 21. FUNCTIONAL PROGRAMMING (LiSP) "Lazy programmer is good programmer“ map(), filter(), reduce(), enumerate() def up(x): return x.upper() map(up, ["a", "test"]) for item in enumerate(["a", "b","c"]) print item 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])
  22. 22. Lamb-daaaaa http://www.youtube.com/watch?v=_WZwp16c4vk
  23. 23. FUNCTIONAL PROGRAMMING http://ua.pycon.org/static/talks/kachayev/#/28 f = lambda x: x * 2 f(2) g = lambda x, y: x + y g(2,2) lambs = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x ** 4] for f in lambs: f(3)
  24. 24. Lambda + F.P. Functions map(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])

×