#!/usr/bin/env python # coding: utf-8 # #NumPy Exercise # 1. **German Lottery Ticket 6 of 49** # 1. Create a ndarray looking like a German Lottery Ticket 6 of 49 # 2. Randomly select a prediction of 6 numbers for the next draw # 2. **The Chessboard** # 1. Create a ndarray looking like a chessboard. 0 represents the white color and 1 the black color. # 3. **Random Walk** # 1. Please, simulate a random walk of 100 steps by flipping a coin using NumPy arrays and functions. # * Start at Position 0 # * Head means postion+1 and tail position-1 # # **Hint:** The position is basically the cumulated sum of movements! # 4. **2D-Random Walk** # 1. Please, simulate a 2D random walk of 100 steps in each direction by flipping a coin using only NumPy arrays and provided functions. # * First draw: Head means x+1 and tail x-1 # * Second draw: Head means y+1 and tail y-1. Start at Position (0,0) # # **Hint:** You can ignore the order of draws. For example: First 100 draws are x movements and second 100 draws are y movements # # In[1]: from IPython.display import HTML HTML('') # #Helper functions # Please, execute and scroll down. # In[2]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt import numpy as np import string import unittest class LotteryTicketTestCase(unittest.TestCase): def test_lottery_ticket(self): result = np.array([[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42], [43, 44, 45, 46, 47, 48, 49]]) self.assertTrue((result==create_ticket()).any()) def plot_lottery_ticket(lottery_ticket, prediction): fig, ax = plt.subplots() dim_x, dim_y = lottery_ticket.shape ax.set_xlim((0, dim_x)) ax.set_ylim((0, dim_y)) ax.tick_params(labeltop=False, labelright=False, labelleft=False, labelbottom=False, length=0) print ax.spines ax.spines['bottom'].set_color('red') ax.spines['top'].set_color('red') ax.spines['right'].set_color('red') ax.spines['left'].set_color('red') ax.grid(color='r', linestyle='-') index_x = np.arange(0.5, dim_x+0.5, 1.0) index_y = np.arange(0.5, dim_y+0.5, 1.0)[::-1] x_positions, y_positions = np.meshgrid(index_x, index_y) flatten_lottery_ticket = lottery_ticket.flatten() for entry, (x_position, y_position) in enumerate(zip(x_positions.flat, y_positions.flat)): number = flatten_lottery_ticket[entry] if number in prediction: ax.text(x_position, y_position, 'X', va='center', ha='center', fontdict={'fontsize': 20, 'color': 'blue'}) ax.text(x_position, y_position, number, va='center', ha='center', fontdict={'fontsize': 14, 'color': 'red'}) def plot_chess_board(chess_board): row_labels = np.fromiter(reversed(xrange(1, 9)), dtype='int') column_labels = np.fromiter(string.ascii_uppercase[:8], dtype='S1') plt.matshow(chess_board, cmap=plt.cm.binary) plt.xticks(xrange(8), column_labels) plt.yticks(xrange(8), row_labels) plt.tick_params(labeltop=True, labelright=True, labelleft=True, labelbottom=True, length=0) plt.show() def plot_random_walk(positions): plt.plot(np.arange(len(positions)), positions) plt.title('Simulated random walk by fliping a coin') plt.xlabel('step') plt.ylabel('position') plt.show() def plot_2d_random_walk(positions_x, positions_y): plt.plot(positions_x, positions_y) cumulated_movements = np.concatenate([positions_x, positions_y]) limit = np.abs(cumulated_movements.flat).max() plt.xlim((-limit, limit)) plt.ylim((-limit, limit)) plt.title('Simulated 2D random walk by fliping a coin') plt.xlabel('x position') plt.ylabel('y position') plt.show() # #German Lottery Ticket 6 of 49 # * Create a ndarray looking like a German Lottery Ticket 6 of 49 # * Randomly select a prediction of 6 numbers for the next draw # In[3]: import numpy as np def create_ticket(): """ Please, write your code here! """ ticket = np.arange(1,50).reshape(7,7) return ticket """ End of your code! """ test_suite = unittest.TestLoader().loadTestsFromTestCase(LotteryTicketTestCase) unittest.TextTestRunner(verbosity=2).run(test_suite) ticket = create_ticket() ticket # In[4]: """ Please, write your code here! """ prediction = np.random.choice(ticket.flat, size=6, replace=False) prediction # In[5]: #Just execute the code below plot_lottery_ticket(ticket, prediction) # #Chess Board # * Create a ndarray looking like a chessboard. 0 represents the white color and 1 the black color. # In[6]: """ Please, write your code here! """ chess_board = np.ones((8,8), dtype='int') chess_board[::2, ::2]=0 chess_board[1::2, 1::2]=0 chess_board # In[7]: #Just execute the code below plot_chess_board(chess_board) # #Random Walk # Please, simulate a random walk of 100 steps by flipping a coin using only NumPy arrays and provided functions. # * Start at Position 0 # * Head means postion+1 and tail position-1 # # Hint: The position is basically the cumulated sum of movements! # In[8]: """ Please, write your code here! """ number_of_steps = 100 movements = np.random.choice((-1, 1), size=number_of_steps) positions = np.append([0], movements.cumsum()) positions # In[9]: #Just execute the code below plot_random_walk(positions) # #2D Random Walk # Please, simulate a 2D random walk of 100 steps in each direction by flipping a coin using only NumPy arrays and provided functions. # * First draw: Head means x+1 and tail x-1 # * Second draw: Head means y+1 and tail y-1. Start at Position (0,0) # # Hint: You can ignore the order of draws. For example: First 100 draws are x movements and second 100 draws are y movements # In[10]: """ Please, write your code here! """ number_of_steps = 100 movements = np.random.choice((-1, 1), size=(2, number_of_steps)) cumulated_movements = movements.cumsum(axis=1) print cumulated_movements positions_x = np.append([0], cumulated_movements[:1, :]) positions_y = np.append([0], cumulated_movements[1:2, :]) positions_x, positions_y # In[11]: #Just execute the code below plot_2d_random_walk(positions_x, positions_y) # In[ ]: