#petal power - data analysis with pandas
import codecademylib
import pandas as pd
inventory = pd.read_csv('inventory.csv')
staten_island = inventory.head(10)
product_request = staten_island.product_description
print(product_request)
seed_request = inventory[(inventory.location == 'Brooklyn') & (inventory.product_type == 'seeds')]
in_stock_lambda = lambda x: True if x > 0 else False
inventory['in_stock'] = inventory.quantity.apply(in_stock_lambda)
print(inventory.in_stock)
inventory['total_value'] = inventory.price * inventory.quantity
print(inventory.total_value)
combine_lambda = lambda row: \
'{} - {}'.format(row.product_type,
row.product_description)
inventory['full_description'] = inventory.apply(combine_lambda, axis=1)
print(inventory)
import codecademylib
import pandas as pd
inventory = pd.read_csv('inventory.csv')
staten_island = inventory.head(10)
product_request = staten_island.product_description
print(product_request)
seed_request = inventory[(inventory.location == 'Brooklyn') & (inventory.product_type == 'seeds')]
in_stock_lambda = lambda x: True if x > 0 else False
inventory['in_stock'] = inventory.quantity.apply(in_stock_lambda)
print(inventory.in_stock)
inventory['total_value'] = inventory.price * inventory.quantity
print(inventory.total_value)
combine_lambda = lambda row: \
'{} - {}'.format(row.product_type,
row.product_description)
inventory['full_description'] = inventory.apply(combine_lambda, axis=1)
print(inventory)
#statistics with numpy - Crunchie Munchies' calorie statistics
import codecademylib
import numpy as np
calorie_stats = np.genfromtxt('cereal.csv', delimiter=',')
average_calories = np.mean(calorie_stats)
calorie_stats_sorted = np.sort(calorie_stats)
median_calories = np.median(calorie_stats)
nth_percentile = np.percentile(calorie_stats, 25)
more_calories = np.mean(calorie_stats > 60)
calorie_std = np.std(calorie_stats)
print(calorie_std)
import codecademylib
import numpy as np
calorie_stats = np.genfromtxt('cereal.csv', delimiter=',')
average_calories = np.mean(calorie_stats)
calorie_stats_sorted = np.sort(calorie_stats)
median_calories = np.median(calorie_stats)
nth_percentile = np.percentile(calorie_stats, 25)
more_calories = np.mean(calorie_stats > 60)
calorie_std = np.std(calorie_stats)
print(calorie_std)
#election results - statistical distributions with numpy
import codecademylib
import numpy as np
import matplotlib
survey_responses = ['Ceballos', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Ceballos', 'Ceballos', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Ceballos']
total_ceballos = sum([1 for n in survey_responses if n == 'Ceballos'])
print(total_ceballos)
percentage_ceballos = 100 * total_ceballos/len(survey_responses)
print(percentage_ceballos)
possible_surveys = np.random.binomial(10000,0.54,10000) / 10000.
print(possible_surveys)
plt.hist(possible_surveys, range=(0,1), bins=20)
import codecademylib
import numpy as np
import matplotlib
survey_responses = ['Ceballos', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Ceballos', 'Ceballos', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Ceballos',
'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Ceballos', 'Ceballos', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Kerrigan', 'Ceballos']
total_ceballos = sum([1 for n in survey_responses if n == 'Ceballos'])
print(total_ceballos)
percentage_ceballos = 100 * total_ceballos/len(survey_responses)
print(percentage_ceballos)
possible_surveys = np.random.binomial(10000,0.54,10000) / 10000.
print(possible_surveys)
plt.hist(possible_surveys, range=(0,1), bins=20)
#hypothesis testing with scipy
import familiar
from scipy.stats import ttest_1samp
from scipy.stats import ttest_ind
from scipy.stats import chi2_contingency
vein_pack_lifespans = familiar.lifespans(package='vein')
tstat, vein_pack_test = ttest_1samp(vein_pack_lifespans, 71)
print(vein_pack_test)
print("The Vein Pack Is Probably Good For You Somehow!")
artery_pack_lifespans = familiar.lifespans(package='artery')
tstat, package_comparison_results = ttest_ind(vein_pack_lifespans, artery_pack_lifespans)
print(package_comparison_results)
print("The Artery Package Is Also A Great Product")
iron_contingency_table = familiar.iron_counts_for_package()
chi2, iron_pvalue, dof, expected = chi2_contingency(iron_contingency_table)
print(iron_pvalue)
def lifespans(package):
if package == 'vein':
return [76.937674313716172, 75.993359130146814, 74.798150123540481, 74.502021471585508, 77.48888897587436, 72.142565731540429, 75.993031671911822, 76.341550480952279, 77.484755629998816, 76.532101480086695, 76.255089552764176, 77.58398316566651, 77.047370349622938, 72.874751745947108, 77.435045470028442, 77.492341410789194, 78.326720468799522, 73.343702468870674, 79.969157652363464, 74.838005833003251]
elif package == 'artery':
return [76.335370084268348, 76.923082315590619, 75.952441644877794, 74.544983480720305, 76.404504275447195, 73.079248886365761, 77.023544610529925, 74.117420420068797, 77.38650656208344, 73.044765837189928, 74.963118508661665, 73.319543019334859, 75.857401376968625, 76.152653513512547, 73.355102863226705, 73.902212564587884, 73.771211950924751, 68.314898302855781, 74.639757177753282, 78.385477308439789]
else:
print "Package not found. Possible values 'vein' or 'artery'"
return None
def iron_counts_for_package():
"""
vein | artery
----+------------+------------
low|200 * 0.7 |145 * 0.2
normal|200 * 0.2 |145 * 0.2
high|200 * 0.1 |145 * 0.6
"""
return [[140, 29],
[40, 87],
[20, 29]]
import familiar
from scipy.stats import ttest_1samp
from scipy.stats import ttest_ind
from scipy.stats import chi2_contingency
vein_pack_lifespans = familiar.lifespans(package='vein')
tstat, vein_pack_test = ttest_1samp(vein_pack_lifespans, 71)
print(vein_pack_test)
print("The Vein Pack Is Probably Good For You Somehow!")
artery_pack_lifespans = familiar.lifespans(package='artery')
tstat, package_comparison_results = ttest_ind(vein_pack_lifespans, artery_pack_lifespans)
print(package_comparison_results)
print("The Artery Package Is Also A Great Product")
iron_contingency_table = familiar.iron_counts_for_package()
chi2, iron_pvalue, dof, expected = chi2_contingency(iron_contingency_table)
print(iron_pvalue)
def lifespans(package):
if package == 'vein':
return [76.937674313716172, 75.993359130146814, 74.798150123540481, 74.502021471585508, 77.48888897587436, 72.142565731540429, 75.993031671911822, 76.341550480952279, 77.484755629998816, 76.532101480086695, 76.255089552764176, 77.58398316566651, 77.047370349622938, 72.874751745947108, 77.435045470028442, 77.492341410789194, 78.326720468799522, 73.343702468870674, 79.969157652363464, 74.838005833003251]
elif package == 'artery':
return [76.335370084268348, 76.923082315590619, 75.952441644877794, 74.544983480720305, 76.404504275447195, 73.079248886365761, 77.023544610529925, 74.117420420068797, 77.38650656208344, 73.044765837189928, 74.963118508661665, 73.319543019334859, 75.857401376968625, 76.152653513512547, 73.355102863226705, 73.902212564587884, 73.771211950924751, 68.314898302855781, 74.639757177753282, 78.385477308439789]
else:
print "Package not found. Possible values 'vein' or 'artery'"
return None
def iron_counts_for_package():
"""
vein | artery
----+------------+------------
low|200 * 0.7 |145 * 0.2
normal|200 * 0.2 |145 * 0.2
high|200 * 0.1 |145 * 0.6
"""
return [[140, 29],
[40, 87],
[20, 29]]
#supervised learning - honey production - plot and predict honey bees and honey production
import codecademylib3_seaborn
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv")
prod_per_year = df.groupby('year').totalprod.mean().reset_index()
X = prod_per_year["year"]
X = X.values.reshape(-1,1)
y = prod_per_year["totalprod"]
plt.scatter(X, y)
plt.show()
regr = linear_model.LinearRegression()
regr.fit(X, y)
print(regr.coef_[0])
print(regr.intercept_)
y_predict = regr.predict(X)
plt.plot(X, y_predict)
plt.show()
X_future = np.array(range(2013,2051))
X_future = X_future.reshape(-1,1)
future_predict = regr.predict(X_future)
plt.plot(X_future, future_predict)
plt.show()
import codecademylib3_seaborn
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
df = pd.read_csv("https://s3.amazonaws.com/codecademy-content/programs/data-science-path/linear_regression/honeyproduction.csv")
prod_per_year = df.groupby('year').totalprod.mean().reset_index()
X = prod_per_year["year"]
X = X.values.reshape(-1,1)
y = prod_per_year["totalprod"]
plt.scatter(X, y)
plt.show()
regr = linear_model.LinearRegression()
regr.fit(X, y)
print(regr.coef_[0])
print(regr.intercept_)
y_predict = regr.predict(X)
plt.plot(X, y_predict)
plt.show()
X_future = np.array(range(2013,2051))
X_future = X_future.reshape(-1,1)
future_predict = regr.predict(X_future)
plt.plot(X_future, future_predict)
plt.show()
#connect four AI supervised learning
from connect_four import *
def two_ai_game():
my_board = make_board()
while not game_is_over(my_board):
#The "X" player finds their best move.
result = minimax(my_board, True, 4, -float("Inf"), float("Inf"), my_evaluate_board)
print( "X Turn\nX selected ", result[1])
print(result[1])
select_space(my_board, result[1], "X")
print_board(my_board)
if not game_is_over(my_board):
#The "O" player finds their best move
result = minimax(my_board, False, 4, -float("Inf"), float("Inf"), codecademy_evaluate_board)
print( "O Turn\nO selected ", result[1])
print(result[1])
select_space(my_board, result[1], "O")
print_board(my_board)
if has_won(my_board, "X"):
print("X won!")
elif has_won(my_board, "O"):
print("O won!")
else:
print("It's a tie!")
def random_eval(board):
return random.randint(-100,100)
def my_evaluate_board(board):
if has_won(board, "X"):
return float("Inf")
elif has_won(board, "O"):
return -float("Inf")
x_two_streak = 0
o_two_streak = 0
for col in range(len(board)):
for row in range(len(board) -1):
if board[col][row] == "X" and board[col - 1][row] == "X":
x_two_streak += 1
if board[col][row] == "O" and board[col - 1][row] == "O":
o_two_streak += 1
return x_two_streak - o_two_streak
new_board = make_board()
select_space(new_board, 1, "X")
select_space(new_board, 2, "X")
select_space(new_board, 5, "X")
select_space(new_board, 7, "X")
select_space(new_board, 4, "O")
select_space(new_board, 7, "O")
select_space(new_board, 7, "O")
select_space(new_board, 7, "O")
print_board(new_board)
print(my_evaluate_board(new_board))
two_ai_game()
#connect_four.py
from copy import deepcopy
import random
random.seed(108)
def print_board(board):
print()
print(' ', end='')
for x in range(1, len(board) + 1):
print(' %s ' % x, end='')
print()
print('+---+' + ('---+' * (len(board) - 1)))
for y in range(len(board[0])):
print('| |' + (' |' * (len(board) - 1)))
print('|', end='')
for x in range(len(board)):
print(' %s |' % board[x][y], end='')
print()
print('| |' + (' |' * (len(board) - 1)))
print('+---+' + ('---+' * (len(board) - 1)))
def select_space(board, column, player):
if not move_is_valid(board, column):
return False
if player != "X" and player != "O":
return False
for y in range(len(board[0])-1, -1, -1):
if board[column-1][y] == ' ':
board[column-1][y] = player
return True
return False
def board_is_full(board):
for x in range(len(board)):
for y in range(len(board[0])):
if board[x][y] == ' ':
return False
return True
def move_is_valid(board, move):
if move < 1 or move > (len(board)):
return False
if board[move-1][0] != ' ':
return False
return True
def available_moves(board):
moves = []
for i in range(1, len(board)+1):
if move_is_valid(board, i):
moves.append(i)
return moves
def has_won(board, symbol):
# check horizontal spaces
for y in range(len(board[0])):
for x in range(len(board) - 3):
if board[x][y] == symbol and board[x+1][y] == symbol and board[x+2][y] == symbol and board[x+3][y] == symbol:
return True
# check vertical spaces
for x in range(len(board)):
for y in range(len(board[0]) - 3):
if board[x][y] == symbol and board[x][y+1] == symbol and board[x][y+2] == symbol and board[x][y+3] == symbol:
return True
# check / diagonal spaces
for x in range(len(board) - 3):
for y in range(3, len(board[0])):
if board[x][y] == symbol and board[x+1][y-1] == symbol and board[x+2][y-2] == symbol and board[x+3][y-3] == symbol:
return True
# check \ diagonal spaces
for x in range(len(board) - 3):
for y in range(len(board[0]) - 3):
if board[x][y] == symbol and board[x+1][y+1] == symbol and board[x+2][y+2] == symbol and board[x+3][y+3] == symbol:
return True
return False
def game_is_over(board):
return has_won(board, "X") or has_won(board, "O") or len(available_moves(board)) == 0
def codecademy_evaluate_board(board):
if has_won(board, "X"):
return float("Inf")
elif has_won(board, "O"):
return -float("Inf")
else:
x_streaks = count_streaks(board, "X")
o_streaks = count_streaks(board, "O")
return x_streaks - o_streaks
def count_streaks(board, symbol):
count = 0
for col in range(len(board)):
for row in range(len(board[0])):
if board[col][row] != symbol:
continue
# right
if col < len(board) - 3:
num_in_streak = 0
for i in range(4):
if board[col + i][row] == symbol:
num_in_streak += 1
elif board[col + i][row] != " ":
num_in_streak = 0
break
count += num_in_streak
#left
if col > 2:
num_in_streak = 0
for i in range(4):
if board[col - i][row] == symbol:
num_in_streak += 1
elif board[col - i][row] != " ":
num_in_streak = 0
break
count += num_in_streak
#up-right
if col < len(board) - 3 and row > 2:
num_in_streak = 0
for i in range(4):
if board[col + i][row - i] == symbol:
num_in_streak += 1
elif board[col + i][row - i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down-right
if col < len(board) - 3 and row < len(board[0]) - 3:
num_in_streak = 0
for i in range(4):
if board[col + i][row + i] == symbol:
num_in_streak += 1
elif board[col + i][row + i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down-left
if col > 2 and row < len(board[0]) - 3:
num_in_streak = 0
for i in range(4):
if board[col - i][row + i] == symbol:
num_in_streak += 1
elif board[col - i][row + i] != " ":
num_in_streak = 0
break
count += num_in_streak
#up-left
if col > 2 and row > 2:
num_in_streak = 0
for i in range(4):
if board[col - i][row - i] == symbol:
num_in_streak += 1
elif board[col - i][row - i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down-left
if col > 2 and row < len(board[0]) - 3:
num_in_streak = 0
for i in range(4):
if board[col - i][row + i] == symbol:
num_in_streak += 1
elif board[col - i][row + i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down
num_in_streak = 0
if row < len(board[0]) - 3:
for i in range(4):
if row + i < len(board[0]):
if board[col][row + i] == symbol:
num_in_streak += 1
else:
break
for i in range(4):
if row - i > 0:
if board[col][row - i] == symbol:
num_in_streak += 1
elif board[col][row - i] == " ":
break
else:
num_in_streak == 0
if row < 3:
if num_in_streak + row < 4:
num_in_streak = 0
count += num_in_streak
return count
def minimax(input_board, is_maximizing, depth, alpha, beta, eval_function):
if game_is_over(input_board) or depth == 0:
return [eval_function(input_board), ""]
if is_maximizing:
best_value = -float("Inf")
moves = available_moves(input_board)
random.shuffle(moves)
best_move = moves[0]
for move in moves:
new_board = deepcopy(input_board)
select_space(new_board, move, "X")
hypothetical_value = minimax(new_board, False, depth - 1, alpha, beta, eval_function)[0]
if hypothetical_value > best_value:
best_value = hypothetical_value
best_move = move
alpha = max(alpha, best_value)
if alpha >= beta:
break
return [best_value, best_move]
else:
best_value = float("Inf")
moves = available_moves(input_board)
random.shuffle(moves)
best_move = moves[0]
for move in moves:
new_board = deepcopy(input_board)
select_space(new_board, move, "O")
hypothetical_value = minimax(new_board, True, depth - 1, alpha, beta, eval_function)[0]
if hypothetical_value < best_value:
best_value = hypothetical_value
best_move = move
beta = min(beta, best_value)
if alpha >= beta:
break
return [best_value, best_move]
def play_game(ai):
BOARDWIDTH = 7
BOARDHEIGHT = 6
board = []
for x in range(BOARDWIDTH):
board.append([' '] * BOARDHEIGHT)
while not game_is_over(board):
print_board(board)
moves = available_moves(board)
print("Available moves: " , moves)
choice = 100
good_move = False
while not good_move:
choice = input("Select a move:\n")
try:
move = int(choice)
except ValueError:
continue
if move in moves:
good_move = True
select_space(board, int(choice), "X")
if not game_is_over(board):
result = minimax(board, False, ai, -float("Inf"), float("Inf"))
print("Computer chose: ", result[1])
select_space(board, result[1], "O")
def make_board():
new_game = []
for x in range(7):
new_game.append([' '] * 6)
return new_game
from connect_four import *
def two_ai_game():
my_board = make_board()
while not game_is_over(my_board):
#The "X" player finds their best move.
result = minimax(my_board, True, 4, -float("Inf"), float("Inf"), my_evaluate_board)
print( "X Turn\nX selected ", result[1])
print(result[1])
select_space(my_board, result[1], "X")
print_board(my_board)
if not game_is_over(my_board):
#The "O" player finds their best move
result = minimax(my_board, False, 4, -float("Inf"), float("Inf"), codecademy_evaluate_board)
print( "O Turn\nO selected ", result[1])
print(result[1])
select_space(my_board, result[1], "O")
print_board(my_board)
if has_won(my_board, "X"):
print("X won!")
elif has_won(my_board, "O"):
print("O won!")
else:
print("It's a tie!")
def random_eval(board):
return random.randint(-100,100)
def my_evaluate_board(board):
if has_won(board, "X"):
return float("Inf")
elif has_won(board, "O"):
return -float("Inf")
x_two_streak = 0
o_two_streak = 0
for col in range(len(board)):
for row in range(len(board) -1):
if board[col][row] == "X" and board[col - 1][row] == "X":
x_two_streak += 1
if board[col][row] == "O" and board[col - 1][row] == "O":
o_two_streak += 1
return x_two_streak - o_two_streak
new_board = make_board()
select_space(new_board, 1, "X")
select_space(new_board, 2, "X")
select_space(new_board, 5, "X")
select_space(new_board, 7, "X")
select_space(new_board, 4, "O")
select_space(new_board, 7, "O")
select_space(new_board, 7, "O")
select_space(new_board, 7, "O")
print_board(new_board)
print(my_evaluate_board(new_board))
two_ai_game()
#connect_four.py
from copy import deepcopy
import random
random.seed(108)
def print_board(board):
print()
print(' ', end='')
for x in range(1, len(board) + 1):
print(' %s ' % x, end='')
print()
print('+---+' + ('---+' * (len(board) - 1)))
for y in range(len(board[0])):
print('| |' + (' |' * (len(board) - 1)))
print('|', end='')
for x in range(len(board)):
print(' %s |' % board[x][y], end='')
print()
print('| |' + (' |' * (len(board) - 1)))
print('+---+' + ('---+' * (len(board) - 1)))
def select_space(board, column, player):
if not move_is_valid(board, column):
return False
if player != "X" and player != "O":
return False
for y in range(len(board[0])-1, -1, -1):
if board[column-1][y] == ' ':
board[column-1][y] = player
return True
return False
def board_is_full(board):
for x in range(len(board)):
for y in range(len(board[0])):
if board[x][y] == ' ':
return False
return True
def move_is_valid(board, move):
if move < 1 or move > (len(board)):
return False
if board[move-1][0] != ' ':
return False
return True
def available_moves(board):
moves = []
for i in range(1, len(board)+1):
if move_is_valid(board, i):
moves.append(i)
return moves
def has_won(board, symbol):
# check horizontal spaces
for y in range(len(board[0])):
for x in range(len(board) - 3):
if board[x][y] == symbol and board[x+1][y] == symbol and board[x+2][y] == symbol and board[x+3][y] == symbol:
return True
# check vertical spaces
for x in range(len(board)):
for y in range(len(board[0]) - 3):
if board[x][y] == symbol and board[x][y+1] == symbol and board[x][y+2] == symbol and board[x][y+3] == symbol:
return True
# check / diagonal spaces
for x in range(len(board) - 3):
for y in range(3, len(board[0])):
if board[x][y] == symbol and board[x+1][y-1] == symbol and board[x+2][y-2] == symbol and board[x+3][y-3] == symbol:
return True
# check \ diagonal spaces
for x in range(len(board) - 3):
for y in range(len(board[0]) - 3):
if board[x][y] == symbol and board[x+1][y+1] == symbol and board[x+2][y+2] == symbol and board[x+3][y+3] == symbol:
return True
return False
def game_is_over(board):
return has_won(board, "X") or has_won(board, "O") or len(available_moves(board)) == 0
def codecademy_evaluate_board(board):
if has_won(board, "X"):
return float("Inf")
elif has_won(board, "O"):
return -float("Inf")
else:
x_streaks = count_streaks(board, "X")
o_streaks = count_streaks(board, "O")
return x_streaks - o_streaks
def count_streaks(board, symbol):
count = 0
for col in range(len(board)):
for row in range(len(board[0])):
if board[col][row] != symbol:
continue
# right
if col < len(board) - 3:
num_in_streak = 0
for i in range(4):
if board[col + i][row] == symbol:
num_in_streak += 1
elif board[col + i][row] != " ":
num_in_streak = 0
break
count += num_in_streak
#left
if col > 2:
num_in_streak = 0
for i in range(4):
if board[col - i][row] == symbol:
num_in_streak += 1
elif board[col - i][row] != " ":
num_in_streak = 0
break
count += num_in_streak
#up-right
if col < len(board) - 3 and row > 2:
num_in_streak = 0
for i in range(4):
if board[col + i][row - i] == symbol:
num_in_streak += 1
elif board[col + i][row - i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down-right
if col < len(board) - 3 and row < len(board[0]) - 3:
num_in_streak = 0
for i in range(4):
if board[col + i][row + i] == symbol:
num_in_streak += 1
elif board[col + i][row + i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down-left
if col > 2 and row < len(board[0]) - 3:
num_in_streak = 0
for i in range(4):
if board[col - i][row + i] == symbol:
num_in_streak += 1
elif board[col - i][row + i] != " ":
num_in_streak = 0
break
count += num_in_streak
#up-left
if col > 2 and row > 2:
num_in_streak = 0
for i in range(4):
if board[col - i][row - i] == symbol:
num_in_streak += 1
elif board[col - i][row - i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down-left
if col > 2 and row < len(board[0]) - 3:
num_in_streak = 0
for i in range(4):
if board[col - i][row + i] == symbol:
num_in_streak += 1
elif board[col - i][row + i] != " ":
num_in_streak = 0
break
count += num_in_streak
#down
num_in_streak = 0
if row < len(board[0]) - 3:
for i in range(4):
if row + i < len(board[0]):
if board[col][row + i] == symbol:
num_in_streak += 1
else:
break
for i in range(4):
if row - i > 0:
if board[col][row - i] == symbol:
num_in_streak += 1
elif board[col][row - i] == " ":
break
else:
num_in_streak == 0
if row < 3:
if num_in_streak + row < 4:
num_in_streak = 0
count += num_in_streak
return count
def minimax(input_board, is_maximizing, depth, alpha, beta, eval_function):
if game_is_over(input_board) or depth == 0:
return [eval_function(input_board), ""]
if is_maximizing:
best_value = -float("Inf")
moves = available_moves(input_board)
random.shuffle(moves)
best_move = moves[0]
for move in moves:
new_board = deepcopy(input_board)
select_space(new_board, move, "X")
hypothetical_value = minimax(new_board, False, depth - 1, alpha, beta, eval_function)[0]
if hypothetical_value > best_value:
best_value = hypothetical_value
best_move = move
alpha = max(alpha, best_value)
if alpha >= beta:
break
return [best_value, best_move]
else:
best_value = float("Inf")
moves = available_moves(input_board)
random.shuffle(moves)
best_move = moves[0]
for move in moves:
new_board = deepcopy(input_board)
select_space(new_board, move, "O")
hypothetical_value = minimax(new_board, True, depth - 1, alpha, beta, eval_function)[0]
if hypothetical_value < best_value:
best_value = hypothetical_value
best_move = move
beta = min(beta, best_value)
if alpha >= beta:
break
return [best_value, best_move]
def play_game(ai):
BOARDWIDTH = 7
BOARDHEIGHT = 6
board = []
for x in range(BOARDWIDTH):
board.append([' '] * BOARDHEIGHT)
while not game_is_over(board):
print_board(board)
moves = available_moves(board)
print("Available moves: " , moves)
choice = 100
good_move = False
while not good_move:
choice = input("Select a move:\n")
try:
move = int(choice)
except ValueError:
continue
if move in moves:
good_move = True
select_space(board, int(choice), "X")
if not game_is_over(board):
result = minimax(board, False, ai, -float("Inf"), float("Inf"))
print("Computer chose: ", result[1])
select_space(board, result[1], "O")
def make_board():
new_game = []
for x in range(7):
new_game.append([' '] * 6)
return new_game
#perceptron logic gates
import codecademylib3_seaborn
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
import numpy as np
from itertools import product
data = [[0,0],[0,1],[1,0],[1,1]]
labels = [0,1,1,0]
plt.scatter([point[0] for point in data], [point[1] for point in data],c=labels)
plt.show()
classifier = Perceptron(max_iter=40)
classifier.fit(data,labels)
print(classifier.score(data,labels))
print(classifier.decision_function([[0,0],[1,1],[0.5,0.5]]))
x_values = np.linspace(0,1,100)
y_values = np.linspace(0,1,100)
point_grid = list(product(x_values,y_values))
distances = classifier.decision_function(point_grid)
abs_distances = [abs(pt) for pt in distances]
distances_matrix = np.reshape(abs_distances,(100,100))
heatmap = plt.pcolormesh(x_values,y_values,distances_matrix)
plt.colorbar(heatmap)
plt.show()
import codecademylib3_seaborn
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
import numpy as np
from itertools import product
data = [[0,0],[0,1],[1,0],[1,1]]
labels = [0,1,1,0]
plt.scatter([point[0] for point in data], [point[1] for point in data],c=labels)
plt.show()
classifier = Perceptron(max_iter=40)
classifier.fit(data,labels)
print(classifier.score(data,labels))
print(classifier.decision_function([[0,0],[1,1],[0.5,0.5]]))
x_values = np.linspace(0,1,100)
y_values = np.linspace(0,1,100)
point_grid = list(product(x_values,y_values))
distances = classifier.decision_function(point_grid)
abs_distances = [abs(pt) for pt in distances]
distances_matrix = np.reshape(abs_distances,(100,100))
heatmap = plt.pcolormesh(x_values,y_values,distances_matrix)
plt.colorbar(heatmap)
plt.show()