Welcome to GKTCS

IT Training .Consultancy . Software Development. Staffing

1

Surendra Panpaliya

Director, GKTCS Innovations Pvt. Ltd, Pune.

13.5 + Years of Experience ( MCA, PGDCS, BSc. [Electronics] , CCNA) Director , GKTCS Innovations Pvt. Ltd. Pune [ Nov 2009 – Till date ] IT Manager and Consultant at Rolta India Ltd, Mumbai [ April 2007 – Oct 2009 ] Associate Professor at Sinhgad Institute , Pune [Jan 2002 – April 2007] Instructor , ITM Bangalore [ May 2000 – Jan 2002 ] Project Trainee, DSYS Software Group, Bangalore [ Jan 1999 to April 2000] Skills  Python, , Django, Android , PHP, LAMP  Data Communication & Networking, CCNA UNIX / Shell Scripting, System Programming  CA Siteminder, Autosys, SSO, Service Desk, Service Delivery Author of 4 Books National Paper Presentation Awards at BARC Mumbai 2 ICE Breaking

• Form a group of 2 or 3. • Listen to your colleague. • Appreciate everyone. • Know everyone skills and appreciate the same. • Learn in team. • Cooperate to each other • Please switch off / Silent your Mobile phone.

3 Jython Programming

Surendra R. Panpaliya M:9975072320 [email protected] www.gktcs.com

2 November 2012 4 Agenda

Day Module Topics Day 1 Module 1 Introduction to Jython Module 2 Simple Program Module 3 Basic Language Construct Module 4 Control Structure Module 5 Functions Module 6 Data Structure

2 November 2012 5 Module 1

Introduction to Jython

2 November 2012 6 Introduction to Jython

• Botanists know that if you cross-pollinate two different strains of plants, you create a hybrid; a new plant that exhibits the strengths of both its parents. • Jython is a programming hybrid. It is an implementation of the Python scripting language written in 100% pure Java that runs under any compliant Java Virtual Machine (JVM). •

2 November 2012 7 Introduction to Jython

• Using Jython, you can write Python programs that interact with any Java code. The Jython interpreter supports a number of shortcuts, which make using Java libraries as easy as using your own Python code. • Jython, then, combines a scripting language of unparalleled ease of development with an operating environment for which many powerful tools have been written.

2 November 2012 8 Introduction to Jython

• The combination can be immensely valuable for , enabling you to cut development time significantly while still retaining the ability to use existing Java tools, such as applets and servlets. • Just as Python was originally conceived as glue to bind together other programs, Jython acts as glue to help you get the most out of Java- based tools.

2 November 2012 9 Introduction to Jython

• In particular, Jython excels at simplifying the use of complex Java programming libraries and APIs, such as the Swing graphical interface toolkit or the JDBC database connectivity API.

2 November 2012 10 Introduction to Jython

• What is Jython? • Who Uses Jython? • Features of Jython • Why Jython

2 November 2012 11 What is Jython?

• Jython is an interpreted, interactive, object oriented language. • It incorporates modules, exceptions, high level data types, dynamic typing and classes. • It has interfaces to system calls and libraries. • It is portable.

2 November 2012 12 What is Jython?

• Jython is an implementation of Python written in the Java language and integrated with the Java platform. • Python is a scripting language often used in UNIX-based systems, including Linux.

• Python was invented by Guido van Rossum and introduced to the developer community in 1991.

13 What is a scripting language?

• Unlike the Java programming language, Jython is a scripting language. A scripting language is generally defined as follows: • Very easy to learn and code • Expressive and concise, yet powerful • Has minimal required structure to create a running "program" • Supports interactive (command-at-a-time) execution • Does not require a compile step • Supports reflective programming • Supports functional programming • Supports dynamic execution of source (that is, an eval function)

• Runs external programs 14

What is a scripting language?

• Scripting languages value efficiency over machine efficiency and performance. • Jython is easy to learn and efficient to code. • Jython can also be described as an agile language. • Agile languages are generally thought of as being capable of performing a wide variety of tasks and useful for many different types of problems, easy-to- use and yet powerful and expressive. • They are also ideal rapid prototyping languages.

15 Brief History of Jython

• Jython was initially created in late 1997 to replace with Java for performance-intensive code accessed by Python programs. • The Python Software Foundation awarded a grant in January 2005. • Over this history, Jython had been developed successively by Jim Hugunin[1],Barry Warsaw, Samuele Pedroni, Brian Zimmer, and Frank Wierzbicki. • Jython 2.5 was released in June 2009.[

16 Status and roadmap

• The current release is Jython 2.5.3, available since August 13, 2012. • Jython 2.5.2 implements the same set of language features as CPython 2.5 • As of 2.5.0, Jython is able to run popular Python frameworks such as Django, Pylons, or SQLAlchemy. • March 05, 2012, it was announced that funding had been procured to produce a 2.7 version of Jython.

17 License terms

• From version 2.2 on, Jython is released under the Python Software Foundation License (v2).

• Older versions are covered by the Jython 2.0, 2.1 license and theJPython 1.1.x Software License.

• The first two are permissive free software licenses. • The command line interpreter is available under the Apache Software License.

18

Usage

• Jython is one of two scripting languages (with Jacl) used in WebSphere Application Server. • It is used in IBM Rational development tools, where Jython projects can be created using wizards. • It is used as the main programming language for the JHepWork data analysis framework.

19 Usability Features

• Very clear syntax. • Obvious way to do most things. • Huge amount of free code and libraries. • Interactive. • Only innovative where innovation is really necessary. – Better to steal a good idea than invent a bad one!

20 The Benefits of Jython

• To improve your productivity for a great number of project types that are currently performed in Java. • We'll also suggest some reasons why Jython might be a good addition to your toolkit even if you are already a CPython programmer.

21 The Benefits of Jython

• For Java Programmers • Why you need another language to run under the JVM. Doesn't Java work just fine? • Java is great. But, by using Jython instead of Java, you'll probably find that the number of lines of code in your program has dropped by as much as 50%. • Many empirical studies of programming suggest that shorter programs have fewer bugs.

22 The Benefits of Jython

• In addition, programmer productivity tends to be about the same for any number of lines of code even if, as in Jython, each line of code tends to do more than it might in another language. • In other words, an expert Jython programmer will likely produce programs faster, and with fewer bugs, than an expert Java programmer.

23 The Benefits of Jython

• We don't mean to attack Java as a programming language. Java, like every programming language, is a tool, and it has its uses. • However, it's hard to use Java for any length of time and not realize that it is an exceptionally verbose and often inflexible language. After you've written lines of code such as the following, which includes a typecast that is there only to keep the compiler happy: • MyClass instance = (MyClass)list.get(2); • it becomes easier to see the benefits of just writing: • instance = list[2]

24 The Benefits of Jython

• The difference between the Java and Python code emphasizes one of the main sources of the productivity advantage of Jython--dynamic typing. • In Python, you do not need to declare variables for use, nor do you need to tell the interpreter what the expected data type of a variable is. • It is important to note that despite being dynamically typed, Python also has strong typing. • This means that a line of code such as "1" + 1 is an error in Python (unlike many other scripting languages, which would quietly allow this).

25 The Benefits of Jython

• In addition to dynamic typing, the Python scripting language used in Jython offers several other features that will improve your programming productivity: • Clean, easy-to-read syntax • Interactive interpreter • Module-based organization • High-level, built-in types • Simple object-oriented semantics • Operator overloading • Dynamic dispatch and polymorphism • No compile phase

26 The Benefits of Jython

• First-class functions and classes • In Java: • import java.lang.reflect.*; • Class aClass = anInstance.getClass( ); • Method someFunc = aClass.getMethod("method", new Class[] {Integer, String}); • someFunc.invoke(anInstance, new Object[] {new Integer(3), "Fred"});

• In Python: • someFunc = anInstance.method • someFunc(3, "Fred")

• Extensive included library

27 For Python Programmers

• There seem to be at least three important gains. • Extended reach • The most notable examples of this are web-based--namely, the creation of applets that will be accepted by mainstream browsers, and the creation of servlets that can be run by Java servlet or J2EE servers.

• Ease of distribution • Jython makes it easy to distribute your program as a cross- platform binary in .jar format. Although there are binary tools for CPython on different platforms, there is no similar cross- platform tool for CPython. 28 For Python Programmers

• Tools and libraries • Although the Python standard library and available third-party tools are varied and wonderful, Java has benefited from a much larger pool of available tools, particularly enterprise- level tools. The Swing GUI toolkit is more complete and more cross-platform than any GUI toolkit available for CPython, and is arguably easier to use. Database tools are much more widely available and standardized in the Java world. There is a large quantity of high-level tools for XML data. All these libraries and tools can be used from Jython at least as easily as other Java tools would be able to use them.

29 Jython: head to head

30 Compared to C/C++

• Much higher level. • Get more done in less time. • Richer built-in data structures, type and libraries • Much less error prone (buffer overruns, pointer dereferences, etc) • Easier to write secure code!

• But Python code can execute much slower than C/C++ code!

31 Jython (nee JPython)

• A reimplementation of Python in Java. • Seamless, magical interface to Java libraries • Good scripting solution for Java. • Compiles Python classes to Java classes • Embedded interpreter allows interactive coding. • Access to all Java classes. • For better or worse: maintains Java's security/platform-independence bubble.

32 Jython Limitations

• Not the fastest executing programming language: – C/C++ is naturally fast – Perl’s regular expressions and IO are a little faster – Some Java implementations have good JITs – But Jython also has some speed advantages: • Psyco is a third-party open source JIT for Python • Fast implementations of built-in data structures • Pyrex compiles Python code to C • Dynamic type checking requires more care in testing. • Language changes (relatively) quickly: this is a strength and a weakness. • Jython is not as resume friendly as Java/C#. Net.

33 Module 2: Simple Program

• Jython shell • Jython command • Prepare source File and execute the code • Print “Hello World” • Comments • Help command

34 Starting up of Jython…

C:\Users\hp>jython Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06) [Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_33 Type "help", "copyright", "credits" or "license" for more information. >>>

2 November 2012 35 How to quit

• Windows users - Press Ctrl-Z followed by enter key. • Linux/BSD/Mac OS X users - Press Ctrl-D.

2 November 2012 36 Using Source Files

• Open your favorite editor • print ‘Hello World’ >jython helloworld.py Hello World • How It Works • The print statement is supplied with the text Hello World, and it promptly prints it to the screen.

2 November 2012 37 Help command

Getting Help • Jython has two closely-related help modes. One is the general “help” utility, the other is a help function that provides the documentation on a specific object, module, function or class. • The help() Utility Help is available through the help() function. If you enter just ‘help()’ you will enter the online help utility. This help utility allows you to explore the Python documentation. • The interaction looks like this: >>> help Type help() for interactive help, or help(object) for help about object. >>> help("EXPRESSIONS")

2 November 2012 38 Module 3: Basic Language Consructs • Data types and Variables • String type • Format method • Operators and Expressions • Indentation

2 November 2012 39 Numeric Types

• int: integral number, e.g. "x=5" • float: accuracy depends on platform, e.g. "x=3.14" • complex: real+imag., "x=5.3+3.2j” • bool: True, False (mathematically equivalent to 1 and 0)

40 Integers

• Simple number literals generate integers. >>> x = 5 • We can also convert other types to integers: >>> x= int(“5”) >>> print int(5.9) 5 • Or round floats to the closest integer >>> print round(5.9) 5

41 Standard Math Operations

>>> 5+3 8 >>> 5*2+3 13 >>> 3+5*2 13

42 Integer Division

>>> 5/2 # Python wart - don't do this 2 >>> 5//2 # Explicit truncating div 2 >>> 5.0/2 # Explicit float division 2.5 >>> float(5)/2 # Another way 2.5

43 Exponents

• The “**” operation means “to the exponent of”. >>> 2**30 1073741824

>>> 2**90 1237940039285380274899124224

44 Integers Are Unbounded

>>> 2**150 1427247692705959881058285969449495136382746624 >>> 2**1000 10715086071862673209484250490600018105614048117 055360744375038837035105112493612249319837881 569585812759467291755314682518714528569231404 359845775746985748039345677748242309854210746 050623711418779541821530464749835819412673987 675591655439460770629145711964776865421676604 29831652624386837205668069376 >>> 2**100000 99900209301438450794403276433003359098042913905 418169177152927386314583246425734832748733133 24…

45 Float Examples

>>> print 4 * 2.5 / 3.3 3.0303030303 >>> print 7.0 / 2 3.5 >>> print float("7.0") 7.0 • Floats have all of the complexities of floats in any other language! Beware!

46 Mathematical Functions

• abs(x) – absolute value • divmod(a, b) - divide a by b and return both the quotient and the remainder • hex( x) - Convert an integer number (of any size) to a hexadecimal string. • oct( x) - Convert an integer number (of any size) to an octal string. • round( x[, n]) - Return the floating point value x rounded to n digits after the decimal point.

47 Booleans

• True and False are the only values of type “bool”. • True can be treated as “1” and False as “0” in mathematical expressions: >>> print True+True+True-False 3 >>> print False==0 True

48 Complex Examples

>>> print complex(3,1)*3 (9+3j)

• Complex numbers can also be created with engineer’s syntax: >>> print (1+2j)/(1+1j) (1.5+0.5j)

49 Objects All the Way Down

• Everything in Jython is an object • Integers are objects. • Characters are objects. • Complex numbers are objects. • Booleans are objects. • Functions are objects. • Methods are objects. • Modules are objects

50 Object Type and Identity

• You can find out the type of any object: >>> print type(1) >>> print type(1.0) • Every object also has a unique identifier (usually only for debugging purposes) >>> print id(1) 2 >>> print id("1") 3

51 Introduction to Attributes

• Attributes are bits of information attached to objects. >>> x = complex(3, 5) >>> x.real 3.0 >>> x.imag 5.0

52 Introduction to Methods

• Methods are behaviours associated with objects. >>> x = complex(3,5) >>> x (3+5j) >>> x.conjugate() (3-5j)

53 None

• “None” represents the lack of a value. • Like “NULL” in some languages or in databases. • For instance:

>>> if y!=0: ... fraction = x/y ... else: ... fraction = None

54 Strings

• Can be enclosed in single or double quotes: >>> print ’spam eggs’ spam eggs >>> print "spam eggs" spam eggs >>> print "doesn't" doesn't >>> print '"He said", she said.' "He said”, she said. >>> #backslash escapes quotes >>> print ' "Isn\'t," she said.' "Isn't," she said.

55 Triple Quoted Strings

• Triple quoted strings span lines • They can also contain quote chars print """ Usage: thingy [OPTIONS] -h Display this "usage message" -H hostname Hostname to connect to """

56 Strings

myStr = "abc" # assignment myStr = myStr + "def"# = "abcdef"

for char in myStr: # iterate print char

myStr = str(5) # create from number

• Pretty much any type can be converted into a string. >>> str(file("catalog.txt")) ""

57 String methods

>>> s="hello there" >>> print s.replace("h", "j") jello tjere >>> print s.capitalize() Hello there >>> print s.title() Hello There >>> print s.upper() HELLO THERE

58 String methods

>>> string = "positively python pow ered" >>> print string.count("po") 2 >>> print string.startswith("abc") False >>> print string.endswith("ed") True >>> print string.find("pow") 18

59 Splitting and joining

>>> joiner = " and " >>> names = ["Peter", "Paul","M ary"] >>> joined = joiner.join(names) >>> joined 'Peter and Paul and Mary' >>> joined.split(" and ") ['Peter', 'Paul', 'Mary']

60 Characters

• Characters are just strings of length 1. x = "a" • The ord function returns the ASCII (or Unicode if appropriate) character number: >>> ord("a") 97 >>> chr(97) # opposite of ord "a"

61 Unicode

• Unicode data type: normal string: “hello” unicode string: u“hello” • More unicode strings: u“\U0265”   u“\N{MICRO SIGN}”   • unichr() • The regular expression engine is Unicode aware

62 Literal Constants

• Numbers – Integers, long, floating point and complex numbers • Strings – A sequence of characters in single or double quotes • For C/C++ programmers – There is no separate char data type in Python

2 November 2012 63 Variables

• Exactly what they mean – values can vary • Used to store information • Can start with alphabets or underscore • Rest can be any alphanumeric

2 November 2012 64 Using Jython as a Calculator >>> 2+2 4 >>> # This is a comment ... 2+2 4 >>> 2+2 # and a comment on the same line as code 4 >>> (50-5*6)/4 5

2 November 2012 65 Using assignment operator

>>> width = 20 >>> height = 5*9 >>> width * height 900

2 November 2012 66 Assignment to several variables

>>> x = y = z = 0 # Zero x, y and z >>> x 0 >>> y 0 >>> z 0

2 November 2012 67 Complex numbers

>>> 1j * 1j (-1+0j) >>> 1j * complex(0,1) (-1+0j) >>> 3+1j*3 (3+3j) >>> (3+1j)*3 (9+3j)

2 November 2012 68 Complex Numbers (cont.)

>>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5

2 November 2012 69 Abs…

>>> a=3.0+4.0j >>> float(a) Traceback (most recent call last): File "", line 1, in ? TypeError: can't convert complex to float; use abs(z) >>> abs(a) # sqrt(a.real**2 + a.imag**2) 5.0

2 November 2012 70 The _

>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06

2 November 2012 71 Strings

>>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't" >>> "doesn't" "doesn't“ >>> '"Yes," he said.' '"Yes," he said.'

2 November 2012 72 String (cont…)

hello = "This is a rather long\n\ string containing several lines\n\ of text just as you would do in\n\ C.\n\ Note that whitespace at the\n\ beginning of the line is\n\ significant."

print hello

2 November 2012 73 Raw strings hello = r"This is a rather\n\ long string containing \n\ several lines of text much\n\ as you would do in C." print hello

2 November 2012 74 Print function

• print evaluates each expression in turn and writes the resulting object to standard output • A "\n" character is written at the end, unless the print statement ends with a comma. • Standard output is defined as the file object named stdout in the built-in module sys. If no such object exists, or if it does not have a write() method, a RuntimeError exception is raised.

2 November 2012 75 Concatenation

>>> word = 'Help' + 'A' >>> word 'HelpA' >>> '<' + word*5 + '>' ''

2 November 2012 76 Subscripting

>>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp'

2 November 2012 77 Subscripting

>>> word[:2] # The first two characters 'He‘ >>> word[2:] # Everything except the first two characters 'lpA'

2 November 2012 78 Unlike C …

>>> word[0] = 'x' Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment

2 November 2012 79 Out of bound…

>>> word[1:100] 'elpA' >>> word[10:] '' >>> word[2:1] '' What happens in case of negative indices?

2 November 2012 80 Negative indices

>>> word[-1] # The last character 'A‘ >>> word[-2] # The last-but-one character 'p' >>> word[-2:] # The last two characters 'pA' >>> word[:-2] # Everything except the last two characters 'Hel'

2 November 2012 81 Easy way to remember

+---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1

2 November 2012 82 Logical and Physical Lines

• A physical line is what you see when you write the program • A logical line is what Python sees as a single statement. • Python implicitly assumes that each physical line corresponds to a logical line.

2 November 2012 83 Examples

• For example, i = 5 print i • is effectively the same as i = 5; print i;

2 November 2012 84 Examples

• and the same can be written as • i = 5; print i; • or even • i = 5; print i

2 November 2012 85 Indentation

• Whitespace is important in Python. • Actually, whitespace at the beginning of the line is important. • This means that statements which go together must have the same level of indentation. • Each such set of statements is called a block.

2 November 2012 86 Error example

>>> i=5 >>> print i 5 >>> print i File "", line 1 print i ^ IndentationError: unexpected indent >>>

2 November 2012 87 How to indent

• Do not use a mixture of tabs and spaces for the indentation as it does not work reliably across different platforms. • The official recommended standard is four spaces for each level of indentation. • You can also use tabs instead.

2 November 2012 88 Operators and Expressions

• Operators • Precedence • Associativity • Expressions

2 November 2012 89 Operators

+ - * ** / % << >> & | ^ ~ < > <= >= == !=

2 November 2012 90 Module 4: Control Structure

• If • While loop • For loop • Break & Continue Statements

2 November 2012 91 The if statement x = int(raw_input("Please enter an integer: ")) if x < 0: x = 0 print 'Negative changed to zero'

2 November 2012 92 elif and else elif x == 0: print 'Zero' elif x == 1: print 'Single' else: print 'More'

2 November 2012 93 for Statements

>>>a = ['cat', 'window', 'defenestrate'] >>> for x in a: print x, len(x) O/p cat 3 window 6 defenestrate 12

2 November 2012 94 The range function

>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70]

