Bit-based universe simulationProject Euler #11 Largest product in a gridGoogle Code Jam Google String problem: a sequence resulting from bit flips and reversalsSaving the Universe - Code Jam 2008 Qualification problem ABit shifting in PythonPython - lookahead driver for a parsing chainA-Star Search with 3D UniverseBlackjack strategy simulationParallel processing simulationCounting lower vs non-lowercase tokens for tokenized text with several conditionsBirthday paradox simulation

How to answer "write something on the board"?

Can a function nowhere continuous have a connected graph?

Bit-based universe simulation

Can I travel from Germany to England alone as an unaccompanied minor?

Prime parity peregrination

What does grep -v "grep" mean and do?

Step into the Octagram

Sharing referee/AE report online to point out a grievous error in refereeing

Pairwise Scatter Plots with Histograms and Correlations

Boolean Difference with Offset?

Handling a player (unintentionally) stealing the spotlight

How did researchers find articles before the Internet and the computer era?

Details of video memory access arbitration in Space Invaders

Can two or more lightbeams (from a laser for example) have visible interference when they cross in mid-air*?

How do I tell the reader that my character is autistic in Fantasy?

Can Aziraphale and Crowley actually become native?

Is the location of an aircraft spoiler really that vital?

Procedurally generate regions on island

In native German words, is Q always followed by U, as in English?

Why is Japan trying to have a better relationship with Iran?

Why was Mal so quick to drop Bester in favour of Kaylee?

How is this practical and very old scene shot?

How did installing this RPM create a file?

Chords behaving as a melody



Bit-based universe simulation


Project Euler #11 Largest product in a gridGoogle Code Jam Google String problem: a sequence resulting from bit flips and reversalsSaving the Universe - Code Jam 2008 Qualification problem ABit shifting in PythonPython - lookahead driver for a parsing chainA-Star Search with 3D UniverseBlackjack strategy simulationParallel processing simulationCounting lower vs non-lowercase tokens for tokenized text with several conditionsBirthday paradox simulation






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.




To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.




My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.



import sys


def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0


def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state


def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False


def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)


num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")



What are some ways to improve the performance of my code?










share|improve this question









New contributor



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






$endgroup$











  • $begingroup$
    Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
    $endgroup$
    – Carcigenicate
    1 hour ago

















4












$begingroup$


I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.




To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.




My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.



import sys


def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0


def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state


def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False


def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)


num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")



What are some ways to improve the performance of my code?










share|improve this question









New contributor



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






$endgroup$











  • $begingroup$
    Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
    $endgroup$
    – Carcigenicate
    1 hour ago













4












4








4





$begingroup$


I am working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.




To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.




My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.



import sys


def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0


def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state


def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False


def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)


num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")



What are some ways to improve the performance of my code?










share|improve this question









New contributor



Gansaikhan Shur 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 working with this problem (https://open.kattis.com/problems/whowantstoliveforever). As the problem states, my program has to determine if the universe lives or dies based on the input 0s and 1s.




To determine the next value of the i-th bit, look at the current
value of the bits at positions i−1 and i+1 (if they exist; otherwise
assume them to be 0). If you see exactly one 1, then the next value of
the i-th bit is 1, otherwise it is 0. All the bits change at once, so
the new values in the next state depend only on the values in the
previous state. We consider the universe dead if it contains only
zeros.




My code works but when submitting it to Kattis.com it says ""Time Limit Exceeded" > 3.00 s". Below is my code.



import sys


def get_bit(bits, i):
if 0 <= i < len(bits):
return int(bits[i])
else:
return 0


def get_new_state(old_state):
new_state = []
for index in range(len(old_state)):
if (get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 0) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 1):
new_state.append(0)
elif(get_bit(old_state, index-1) == 0 and get_bit(old_state, index+1) == 1) or (get_bit(old_state, index-1) == 1 and get_bit(old_state, index+1) == 0):
new_state.append(1)
return new_state


def is_dead(state):
if set(state).pop() == "1":
return False
elif set(state).pop() == 1:
return False
elif len(set(state)) == 1:
return True
else:
return False


def foresee_fate(state):
seen = []
while True:
if is_dead(state):
return False
if state in seen:
return True
seen.append(state)
state = get_new_state(state)


