Looping through, and updating, array values until a condition is met, or until 100 loops have been completed? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Loop through an array in JavaScriptHow to loop through array in jQuery?Loop through array, query each value until certain condition is metLoop through an array of strings in Bash?php how to loop through array until condition is met?Looping through function until condition is metJavascript loop until condition is metPython: Export multiple arrays using def and for loops for a range of values in a listloop until a certain condition is metHow to add and extend a new row in Python list?

Align column where each cell has two decimals with siunitx

PIC mathematical operations weird problem

What *exactly* is electrical current, voltage, and resistance?

Where did Arya get these scars?

All ASCII characters with a given bit count

"My boss was furious with me and I have been fired" vs. "My boss was furious with me and I was fired"

Is accepting an invalid credit card number a security issue?

Are all CP/M-80 implementations binary compatible?

Are these square matrices always diagonalisable?

Co-worker works way more than he should

Passing args from the bash script to the function in the script

France's Public Holidays' Puzzle

c++ diamond problem - How to call base method only once

Would reducing the reference voltage of an ADC have any effect on accuracy?

A Paper Record is What I Hamper

What is a 'Key' in computer science?

What was Apollo 13's "Little Jolt" after MECO?

Suing a Police Officer Instead of the Police Department

Trumpet valves, lengths, and pitch

Seek and ye shall find

Does Mathematica have an implementation of the Poisson Binomial Distribution?

What is this word supposed to be?

How to count in linear time worst-case?

As an international instructor, should I openly talk about my accent?



Looping through, and updating, array values until a condition is met, or until 100 loops have been completed?



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Loop through an array in JavaScriptHow to loop through array in jQuery?Loop through array, query each value until certain condition is metLoop through an array of strings in Bash?php how to loop through array until condition is met?Looping through function until condition is metJavascript loop until condition is metPython: Export multiple arrays using def and for loops for a range of values in a listloop until a certain condition is metHow to add and extend a new row in Python list?



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








0















Working in Python 3.7 on a Jupyter Notebook. I'm working on a project that will loop through a 2D Numpy Array ("board", if you will) check for all instances of the number 1. When it finds the number 1, I need it to check the values to the left, right, above it, and below it. If any of the values next to it is a 2, then that element itself becomes a 2.



After looping through the entire array, I will need the code to check if the board has changed at all from the start of that single loop. If it hasn't changed, then the simulation (the loop) should end. If it has changed, however, then the simulation should run again. However, the simulation should not loop for more than 100 turns.



Here is the set-up leading up to my problem-cell:



import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import numpy.random as rand
import time
from IPython.display import display, clear_output

def set_board(height=5,width=10,density=.75):
city = np.zeros((height,width),dtype='int64')
for i in range(height):
for j in range(width):
if rand.random() <= density:
city[i,j] = 1
return city

def VisMap(Map=set_board(),Colors=plt.cm.RdYlGn):
MapVis = plt.imshow(Map, Colors)
return MapVis

def onBoard(i, j, array):
if (i >= 0 and i < array.shape[0]-1
and j >= 0 and j < array.shape[1]-1):
return True
return False

def getNeighborValues(i, j, board):
neighborhood_indices = [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]
neighborhood_values = []
for index in neighborhood_indices:
if onBoard(index[0],index[1],board) == True:
neighborhood_values.append(board[index[0],index[1]])
pass
return neighborhood_values

def startRumor(board):
height, width = board.shape
height_quarters = int(height/4)
width_quarters = int(width/4)
starting_middle_height_index = height_quarters
ending_middle_height_index = 3*height_quarters
starting_middle_width_index = width_quarters
ending_middle_width_index = 3*width_quarters
found_starting_point = False
if np.all(board[starting_middle_height_index:ending_middle_height_index, starting_middle_width_index:ending_middle_width_index] == 0):
i = rand.randint(starting_middle_height_index, ending_middle_height_index)
j = rand.randint(starting_middle_width_index, ending_middle_width_index)
board[i,j] = 2
found_starting_point = True
while not found_starting_point:
i = rand.randint(starting_middle_height_index, ending_middle_height_index)
j = rand.randint(starting_middle_width_index, ending_middle_width_index)
if board[i,j] == 1:
found_starting_point = True
board[i, j] = 2


And here is the cell I'm having an issue with (specifically beginning with Step 5):



#Step 1: Initializing my board
StartingBoard = set_board(100,200,.4)

#Step 2: Visualizing my board
PreRumorVis = VisMap(StartingBoard)

#Step 3: Starting the rumor
startRumor(StartingBoard)

#Step 4: Visualizing the board after the rumor has started
PostRumorVis = VisMap(StartingBoard)

#Step 5: Create a copy of the city, and turn anything
#with a 2 around it into a 2, and keep doing that for 100
#loops. Or, if the city at the end of the loop is equal to
#the one from the beginning of the loop, break it. If there
#is some change, though, set the new city to now be the
#updated copy, and loop through again. (In this case, it
#probably should loop all 100 times).

City_Copy = StartingBoard.copy()
New_City = City_Copy.copy()
iterations = 0
for num in range(100):
for i in range(City_Copy.shape[0]):
for j in range(City_Copy.shape[1]):
if City_Copy[i,j] == 1:
if 2 in getNeighborValues(i,j, City_Copy):
New_City[i,j] = 2
else:
New_City[i,j] = 1
if np.array_equal(New_City, City_Copy) == True:
break
else:
City_Copy = New_City.copy()
iterations += 1

print("This rumor has been around for", iterations, "days.")
New_City


Edit: I found I was missing the copy function at first, thanks to one of the commenters. However, I'm still getting about 18 days, when it should be 100 (or very close). Wondering if I should be opening with a for loop or a while loop. The problem might be somewhere with setting the variables equal to copies.... It's a little confusing to me. It all makes sense logically, but there's a screw loose somewhere.










