Python 等效代码,可像C++一样直接附加两个整数

Python equivalent code to append two integers directly like in C++

本文关键字:整数 两个 一样 代码 可像 C++ Python      更新时间:2023-10-16

>X Y 所以,我有两个数字。说, [12,3] 我想将 123 与 321 i,e XY 和 YX 进行比较 或 [1234,4] --->12344<44321

如果我直接尝试使用 append,那在 python 中是无效的。 C++执行我想要的操作的代码 ->

int Compare(string X, string Y)
{
// first append Y at the end of X
string XY = X.append(Y);
// then append X at the end of Y
string YX = Y.append(X);
// Now see which of the two formed numbers is greater
if (XY > YX)
{
return 1;
}
else
{
return 0;
}
}

首先,您的C++代码中存在错误

XY=X.append(Y)还将 X 更改为 X+Y 例如,请考虑以下代码片段:

string X="ab", Y="cd";
string XY=X.append(Y);
cout<<"X="<<X<<", Y="<<Y<<", XY="<<XY;

输出:

X=abcd, Y=cd, XY=abcd

因为追加将首先在 X 中连接 Y,然后将 X 的值分配给 XY。 这将在以后计算 YX 时导致问题。 我建议改用"+"运算符:

int Compare(string X, string Y)
{
string XY = X+Y;
string YX = Y+X;
if (XY > YX) return 1;
else return 0;
}

等效的 Python3 代码将是

def Compare(X, Y):
X=str(X)   # Convert to string in case integer parameters are passed (if you are
Y=str(Y)   # sure that only string will be passed you can skip these two lines)
XY = X+Y
YX = Y+X
if (XY > YX):
return 1
else: 
return 0

您可以使用+在 python 中连接字符串。 即,"a" + "b"结果为字符串"ab"。若要将字符串转换为数字,请使用构造函数int()。即,int("10")将产生10的数字。

这应该为您提供足够的信息来形成问题的解决方案。