0% found this document useful (0 votes)
6 views

data structure 总结

Uploaded by

AILIN ZHANG
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

data structure 总结

Uploaded by

AILIN ZHANG
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Primitive data type:

a=5
b=3
print(a + b) # Addition: 8
print(a - b) # Subtraction: 2
print(a * b) # Multiplication: 15
print(a / b) # Division: 1.6666666666666667
print(a // b) # Floor Division: 1 5/3 = 1.666, floor division use the nearest int not larger
1.66 -> 1
print(a % b) # Modulus: 2 5÷3=1 with a remainder of 2
print(a ** b) # Exponentiation: 125

Python have no “char”


c = 'a'
print(c) # Output: 'a'
print(c.upper()) # Converts to uppercase: 'A'
print(c.isalpha()) # Checks if alphabetic: True

Bitwise operation:

Bitwise AND (&)


Example:
a = 12 # In binary: 1100
b = 10 # In binary: 1010

result = a & b # Result: 8 (In binary: 1000)


print(result) # Output: 8

2. Bitwise OR (|)

● Operation: Each bit of the output is 1 if the corresponding bit of either operand is
1. If both are 0, the result is 0.

Example:
a = 12 # In binary: 1100
b = 10 # In binary: 1010

result = a | b # Result: 14 (In binary: 1110)

● print(result) # Output: 14
XOR stands for "Exclusive OR." It is a bitwise operation that compares two bits and
returns 1 if the bits are different and 0 if they are the same.

Bitwise XOR (^)


Example:
a = 12 # In binary: 1100
b = 10 # In binary: 1010

result = a ^ b # Result: 6 (In binary: 0110)

● print(result) # Output: 6

Bitwise NOT (~)

● Operation: This operation inverts all the bits of the operand. Each 1 becomes 0,
and each 0 becomes 1. It’s a unary operator (operates on a single operand).
● Note: In Python, the result of ~x is -x-1 because Python integers are signed.

Example:
python
Copy code
a = 12 # In binary: 00000000 00000000 00000000 00001100

result = ~a # Result: -13 (In binary: 11111111 11111111 11111111 11110011)

● print(result) # Output: -13

Left Shift (<<)

● Operation: Shifts the bits of the number to the left by a specified number of
positions. Each left shift multiplies the number by 2.

Example:
python
Copy code
a = 5 # In binary: 0000 0101

result = a << 2 # Shift left by 2 positions: 0001 0100 (Result: 20)


● print(result) # Output: 20

Right Shift (>>)

● Operation: Shifts the bits of the number to the right by a specified number of
positions. Each right shift divides the number by 2 (integer division).

Example:
python
Copy code
a = 20 # In binary: 0001 0100

result = a >> 2 # Shift right by 2 positions: 0000 0101 (Result: 5)

● print(result) # Output: 5

Mask in python:

# Example 1: Selecting Specific Bits (Using AND with a Mask)

number = 0b10101100 # 172 in decimal

mask = 0b00001111 # Select the last 4 bits

result = number & mask

print(bin(result)) # Output: 0b1100 (12 in decimal)

# Example 2: Setting Specific Bits (Using OR with a Mask)

number = 0b10101100 # 172 in decimal

mask = 0b00000101 # Set the 3rd and 1st bits from the right

result = number | mask


print(bin(result)) # Output: 0b10101101 (173 in decimal)

Parity of a word:

Parity of a binary word is 1 if the number of 1s in the word is odd(奇数)

Parity is 0 ir the number of 1s in the word is even(偶数)

Count parity of a very large 64 bit binary word:

1101101001111001011010110101010111100101011010111101101010101010

Iterate and count 1

If count %% 2 == 1 return 1

== 0 return 0

Heap

container in python? yes


which python library
how it is implemented arry with index, minheap, import heapq
does it have iterator? no
immutable? no, heappush, heappop modify heap itself
add time complx O(logn) heappush
get time complx
remove complx O(logN)heappop
sort o(n) heapify
k largest nlargest / nsmallest
is element in stored in continuous block of
memory yes
什么时候用 priority queue, scheduling
get min/max O(1), O(logN) for
insert/remove, space efficient no pointer
advantage used
not good for fast search arbitrary item, do
disadvantage not support fast deletion of arbitrary item

import heapq

# Create a heap
heap = []
heapq.heapify(heap) # O(n)

# Add elements
heapq.heappush(heap, 3) # O(log n)
heapq.heappush(heap, 1)
heapq.heappush(heap, 4)

# Remove smallest element


smallest = heapq.heappop(heap) # O(log n)
print(smallest) # 1

# Peek at smallest element without removing


print(heap[0]) # O(1)

# Replace smallest element


heapq.heapreplace(heap, 2) # O(log n)

# Find k smallest elements


k_smallest = heapq.nsmallest(2, heap) # O(n log k)
print(k_smallest) # [2, 3]

import heapq

heap = [3, 1, 4, 1, 5, 9, 2, 6]
heapq.heapify(heap)

largest = max(heap) #O(n) for max()


heapq.heapreplace(heap, float('-inf')) # O(log n) for heapreplace()
print(largest) # Output: 9
Tuple

container in python? yes


which python library
how it is implemented array of pointers
does it have iterator? yes
immutable? yes
O(n) immutable need to create new tuple
add time complx with new element
O(n) array in contiguous memory with no
get time complx index/hashing, linear find
O(n) immutable cannot remove, need to
remove complx create new tuple without element
Use Timsort, O(n log n) like in list sort
sort
count Allow multiple duplicate items
k largest No, but you can use heapq
is element in stored in continuous block of
memory yes
immutable, dictionary keys, coordinates,
什么时候用 etc

1. immutability: Provides data integrity


and security
2. Memory efficiency: Use less memory
than lists
3. Performance: Faster for certain
operations due to their simplicity
4. Can be used as dictionary keys and
set elements (unlike lists)
5. Useful for multiple variable
assignment and unpacking
6. Ordered, allowing reliable indexing
advantage
disadvantage
1. Immutability: Cannot be modified
after creation
2. Less flexible than lists (fewer built-in
methods)
3. Cannot be sorted in-place
4. Limited functionality compared to
lists (e.g., no append, remove, or
insert methods)

Tuple lambda sort

# List of tuples (name, age, score)


students = [
("Alice", 22, 95),
("Bob", 19, 88),
("Charlie", 21, 92),
("David", 20, 90),
("Eve", 18, 98)
]

# Sort by age (second element)


sorted_by_age = sorted(students, key=lambda x: x[1])
print("Sorted by age:")
for student in sorted_by_age:
print(student)

# Sort by score (third element) in descending order


sorted_by_score = sorted(students, key=lambda x: x[2], reverse=True)
print("\nSorted by score (descending):")
for student in sorted_by_score:
print(student)

# Sort by name length, then by age


sorted_complex = sorted(students, key=lambda x: (len(x[0]), x[1]))
print("\nSorted by name length, then age:")
for student in sorted_complex:
print(student)
# Tuple operations and their time complexities

# Creating a tuple
# Time complexity: O(n), where n is the number of elements
my_tuple = (1, 2, 3, 4, 5)

# Accessing an element by index


# Time complexity: O(1)
element = my_tuple[2] # Access the third element

# Slicing a tuple
# Time complexity: O(k), where k is the size of the slice
slice = my_tuple[1:4] # Get elements from index 1 to 3

# Concatenation
# Time complexity: O(n + m), where n and m are the lengths of the tuples being
concatenated
new_tuple = my_tuple + (6, 7, 8)

# Length of a tuple
# Time complexity: O(1)
length = len(my_tuple)

# Checking membership
# Time complexity: O(n) - requires linear search
is_present = 3 in my_tuple

# Count occurrences of an element


# Time complexity: O(n) - requires traversing the entire tuple
count = my_tuple.count(2)

# Find index of an element


# Time complexity: O(n) - requires linear search
index = my_tuple.index(4)

# Tuple unpacking
# Time complexity: O(n), where n is the number of elements being unpacked
a, b, c = (1, 2, 3)

# Iteration
# Time complexity: O(n), where n is the number of elements in the tuple
for item in my_tuple:
print(item)

# Sorting a list of tuples


# Time complexity: O(n log n), where n is the number of tuples
sorted_tuples = sorted([(3, 'c'), (1, 'a'), (2, 'b')])

# Finding k largest elements using heapq


# Time complexity: O(n log k), where n is the number of elements and k is the number
of largest elements to find
import heapq
k_largest = heapq.nlargest(2, my_tuple)

# Finding k smallest elements using heapq


# Time complexity: O(n log k), where n is the number of elements and k is the number
of smallest elements to find
k_smallest = heapq.nsmallest(2, my_tuple)

# Comparing tuples
# Time complexity: O(n), where n is the number of elements to compare
comparison_result = (1, 2, 3) < (1, 2, 4)

# Creating a tuple from an iterable


# Time complexity: O(n), where n is the number of elements in the iterable
list_to_tuple = tuple([1, 2, 3, 4, 5])

# Multiplying a tuple (repetition)


# Time complexity: O(n * k), where n is the length of the original tuple and k is the
multiplier
repeated_tuple = my_tuple * 3

# Checking equality of tuples


# Time complexity: O(n), where n is the number of elements in the tuples
are_equal = (1, 2, 3) == (1, 2, 3)

# Note: Tuples are immutable, so operations like append, remove, or in-place sort are
not available.
BST binary search trees
BST definition: any left subtree node value < current node < right subtree node value
No duplication

container in python? no
which python library
how it is implemented node
does it have iterator? no
immutable? No, most likely implemented mutable
add time complx/insert Average logN, worst N
get time complx/search Average logN, worst N
remove complx Average logN, worst N
Don’t need to sort, do in order traversal
To maintain logN, need to do self balanced
sort tree like RED BLACK Tree or AVL tree
k largest Average logN, worst N
No, use node for implementation
is element in stored in continuous block of linked structure of individually allocated
memory nodes
什么时候用
Efficient search, remove, insert, O(log n),
good for database indexing, search, quick
advantage file system access
1. Not self-balanced, if unbalanced
become O(N) end up being a linked
list
2. Need extra memory for node,
memory overload
3. Bad cache performance, node
disadvantage structure use uncontigous memory

You might also like