Python 等效代码,可像C++一样直接附加两个整数
Python equivalent code to append two integers directly like in C++
>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
的数字。
这应该为您提供足够的信息来形成问题的解决方案。
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 为什么将两个浮点数相加会得到一个整数C++?
- 从两个 4x64 位整数数组中获取取模
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 比较两个整数在C++中与未知 int 类型的相等性
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 如何组合两个整数向量
- 在两个整数之间交换最右边的N位
- 打印出两个整数之间的偶数
- 为什么将两个总和为 32k >整数相加时得到负数?
- C++ 两个线程,共享几个整数变量
- Python 等效代码,可像C++一样直接附加两个整数
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- 移位运算符如何在查找两个整数中的不同位数?
- 如何安全地比较两个无符号整数计数器?
- 添加两个二进制数(整数数组)
- 运算符"|"如何计算两个整数?
- 如何找出在两个整数的乘积中设置了多少位(等于 1)