2 November 2012 95 Iterate over indices

>>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i] ...

2 November 2012 96 Left overs…

• break • continue • pass (to be covered later)

2 November 2012 97 Functions

• Module 5: Functions • Simple Function declaration • Function with parameter • Variable Scope • The “global” statement

2 November 2012 98 Functions def fib(n): # write Fibonacci #series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b # Now call #the function we just defined: fib(200)

2 November 2012 99 Functions

• Note – A function definition introduces the function name in the current symbol table. The value of the function name has a type that is recognized by the interpreter as a user-defined function. – This value can be assigned to another name which can then also be used as a function.

2 November 2012 100 Example

>>> fib >>> f = fib >>> f(100) 1 1 2 3 5 8 13 21 34 55 89

2 November 2012 101 Multiple arguments

def print_max(x, y): if x > y: print x, 'is maximum' else: print y, 'is maximum' print_max(3, 4)

2 November 2012 102 Local variables def func(x): print 'x is', x x = 2 print 'Changed local x to', x >>>x = 50 >>>func(x) >>>print 'x is still', x

2 November 2012 103 global statement

def func(): global x print 'x is', x x = 2 print 'Changed global x to', x >>>x = 50 >>>func() >>>print 'Value of x is', x

2 November 2012 104 Default argument values def say(message, times = 1): print message * times

>>>say('Hello') >>>say('World', 5)

2 November 2012 105 Keyword arguments def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', c func(3, 7) func(25, c=24) func(c=50, a=100)

2 November 2012 106 Return statement def maximum(x, y): if x > y: return x else: return y print maximum(2, 3)

2 November 2012 107 DocStrings def print_max(x, y): '''Prints the maximum of two numbers. The two values must be integers or strings containing integers.''' x = int(x) # convert to integers, if possible y = int(y) if x > y: print x, 'is maximum' else: print y, 'is maximum' print_max(3, 5) print print_max.__doc__

2 November 2012 108 Variable argument in python • def all_of(*args): result = 1 for i in args: result *= i return result print all_of(3,4,5)

2 November 2012 109 Multiple Arguments def f(*args, **kwargs): print args print kwargs >>> f(1, 2, "cow", "kitty") (1, 2, "cow", "kitty") {} >>> f(arg1=1, sample=2, name="cow", hero="kitty") () {"arg1": 1, "sample": 2, "name": "cow", "hero": "kitty"} >>> f(1, 2, name="cow", hero="kitty") (1, 2) {"name": "cow", "hero": "kitty"}

2 November 2012 110 Lambda calculus

• Alonzo Church, 1936 • An alternative view of the ’meaning of computation’ • Is the core foundation for: – Theoretical computer science – Functional programming languages – Constructive logics • Think of it this way: if you didn’t have any programming language and had to build one, where would you start?

2 November 2012 111 Syntax of the λ calculus

• variable Any variable “v” is an expression • application Given any two expressions e1 and e2, then “(e1 e2)” is a valid expression, and denotes the application of e1 to e2. • abstraction Given any variable v, and any expression e, then “(v · e)” is an expression representing a function with v as the formal parameter, and e as the body of the function • Note that the application of f to x is written “functional style” as (f x) and not the more common f(x)

2 November 2012 112 In jython

>>>def make_incrementor(n): ... return lambda x: x + n >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43

2 November 2012 113 Module 6: Data Structures

• Types • List • Tuple • Dictionary • Sequences • Set

2 November 2012 114 Types

• Immutable – Numbers – Strings – Tuples • Mutable – Lists – Dictionaries – Sets – Most user defined objects

2011/05/24 115 Lists myList = ["a",5,3.25,2L,4+3j] anotherList = ["a",myList, ["3","2"]] anotherList2 = myList + myList # = ["a",5,...,"a",5,...]

116 Sequence Types

• Strings and lists are just a special case of “sequence types”. • These types can be looped over, indexed, sliced, etc. – Tuples: (1,2,"b") – Lists: [1,"a",3] – … • Anybody can define a new sequence type!

117 Sequence Operations

• Iteration: for i in myList: print i

• Numeric indexing: k = myList[3]

• Slicing: k = mylist[2:5]

118 Iterating Over Sequences strlist = ["abc", "def", "ghi"] for item in strlist: for char in item: print char

119 Sequence Concatenation

>>> word = 'Help' + 'Me' >>> print word HelpMe >>> list = ["Hello"] + ["World"] >>> print list ['Hello', 'World']

120 Sequence Repetition

>>> word = "HelpMe" >>> print '<' + word*5 + '>' >>> ['Hello', 'World'] *3 ['Hello', 'World', 'Hello', 'Wo rld', 'Hello', 'World']

121 Getting Sequence Length

• The len() function gets a sequence's length >>> len( "abc" ) 3 >>> len( ["abc","def"] ) 2

122 Sequence Indexing

>>> str="abc" >>> print str[0] a >>> print str[1] b

123 Negative Indices

>>> word = 'HelpMe' >>> # The last character >>> print word[-1] e >>> # The last-but- one character >>> print word[-2] M

124 One Way of Thinking About It • indices point between characters • length of a slice is top minus bottom

P y t h o n

0 1 2 3 4 5 -6 -5 -4 -3 -2 -1

125 Sequence Slicing

>>> word = "Python" >>> word[1] 'y' >>> word[0:2] 'Py' >>> word[2:4] 'th'

• Length of a (positive) slice is top-bottom • Avoids off-by-one errors

126 Negative Slicing

>>> word="Python" >>> print word[-1] n >>> print word[0:-1] Pytho >>> print word[0:-2] Pyth >>> print word[2:-2] th

127 Defaults

• Basic slice form is obj[x:y] • If “x” is missing or None, it defaults to “0”. • If “y” is missing or None, it defaults to the length of the string.

128 A Useful Invariant

>>> word = "Python" >>> print word[:2] + word[2:] Python

>>> print word[:3] + word[3:] Python

• This works because Python treats the first slice parameter inclusively and the last exclusively!

129 Defaults