num_cases = int(sys.stdin.readline().strip())
for i in range(num_cases):
cur_state = []
case = sys.stdin.readline().strip()
for char in case:
cur_state.append(char)
print("LIVES" if foresee_fate(cur_state) else "DIES")



What are some ways to improve the performance of my code?







python python-3.x programming-challenge python-2.x time-limit-exceeded






share|improve this question









New contributor



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










share|improve this question









New contributor



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








share|improve this question




share|improve this question








edited 6 hours ago









200_success

134k21 gold badges169 silver badges440 bronze badges




134k21 gold badges169 silver badges440 bronze badges






New contributor



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








asked 8 hours ago









Gansaikhan ShurGansaikhan Shur

212 bronze badges




212 bronze badges




New contributor



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




New contributor




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













  • $begingroup$
    Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
    $endgroup$
    – Carcigenicate
    1 hour ago
















  • $begingroup$
    Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
    $endgroup$
    – Carcigenicate
    1 hour ago















$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
1 hour ago




$begingroup$
Just a note, this is basically a very simple Cellular Automata. If you want to try other stuff like this, looking into Conway's Game of Life and a Forest Fire simulator. They're very cool learning projects.
$endgroup$
– Carcigenicate
1 hour ago










2 Answers
2






active

oldest

votes


















4












$begingroup$

You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!



Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).



You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.






share|improve this answer









$endgroup$




















    1












    $begingroup$

    Testing for state repetition by if state in seen: is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen is a list, the search time is linear, making the total time complexity quadratic with the size of the period.



    Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.






    share|improve this answer









    $endgroup$















      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: "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
      );



      );






      Gansaikhan Shur 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%2f222928%2fbit-based-universe-simulation%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









      4












      $begingroup$

      You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!



      Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).



      You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.






      share|improve this answer









      $endgroup$

















        4












        $begingroup$

        You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!



        Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).



        You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.






        share|improve this answer









        $endgroup$















          4












          4








          4





          $begingroup$

          You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!



          Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).



          You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.






          share|improve this answer









          $endgroup$



          You are representing each state of the universe as a list of bits. However, CPUs are experts at handling sequences of bits — that's what an integer is!



          Given two bits, the way to find out whether exactly one of them is 1 is to use the ^ operator (XOR).



          You should be able to solve this challenge using bit-shifting (<< and >> operators) and ^.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 8 hours ago









          200_success200_success

          134k21 gold badges169 silver badges440 bronze badges




          134k21 gold badges169 silver badges440 bronze badges























              1












              $begingroup$

              Testing for state repetition by if state in seen: is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen is a list, the search time is linear, making the total time complexity quadratic with the size of the period.



              Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.






              share|improve this answer









              $endgroup$

















                1












                $begingroup$

                Testing for state repetition by if state in seen: is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen is a list, the search time is linear, making the total time complexity quadratic with the size of the period.



                Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.






                share|improve this answer









                $endgroup$















                  1












                  1








                  1





                  $begingroup$

                  Testing for state repetition by if state in seen: is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen is a list, the search time is linear, making the total time complexity quadratic with the size of the period.



                  Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.






                  share|improve this answer









                  $endgroup$



                  Testing for state repetition by if state in seen: is suboptimal. The number of states could grow exponentially with number of bits (and you are dealing with 200000 bits universe). Since seen is a list, the search time is linear, making the total time complexity quadratic with the size of the period.



                  Using a set instead of list would immediately improve the performance. However, I recommend to avoid huge collections whatsoever and investigate a Tortoise and Hare approach.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 7 hours ago









                  vnpvnp

                  41.9k2 gold badges35 silver badges107 bronze badges




                  41.9k2 gold badges35 silver badges107 bronze badges




















                      Gansaikhan Shur is a new contributor. Be nice, and check out our Code of Conduct.









                      draft saved

                      draft discarded


















                      Gansaikhan Shur is a new contributor. Be nice, and check out our Code of Conduct.












                      Gansaikhan Shur is a new contributor. Be nice, and check out our Code of Conduct.











                      Gansaikhan Shur 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%2f222928%2fbit-based-universe-simulation%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

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480