0

I created a while loop that's random each time I run it and I need to save all the values of x and y as arrays. I don't know how to do this because their values are different each time I run the code. This is what I have so far

import numpy as np
x = 5                                 
y = 5                               
while True:
    a = np.random.rand(1)              
    print x
    if a < .5:  
        x = x + 1                      
        y = y - 1             
        print x
        print y
    if a > .5:                          
        y = y + 1
        x = x - 1              
        print x
        print y
    if x == 0:                        
        print x
        break                           
    if y == 0:                        
        print y  
        break   
2
  • 4
    Whats wrong with initialing an empty list and using list.append() method? Commented Jul 14, 2015 at 17:20
  • What are you trying to accomplish? What do you want to happen if a == 0.5? Commented Jul 14, 2015 at 17:38

2 Answers 2

2

You can create an empty list for each one and append new values as you go.

For example:

import numpy as np
x = 5   
xs = []                              
y = 5   
ys = []                            
while True:
    a = np.random.rand(1)              
    print x
    if a < .5:  
        x = x + 1                      
        y = y - 1             
        print x, y
    if a > .5:                          
        y = y + 1
        x = x - 1              
        print x, y

    xs.append(x)
    ys.append(y)

    if x == 0:                        
        print 'y won.'
        break                           
    if y == 0:                        
        print 'x won.'
        break   

print 'xs', xs
print 'ys', ys

Sample output:

6 4
7 3
6 4
5 5
4 6
5 5
6 4
5 5
4 6
3 7
4 6
3 7
2 8
1 9
0 10
y won.
xs [6, 7, 6, 5, 4, 5, 6, 5, 4, 3, 4, 3, 2, 1, 0]
ys [4, 3, 4, 5, 6, 5, 4, 5, 6, 7, 6, 7, 8, 9, 10]
Sign up to request clarification or add additional context in comments.

Comments

0

How about this:

import numpy as np
x = 5                                 
y = 5
x_results = []
y_results = []                             
while True:
    a = np.random.rand(1)              
    x_results.append(x)
    if a < .5:  
        x += 1                      
        y -= 1
        x_results.append(x)             
        y_results.append(y)
    elif a > .5:                          
        y += 1
        x -= 1              
        x_results.append(x)
        y_results.append(y)
    if x == 0:                        
        x_results.append(x)
        break                           
    if y == 0:                        
        y_results.append(y) 
        break   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.