Saturday, March 25, 2017

Python Part3: Bytes, Lists, Shallow copies and Dictionaries

Bytes

  • Immutable sequence of bytes.

Lists

  • Mutable sequences of objects.
    • e.g a = [1, 2, 3 ,4]
  • Get or set value using index
    • e.g a[1] = 20 and print(a[1])
  • Negative integers index from the end.
  • The last element is at index -1
  • Slicing extracts part of a list.
    • Slice = seq[start:stop]
  • Slice range is half open-stop not included.
    • >>> s = [1, 2, 3, 4, 5, 6]
    • >>> s[1:4]
    • 2, 3, 4
  • Slicing works with negative indexes. 
    • >>> s[1:-1] 
    • 2, 3, 4, 5 
  • Omitting the stop index slices to the end. 
    • Slice_to_end = seq[start:] 
  • Omitting the start index slices from the beginning. 
    • Slice_from_beginning = seq[:stop] 
  • Half open ranges give complementary.
    • slices S[:x] + s[x:] == s 
  • Omitting the start and stop indexes slices from beginning to the end – a full slice. 
    • Full_slice = seq[:]
  • Important idiom for copying lists: 
  • Copy list using 
    • Copy() method 
      •  U = seq.copy() 
    • List() constructor 
      •  V = list(seq) 
  • All of these techniques create shallow copies, mean create new list containing same object reference to source list.

Shallow copies: Examples

  • >>> A = [[1, 2], [3, 4]] 
  • >>> B = A[:]      (copy using full slice) 
  • >>> A is B      (both objects have different identities.) 
    • False 
  • >>> A == B 
    •  True 
  • >>> A[0] 
    • [1, 2] 
  • >>> B[0] 
    • [1, 2] 
  • A[0] is B[0]      (both objects have same identities.) 
    • True
  • >>> A[0] = [8, 9]      (This create a new list and set reference of A[0] to this.) 
  • >>> A[0] 
    • [8, 9] 
  • >>> B[0]      (B[0] is unchanged because it has reference to old list.) 
    • [1, 2] 
  • >>> A[1].append(5)      (A[1] and B[1] still have reference to same list. So changes reflects in both places.) 
  • >>> A[1] 
    • [3, 4, 5] 
  • >>> B[1] 
    • [3, 4, 5] 
  • >>> A      (Now both lists look like this) 
    • [[8, 9], [3, 4, 5]] 
  • >>> B 
    • [[1, 2], [3, 4, 5]]
  • Repeat lists using the * operator. 
  • Most often used for initializing a list of known size with a constant. 
    • S = [constant] * size 
  • Multiple references to one instance of the constant in the produced list. 
  • Repetition is shallow. 
    • >>> S = [[1, 2]] * 5 
      • [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]] 
    • >>> S[3].append(7) 
    • >>> S 
      • [[1, 2, 7], [1, 2, 7], [1, 2, 7], [1, 2, 7], [1, 2, 7]] 
  • Index(item) returns the integer index of the first equivalent element raises value error if not found. 
    • I = w.index(‘the’)
  • Count(item) returns the number of matching elements. 
    • W.count(‘the’) 
  • The in and not in operators test for membership. 
    • 5 in [1, 2, 3] 
    • 5 not in [1, 2, 3] 
  • Del seq[index] to remove by index. 
  • Seq.remove(item) to remove by value. Raises value error if not found. 
  • Insert items with seq.insert(index, item) 
  • Concatenate lists with + operator 
    • >>> M = [1, 2] 
    • >>> N = [3, 4] 
    • >>> K = m + n 
    • >>> k 
      • [1, 2, 3, 4]
  • In-place extension with += operator or extend method. 
    •  >>> K += [6, 7] 
    •  >>> K 
      •  [1, 2, 3, 4, 6, 7] 
    •  >>> K.entend([11, 12]) 
    •  >>> K 
      •  [1, 2, 3, 4, 6, 7, 11, 12] 
  • K.reverse() reverses in place. 
  • K.sort() sorts in place. 
  • K.sort(reverse=true) gives descending sort.

