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

How to find permutations in a list then remove them?

我试图在此 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 中的比较键 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]

编辑:甚至测试了它。

似乎有两个问题:如何从文本文件中读取数字,以及如何检测和过滤掉重复项w.r.t。排列。首先,您可以使用 strip 摆脱 \n 并转换为 int 以获得实际数字(尽管使用 int 时,第一步并不是真正的必要的)。为了过滤掉排列,我建议使用字典,按排序顺序将每个数字与其自身相关联。由于排序后每个排列都是相同的,因此这会将彼此排列的数字分组。如果要保留原来的顺序,使用collections.OrderedDict.

import collections
numbers = collections.OrderedDict()

with open("file.txt") as f:
    for line in map(str.strip, f):
        print(line)
        key = ''.join(sorted(line))
        if key not in numbers:
            numbers[key] = []
        numbers[key].append(int(line))
    print(numbers)

之后,numbers就是

OrderedDict([('167', [167]), ('168', [168]), ('148', [148]), ('134', [143]), ('289', [289]), ('149', [194, 491]), ('368', [683])])

要获得没有 "permutation-duplicates" 的有序数字序列,只需从每个值列表中获取第一个元素:

>>> [v[0] for v in numbers.values()]
[167, 168, 148, 143, 289, 194, 683]

如果您想删除两个 重复项,您可以添加一个一致的条件:

>>> [v[0] for v in numbers.values() if len(v) == 1]
[167, 168, 148, 143, 289, 683]

因此,您只需添加 3 行代码即可完成此操作:

  1. 对列表中的每个项目进行排序,以便排列匹配
  2. 检查列表中的每一项以查看哪里有排列,并创建这些索引的列表
  3. 创建新列表不添加被识别为排列的索引:

因此整个程序将如下所示:

numberList = []

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

x = [sorted(y) for y in numberList]
indices = [i for i, item in enumerate(x) if x.count(item) > 1]
numberList = [item for i, item in enumerate(numberList) if i not in indices]

结果:

>>> numberList
[167, 168, 148, 143, 289, 683]
>>>