-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharray.py
More file actions
109 lines (81 loc) · 1.64 KB
/
array.py
File metadata and controls
109 lines (81 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Arrays (called lists in python)
arr = [1, 2, 3]
print(arr)
# Can be used as a stack
arr.append(4)
arr.append(5)
print(arr)
arr.pop()
print(arr)
arr.insert(1, 7)
print(arr)
arr[0] = 0
arr[3] = 0
print(arr)
# Initialize arr of size n with default value of 1
n = 5
arr = [1] * n
print(arr)
print(len(arr))
# Careful: -1 is not out of bounds, it's the last value
arr = [1, 2, 3]
print(arr[-1])
# Indexing -2 is the second to last value, etc.
print(arr[-2])
# Sublists (aka slicing)
arr = [1, 2, 3, 4]
print(arr[1:3])
# Similar to for-loop ranges, last index is non-inclusive
print(arr[0:4])
# But no out of bounds error
print(arr[0:10])
# Unpacking
a, b, c = [1, 2, 3]
print(a, b, c)
# Be careful though
# a, b = [1, 2, 3]
# Loop through arrays
nums = [1, 2, 3]
# Using index
for i in range(len(nums)):
print(nums[i])
# Without index
for n in nums:
print(n)
# With index and value
for i, n in enumerate(nums):
print(i, n)
# Loop through multiple arrays simultaneously with unpacking
nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
for n1, n2 in zip(nums1, nums2):
print(n1, n2)
# Reverse
nums = [1, 2, 3]
nums.reverse()
print(nums)
# Sorting
arr = [5, 4, 7, 3, 8]
arr.sort()
print(arr)
arr.sort(reverse=True)
print(arr)
arr = ["bob", "alice", "jane", "doe"]
arr.sort()
print(arr)
# Custom sort (by length of string)
arr.sort(key=lambda x: len(x))
print(arr)
# List comprehension
arr = [i for i in range(5)]
print(arr)
# 2-D lists / Matrix
# creating 4 unique rows
arr = [[0] * 4 for i in range(4)]
print(arr)
print(arr[0][0], arr[3][3])
# This won't work
# arr = [[0] * 4] * 4
# 3 (row) * 4 (col) matrix
mat = [[0] * 4 for row in range(3)]
print(mat)