Swapping values in python

Обмен значений двух переменных без использования третьей в Python

В этом руководстве мы обсудим различные методы, используемые для обмена значений двух переменных (n1 и n2) без использования третьей переменной в программах Python.

P: 112 Q: 211 After swapping P and Q: P: 211 Q: 112

Метод 1: с помощью встроенного метода

Встроенный метод может работать со значениями любого типа данных, такими как string, float, it. Этот метод очень прост в использовании.

P = JavaTpoint Q = Tutorial print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P, Q = Q, P print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: JavaTpoint Value of Q: Tutorial Variables Value After Swapping: Value of P: Tutorial Value of Q: JavaTpoint

Метод 2: с помощью побитового оператора XOR

Метод побитового оператора XOR применяется только для целых чисел, и он работает быстрее, поскольку он использует битовую операцию, которая предназначена для того же значения result = 0 и для другого значения result = 1.

P = 5 # P = 0101 Q = 10 # Q = 1010 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P ^= Q # P = 1111, Q = 1010 Q ^= P # Q = 0101, P = 1111 P ^= Q # P = 1010, Q = 0101 print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 5 Value of Q: 10 Variables Value After Swapping: Value of P: 10 Value of Q: 5

Метод 3: с помощью операторов сложения и вычитания

Этот метод можно использовать только для числовых значений.

P = 112 Q = 211 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P = P + Q # P = 323, Q = 211 Q = P - Q # P = 323, Q = 112 P = P - Q # P = 211, Q = 112 print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 112 Value of Q: 211 Variables Value After Swapping: Value of P: 112 Value of Q: 211

Метод 4: с помощью операторов умножения и деления

Этот метод можно использовать только для числовых значений, кроме 0.

P = 11.2 Q = 21.1 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Method to swap 'P' and 'Q' P = P * Q # P = 236.32, Q = 21.1 Q = P / Q # P = 236.32, Q = 11.2 P = P / Q # P = 21.1, Q = 11.2 print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 11.2 Value of Q: 21.1 Variables Value After Swapping: Value of P: 21.1 Value of Q: 11.2

Метод 5: с использованием побитовых и арифметических операторов

В этом методе мы будем использовать как побитовые, так и арифметические операторы. Этот метод работает только с целыми числами, но не с числами с плавающей запятой.