>>> word = "HelpMe" >>> #All but first two characters >>> print word[2: ] lpMe >>> #The last two characters >>> print word[-2: ] Me >>> # First two characters >>> print word[ :2] He >>> # All but last two characters >>> print word[ :-2] Help

130 Copying a Sequence

• The start and end can both be inferred:

>>> mylist=["a", "b", "c", "d"] >>> anotherlist = mylist[ : ]

131 Mutability

132 Bindings

• When we assign a variable, we establish another reference or “binding” to the original value.

• a=b # the same object

• If you change a, you change b!

133 Lists Are Mutable

• Lists can be changed "in-place" >>> a = ['spam', 'eggs', 100, 1234] >>> b = a >>> print b ['spam', 'eggs', 100, 1234] >>> a[2] = 5.5 >>> print a ['spam', 'eggs', 5.5, 1234] >>> print b ['spam', 'eggs', 5.5, 1234]

134 Other List Mutations

>>> lst= ["a", "b", 5, 3, "g", 1.3] >>> lst.append( "someitem" ) >>> lst.sort() # sorts lst in-place >>> lst.reverse() # reverse in-place >>> del lst[5] # delete sixth item >>> lst2 = lst[:] # copy list >>> lst2.reverse() >>> print lst ['someitem', 'g', 'b', 'a', 5, 1.3] >>> print lst2 [1.3, 5, 'a', 'b', 'g', 'someitem']

135 Mutation Method in Action >>> a = ['spam', 'eggs', 100, 1234] >>> b = a >>> b.append("abc") >>> print a ['spam', 'eggs', 100, 1234, 'abc'] >>> print b ['spam', 'eggs', 100, 1234, 'abc']

136 Rebinding

>>> a=['spam','eggs',100,1234] >>> b = a[ : ] >>> a.append("abc") >>> print a ['spam', 'eggs', 100, 1234, 'abc'] >>> print b ['spam', 'eggs', 100, 1234] • “a” gets a new object that is a slice of b. • “b” remains bound to the original object. • “a” has “abc” appeneded.

137 Strings Are Not Mutable

>>> a = "abcdefgh" >>> a[3]="k" Traceback (innermost last): File "", line 1, in ? TypeError: object doesn't support item as signment >>> a = a + "qrs" >>> a "abcdefghqrs"

138 Tuples

• Immutable list-like objects are called "tuples“ >>> tup = (“a”, 1, 5.3, 4) >>> a[3]="k" Traceback (innermost last): File "", line 1, in ? TypeError: object doesn't have supt. assignment

139 Fun With Tuples

>>> cnum = 1 + 2j >>> (a,b)=(cnum.real,cnum.imag) >>> print a; print b 1 2 # old-fashioned swap # temp=a; a=b; b=temp >>> (a,b) = (b,a) # pythonic swap >>> print a; print b 2 1

140 Real Work With Tuples

• Tuples can be returned from functions. • This makes it easy to return multiple values without defining some kind of class. (unlike Java!) >>> import time >>> (year,month,day, hrs,mins,secs, day, da te, dst) = time.localtime()

• Note: there is also a class-based way to deal with date/times.

141 Tuple Shortcut

• We can usually leave out the parens: >>> j=1,2 >>> j=(1,2) # same as above >>> a,b = 1,2 >>> a,b = b,a >>> j=[1,2] >>> a,b=j >>> x,y = getXYCoords()

142 Dictionaries

• Serve as a lookup table • Maps "keys" to "values". • Keys can be of any immutable type • Assignment adds or changes members • keys() method returns keys

143 Dictionaries

>>> mydict={"a":"alpha", "b":"bravo","c":"charlie"} >>> mydict["abc"]=10 >>> mydict[5]="def" >>> mydict[2.52]=6.71 >>> print mydict {2.52: 6.71, 5: 'def', 'abc': 10, 'b': 'bravo', 'c': 'charlie', 'a': 'alpha'}

144 Constructing Dictionaries

• Dictionaries can be constructed directly as before or by using the “dict” function.

>>> list_of_tuples = [("a", "alpha"), ("b", "brav o"), ("c", "charlie")] >>> mydict = dict(list_of_tuples) >>> print mydict {'a': 'alpha', 'c': 'charlie', 'b': 'bravo'}

145 Dictionary Methods

>>> mydict={"a":"alpha", "b":"bravo ", "c":"charlie"} >>> mydict.keys() ['a', 'c', 'b'] >>> mydict.values() ['alpha', 'charlie', 'bravo'] >>> mydict.items() [('a', 'alpha'), ('c', 'charlie'), ('b', 'bravo')] >>> mydict.clear(); print dict {}

146 More on Lists

• append(x) – Add an item to the end of the list; equivalent to a[len(a):] = [x]. • extend(L) – Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L. • insert(i, x) – Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

2 November 2012 147 Functions (cont…)

• remove(x) – Remove the first item from the list whose value is x. It is an error if there is no such item. • pop([i]) – Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.

2 November 2012 148 Functions (cont…)

• index(x) – Return the index in the list of the first item whose value is x. It is an error if there is no such item. • count(x) – Return the number of times x appears in the list. • sort() – Sort the items of the list, in place. • reverse() – Reverse the elements of the list, in place

2 November 2012 149 Using Lists as Stacks

>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6]

2 November 2012 150 Using Lists as Queues

>>> queue = ["", "John", "Michael"] >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.pop(0) 'Eric' >>> queue.pop(0) 'John' >>> queue ['Michael', 'Terry', 'Graham']

2 November 2012 151 Functional Programming Tools

• filter(function, sequence)" returns a sequence consisting of those items from the sequence for which function(item) is true. • If sequence is a string or tuple, the result will be of the same type; otherwise, it is always a list.

2 November 2012 152 Example of filter

>>> def f(x): return x % 2 != 0 and x % 3 != 0 ... >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23]

2 November 2012 153 map function

>>> def cube(x): return x*x*x ... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

2 November 2012 154 A small variant

• More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence

2 November 2012 155 An example

>>> seq = range(8) >>> def add(x, y): return x+y >>> map(add, seq, seq) [0, 2, 4, 6, 8, 10, 12, 14]

2 November 2012 156 reduce function

• reduce(function, sequence)" returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on.

2 November 2012 157 An example

>>> def add(x,y): return x+y ... >>> reduce(add, range(1, 11)) 55 What if the sequence is empty?

2 November 2012 158 Handling it

>>> def sum(seq): ... def add(x,y): return x+y ... return reduce(add, seq, 0) ... >>> sum(range(1, 11)) 55 >>> sum([]) 0

2 November 2012 159 List Comprehensions

• List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. • The resulting list definition tends often to be clearer than lists built using those constructs. • Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses.

2 November 2012 160 Examples

>>>freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>>[weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18]

2 November 2012 161 Examples

>>> [3*x for x in vec if x > 3] [12, 18] >>> [3*x for x in vec if x < 2] [] >>> [[x,x**2] for x in vec] [[2, 4], [4, 16], [6, 36]]

2 November 2012 162 The del statement

>>> a = [-1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5]

2 November 2012 163 Cont…

>>> del a[:] >>> a []

2 November 2012 164 Sets

• Python also includes a data type for sets. • A set is an unordered collection with no duplicate elements. • Basic uses include membership testing and eliminating duplicate entries.

2 November 2012 165 Example

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit set(['orange', 'pear', 'apple', 'banana'])

2 November 2012 166 Example

>>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit False

2 November 2012 167 Set operations

>>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a set (['a', 'r', 'b', 'c', 'd']) >>> a - b set(['r', 'd', 'b'])

2 November 2012 168 Set ops (cont…)

>>> a | b # letters in either a or b set (['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) >>> a & b # letters in both a and b set (['a', 'c']) >>> a ^ b # letters in a or b but not both set (['r', 'd', 'b', 'm', 'z', 'l'])

2 November 2012 169 Looping through sequence

>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe

2 November 2012 170 Looping over two sequences

>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print 'What is your %s? It is %s.' % (q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.

2 November 2012 171 Looping in reversed manner >>> for i in reversed(xrange(1,10,2)): ... print i ... 9 7 5 3 1

2 November 2012 172 Sorted looping

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', ‘banana'] >>> for f in sorted(set(basket)): ... print f ... apple banana orange pear

2 November 2012 173 Comparing Sequences

(1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABC' < 'C' < 'Pascal' < 'Python' (1, 2) < (1, 2, -1) (1, 2, 3) == (1.0, 2.0, 3.0) (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)

2 November 2012 174 Summary

What did we learn today? Recap and Memory Test. Question and Answers

2 November 2012 175 Contact Us on:

G K T C S IT Training, Consultancy, Software Development, Staffing 4/A, Chandrakiran Apt, Near Tirupati Hospital, Opp. State Bank Nagar, Karve Nagar, Pune – 4110 52, Maharashtra, India. Phone: +(91)-20-25459062 M: +91- 9975072320, 8308761477 Email : [email protected] Web: www.gktcs.com

176