|
1 |
| -x = 5 |
2 |
| -y = 10 |
| 1 | +class Swapper: |
| 2 | + """ |
| 3 | + A class to perform swapping of two values. |
3 | 4 |
|
4 |
| -# To take inputs from the user |
5 |
| -# x = input('Enter value of x: ') |
6 |
| -# y = input('Enter value of y: ') |
| 5 | + Methods: |
| 6 | + ------- |
| 7 | + swap_tuple_unpacking(self): |
| 8 | + Swaps the values of x and y using a tuple unpacking method. |
| 9 | + |
| 10 | + swap_temp_variable(self): |
| 11 | + Swaps the values of x and y using a temporary variable. |
| 12 | + |
| 13 | + swap_arithmetic_operations(self): |
| 14 | + Swaps the values of x and y using arithmetic operations. |
7 | 15 |
|
8 |
| -# Swap the values of x and y without the use of any temporary value |
9 |
| -x, y = y, x |
| 16 | + """ |
10 | 17 |
|
11 |
| -print("The value of x after swapping: {}".format(x)) |
12 |
| -print("The value of y after swapping: {}".format(y)) |
| 18 | + def __init__(self, x, y): |
| 19 | + """ |
| 20 | + Initialize the Swapper class with two values. |
| 21 | +
|
| 22 | + Parameters: |
| 23 | + ---------- |
| 24 | + x : int |
| 25 | + The first value to be swapped. |
| 26 | + y : int |
| 27 | + The second value to be swapped. |
| 28 | +
|
| 29 | + """ |
| 30 | + if not isinstance(x, int) or not isinstance(y, int): |
| 31 | + raise ValueError("Both x and y should be integers.") |
| 32 | + |
| 33 | + self.x = x |
| 34 | + self.y = y |
| 35 | + |
| 36 | + def display_values(self, message): |
| 37 | + print(f"{message} x: {self.x}, y: {self.y}") |
| 38 | + |
| 39 | + def swap_tuple_unpacking(self): |
| 40 | + """ |
| 41 | + Swaps the values of x and y using a tuple unpacking method. |
| 42 | +
|
| 43 | + """ |
| 44 | + self.display_values("Before swapping") |
| 45 | + self.x, self.y = self.y, self.x |
| 46 | + self.display_values("After swapping") |
| 47 | + |
| 48 | + def swap_temp_variable(self): |
| 49 | + """ |
| 50 | + Swaps the values of x and y using a temporary variable. |
| 51 | +
|
| 52 | + """ |
| 53 | + self.display_values("Before swapping") |
| 54 | + temp = self.x |
| 55 | + self.x = self.y |
| 56 | + self.y = temp |
| 57 | + self.display_values("After swapping") |
| 58 | + |
| 59 | + def swap_arithmetic_operations(self): |
| 60 | + """ |
| 61 | + Swaps the values of x and y using arithmetic operations. |
| 62 | +
|
| 63 | + """ |
| 64 | + self.display_values("Before swapping") |
| 65 | + self.x = self.x - self.y |
| 66 | + self.y = self.x + self.y |
| 67 | + self.x = self.y - self.x |
| 68 | + self.display_values("After swapping") |
| 69 | + |
| 70 | + |
| 71 | +print("Example 1:") |
| 72 | +swapper1 = Swapper(5, 10) |
| 73 | +swapper1.swap_tuple_unpacking() |
| 74 | +print() |
| 75 | + |
| 76 | +print("Example 2:") |
| 77 | +swapper2 = Swapper(100, 200) |
| 78 | +swapper2.swap_temp_variable() |
| 79 | +print() |
0 commit comments