Last active
July 26, 2024 17:48
-
-
Save singhAmandeep007/94779c2be14af8cd0f3e31a6d148017f to your computer and use it in GitHub Desktop.
Higher order functions in python with typing
This file contains hidden or 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
| def apply_operation(operation: Callable[[int], int], numbers: List[int]) -> List[int]: | |
| result = [] | |
| for num in numbers: | |
| result.append(operation(num)) | |
| return result | |
| def square(num: int) -> int: | |
| return num * num | |
| def cube(num: int) -> int: | |
| return num * num * num | |
| operation_result = apply_operation(square, [1, 2, 3, 4, 5]) | |
| print(operation_result) | |
| # data transformation | |
| playlist = [ | |
| ("What Was I Made For?", 3.42), | |
| ("Just Like That", 5.05), | |
| ("Song 3", 6.8), | |
| ("Leave The Door Open", 4.02), | |
| ("I Can't Breath", 4.47), | |
| ("Bad Guy", 3.14), | |
| ] | |
| songs_longer_than_five_minutes = list(filter(lambda t: t[1] > 5, playlist)) | |
| def minutes_to_seconds(m: int) -> int: | |
| minutes = int(m) | |
| seconds = (m - minutes) * 100 | |
| return minutes * 60 + round(seconds) | |
| songs_with_duration_in_seconds = list(map(lambda t: minutes_to_seconds(t[1]), playlist)) | |
| total_duration_of_playlist = reduce( | |
| lambda accumulator, current: accumulator + current[1], playlist, 0 | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment