Split a string to K substrings using List Comprehension












1















I have a long string with me like this



s = 'abcdabcdabcdabcdabcdefghi'



I want to split it to K substrings, where each substring must be at least of length 1 ie non-empty. I want all such possible combinations.



The output I am expecting must be like following if K is 3



[['abcda', 'bcdabcdabcda', 'bcdefghi'], [.....], [....], ... ]


I wanted to do this with list comprehension but I am stuck. Is it possible to implement.? Are there any other faster alternatives.?










share|improve this question


















  • 2





    Why does your expected output with K=3 not start with ['a','b','cdabcdabcdabcdabcdefghi']?

    – usr2564301
    Nov 25 '18 at 10:48











  • I just gave a random sample. The order doesn't matter

    – Sreeram TP
    Nov 25 '18 at 10:49











  • Do you want every possible combination of K sublists?

    – SuperShoot
    Nov 25 '18 at 10:49











  • I want to get every possible combination of K sublists. I am looking for some faster method. List comprehension most preferably.

    – Sreeram TP
    Nov 25 '18 at 10:51


















1















I have a long string with me like this



s = 'abcdabcdabcdabcdabcdefghi'



I want to split it to K substrings, where each substring must be at least of length 1 ie non-empty. I want all such possible combinations.



The output I am expecting must be like following if K is 3



[['abcda', 'bcdabcdabcda', 'bcdefghi'], [.....], [....], ... ]


I wanted to do this with list comprehension but I am stuck. Is it possible to implement.? Are there any other faster alternatives.?










share|improve this question


















  • 2





    Why does your expected output with K=3 not start with ['a','b','cdabcdabcdabcdabcdefghi']?

    – usr2564301
    Nov 25 '18 at 10:48











  • I just gave a random sample. The order doesn't matter

    – Sreeram TP
    Nov 25 '18 at 10:49











  • Do you want every possible combination of K sublists?

    – SuperShoot
    Nov 25 '18 at 10:49











  • I want to get every possible combination of K sublists. I am looking for some faster method. List comprehension most preferably.

    – Sreeram TP
    Nov 25 '18 at 10:51
















1












1








1


1






I have a long string with me like this



s = 'abcdabcdabcdabcdabcdefghi'



I want to split it to K substrings, where each substring must be at least of length 1 ie non-empty. I want all such possible combinations.



The output I am expecting must be like following if K is 3



[['abcda', 'bcdabcdabcda', 'bcdefghi'], [.....], [....], ... ]


I wanted to do this with list comprehension but I am stuck. Is it possible to implement.? Are there any other faster alternatives.?










share|improve this question














I have a long string with me like this



s = 'abcdabcdabcdabcdabcdefghi'



I want to split it to K substrings, where each substring must be at least of length 1 ie non-empty. I want all such possible combinations.



The output I am expecting must be like following if K is 3



[['abcda', 'bcdabcdabcda', 'bcdefghi'], [.....], [....], ... ]


I wanted to do this with list comprehension but I am stuck. Is it possible to implement.? Are there any other faster alternatives.?







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 10:44









Sreeram TPSreeram TP

2,98731438




2,98731438








  • 2





    Why does your expected output with K=3 not start with ['a','b','cdabcdabcdabcdabcdefghi']?

    – usr2564301
    Nov 25 '18 at 10:48











  • I just gave a random sample. The order doesn't matter

    – Sreeram TP
    Nov 25 '18 at 10:49











  • Do you want every possible combination of K sublists?

    – SuperShoot
    Nov 25 '18 at 10:49











  • I want to get every possible combination of K sublists. I am looking for some faster method. List comprehension most preferably.

    – Sreeram TP
    Nov 25 '18 at 10:51
















  • 2





    Why does your expected output with K=3 not start with ['a','b','cdabcdabcdabcdabcdefghi']?

    – usr2564301
    Nov 25 '18 at 10:48











  • I just gave a random sample. The order doesn't matter

    – Sreeram TP
    Nov 25 '18 at 10:49











  • Do you want every possible combination of K sublists?

    – SuperShoot
    Nov 25 '18 at 10:49











  • I want to get every possible combination of K sublists. I am looking for some faster method. List comprehension most preferably.

    – Sreeram TP
    Nov 25 '18 at 10:51










