SlideShare a Scribd company logo
1 of 29
SHOCKING
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);
}
Reverse String – Java
String s = "This is the test";
System.out.println(new StringBuilder(s).reverse().toString());
Reverse String – PHP
echo strrev("Hello World");
Reverse String – Python
s[::-1]
Find element in array
JavaScript
var zipCodes = (['90001','90002','90003']);
if ( zipCodes.indexOf('9005') > -1
console.log("found") ;
} else {
console.log("not Found");
}

) {
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>();
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;
Find element in array
Python
element

in

data
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
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'
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
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
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()
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
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
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'))
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
Functions and F.Programming
def f1():
return "function One!"
def f2():
return "function Two!"
d = {"one" : f1, "two" : f2}
d["one"]()
d["two"]()
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))
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])
Lamb-daaaaa

http://www.youtube.com/watch?v=_WZwp16c4vk
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)
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])

More Related Content

What's hot

Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonakaptur
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & howlucenerevolution
 
20170714 concurrency in julia
20170714 concurrency in julia20170714 concurrency in julia
20170714 concurrency in julia岳華 杜
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...akaptur
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python Chetan Giridhar
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 
Functional perl
Functional perlFunctional perl
Functional perlErrorific
 
Recursion and Functional Programming
Recursion and Functional ProgrammingRecursion and Functional Programming
Recursion and Functional Programmingsathish316
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance PythonIan Ozsvald
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rathSANTOSH RATH
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理rfyiamcool
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 

What's hot (20)

Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPythonByterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
Byterun, a Python bytecode interpreter - Allison Kaptur at NYCPython
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
20170714 concurrency in julia
20170714 concurrency in julia20170714 concurrency in julia
20170714 concurrency in julia
 
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
Allison Kaptur: Bytes in the Machine: Inside the CPython interpreter, PyGotha...
 
Recognize Godzilla
Recognize GodzillaRecognize Godzilla
Recognize Godzilla
 
Diving into byte code optimization in python
Diving into byte code optimization in python Diving into byte code optimization in python
Diving into byte code optimization in python
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Functional perl
Functional perlFunctional perl
Functional perl
 
Recursion and Functional Programming
Recursion and Functional ProgrammingRecursion and Functional Programming
Recursion and Functional Programming
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
Euro python2011 High Performance Python
Euro python2011 High Performance PythonEuro python2011 High Performance Python
Euro python2011 High Performance Python
 
Rkf
RkfRkf
Rkf
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Clojure
ClojureClojure
Clojure
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
python高级内存管理
python高级内存管理python高级内存管理
python高级内存管理
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 

Viewers also liked

Military secrets
Military secretsMilitary secrets
Military secretswhkrueg
 
Africananimals 110517215651-phpapp01
Africananimals 110517215651-phpapp01Africananimals 110517215651-phpapp01
Africananimals 110517215651-phpapp01Geraldine Salazar
 
Mias presentation av kvalitativa undersökningar
Mias presentation av kvalitativa undersökningarMias presentation av kvalitativa undersökningar
Mias presentation av kvalitativa undersökningarmariajohansson1
 

Viewers also liked (6)

Military secrets
Military secretsMilitary secrets
Military secrets
 
Jk
JkJk
Jk
 
Vanessa
VanessaVanessa
Vanessa
 
Spotify Apps
Spotify AppsSpotify Apps
Spotify Apps
 
Africananimals 110517215651-phpapp01
Africananimals 110517215651-phpapp01Africananimals 110517215651-phpapp01
Africananimals 110517215651-phpapp01
 
Mias presentation av kvalitativa undersökningar
Mias presentation av kvalitativa undersökningarMias presentation av kvalitativa undersökningar
Mias presentation av kvalitativa undersökningar
 

Similar to Python 101 language features and functional programming

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7decoupled
 
C Code and the Art of Obfuscation
C Code and the Art of ObfuscationC Code and the Art of Obfuscation
C Code and the Art of Obfuscationguest9006ab
 
Modern technologies in data science
Modern technologies in data science Modern technologies in data science
Modern technologies in data science Chucheng Hsieh
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basicsopenbala
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
 

Similar to Python 101 language features and functional programming (20)

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
C Code and the Art of Obfuscation
C Code and the Art of ObfuscationC Code and the Art of Obfuscation
C Code and the Art of Obfuscation
 
Modern technologies in data science
Modern technologies in data science Modern technologies in data science
Modern technologies in data science
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
Vcs16
Vcs16Vcs16
Vcs16
 
Spark_Documentation_Template1
Spark_Documentation_Template1Spark_Documentation_Template1
Spark_Documentation_Template1
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Practical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan HodorogPractical Functional Programming Presentation by Bogdan Hodorog
Practical Functional Programming Presentation by Bogdan Hodorog
 
Scala
ScalaScala
Scala
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Javascript
JavascriptJavascript
Javascript
 
Python 1 liners
Python 1 linersPython 1 liners
Python 1 liners
 
Monadologie
MonadologieMonadologie
Monadologie
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 

Recently uploaded

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 

Python 101 language features and functional programming

  • 1.
  • 2.
  • 4.
  • 5. 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); }
  • 6. Reverse String – Java String s = "This is the test"; System.out.println(new StringBuilder(s).reverse().toString());
  • 7. Reverse String – PHP echo strrev("Hello World");
  • 8. Reverse String – Python s[::-1]
  • 9. Find element in array JavaScript var zipCodes = (['90001','90002','90003']); if ( zipCodes.indexOf('9005') > -1 console.log("found") ; } else { console.log("not Found"); } ) {
  • 10. 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>();
  • 11. 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;
  • 12. Find element in array Python element in data
  • 13.
  • 14. 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
  • 16. 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
  • 17. 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
  • 18. 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()
  • 19. 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
  • 20. 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
  • 21. 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'))
  • 22.
  • 23. 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
  • 24. Functions and F.Programming def f1(): return "function One!" def f2(): return "function Two!" d = {"one" : f1, "two" : f2} d["one"]() d["two"]()
  • 25. 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))
  • 26. 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])
  • 28. 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)
  • 29. 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])