私信  •  关注

hiro protagonist

hiro protagonist 最近创建的主题
hiro protagonist 最近回复了
4 年前
回复了 hiro protagonist 创建的主题 » 如何从python列表中删除类对象?

list.remove 需要能够判断何时要删除的元素与列表中的一个元素相同。

所以你可以实施 __eq__ 方法如下:

class Base:    
    def __eq__(self, other):
        if not isinstance(other, Base):
            return NotImplemented
        return self.x, self.y == other.x, other.y

obj.remove(Base(2,5)) 会有用的。

6 年前
回复了 hiro protagonist 创建的主题 » math.log中的错误答案(python 3)

你可以用 gmpy2 图书馆:

import gmpy2

print(gmpy2.iroot(4913, 3))
# (mpz(17), True)

print(gmpy2.iroot(4913 + 1, 3))
# (mpz(17), False)

它告诉你结果和是否准确。

也看看 Log precision in python Is floating point math broken? .

6 年前
回复了 hiro protagonist 创建的主题 » python中的sentinel循环
userInput.upper() != "Stop":

永远都是 True : 'stop'.upper() 'STOP' .

如果希望在用户输入任何大写版本的 'stop' 你应该写信

while userInput.upper() != "STOP":
    ....

捕捉用户可以使用的其他内容可能是明智的

userIntput = input("")
try:
    nums.append(int(userInput))
except ValueError:
    # somehow handle what should happen here...
6 年前
回复了 hiro protagonist 创建的主题 » 不带scipy或numpy的python多项式乘法

你可以很容易地用 defaultdict (口述可能对你的多项式更好地表示… poly = {exp: coeff} )

from collections import defaultdict

mult = defaultdict(int)  # mult[i] will default to 0

for i1, c1 in zip(idx1, coef1):
    for i2, c2 in zip(idx2, coef2):
        mult[i1 + i2] += c1 * c2

为了你的投入,这给了

mult = defaultdict(<class 'int'>, {10: 1, 8: 5, 9: 2, 7: 10, 5: 3, 3: 15})

然后您可以将其排列到您感兴趣的列表中:

mult_sorted = tuple(sorted(mult.items(), reverse=True))
idx_mult = [item[0] for item in mult_sorted]
# [10, 9, 8, 7, 5, 3]
coeff_mult = [item[1] for item in mult_sorted]
# [1, 2, 5, 10, 3, 15]

这些都没有经过彻底的测试!


减少 for 循环:

from itertools import product

for (i1, c1), (i2, c2) in product(zip(idx1, coef1), zip(idx2, coef2)):
    mult[i1 + i2] += c1 * c2