2




2





Why does your expected output with K=3 not start with ['a','b','cdabcdabcdabcdabcdefghi']?

– usr2564301
Nov 25 '18 at 10:48





Why does your expected output with K=3 not start with ['a','b','cdabcdabcdabcdabcdefghi']?

– usr2564301
Nov 25 '18 at 10:48













I just gave a random sample. The order doesn't matter

– Sreeram TP
Nov 25 '18 at 10:49





I just gave a random sample. The order doesn't matter

– Sreeram TP
Nov 25 '18 at 10:49













Do you want every possible combination of K sublists?

– SuperShoot
Nov 25 '18 at 10:49





Do you want every possible combination of K sublists?

– SuperShoot
Nov 25 '18 at 10:49













I want to get every possible combination of K sublists. I am looking for some faster method. List comprehension most preferably.

– Sreeram TP
Nov 25 '18 at 10:51







I want to get every possible combination of K sublists. I am looking for some faster method. List comprehension most preferably.

– Sreeram TP
Nov 25 '18 at 10:51














2 Answers
2






active

oldest

votes


















2














Using itertools.combinations, you can get separation index pairs:



>>> s = 'abcdef'
>>> k = 3
>>> list(combinations(range(1, len(s)), k-1))
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]


using that index pair to get string slices





  • (1, 2) -> (s[:1], s[1:2], s[2:])


  • (1, 3) -> (s[:1], s[1:3], s[3:])

  • ...


  • (4, 5) -> (s[:4], s[4:5], s[5:])




>>> from itertools import combinations
>>> s = 'abcdef'

>>> k = 3
>>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
... for idxs in combinations(range(1, len(s)), k-1)]
[['a', 'b', 'cdef'], ['a', 'bc', 'def'], ..., ['abcd', 'e', 'f']]


>>> k = 4
>>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
... for idxs in combinations(range(1, len(s)), k-1)]
[['a', 'b', 'c', 'def'], ['a', 'b', 'cd', 'ef'], ..., ['abc', 'd', 'e', 'f']]



  • s[:1] == s[0:1] == s[None:1]

  • s[2:] == s[2:len(s)] == s[2:None]






share|improve this answer


























  • Seems cool. Will this be faster than the other solution.?

    – Sreeram TP
    Nov 25 '18 at 10:57











  • @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

    – falsetru
    Nov 25 '18 at 10:59





















0














You could find all slices of your list so that none of sliced parts will be empty without any extended libraries like so:



s = 'abcd'
substrings =

# find slice of first part - from a|bcd to ab|cd
for first_slice in range(len(s)-2):
# find slice of second and last part, for bcd - from b|cd to bc|d
# for cd - just c|d
for second_slice in range(first_slice+1, len(s)-1):
substrings.append([s[:first_slice+1], s[first_slice+1: second_slice+1], s[second_slice+1:]])

print(substrings) # -> [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]

s = 'abcdabcdabcdabcdabcdefghi'
print(len(substrings)) # -> 276





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466685%2fsplit-a-string-to-k-substrings-using-list-comprehension%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Using itertools.combinations, you can get separation index pairs:



    >>> s = 'abcdef'
    >>> k = 3
    >>> list(combinations(range(1, len(s)), k-1))
    [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]


    using that index pair to get string slices





    • (1, 2) -> (s[:1], s[1:2], s[2:])


    • (1, 3) -> (s[:1], s[1:3], s[3:])

    • ...


    • (4, 5) -> (s[:4], s[4:5], s[5:])




    >>> from itertools import combinations
    >>> s = 'abcdef'

    >>> k = 3
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'cdef'], ['a', 'bc', 'def'], ..., ['abcd', 'e', 'f']]


    >>> k = 4
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'c', 'def'], ['a', 'b', 'cd', 'ef'], ..., ['abc', 'd', 'e', 'f']]



    • s[:1] == s[0:1] == s[None:1]

    • s[2:] == s[2:len(s)] == s[2:None]






    share|improve this answer


























    • Seems cool. Will this be faster than the other solution.?

      – Sreeram TP
      Nov 25 '18 at 10:57











    • @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

      – falsetru
      Nov 25 '18 at 10:59


















    2














    Using itertools.combinations, you can get separation index pairs:



    >>> s = 'abcdef'
    >>> k = 3
    >>> list(combinations(range(1, len(s)), k-1))
    [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]


    using that index pair to get string slices





    • (1, 2) -> (s[:1], s[1:2], s[2:])


    • (1, 3) -> (s[:1], s[1:3], s[3:])

    • ...


    • (4, 5) -> (s[:4], s[4:5], s[5:])




    >>> from itertools import combinations
    >>> s = 'abcdef'

    >>> k = 3
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'cdef'], ['a', 'bc', 'def'], ..., ['abcd', 'e', 'f']]


    >>> k = 4
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'c', 'def'], ['a', 'b', 'cd', 'ef'], ..., ['abc', 'd', 'e', 'f']]



    • s[:1] == s[0:1] == s[None:1]

    • s[2:] == s[2:len(s)] == s[2:None]






    share|improve this answer


























    • Seems cool. Will this be faster than the other solution.?

      – Sreeram TP
      Nov 25 '18 at 10:57











    • @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

      – falsetru
      Nov 25 '18 at 10:59
















    2












    2








    2







    Using itertools.combinations, you can get separation index pairs:



    >>> s = 'abcdef'
    >>> k = 3
    >>> list(combinations(range(1, len(s)), k-1))
    [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]


    using that index pair to get string slices





    • (1, 2) -> (s[:1], s[1:2], s[2:])


    • (1, 3) -> (s[:1], s[1:3], s[3:])

    • ...


    • (4, 5) -> (s[:4], s[4:5], s[5:])




    >>> from itertools import combinations
    >>> s = 'abcdef'

    >>> k = 3
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'cdef'], ['a', 'bc', 'def'], ..., ['abcd', 'e', 'f']]


    >>> k = 4
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'c', 'def'], ['a', 'b', 'cd', 'ef'], ..., ['abc', 'd', 'e', 'f']]



    • s[:1] == s[0:1] == s[None:1]

    • s[2:] == s[2:len(s)] == s[2:None]






    share|improve this answer















    Using itertools.combinations, you can get separation index pairs:



    >>> s = 'abcdef'
    >>> k = 3
    >>> list(combinations(range(1, len(s)), k-1))
    [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]


    using that index pair to get string slices





    • (1, 2) -> (s[:1], s[1:2], s[2:])


    • (1, 3) -> (s[:1], s[1:3], s[3:])

    • ...


    • (4, 5) -> (s[:4], s[4:5], s[5:])




    >>> from itertools import combinations
    >>> s = 'abcdef'

    >>> k = 3
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'cdef'], ['a', 'bc', 'def'], ..., ['abcd', 'e', 'f']]


    >>> k = 4
    >>> [[s[i:j] for i, j in zip((None,) + idxs, idxs + (None,))]
    ... for idxs in combinations(range(1, len(s)), k-1)]
    [['a', 'b', 'c', 'def'], ['a', 'b', 'cd', 'ef'], ..., ['abc', 'd', 'e', 'f']]



    • s[:1] == s[0:1] == s[None:1]

    • s[2:] == s[2:len(s)] == s[2:None]







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 25 '18 at 11:05

























    answered Nov 25 '18 at 10:53









    falsetrufalsetru

    250k34443436




    250k34443436













    • Seems cool. Will this be faster than the other solution.?

      – Sreeram TP
      Nov 25 '18 at 10:57











    • @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

      – falsetru
      Nov 25 '18 at 10:59





















    • Seems cool. Will this be faster than the other solution.?

      – Sreeram TP
      Nov 25 '18 at 10:57











    • @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

      – falsetru
      Nov 25 '18 at 10:59



















    Seems cool. Will this be faster than the other solution.?

    – Sreeram TP
    Nov 25 '18 at 10:57





    Seems cool. Will this be faster than the other solution.?

    – Sreeram TP
    Nov 25 '18 at 10:57













    @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

    – falsetru
    Nov 25 '18 at 10:59







    @SreeramTP, Time complexity is same as far as I know. But other solution (Filip Młynarski) works only for k=3 case. To go future you need to add another for loop(s).

    – falsetru
    Nov 25 '18 at 10:59















    0














    You could find all slices of your list so that none of sliced parts will be empty without any extended libraries like so:



    s = 'abcd'
    substrings =

    # find slice of first part - from a|bcd to ab|cd
    for first_slice in range(len(s)-2):
    # find slice of second and last part, for bcd - from b|cd to bc|d
    # for cd - just c|d
    for second_slice in range(first_slice+1, len(s)-1):
    substrings.append([s[:first_slice+1], s[first_slice+1: second_slice+1], s[second_slice+1:]])

    print(substrings) # -> [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]

    s = 'abcdabcdabcdabcdabcdefghi'
    print(len(substrings)) # -> 276





    share|improve this answer






























      0














      You could find all slices of your list so that none of sliced parts will be empty without any extended libraries like so:



      s = 'abcd'
      substrings =

      # find slice of first part - from a|bcd to ab|cd
      for first_slice in range(len(s)-2):
      # find slice of second and last part, for bcd - from b|cd to bc|d
      # for cd - just c|d
      for second_slice in range(first_slice+1, len(s)-1):
      substrings.append([s[:first_slice+1], s[first_slice+1: second_slice+1], s[second_slice+1:]])

      print(substrings) # -> [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]

      s = 'abcdabcdabcdabcdabcdefghi'
      print(len(substrings)) # -> 276





      share|improve this answer




























        0












        0








        0







        You could find all slices of your list so that none of sliced parts will be empty without any extended libraries like so:



        s = 'abcd'
        substrings =

        # find slice of first part - from a|bcd to ab|cd
        for first_slice in range(len(s)-2):
        # find slice of second and last part, for bcd - from b|cd to bc|d
        # for cd - just c|d
        for second_slice in range(first_slice+1, len(s)-1):
        substrings.append([s[:first_slice+1], s[first_slice+1: second_slice+1], s[second_slice+1:]])

        print(substrings) # -> [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]

        s = 'abcdabcdabcdabcdabcdefghi'
        print(len(substrings)) # -> 276





        share|improve this answer















        You could find all slices of your list so that none of sliced parts will be empty without any extended libraries like so:



        s = 'abcd'
        substrings =

        # find slice of first part - from a|bcd to ab|cd
        for first_slice in range(len(s)-2):
        # find slice of second and last part, for bcd - from b|cd to bc|d
        # for cd - just c|d
        for second_slice in range(first_slice+1, len(s)-1):
        substrings.append([s[:first_slice+1], s[first_slice+1: second_slice+1], s[second_slice+1:]])

        print(substrings) # -> [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]

        s = 'abcdabcdabcdabcdabcdefghi'
        print(len(substrings)) # -> 276






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 25 '18 at 11:00

























        answered Nov 25 '18 at 10:53









        Filip MłynarskiFilip Młynarski

        1,7961413




        1,7961413






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53466685%2fsplit-a-string-to-k-substrings-using-list-comprehension%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Costa Masnaga

            Fotorealismo

            Sidney Franklin