最近学习Python,学到元组(tuple)使用中有个组包和解包的逻辑,发现变量值的交换,目前就只有Python是最优雅的,叹为观止!!
Python目前来看是当之无愧的明星编程语言:
下面我用我用过的五种编程语言实现两个数字交换:
1. C语言
#include<stdio.h>// 方式1:临时变量voidswap1(int* x, int* y){ int temp = *x; *x = *y; *y = temp;}// 方式2:加减法(注意: 可能会溢出) 算是一个比较妙的方法voidswap2(int* x, int* y){ *x = *x + *y; *y = *x - *y; *x = *x - *y;}// 方式3:异或(位运算)voidswap3(int* x, int* y){ *x = *x ^ *y; *y = *x ^ *y; *x = *x ^ *y;}intmain(){ int x = 20, y = 10; printf("before:x=%d, y=%d\n", x, y); // 使用了指针, 指针是C/C++令人不喜的原因之一 swap1(&x, &y); // 中间变量 // swap2(&x, &y); // 减法 // swap3(&x, &y); // 异或 printf("after:x=%d, y=%d\n", x, y); return 0;}
2. C++语言
#include<iostream>using namespace std;// 方式1:临时变量voidswap1(int &x, int &y){ int temp = x; x = y; y = temp;}// 方法2:使用STL函数#include<algorithm>intmain(){ int x = 20, y = 10; // 自定义函数 swap1(x, y); cout<<"交换:x="<<x<<",y="<<y<<endl; // 恢复原值 x = 20; y = 10; // 使用STL swap swap(x, y); cout<<"STL交换:x="<<x<<",y="<<y<<endl; return 0;}
3. Java语言
public class SwapTwoNumber { // Java不能直接交换基本类型,需要包装类或数组 // 数组+临时变量 publicstaticvoidswap(int[] arrNums) { int temp = arrNums[0]; arrNums[0] = arrNums[1]; arrNums[1] = temp; } // 包装类 publicstaticvoidswap(IntegerPacker x, IntegerPacker y) { int temp = x.value; x.value = y.value; y.value = temp; } publicstaticvoidmain(String[] args) { // 都需要一个中间变量 // 1:使用数组 int[] nums = {20, 10}; System.out.println("before:"+nums[0]+","+nums[1]); swap(nums); System.out.println("after:"+nums[0]+","+nums[1]); // 2:使用包装类 IntegerPacker x = new IntegerPacker(20); IntegerPacker y = new IntegerPacker(10); System.out.println("before:x="+x.value+",y="+y.value); swap(x, y); System.out.println("after:x="+x.value+",y="+y.value); } // 辅助包装类 static class IntegerPacker { int value; IntegerPacker(int num) { this.value = num; } }}
java代码量目前看是最多的.
4. Python语言
# 方式1:Python特有的元组解包def swap1(x, y): return y, x# 方式2:临时变量def swap2(x, y): temp = x x = y y = temp return x, y# 方式3:加减法def swap3(x, y): x = x + y y = x - y x = x - y return x, y# 方式4:异或(只适用于整数)def swap4(x, y): x = x ^ y y = x ^ y a = x ^ y return x, y# 测试x, y = 20, 10print(f"before:x = {x}, y = {y}")# Python中最简单的交换方式# 使用了 元组的组包\解包, "="右边的结果是组包, "="左边再解包# 就是这么优雅x, y = y, xprint(f"after:x = {x}, y = {y}")
5. JavaScript语言
// 方法1:临时变量function swap1(x, y) { let temp = x; x = y; y = temp; return [x, y];}// 方式2:解构赋值(ES6) 这个和python 有点像了function swap2(x, y) { [x, y] = [y, x]; return [x, y];}// 方式3:加减法function swap3(x, y) { x = x + y; y = x - y; x = x - y; return [x, y];}// 方法4:异或(只适用于数字)function swap4(x, y) { x = x ^ y; y = x ^ y; x = x ^ y; return [x, y];}// 测试let x = 20, y = 10;console.log(`before:x = ${x}, y = ${y}`);// 使用解构赋值[x, y] = [y, x];console.log(`after:x = ${x}, y = ${y}`);// 使用函数let result = swap1(20, 10);console.log(`after1:a = ${result[0]}, b = ${result[1]}`);
总结
不同语言实现数字交换的特点:
· C语言:需要指针操作,直接内存操作, 指针比较危险, 大多数人不喜欢
· C++:支持引用和STL,更加方便, 指针\引用等方式都可以.
· Java:没有指针,需要通过数组或对象包装,比较麻烦
· Python:语法简洁,支持元组解包, 优雅简单
· JavaScript:支持解构赋值,语法灵活
由此可见每种语言都有其独特的实现方式,反映了各自的设计哲学和语法特性。