Created
August 19, 2024 05:33
-
-
Save neybapps/1eb60d9bedb9f9bbbec817c7ad612a86 to your computer and use it in GitHub Desktop.
Pythonic Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# unpacking | |
point1 = [0, 0] | |
point2 = [2, 4] | |
x1, y1 = point1 # x1 = 0, y1 = 0 | |
x2, y2 = point2 # x2 = 2, y2 = 4 | |
slope = (y2 - y1) / (x2 - x1) | |
print(slope) # Output: 2.0 | |
# Loop Unpacking | |
points = [[0, 0], [2, 4], [3, 6], [5, 10]] | |
for x, y in points: | |
print(f"x: {x}, y: {y}") | |
# Enumerate | |
# without | |
nums = [2, 7, 9, 2] | |
for i in range(len(nums)): | |
n = nums[i] | |
print(i, n) | |
# with | |
nums = [2, 7, 9, 2] | |
for i, n in enumerate(nums): | |
print(i, n) | |
# Zip | |
names = ['Alice', 'Bob', 'Charlie', 'David'] | |
scores = [90, 85, 88, 92] | |
for name, score in zip(names, scores): | |
print(f"{name} scored {score}") | |
# Inequality | |
# Regular way: | |
x = 5 | |
if 0 < x and x < 10: | |
print('x is between 0 and 10') | |
# is equivalent to: | |
x = 5 | |
if 0 < x < 10: | |
print('x is between 0 and 10') | |
# Min Max Shortcut | |
transactions = -2 | |
if transactions < 0: | |
transactions = 0 | |
#into: | |
transactions = -2 | |
transactions = max(0, transactions) | |
transactions = 101 | |
# This will ensure transactions is never greater than 100 | |
if transactions > 100: | |
transactions = 100 | |
# This is equivalent to the above code | |
transactions = min(100, transactions) | |
# reverse sort | |
elements = [5, 3, 6, 2, 1] | |
elements.sort(key=None, reverse=True) | |
elements.reverse() | |
def get_word_length(word: str) -> int: | |
return len(word) | |
words = ["apple", "banana", "kiwi", "pear", "watermelon", "blueberry", "cherry"] | |
words.sort(key=get_word_length) | |
print(words) # ['kiwi', 'pear', 'apple', 'banana', 'cherry', 'blueberry', 'watermelon'] | |
words = ["apple", "banana", "kiwi", "pear", "watermelon", "blueberry", "cherry"] | |
words.sort(key=lambda word: len(word)) | |
words = ["kiwi", "pear", "apple", "banana", "cherry", "blueberry"] | |
sorted_words = sorted(words) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment