请在这个计算中解决Python的"魔法"。

2024-04-26 06:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个脚本,可以通过重新排列数字来执行简单的数学杂耍。你知道吗

它应该做什么:

x = 777.0
y = 5
calc = x / y # 155.4

。。。 伪代码:

Rearrange numbers (last digit + first) = 555.
Difference from 777 and 555 = 222
Add 222 to 555 = 777

基本上,它应该在不进行实际计算的情况下重新创建原始变量,而只是重新排列数字和相加。你知道吗

由于脚本的设计,我希望它只能处理4位数字,比如333.3。事实证明,它(似乎)也适用于像2543.6452这样的数字,至少从我(非学术)的观点来看,这似乎是不可能的。 有人能告诉我这里发生了什么吗?是代码工作正常还是我创建了一些我根本不明白的东西?在我看来这是个幻觉。:D个

x = 5.0
y = 7345.3297
z= y / x
print "Initial Value = " + str(y)
print "Calculate:"
print str(y) + "/" + str(x) 
print z # 177.6
print
a = int(str(z)[0])
print "First Number = " + str(a)
print
b = int(str(z)[1])
c = int(str(z)[2])
print "In between = " + str(b) + str(c)
d = int(str(z)[-1]) # treat z as string, take first string after . from z and format it back to int
print "Last Number = " + str(d)
print
print "Rearrange Numbers"
res = str(a+d) +str(b) +str(c)
to_int = int(res)
dif = y - to_int
add = to_int + dif
print "number = " + str(add)

Tags: andto代码from脚本numberstringres
1条回答
网友
1楼 · 发布于 2024-04-26 06:28:39

让我们在这里做些替换。底线是:

dif = y - to_int
add = to_int + dif

这可以写成一行:

add = y - to_int + to_int

或:

add = y

所以你做了所有这些“魔术”,然后完全忽略它来打印你开始的东西。你可以把任何东西放在上面,所有这些代码在最后做的就是打印y:-)

相关问题 更多 >