Table of Contents

1 Install python package with Python3

# It does not work for Python3
pip install fastnumbers
# It does work for Python3
python3 -m       pip install fastnumbers

2 Python packages

  • Python stores large matrix in a file with HDF5 format
  • Science Python SciPy

    # install scipy on my MacOS
    python3 -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
    
  • Numerical computation with numpy NumPy
  • Convert string to int or float package: fastnumbers
  • Plot and statistics package: matplotlib
  • Iterator, itertools, fast loop : itertools
    • speed up your loop
  • Python English dictionary words. pyenchant

    • StackOverFlow SO
    python3 -m pip install pyenchant
    
  • Browser Editor Python Jupyter Lab

    python3 -m pip install jupyterlab
    

3 Class in Python

  • Python has class, it is similar to Java and C++, but it is more flexible.

    • Python DOES not have access modifier such as public, protected and private
    class Person:
        name
        __init__(self, name):
        self.name = name
    
    c = Person("David")
    print(c.name)
    
    • Python __call__ and __init__

      class Person:
          __init__(self, name):
          self.name = name
          __call__(self, newName):
          self.newName = newName
      

      The difference is __call__ is used to instantiate object, but __call__ is used to modify and instance.

      p = Person("David")
      print(p.name) # => David
      p1 = p("Michael") 
      print(p.name) # => Michael
      
      • It is almost like setter and getter in Java
    • Why Python is weird

      • self in Python is not a keyeword. WOW, so you can do the following.
      • If you are an Java programmer, you might like it.
      class Thing:
         name = 'David'
         def __init__(this, name):
            this.name = name
      // no problem
      
    • Python needs less code to create a class comparing to Java, C# or C++
      • Java class is more complicated.
     public class Person{
        public String name;
        public Person(String name){
          this.name = name;
        }
     }
    Person p = new Person("David");
    System.out.print(p.name);
    

4 Why Python is weird?

  • Use following import statement does not work in Python console or source file.

    # wrong 
    import AronLib 
    # right
    import AronLib as a
    

5 Constructor is weird in Pyton. You need lots of underscore

  • one underscore means private variable.
class Person:
    _name
    __init__(self, name)
    self._name = name

6 Class variable in Python is very weird. If you love to mutate variables, then it might be not that weird.

  • Define a class variable called trick for a dog.
class Dog:
   trick = []
   def __init__(self, name):
      self.name = name
   def append(self, trick)
      self.trick.append(trick)

# trick will be shared for all instance Dog
d1 = Dog('Fido')
d2 = Dog('xFido')
d1.append('new trick')
d2.append('old trick')
print(d2.trick) # ['new trick', 'old trick']
  • Never use class variable in Python
class Dog:
  def __init__(self, name):
     self.trick = []
     self.name = name
  def append(self, trick):
     self.trick.append(trick)

d1 = Dog('Fido')
d2 = Dog('xFido')
d1.append('new trick')
d2.append('old trick')
print(d2) # ['old trick']

7 Initialize a list is easy in Python.

  • Python uses simple way to initialize a list, it is like Haskell.
ls = [1, 2, 3]                                                             
ls = ['dog', 'cat', 'cow']                                                 
  • In Haskell
let ls = [1, 2, 3]                                                         
let ls = ["dog", "cat", "cow"]                                             
  • In Java, you need lots more code.
List<Integer> ls = new ArrayList<>();                                          
ls.add(1);                                                                 
ls.add(2);                                                                 
ls.add(3);                                                                 

// Better way to initialize List                                           
List<Integer> ls = Arrays.asList(1, 2, 3);                                 
  • In C++, it is relative easy.
std::vector<int> vec = {1, 2, 3};                                          
std::vector<string> vec = {"dog", "cat", "cow"};                           