share|improve this question






























    0















    Working in Python 3.7 on a Jupyter Notebook. I'm working on a project that will loop through a 2D Numpy Array ("board", if you will) check for all instances of the number 1. When it finds the number 1, I need it to check the values to the left, right, above it, and below it. If any of the values next to it is a 2, then that element itself becomes a 2.



    After looping through the entire array, I will need the code to check if the board has changed at all from the start of that single loop. If it hasn't changed, then the simulation (the loop) should end. If it has changed, however, then the simulation should run again. However, the simulation should not loop for more than 100 turns.



    Here is the set-up leading up to my problem-cell:



    import numpy as np
    import matplotlib.pyplot as plt
    %matplotlib inline
    import numpy.random as rand
    import time
    from IPython.display import display, clear_output

    def set_board(height=5,width=10,density=.75):
    city = np.zeros((height,width),dtype='int64')
    for i in range(height):
    for j in range(width):
    if rand.random() <= density:
    city[i,j] = 1
    return city

    def VisMap(Map=set_board(),Colors=plt.cm.RdYlGn):
    MapVis = plt.imshow(Map, Colors)
    return MapVis

    def onBoard(i, j, array):
    if (i >= 0 and i < array.shape[0]-1
    and j >= 0 and j < array.shape[1]-1):
    return True
    return False

    def getNeighborValues(i, j, board):
    neighborhood_indices = [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]
    neighborhood_values = []
    for index in neighborhood_indices:
    if onBoard(index[0],index[1],board) == True:
    neighborhood_values.append(board[index[0],index[1]])
    pass
    return neighborhood_values

    def startRumor(board):
    height, width = board.shape
    height_quarters = int(height/4)
    width_quarters = int(width/4)
    starting_middle_height_index = height_quarters
    ending_middle_height_index = 3*height_quarters
    starting_middle_width_index = width_quarters
    ending_middle_width_index = 3*width_quarters
    found_starting_point = False
    if np.all(board[starting_middle_height_index:ending_middle_height_index, starting_middle_width_index:ending_middle_width_index] == 0):
    i = rand.randint(starting_middle_height_index, ending_middle_height_index)
    j = rand.randint(starting_middle_width_index, ending_middle_width_index)
    board[i,j] = 2
    found_starting_point = True
    while not found_starting_point:
    i = rand.randint(starting_middle_height_index, ending_middle_height_index)
    j = rand.randint(starting_middle_width_index, ending_middle_width_index)
    if board[i,j] == 1:
    found_starting_point = True
    board[i, j] = 2


    And here is the cell I'm having an issue with (specifically beginning with Step 5):



    #Step 1: Initializing my board
    StartingBoard = set_board(100,200,.4)

    #Step 2: Visualizing my board
    PreRumorVis = VisMap(StartingBoard)

    #Step 3: Starting the rumor
    startRumor(StartingBoard)

    #Step 4: Visualizing the board after the rumor has started
    PostRumorVis = VisMap(StartingBoard)

    #Step 5: Create a copy of the city, and turn anything
    #with a 2 around it into a 2, and keep doing that for 100
    #loops. Or, if the city at the end of the loop is equal to
    #the one from the beginning of the loop, break it. If there
    #is some change, though, set the new city to now be the
    #updated copy, and loop through again. (In this case, it
    #probably should loop all 100 times).

    City_Copy = StartingBoard.copy()
    New_City = City_Copy.copy()
    iterations = 0
    for num in range(100):
    for i in range(City_Copy.shape[0]):
    for j in range(City_Copy.shape[1]):
    if City_Copy[i,j] == 1:
    if 2 in getNeighborValues(i,j, City_Copy):
    New_City[i,j] = 2
    else:
    New_City[i,j] = 1
    if np.array_equal(New_City, City_Copy) == True:
    break
    else:
    City_Copy = New_City.copy()
    iterations += 1

    print("This rumor has been around for", iterations, "days.")
    New_City


    Edit: I found I was missing the copy function at first, thanks to one of the commenters. However, I'm still getting about 18 days, when it should be 100 (or very close). Wondering if I should be opening with a for loop or a while loop. The problem might be somewhere with setting the variables equal to copies.... It's a little confusing to me. It all makes sense logically, but there's a screw loose somewhere.










    share|improve this question


























      0












      0








      0








      Working in Python 3.7 on a Jupyter Notebook. I'm working on a project that will loop through a 2D Numpy Array ("board", if you will) check for all instances of the number 1. When it finds the number 1, I need it to check the values to the left, right, above it, and below it. If any of the values next to it is a 2, then that element itself becomes a 2.



      After looping through the entire array, I will need the code to check if the board has changed at all from the start of that single loop. If it hasn't changed, then the simulation (the loop) should end. If it has changed, however, then the simulation should run again. However, the simulation should not loop for more than 100 turns.



      Here is the set-up leading up to my problem-cell:



      import numpy as np
      import matplotlib.pyplot as plt
      %matplotlib inline
      import numpy.random as rand
      import time
      from IPython.display import display, clear_output

      def set_board(height=5,width=10,density=.75):
      city = np.zeros((height,width),dtype='int64')
      for i in range(height):
      for j in range(width):
      if rand.random() <= density:
      city[i,j] = 1
      return city

      def VisMap(Map=set_board(),Colors=plt.cm.RdYlGn):
      MapVis = plt.imshow(Map, Colors)
      return MapVis

      def onBoard(i, j, array):
      if (i >= 0 and i < array.shape[0]-1
      and j >= 0 and j < array.shape[1]-1):
      return True
      return False

      def getNeighborValues(i, j, board):
      neighborhood_indices = [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]
      neighborhood_values = []
      for index in neighborhood_indices:
      if onBoard(index[0],index[1],board) == True:
      neighborhood_values.append(board[index[0],index[1]])
      pass
      return neighborhood_values

      def startRumor(board):
      height, width = board.shape
      height_quarters = int(height/4)
      width_quarters = int(width/4)
      starting_middle_height_index = height_quarters
      ending_middle_height_index = 3*height_quarters
      starting_middle_width_index = width_quarters
      ending_middle_width_index = 3*width_quarters
      found_starting_point = False
      if np.all(board[starting_middle_height_index:ending_middle_height_index, starting_middle_width_index:ending_middle_width_index] == 0):
      i = rand.randint(starting_middle_height_index, ending_middle_height_index)
      j = rand.randint(starting_middle_width_index, ending_middle_width_index)
      board[i,j] = 2
      found_starting_point = True
      while not found_starting_point:
      i = rand.randint(starting_middle_height_index, ending_middle_height_index)
      j = rand.randint(starting_middle_width_index, ending_middle_width_index)
      if board[i,j] == 1:
      found_starting_point = True
      board[i, j] = 2


      And here is the cell I'm having an issue with (specifically beginning with Step 5):



      #Step 1: Initializing my board
      StartingBoard = set_board(100,200,.4)

      #Step 2: Visualizing my board
      PreRumorVis = VisMap(StartingBoard)

      #Step 3: Starting the rumor
      startRumor(StartingBoard)

      #Step 4: Visualizing the board after the rumor has started
      PostRumorVis = VisMap(StartingBoard)

      #Step 5: Create a copy of the city, and turn anything
      #with a 2 around it into a 2, and keep doing that for 100
      #loops. Or, if the city at the end of the loop is equal to
      #the one from the beginning of the loop, break it. If there
      #is some change, though, set the new city to now be the
      #updated copy, and loop through again. (In this case, it
      #probably should loop all 100 times).

      City_Copy = StartingBoard.copy()
      New_City = City_Copy.copy()
      iterations = 0
      for num in range(100):
      for i in range(City_Copy.shape[0]):
      for j in range(City_Copy.shape[1]):
      if City_Copy[i,j] == 1:
      if 2 in getNeighborValues(i,j, City_Copy):
      New_City[i,j] = 2
      else:
      New_City[i,j] = 1
      if np.array_equal(New_City, City_Copy) == True:
      break
      else:
      City_Copy = New_City.copy()
      iterations += 1

      print("This rumor has been around for", iterations, "days.")
      New_City


      Edit: I found I was missing the copy function at first, thanks to one of the commenters. However, I'm still getting about 18 days, when it should be 100 (or very close). Wondering if I should be opening with a for loop or a while loop. The problem might be somewhere with setting the variables equal to copies.... It's a little confusing to me. It all makes sense logically, but there's a screw loose somewhere.










      share|improve this question
















      Working in Python 3.7 on a Jupyter Notebook. I'm working on a project that will loop through a 2D Numpy Array ("board", if you will) check for all instances of the number 1. When it finds the number 1, I need it to check the values to the left, right, above it, and below it. If any of the values next to it is a 2, then that element itself becomes a 2.



      After looping through the entire array, I will need the code to check if the board has changed at all from the start of that single loop. If it hasn't changed, then the simulation (the loop) should end. If it has changed, however, then the simulation should run again. However, the simulation should not loop for more than 100 turns.



      Here is the set-up leading up to my problem-cell:



      import numpy as np
      import matplotlib.pyplot as plt
      %matplotlib inline
      import numpy.random as rand
      import time
      from IPython.display import display, clear_output

      def set_board(height=5,width=10,density=.75):
      city = np.zeros((height,width),dtype='int64')
      for i in range(height):
      for j in range(width):
      if rand.random() <= density:
      city[i,j] = 1
      return city

      def VisMap(Map=set_board(),Colors=plt.cm.RdYlGn):
      MapVis = plt.imshow(Map, Colors)
      return MapVis

      def onBoard(i, j, array):
      if (i >= 0 and i < array.shape[0]-1
      and j >= 0 and j < array.shape[1]-1):
      return True
      return False

      def getNeighborValues(i, j, board):
      neighborhood_indices = [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]
      neighborhood_values = []
      for index in neighborhood_indices:
      if onBoard(index[0],index[1],board) == True:
      neighborhood_values.append(board[index[0],index[1]])
      pass
      return neighborhood_values

      def startRumor(board):
      height, width = board.shape
      height_quarters = int(height/4)
      width_quarters = int(width/4)
      starting_middle_height_index = height_quarters
      ending_middle_height_index = 3*height_quarters
      starting_middle_width_index = width_quarters
      ending_middle_width_index = 3*width_quarters
      found_starting_point = False
      if np.all(board[starting_middle_height_index:ending_middle_height_index, starting_middle_width_index:ending_middle_width_index] == 0):
      i = rand.randint(starting_middle_height_index, ending_middle_height_index)
      j = rand.randint(starting_middle_width_index, ending_middle_width_index)
      board[i,j] = 2
      found_starting_point = True
      while not found_starting_point:
      i = rand.randint(starting_middle_height_index, ending_middle_height_index)
      j = rand.randint(starting_middle_width_index, ending_middle_width_index)
      if board[i,j] == 1:
      found_starting_point = True
      board[i, j] = 2


      And here is the cell I'm having an issue with (specifically beginning with Step 5):



      #Step 1: Initializing my board
      StartingBoard = set_board(100,200,.4)

      #Step 2: Visualizing my board
      PreRumorVis = VisMap(StartingBoard)

      #Step 3: Starting the rumor
      startRumor(StartingBoard)

      #Step 4: Visualizing the board after the rumor has started
      PostRumorVis = VisMap(StartingBoard)

      #Step 5: Create a copy of the city, and turn anything
      #with a 2 around it into a 2, and keep doing that for 100
      #loops. Or, if the city at the end of the loop is equal to
      #the one from the beginning of the loop, break it. If there
      #is some change, though, set the new city to now be the
      #updated copy, and loop through again. (In this case, it
      #probably should loop all 100 times).

      City_Copy = StartingBoard.copy()
      New_City = City_Copy.copy()
      iterations = 0
      for num in range(100):
      for i in range(City_Copy.shape[0]):
      for j in range(City_Copy.shape[1]):
      if City_Copy[i,j] == 1:
      if 2 in getNeighborValues(i,j, City_Copy):
      New_City[i,j] = 2
      else:
      New_City[i,j] = 1
      if np.array_equal(New_City, City_Copy) == True:
      break
      else:
      City_Copy = New_City.copy()
      iterations += 1

      print("This rumor has been around for", iterations, "days.")
      New_City


      Edit: I found I was missing the copy function at first, thanks to one of the commenters. However, I'm still getting about 18 days, when it should be 100 (or very close). Wondering if I should be opening with a for loop or a while loop. The problem might be somewhere with setting the variables equal to copies.... It's a little confusing to me. It all makes sense logically, but there's a screw loose somewhere.







      python arrays for-loop while-loop agent-based-modeling






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 at 10:13







      Cornel Westside

















      asked Mar 9 at 6:21









      Cornel WestsideCornel Westside

      437




      437






















          1 Answer
          1






          active

          oldest

          votes


















          1














          In Python, Assignment statements do not copy objects, instead they create bindings between a target and an object. When we use = operator the user thinks that this creates a new object, Well, it doesn’t. It only creates a new variable that shares the reference of the original object.



          Example:-



          >>> a=np.array([[0,1],[0,2]])
          >>> b=a
          >>> np.array_equal(b,a)
          True
          >>> b[0][1]=1
          >>> b
          array([[0, 1],
          [0, 2]])
          >>> a
          array([[0, 1],
          [0, 2]])
          >>> np.array_equal(b,a)
          True


          This happens due to the fact of shallow copying. Shallow copying is only limited to compound objects such as lists. To avoid this go for deep copying.



          >>> import copy
          >>> a=np.array([[0,1],[0,2]])
          >>> b=copy.deepcopy(a)
          >>> np.array_equal(b,a)
          True
          >>>b[0][0]=1
          >>> np.array_equal(b,a)
          False


          Solution:-



          Since you have assigned New_City=City_Copy whatever changes in New_City is done it is reflected in City_Copy. Thus they are both equal and the loop breaks the first time itself.So loop is not incremented. Try to use deepcopy to solve this.



          Reference:-



          1. Shallow copy vs Deep
            copy





          share|improve this answer

























          • Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

            – Cornel Westside
            Mar 9 at 9:48











          • @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

            – Justice_Lords
            Mar 9 at 12:33











          • It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

            – Cornel Westside
            Mar 10 at 0:03











          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%2f55074628%2flooping-through-and-updating-array-values-until-a-condition-is-met-or-until-1%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














          In Python, Assignment statements do not copy objects, instead they create bindings between a target and an object. When we use = operator the user thinks that this creates a new object, Well, it doesn’t. It only creates a new variable that shares the reference of the original object.



          Example:-



          >>> a=np.array([[0,1],[0,2]])
          >>> b=a
          >>> np.array_equal(b,a)
          True
          >>> b[0][1]=1
          >>> b
          array([[0, 1],
          [0, 2]])
          >>> a
          array([[0, 1],
          [0, 2]])
          >>> np.array_equal(b,a)
          True


          This happens due to the fact of shallow copying. Shallow copying is only limited to compound objects such as lists. To avoid this go for deep copying.



          >>> import copy
          >>> a=np.array([[0,1],[0,2]])
          >>> b=copy.deepcopy(a)
          >>> np.array_equal(b,a)
          True
          >>>b[0][0]=1
          >>> np.array_equal(b,a)
          False


          Solution:-



          Since you have assigned New_City=City_Copy whatever changes in New_City is done it is reflected in City_Copy. Thus they are both equal and the loop breaks the first time itself.So loop is not incremented. Try to use deepcopy to solve this.



          Reference:-



          1. Shallow copy vs Deep
            copy





          share|improve this answer

























          • Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

            – Cornel Westside
            Mar 9 at 9:48











          • @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

            – Justice_Lords
            Mar 9 at 12:33











          • It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

            – Cornel Westside
            Mar 10 at 0:03















          1














          In Python, Assignment statements do not copy objects, instead they create bindings between a target and an object. When we use = operator the user thinks that this creates a new object, Well, it doesn’t. It only creates a new variable that shares the reference of the original object.



          Example:-



          >>> a=np.array([[0,1],[0,2]])
          >>> b=a
          >>> np.array_equal(b,a)
          True
          >>> b[0][1]=1
          >>> b
          array([[0, 1],
          [0, 2]])
          >>> a
          array([[0, 1],
          [0, 2]])
          >>> np.array_equal(b,a)
          True


          This happens due to the fact of shallow copying. Shallow copying is only limited to compound objects such as lists. To avoid this go for deep copying.



          >>> import copy
          >>> a=np.array([[0,1],[0,2]])
          >>> b=copy.deepcopy(a)
          >>> np.array_equal(b,a)
          True
          >>>b[0][0]=1
          >>> np.array_equal(b,a)
          False


          Solution:-



          Since you have assigned New_City=City_Copy whatever changes in New_City is done it is reflected in City_Copy. Thus they are both equal and the loop breaks the first time itself.So loop is not incremented. Try to use deepcopy to solve this.



          Reference:-



          1. Shallow copy vs Deep
            copy





          share|improve this answer

























          • Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

            – Cornel Westside
            Mar 9 at 9:48











          • @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

            – Justice_Lords
            Mar 9 at 12:33











          • It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

            – Cornel Westside
            Mar 10 at 0:03













          1












          1








          1







          In Python, Assignment statements do not copy objects, instead they create bindings between a target and an object. When we use = operator the user thinks that this creates a new object, Well, it doesn’t. It only creates a new variable that shares the reference of the original object.



          Example:-



          >>> a=np.array([[0,1],[0,2]])
          >>> b=a
          >>> np.array_equal(b,a)
          True
          >>> b[0][1]=1
          >>> b
          array([[0, 1],
          [0, 2]])
          >>> a
          array([[0, 1],
          [0, 2]])
          >>> np.array_equal(b,a)
          True


          This happens due to the fact of shallow copying. Shallow copying is only limited to compound objects such as lists. To avoid this go for deep copying.



          >>> import copy
          >>> a=np.array([[0,1],[0,2]])
          >>> b=copy.deepcopy(a)
          >>> np.array_equal(b,a)
          True
          >>>b[0][0]=1
          >>> np.array_equal(b,a)
          False


          Solution:-



          Since you have assigned New_City=City_Copy whatever changes in New_City is done it is reflected in City_Copy. Thus they are both equal and the loop breaks the first time itself.So loop is not incremented. Try to use deepcopy to solve this.



          Reference:-



          1. Shallow copy vs Deep
            copy





          share|improve this answer















          In Python, Assignment statements do not copy objects, instead they create bindings between a target and an object. When we use = operator the user thinks that this creates a new object, Well, it doesn’t. It only creates a new variable that shares the reference of the original object.



          Example:-



          >>> a=np.array([[0,1],[0,2]])
          >>> b=a
          >>> np.array_equal(b,a)
          True
          >>> b[0][1]=1
          >>> b
          array([[0, 1],
          [0, 2]])
          >>> a
          array([[0, 1],
          [0, 2]])
          >>> np.array_equal(b,a)
          True


          This happens due to the fact of shallow copying. Shallow copying is only limited to compound objects such as lists. To avoid this go for deep copying.



          >>> import copy
          >>> a=np.array([[0,1],[0,2]])
          >>> b=copy.deepcopy(a)
          >>> np.array_equal(b,a)
          True
          >>>b[0][0]=1
          >>> np.array_equal(b,a)
          False


          Solution:-



          Since you have assigned New_City=City_Copy whatever changes in New_City is done it is reflected in City_Copy. Thus they are both equal and the loop breaks the first time itself.So loop is not incremented. Try to use deepcopy to solve this.



          Reference:-



          1. Shallow copy vs Deep
            copy






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 9 at 7:21

























          answered Mar 9 at 7:08









          Justice_LordsJustice_Lords

          732211




          732211












          • Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

            – Cornel Westside
            Mar 9 at 9:48











          • @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

            – Justice_Lords
            Mar 9 at 12:33











          • It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

            – Cornel Westside
            Mar 10 at 0:03

















          • Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

            – Cornel Westside
            Mar 9 at 9:48











          • @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

            – Justice_Lords
            Mar 9 at 12:33











          • It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

            – Cornel Westside
            Mar 10 at 0:03
















          Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

          – Cornel Westside
          Mar 9 at 9:48





          Good point. Was missing the copy function. My professor said to stay away from deepcopy for now. That didn't seem to be the issue. Now I'm using copy, and getting about 18 days when I run it. I've edited my code above, if you can take a look.

          – Cornel Westside
          Mar 9 at 9:48













          @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

          – Justice_Lords
          Mar 9 at 12:33





          @CornelWestside Actually the rumour entirely depends on the number of "1"s which in turn depends on the density given. If the density the rumour spreads quickly as there more "1"s are scattered around so the rumour ends quickly. If the density is less the rumour cant spread and it dies out quickly. I have checked your program it works fine. BTW, I checked it for (10,20,.99).

          – Justice_Lords
          Mar 9 at 12:33













          It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

          – Cornel Westside
          Mar 10 at 0:03





          It definitely seems logical... I'll ask my professor if it's returning the correct answer. Thanks so much!

          – Cornel Westside
          Mar 10 at 0:03



















          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%2f55074628%2flooping-through-and-updating-array-values-until-a-condition-is-met-or-until-1%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

          1928 у кіно

          Захаров Федір Захарович

          Ель Греко