How to make this run 'faster'? Or is that the right terminology?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?Is there a way to run Python on Android?How can I safely create a nested directory?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I list all files of a directory?

Employer demanding to see degree after poor code review

Why are values I enter in the interface getting halved?

Is Jon Snow the last of his House?

Count rotary dial pulses in a phone number (including letters)

Are these reasonable traits for someone with autism?

Make 24 using exactly three 3s

Looking for a soft substance that doesn't dissolve underwater

Where's this lookout in Nova Scotia?

What are these arcade games in Ghostbusters 1984?

Using credit/debit card details vs swiping a card in a payment (credit card) terminal

Why do airplanes use an axial flow jet engine instead of a more compact centrifugal jet engine?

Would jet fuel for an F-16 or F-35 be producible during WW2?

Is it true that cut time means "play twice as fast as written"?

What is quasi-aromaticity?

What will be the real voltage along the line with a voltage source and a capacitor?

Is the Starlink array really visible from Earth?

Line of lights moving in a straight line , with a few following

Employer asking for online access to bank account - Is this a scam?

Why are C64 games inconsistent with which joystick port they use?

Compactness of finite sets

Python program to find the most frequent letter in a text

How to execute this code on startup?

Defining the standard model of PA so that a space alien could understand

Who will lead the country until there is a new Tory leader?



How to make this run 'faster'? Or is that the right terminology?


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?Is there a way to run Python on Android?How can I safely create a nested directory?How can I make a time delay in Python?How do I sort a dictionary by value?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I list all files of a directory?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?



I've pasted the main swap function below.
(Repeats M times)



temp = input()
temp = temp.split(" ")
i = int(temp[1])-1
j = int(temp[2])-1
rep = (i-1)+1

if(temp[0]=='1') :
rep = (i-1)+1
while(i<=j) :
count = i-1
ex1 = count
ex2 = i
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1-1
ex2 = ex2-1
i = i+1
else :
rep = (N-(j+1))
while(j>=i) :
count = j+1
ex1 = count
ex2 = j
for k in range(0,rep) :
arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
ex1 = ex1+1
ex2 = ex2+1
j=j-1









share|improve this question






























    1















    I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?



    I've pasted the main swap function below.
    (Repeats M times)



    temp = input()
    temp = temp.split(" ")
    i = int(temp[1])-1
    j = int(temp[2])-1
    rep = (i-1)+1

    if(temp[0]=='1') :
    rep = (i-1)+1
    while(i<=j) :
    count = i-1
    ex1 = count
    ex2 = i
    for k in range(0,rep) :
    arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
    ex1 = ex1-1
    ex2 = ex2-1
    i = i+1
    else :
    rep = (N-(j+1))
    while(j>=i) :
    count = j+1
    ex1 = count
    ex2 = j
    for k in range(0,rep) :
    arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
    ex1 = ex1+1
    ex2 = ex2+1
    j=j-1









    share|improve this question


























      1












      1








      1


      1






      I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?



      I've pasted the main swap function below.
      (Repeats M times)



      temp = input()
      temp = temp.split(" ")
      i = int(temp[1])-1
      j = int(temp[2])-1
      rep = (i-1)+1

      if(temp[0]=='1') :
      rep = (i-1)+1
      while(i<=j) :
      count = i-1
      ex1 = count
      ex2 = i
      for k in range(0,rep) :
      arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
      ex1 = ex1-1
      ex2 = ex2-1
      i = i+1
      else :
      rep = (N-(j+1))
      while(j>=i) :
      count = j+1
      ex1 = count
      ex2 = j
      for k in range(0,rep) :
      arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
      ex1 = ex1+1
      ex2 = ex2+1
      j=j-1









      share|improve this question
















      I am new to python and I submitted this code for a Hackerrank problem Arrays and Simple Queries, but for a large number of test cases the program is 'terminated due to timeout'. How can I make this more efficient?



      I've pasted the main swap function below.
      (Repeats M times)



      temp = input()
      temp = temp.split(" ")
      i = int(temp[1])-1
      j = int(temp[2])-1
      rep = (i-1)+1

      if(temp[0]=='1') :
      rep = (i-1)+1
      while(i<=j) :
      count = i-1
      ex1 = count
      ex2 = i
      for k in range(0,rep) :
      arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
      ex1 = ex1-1
      ex2 = ex2-1
      i = i+1
      else :
      rep = (N-(j+1))
      while(j>=i) :
      count = j+1
      ex1 = count
      ex2 = j
      for k in range(0,rep) :
      arr[ex1], arr[ex2] = arr[ex2], arr[ex1]
      ex1 = ex1+1
      ex2 = ex2+1
      j=j-1






      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 5:37









      John Kugelman

      252k55412464




      252k55412464










      asked Mar 24 at 5:32









      dcddcd

      62




      62






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Instead of using many loops, you can try simply concatenating slices:



          def query(lst, t, start, end):
          # Convert to proper zero-indexed index
          start -= 1

          if t == '1':
          return lst[start:end] + lst[:start] + lst[end:]
          elif t == '2':
          return lst[:start] + lst[end:] + lst[start:end]


          # Get the input however you want
          N, M = map(int, input().split())
          arr = list(map(int, input().split()))
          assert len(arr) == N

          for _ in range(M):
          t, start, end = input().split()
          arr = query(arr, t, int(start), int(end))

          print(abs(arr[0] - arr[N - 1]))
          print(*arr)


          Input:



          8 4
          1 2 3 4 5 6 7 8
          1 2 4
          2 3 5
          1 4 7
          2 1 4


          Output:



          1
          2 3 6 5 7 8 4 1





          share|improve this answer























          • It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

            – dcd
            Mar 24 at 6:00












          • @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

            – Tomothy32
            Mar 24 at 6:10











          • so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

            – dcd
            Mar 24 at 6:24











          • @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

            – Tomothy32
            Mar 24 at 6:27












          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%2f55321002%2fhow-to-make-this-run-faster-or-is-that-the-right-terminology%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Instead of using many loops, you can try simply concatenating slices:



          def query(lst, t, start, end):
          # Convert to proper zero-indexed index
          start -= 1

          if t == '1':
          return lst[start:end] + lst[:start] + lst[end:]
          elif t == '2':
          return lst[:start] + lst[end:] + lst[start:end]


          # Get the input however you want
          N, M = map(int, input().split())
          arr = list(map(int, input().split()))
          assert len(arr) == N

          for _ in range(M):
          t, start, end = input().split()
          arr = query(arr, t, int(start), int(end))

          print(abs(arr[0] - arr[N - 1]))
          print(*arr)


          Input:



          8 4
          1 2 3 4 5 6 7 8
          1 2 4
          2 3 5
          1 4 7
          2 1 4


          Output:



          1
          2 3 6 5 7 8 4 1





          share|improve this answer























          • It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

            – dcd
            Mar 24 at 6:00












          • @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

            – Tomothy32
            Mar 24 at 6:10











          • so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

            – dcd
            Mar 24 at 6:24











          • @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

            – Tomothy32
            Mar 24 at 6:27
















          1














          Instead of using many loops, you can try simply concatenating slices:



          def query(lst, t, start, end):
          # Convert to proper zero-indexed index
          start -= 1

          if t == '1':
          return lst[start:end] + lst[:start] + lst[end:]
          elif t == '2':
          return lst[:start] + lst[end:] + lst[start:end]


          # Get the input however you want
          N, M = map(int, input().split())
          arr = list(map(int, input().split()))
          assert len(arr) == N

          for _ in range(M):
          t, start, end = input().split()
          arr = query(arr, t, int(start), int(end))

          print(abs(arr[0] - arr[N - 1]))
          print(*arr)


          Input:



          8 4
          1 2 3 4 5 6 7 8
          1 2 4
          2 3 5
          1 4 7
          2 1 4


          Output:



          1
          2 3 6 5 7 8 4 1





          share|improve this answer























          • It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

            – dcd
            Mar 24 at 6:00












          • @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

            – Tomothy32
            Mar 24 at 6:10











          • so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

            – dcd
            Mar 24 at 6:24











          • @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

            – Tomothy32
            Mar 24 at 6:27














          1












          1








          1







          Instead of using many loops, you can try simply concatenating slices:



          def query(lst, t, start, end):
          # Convert to proper zero-indexed index
          start -= 1

          if t == '1':
          return lst[start:end] + lst[:start] + lst[end:]
          elif t == '2':
          return lst[:start] + lst[end:] + lst[start:end]


          # Get the input however you want
          N, M = map(int, input().split())
          arr = list(map(int, input().split()))
          assert len(arr) == N

          for _ in range(M):
          t, start, end = input().split()
          arr = query(arr, t, int(start), int(end))

          print(abs(arr[0] - arr[N - 1]))
          print(*arr)


          Input:



          8 4
          1 2 3 4 5 6 7 8
          1 2 4
          2 3 5
          1 4 7
          2 1 4


          Output:



          1
          2 3 6 5 7 8 4 1





          share|improve this answer













          Instead of using many loops, you can try simply concatenating slices:



          def query(lst, t, start, end):
          # Convert to proper zero-indexed index
          start -= 1

          if t == '1':
          return lst[start:end] + lst[:start] + lst[end:]
          elif t == '2':
          return lst[:start] + lst[end:] + lst[start:end]


          # Get the input however you want
          N, M = map(int, input().split())
          arr = list(map(int, input().split()))
          assert len(arr) == N

          for _ in range(M):
          t, start, end = input().split()
          arr = query(arr, t, int(start), int(end))

          print(abs(arr[0] - arr[N - 1]))
          print(*arr)


          Input:



          8 4
          1 2 3 4 5 6 7 8
          1 2 4
          2 3 5
          1 4 7
          2 1 4


          Output:



          1
          2 3 6 5 7 8 4 1






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 5:53









          Tomothy32Tomothy32

          9,6132928




          9,6132928












          • It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

            – dcd
            Mar 24 at 6:00












          • @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

            – Tomothy32
            Mar 24 at 6:10











          • so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

            – dcd
            Mar 24 at 6:24











          • @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

            – Tomothy32
            Mar 24 at 6:27


















          • It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

            – dcd
            Mar 24 at 6:00












          • @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

            – Tomothy32
            Mar 24 at 6:10











          • so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

            – dcd
            Mar 24 at 6:24











          • @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

            – Tomothy32
            Mar 24 at 6:27

















          It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

          – dcd
          Mar 24 at 6:00






          It would definitely take me some time to understand what you have done and I'll try writing something similar. Thank you :)

          – dcd
          Mar 24 at 6:00














          @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

          – Tomothy32
          Mar 24 at 6:10





          @dcd The only important part should be the query function. Everything else is just to receive input and give output. I just tested this solution, and unfortunately it times out on some of the later test cases. I'll try to make some improvements and get back to you.

          – Tomothy32
          Mar 24 at 6:10













          so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

          – dcd
          Mar 24 at 6:24





          so we're losing time only on the query function? And yeah, it is timing out on a couple of test cases but it's still considerably faster than my code. I have so much more to learn damn. Alright, thanks :)

          – dcd
          Mar 24 at 6:24













          @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

          – Tomothy32
          Mar 24 at 6:27






          @dcd No problem! I'm glad I was able to help despite the solution not fully meeting the time restrictions. I'll keep thinking about the problem in the meanwhile. Switching to the dark side (a.k.a. C++) might be an option... :)

          – Tomothy32
          Mar 24 at 6:27




















          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%2f55321002%2fhow-to-make-this-run-faster-or-is-that-the-right-terminology%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

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해