Dictionaries

  • Unordered mapping from unique, immutable keys to mutable values. 
  • Recap literals: 
    • Delimited by { and } 
    • Key-value pairs comma separated 
    • Corresponding keys and values joined by colon. 
    • Keys must be unique 
    • Urls = {'google':'http://google.com', 'microsoft':'http://Microsoft.com' } 
    • >>> url['google'] 
      • http://google.com
  • Dict() constructor accepts: 
    • Iterable series of key-value 2-tuples. 
      • >>> Names_and_ages = [('Alice', 32), ('Bob', 48)] 
      • >>> d = dict(Names_and_ages) 
      • >>> d 
        • {'Alice':32, 'Bob':48} 
  • Keyword arguments-requires keys are valid python identifiers. 
  • A mapping, such as another dict. 
    • >>> Phonetic = dict(a='alfa', b='bravo') 
    • >>> phonetic 
      • {'a':'alfa', 'b':'bravo'}
  • d.copy() for copying dictionaries. 
    • >>> e = d.copy() 
    • >>> e 
      • {'Alice':32, 'Bob':48} 
  • Or simply dict(d) constructor 
    • >>> f = dict(e) 
    • >>> f 
      • {'Alice':32, 'Bob':48}
  • Extend a dictionary with update() 
    • >>> g = dict('c':'charle', 'f':'fort') 
    • >>> f.update(g) 
    • >>> f 
      • {'a':'alfa', 'b':'bravo', 'c':'charle', 'f':'fort'} 
  • Update replaces values corresponding to duplicate keys. 
  • Iteration is over keys. 
  • Get corresponding value with d[key] lookup. 
    • >>> for key in f: 
    •  print("{key} => {value}".format(key= key, value=f[key])) 
  • Use values() for an iterable view onto the series of values 
  • No efficient way to get the key corresponding to a value. 
    •  >>> for value in f.values(): 
    •  print(value)
  • Keys() method gives iterable view onto keys – not often needed. 
    • >>> for key in f.keys(): 
    •  print(key) 
  • Use items for an iterable view onto the series of key-value tuples. 
  • Use with tuple unpacking. 
    • >>> for key, value in f.items(): 
    •  print("{key} => {value}".format(key=key, value=value)) 
  • The in and not in operators work on the keys. 
    • >>> 'a' in f 
    • >>> 'h' in f
  • Use del keyword to remove by key. del d[key] 
    • >>> del f['a'] 
  • Keys must be immutable. 
  • Values may be mutable. 
  • The dictionary itself is mutable.

Python Part2: Conditional statements, While loops, Strings and Range

Conditional statements

If expr:
     print("expr is true")

If expr:
     print("It's true")
else:
     print("its’s false")

Python provides the elif keyword to eliminate the need for nested if … else structure.

h = 5
if h > 5:
      print("greater than 5")
elif h < 2:
      print("less than 2")
else:
      print("between 2 and 5.")

While loops

# While loop 
 While expr: 
     print("loop while expr is true") 

# Do-while in python 
 While True: 
     If expr: 
          Break

Strings

  • Immutable sequence of Unicode codepoints.
    • Immutable mean when you construct a string you can't modify its content.
  • Strings with Newlines
    • Multiline strings
      • """ this is
      • Multiline string"""
    • Escape sequences
      • This is \nmultiline \nstring.
  • len(s) gives number of codepoints(characters).
  • The + operator can be used for string concatenation.
    • >>> "This" + "is" + "a" + "string"
    • Thisisastring
  • Strings are immutable, so the += operator re-binds the reference to a new object. 
  • Use sparingly, concatenation with + or += can cause performance degradation. 
  • Call the join() method on the separator string. 
    • >>> Numbers = ';'.join([1, 2, 3, 4]) 
    • '1;2;3;4' 
  • Use the split() to divide a string into a list. 
    • >>> Numbers.split(';') 
    • [1, 2, 3, 4] 
  • Without an argument, split() divides on whitespace.
  • Join()-ing on an empty separator is an important and fast way of concatenating a collection of strings. 
  • The partition() method divides a string into three around a separator: prefix, separator, suffix.
  • Tuple unpacking is useful to destructure the result.