P = 112 Q = 211 print("Variables Value Before Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q) # Same as P = P + Q P =(P & Q) +(P | Q) ; # Same as Q = P - Q Q = P +(~Q) + 1 ; # Same as P = P - Q P = P +(~Q) + 1 ; print("Variables Value After Swapping: ") print("Value of P: ", P) print("Value of Q: ", Q)
Variables Value Before Swapping: Value of P: 112 Value of Q: 211 Variables Value After Swapping: Value of P: 211 Value of Q: 112

Заключение

В этом руководстве мы обсудили различные методы, используемые для обмена значениями двух переменных без использования третьей.

Читайте также:  Php разрешить короткие php теги

Источник

Swap Function in Python

In programming, a swap function is a useful tool that allows the values of two variables to be exchanged with each other. In Python, the swap function is implemented using a few different methods, each of which can be used to accomplish the same task.

Swapping two values is a common task in programming, and it can be used in many different situations. For example, it can be used to sort a list of items or to swap the values of two variables in an equation.

Methods to Use Swap Function in Python

In Python, the swap function is implemented using various different methods. These methods are discussed below in detail.

Method 1: Using a Temporary Variable

One of the most common methods of implementing the swap function in Python is by using a temporary variable. This method involves creating a temporary variable and then using it to interchange the values of the two variables.

# Using a temporary variable a = 5 b = 10 temp = a a = b b = temp print("a =", a) print("b fadeIn"; var c; var a; d(jQuery("#myTab_13959 a"),jQuery("#tab-content_13959"));function d(e,f,g) < e.click(function(i)< i.preventDefault(); jQuery(this).tab("show"); var h=jQuery(this).data("easein"); if(c)if(h) elseelse>c=f.find("div.active"); >); > >); function do_resize()< var width=jQuery( '.tab-content .tab-pane iframe' ).width(); var height=jQuery( '.tab-content .tab-pane iframe' ).height(); var toggleSize = true; jQuery('iframe').animate(< width: toggleSize ? width : 640, height: toggleSize ? height : 360 >, 250); toggleSize = !toggleSize; > 

Output:

a = 10 b = 5

Explanation:
In this method, we first create two variables a and b with values 5 and 10 respectively. We then create a temporary variable temp and assign the value of a to it. We then assign the value of b to a and finally assign the value of temp to b. This way, the values of a and b are swapped.

Method 2: Using Arithmetic Operations

Another way to implement the swap function in Python is by using arithmetic operations. This method involves adding the two variables and then subtracting the value of one variable from the sum to get the value of the other variable.

# Using arithmetic operations a = 5 b = 10 a = a + b b = a - b a = a - b print("a =", a) print("b fadeIn"; var c; var a; d(jQuery("#myTab_13960 a"),jQuery("#tab-content_13960"));function d(e,f,g) < e.click(function(i)< i.preventDefault(); jQuery(this).tab("show"); var h=jQuery(this).data("easein"); if(c)if(h) elseelse>c=f.find("div.active"); >); > >); function do_resize()< var width=jQuery( '.tab-content .tab-pane iframe' ).width(); var height=jQuery( '.tab-content .tab-pane iframe' ).height(); var toggleSize = true; jQuery('iframe').animate(< width: toggleSize ? width : 640, height: toggleSize ? height : 360 >, 250); toggleSize = !toggleSize; > 

Output:

a = 10 b = 5

Explanation:
In this method, we first create two variables a and b with values 5 and 10 respectively. We then add the values of a and b and store the result in a. We then subtract the value of b from a and store the result in b. Finally, we subtract the value of b from a again and store the result in a. This way, the values of a and b are swapped.

Method 3: Using Tuple Unpacking

Another way to implement the swap function in Python is by using tuple unpacking. This method involves packing the values of the two variables into a tuple, swapping the positions of the variables in the tuple, and then unpacking the values of the tuple into the variables.

# Using tuple unpacking a = 5 b = 10 a, b = b, a print("a =", a) print("b fadeIn"; var c; var a; d(jQuery("#myTab_13961 a"),jQuery("#tab-content_13961"));function d(e,f,g) < e.click(function(i)< i.preventDefault(); jQuery(this).tab("show"); var h=jQuery(this).data("easein"); if(c)if(h) elseelse>c=f.find("div.active"); >); > >); function do_resize()< var width=jQuery( '.tab-content .tab-pane iframe' ).width(); var height=jQuery( '.tab-content .tab-pane iframe' ).height(); var toggleSize = true; jQuery('iframe').animate(< width: toggleSize ? width : 640, height: toggleSize ? height : 360 >, 250); toggleSize = !toggleSize; > 

Output:

a = 10 b = 5

Explanation:
In this method, we first create two variables a and b with values 5 and 10 respectively. We then pack the values of a and b into a tuple and swap the positions of the variables in the tuple. Finally, we unpack the values of the tuple into the variables a and b. This way, the values of a and b are swapped.

Method 4: Using the XOR Operator

Another way to implement the swap function in Python is by using the XOR operator. This method involves performing XOR operations on the values of the two variables to swap their values.

# Using XOR operator a = 5 b = 10 a = a ^ b b = a ^ b a = a ^ b print("a =", a) print("b fadeIn"; var c; var a; d(jQuery("#myTab_13962 a"),jQuery("#tab-content_13962"));function d(e,f,g) < e.click(function(i)< i.preventDefault(); jQuery(this).tab("show"); var h=jQuery(this).data("easein"); if(c)if(h) elseelse>c=f.find("div.active"); >); > >); function do_resize()< var width=jQuery( '.tab-content .tab-pane iframe' ).width(); var height=jQuery( '.tab-content .tab-pane iframe' ).height(); var toggleSize = true; jQuery('iframe').animate(< width: toggleSize ? width : 640, height: toggleSize ? height : 360 >, 250); toggleSize = !toggleSize; > 

Output:

a = 10 b = 5

Explanation:
In this method, we first create two variables a and b with values 5 and 10 respectively. We then perform XOR operations on the values of a and b to swap their values. First, we perform the XOR operation on a and b and store the result in a. We then perform the XOR operation on b and the new value of a and store the result in b. Finally, we perform the XOR operation on the new value of a and b and store the result in a. This way, the values of a and b are swapped.

Conclusion
The swap function is a useful tool in Python that allows the values of two variables to be exchanged with each other. In Python, the swap function can be implemented using various different methods as discussed in the article. By using the swap function, you can easily manipulate the values of your variables, which can be useful in a wide variety of programming tasks. Whether you are sorting a list of items or exchanging the values of two variables in an equation, the swap function is a powerful tool that can help you get the job done quickly and efficiently.

Here are some FAQs on Swap Function in Python

Ques 1. How does the swap function work in Python?
Ans. The swap function works by assigning the value of one variable to another variable, and then assigning the value of the second variable to the first variable. This process is done in a single line of code.

Ques 2. Can the swap function be used with different data types in Python?
Ans. Yes, the swap function can be used with different data types in Python, as long as both variables are of the same type. For example, you can swap the values of two integers, two strings, or two lists.

Ques 3. Can the swap function be used with more than two variables in Python?
Ans. Yes, the swap function can be used with more than two variables in Python. For example, to swap the values of three variables a, b, and c, you can use the following syntax:

Ques 4. What are the advantages of using the swap function in Python?
Ans. The advantages of using the swap function in Python include

  • It simplifies the code by eliminating the need for a temporary variable.
  • It saves memory by using a single line of code instead of multiple lines.
  • It improves readability by making the code more concise and easier to understand.
  • It can be used with different data types, making it a versatile tool in Python programming.

Источник

Swap Two Values in Python

Swap Two Values in Python

  1. Swap Two Values Using Tuple Swap in Python
  2. Swap Two Values Using a Temporary Variable in Python
  3. Swap Two Values Using XOR Logic in Python

When dealing with data or programming in general, we land up in situations where we have to swap the values of two variables. For example, if a is storing 5 and b is storing 25 , a will store 25 after swapping, and b will store 5 . This article will talk about different ways that we can use to perform swapping of values between two variables.

Swap Two Values Using Tuple Swap in Python

In Python, we can use an assignment expression or tuple swap to swap to values. Refer to the following code.

a = 5 b = 25 print("Before swapping") print("a:", a, "b:", b) a, b = b, a # Swapping print("After swapping") print("a:", a, "b:", b) 
Before swapping a: 5 b: 25 After swapping a: 25 b: 5 

Notice the expression a, b = b, a . What this expression essentially does is to create a tuple of two values on the right side and then on the left side. Next, the first value of the tuple on the right side is assigned to the first variable of the tuple on the left side. Lastly, the second value of the tuple on the right side is assigned to the second variable of the tuple on the left side. This operation swaps the two values.

Swap Two Values Using a Temporary Variable in Python

In this method, a temporary variable is used to swap two values. Consider two variables, a and b and a temporary variable, temp . First, the value of a will be copied to temp . Then the value of b will be assigned to a . Lastly, the value of temp will be assigned to b , and the temp variable will be either deleted or set to None .

Refer to the following code for the same.

a = 5 b = 25 print("Before swapping") print("a:", a, "b:", b) temp = a # Step 1 a = b # Step 2 b = temp # Step 3 del temp # (optional) print("After swapping") print("a:", a, "b:", b) 
Before swapping a: 5 b: 25 After swapping a: 25 b: 5 

Swap Two Values Using XOR Logic in Python

In Python, XOR is represented with the ^ symbol. And, we can use it to perform swapping in the following way. Note that this approach only works for integers. For float values, we will get the following error.

TypeError: unsupported operand type(s) for ^=: 'float' and 'float'`. 
a = 5 b = 25 print("Before swapping") print("a:", a, "b:", b) a ^= b # Step 1 b ^= a # Step 2 a ^= b # Step 3 print("After swapping") print("a:", a, "b:", b) 
Before swapping a: 5 b: 25 After swapping a: 25 b: 5 

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Источник

Оцените статью