Skip to content

Commit 1017326

Browse files
Merge pull request #1941 from NitkarshChourasia/master
Update Swap.py using best practices and standards of python.
2 parents fd181de + 95a57df commit 1017326

File tree

1 file changed

+76
-9
lines changed

1 file changed

+76
-9
lines changed

swap.py

+76-9
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,79 @@
1-
x = 5
2-
y = 10
1+
class Swapper:
2+
"""
3+
A class to perform swapping of two values.
34
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.
715
8-
# Swap the values of x and y without the use of any temporary value
9-
x, y = y, x
16+
"""
1017

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

Comments
 (0)