Spaces:
Running
Running
File size: 1,164 Bytes
2b03193 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | python
# Function to swap two numbers
def swap_numbers(a, b):
"""
Swaps two numbers using a temporary variable
Args:
a: First number
b: Second number
Returns:
Tuple of (a, b) after swapping
"""
print(f"Before swap: a = {a}, b = {b}")
# Swapping logic
temp = a
a = b
b = temp
print(f"After swap: a = {a}, b = {b}")
return a, b
# Alternative method without temporary variable (using arithmetic)
def swap_without_temp(a, b):
"""
Swaps two numbers without using temporary variable
Args:
a: First number
b: Second number
Returns:
Tuple of (a, b) after swapping
"""
print(f"Before swap: a = {a}, b = {b}")
a = a + b
b = a - b
a = a - b
print(f"After swap: a = {a}, b = {b}")
return a, b
# Example usage
if __name__ == "__main__":
num1 = 5
num2 = 10
# Using temporary variable
swapped1, swapped2 = swap_numbers(num1, num2)
print("\nAlternative method:")
# Using arithmetic operations
swapped1, swapped2 = swap_without_temp(num1, num2)
</html> |