상세 컨텐츠

본문 제목

Built-in Functions

Python

by techbard 2024. 11. 28. 16:38

본문

반응형

 

# Building functionality that already exists from scratch
# in most cases in going to be a complete waste of time.

# args -> *values, *args
# So we can pass in an unlimited amount of argument by default.

print('a', 'b', 'c', sep='|')

people: list[str] = ['Mario', 'James', 'Hannah']
print(*people, sep=', ', end='.') # It's inserting them as argument, not as a list.
print('\n', end='')
print(people)

# 결과
a|b|c
Mario, James, Hannah.
['Mario', 'James', 'Hannah']

 

# iterable을 대상으로 해서
# 모두가 True 일때만 True -> all()
# 그중 하나만 True 일때도 True -> any()
 
ls = [True, False]
print(all(ls))
 
# 결과
False
 
ls = [True, True]
print(all(ls))
 
# 결과
True
 
ls = [False, False]
print(all(ls))
 
# 결과
False
 
ls = [True, False]
print(any(ls))
 
# 결과
True
 
ls = [False, False]
print(any(ls))
 
# 결과
False
 
tof_ls = [10/2, 1 > 2, True]
print(all(tof_ls))
 
# 결과
False

 

# all(iterable)
wifi_enabled: bool = True
has_electricity: bool = False
has_subscription: bool = True

if wifi_enabled and has_electricity and has_subscription:
    print("(1) Connected to internet!")
else:
    print("(1) Connection failed to internet!")

requirements: list[bool] = \
    [wifi_enabled, has_electricity, has_subscription]

if all(requirements):
    print("(2) Connected to internet!")
else:
    print("(2) Connection failed to internet!")

# 모두가 True 이면
false_idx = requirements.index(False)
requirements[false_idx] = True

if all(requirements):
    print("(3) Connected to internet!")
else:
    print("(3) Connection failed to internet!")

# 결과
(1) Connection failed to internet!
(2) Connection failed to internet!
(3) Connected to internet!

 

# all()이 dict에서 작동하는가?

# When you use the all() method on a dictionary, 
# it only checks the keys, not the values. 
# Only if all of the keys in the dictionary are true, 
# then the all() function returns TRUE; 
# otherwise, it returns FALSE. 
# The all() function also returns a TRUE value 
# when the dictionary is empty.

d = {i: [] for i in range(1, 6)}
if all(d): print(f"{d.keys()} are all true")

d[0] = []
if all(d):
    print(f"{d.keys()} are all true")
else:
    print(f"{d.keys()} contain falsy!")

# 결과
dict_keys([1, 2, 3, 4, 5]) are all true
dict_keys([1, 2, 3, 4, 5, 0]) contain falsy!

 

# str이 iterable이라서 넘겨 봤는데 all()로 체크 안 됨
# -> Any character, number, or text inside the quotation mark 
# is considered as a TRUE value. 
# Even if the string is empty, the all() function returns 
# a TRUE value.

# [Definition]
# Python all() method is a built-in function that returns TRUE 
# if all of the items of a provided iterable 
# (List, Dictionary, Tuple, Set, etc.) are True; 
# otherwise, it returns FALSE.
# The Python all() function returns value TRUE if 
# all the items in an iterable are true; 
# else it returns FALSE.


def check_true(nums: list[int]) -> bool:
    return True if all(nums) else False

num_str: list[int] = [1, 1, 1, 0, 1, 0, 1, 1]

if check_true(num_str):
    print("(1) all of true")
else:
    print("(1) any one can be falsy")

num_str: list[int] = [1, 1, 1, 1, 1, 1, 1, 1]

if check_true(num_str):
    print("(2) all of true")
else:
    print("(2) any one can be falsy")

# 결과
(1) any one can be falsy
(2) all of true

 

# any(iterable)

people_voted: list[int] = [0, 1, 0, 0, 0]

if any(people_voted):
    print("At least 1 person voted!")
else:
    print("No one voted...")

# 결과
At least 1 person voted!

 

