%load_ext nb_black
Python Built-in Methods¶
Number¶
Get Multiples of a Number Using Modulus¶
If you want to get multiples of a number, use the modulus operator %
. The modulus operator is used to get the remainder of a division. For example, 4 % 3 = 1
, 5 % 3 = 2
.
Thus, to get multiples of n
, we select only numbers whose remainders are 0 when dividing them by n
.
def get_multiples_of_n(nums: list, n: int):
"""Select only numbers whose remainders
are 0 when dividing them by n"""
return [num for num in nums if num % n == 0]
nums = [1, 4, 9, 12, 15, 16]
get_multiples_of_n(nums, 2) # multiples of 2
[4, 12, 16]
get_multiples_of_n(nums, 3) # multiples of 3
[9, 12, 15]
get_multiples_of_n(nums, 4) # multiples of 4
[4, 12, 16]
fractions: Get Numerical Results in Fractions instead of Decimals¶
Normally, when you divide a number by another number, you will get a decimal:
2 / 3 + 1
1.6666666666666665
Sometimes, you might prefer to get the results in fractions instead of decimals. There is Python built-in function called fractions that allows you to do exactly that. The code above shows how it works:
from fractions import Fraction
res = Fraction(2 / 3 + 1)
print(res)
3752999689475413/2251799813685248
Cool! We got a fraction instead of a decimal. To limit the number of decimals displayed, use limit_denominator()
.
res = res.limit_denominator()
print(res)
5/3
What happens if we divide the result we got from Fraction
by another number?
print(res / 3)
5/9
Nice! We got back a fraction without using the Fraction
object again.
Being able to turn decimals into fractions is nice, but what if want to get other nice math outputs in Python such as \(\sqrt{8} = 2\sqrt{2}\)? That is when SymPy comes in handy.
How to Use Underscores to Format Large Numbers in Python¶
large_num = 1_000_000
large_num
1000000
Confirm whether a variable is a number¶
from numbers import Number
a = 2
b = 0.4
isinstance(a, Number)
True
isinstance(b, Number)
True
Boolean Operators: Connect Two Boolean Expressions into One Expression¶
movie_available = True
have_money = False
get_excited = movie_available | have_money
get_excited
True
buy = movie_available & have_money
buy
False
String¶
String find: Find the Index of a Substring in a Python STring¶
sentence = "Today is Saturaday"
# Find the index of first occurrence of the substring
sentence.find("day")
2
# Start searching for the substring at index 3
sentence.find("day", 3)
15
sentence.find("nice")
# No substring is found
-1
re.sub: Replace One String with Another String Using Regular Expression¶
import re
text = "Today is 3/7/2021"
match_pattern = r"(\d+)/(\d+)/(\d+)"
re.sub(match_pattern, "Sunday", text)
'Today is Sunday'
re.sub(match_pattern, r"\3-\1-\2", text)
'Today is 2021-3-7'
List¶
any: Check if Any Element of an Iterable is True¶
text = "abcdE"
any(c for c in text if c.isupper())
True
Extended Iterable Unpacking: Ignore Multiple Values when Unpacking a Python Iterable¶
a, *_, b = [1, 2, 3, 4]
print(a)
1
b
4
_
[2, 3]
How to Unpack Iterables in Python¶
nested_arr = [[1, 2, 3], ["a", "b"], 4]
num_arr, char_arr, num = nested_arr
num_arr
[1, 2, 3]
char_arr
['a', 'b']
Class¶
str and repr: Create a String Representation of a Python Object¶
class Food:
def __init__(self, name: str, color: str):
self.name = name
self.color = color
def __str__(self):
return f"{self.color} {self.name}"
def __repr__(self):
return f"Food({self.color}, {self.name})"
food = Food("apple", "red")
print(food) # str__
red apple
food # __repr__
Food(red, apple)