Generate next bigger combination in lexicographic order in python












0












$begingroup$


I am new in python.I am developing my python skill by solving problems in Hackerrank. I am currently experiencing the problem with finding solution one interesting challenges. The task of the problem is the following:
I need to find a bigger string (within lexicographical order) that greater than given string.



Condition:
Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria:



It must be greater than the original word
It must be the smallest word that meets the first condition
For example, given the w="hega", the next largest word is "gahe" or w="abcd", the next largest word is "abdc".



I first try to do it through permutations methods in python. for some reason, that code did not pass all test cases.



Then, I wrote the following code.
This code works for majority cases (i believe), however, when the given string is too long, it takes a lot of time to converge (times out) and therefore it fails the test.



import string

w="dcba"


number=[n for n in range(1,27)]
letter=[x for x in string.ascii_lowercase]
dict_storage=dict(zip(string.ascii_lowercase,number))


def biggerIsGreater(w):
total_len=len(w)
count1=0

for _ in range(1,len(w)):
if count1==1:
break
else:
total_len-=1
count=total_len
for _ in range(0,len(w[:total_len])):
move_letter=dict_storage.get(w[total_len])
s1_max=dict_storage.get(max(set(w[:total_len])))
if move_letter>s1_max:
break
else:
count-=1
iter_letter=dict_storage.get(w[count])
if move_letter>iter_letter and count1==0:
move_index=total_len
loc_index=count
count1+=1
break
if count1==0:
return "no answer"
else:
left_str=w[:loc_index]
right_str=w[loc_index:move_index]
move_str=w[move_index:]
new_str=left_str+move_str+right_str
return new_str
print(biggerIsGreater(w))


sample input:
ab
bb
hefg
dhck
dkhc



Sample output:
ba
no answer
hegf
dhkc
hcdk



would you please have review the code and suggest more elegant way to solve this challange.



Thanks in advance



Reagrds
Ahad









share







New contributor




ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    I am new in python.I am developing my python skill by solving problems in Hackerrank. I am currently experiencing the problem with finding solution one interesting challenges. The task of the problem is the following:
    I need to find a bigger string (within lexicographical order) that greater than given string.



    Condition:
    Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria:



    It must be greater than the original word
    It must be the smallest word that meets the first condition
    For example, given the w="hega", the next largest word is "gahe" or w="abcd", the next largest word is "abdc".



    I first try to do it through permutations methods in python. for some reason, that code did not pass all test cases.



    Then, I wrote the following code.
    This code works for majority cases (i believe), however, when the given string is too long, it takes a lot of time to converge (times out) and therefore it fails the test.



    import string

    w="dcba"


    number=[n for n in range(1,27)]
    letter=[x for x in string.ascii_lowercase]
    dict_storage=dict(zip(string.ascii_lowercase,number))


    def biggerIsGreater(w):
    total_len=len(w)
    count1=0

    for _ in range(1,len(w)):
    if count1==1:
    break
    else:
    total_len-=1
    count=total_len
    for _ in range(0,len(w[:total_len])):
    move_letter=dict_storage.get(w[total_len])
    s1_max=dict_storage.get(max(set(w[:total_len])))
    if move_letter>s1_max:
    break
    else:
    count-=1
    iter_letter=dict_storage.get(w[count])
    if move_letter>iter_letter and count1==0:
    move_index=total_len
    loc_index=count
    count1+=1
    break
    if count1==0:
    return "no answer"
    else:
    left_str=w[:loc_index]
    right_str=w[loc_index:move_index]
    move_str=w[move_index:]
    new_str=left_str+move_str+right_str
    return new_str
    print(biggerIsGreater(w))


    sample input:
    ab
    bb
    hefg
    dhck
    dkhc



    Sample output:
    ba
    no answer
    hegf
    dhkc
    hcdk



    would you please have review the code and suggest more elegant way to solve this challange.



    Thanks in advance



    Reagrds
    Ahad









    share







    New contributor




    ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      I am new in python.I am developing my python skill by solving problems in Hackerrank. I am currently experiencing the problem with finding solution one interesting challenges. The task of the problem is the following:
      I need to find a bigger string (within lexicographical order) that greater than given string.



      Condition:
      Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria:



      It must be greater than the original word
      It must be the smallest word that meets the first condition
      For example, given the w="hega", the next largest word is "gahe" or w="abcd", the next largest word is "abdc".



      I first try to do it through permutations methods in python. for some reason, that code did not pass all test cases.



      Then, I wrote the following code.
      This code works for majority cases (i believe), however, when the given string is too long, it takes a lot of time to converge (times out) and therefore it fails the test.



      import string

      w="dcba"


      number=[n for n in range(1,27)]
      letter=[x for x in string.ascii_lowercase]
      dict_storage=dict(zip(string.ascii_lowercase,number))


      def biggerIsGreater(w):
      total_len=len(w)
      count1=0

      for _ in range(1,len(w)):
      if count1==1:
      break
      else:
      total_len-=1
      count=total_len
      for _ in range(0,len(w[:total_len])):
      move_letter=dict_storage.get(w[total_len])
      s1_max=dict_storage.get(max(set(w[:total_len])))
      if move_letter>s1_max:
      break
      else:
      count-=1
      iter_letter=dict_storage.get(w[count])
      if move_letter>iter_letter and count1==0:
      move_index=total_len
      loc_index=count
      count1+=1
      break
      if count1==0:
      return "no answer"
      else:
      left_str=w[:loc_index]
      right_str=w[loc_index:move_index]
      move_str=w[move_index:]
      new_str=left_str+move_str+right_str
      return new_str
      print(biggerIsGreater(w))


      sample input:
      ab
      bb
      hefg
      dhck
      dkhc



      Sample output:
      ba
      no answer
      hegf
      dhkc
      hcdk



      would you please have review the code and suggest more elegant way to solve this challange.



      Thanks in advance



      Reagrds
      Ahad









      share







      New contributor




      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      I am new in python.I am developing my python skill by solving problems in Hackerrank. I am currently experiencing the problem with finding solution one interesting challenges. The task of the problem is the following:
      I need to find a bigger string (within lexicographical order) that greater than given string.



      Condition:
      Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria:



      It must be greater than the original word
      It must be the smallest word that meets the first condition
      For example, given the w="hega", the next largest word is "gahe" or w="abcd", the next largest word is "abdc".



      I first try to do it through permutations methods in python. for some reason, that code did not pass all test cases.



      Then, I wrote the following code.
      This code works for majority cases (i believe), however, when the given string is too long, it takes a lot of time to converge (times out) and therefore it fails the test.



      import string

      w="dcba"


      number=[n for n in range(1,27)]
      letter=[x for x in string.ascii_lowercase]
      dict_storage=dict(zip(string.ascii_lowercase,number))


      def biggerIsGreater(w):
      total_len=len(w)
      count1=0

      for _ in range(1,len(w)):
      if count1==1:
      break
      else:
      total_len-=1
      count=total_len
      for _ in range(0,len(w[:total_len])):
      move_letter=dict_storage.get(w[total_len])
      s1_max=dict_storage.get(max(set(w[:total_len])))
      if move_letter>s1_max:
      break
      else:
      count-=1
      iter_letter=dict_storage.get(w[count])
      if move_letter>iter_letter and count1==0:
      move_index=total_len
      loc_index=count
      count1+=1
      break
      if count1==0:
      return "no answer"
      else:
      left_str=w[:loc_index]
      right_str=w[loc_index:move_index]
      move_str=w[move_index:]
      new_str=left_str+move_str+right_str
      return new_str
      print(biggerIsGreater(w))


      sample input:
      ab
      bb
      hefg
      dhck
      dkhc



      Sample output:
      ba
      no answer
      hegf
      dhkc
      hcdk



      would you please have review the code and suggest more elegant way to solve this challange.



      Thanks in advance



      Reagrds
      Ahad







      python algorithm





      share







      New contributor




      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 5 mins ago









      ahad pashayevahad pashayev

      1




      1




      New contributor




      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      ahad pashayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          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: "196"
          };
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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
          });


          }
          });






          ahad pashayev is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212513%2fgenerate-next-bigger-combination-in-lexicographic-order-in-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          ahad pashayev is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          ahad pashayev is a new contributor. Be nice, and check out our Code of Conduct.













          ahad pashayev is a new contributor. Be nice, and check out our Code of Conduct.












          ahad pashayev is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • 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.


          Use MathJax to format equations. MathJax reference.


          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%2fcodereview.stackexchange.com%2fquestions%2f212513%2fgenerate-next-bigger-combination-in-lexicographic-order-in-python%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

          Сан-Квентин

          Алькесар

          Josef Freinademetz