# enumerate
elems = ['x', 'y', 'z']
d = {}

for i, e in enumerate(elems, start=1):
    d[i] = e
print(f"for-in-loop unpacking: {d}")

enumeration: enumerate = enumerate(elems)
print(f"enumerate object: {list(enumeration)}")

# 결과
for-in-loop unpacking: {1: 'x', 2: 'y', 3: 'z'}
enumerate object: [(0, 'x'), (1, 'y'), (2, 'z')]

 

# Range()

numbers: list[int] = [1, 2, 3, 4, 5]
numbers_ran: list[int] = list(range(1, 6))
print(f"list - range: {numbers_ran}")

print("for-in-loop: ", end='')
for i in range(1, 6):
    if i == 5:
        print(i)
    else:
        print(i, end=', ')

# 여기서 갑자기 list to str 해본다.
x = ', '.join(map(str, numbers))
print(f"list to str: {x}")

# 결과
list - range: [1, 2, 3, 4, 5]
for-in-loop: 1, 2, 3, 4, 5
list to str: 1, 2, 3, 4, 5

 

# if you ever need to compare types, use the isinstance function.
# It will make sure that you compare your types properly.

class Animal:
    pass

class Cat(Animal):
    pass

print(isinstance(Cat(), Animal))
print(isinstance(Animal(), Cat))

# 결과
True
False

 

# slice()
numbers: list[int] = [1, 2, 3, 4, 5]
print(numbers[:5:2])
# 이렇게 사용하는 것은 올바른 방법이지만
# 사용하기 어렵다.
# 이 경우 슬라이스 객체를 생성하는 것이 이해하기 편하다.

text: str = "Hello, World!"
first_word: slice = slice(0, 5)
print(text[first_word])

reverse_slice: slice = slice(None, None, -1)
print(text[reverse_slice])

step_two: slice = slice(None, None, 2)
print(text[step_two])

# 결과
[1, 3, 5]
Hello
!dlroW ,olleH
Hlo ol!

 

# callable(func)

name: str = 'Bob'

def fn() -> None:
    prinf("fn() was called!")

print(f"callable(): {callable(name)}")
print(f"callable(): {callable(fn)}")
print(f"callable(): {callable(range)}")
print(f"callable(): {callable(str)}")

# 결과
callable(): False
callable(): True
callable(): True
callable(): True

 

# filter(func, sequence)
nums: list[int] = list(range(1, 21))

def is_even(n: int) -> bool:
    return n % 2 == 0
    
evens = list(filter(is_even, nums))
print(f"(1) {evens}")

# or
# We would get back this filter object, which is
# incredibly memory efficient.
# So you can use that in for loops, and it
# won't take that much much memory.
# Note that once we convert this into a list,
# it loads everything into memory, while a filter objcet
# will not do that.
# And that's why Python sometimes returns objects
# instead of just lists or tuples.
# It's just much more memory efficient.

evens_filter: filter = filter(is_even, nums)
print(f"(2) {evens_filter}")

even_num_list: list[int] = [n for n in evens_filter]
print(f"(3) {even_num_list}")

# or

even_nums_lc = list(filter(lambda n: n % 2 == 0, nums))
print(f"(4) {even_nums_lc}")

# So if you have millions of elements in general,
# you might want to use filter, because filter will
# return that memory efficient object that
# does not load everything into memory immediately,
# while a list comprehension will load that into memory immediately.

# 결과
(1) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
(2) <filter object at 0x0000020194B3BBB0>
(3) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
(4) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

 

# And map allows us to map a function to an iterable.
numbers: list[int] = [1, 2, 3, 4, 5]
letters: list[str] = ['a', 'b', 'c']

def zip_two(number: int, letter: str) -> tuple[int, str]:
    return (number, letter)

zipped_map: map = map(zip_two, numbers, letters)
print(zipped_map)
print(list(zipped_map))

# or
# 함수에 람다를 써도 되지만
# 역시 zip을 쓰는게 간단하다.

zipped_zip = zip(numbers, letters)
print(zipped_zip)
print(list(zipped_zip))

