Skip to main content
 首页 » 编程设计

python之如何在列表中找到排列然后删除它们

2025年05月04日11bonelee

我试图在此 txt 文件中找到另一个数字的排列,然后将它们添加到列表中:

167 
168 
148 
143 
289 
194  
683 
491 

在此文件中,排列是 491 和 194。

这是我的代码:

numberList = [] 
 
file = open("file.txt", "r") 
for line in file: 
    numberList.append(line) 

现在它们已添加到 numberList,如何从该列表中删除它们(491 和 194)。

请您参考如下方法:

好的,让我们做一些群论:

假设你可以将你的数字 x 分解成数字 X[i](删除 \n 真的很简单,而且肯定有人会解决这个问题)。

然后我们知道,根据十进制的工作原理,

我们需要找到一个函数 y=f(x),它将相同数字的排列 x 映射到相同的 y,但不是排列的 x 映射到不同的 y。

我们可以利用不同数字的素数分解不同这一事实,并简单地找到不是数字(并且大于数字*数字的长度)的素数的指数之和。如果我们假设少于 9 位数字,这会变得更容易,所以我们会这样做。

对于这个例子,让我们坚持使用 17(这进一步限制了我们的位数,但是哦好吧)。

所以,现在您可以将该函数用作 python set 中的比较键 并完成。

所以,非常天真(而且非常未经测试):

class permutation(object): 
    def __init__(self, x): 
         """ 
         we'll assume x is an integer 
         """ 
         digits = str(x) 
         self.original = x 
         self._hash = sum([17**int(digit) for digit in digits]) 
    def __hash__(self): 
         return self._hash 
    def __eq__(self,other): 
         return self._hash == hash(other) 
    def __ne__(self,other): 
         return self._hash != hash(other) 
 
 
permutation_free = set() 
 
file = open("file.txt", "r") 
for line in file: 
    x = int(line) 
    permutation_free.add(permutation(x)) 
print [perm.original for perm in permutation_free] 

编辑:甚至对其进行了测试。