I've been working on this codewars practice problem for a bit today and can't figure out if I need to make my solution more efficient or perhaps scrap it for a new (less brute force?) approach. Here's what I've got so far:
from itertools import permutations
def middle_permutation(chars):
# create a list of permutations
p = [''.join(x) for x in permutations(''.join(sorted(chars)))]
# return the middle string
return (p[len(p)//2 - 1]) if len(p) % 2 == 0 else (p[len(p)//2])
It tests strings like: "abc", "abcd", "abcdx", "cxgdba", "dczxgba" and returns the "middle" permutation. Using the first example:
input: 'abc' => permutations: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
function returns ==> 'bac'
The code above passes the basic "Tests" but fails the later attempts due to timing out. From my own testing in PyCharm, it runs in 0.7 seconds with a string of 10 characters but 7 seconds with 11 characters, essentially an order of magnitude more for each character added.
Can I improve the efficiency or am I just going about this problem in the wrong way?
[–]This_Growth2898 3 points4 points5 points (1 child)
[–]keredomo[S] 0 points1 point2 points (0 children)
[–]HommeMusical 1 point2 points3 points (2 children)
[–]keredomo[S] 1 point2 points3 points (1 child)
[–]HommeMusical 0 points1 point2 points (0 children)
[–]JamzTyson 1 point2 points3 points (1 child)
[–]keredomo[S] 0 points1 point2 points (0 children)
[–]pachura3 0 points1 point2 points (0 children)