简体   繁体   中英

Sorted number permutations list from numeric variables or numeric list with no duplicates

Number permutations function, creates a list of all possible arrangements. Worked on this code for a while, it works well and I'm trying to find a shorter an more efficient way of writing it.

a = [3,7,9]
perms = lambda a:list(sorted(z) for z in map(lambda p:dict.fromkeys([str(sum(v* (10**(len(p) -1 - i)) for i,v in enumerate(item))).zfill(len(a)) for item in itertools.permutations(p)]).keys(), [[int(x) for x in ''.join(str(i) for i in a)]]))[0]

The code returns:

['379', '397', '739', '793', '937', '973']

You can also input numeric string variable

a = '468'
perms(a)
['468', '486', '648', '684', '846', '864']

This is code is different, instead of returning tuples or list. It returns a list of results in string format. Also, you are allowed to input numeric strings, tuples or lists. Trust me I've checked any duplicates before posting.

The triple digits work pretty well

perms('000')
['000']

Other codes produces this

['000', '000', '000', '000', '000', '000']

Also, this code returns an ordered list.

You are already using itertools.permutations , why not just:

def perms(iterable):
    return [''.join(p) for p in (map(str, perm) for perm in itertools.permutations(iterable))]

>>> perms('123')
# Result: ['123', '132', '213', '231', '312', '321']

Update: If you wish to avoid duplicates, you can extend the functionality like so by using a set, as elaborated on in Why does Python's itertools.permutations contain duplicates? (When the original list has duplicates)

def unique_perms(iterable):
    perm_set = set()
    permutations = [i for i in itertools.permutations(iterable) if i not in perm_set and not perm_set.add(i)]
    return [''.join(p) for p in (map(str, perm) for perm in permutations)]

This is still significantly faster than the posters original method, especially for examples like '000' and is stable (preserves permutation order).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM