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

Data normalization before or after train-test split?

Why do Klingons use cloaking devices?

In the Seventh Seal why does Death let the chess game happen?

Advice for making/keeping shredded chicken moist?

Convenience stores in India

Why do we need a bootloader separate than our application program in MCU's?

Who pays for increased security measures on flights to the US?

Milky way is orbiting around?

My players like to search everything. What do they find?

Could you sell yourself into slavery in the USA?

Did Snape really give Umbridge a fake Veritaserum potion that Harry later pretended to drink?

What units are kpts?

How to travel between two stationary worlds in the least amount of time? (time dilation)

Can a Time Lord survive with just one heart?

Can 4 Joy cons connect to the same Switch?

What is the name of the technique when an element is repeated at different scales?

Taking advantage when the HR forgets to communicate the rules

Did Stalin kill all Soviet officers involved in the Winter War?

Should I hide my travel history to the UK when I apply for an Australian visa?

How might boat designs change in order to allow them to be pulled by dragons?

How can one synthesise a conjugated alkyne chain?

Short SF story , future people who feed on sunlight try solid food

Interview Question - Card betting

How frequently do Russian people still refer to others by their patronymic (отчество)?



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;








5












$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











$endgroup$







  • 1




    $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
    Jun 25 at 21:00

















5












$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











$endgroup$







  • 1




    $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
    Jun 25 at 21:00













5












5








5





$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











$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















share|improve this question













share|improve this question




share|improve this question








edited Jun 25 at 16:05









200_success

134k21 gold badges170 silver badges440 bronze badges




134k21 gold badges170 silver badges440 bronze badges










asked Jun 25 at 13:53









Gansaikhan ShurGansaikhan Shur

262 bronze badges




262 bronze badges







  • 1




    $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
    Jun 25 at 21:00












  • 1




    $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
    Jun 25 at 21:00







1




1




$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
Jun 25 at 21:00




$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
Jun 25 at 21:00










2 Answers
2






active

oldest

votes


















6












$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$




















    3












    $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
      );



      );













      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









      6












      $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$

















        6












        $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$















          6












          6








          6





          $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 Jun 25 at 14:09









          200_success200_success

          134k21 gold badges170 silver badges440 bronze badges




          134k21 gold badges170 silver badges440 bronze badges























              3












              $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$

















                3












                $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$















                  3












                  3








                  3





                  $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 Jun 25 at 15:27









                  vnpvnp

                  42.2k2 gold badges35 silver badges109 bronze badges




                  42.2k2 gold badges35 silver badges109 bronze badges



























                      draft saved

                      draft discarded
















































                      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

                      Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form