text: 
  import gym
  import seaborn as sns
  import numpy as np
  import pandas as pd
  
  def computeAction(state, weights):
      p = np.matmul(weights, state)
      if p < 0:
          return 0
      else:
          return 1
  
  
  env = gym.make('CartPole-v0')
  
  #results = pd.DataFrame({'iteration': [], 'totalreward': [], 'steps': [],
  #                   'w1': [], 'w2': [], 'w3': [], 'w4': []})
  results = list()
  
  ############################################
  # Initial trainings for best weights
  ############################################
  best_reward = 0
  episodes = 20
  iterations = 1000
  for iteration in range(iterations):
      observation = env.reset()
      weights = 2 * np.random.rand(4) - 1.0
      totalReward = 0
      rewards = list()
      for episode in range(episodes):
          totalReward = 0
          observation = env.reset()
          done = False
          steps = 0
          while not done:
              action = computeAction(observation, weights)
              observation, reward, done, info = env.step(action)
              totalReward = totalReward + reward
              steps = steps + 1
              rewards.append(totalReward)
  
      results.append({'iteration':iteration, 'totalreward':totalReward, 'avgreward':sum(rewards)/len(rewards), 
                      'steps':steps, 
                      'w1': weights[0],'w2': weights[1],'w3': weights[2],'w4': weights[3]})
  
      if totalReward > best_reward:
          best_reward = totalReward
          best_weights = weights
  
  ############################################
  # Output initial results
  ############################################
  output = pd.DataFrame(results)
  output = output.sort_values(by='avgreward', ascending=False)
  #sns.distplot(results)
  #print("Average number of steps during experiment {}".format(sum(results) / len(results)))
  display(output)
  
  
  ############################################
  # Use best weights for 1000 episodes
  ############################################
  print('1000 episodes run for weights')
  print(best_weights)
  rewards = list()
  for episode in range(1000):
      totalReward = 0
      observation = env.reset()
      done = False
      steps = 0
      while not done:
          action = computeAction(observation, best_weights)
          observation, reward, done, info = env.step(action)
          totalReward = totalReward + reward
          steps = steps + 1
          rewards.append(totalReward)
  
  print('Average reward {}'.format(sum(rewards) / len(rewards)))
  env.close()