原文链接https://cs231n.github.io/python-numpy-tutorial/Python Tutorial With Google Colab
检查python版本
!python --version
经典快速排序
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
print(quicksort([3,6,8,10,1,2,1]))
数据类型
- int
x = 3
print(x, type(x))
3 <class ‘int’>
- float
y = 2.5
print(type(y))
print(y, y + 1, y * 2, y ** 2)
<class ‘float’>
2.5 3.5 5.0 6.25
- Booleans
t, f = True, False
print(type(t))
<class ‘bool’>
print(t and f) # Logical AND;
print(t or f) # Logical OR;
print(not t) # Logical NOT;
print(t != f) # Logical XOR;
False
True
False
True
- strings
hello = 'hello'
#String literals can use single quotes
world = ''world"
# or double quotes, it does not matter
print(hello, len(hello))
hello 5
hw = hello + ' ' + world # String concatenation print(hw)
hello world
hw12 = '{} {} {}'.format(hello, world, 12) # string formatting print(hw12)
hello world 12
String objects have a bunch of useful methods; for example:
s = "hello"
print(s.capitalize()) # Capitalize a string
print(s.upper()) # Convert a string to uppercase; prints "HELLO"
print(s.rjust(7)) # Right-justify a string, padding with spaces
print(s.center(7)) # Center a string, padding with spaces
print(s.replace('l', '(ell)')) # Replace all instances of one substring with another
print(' world '.strip()) # Strip leading and trailing whitespace
Hello
HELLO
hello
hello
he(ell)(ell)o
world
容器
- Lists
A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:
xs = [3, 1, 2] # Create a list
print(xs, xs[2])
print(xs[