# 결과
<map object at 0x0000028F2252B850>
[(1, 'a'), (2, 'b'), (3, 'c')]
<zip object at 0x0000028F2254FAC0>
[(1, 'a'), (2, 'b'), (3, 'c')]

 

# sorted(iterable, key=)

class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
    
    def __repr__(self) -> None:
        return f"{self.name}={self.age} old"

Bob: Person = Person('Bob', 29)
Sally: Person = Person('Sally', 19)

sorted_person: list[Person] = sorted([Bob, Sally], key=lambda person: person.age)
print(f"sorted by age: {sorted_person}")

# 결과
sorted by age: [Sally=19 old, Bob=29 old]

 

# eval()

# If users can enter anything into your program,
# this can be extremely dangerous as well.
# So you need to handle this with extreme caution,
# because if you ever post this kind of code online somewhere,
# there are some very clever people out there that can actually
# inject their own code into your script,
# meaning they might be able to access sensitive information from
# your script or even from your computer.

# 평가식을 바로 넘길 수 있지만, 코드를 인젝트하는데도 쓰일 수 있다.
# 개인적인 프로젝트를 위해서는 쓸 수도 있지만, 외부 사용자가 쓸 수 있는
# 제품에는 반드시 반드시 반드시 왜 써야 하는지 확인한다.

 

# F-Strings
# one useful trick for debugging

var: int = 10

def add(x: int, y: int) -> int:
    return x + y

print(f"{var = }")
print(f"{add(1, 1) = }")

# the real f-news in Python 3.8 is the new debugging specifier. 
# You can now add = at the end of an expression, 
# and it will print both the expression and its value:

python = 3.8
print(f"{python=}")

# 결과
var = 10
add(1, 1) = 2
python=3.8

 

# F-Strings
# The comma is going to work as the thousand separator.

big_number: float = 1234567890
# , _ 이 두 개만 지원한다.
print(f"{big_number:,}")
print(f"{big_number:_}")

fraction: float = 1234.5678
print(f"{fraction:.2f}")
print(f"{fraction:,.2f}")

percent: float = 0.5
print(f"{percent:.2%}")
print(f"{percent:.1%}")
print(f"{percent:.0%}")

var: str = 'BOB'
print(f"{var:10}: hello")
print(f"{var:<10}: hello")
print(f"{var:>10}: hello")
print(f"{var:^10}: hello")

print(f"{var:#<10}: hello")
print(f"{var:#>10}: hello")
print(f"{var:#^10}: hello")

long_numbers: list[int] = [1, 100, 1_000, 10_000]
for number in long_numbers:
    print(f"{number:>5}: counting!")

import os

base_path: str = r"c:\\Windows"
folder_path = "Temp"
target_path = fr"{base_path}\\{folder_path}\\"
if os.path.exists(target_path):
    print("windows temp folder exists!")

# 결과
1,234,567,890
1_234_567_890
1234.57
1,234.57
50.00%
50.0%
50%
BOB       : hello
BOB       : hello
       BOB: hello
   BOB    : hello
BOB#######: hello
#######BOB: hello
###BOB####: hello
    1: counting!
  100: counting!
 1000: counting!
10000: counting!
windows temp folder exists!

 

# When you are developing program, sometimes you're going to
# want to make sure that certain conditions are met, 
# because those conditions are going to determine whether
# your program will work or not.

def start_program(db: dict[int, str]) -> None:
    assert db, 'Database is empty'

    print("Loaded:", db)
    print("Program started sucessfully!")

def main() -> None:
    db1: dict[int, str] = {1: 'john', 2: 'Sally'}
    start_program(db=db1)

    db2: dict[int, str] = {}
    start_program(db=db2)
    
main()

# 결과
Loaded: {1: 'john', 2: 'Sally'}
Program started sucessfully!

    assert db, 'Database is empty'
           ^^
AssertionError: Database is empty

 

# equality vs identity
# eq는 값 비교
# iden는 타입 비교
반응형

관련글 더보기

댓글 영역