超级英雄的Python DSA备忘单
#初学者 #编程 #python #面试

这是一个Python备忘单,可用于求解数据结构和算法问题。它涵盖了列表,元素,词典和集合的一些基本和中间操作,以及一些常见的算法及其复杂性。我希望您觉得很有帮助。

Image description

# Python Cheat Sheet for Data Structures and Algorithms

# List and Tuple Operations

# Creating a list or tuple
my_list = [1, 2, 3, 4] # use square brackets for lists
my_tuple = (5, 6, 7, 8) # use parentheses for tuples

# Accessing elements by index
first = my_list[0] # get the first element of the list (index 0)
last = my_tuple[-1] # get the last element of the tuple (index -1)

# Slicing a list or tuple
sublist = my_list[1:3] # get a sublist from index 1 (inclusive) to index 3 (exclusive)
subtuple = my_tuple[:2] # get a subtuple from the beginning to index 2 (exclusive)
reversed_list = my_list[::-1] # get a reversed list using negative step

# Concatenating two lists or tuples
new_list = my_list + [9, 10] # create a new list by adding another list
new_tuple = my_tuple + (11, 12) # create a new tuple by adding another tuple

# Repeating a list or tuple
repeated_list = my_list * 2 # create a new list by repeating the original list twice
repeated_tuple = my_tuple * 3 # create a new tuple by repeating the original tuple three times

# Checking membership of an element
is_in_list = 3 in my_list # returns True if 3 is in the list, False otherwise
is_in_tuple = 9 in my_tuple # returns False if 9 is not in the tuple, True otherwise

# Iterating over a list or tuple
for x in my_list: # loop through each element x in the list
    print(x) # print x

for i, x in enumerate(my_tuple): # loop through each index i and element x in the tuple
    print(i, x) # print i and x

# Unpacking a list or tuple
a, b, c, d = my_list # assign each element of the list to a variable
e, f, g, h = my_tuple # assign each element of the tuple to a variable

列表方法

# List methods (do not apply to tuples)
my_list.append(5) # add an element 5 at the end of the list
my_list.insert(2, 6) # insert an element 6 at index 2 of the list
my_list.remove(4) # remove the first occurrence of element 4 from the list
my_list.pop() # remove and return the last element of the list
my_list.pop(1) # remove and return the element at index 1 of the list
my_list.index(3) # return the index of the first occurrence of element 3 in the list
my_list.count(2) # return the number of times element 2 appears in the list
my_list.sort() # sort the list in ascending order (modify the original list)
my_list.reverse() # reverse the order of the list (modify the original list)
my_list.copy() # return a shallow copy of the list
my_list.clear() # remove all elements from the list

字典操作

  • 字典是不允许重复键的键值对的无序集
  • 词典是可变的(可以更改),并通过钥匙来支持索引,键测试
  • 按密钥或价值或项目进行迭代,并将包装拆开为变量
# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "gender": "female"} # use curly braces and colons for dictionaries

# Accessing values by keys
name = my_dict["name"] # get the value associated with the key "name"
age = my_dict.get("age") # get the value associated with the key "age" or None if not found

# Adding or updating key-value pairs
my_dict["email"] = "alice@gmail.com" # add a new key-value pair to the dictionary
my_dict["age"] = 26 # update the value associated with the key "age"

# Removing key-value pairs
del my_dict["gender"] # delete the key-value pair with the key "gender" from the dictionary
email = my_dict.pop("email") # remove and return the value associated with the key "email"
name, age = my_dict.popitem() # remove and return an arbitrary key-value pair as a tuple

# Checking membership of a key
is_in_dict = "name" in my_dict # returns True if "name" is a key in the dictionary, False otherwise

# Iterating over a dictionary
for key in my_dict: # loop through each key in the dictionary
    print(key) # print key

for value in my_dict.values(): # loop through each value in the dictionary
    print(value) # print value

for key, value in my_dict.items(): # loop through each key-value pair in the dictionary
    print(key, value) # print key and value

# Unpacking a dictionary into variables
name, age, gender = my_dict # assign each key of the dictionary to a variable
{"name": name, "age": age, "gender": gender} = my_dict # assign each value of the dictionary to a variable

字典方法

my_dict.keys() # return a view object of the keys of the dictionary
my_dict.values() # return a view object of the values of the dictionary
my_dict.items() # return a view object of the key-value pairs of the dictionary
my_dict.update({"city": "New York", "age": 27}) # update the dictionary with another dictionary or iterable
my_dict.copy() # return a shallow copy of the dictionary
my_dict.clear() # remove all key-value pairs from the dictionary

设置操作

  • 集合是不允许重复的元素的无序集合
  • 集合是可变的(可以更改)并支持会员资格测试,迭代和数学集操作

# Creating a set
my_set = {1, 2, 3, 4} # use curly braces for sets (but no colons)
empty_set = set() # use the set() function to create an empty set

# Adding or removing elements
my_set.add(5) # add an element 5 to the set
my_set.remove(4) # remove an element 4 from the set (raises KeyError if not found)
my_set.discard(3) # remove an element 3 from the set (does nothing if not found)
my_set.pop() # remove and return an arbitrary element from the set (raises KeyError if empty)
my_set.clear() # remove all elements from the set

# Checking membership of an element
is_in_set = 2 in my_set # returns True if 2 is in the set, False otherwise

# Iterating over a set
for x in my_set: # loop through each element x in the set
    print(x) # print x

字符串方法

这些字符串方法可能有助于求解您在诸如LeetCode之类的平台上可能会在数据结构和算法问题中遇到的各种字符串操作问题。

my_string = "   Hello, World!   "

# Length of a string
length = len(my_string)
print(length)  # Output: 19

# Splitting a string into a list
my_list = my_string.split(" ")
print(my_list)  # Output: ['', '', '', 'Hello,', 'World!', '', '', '']

# Joining elements of a list into a string
my_string = " ".join(my_list)
print(my_string)  # Output:    Hello, World!

# Checking if a substring exists in a string
if "Hello" in my_string:
    print("Substring found!")  # Output: Substring found!

# Replacing occurrences of a substring
new_string = my_string.replace("World", "Python")
print(new_string)  # Output:    Hello, Python!

# Converting a string to lowercase/uppercase
lowercase = my_string.lower()
uppercase = my_string.upper()
print(lowercase)  # Output:    hello, world!
print(uppercase)  # Output:    HELLO, WORLD!

# Checking if a string starts/ends with a specific substring
starts_with_hello = my_string.startswith("Hello")
ends_with_exclamation = my_string.endswith("!")
print(starts_with_hello)  # Output: False
print(ends_with_exclamation)  # Output: True

# Removing leading/trailing whitespace from a string
stripped_string = my_string.strip()
print(stripped_string)  # Output: Hello, World!

# Checking if a string is alphanumeric
is_alphanumeric = my_string.isalnum()
print(is_alphanumeric)  # Output: False

# Counting occurrences of a substring
count = my_string.count("Hello")
print(count)  # Output: 1