Introduction to Python Programming

June 09, 2023

List

def example():
  def insert(lst, *args):
    for arg in args:
      lst.append(arg)

  def show(dataset):
    for index, value in enumerate(dataset):
      print(f"{index} => {value}")

  onlineCourse = ['MIT OpenCourseWare', 'Coursera', 'edX']
  # show(onlineCourse)
  # print(type(onlineCourse))

  insert(onlineCourse, 'Udemy', 'Udacity')
  show(onlineCourse)

if __name__ == '__main__':
  example()

Dictionaries

def example():
  def insert(dataset, **kwargs):
    for kw in kwargs:
      dataset.update({kw: kwargs[kw]}) 

  def show(dataset):
    for key, value in dataset.items():
      print(f"\"{key}\", url = {value}")

  onlineCourse = {'MIT OpenCourseWare': 'https://ocw.mit.edu/',
                  'Coursera'          : 'https://www.coursera.org/',
                  'edX'               : 'https://www.edx.org/'}
  
  print(type(onlineCourse))

  show(onlineCourse)

  insert(onlineCourse, Udemy   = 'https://www.udemy.com/', 
                       Udacity = 'https://www.udacity.com/')

  show(onlineCourse)

if __name__ == '__main__':
  example()

Map

def example():
  dataset = list(range(1, 10 + 1, 1))

  xs = list(map((lambda x: x ** 2), dataset))
  ys = list(map((lambda x: x ** 3), dataset))

  print(dataset) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  print(xs)      # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
  print(ys)      # [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

if __name__ == '__main__':
  example()

Filter

def example():
  dataset = list(range(-5, 5 + 1, 1))

  pos_lst = list(filter((lambda x: x > 0), dataset))
  neg_lst = list(filter((lambda x: x < 0), dataset))

  print(dataset) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
  print(pos_lst) # [1, 2, 3, 4, 5]
  print(neg_lst) # [-5, -4, -3, -2, -1]

if __name__ == '__main__':
  example()

Reduce

from functools import reduce
import operator

def example():
  # create the dataset
  dataset = list(range(-5, 5 + 1, 1))

  # get all positive elements in the list
  pos_lst = list(filter(lambda x: x > 0, dataset)) 

  # scale the list
  div_lst = list(map(lambda x: x / 2, pos_lst))

  # usage of the operator and reduce to evaluate 
  # the element in the list to a single value.
  result  = reduce(operator.add, div_lst)

  print(dataset) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
  print(pos_lst) # [1, 2, 3, 4, 5]
  print(div_lst) # [0.5, 1.0, 1.5, 2.0, 2.5]
  print(result)  # 7.5

if __name__ == '__main__':
  example()

Primality Test

def is_prime(n):
  for x in [i for i in range(2, n + 1, 1) if i <= n / i]:
    if n % x == 0:
      return False
  return True

def find_prime(m, n):
  return [i for i in range(m, n + 1, 1) if is_prime(i)]

def example():
  print(find_prime(1, 30)) # [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

if __name__ == '__main__':
  example()

Combination

Definition

Factorial
n!=n×(n1)×(n2)×...×2×1=n×(n1)!n! = n \times (n - 1) \times (n - 2) \times ... \times 2 \times 1 = n \times (n - 1)!
Number of kk-Combinations
C(n,k)=Ckn=(kn)=n!k!(nk)!C(n, k) = C^n_k = ({}^n_k) = \frac{n!}{k!(n - k)!}

Example

import itertools as it

def factorial(n):
  return 1 if n == 1 else n * factorial(n - 1)

def comb(n, k):
  return factorial(n) / (factorial(k) * factorial(n - k))

def example():
  dataset = [1, 2, 3, 4]

  xs = list(it.combinations(dataset, 2))
  ys = list(it.combinations(dataset, 3))

  assert len(xs) == comb(len(dataset), 2)
  assert len(ys) == comb(len(dataset), 3)

  print(xs) # [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
  print(ys) # [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

if __name__ == '__main__':
  example()

Permutations

import itertools as it

def example():
  def printAllPermutations(dataset):      
    for i in range(len(dataset)):
      xs = list(it.permutations(dataset, i + 1))
      print(xs)

  dataset = list(range(1, 3 + 1, 1)) # [1, 2, 3]

  printAllPermutations(dataset)
  # [(1,), (2,), (3,)]
  # [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
  # [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

if __name__ == '__main__':
  example()

Use SymPy to Compute Limits

Encapsulation of SymPy

import sympy as sy

class SymMath:
  x = sy.Symbol("X")

  @staticmethod
  def limitOf(f, n):
    return sy.limit(f, SymMath.x, n)

e=limx0(1+x)1x=limn(1+1n)nx=1ne = \lim\limits_{x \to 0}(1 + x)^{\frac{1}{x}} = \lim\limits_{n \to \infty}(1 + \frac{1}{n})^n \text{, } x = \frac{1}{n}

print(SymMath.limitOf((1 + SymMath.x) ** (1 / SymMath.x), 0))  
print(SymMath.limitOf((1 + 1 / SymMath.x) ** SymMath.x, sy.S.Infinity)) 

limx0sin(x)x=1\lim\limits_{x \to 0}\frac{sin(x)}{x} = 1

print(SymMath.limitOf((sy.sin(SymMath.x) / SymMath.x), 0)) 

limx0cos(x)1x=0\lim\limits_{x \to 0}\frac{cos(x) - 1}{x} = 0

print(SymMath.limitOf(((sy.cos(SymMath.x) - 1) / SymMath.x), 0))

Complete Example Code

import sympy as sy

class SymMath:
  x = sy.Symbol("X")

  @staticmethod
  def limitOf(f, n):
    return sy.limit(f, SymMath.x, n)

def example():
  print(SymMath.limitOf((1 + SymMath.x) ** (1 / SymMath.x), 0))           # E
  print(SymMath.limitOf((1 + 1 / SymMath.x) ** SymMath.x, sy.S.Infinity)) # E
  print(SymMath.limitOf((sy.sin(SymMath.x) / SymMath.x), 0))              # 1
  print(SymMath.limitOf(((sy.cos(SymMath.x) - 1) / SymMath.x), 0))        # 0

if __name__ == '__main__':
  example()

Random Integers Matrix

import numpy as np

class Matrix:
  def __init__(self, rows, cols, start, stop):
    assert rows > 0 and cols > 0
    self.data  = np.random.randint(start, stop + 1, size = (rows, cols))
    self.row   = self.data.shape[0]
    self.colum = self.data.shape[1]

  def __str__(self):
    return f"Matrix = \n{self.data}"

def example():
  m1 = Matrix(3, 4, -12345, 67890)
  print(m1)
  print(f"row = {m1.row}")
  print(f"column = {m1.colum}")

if __name__ == '__main__':
  example()

Profile picture

Written by Gapry, 魏秋
Twitter | GitHub | Facebook | Mastodon