[英]How to find the absolute value of an integer or float in Python, without using libraries, division, square roots, conditions, or inbuilt functions
I wanted to know if it was possible to do such a thing in Python 3. Using abs() is of course not allowed.我想知道在 Python 3 中是否可以做这样的事情。当然不允许使用 abs()。 No importing is allowed as well.
也不允许导入。
{1e999: x, -1e999: -x}[x*1e999]
I'm serious.我是认真的。 This works.
这行得通。
The 1e999
is interpreted as a float, but it overflows the available precision, so it's inf
. 1e999
被解释为浮点数,但它溢出了可用的精度,所以它是inf
。 But infinity can be positive or negative.但无穷大可以是正数或负数。 By multiplying
x
with infinity, we can coerce it into one of two values based on its sign, without using a condition operator.通过将
x
与无穷大相乘,我们可以根据其符号将其强制转换为两个值之一,而无需使用条件运算符。 Then we can select x
or its negation from a lookup table.然后我们可以从查找表中得到 select
x
或其否定。
It's equivalent to the following, but doesn't require the import:它等效于以下内容,但不需要导入:
from math import inf
{inf: x, -inf: -x}[x*inf]
If you consider the built-in classes ( int
, str
, etc) to be built-in "functions".如果您认为内置类(
int
、 str
等)是内置“函数”。 You could do something like the following您可以执行以下操作
num.__class__(('%s' % num).lstrip('-'))
Convert the number to a string, strip the negative sign and then use the original numbers class to convert back将数字转换为字符串,去掉负号,然后使用原始数字 class 转换回来
Convert to a string with a sign and slice off the first character.转换为带符号的字符串并切掉第一个字符。 The
__class__
is not technically a method, so no methods. __class__
在技术上不是一种方法,所以没有方法。
x.__class__(f'{x:+}'[1:])
Assume the first character of the string representation is '-' and return the negation.假设字符串表示的第一个字符是“-”并返回否定。 But don't negate when you're wrong.
但是当你错的时候不要否定。
def abs(x):
try:
return {'-': -x}[f'{x}'[0]]
except:
return x
Format a string to always include the sign and then look up its first character in a table.格式化字符串以始终包含符号,然后在表中查找其第一个字符。
{'-': -x, '+': x}[f'{x:+}'[0]]
The abs()
builtin just calls the .__abs__()
method. abs()
内置函数只调用.__abs__()
方法。 No imports, no builtins, no conditions, no division, no square roots.没有导入,没有内置函数,没有条件,没有除法,没有平方根。 And no
abs()
.并且没有
abs()
。
x.__abs__()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.