Terence Chow
Terence Chow

Reputation: 11173

combining strings of n length in a list python

Whenever I use permutations, I have to create a list of the permutations because it returns a 'itertools.permutations object at 0x0190A5D0'. Then after I create the list, I have to combine the strings in each list so that I have the permutation I wanted originally. If it is a number, then I have to make them all integers again.

Two part question:

1) Is there an easier way to do a permutation and create the list of numbers?

2) Below I've created a permutation of a number with 5 digits. However, where I have '12345', I want the user to input their own number. Thus the formatting string b=['s%s%s...] will have to be n %s and n x. Anyone know how to do this?

(FYI my program is trying to find the next largest number with the same digits given a user's input so 12345 next largest is 12354)

Both questions were answered below please see both responses. Thanks!!!

def nexthighest():
    from itertools import permutations
    numb = str(12345)
    a = list(permutations(numb))
    b = ['%s%s%s%s%s' % xxxxx for xxxxx in a]  #<-- this is where the n length problem occurs
    c = list(map(int,b))
    for i in c:
        if i >12345:
            print(i)
            break

Upvotes: 1

Views: 256

Answers (2)

Fred Foo
Fred Foo

Reputation: 363858

You don't need to build all those lists. Just loop over the return value from permutations, joining and parsing as an integer each permutation as it comes by:

def nexthigher(n):
    for p in permutations(sorted(str(n))):
        i = int("".join(p))
        if i > n:
            return i

Upvotes: 4

C0deH4cker
C0deH4cker

Reputation: 4075

I can answer part two for you:

b = ["".join(x) for x in a]

Upvotes: 1

Related Questions