1. Retrieve matching records between two tables
SELECT * FROM table_b
JOIN table_a ON table_a.username = table_b.username;
2. Normalize consecutive repeated characters using regex
Given input_str = "abbbccc", ensure only a single b appears.
import re
normalized = re.sub(r'b+', 'b', input_str)
3. Library for XPath queries in Python
from lxml import etree
4. Check the length of a Redis list
LLEN my_list_key
5. Preventing duplicate data processing in multithreading
Maintain a shared visited_set protected by a threading.Lock. Before processing an item, acquire the lock, check if the item exists in the set, and add it if it does not.
6. Sort a dictionary by its values
data = {'a': 24, 'g': 52, 'l': 12, 'k': 33}
sorted_items = sorted(data.items(), key=lambda item: item[1])
7. Managing excessive fingerprints in Redis
- Apply TTL (Time to Live) to keys.
- Schedule periodic cleanup jobs.
- Configure data persistence (RDB/AOF).
- Utilize master-slave replication.
8. Definition of a function
A function is a reusable block of code designed to perform a specific task. It enhances modularity and reduces code repetition. Users can define custom functions beyond the built-in ones.
9. Difference between self and cls
self refers to an instance of a class, while cls refers to the class itself. cls is typically used in @classmethod decorators, whereas self is used in standard instance methods.
10. Storing media files
It is common practice to store media files (images, videos) on cloud storage services and save the corresponding acces URLs in the database.
11. Swap two variables without a temporary variable
x, y = 1, 2
x, y = y, x
12. Calculate day position in year, month, and week
import datetime
current_date = datetime.datetime.now()
year = current_date.year
month = current_date.month
day = current_date.day
# Day of the year
day_of_year = current_date.strftime('%j')
# Day of the month
print(f"Day of month: {day}")
# Day of the week (Monday=1, Sunday=7)
week_day = current_date.isoweekday()
print(f"Day of week: {week_day}")
13. Overview of MD5
MD5 generates a 128-bit hash value (fingerprint) from input data of any length. It is deterministic but irreversible. Common uses include:
- Integrity verification
- Hiding plaintext data
- Digital signatures
14. Hash Tables
A hash table is a structure that maps keys to values for efficient lookup. By providing a key, the corresponding value can be retrieved in near-constant time.
15. Python Magic Methods
Magic methods (dunder methods) allow customization of class behavior:
__init__: Instance initializer.__new__: Creates and returns a new instance (called before__init__).__call__: Allows an instance to be called like a function.__getattribute__: Defines behavior when accessing attributes.
16. Character Sets and Encodings
A character set is a collection of characters. Encoding is the method of representing these characters as binary numbers.
- ASCII: Standard for English characters.
- GB2312: Encoding for Simplified Chinese.
- Unicode: Aims to cover all characters globally.
17. Remove the maximum value from a list
numbers = [1, 3, 5, 7]
numbers.remove(max(numbers))
18. requests: content vs text
response.textreturns data as a string (Unicode).response.contentreturns data in bytes (binary), suitable for images or files.
19. Return value of conn.execute()
It typically returns the number of rows affected by the SQL operation.
20. Fetching results from a database cursor
cursor.fetchone() # Single record
cursor.fetchall() # All records
cursor.fetchmany(size=3) # Specific number of records
21. Using dir()
The dir() function lists all attributes and methods available on an object.
22. Ensert a number in to a sorted list
sorted_numbers = [0, 10, 20, 30, 40, 50]
new_val = 25
sorted_numbers.append(new_val)
sorted_numbers.sort()
23. Generate Fibonacci sequence
limit = 10
fib_sequence = [0, 1]
for i in range(2, limit):
next_val = fib_sequence[-1] + fib_sequence[-2]
fib_sequence.append(next_val)
print(fib_sequence)