kiice5 - 1 year ago 111

Python Question

I'm trying to find a permutation of another number in this txt file and then add them to a list:

`167`

168

148

143

289

194

683

491

In this file, the permutations are 491 and 194.

This is my code:

`numberList = []`

file = open("file.txt", "r")

for line in file:

numberList.append(line)

Now they're added to

`numberList`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Ok, let's do a bit of group theory:

assume you can decompose your numbers x into digits X[i] (removing the `\n`

is really trivial, and surely someone else will cover this).

Then we know that, by how the decimal system works,

what we need to find is a function y=f(x) that maps x'es that are permutations of the same number to the same y, but x'es that aren't permutations to different y.

we can use the fact that the prime factorization of different numbers is different, and simply find the sum over exponents of a prime that isn't a digit (and larger than the length of the number*digits). This get's easier if we assume less than 9 digits, so we'll do that.

for this example, let's stick to 17 (which further limits our number of digits, but oh well).

so, now you'd use that function as *comparison key* in a python `set`

and be done.

So, very naively (and very untested):

```
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)
numberList = set()
file = open("file.txt", "r")
for line in file:
x = int(line)
numberList.add(permutation(x))
print [perm.original for perm in numberList]
```

**EDIT:** even tested it.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**