Skip to content

Update Swap.py using best practices and standards of python. #1941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 76 additions & 9 deletions swap.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,79 @@
x = 5
y = 10
class Swapper:
"""
A class to perform swapping of two values.

# To take inputs from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')
Methods:
-------
swap_tuple_unpacking(self):
Swaps the values of x and y using a tuple unpacking method.

swap_temp_variable(self):
Swaps the values of x and y using a temporary variable.

swap_arithmetic_operations(self):
Swaps the values of x and y using arithmetic operations.

# Swap the values of x and y without the use of any temporary value
x, y = y, x
"""

print("The value of x after swapping: {}".format(x))
print("The value of y after swapping: {}".format(y))
def __init__(self, x, y):
"""
Initialize the Swapper class with two values.

Parameters:
----------
x : int
The first value to be swapped.
y : int
The second value to be swapped.

"""
if not isinstance(x, int) or not isinstance(y, int):
raise ValueError("Both x and y should be integers.")

self.x = x
self.y = y

def display_values(self, message):
print(f"{message} x: {self.x}, y: {self.y}")

def swap_tuple_unpacking(self):
"""
Swaps the values of x and y using a tuple unpacking method.

"""
self.display_values("Before swapping")
self.x, self.y = self.y, self.x
self.display_values("After swapping")

def swap_temp_variable(self):
"""
Swaps the values of x and y using a temporary variable.

"""
self.display_values("Before swapping")
temp = self.x
self.x = self.y
self.y = temp
self.display_values("After swapping")

def swap_arithmetic_operations(self):
"""
Swaps the values of x and y using arithmetic operations.

"""
self.display_values("Before swapping")
self.x = self.x - self.y
self.y = self.x + self.y
self.x = self.y - self.x
self.display_values("After swapping")


print("Example 1:")
swapper1 = Swapper(5, 10)
swapper1.swap_tuple_unpacking()
print()

print("Example 2:")
swapper2 = Swapper(100, 200)
swapper2.swap_temp_variable()
print()