8 list complehension is almost like Haskell.

  • Python takes some nice features from Haskell.

    ls = [ x for x in [1, 2, 3] if x % == 0]
    # ls = [2]
    
  • Nested list comprehension.

    lss = [[x for x in [1, 2, 3] for y in [1, 1, 1]]
    # lss = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
    

9 Loop and Range in Python

  • Python does not have loop like C++/Java, but it has range and it is better.
items = 'abc'
# 0 <= i < 10
for i in len(items):
    print(items[i])

10 Nested list in Python.

  • Nested list is very easy in Python

    s1 = [1, 2, 3]
    s2 = ['dog', 'cat']
    s3 = [s1, s2]
    print(s3) # [[1, 2, 3], ['dog', 'cat']]
    
  • In Haskell, nested list is similar Python but it is only for the same type.

    • This is main difference between static and dynamic type.
    let s1 = [1, 2, 3]
    let s2 = [11, 22]
    let s3 = [s1, s2] 
    --  s3 = [[1, 2, 3], [11, 22]]
    
  • Also, you need to understand List is a interface and ArrayList is a class in Java.
  • Python is a programming language that you can get stuff done now.
  • Let's sort a list that contains many tuples.
import AronLib as A
ls = [(1, "dog"), (2, "cow"), (0, "cat")]
ls.sort(key=lambda x: x[0])
print(ls)
  • It is very simple code to solve it.
  • If do the same think in Java, then you will need lots more code.

    // add java code to solve above problem.
    // There is no tuple in Java originally, 
    // define a class instead
    // In the old Java, you need to implement Comparable or Comparator
    // But the new Java, you can use lambda to get away it with Collections.sort()
    

11 Concatenation list is super easy in Python.

ls1 = [1, 2, 3]
ls2 = [11, 22]
ls3 = ls1 + ls2
  • In Java, you can us addAll method from the list. It is not very elegrant, but it works.

    • I wish I can overload the \( + \) operator for list, unfortunately Java does not allow operator overloading.
    List<Integer> ls1 = Arrays.asList(1, 2);
    List<Integer> ls2 = Arrays.asList(11, 22);
    ls1.addAll(ls2);
    // ls1 = [1, 2, 11, 22]
    
  • In C++, it is less elegrant if you need to concate two vectors.(We use vector instead of list)

    • list and vector are both STL template container.
      • list is implemented in Double Linkedlist, it is non-cotiguous memory.
      • vector is implemented in array, it is cotiguous memory.

    cppvectorandlist.jpg

  • Here is C++ code to concate two vectors.

    • \( + \) can be overloaded for two vectors if you want to.
    vector<int> v1 = {1, 2, 3};
    vector<int> v2 = {11, 22};
    v1.insert(v1.end(), v2.begin(), v2.end());
    // v2 = {1, 2, 3, 11, 22}
    

12 Slicing in Python is pretty cool too.

ls = [1, 2, 3, 4, 5]
ss = ls[-2:]
# ss = [4, 5]
  • -2: it means take 2 elements from the left.
  • 2: it means take 2 elements from the right.
ls = [1, 2, 3, 4, 5]
ss = ls[2:]
# ss = [1, 2]

pythonlist.jpg

  • In Haskell, you can do the following

    -- take n elements from the left
    let ls = [1, 2, 3, 4, 5]
    let ss = drop (length ls - n) ls
    
  • Python has lambda too. Well everyone uses lambda this day because it is COOL

    f = lambda x, y: x + y
    
  • It is very close to Haskell

    let f = \x y -> x + y
    
    • In C++, lambda function can be defined as following.

      auto f = [](auto& x, auto& y) { return x + y;};
      // or 
      std::function<int(int, int)> f = [](auto& x, auto& y) { return x + y;};
      
    • In Java, lambda function is less flexible.

      Function<Integer, Boolean> f = x -> x % 2 == 0;
      BiFunction<Integer, Integer, Integer> f = (x, y) -> x + y;
      // You need to define your lambda interface if you need to pass more parameters.
      
    • Haskell is more elegant. I should not compare Python and Haskell because they are in different world completely.

13 Python and Matplotlib

  • Install matplotlib
python3 -m pip install -U matplotlib
  • plot \( f(x) = x^3 \)
import matplotlib.pyplot as plt

# plot f(x) = x^3
x = [0.1*x for x in range(-10, 10, 1) ]
y = [(0.1*x)**3 for x in range(-10, 10, 1) ]
plt.plot(x, y)
plt.ylabel('some numbers')
plt.show()

python_cube_equation.png

14 Python pass lambda function to a function

 def fun(f):
    interval = [x for x in range(-10, 10, 1)]
    y = list(map(f, interval))

 # create a lambda function
f = lambda x : x**2
# call f from fun()
fun(f)

15 Python Regex

  • Python regex expression regex Python3 Regex
  • Split word with \W Regex Expression Extension
import re

sentence = 'what is that'
m = re.split(r'\W+', sentence)
print(m)
m1 = re.split(r'(\W+)', sentence)
print(m1)

16 Python loop, list comprehension and iterator tools or itertools

  • Find all integers that satify the following equation

    \begin{align*} a, b, c, d & \in \mathbf{N} \\ a^3 + b^3 + c^3 &= d^3 \end{align*}
  • Python code to solve it, naive way.

    n = [x for x in range(1, 101, 1)]
    for a in n:
      for b in n:
        for c in n:
          for d in n:
            if d > a && d > b && d > c and a**3 + b**3 + c**3 == d**3:
               print(a, b, c, d)
    
  • Better way to solve it.

    ns = [x for x in range(1, 10)]
    tu = [
         (a, b, c, d)
         for a in ns for b in ns for c in ns for d in ns if d > a and d > b and d > c and a**3 + b**3 + c**3 == d**3
    ]
    

17 The difference among array, dictionary, list, set, tuple

  • Python does not have Array like other languages such as Java and C++.
    • Array means it can only contain primary date type
  • Instead Python has list which is similar to Array and it can contain any object
    • list is like vector or list in C++ or ArrayList in Java.
ls1 = [1, 2, 3]
ls2 = ['dog', 'cat', 'cow', 'pig']
  • Dictionary in Python
    • Python has Dictionary or HashMap or HashTable.

      dict = {'dog' : 1, 'cat':2}
      
    • Iterator through Dictionary

      dict = {1:'dog', 2:'cat'}
      for k in dict:
         print(dict[k])
      
  • The difference between Tuple and Dictionary in Python
    • Tuple is like Dictionary but all its elements are immutable.

      t = (1, 2, 3)
      t[0] = 4; # error
      
      dict = {1 : 'dog'}
      dict[1] = 'cat' # no problem
      
  • NumPy does have Array

    import numpy as np
    arr1 = np.array([1, 2, 3])
    ls = [x for x in range(1, 10)]
    arr2 = np.array(ls)
    
    
  • Set in Python

    • The value of set is immutable in Python so it can not contain other set
    myset = set()
    myset.add(1)
    myset.add(2)
    myset.add(1)
    print(myset)
    # {1, 2}
    
    • Add set to set using frozenset in Python

      s1 = set()
      s2 = set()
      s1.add(frozenset(s2))
      

18 Check a variable is string or not

  • Check whether a varaible is string or not in Python
  • When to use it?
    • When a variable is passed into a function, the function needs to know the type of variable.

      def fl(var = None):
          if var is None:
             print('cool')
          elif isinstance(var, string_types):
             print('it is not cool')
          else:
             print('it is awesome')
      
from six import string_types
str = "dog"
if isinstance(str, string_types):
   print("yes")
else:
   print("no")

19 Some differences between Python 2 and Python 3

  • The differences between Python 2 and Python 3 Diff Python 2 and Python 3
  • map return a list in Python 2
  • map return a iterator in Python 3, Yes, I'm always wondering why we need following:

    # Python 3
    ls = [1, 2, 3]
    newlist = list(map(lambda x: x + 1, ls)
    
  • Python 2 has int and long, Python 3 only has int

20 Why Python is so popular?

  • You can code a binary search tree in less then 10 mins
  • In Java, you might need an half hour.

    # Node
    class Node:
      def __init__(self, data):
         self.data = data
         self.left = None
         self.right = None
    
    # insert a node to a binary tree
    # if data < then the current data
    #    traveral to left subtree
    # else
    #    traveral to right subtree
    #
    def insert(root, node):
        if root is None:
           root = node
        else:
           if node.data < root.data:
              if root.left == None:
                 root.left = node
              else:
                 insert(root.left, node)
           else:
              if root.right == None:
                 root.right = node
              else: 
                 insert(root.right, node)
    
    
  • Python code without type, you can pass anything to everything and Python interpeter never complain.

21 Python verison Hell

  • When you run pip install package_name, you might not know which Python version the package uses
    • Ex: I install Rabbit message queue on on FreeBSD, but pip use Python 3.6. On my MacOS, I use Python 3.7 to run all the Python scripts, and Python 3.7 can not find module pika which is Python module for Rabbitmq.
  • I have many Python versions on my MacOS now. I have no idea which to which??

22 Python does not like char function?

  • When you try to conver character to int, ord() is used.

    ord('a') => 97
    chr(97) => 'a'
    
  • No clue who come up the name of function??, 4) Tuple in Python

    t = (1, 2, 3)
    print(t) # => (1, 2, 3)
    t[0] # => 1
    t[1] # => 2
    t[2] # => 3
    # tuple to list
    ls = list(t)
    print(ls) # => [1, 2, 3]
    

23 Python Redis and installation

  • Code in Python Redis
  • Connect to Redis Server
  • Set key and value
  • Retrieve a key
python3 -m pip install redis

Author: cat

Created: 2019-09-29 Sun 23:26

Validate