deffind_second_largest(sequence): # Time complexity: O(n) # Space complexity: O(1) first, second = 0, 0 for i in sequence: if i in (first, second): continue
for idx, val inenumerate(args): if idx == 0: result = val elif exp == '+': result += val elif exp == '-': result -= val elif exp == '*': result *= val elif exp == '/': result = round(result / val, 2)
Write some examples using python comprehension here. 請嘗試使用comprehension實作一個函式。
1 2 3 4 5 6
# Python comprehension: # List Comprehension: [i for i in range(10)] # Set & Dictionary Comprehension: {i: i for i in range(10)} # Generator Comprehension: (i for i in range(10)) square = lambda x: x * x assert [square(i) for i in (1, 2, 3, 4, 6) ifnot i % 2] == [4, 16, 36]
技巧五
Write some examples using python decorator here. 請嘗試使用decorator實作一個函式。
# Explain the benefit of generators: # 1. Save memory: # - Only generate the next value when needed. # - 不用一次性產生所有的數據,而是一次產生一個,這樣就不會有內存溢出的問題。 # 2. Lazy evaluation: # - only evaluate when needed.
tasks = [ 'task A', 'task B', 'task C', ]
defpop_tasks(): for task in tasks: print(f'pop task: {task}') yield task
print("===Example 1===") for task in pop_tasks(): print(f'{task} is done.')
print() print("===Example 2===") print(">pop task and add new task at the same time.") for idx, task inenumerate(pop_tasks()): print(f'idx:{idx}, {task} is done.') if idx < 5: print(f'add new task {idx}') tasks.append(f'task {idx}')
# Output: # ===Example 1=== # pop task: task A # task A is done. # pop task: task B # task B is done. # pop task: task C # task C is done. # # ===Example 2=== # >pop task and add new task at the same time. # pop task: task A # idx:0, task A is done. # add new task 0 # pop task: task B # idx:1, task B is done. # add new task 1 # pop task: task C # idx:2, task C is done. # add new task 2 # pop task: task 0 # idx:3, task 0 is done. # add new task 3 # pop task: task 1 # idx:4, task 1 is done. # add new task 4 # pop task: task 2 # idx:5, task 2 is done. # pop task: task 3 # idx:6, task 3 is done. # pop task: task 4 # idx:7, task 4 is done.
技巧七
Write some examples using python context manager here. 請嘗試使用context manager實作一個函式。