from typing import TypeVar, Generic
# Generic Swap Method in Python
from typing import TypeVar, List
T = TypeVar('T')
# Generic swap function
def swap(arr: List[T], i: int, j: int) -> None:
arr[i], arr[j] = arr[j], arr[i]
# Helper function to print lists
def print_list(label: str, arr: List[T]) -> None:
print(f"{label}: {arr}")
def main():
# Integer list
nums = [10, 20, 30, 40]
print_list("Before swap (int)", nums)
swap(nums, 1, 3)
print_list("After swap (int)", nums)
print()
# String list
words = ["Python", "Java", "C#", "Go"]
print_list("Before swap (str)", words)
swap(words, 0, 2)
print_list("After swap (str)", words)
print()
# Float list
floats = [1.1, 2.2, 3.3, 4.4]
print_list("Before swap (float)", floats)
swap(floats, 2, 3)
print_list("After swap (float)", floats)
if __name__ == "__main__":
main()
'''
run:
Before swap (int): [10, 20, 30, 40]
After swap (int): [10, 40, 30, 20]
Before swap (str): ['Python', 'Java', 'C#', 'Go']
After swap (str): ['C#', 'Java', 'Python', 'Go']
Before swap (float): [1.1, 2.2, 3.3, 4.4]
After swap (float): [1.1, 2.2, 4.4, 3.3]
'''