Range

  • Arithmetic progression of integers. 
  • Stop value is one-past-the-end. 
    • >>> range(5) 
    • range(0, 5) 
  • Ranges are 'half open'-start is include but stop is not. 
    • >>> for I in range(5) 
    • print(I) 
    • 4
  • Stop value of a range used as start value of consecutive range. 
    • >>> list(range(5, 10)) 
    • [5, 6, 7, 8, 9] 
    • >>> list(range(10, 15)) 
    • [10, 11, 12, 13, 14] 
  • Optional third step value. 
    • >>> List(range(0, 10, 2)) 
    • [0, 2, 4, 6, 8] 
  • Range(stop) range(10) 
  • Range(start:stop) range(0, 10) 
  • Range(start:stop:step) range(0, 10, 2)

Python Part1: Introduction, Install on windows, Scalar Types and Relational Operators

Introduction to python

  1. Open source programming language developed in late 1980’s.
  2. Strongly typed language in the sense that every object in the language has a definite type.
  3. At the same time, it is dynamically typed means no type checking prior to running it.
  4. General purpose language. 
  5. There are some areas where it's less suitable than others, for example, in extremely time sensitive or memory constrained environments.

Install python on windows

Scalar types

  • Int
  • Float
  • None
  • bool

Relational operators

  • ==      value equality
  • !=       value inequality
  • <        less-than
  • >        greater-than
  • <=      less-than or equal to
  • >=      greater-than or equal to

Sunday, June 26, 2016

How To:Set python virtual environment as python interpreter in eclipse

In this lesson we 'll set virtual env as default interpreter in pydev eclipse project.

1). In PyDev Package Explorer panel, right click on project name and select Properties, a new window will open.

2). Click PyDev - Interpreter/Grammar -> Click here to configure an interpreter not listed, a new window will open.

3). Click PyDev -> Interpreters -> Python Interpreter on left panel.

4). In Python Interpreters section click New -> Browse

5). Open virtual environment folder, move to Scripts folder, select python.exe file and click Open.

6). Enter venv in Interpreter Name: instead of default value and click Ok. You can choose name of your own choice.

7). Select newly added python interpreter iPython Interpreters section and click OK

8). Now select newly added python interpreter under Interpreter drop down list and click OK.

How To:Import python project in eclipse

In this lesson we 'll import python django project in pydev eclipse.
Copy these two files from some existing pydev eclipse project to root folder of new project which you want to import in eclipse.
.project
.pydevproject

Open .project file in notepad and change name to your_project_name.
If you don't have these files then you can create them yourself.


Open notepad, copy following text, click File -> Save As... -> Enter ".project" in File name: -> Select All Files from Save as type: drop down list.


<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>your_project_name</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.django.djangoNature</nature>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>

Now again open notepad, copy following text, click File -> Save As... -> Enter ".pydevproject" in File name: -> Select All Files from Save as type: drop down list.


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?><pydev_project>
<pydev_variables_property name="org.python.pydev.PROJECT_VARIABLE_SUBSTITUTION">
<key>DJANGO_MANAGE_LOCATION</key>
<value>manage.py</value>
</pydev_variables_property>
<pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
<path>/${PROJECT_DIR_NAME}</path>
</pydev_pathproperty>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 3.0</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
</pydev_project>

Open eclipse, click File -> Import. New window will open. Now select 'Existing Projects into Workspace' under 'General' and click Next. On new window browse to project root directory and select root folder. Then click finish.