Abhishek Sharma
Abhishek Sharma

Reputation: 11

I am getting this error again and again (TypeError: can't multiply sequence by non-int of type 'list')

Walk as you see in the function def i am gettind an error of

"can't multiply sequence by non-int of type 'list'".

I am struggling to resolve it please somebody tell me its my assignment.

   import matplotlib.pyplot as plt 
   import random
    
    class RandomWalk():
        
        def __init__(self, num_points = 5000):
            #Initialize attributes of a walk
            self.num_points = num_points
            # walk start at (0, 0)
            self.x_value = [0]
            self.y_value = [0]
            
        def walk(self):
            while len(self.x_value) < self.num_points:            
                # Decide which direction to go and how far to go in that direction.
                x_direction = random.choices([1, -1])
                x_distance = random.choices([0, 1, 2, 3, 4])
                x_step = x_direction * x_distance # here i am getting this error I'm trying to resolve but not able to fix some body help me...
                y_direction = random.choices([1, -1])
                y_distance = random.choices([0, 1, 2, 3, 4])
                y_step = y_direction * y_distance
    
                # Reject moves that go nowhere.
                if x_step == 0 and y_step == 0:
                    continue
    
                # Calculate the next x and y values.
                next_x = self.x_value[-1] + x_step
                next_y = self.y_value[-1] + y_step
    
                self.x_value.append(next_x)
                self.y_value.append(next_y)
                
    
    # Make a random walk, and plot the points.
    rw = RandomWalk()
    rw.walk()
    
    plt.scatter(rw.x_value, rw.y_value, s = 15)
    plt.show() 

Upvotes: 1

Views: 54

Answers (1)

Rabbid76
Rabbid76

Reputation: 211135

The error is caused, because x_direction and x_distance are lists. You have to use random.choice instead of random.choices (focus on the s at the end):

x_direction = random.choice([1, -1])
x_distance = random.choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance

While random.choice returns 1 element of the list, random.choices returns a list of k elements, where k is an optional argument. See random

Upvotes: 1

Related Questions