03. math, random

最後更新: 2015-06-03

目錄

 


除數的處理

 

>>> 1/2

0

>>> 1.0/2

0.5

>>> from __future__ import division

>>> 1 / 2

0.5

>>> 1//2

0

 


指數表達

 

>>> 2**3

8

 


Complex munber

 

>>> import cmath

>>> cmath.sqrt(-1)

1j

>>> (1+1j)*(1-1j)

(2+0j)

 


16 進及 8 進制

 

>>> 0xff

255

>>> 010

8

 


range()

 

range([start,] stop [, step])

>>> range(10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(5,10)

[5, 6, 7, 8, 9]

>>> range(0,10,2)

[0, 2, 4, 6, 8]

 


Math. Function

 

>>> import math

>>> pow(2,3)

>>> abs(-1)

>>> math.floor(0.7)
0.0

>>> math.ceil(0.7)

>>> int(0.0)
0

>>> round(number[, ndigits])

 


PI

 

from math import pi

 



Random

 

import random

# Initialize the basic random number generator.

# omitted => current system time is used

random.seed([x])

# 浮點

random.random()

# 整數

random.randint(0,99)

# 偶數

random.randrange(0, 101, 2)

# 任何 2 個不帶重複的, return list

random.sample('abcdefghij', 2)

P.S.

選 11 個時 => "raise ValueError("sample larger than population")"

# 任何一個生字

random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )

# shuffles a list in-place

items = [1, 2, 3, 4, 5, 6]
random.shuffle(items)

應用

# a-z, A-Z, 0-9 的 8 位 password

newpw = ''.join(random.sample('abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789', 8))

 


 

Creative Commons license icon Creative Commons license icon