text
stringlengths
37
1.41M
print("Привет, я Анфиса!") friends = ['Серёга', 'Соня', 'Дима', 'Алина', 'Егор'] friends_string = ', '.join(friends) print("Твои друзья: " + friends_string) stations = ['Москва', 'Серп и Молот', 'Карачарово', 'Чухлинка', 'Кусково', 'Новогиреево', 'Реутово', 'Никольское', 'Салтыковская', 'Кучино', 'Железнодорожная', 'Чёрное', 'Купавна', '33-й километр', 'Электроугли', '43-й километр', 'Храпуново', 'Есино', 'Фрязево', '61-й километр', '65-й километр', 'Павлово-Посад', 'Назарьево', 'Дрезна', '85-й километр', 'Орехово-Зуево', 'Крутое', 'Воиново', 'Усад', '105-й километр', 'Покров', '113-й километр', 'Омутище', 'Леоново', 'Петушки'] navi = " - ".join(stations) print(navi)
def func(square): return square ** 2 iterator_list = [1,2,3,4,5] print(list(map(func, iterator_list)))
#Write a function that checks whether a number is in a given range (inclusive of high and low) def ran(num,high,low): if num > low and num < high: print(f"the middle number is {num} and low is {low} and high is {high}") # if num in range(low,high)
from utils import read_file def calc_fuel(mass): return mass // 3 - 2 def calc_fuel_recursive(mass): total = 0 res = calc_fuel(mass) while res > 0: total += res res = calc_fuel(res) return total print("#--- part1 ---#") assert(calc_fuel(12) == 2) assert(calc_fuel(14) == 2) assert(calc_fuel(1969) == 654) assert(calc_fuel(100756) == 33583) values = map(int, read_file('01.txt')) print(sum(map(calc_fuel, values))) print("#--- part2 ---#") assert(calc_fuel_recursive(14) == 2) assert(calc_fuel_recursive(1969) == 966) assert(calc_fuel_recursive(100756) == 50346) values = map(int, read_file('01.txt')) print(sum(map(calc_fuel_recursive, values)))
# Rearrange an array with alternate high and low elements def solve(arr): for i in range(1, len(arr), 2): if arr[i-1] > arr[i]: arr[i], arr[i-1] = arr[i-1], arr[i] if i + 1 < len(arr) and arr[i+1] > arr[i]: arr[i+1], arr[i] = arr[i], arr[i + 1] return arr arr = list(map(int, input("Please enter the array: ").split())) print(solve(arr))
# Merge two arrays by satisfying given constraints def solve(x, y): # move non empty elements of x to the begining j = 0 for i in range(len(x)): if x[i]: x[j] = x[i] j += 1 x_pos = len(x) - len(y) - 1 y_pos = len(y) - 1 k = len(x) - 1 while x_pos > -1 and y_pos > -1: if x[x_pos] >= y[y_pos]: x[k] = x[x_pos] x_pos -= 1 k -= 1 else: x[k] = y[y_pos] y_pos -= 1 k -= 1 while y_pos > -1: x[k] = y[y_pos] k -= 1 y_pos -= 1 return x x = list(map(int, input("Enter first array: ").split())) y = list(map(int, input("Enter second array: ").split())) print(solve(x, y)) # 0 2 0 3 0 5 6 0 0 # 1 8 9 10 15
numb = int(input("Enter a number: ")) if numb > 1: # check for factors for i in range(2,numb): if (numb % i) == 0: print(numb,"is not a prime number") print(i,"times",numb//i,"is",numb) break else: print(numb,"is a prime number") else: print(numb,"is not a prime number")
import sqlite3 try: sqliteConnection = sqlite3.connect("SQLite_Python.db") cursor = sqliteConnection.cursor() print("Succesfully connected to SQLite") sqlite_insert_query = """INSERT INTO SQLiteDb_developers (id, name, email, joining_date, salary) VALUES (2, 'Alan', 'agomeztagle7@gmail.com', '2019-07-10', 0)""" count = cursor.execute(sqlite_insert_query) sqliteConnection.commit() print("Record succesfully inserted into the SQLiteDb_developers table ", cursor) cursor.close() except sqlite3.Error as error: print("Failed to insert data into SqliteDb_developers table", error) finally: if(sqliteConnection): sqliteConnection.close() print("The SQL connection is closed")
import random def random_color(): number = "#" for n in range(6): number += str(random.randint(0, 9)) return number if __name__ == "__main__": print(type(random_color()))
"""This module contain functions to calculate option pricing using different finite difference methods. This will work for 1 factor(asset) and 2 factors(asset and interest rate) models. -*- coding: utf-8 -*- Author: Agam Shah(shahagam4@gmail.com) Reference "Paul-Wilmott-on-Quantitative-Finance" """ import math import numpy as np # from grid import Grid def solve(grid, asset_volatility, interest_rate, strike_price, current_stock_price, excercise_type="European", solving_method="Explicit", extrapolation_grid=None, current_time=0.0, option_type="Call", interest_rate_volatility=None, interest_rate_drift=None): """This is wrapper function for option pricing. It takes generic input for option pricing. Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option current_stock_price : float the current price of asset where one want to find option value excercise_type : {"European","American"} specify excercise type solving_method : {"Explicit","FullyImplicit","CrankNicolson","CrankNicolsonLU", "CrankNicolsonSORwithOptimalW","CrankNicolsonDouglas"} extrapolation_grid : Grid class object, optional Specify the value if one want to improve accuracy using Richardson's extrapolation current_time : float time at which one want to calculate the option value, default is t=0.0 for 2 factor this should be always 0.0 option_type : {"Call","Put"} specify option type interest_rate_volatility : float value of the interest rate volatility interest_rate_drift : float value of the interest rate drift Returns ------- final_option_value : float for 1-factor returns option value at given stock price and time option_value_matrix : numpy_array for 2-factor returns option value matrix at t=0.0 """ final_option_value = -1 option_value_matrix = None extrapolation_option_value = None if interest_rate_volatility is not None: option_value_matrix = two_factor_Explicit( grid, asset_volatility, strike_price, excercise_type, interest_rate_volatility, interest_rate_drift, option_type) return option_value_matrix else: if extrapolation_grid is None: if current_time == 0.0: if solving_method == "Explicit": option_value_matrix = Explicit_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "FullyImplicit": option_value_matrix = fully_implicit_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolson": option_value_matrix = crank_nicolson_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonLU": option_value_matrix = crank_nicolson_lu_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonSORwithOptimalW": option_value_matrix = crankNicolsonSORwithOptimalW_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonDouglas": option_value_matrix = crank_nicolson_douglas_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) final_option_value = interpolate_two_d(grid, option_value_matrix, current_stock_price) else: if solving_method == "Explicit": option_value_matrix = Explicit_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "FullyImplicit": option_value_matrix = fully_implicit_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolson": option_value_matrix = crank_nicolson_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonLU": option_value_matrix = crank_nicolson_lu_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonSORwithOptimalW": option_value_matrix = crankNicolsonSORwithOptimalW_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonDouglas": option_value_matrix = crank_nicolson_douglas_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) final_option_value = interpolate_three_d(grid, option_value_matrix, current_stock_price, current_time) else: if current_time == 0.0: if solving_method == "Explicit": option_value_matrix = Explicit_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = Explicit_two_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "FullyImplicit": option_value_matrix = fully_implicit_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = fully_implicit_two_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolson": option_value_matrix = crank_nicolson_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = crank_nicolson_two_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonLU": option_value_matrix = crank_nicolson_lu_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = crank_nicolson_lu_two_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonSORwithOptimalW": option_value_matrix = crankNicolsonSORwithOptimalW_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value =\ crankNicolsonSORwithOptimalW_two_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonDouglas": option_value_matrix = crank_nicolson_douglas_two_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value =\ crank_nicolson_douglas_two_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) option_value_grid = interpolate_two_d( grid, option_value_matrix, current_stock_price) option_value_extrapolation_grid = interpolate_two_d( extrapolation_grid, extrapolation_option_value, current_stock_price) final_option_value = richardson_extrapolation( grid, option_value_grid, extrapolation_grid, option_value_extrapolation_grid) else: if solving_method == "Explicit": option_value_matrix = Explicit_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = Explicit_three_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "FullyImplicit": option_value_matrix = fully_implicit_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = fully_implicit_three_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolson": option_value_matrix = crank_nicolson_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = crank_nicolson_three_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonLU": option_value_matrix = crank_nicolson_lu_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value = crank_nicolson_lu_three_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonSORwithOptimalW": option_value_matrix = crankNicolsonSORwithOptimalW_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value =\ crankNicolsonSORwithOptimalW_three_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) elif solving_method == "CrankNicolsonDouglas": option_value_matrix = crank_nicolson_douglas_three_d( grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) extrapolation_option_value =\ crank_nicolson_douglas_three_d( extrapolation_grid, asset_volatility, interest_rate, strike_price, excercise_type, option_type) option_value_grid = interpolate_three_d(grid, option_value_matrix, current_stock_price, current_time) option_value_extrapolation_grid = interpolate_three_d( extrapolation_grid, extrapolation_option_value, current_stock_price, current_time) final_option_value = richardson_extrapolation( grid, option_value_grid, extrapolation_grid, option_value_extrapolation_grid) return final_option_value def richardson_extrapolation(grid, option_value_grid, extrapolation_grid, option_value_extrapolation_grid): """Richardson's extrapolation method take two non similar grids (means different asset step size grids) and give option value with improved accuracy. For more information refer section 78.8 Parameters ---------- grid : Grid class object Grid class object for first grid option_value_grid : float option value correspond to first grid extrapolation_grid : Grid class object Grid class object for second grid option_value_extrapolation_grid : float option value correspond to second grid Returns ------- float returns extrapolated(more accurate) option value """ asset_step_size_grid = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) asset_step_size_second_grid = float( (extrapolation_grid.maximum_asset_value - extrapolation_grid.minimum_asset_value) / extrapolation_grid.number_of_asset_step) print(option_value_grid, option_value_extrapolation_grid) option_value = ((asset_step_size_second_grid**2 * option_value_grid - asset_step_size_grid**2 * option_value_extrapolation_grid) / (asset_step_size_second_grid**2-asset_step_size_grid**2)) return option_value def interpolate_two_d(grid, option_value_matrix, current_stock_price): """To estimate the option value at point in between. It uses bilinear interpolation to estimate value. For more information refer section 77.16 Parameters ---------- grid : Grid class object Grid class object for grid option_value_matrix : numpy_array one dimensional option value array current_stock_price : float stock price at which you want to find option value Returns ------- float returns interpolated option value """ asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) lower_asset_index = math.floor( (current_stock_price-grid.minimum_asset_value)/asset_step_size) upper_asset_index = lower_asset_index+1 option_value = ((option_value_matrix[lower_asset_index] * (grid.minimum_asset_value+asset_step_size * upper_asset_index-current_stock_price) + option_value_matrix[upper_asset_index] * (current_stock_price - (grid.minimum_asset_value + asset_step_size * lower_asset_index)))/asset_step_size) return option_value def interpolate_three_d(grid, option_value_matrix, current_stock_price, current_time): """To estimate the option value at point in between. It uses bilinear interpolation to estimate value. This also find option value at in between time point. For more information refer section 77.16 Parameters ---------- grid : Grid class object Grid class object for grid option_value_matrix : numpy_array two dimensional option value array current_stock_price : float stock price at which you want to find option value current_time : float time at which you want to find option value Returns ------- float returns interpolated option value """ asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) lower_asset_index = math.floor( (current_stock_price-grid.minimum_asset_value)/asset_step_size) upper_asset_index = lower_asset_index + 1 time_step_size = grid.expiration_time / grid.number_of_time_step lower_time_index = math.floor(current_time / time_step_size) upper_time_index = lower_time_index + 1 area3 = ((current_stock_price - (grid.minimum_asset_value+asset_step_size * lower_asset_index)) * (current_time-lower_time_index*time_step_size)) area4 = ((current_stock_price - (grid.minimum_asset_value+asset_step_size * lower_asset_index)) * (upper_time_index*time_step_size-current_time)) area2 = (grid.minimum_asset_value+asset_step_size*upper_asset_index - current_stock_price)*(current_time-lower_time_index*time_step_size) area1 = (grid.minimum_asset_value+asset_step_size*upper_asset_index - current_stock_price)*(upper_time_index*time_step_size-current_time) option_value_1 = option_value_matrix[lower_asset_index, lower_time_index] option_value_2 = option_value_matrix[lower_asset_index, upper_time_index] option_value_3 = option_value_matrix[upper_asset_index, upper_time_index] option_value_4 = option_value_matrix[upper_asset_index, lower_time_index] option_value = (area1*option_value_1+area2*option_value_2+area3 * option_value_3+area4*option_value_4)/(area1+area2+area3+area4) return option_value def Explicit_three_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses Explicit finite-difference method. This is for 1 factor model. For more information refer section 77.11 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step + 1) pay_off = np.zeros(grid.number_of_asset_step+1) asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) if((int(grid.expiration_time / (asset_volatility**2*grid.number_of_asset_step**2)) + 1) > grid.number_of_time_step): print("numer Of Time Steps Changed") grid.number_of_time_step = (int( grid.expiration_time/(asset_volatility**2 * grid.number_of_asset_step**2))+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value = np.zeros((grid.number_of_asset_step+1, grid.number_of_time_step+1)) multiplier = 1 if option_type == "Put": multiplier = -1 for i in range(grid.number_of_asset_step+1): option_value[i, 0] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value[i, 0] for k in range(1, grid.number_of_time_step+1): for i in range(1, grid.number_of_asset_step): delta = (option_value[i+1, k-1] - option_value[i-1, k-1])/(2*asset_step_size) gamma = ((option_value[i+1, k-1] - 2*option_value[i, k-1]+option_value[i-1, k-1]) / (asset_step_size*asset_step_size)) theta = -0.5*asset_volatility**2*asset_value[i]**2*gamma - \ interest_rate*asset_value[i]*delta + \ interest_rate*option_value[i, k-1] option_value[i, k] = option_value[i, k-1]-time_step_size*theta option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) option_value[grid.number_of_asset_step, k] = 2 * \ option_value[grid.number_of_asset_step-1, k] - \ option_value[grid.number_of_asset_step-2, k] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value[i, k] = max(option_value[i, k], pay_off[i]) return option_value def Explicit_two_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses Explicit finite-difference method. This is for 1 factor model. For more information refer section 77.11 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns one dimensional numpy array of option value for t=0.0 """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value) / grid.number_of_asset_step) if((int(grid.expiration_time / (asset_volatility**2*grid.number_of_asset_step**2))+1) > grid.number_of_time_step): print("numer Of Time Steps Changed") grid.number_of_time_step = (int( grid.expiration_time / (asset_volatility**2*grid.number_of_asset_step**2))+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros(grid.number_of_asset_step + 1) option_value_new = np.zeros(grid.number_of_asset_step + 1) option_value_with_greeks = np.zeros((grid.number_of_asset_step + 1, 6)) multiplier = 1 if option_type == "Put": multiplier = -1 for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value_old[i] option_value_with_greeks[i, 0] = asset_value[i] option_value_with_greeks[i, 1] = pay_off[i] for _ in range(1, grid.number_of_time_step + 1):# time(k) loop for i in range(1, grid.number_of_asset_step): delta = (option_value_old[i+1]-option_value_old[i-1])/(2*asset_step_size) gamma = (option_value_old[i+1]-2*option_value_old[i] + option_value_old[i-1])/(asset_step_size*asset_step_size) theta = -0.5*asset_volatility**2*asset_value[i]**2*gamma - \ interest_rate*asset_value[i]*delta+interest_rate*option_value_old[i] option_value_new[i] = option_value_old[i]-time_step_size*theta option_value_new[0] = option_value_old[0]*(1-interest_rate*time_step_size) option_value_new[grid.number_of_asset_step] = 2 * \ option_value_new[grid.number_of_asset_step-1] - \ option_value_new[grid.number_of_asset_step-2] option_value_old = list(option_value_new) if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(option_value_old[i], pay_off[i]) for i in range(1, grid.number_of_asset_step): option_value_with_greeks[i, 2] = option_value_old[i] option_value_with_greeks[i, 3] = ( option_value_old[i+1]-option_value_old[i-1])/(2*asset_step_size) option_value_with_greeks[i, 4] = (( option_value_old[i+1]-2*option_value_old[i]+option_value_old[i-1]) / (asset_step_size*asset_step_size)) option_value_with_greeks[i, 5] = ( (-0.5)*asset_volatility**2*asset_value[i]**2 * option_value_with_greeks[i, 4] - interest_rate*asset_value[i] * option_value_with_greeks[i, 3] + interest_rate*option_value_old[i]) option_value_with_greeks[0, 2] = option_value_old[0] option_value_with_greeks[grid.number_of_asset_step, 2] = option_value_old[grid.number_of_asset_step] option_value_with_greeks[0, 3] = ( option_value_old[1]-option_value_old[0])/asset_step_size option_value_with_greeks[grid.number_of_asset_step, 3] = (( option_value_old[grid.number_of_asset_step] - option_value_old[grid.number_of_asset_step-1]) / asset_step_size) option_value_with_greeks[0, 4] = 0 option_value_with_greeks[grid.number_of_asset_step, 4] = 0 option_value_with_greeks[0, 5] = interest_rate*option_value_old[0] option_value_with_greeks[grid.number_of_asset_step, 5] = ( (-0.5)*asset_volatility**2*asset_value[grid.number_of_asset_step]**2 * option_value_with_greeks[grid.number_of_asset_step, 4] - interest_rate * asset_value[grid.number_of_asset_step] * option_value_with_greeks[grid.number_of_asset_step, 3]+interest_rate * option_value_old[grid.number_of_asset_step]) # return option_value_with_greeks return option_value_old def fully_implicit_three_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses fully implicit finite-difference method. This is for 1 factor model. For more information refer section 78.2 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value = np.zeros((grid.number_of_asset_step+1, grid.number_of_time_step+1)) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = -((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/2 coefficient_b[i-1] = ((asset_volatility**2*i**2+interest_rate)*time_step_size) coefficient_c[i-1] = -((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/2 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = coefficient_a[grid.number_of_asset_step-2] - \ coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1+coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 + \ coefficient_b[grid.number_of_asset_step-2]+2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = coefficient_c[i] matrix_left = (np.diagonal(sub_diagonal[1:], k=-1) + np.diagonal(diagonal[:]) + np.diagonal(super_diagonal[0:grid.number_of_asset_step-2], k=1)) for i in range(grid.number_of_asset_step+1): option_value[i, 0] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value[i, 0] for k in range(1, grid.number_of_time_step+1): option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = coefficient_a[0]*option_value[0, k] vector_right = np.zeros((1, grid.number_of_asset_step-1)) vector_right = list(option_value[1:grid.number_of_asset_step, k-1]) vector_right[0] = vector_right[0]-remainder_vector[0] option_value[1:grid.number_of_asset_step, k] = np.linalg.solve(matrix_left, vector_right) option_value[grid.number_of_asset_step, k] = 2 * \ option_value[grid.number_of_asset_step-1, k] - \ option_value[grid.number_of_asset_step-2, k] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value[i, k] = max(option_value[i, k], pay_off[i]) return option_value def fully_implicit_two_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses fully implicit finite-difference method. This is for 1 factor model. For more information refer section 77.2 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns one dimensional numpy array of option value for t=0.0 """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros(grid.number_of_asset_step + 1) option_value_new = np.zeros(grid.number_of_asset_step + 1) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = -((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/2 coefficient_b[i-1] = ((asset_volatility**2*i**2+interest_rate)*time_step_size) coefficient_c[i-1] = -((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/2 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = coefficient_a[grid.number_of_asset_step-2] - \ coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1+coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 + \ coefficient_b[grid.number_of_asset_step-2]+2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = coefficient_c[i] matrix_left = (np.diagonal(sub_diagonal[1:], k=-1) + np.diagonal(diagonal[:]) + np.diagonal(super_diagonal[0:grid.number_of_asset_step-2], k=1)) for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value_old[i] for _ in range(1, grid.number_of_time_step+1):# time(k) loop option_value_new[0] = option_value_old[0] * \ (1-interest_rate*time_step_size) if excercise_type == "American": option_value_new[0] = max(option_value_new[0], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = coefficient_a[0]*option_value_new[0] vector_right = np.zeros((1, grid.number_of_asset_step-1)) vector_right = list(option_value_old[1:grid.number_of_asset_step]) vector_right[0] = vector_right[0]-remainder_vector[0] option_value_new[1:grid.number_of_asset_step] = np.linalg.solve(matrix_left, vector_right) option_value_new[grid.number_of_asset_step] = 2 * \ option_value_new[grid.number_of_asset_step-1] - \ option_value_new[grid.number_of_asset_step-2] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value_new[i] = max(option_value_new[i], pay_off[i]) option_value_old = list(option_value_new) return option_value_new def crank_nicolson_three_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses CRANK–NICOLSON finite-difference method. This is for 1 factor model. For more information refer section 78.3 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value = np.zeros((grid.number_of_asset_step+1, grid.number_of_time_step+1)) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = ((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/4 coefficient_b[i-1] = -((asset_volatility**2*i**2+interest_rate)*time_step_size)/2 coefficient_c[i-1] = ((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/4 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = - \ coefficient_a[grid.number_of_asset_step-2]+coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 - \ coefficient_b[grid.number_of_asset_step-2]-2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -coefficient_c[i] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = coefficient_a[i] matrix_right[i, i+1] = 1+coefficient_b[i] matrix_right[i, i+2] = coefficient_c[i] matrix_left = np.diagonal(sub_diagonal[1:], k=-1) + np.diagonal(diagonal[:]) + \ np.diagonal(super_diagonal[0:grid.number_of_asset_step-2], k=1) for i in range(grid.number_of_asset_step+1): option_value[i, 0] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value[i, 0] for k in range(1, grid.number_of_time_step + 1): option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value[0, k] vector_right = np.matmul(matrix_right, option_value[:, k-1]) vector_right[0] = vector_right[0]-remainder_vector[0] option_value[1:grid.number_of_asset_step, k] = np.linalg.solve(matrix_left, vector_right) option_value[grid.number_of_asset_step, k] = 2 * \ option_value[grid.number_of_asset_step-1, k] - \ option_value[grid.number_of_asset_step-2, k] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value[i, k] = max(option_value[i, k], pay_off[i]) return option_value def crank_nicolson_two_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses fully CRANK–NICOLSON finite-difference method. This is for 1 factor model. For more information refer section 78.3 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns one dimensional numpy array of option value for t=0.0 """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros(grid.number_of_asset_step + 1) option_value_new = np.zeros(grid.number_of_asset_step + 1) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = ((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/4 coefficient_b[i-1] = -((asset_volatility**2*i**2+interest_rate)*time_step_size)/2 coefficient_c[i-1] = ((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/4 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = - \ coefficient_a[grid.number_of_asset_step-2]+coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 - \ coefficient_b[grid.number_of_asset_step-2]-2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -coefficient_c[i] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = coefficient_a[i] matrix_right[i, i+1] = 1+coefficient_b[i] matrix_right[i, i+2] = coefficient_c[i] matrix_left = np.diagonal(sub_diagonal[1:], k=-1) + np.diagonal(diagonal[:]) + \ np.diagonal(super_diagonal[0:grid.number_of_asset_step-2], k=1) for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value_old[i] for _ in range(1, grid.number_of_time_step + 1):# time(k) loop option_value_new[0] = option_value_old[0] * \ (1-interest_rate*time_step_size) if excercise_type == "American": option_value_new[0] = max(option_value_new[0], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value_new[0] vector_right = np.matmul(matrix_right, option_value_old[:]) vector_right[0] = vector_right[0]-remainder_vector[0] option_value_new[1:grid.number_of_asset_step] = np.linalg.solve(matrix_left, vector_right) option_value_new[grid.number_of_asset_step] = 2 * \ option_value_new[grid.number_of_asset_step-1] - \ option_value_new[grid.number_of_asset_step-2] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value_new[i] = max(option_value_new[i], pay_off[i]) option_value_old = list(option_value_new) return option_value_new def crank_nicolson_lu_three_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses CRANK–NICOLSON finite-difference method. This also uses LU decomposition. This is for 1 factor model. For more information refer section 78.3.5 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value = np.zeros((grid.number_of_asset_step+1, grid.number_of_time_step+1)) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = ((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/4 coefficient_b[i-1] = -((asset_volatility**2*i**2+interest_rate)*time_step_size)/2 coefficient_c[i-1] = ((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/4 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = - \ coefficient_a[grid.number_of_asset_step-2]+coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 - \ coefficient_b[grid.number_of_asset_step-2]-2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -coefficient_c[i] new_diagonal = np.zeros(grid.number_of_asset_step-1) new_upper_diagonal = np.zeros(grid.number_of_asset_step-1) new_lower_diagonal = np.zeros(grid.number_of_asset_step-1) new_diagonal[0] = diagonal[0] for i in range(1, grid.number_of_asset_step-1): new_upper_diagonal[i-1] = super_diagonal[i-1] new_lower_diagonal[i] = sub_diagonal[i]/new_diagonal[i-1] new_diagonal[i] = diagonal[i]-new_lower_diagonal[i]*super_diagonal[i-1] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = coefficient_a[i] matrix_right[i, i+1] = 1+coefficient_b[i] matrix_right[i, i+2] = coefficient_c[i] for i in range(grid.number_of_asset_step+1): option_value[i, 0] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value[i, 0] for k in range(1, grid.number_of_time_step + 1): option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value[0, k] w = np.zeros(grid.number_of_asset_step - 1) # vector_right=np.matmul(matrix_right, V[:,k-1][:, None])-remainder_vector vector_right = np.matmul(matrix_right, option_value[:, k-1])-remainder_vector w[0] = vector_right[0] for i in range(1, grid.number_of_asset_step-1): w[i] = vector_right[i]-new_lower_diagonal[i]*w[i-1] option_value[grid.number_of_asset_step-1, k] =\ (w[grid.number_of_asset_step-2]/new_diagonal[grid.number_of_asset_step-2]) for i in range(grid.number_of_asset_step-2, 0, -1): option_value[i, k] = (w[i-1]-(new_upper_diagonal[i-1]*option_value[i+1, k])) / \ new_diagonal[i-1] option_value[grid.number_of_asset_step, k] = 2 * \ option_value[grid.number_of_asset_step-1, k] - \ option_value[grid.number_of_asset_step-2, k] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value[i, k] = max(option_value[i, k], pay_off[i]) return option_value def crank_nicolson_lu_two_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses fully CRANK–NICOLSON finite-difference method. This also uses LU decomposition. This is for 1 factor model. For more information refer section 78.3.5 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns one dimensional numpy array of option value for t=0.0 """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros(grid.number_of_asset_step + 1) option_value_new = np.zeros(grid.number_of_asset_step + 1) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = ((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/4 coefficient_b[i-1] = -((asset_volatility**2*i**2+interest_rate)*time_step_size)/2 coefficient_c[i-1] = ((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/4 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = - \ coefficient_a[grid.number_of_asset_step-2]+coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 - \ coefficient_b[grid.number_of_asset_step-2]-2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -coefficient_c[i] new_diagonal = np.zeros(grid.number_of_asset_step-1) new_upper_diagonal = np.zeros(grid.number_of_asset_step-1) new_lower_diagonal = np.zeros(grid.number_of_asset_step-1) new_diagonal[0] = diagonal[0] for i in range(1, grid.number_of_asset_step-1): new_upper_diagonal[i-1] = super_diagonal[i-1] new_lower_diagonal[i] = sub_diagonal[i]/new_diagonal[i-1] new_diagonal[i] = diagonal[i]-new_lower_diagonal[i]*super_diagonal[i-1] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = coefficient_a[i] matrix_right[i, i+1] = 1+coefficient_b[i] matrix_right[i, i+2] = coefficient_c[i] for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value_old[i] for _ in range(1, grid.number_of_time_step + 1):# time(k) loop option_value_new[0] = option_value_old[0]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value_new[0] = max(option_value_new[0], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value_new[0] w = np.zeros(grid.number_of_asset_step - 1) # vector_right=np.matmul(matrix_right, V[:,k-1][:, None])-remainder_vector vector_right = np.matmul(matrix_right, option_value_old[:])-remainder_vector w[0] = vector_right[0] for i in range(1, grid.number_of_asset_step-1): w[i] = vector_right[i]-new_lower_diagonal[i]*w[i-1] option_value_new[grid.number_of_asset_step - 1] =\ (w[grid.number_of_asset_step-2]/new_diagonal[grid.number_of_asset_step-2]) for i in range(grid.number_of_asset_step-2, 0, -1): option_value_new[i] = (w[i-1]-(new_upper_diagonal[i-1]*option_value_new[i+1])) / \ new_diagonal[i-1] option_value_new[grid.number_of_asset_step] = 2 * \ option_value_new[grid.number_of_asset_step-1] - \ option_value_new[grid.number_of_asset_step-2] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value_new[i] = max(option_value_new[i], pay_off[i]) option_value_old = list(option_value_new) print(option_value_new) return option_value_new def crankNicolsonSORwithOptimalW_three_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses CRANK–NICOLSON finite-difference method. This also uses SOR with optimal w. This is for 1 factor model. For more information refer section 78.3.6 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value = np.zeros((grid.number_of_asset_step+1, grid.number_of_time_step+1)) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = ((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/4 coefficient_b[i-1] = -((asset_volatility**2*i**2+interest_rate)*time_step_size)/2 coefficient_c[i-1] = ((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/4 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = - \ coefficient_a[grid.number_of_asset_step-2]+coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 - \ coefficient_b[grid.number_of_asset_step-2]-2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -coefficient_c[i] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = coefficient_a[i] matrix_right[i, i+1] = 1+coefficient_b[i] matrix_right[i, i+2] = coefficient_c[i] for i in range(grid.number_of_asset_step+1): option_value[i, 0] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value[i, 0] k = 1 option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value[0, k] vector_right = np.matmul(matrix_right, option_value[:, k-1]) vector_right[0] = vector_right[0]-remainder_vector[0] temp = np.zeros(grid.number_of_asset_step-1) temp2 = np.zeros(grid.number_of_asset_step+1) temp2[0] = option_value[0, k] tol = 0.001 err = strike_price # random big number temp2[1:grid.number_of_asset_step] = list( option_value[1:grid.number_of_asset_step, k-1]) omega = 1.0 number_iteration_old = 1000000000 number_iteration_new = 0 while omega <= 2.0: number_iteration_new = 0 temp2[1:grid.number_of_asset_step] = list( option_value[1:grid.number_of_asset_step, k-1]) temp2[grid.number_of_asset_step] = 0 err = strike_price # random big number while err > tol: err = 0 number_iteration_new = number_iteration_new+1 for i in range(grid.number_of_asset_step-1): temp[i] = (temp2[i+1]+(omega/diagonal[i]) * (vector_right[i]-super_diagonal[i]*temp2[i+2]-diagonal[i] * temp2[i+1]-sub_diagonal[i]*temp2[i])) if excercise_type == "American": temp[i] = max(temp[i], pay_off[i]) err = err + (temp[i]-temp2[i+1])**2 temp2[i+1] = temp[i] temp2[grid.number_of_asset_step] = 2 * \ temp2[grid.number_of_asset_step-1]-temp2[grid.number_of_asset_step-2] if number_iteration_new > number_iteration_old: omega = omega-0.05 break number_iteration_old = number_iteration_new omega = omega+0.05 # end optimal w for k in range(1, grid.number_of_time_step + 1): option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value[0, k] vector_right = np.matmul(matrix_right, option_value[:, k-1]) vector_right[0] = vector_right[0]-remainder_vector[0] temp = np.zeros(grid.number_of_asset_step-1) err = strike_price # random big number option_value[1:grid.number_of_asset_step, k] = option_value[1:grid.number_of_asset_step, k-1] while err > tol: err = 0 for i in range(grid.number_of_asset_step-1): temp[i] = (option_value[i+1, k]+(omega/diagonal[i]) * (vector_right[i]-super_diagonal[i] * option_value[i+2, k] - diagonal[i]*option_value[i+1, k]-sub_diagonal[i] * option_value[i, k])) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) err = err+(temp[i]-option_value[i+1, k])**2 option_value[i+1, k] = temp[i] option_value[grid.number_of_asset_step, k] = 2 * \ option_value[grid.number_of_asset_step-1, k] - \ option_value[grid.number_of_asset_step-2, k] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value[i, k] = max(option_value[i, k], pay_off[i]) return option_value def crankNicolsonSORwithOptimalW_two_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses fully CRANK–NICOLSON finite-difference method. This also uses SOR with optimal w. This is for 1 factor model. For more information refer section 78.3.6 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns one dimensional numpy array of option value for t=0.0 """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros(grid.number_of_asset_step + 1) option_value_new = np.zeros(grid.number_of_asset_step + 1) multiplier = 1 if option_type == "Put": multiplier = -1 coefficient_a = np.zeros(grid.number_of_asset_step-1) coefficient_b = np.zeros(grid.number_of_asset_step-1) coefficient_c = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): coefficient_a[i-1] = ((asset_volatility**2*i**2-interest_rate*i)*time_step_size)/4 coefficient_b[i-1] = -((asset_volatility**2*i**2+interest_rate)*time_step_size)/2 coefficient_c[i-1] = ((asset_volatility**2*i**2+interest_rate*i)*time_step_size)/4 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -coefficient_a[i] sub_diagonal[grid.number_of_asset_step-2] = - \ coefficient_a[grid.number_of_asset_step-2]+coefficient_c[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-coefficient_b[i] diagonal[grid.number_of_asset_step-2] = 1 - \ coefficient_b[grid.number_of_asset_step-2]-2*coefficient_c[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -coefficient_c[i] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = coefficient_a[i] matrix_right[i, i+1] = 1+coefficient_b[i] matrix_right[i, i+2] = coefficient_c[i] for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value_old[i] #k = 1 option_value_new[0] = option_value_old[0]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value_new[0] = max(option_value_new[0], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value_new[0] vector_right = np.matmul(matrix_right, option_value_old[:]) vector_right[0] = vector_right[0]-remainder_vector[0] temp = np.zeros(grid.number_of_asset_step-1) temp2 = np.zeros(grid.number_of_asset_step+1) temp2[0] = option_value_new[0] tol = 0.001 err = strike_price # random big number temp2[1:grid.number_of_asset_step] = list( option_value_old[1:grid.number_of_asset_step]) omega = 1.0 number_iteration_old = 1000000000 number_iteration_new = 0 while omega <= 2.0: number_iteration_new = 0 temp2[1:grid.number_of_asset_step] = list( option_value_old[1:grid.number_of_asset_step]) temp2[grid.number_of_asset_step] = 0 err = strike_price # random big number while err > tol: err = 0 number_iteration_new = number_iteration_new+1 for i in range(grid.number_of_asset_step-1): temp[i] = (temp2[i+1]+(omega/diagonal[i])*( vector_right[i]-super_diagonal[i]*temp2[i+2]-diagonal[i]*temp2[i+1] - sub_diagonal[i]*temp2[i])) if excercise_type == "American": temp[i] = max(temp[i], pay_off[i]) err = err + (temp[i]-temp2[i+1])**2 temp2[i+1] = temp[i] temp2[grid.number_of_asset_step] = 2 * \ temp2[grid.number_of_asset_step-1]-temp2[grid.number_of_asset_step-2] if number_iteration_new > number_iteration_old: omega = omega-0.05 break number_iteration_old = number_iteration_new omega = omega+0.05 # end optimal w for _ in range(1, grid.number_of_time_step + 1):# time(k) loop option_value_new[0] = option_value_old[0]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value_new[0] = max(option_value_new[0], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -coefficient_a[0]*option_value_new[0] vector_right = np.matmul(matrix_right, option_value_old[:]) vector_right[0] = vector_right[0]-remainder_vector[0] temp = np.zeros(grid.number_of_asset_step-1) err = strike_price # random big number option_value_new[1:grid.number_of_asset_step] =\ option_value_old[1:grid.number_of_asset_step] while err > tol: err = 0 for i in range(grid.number_of_asset_step-1): temp[i] = (option_value_new[i+1]+(omega/diagonal[i]) * (vector_right[i]-super_diagonal[i] * option_value_new[i+2]-diagonal[i] * option_value_new[i+1]-sub_diagonal[i]*option_value_new[i])) if excercise_type == "American": option_value_new[0] = max(option_value_new[0], pay_off[0]) err = err+(temp[i]-option_value_new[i+1])**2 option_value_new[i+1] = temp[i] option_value_new[grid.number_of_asset_step] = 2 * \ option_value_new[grid.number_of_asset_step-1] - \ option_value_new[grid.number_of_asset_step-2] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value_new[i] = max(option_value_new[i], pay_off[i]) option_value_old = list(option_value_new) return option_value_new def crank_nicolson_douglas_three_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses CRANK–NICOLSON finite-difference method. This also uses Douglas scheme to improve accuracy. This is for 1 factor model. For more information refer section 78.6 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) time_step_size = grid.expiration_time / grid.number_of_time_step option_value = np.zeros((grid.number_of_asset_step+1, grid.number_of_time_step+1)) multiplier = 1 if option_type == "Put": multiplier = -1 douglas = 0.5-asset_step_size**2/(12*time_step_size) a_left = np.zeros(grid.number_of_asset_step-1) b_left = np.zeros(grid.number_of_asset_step-1) c_left = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): a_left[i-1] = ((asset_volatility**2*i**2-interest_rate*i) * time_step_size*douglas)/2 b_left[i-1] = -((asset_volatility**2*i**2+interest_rate) * time_step_size*douglas) c_left[i-1] = ((asset_volatility**2*i**2+interest_rate*i) * time_step_size*douglas)/2 a_right = np.zeros(grid.number_of_asset_step-1) b_right = np.zeros(grid.number_of_asset_step-1) c_right = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step): a_right[i-1] = ((asset_volatility**2*i**2-interest_rate*i) * time_step_size*(1-douglas))/2 b_right[i-1] = -((asset_volatility**2*i**2+interest_rate) * time_step_size*(1-douglas)) c_right[i-1] = ((asset_volatility**2*i**2+interest_rate*i) * time_step_size*(1-douglas))/2 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -a_left[i] sub_diagonal[grid.number_of_asset_step-2] = - \ a_left[grid.number_of_asset_step-2]+c_left[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-b_left[i] diagonal[grid.number_of_asset_step-2] = 1 - \ b_left[grid.number_of_asset_step-2]-2*c_left[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -c_left[i] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = a_right[i] matrix_right[i, i+1] = 1+b_right[i] matrix_right[i, i+2] = c_right[i] matrix_left = np.diagonal(sub_diagonal[1:], k=-1) + np.diagonal(diagonal[:]) + \ np.diagonal(super_diagonal[0:grid.number_of_asset_step-2], k=1) for i in range(grid.number_of_asset_step+1): option_value[i, 0] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value[i, 0] for k in range(1, grid.number_of_time_step + 1): option_value[0, k] = option_value[0, k-1]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value[0, k] = max(option_value[0, k], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -a_left[0]*option_value[0, k] vector_right = np.matmul(matrix_right, option_value[:, k-1]) vector_right[0] = vector_right[0]-remainder_vector[0] option_value[1:grid.number_of_asset_step, k] = np.linalg.solve(matrix_left, vector_right) option_value[grid.number_of_asset_step, k] = 2 * \ option_value[grid.number_of_asset_step-1, k] - \ option_value[grid.number_of_asset_step-2, k] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value[i, k] = max(option_value[i, k], pay_off[i]) return option_value def crank_nicolson_douglas_two_d(grid, asset_volatility, interest_rate, strike_price, excercise_type="European", option_type="Call"): """This function uses fully CRANK–NICOLSON finite-difference method. This also uses Douglas scheme to improve accuracy. This is for 1 factor model. For more information refer section 78.6 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price interest_rate : float value of the fixed interest rate strike_price : float strike price for the option excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns one dimensional numpy array of option value for t=0.0 """ asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) pay_off = np.zeros(grid.number_of_asset_step+1) asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros(grid.number_of_asset_step + 1) option_value_new = np.zeros(grid.number_of_asset_step + 1) multiplier = 1 if option_type == "Put": multiplier = -1 douglas = 0.5-asset_step_size**2/(12*time_step_size) a_left = np.zeros(grid.number_of_asset_step-1) b_left = np.zeros(grid.number_of_asset_step-1) c_left = np.zeros(grid.number_of_asset_step-1) # from page 1230 for i in range(1, grid.number_of_asset_step): a_left[i-1] = ((asset_volatility**2*i**2-interest_rate*i) * time_step_size*douglas)/2 b_left[i-1] = -((asset_volatility**2*i**2+interest_rate) * time_step_size*douglas) c_left[i-1] = ((asset_volatility**2*i**2+interest_rate*i) * time_step_size*douglas)/2 a_right = np.zeros(grid.number_of_asset_step-1) b_right = np.zeros(grid.number_of_asset_step-1) c_right = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step): a_right[i-1] = ((asset_volatility**2*i**2-interest_rate*i) * time_step_size*(1-douglas))/2 b_right[i-1] = -((asset_volatility**2*i**2+interest_rate) * time_step_size*(1-douglas)) c_right[i-1] = ((asset_volatility**2*i**2+interest_rate*i) * time_step_size*(1-douglas))/2 sub_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(1, grid.number_of_asset_step-2): sub_diagonal[i] = -a_left[i] sub_diagonal[grid.number_of_asset_step-2] = - \ a_left[grid.number_of_asset_step-2]+c_left[grid.number_of_asset_step-2] diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): diagonal[i] = 1-b_left[i] diagonal[grid.number_of_asset_step-2] = 1 - \ b_left[grid.number_of_asset_step-2]-2*c_left[grid.number_of_asset_step-2] super_diagonal = np.zeros(grid.number_of_asset_step-1) for i in range(grid.number_of_asset_step-2): super_diagonal[i] = -c_left[i] matrix_right = np.zeros((grid.number_of_asset_step-1, grid.number_of_asset_step+1)) for i in range(grid.number_of_asset_step-1): matrix_right[i, i] = a_right[i] matrix_right[i, i+1] = 1+b_right[i] matrix_right[i, i+2] = c_right[i] matrix_left = np.diagonal(sub_diagonal[1:], k=-1) + np.diagonal(diagonal[:]) + \ np.diagonal(super_diagonal[0:grid.number_of_asset_step-2], k=1) for i in range(grid.number_of_asset_step+1): option_value_old[i] = max(multiplier*(asset_value[i]-strike_price), 0) pay_off[i] = option_value_old[i] for _ in range(1, grid.number_of_time_step + 1):# time(k) loop option_value_new[0] = option_value_old[0]*(1-interest_rate*time_step_size) if excercise_type == "American": option_value_new[0] = max(option_value_old[0], pay_off[0]) remainder_vector = np.zeros(grid.number_of_asset_step-1) remainder_vector[0] = -a_left[0]*option_value_new[0] vector_right = np.matmul(matrix_right, option_value_old[:]) vector_right[0] = vector_right[0]-remainder_vector[0] option_value_new[1:grid.number_of_asset_step] = np.linalg.solve(matrix_left, vector_right) option_value_new[grid.number_of_asset_step] = 2 * \ option_value_new[grid.number_of_asset_step-1] - \ option_value_new[grid.number_of_asset_step-2] if excercise_type == "American": for i in range(grid.number_of_asset_step+1): option_value_new[i] = max(option_value_new[i], pay_off[i]) option_value_old = list(option_value_new) return option_value_new def two_factor_Explicit(grid, asset_volatility, strike_price, interest_rate_volatility, interest_rate_drift, excercise_type="European", option_type="Call"): """This function uses fully Explicit finite-difference method. This is for 2 factor model. For more information refer section 79.3 Parameters ---------- grid : Grid class object Grid class object for grid asset_volatility : float volatility of asset price strike_price : float strike price for the option interest_rate_volatility : float value of the interest rate volatility interest_rate_drift : float value of the interest rate drift excercise_type : {"European","American"} specify excercise type option_type : {"Call","Put"} specify option type Returns ------- numpy_array returns two dimensional numpy array of option value for t=0.0 """ lamda = 0.1 rho = 0.5 converet_rate = 0.9 asset_value = np.linspace(grid.minimum_asset_value, grid.maximum_asset_value, grid.number_of_asset_step+1) interest_rate_value = np.linspace(grid.minimum_interest_rate_value, grid.maximum_interest_rate_value, grid.number_of_interest_rate_step+1) pay_off = np.zeros( (grid.number_of_asset_step+1, grid.number_of_interest_rate_step+1)) asset_step_size = float( (grid.maximum_asset_value-grid.minimum_asset_value)/grid.number_of_asset_step) interest_rate_step_size = float( (grid.maximum_interest_rate_value-grid.minimum_interest_rate_value) / grid.number_of_interest_rate_step) if((int(grid.expiration_time / (asset_volatility**2*grid.number_of_asset_step**2 + (interest_rate_volatility/interest_rate_step_size)**2))+1) > grid.number_of_time_step): print("numer Of Time Steps Changed for stability.") grid.number_of_time_step = (int( grid.expiration_time / (asset_volatility**2*grid.number_of_asset_step**2))+1) time_step_size = grid.expiration_time / grid.number_of_time_step option_value_old = np.zeros( (grid.number_of_asset_step+1, grid.number_of_interest_rate_step+1)) option_value_new = np.zeros( (grid.number_of_asset_step+1, grid.number_of_interest_rate_step+1)) multiplier = 1 # Dummy = np.zeros((NAS+1,6)) if option_type == "Put": multiplier = -1 print(asset_value) for i in range(grid.number_of_asset_step + 1): for j in range(grid.number_of_interest_rate_step + 1): option_value_old[i, j] = max( multiplier*(asset_value[i]-strike_price), 0) pay_off[i, j] = option_value_old[i, j] for _ in range(1, grid.number_of_time_step + 1):# time(k) loop for i in range(1, grid.number_of_asset_step): for j in range(1, grid.number_of_interest_rate_step): VS = (option_value_old[i+1, j] - option_value_old[i-1, j])/(2*asset_step_size) Vrp = (option_value_old[i, j + 1] - option_value_old[i, j]) / interest_rate_step_size Vrm = ((option_value_old[i, j] - option_value_old[i, j - 1]) / interest_rate_step_size) Vr = Vrm if(interest_rate_drift-lamda*interest_rate_volatility) > 0: Vr = Vrp VSS = ((option_value_old[i + 1, j] - 2 * option_value_old[i, j] + option_value_old[i - 1, j]) / (asset_step_size * asset_step_size)) Vrr = ((option_value_old[i, j + 1] - 2 * option_value_old[i, j] + option_value_old[i, j - 1]) / (interest_rate_step_size * interest_rate_step_size)) VSr = ((option_value_old[i + 1, j + 1] - option_value_old[i - 1, j + 1] - option_value_old[i + 1, j - 1] + option_value_old[i - 1, j - 1]) / (4 * asset_step_size * interest_rate_step_size)) option_value_new[i, j] = (option_value_old[i, j] + time_step_size * (0.5 * asset_value[i] * asset_value[i] * asset_volatility * asset_volatility * VSS + 0.5 * interest_rate_volatility * interest_rate_volatility * Vrr + rho * asset_volatility * interest_rate_volatility * asset_value[i] * VSr + interest_rate_value[j] * (asset_value[i] * VS - option_value_old[i, j]) + (interest_rate_drift-lamda * interest_rate_volatility) * Vr)) for j in range(grid.number_of_interest_rate_step+1): option_value_new[0, j] = 0 option_value_new[grid.number_of_asset_step, j] = 2 * \ option_value_new[grid.number_of_asset_step-1, j] - \ option_value_new[grid.number_of_asset_step-2, j] for i in range(1, grid.number_of_asset_step): option_value_new[i, grid.number_of_interest_rate_step] = asset_value[i] j = 0 VS = (option_value_old[i + 1, j] - option_value_old[i - 1, j])/(2*asset_step_size) Vrp = (option_value_old[i, j + 1] - option_value_old[i, j]) / interest_rate_step_size Vrm = (option_value_old[i, j] - option_value_old[i, j]) / interest_rate_step_size Vr = Vrm if(interest_rate_drift-lamda*interest_rate_volatility) > 0: Vr = Vrp VSS = (option_value_old[i + 1, j] - 2 * option_value_old[i, j] + option_value_old[i - 1, j]) / (asset_step_size * asset_step_size) Vrr = ((option_value_old[i, j + 1] - 2 * option_value_old[i, j] + option_value_old[i, j]) / (interest_rate_step_size * interest_rate_step_size)) VSr = ((option_value_old[i + 1, j + 1] - option_value_old[i - 1, j + 1] - option_value_old[i + 1, j] + option_value_old[i - 1, j]) / (4 * asset_step_size * interest_rate_step_size)) option_value_new[i, j] = (option_value_old[i, j] + time_step_size * (0.5 * asset_value[i] * asset_value[i] * asset_volatility * asset_volatility * VSS + 0.5 * interest_rate_volatility * interest_rate_volatility * Vrr + rho * asset_volatility * interest_rate_volatility * asset_value[i] * VSr + interest_rate_value[j] * (asset_value[i] * VS - option_value_old[i, j]) + (interest_rate_drift-lamda * interest_rate_volatility) * Vr)) for i in range(grid.number_of_asset_step+1): for j in range(grid.number_of_interest_rate_step+1): option_value_old[i, j] = max( option_value_new[i, j], converet_rate*asset_value[i]) if excercise_type == "American": for i in range(grid.number_of_asset_step+1): for j in range(grid.number_of_interest_rate_step+1): option_value_old[i, j] = max( option_value_old[i, j], pay_off[i, j]) # option_value_old = list(option_value_new) return option_value_new
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data if __name__ == '__main__': file = "F:/Data/MNIST" mnist = input_data.read_data_sets(file, one_hot=True) x = tf.placeholder(tf.float32, shape=[None, 784]) output = tf.placeholder(tf.float32, shape=[None, 10]) w = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) session = tf.InteractiveSession() session.run(tf.global_variables_initializer()) y = tf.nn.softmax(tf.matmul(x, w) + b) cross_entropy = -tf.reduce_sum(output*tf.log(y)) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) for i in range(1000): batch = mnist.train.next_batch(50) train_step.run(feed_dict={x: batch[0], output:batch[1]}) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(output, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(session.run(accuracy, feed_dict={x:mnist.test.images, output:mnist.test.labels}))
import pygame #importa funciones especificas de la libreria pygame class Tablero(): # Funcion constrcutra (se ejecuta al crear el objeto) def __init__(self,window,color=(255,255,255)): self._window = window self._window self self._color = color self._recuadros = [] def _newLine(self,init,final,grosor): pygame.draw.line(self._window,self._color,init,final,grosor) def _draw_lines(self): self._newLine((30,30),(630,30),3) self._newLine((30,30),(30,630),3) self._newLine((30,630),(630,630),3) self._newLine((630,30),(630,630),3) self._newLine((230,60),(230,600),1) self._newLine((430,60),(430,600),1) self._newLine((60,240),(600,240),1) self._newLine((60,420),(600,420),1) #Funcion publica para actualizar el estado del tablero def Update(self): self._draw_lines() class Game(): def __init__(self,widht,height,players): self.widht = widht self.height = height self.window = pygame.display.set_up((self.widht,self.height)) def update(self): pygame.display.update()
name_1 = 'karim' name_2 = 'karim' name_3 = 'KARim' name_4 = 'karim' name_5 = 'karim' # find upper letter def find_upper_litter(name): for i in range(len(name)): if name[i].isupper(): return name[i] return 'no upper letters found !' x = find_upper_litter(name_1) x1 = find_upper_litter(name_2) x2 = find_upper_litter(name_3) x3 = find_upper_litter(name_4) x4 = find_upper_litter(name_5) print(x) print(x1) print(x2) print(x3) print(x4)
data = [] for i in range(1,100): data.append(i) target = 22 # linear search def linear_search(data,target): for j in range(len(data)): if data[j]==target: return True return False x = linear_search(data,target) print(x)
import random class Entity(object): def __init__(self, node, max_moves): self.node = node self.alive = True self.max_moves = max_moves def action(self): """What to do after movement""" pass def can_move(self): """Whether there's anything interesting enough in this node to justify stopping""" return True def move(self): """Move/Wander to a new node.""" for i in xrange(self.max_moves): if self.can_move(): retries = 1 # Bears don't go where bears are, lumberjacks don't go where lumberjacks are # If that's where we're headed, retry while (retries >= 0): random_adjacent_node = random.choice(self.node.travel_directions.values()) if not random_adjacent_node.has(type(self)): self.node.move_entity_to_node(self, random_adjacent_node) break retries = retries - 1 if retries == 0: # Stop moving if there don't seem to be enough places to move break def short(self): return type(self).__name__[0]
""" This module contains an interface for the distance measures that are used to compute the distance between two data points in the 'SeqClu' algorithm. """ from abc import ABC, abstractmethod from typing import Union from numpy import ndarray class IDistanceMeasure(ABC): @abstractmethod def calculateDistance(self, sequenceOne: Union[ndarray, list], sequenceTwo: Union[ndarray, list]) -> float: """ This method calculates the distance between two sequences. :param sequenceOne: The first sequence for which the distance should be computed. :param sequenceTwo: The second sequence for which the distance should be computed. :return: The distance between the two sequences. """ pass
def computepay(h, r): if h <= 40: return h*r else: return (r*1.5)*(h-40) + (r*40) hrs = float(input("Enter Hours:")) rate = float(input("Enter Rate:")) p = computepay(hrs, rate) print("Pay", p)
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) count = 0 num = 0 for line in fh: if not line.startswith("X-DSPAM-Confidence:"): continue # line = line.find("0") line = float(line[20:]) count += line num += 1 # print(line) # print(count) # print(num) avg = count/num print("Average spam confidence:", avg)
from string import Template first = int(input("What's the first number? ")) second = int(input("What's the second number? ")) total = first + second diff = first - second product = first * second quotient = first / second output = Template("$first + $second = $sum\n$first - $second = $diff\n" "$first * $second = $product\n$first / $second = $quotient\n") print(output.substitute(first=first, second=second, sum=total, diff=diff, product=product, quotient=quotient))
# Program takes a sequence of DNA, searches for and counts STR repetitions, then cross-references the # results with a table in a CSV file to identify who the DNA sequence belongs to. import csv from sys import argv, exit def main(): # User must provide at least one command line argument, otherwise terminate program if len(argv) != 3: print("Usage: python dna.py data.csv sequence.txt") exit(1) # Open DNA database and store as a list in dna_file variable file_one = open(f"{argv[1]}", 'r') str_list = list(csv.reader(file_one)) # Create a list of all the STRs we need to search for str_search = str_list[0] del str_search[0] # Grab DNA sequence from CSV file and calculate its length sequence_file = open(f"{argv[2]}", "r").read() sequence = sequence_file.split()[0] sequence_length = len(sequence) # Will loop through the DNA sequence once for each STR. Returned each time from the function will be the # highest number of repeats for that particular STR. repeats = [] for i in range(len(str_search)): repeats.append(check_repeats(str_search[i], sequence_length, sequence)) # Create a list of lists - each list will represent a row of the csv file with open(f"{argv[1]}", "r") as file: read_data = csv.reader(file) list_of_rows = list(read_data) # Calculate number of rows in table row_no = len(list_of_rows) # Initialise match variable match = 0 # For each row of the CSV file, loop through the repeats list to see if there are any matches. for x in range(1, row_no, 1): counter = 0 for y in range(0, len(str_search), 1): if repeats[y] == int(list_of_rows[x][y + 1]): counter += 1 if counter == len(str_search): match = x print(list_of_rows[x][0]) break # Print "No match" if there are no exact matches in the data file. if match == 0: print("No match") # Close file(s) file_one.close() # Function to record STR appearances in sequence def check_repeats(the_str, sequence_length, sequence): # Calculate number of characters in the STR, ie 4 in AATG str_chars = len(the_str) # Empty list into which the locations of the STRs in the sequence will be recorded str_starts = [] # Loop through the sequence, recording the location of the first STR character (i.e. A in AATG) # and storing that location in the str_starts list for i in range(sequence_length - str_chars): if the_str in sequence[i:i + str_chars]: str_starts.append(i) # If there was only one instance of the STR in the sequence, simply return 1 if len(str_starts) == 1: return 1 # Set counter variables current_count = 1 highest_count = 0 # Loop through the str_starts list, looking for repeating STRs. When found, begin counting, and update # the highest_count variable. When a new repeating sequence is found, overwrite the previous highest_count # value if it is higher. Always reset current_count when repetition is stopped/not found. for j in range(len(str_starts) - 1): if str_starts[j] + str_chars == str_starts[j + 1]: current_count += 1 if current_count > highest_count: highest_count = current_count elif current_count > highest_count: highest_count = current_count current_count = 1 else: current_count = 1 # If there was more than one instance of the STR in the sequence, look if the repetition occurred at the # end of the sequence. If so add one to the value returned by the function. if len(str_starts) > 1: if str_starts[-1] == sequence[-str_chars]: highest_count += 1 return highest_count if __name__ == "__main__": main()
#!/usr/bin/python import sys import os import math ##################################################################### # Helper functions ##################################################################### # function getNGrams(text, n) # returns all phrases of length n words in text def getNGrams(text, n): ngrams = [] textList = text.split() i = 1 while i <= (len(textList) - n + 1): ngram = " ".join(textList[i:i + n]) ngrams.append(ngram) i+= int(n/4) return ngrams # end def getNGrams() # function readTxtFile(filepath) # returns contents of text file as string def readFile(filepath): fo = open(filepath) return fo.read() # end def readTxtFile() # function percentileThreshold(lst, pct) def percentileThreshold(lst, pct): lst = sorted((lst)) if len(lst) < 1: return None else: return lst[int(math.ceil(len(lst)*pct))] # end def topPct() ##################################################################### # Main Script ##################################################################### path = sys.argv[1] targetfile = sys.argv[2] + ".txt" specificity = int(sys.argv[3]) scoreThreshold = int(sys.argv[4]) filenames = os.listdir(path) os.chdir(path) files = {} for filename in filenames: if filename.endswith("txt"): files.update({filename: getNGrams(str(readFile(filename)).replace("\r\n", " "), specificity)}) targetNGrams = getNGrams(str(readFile(targetfile)).replace("\r\n", " "), specificity) matchedFiles = {} for file1 in files.items(): if (file1[0] != targetfile): matches = list(set(file1[1]) & set(targetNGrams)) score = len(matches) if score >= scoreThreshold: matchedFiles.update({file1[0]: matches}) #end if #end if #end for for file in matchedFiles.items(): print "#####################################################################" print file[0] print "#####################################################################" for i, str in enumerate(file[1]): print str print "" #end for print ""
from decimal import * ''' Initialize the variables ''' darlehen = Decimal(0) zinssatz = Decimal(0) laufzeit = Decimal(0) while Decimal(darlehen)<=0: darlehen = input("Geben Sie bitte die Darlehen ein: (€) ") while Decimal(zinssatz)<=0: zinssatz = input("Geben Sie bitte die Zinssatz ein: (%) ") while Decimal(laufzeit) <= 0: laufzeit = input("Geben Sie bitte die Laufzeit ein: (Jahr) ") jaehrlich = Decimal(darlehen)* (Decimal(zinssatz) / Decimal(100)) insgesamt= (Decimal(jaehrlich) * Decimal(laufzeit))+ Decimal(darlehen) print("Jährlich: ",jaehrlich) print("Gesamt: ", insgesamt)
from move import Move class InputReader(object): def read_move(self): print "Place your move:row,column,number or quit" print "sudoku> ", raw_move = raw_input() # input (he reads what you type) if raw_move == "quit": return Move(0,0,0,True) # returns the instantiation of the class Move else: row_index, col_index, number = raw_move.split(',') # split function returns a list of strings return Move(int(row_index), int(col_index), int(number)) # returns the instantiation of the class Move with the variables above
def factorial(number): if number == 1: print('Base case reached!') return 1 else: print('Finding ', number, ' * ', number - 1, '!', sep='') result = number * factorial(number - 1) print(number, ' * ', number -1, '! = ', result, sep='') return result print('5! is', factorial(5))
#Write a function called add_to_dictionary. add_to_dictionary #should have three parameters: a dictionary, a potential new #key, and a potential new value. # #add_to_dictionary should add the given key and value to the #dictionary if the key is of a legal type to be used as a #dictionary key. # #If the key is a legal type to be used as a dictionary key, #return the resultant dictionary. # #If the key is _not_ a legal type to be used as a dictionary #key, return the string "Error!" # #Remember, only immutable types can be used as dictionary #keys. If you don't remember which types are immutable or #how to check a value's type, don't fret: there's a way #to do this without checking them directly! #Write your function here! #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #{1: "a", 2: "b", 3: "c", 4: "d"} #Error! # a_dictionary = {1: "a", 2: "b", 3: "c"} # print(add_to_dictionary(a_dictionary, 4, "d")) # print(add_to_dictionary(a_dictionary, [4, 5, 6], "e"))
#Write a function called check_value. check_value should #take as input two parameters: a dictionary and a string. #Both the keys and the values in the dictionary will be #strings. The string parameter will be the key to look up in #the dictionary. # #check_value should look up the string in the dictionary and #get its value. Its current value will always be a string; #however, check_value should try to convert it to an integer #and a float, then return a message indicating the success #of those conversions: # # - If the key is not found in the dictionary, check_value # should return the string: "Not found!" # - If the value corresponding to the key can be converted # to an integer, check_value should return the string: # "Integer!" # - Otherwise, if the value corresponding to the key can be # converted to a float, check_value should return the # string: "Float!" # - Otherwise, check_value should return the string: # "String!" # #You do not need to check for any other types. We suggest #using error handling to try to convert the values to the #corresponding data types. # #For example, given this dictionary: # # d = {"k1": "1.1", "k2": "1", "k3": "1.4.6", "k4": "a"} # #Here are some calls and their results: # # - check_value(d, "k1") -> "Float!" # - check_value(d, "k2") -> "Integer!" # - check_value(d, "k3") -> "String!" # - check_value(d, "k4") -> "String!" # - check_value(d, "k5") -> "Not found!" # #Hint: The error that arises when trying to convert a #string to a type it can't convert to (e.g. "ABC" to a #float) is a ValueError. The error that arises when #trying to access a key that doesn't exist in a #dictionary is a KeyError. #Write your function here! #The lines below will test your code. Their output should #match the examples above. d = {"k1": "1.1", "k2": "1", "k3": "1.4.6", "k4": "a"} # print(check_value(d, "k1")) # print(check_value(d, "k2")) # print(check_value(d, "k3")) # print(check_value(d, "k4")) # print(check_value(d, "k5"))
#Imagine you're writing a program to check attendance on a #classroom roster. The list of students in attendance comes #in the form of a list of instances of the Student class. # #You don't have access to the code for the Student class. #However, you know that it has at least two attributes: #first_name and last_name. # #Write a function called check_attendance. check_attendance #should take three parameters: a list of instances of #Student representing the students in attendance, a first #name as a string, and a last name as a string (in that #order). # #The function should return True if any instance in the #list has the same first and last name as the two #arguments. It should return False otherwise. # #You may assume that the list of students is sorted #alphabetically, by last name and then by first name. This #allows you to solve this with a binary search. However, #you may also solve this problem with a linear search if #you would prefer. #Write your function here! #If you would like, you may implement the Student class as #described and use it to test your code. This is not #necessary to complete the problem, but it may help you #debug. If you create a Student class, all you need is #a constructor that assigns values to two attributes: #self.first_name and self.last_name.
#Write a function called to_upper_copy. This function should #take two parameters, both strings. The first string is the #filename of a file to which to write (output_file), and the #second string is the filename of a file from which to read #(input_file). # #to_upper_copy should copy the contents of input_file into #output_file, capitalizing all letters (not just all words, #each individual letter). You may use the .upper() method #from the string class. # #For example, if these were the contents of input_file (the #second parameter): # # This is some text. Yay text. # #Then to_upper_copy would write this text to output_file (the #first parameter): # # THIS IS SOME TEXT. YAY TEXT. # #No other characters should be changed. Note that the file #to be copied will have multiple lines of text. # #We've included two files for you to test on: anInputFile.txt #and anOutputFile.txt. The test code below will copy the text #from the first file to the second. Feel free to modify the #first to test different setups. #Write your function here! #The code below will test your function. You can find the two #files it references in the drop-down in the top left. # to_upper_copy("pp03_output_file.txt", "pp03_input_file.txt") # print("Done running! Check anOutputFile.txt for the result.")
#Copy your Burrito class from the last exercise. Now, add #a method called "get_cost" to the Burrito class. It should #accept zero arguments (except for "self", of course) and #it will return a float. Here's how the cost should be #computed: # # - The base cost of a burrito is $5.00 # - If the burrito's meat is "chicken", "pork" or "tofu", # add $1.00 to the cost # - If the burrito's meat is "steak", add $1.50 to the cost # - If extra_meat is True and meat is not set to False, add # $1.00 to the cost # - If guacamole is True, add $0.75 to the cost # #Make sure to return the result as a float even if the total #is a round number (e.g. for burrito with no meat or #guacamole, return 5.0 instead of 5). #Write your code here! from typing import Union class Burrito: def __init__(self, meat, to_go, rice, beans, extra_meat: bool = False, guacamole: bool = False, cheese: bool = False, pico: bool = False, corn: bool = False) -> None: self.set_meat(meat) self.set_to_go(to_go) self.set_rice(rice) self.set_beans(beans) self.set_extra_meat(extra_meat = extra_meat) self.set_guacamole(guacamole = guacamole) self.set_cheese(cheese = cheese) self.set_pico(pico = pico) self.set_corn(corn = corn) def set_meat(self, meat: str) -> None: valid_meat = ["chicken", "pork", "steak", "tofu"] self.meat = meat if meat in valid_meat else False def set_to_go(self, to_go: bool) -> None: self.to_go = to_go if isinstance(to_go, bool) else False def set_rice(self, rice: str) -> None: valid_rice = ["brown", "white"] self.rice = rice if rice in valid_rice else False def set_beans(self, beans: str) -> None: valid_beans = ['black', 'pinto'] self.beans = beans if beans in valid_beans else False def set_extra_meat(self, extra_meat: bool) -> None: self.extra_meat = extra_meat if isinstance(extra_meat, bool) else False def set_guacamole(self, guacamole: bool) -> None: self.guacamole = guacamole if isinstance(guacamole, bool) else False def set_cheese(self, cheese: bool) -> None: self.cheese = cheese if isinstance(cheese, bool) else False def set_pico(self, pico: bool) -> None: self.pico = pico if isinstance(pico, bool) else False def set_corn(self, corn: bool) -> None: self.corn = corn if isinstance(corn, bool) else False def get_meat(self) -> Union[str, bool]: return self.meat def get_to_go(self) -> bool: return self.to_go def get_rice(self) -> Union[str, bool]: return self.rice def get_beans(self) -> Union[str, bool]: return self.beans def get_extra_meat(self) -> bool: return self.extra_meat def get_guacamole(self) -> bool: return self.guacamole def get_cheese(self) -> bool: return self.cheese def get_pico(self) -> bool: return self.pico def get_corn(self) -> bool: return self.corn def get_cost(self) -> float: cost = 5.00 if self.get_meat() in ['chicken', 'pork', 'tofu']: cost += 1.00 elif self.get_meat() == 'steak': cost += 1.50 if self.get_extra_meat(): cost += 1.00 if self.get_guacamole(): cost += 0.75 return cost #Below are some lines of code that will test your class. #You can change the value of the variable(s) to test your #class with different inputs. # #If your function works correctly, this will originally #print: 7.75 a_burrito = Burrito("pork", False, "white", "black", extra_meat = True, guacamole = True) print(a_burrito.get_cost())
#Write a function called not_list. not_list should have two #parameters: a list of booleans and a list of integers. # #The list of integers will represent indices for the list of #booleans. not_list should switch the values of all the #booleans located at those indices. # #For example: # # bool_list = [True, False, False] # index_list = [0, 2] # not_list(bool_list, index_list) -> [False, False, True] # #After calling not_list, the booleans at indices 0 and 2 #have been switched. # #Note that it may be the case that the same index is present #in the second twice. If this happens, you should switch the #boolean at that index twice. For example: # # bool_list = [True, False, False] # index_list = [0, 2, 2] # not_list(bool_list, index_list) -> [False, False, False] # #2 is in index_list twice, so the boolean at index 2 is #switched twice: False to True, then True back to False. # #Hint: Remember you can change a list in place! You don't #need to create a new list. a_list[1] = False, for example, #changes the item in a_list at index 1 to False. #Write your function here! #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #[False, False, True] #[False, False, False] # print(not_list([True, False, False], [0, 2])) # print(not_list([True, False, False], [0, 2, 2]))
#Last problem, you wrote a function that generated the all- #time win-loss-tie record for Georgia Tech against any other #team. # #That dataset had a lot of other information in it. Let's #use it to answer some more questions. As a reminder, the #data will be a CSV file, meaning that each line will be a #comma-separated list of values. Each line will describe one #game. # #The columns, from left-to-right, are: # # - Date: the date of the game, in Year-Month-Day format. # - Opponent: the name of the opposing team # - Location: Home, Away, or Neutral # - Points For: Points scored by Georgia Tech # - Points Against: Points scored by the opponent #Here Below, add any code you want to allow you to answer the #questions asked below over on edX. This is just a sandbox #for you to explore the dataset: nothing is required for #submission here. # --------------------------------------------------------------------------- # from all-time football history CVS file (data set) of Georgia Tech # you'll be asked to return statistics about a certain opponent # team from the data set. # each opponent team should has the following statistics: # games_list with each game has the following: # [date, opponent, place, points for Georgia Tech, points against Georgia Tech], # total wins, home wins, away wins, neutral wins, # total losses, home losses, away losses, neutral losses, # total ties, home ties, away ties, neutral ties, # points for, points against. # # Question 1: what is the total Points scored by Georgia Tech team against Auburn team. # Questoin 2: what is the total Points scored by Auburn team against Georgia Tech team. # Questoin 3: what is the Earliest (first) game ever Georgia Tech team played. # Question 4: give the home record for all games. # Question 5: give the record of the year 2009 for all games. # Question 6: give the record of October months for all games. #This line will open the file: # record_file = open('../resource/lib/public/georgia_tech_football.csv', 'r') from typing import Dict, List, Union from pprint import pprint import datetime def get_games_info(file_name: str) -> Dict[str, Dict[str, Union[int, List[list]]]]: with open(file_name) as record_file: record = record_file.read().split('\n')[1:] statistics = {} for game in record: row = game.split(',') opponent_name = row[1] row[3], row[4] = int(row[3]), int(row[4]) if opponent_name not in statistics.keys(): statistics[opponent_name] = {'games': [], 'total wins': 0, 'home wins': 0, 'away wins': 0, 'neutral wins': 0, 'total losses': 0, 'home losses': 0, 'away losses': 0, 'neutral losses': 0, 'total ties': 0, 'home ties': 0, 'away ties': 0, 'neutral ties': 0, 'points for': 0, 'points against': 0} opponent_info = statistics[opponent_name] if row[3] > row[4]: opponent_info['total wins'] += 1 row.append('win') if row[2] == 'Home': opponent_info['home wins'] += 1 elif row[2] == 'Away': opponent_info['away wins'] += 1 else: opponent_info['neutral wins'] += 1 elif row[3] == row[4]: opponent_info['total ties'] += 1 row.append('tie') if row[2] == 'Home': opponent_info['home ties'] += 1 elif row[2] == 'Away': opponent_info['away ties'] += 1 else: opponent_info['neutral ties'] += 1 else: opponent_info['total losses'] += 1 row.append('loss') if row[2] == 'Home': opponent_info['home losses'] += 1 elif row[2] == 'Away': opponent_info['away losses'] += 1 else: opponent_info['neutral losses'] += 1 opponent_info['points for'] += row[3] opponent_info['points against'] += row[4] statistics[opponent_name]['games'].append(row) # statistics[opponent_name] = opponent_info return statistics history_file_path = 'Final_Problem_Set\\Raw_files\\georgia_tech_football.csv' # season_file_path for test # season_file_path = 'Final_Problem_Set\\Raw_files\\season_2016.csv' # pprint(get_games_info(history_file_path)) def earliest_game(statistics: dict) -> dict: first_game = {'team': '', 'date': None} for key in statistics: games = sorted(statistics[key]['games']) game1 = games[0][0] game1 = datetime.datetime(int(game1[0:4]), int(game1[5:7].lstrip('0')), int(game1[8:10].lstrip('0'))).strftime('%Y-%m-%d') if first_game['date'] is None: first_game['date'] = game1 first_game['team'] = key elif game1 < first_game['date']: first_game['date'] = game1 first_game['team'] = key return first_game team_info = get_games_info(history_file_path) # Question 1: what is the total Points scored by Georgia Tech team against Auburn team # Answer: Auburn points for 1327 print ('Auburn points for {0}'.format(team_info['Auburn']['points for'])) # Questoin 2: what is the total Points scored by Auburn team against Georgia team # :Answer: Auburn points against 1143 print ('Auburn points against {0}'.format(team_info['Auburn']['points against'])) # Questoin 3: what is the Earliest (first) game ever Georgia Tech team played # Answer: Earliest game was 1902-10-11 against Auburn first_game = earliest_game(team_info) print(f'Earliest (first) game ever played was {first_game["date"]} against {first_game["team"]}') # Question 4: give the home record for all games. # Answer: Home record: 513-226-27 home_wins, home_losses, home_ties = 0, 0, 0 for key in team_info.keys(): home_wins += team_info[key]['home wins'] home_losses += team_info[key]['home losses'] home_ties += team_info[key]['home ties'] print(f'Home record -> Home wins: {home_wins} - Home losses: {home_losses} - Home ties: {home_ties}') # Question 5: give the record of the year 2009 for all games. # Answer: 2009 record: 11-3-0 home_wins_09, home_losses_09, home_ties_09 = 0, 0 , 0 for team in team_info: for game in team_info[team]['games']: if game[0][0:4] == '2009': if 'win' in game: home_wins_09 += 1 elif 'loss' in game: home_losses_09 += 1 else: home_ties_09 += 1 print(f'2009 record -> Home wins: {home_wins_09} - Home losses: {home_losses_09} - Home ties: {home_ties_09}') # Question 6: give the record of October months for all games. # Answer: Oct record: 302-177-10 oct_wins, oct_losses, oct_ties = 0, 0, 0 for team, info in team_info.items(): for game in info['games']: game_date = game[0] if datetime.datetime(int(game_date[:4]), int(game_date[5:7].lstrip('0')), int(game_date[8:10])).date().month == 10: if 'win' in game: oct_wins += 1 elif 'loss' in game: oct_losses += 1 else: oct_ties += 1 print(f'October record -> Oct wins: {oct_wins} - Oct losses: {oct_losses} - Oct ties: {oct_ties}') # Question 6: give the record of years in range(1932 + 1, 1964) for all games. # Answer: range_win, range_looses, range_ties = 0, 0, 0 for team, info in team_info.items(): for game in team_info[team]['games']: game_date = game[0] # game_date = if 1964 > datetime.datetime(int(game_date[:4]), int(game_date[5:7].lstrip('0')), int(game_date[8:10])).date().year > 1932: if 'win' in game: range_win += 1 elif 'loss' in game: range_looses += 1 else: range_ties += 1 print(f'years range(1933, 1964) record -> range wins: {range_win} - range losses: {range_looses} - range ties: {range_ties}')
# CMPS 101 # HW7 # Andres Segundo # Tarum Fraz import copy import collections import heapq import time import os class Graph(object): # Initializing empty graph def __init__(self): self.adj_list = dict() # Initial adjacency list is empty dictionary self.vertices = set() # Vertices are stored in a set self.degrees = dict() # Degrees stored as dictionary # Checks if (node1, node2) is edge of graph. Output is 1 (yes) or 0 (no). def isEdge(self,node1,node2): if node1 in self.vertices: # Check if node1 is vertex if node2 in self.adj_list[node1]: # Then check if node2 is neighbor of node1 return 1 # Edge is present! if node2 in self.vertices: # Check if node2 is vertex if node1 in self.adj_list[node2]: # Then check if node1 is neighbor of node2 return 1 # Edge is present! return 0 # Edge not present! # Add undirected, simple edge (node1, node2) def addEdge(self,node1,node2): # print('Called') if node1 == node2: # Self loop, so do nothing # print('self loop') return if node1 in self.vertices: # Check if node1 is vertex nbrs = self.adj_list[node1] # nbrs is neighbor list of node1 if node2 not in nbrs: # Check if node2 already neighbor of node1 nbrs.add(node2) # Add node2 to this list self.degrees[node1] = self.degrees[node1]+1 # Increment degree of node1 else: # So node1 is not vertex self.vertices.add(node1) # Add node1 to vertices self.adj_list[node1] = {node2} # Initialize node1's list to have node2 self.degrees[node1] = 1 # Set degree of node1 to be 1 if node2 in self.vertices: # Check if node2 is vertex nbrs = self.adj_list[node2] # nbrs is neighbor list of node2 if node1 not in nbrs: # Check if node1 already neighbor of node2 nbrs.add(node1) # Add node1 to this list self.degrees[node2] = self.degrees[node2]+1 # Increment degree of node2 else: # So node2 is not vertex self.vertices.add(node2) # Add node2 to vertices self.adj_list[node2] = {node1} # Initialize node2's list to have node1 self.degrees[node2] = 1 # Set degree of node2 to be 1 # Give the size of the graph. Outputs [vertices edges wedges] # def size(self): n = len(self.vertices) # Number of vertices m = 0 # Initialize edges/wedges = 0 wedge = 0 for node in self.vertices: # Loop over nodes deg = self.degrees[node] # Get degree of node m = m + deg # Add degree to current edge count wedge = wedge+deg*(deg-1)/2 # Add wedges centered at node to wedge count return [n, m, wedge] # Return size info # Print the graph def output(self,fname,dirname): os.chdir(dirname) f_output = open(fname,'w') for node1 in list(self.adj_list.keys()): f_output.write(str(node1)+': ') for node2 in (self.adj_list)[node1]: f_output.write(str(node2)+' ') f_output.write('\n') f_output.write('------------------\n') f_output.close() def path(self, start, end): visit = collections.deque() # A queue to collect the nodes in graph we have visited queue = collections.deque() # originial queue to place all of the nodes queue.append([start]) # Add the source to the queue while queue: path = queue.popleft() # First path in the txt file node = path[-1] # We want to extract the last node in the path if node == end: # If we have reached the end of it return list(path) # Add it to the list elif node not in visit: # if the node is not in the queue of visited nodes for currNode in self.adj_list.get(node, []): path2 = collections.deque(path) # Create NEW path path2.append(currNode) # Add the current node to it queue.append(list(path2)) # Append it with the lsit visit.append(node) # Put the node in the visited list def levels(self, start): visit, q = collections.deque(), set([start]) # Make 2 queues, one for initial and one for visited lev = [0, 0, 0, 0, 0, 0, 0] # Initial array of all of the levels we have visited count = 0 # We will use a counter to count the nodes at each level while q: # While the queue is not empty nextLev=set() # Create a new empty set for the next level for node in q - set(visit): # for all of the nodes that are in the set lev[count] = lev[count] + 1 # keep adding at each level visit.append(node) # Add to the visited node so we know we have been there nextLev = nextLev | set(self.adj_list.get(node, [])) - set(visit) # Go to the next level q = nextLev # We need the queue for the bext level count = count + 1 # Iterate the counter return lev # Return all of the levels
def reverse(S): if S=='': return '' else: return S[-1] + reverse(S[:-1]) print reverse('Ryan')
f = open("goodStuff.txt") linesList = f.readlines() f.close() print linesList newList=[] # A new list! for line in linesList: # for each line in our linesList... newList.append(line[:-1]) # ... slice off the last character and append the truncated string to the newList print newList
#coding:utf-8 radius = input("请输入半径: ") area = radius * radius * 3.14159 #Display results print "结果:" #正常情况 print "半径为",radius,"的圆面积为", area #去处之间空格 print "半径为"+str(radius)+"的圆面积为"+str(area)
"""programa que crea el resumen de una contrasenya""" from Crypto.Hash import SHA256 CLAU = input("ingrese una contraseña: ") CLAU = CLAU.encode("UTF-8") OBJH = SHA256.new(CLAU) RESUM = OBJH.digest() IV = b"1234567887654321" print(OBJH.hexdigest())
#!/usr/bin/python3 import csv def readData(fileName): """Reads existing data file and returns contents. Args: fileName: string; name of file to read. Returns: List of lists of strings; with all data previously recorded.""" history = [] with open(fileName, newline='') as csvfile: reader = csv.reader(csvfile) for row in reader: history.append(row) return history def writeData(fileName, dataToWrite): """Appends values in CSV format to an output file. Args: dataToWrite: list of strings; containg all data to be written to file. Returns: None """ with open(fileName, 'a', newline='') as csvfile: writer = csv.writer(csvfile, 'excel') writer.writerow(dataToWrite)
from dataclasses import dataclass from math import sqrt from typing import Optional @dataclass class Point: x: float y: float previous_point: Point = Point(0, 0) length = 0 number = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'nineth', 'tenth'] def find_distance(distance, first_point: Point, second_point: Point) -> float: sum = (first_point.x - second_point.x) ** 2 + (first_point.y - second_point.y) ** 2 distance += sqrt(sum) print(f'The length of your line is {distance}') return distance n = int(input('Please enter the number of points: ')) for i in range(n): print(f'Enter the coordinates of the {number[i]} point: ') point = Point(*list(map(float, input("> ").split()))) find_distance(length, point, previous_point) previous_point = point
# -*- coding:utf-8 -*- """ 作者:lby 日期:2020年11月08日 """ class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ # 暴力破解法(超出时间限制) # if len(s) < 2: # return s # max = s[0] # for i in range(len(s)): # for j in range(i + 1, len(s)+1): # zs = s[i:j] # rs = zs[::-1] # if zs == rs and len(rs) > len(max): # max = rs # return max # 动态规划法 num = len(s) dp = [[False] * num for _ in range(num)] ans = "" for l in range(num): for i in range(num): j = i + l if j >= len(s): break if l == 0: dp[i][j] = True elif l == 1: dp[i][j] = (s[i] == s[j]) else: dp[i][j] = (dp[i + 1][j - 1] and s[i] == s[j]) if dp[i][j] and l + 1 > len(ans): ans = s[i:j + 1] return ans
# -*- coding:utf-8 -*- """ 作者:lby 日期:2020年12月24日 """ class Solution(object): def xorOperation(self, n, start): """ :type n: int :type start: int :rtype: int """ result = 0 for i in [start + 2 * i for i in range(n)]: result ^= i return result
##The following code is based on Fig.12.2. in John Guttag's book. Class Item defines name, value and weight attribute for each item.## class Item(object): def __init__(self,n,v,w): self.name=n self.value=v self.weight=w def getName(self): return self.name def getValue(self): return self.value def getWeight(self): return self.weight def __str__(self): result='<'+self.name+','+str(self.value)\ +','+str(self.weight)+'>' return result ##The following are functions based on class Item above## def value(item): return item.getValue() def weightInverse(item): return 1.0/item.getWeight() def density(item): return item.getValue()/item.getWeight()
#Sum of all items in a list list=[1,2,5,6,8,7,9,11] print(list) sum=0 for i in list: sum=sum+i print("Sum of the list is",sum)
#Work with built-in packages import math num = int(input("Enter a number: ")) p = int(input("Enter the power: ")) print(num,"to the power of", p, " is: ", math.pow(num, p)) print("Square root of ", p, " is: ", math.sqrt(num))
import random MINIMUM = 1 MAXIMUM = 45 NUMBERS_PER_LINE = 6 def main(): number_of_quick_picks = int(input("How many quick picks? ")) for i in range(number_of_quick_picks): row_numbers_generated = calculate_row_numbers() row_numbers_generated.sort() print(" ".join("{:2}".format(number) for number in row_numbers_generated)) def calculate_row_numbers(): numbers = [] for i in range(NUMBERS_PER_LINE): number = random.randint(MINIMUM, MAXIMUM) while number in numbers: number = random.randint(MINIMUM, MAXIMUM) numbers.append(number) return numbers main()
''' ************* * * * * * * ************* ''' def boxPrint(symbol, width, height): if len(symbol) != 1: raise Exception('"symbol" needs to a string of length 1.') if (width < 2) or (height < 2): raise Exception('"width" and "height" must be greater than or equal to 2.') print(symbol * width) for i in range(height - 2): print(symbol + (' ' * (width - 2 )) + symbol) print(symbol * width) boxPrint('#*', 8, 4)
## Assignment 1 ## # Importing the data # import pandas as pd king = pd.read_csv('https://raw.githubusercontent.com/mcanela-iese/' + 'DataSci_Course/master/Data/king.csv') # Linear regression model (class) # from sklearn import linear_model lm = linear_model.LinearRegression() y = king['price'] X = king[['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'waterfront', 'condition', 'sqft_above', 'yr_built', 'yr_renovated', 'lat', 'long']] lm.fit(X, y) king['pred1'] = lm.predict(X) r1 = king[['price', 'pred1']].corr().iloc[0, 1] r1.round(3) # Scatter plot (class) # plt.figure(figsize=(6,6)) plt.scatter(king['pred1']/10**3, king['price']/10**3, color='0.3', s=1) plt.title('Figure 1. Actual vs predicted price (class)') plt.xlabel('Predicted price (thousands)') plt.ylabel('Actual price (thousands)') plt.show() # Linear regression model (log scale) # import numpy as np lm.fit(X, np.log(y)) king['pred2'] = np.exp(lm.predict(X)) r2 = king[['price', 'pred2']].corr().iloc[0, 1] r2.round(3) # Scatter plot (log scale) # plt.figure(figsize=(6,6)) plt.scatter(king['pred2']/10**3, king['price']/1000, color='0.3', s=1) plt.title('Figure 2. Actual vs predicted price (log scale)') plt.xlabel('Predicted price (thousands)') plt.ylabel('Actual price (thousands)') plt.show() # Rescaling the plot # plt.figure(figsize=(6,6)) plt.scatter(king['pred2']/10**3, king['price']/10**3, color='0.3', s=1) plt.title('Figure 2bis. Actual vs predicted price (log scale)') plt.xlabel('Predicted price (thousands)') plt.ylabel('Actual price (thousands)') plt.xlim(0, 5*10**3) plt.ylim(0, 5*10**3) plt.show() # Direct evaluation of the prediction error (absolute terms) # king['error1'] = king['price'] - king['pred1'] (king['error1']/10**3).describe().round() king['error2'] = king['price'] - king['pred2'] (king['error2']/10**3).describe().round() # Direct evaluation of the prediction error (relative terms) # (king['error1']/king['price']).describe().round(3) (king['error2']/king['price']).describe().round(3) # Trimming the data # trim = (king['price'] > 10**4) & (king['price'] < 10**6) king = king[trim] y = king['price'] X = king[['bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors', 'waterfront', 'condition', 'sqft_above', 'yr_built', 'yr_renovated', 'lat', 'long']] lm.fit(X, y) king['pred3'] = lm.predict(X) r3 = king[['price', 'pred3']].corr().iloc[0, 1] r3.round(3) king['error3'] = king['price'] - king['pred3'] (king['error3']/10**3).describe().round() (king['error3']/king['price']).describe().round(3)
# -*- coding: utf-8 -*- """ ***** STUDENT MANAGEMENT SYSTEM ***** """ import sys lessons = ["A", "B", "C", "D", "E"] list0 = [] student = "Serkan Toraman" i = 0 while i<3: name = input("Name Surname: ") if name == student: print(f'\n Welcome {name}\n') break else: i=i+1 print("Failed.") if i==3: print("Please try again later...") sys.exit() print("Lessons: ", lessons) #Choose your lessons!!! x = 0 while x<5: L = input("Choose your lesson: ") L=L.upper() if L in lessons: list0.append(L) x=x+1 elif L == "Q": if len(list0)<3: print(list0, "\nYou failed in class") sys.exit() else: print("Wrong choice, choose true one") if x<len(list0): print(list0, "You failed in class!!!") elif x>=len(list0): print(list0) sL = input("Select Your Lesson: ") sL = sL.upper() print( "\n", sL, "\n") if sL in list0: grades = {"Midterm":45, "Final":70, "Project":80} Total_Grade = (grades["Midterm"]*0.30 + grades["Final"]*0.50 + grades["Project"]*0.20) if Total_Grade >= 90: print("Total Grade: ",Total_Grade, "AA") elif Total_Grade>=70 and Total_Grade<90: print("Total Grade:",Total_Grade, "BB") elif Total_Grade>=50 and Total_Grade<70: print("Total Grade:",Total_Grade, "CC") elif Total_Grade>=30 and Total_Grade<50: print("Total Grade:",Total_Grade, "DD") elif Total_Grade<30: print("Total Grade:",Total_Grade, "FF", "\nFailed!!!") else: print("Wrong choice, choose true one")
def bubble_sort(l): for i in range(len(l)): for j in range(len(l)-1): if l[i] < l[j]: l[i], l[j] = l[j] , l[i] return l
# ***Notes from class*** # CAT # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z # 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 # Shift = 3 # C = F # A = D # T = W # set a message # get a message # set shift # encrypt message # decrypt message! # print message - getter # Obfuscation - hiding it in plain sight; only one step to do conversion. class shiftCipher(object): def __init__(self): self.plainText = 'None' self.cipherText = 'None' self.cleanText = 'None' self.shift = 3 #**************************************************************************************** # Name: getUserMessage # Description: Prompts the user for message from standard in # Parameters: None #**************************************************************************************** def getUserMessage(self): temp = input("Message: ") self.setMessage(temp) #**************************************************************************************** # Name: setMessage # Description: Sets plainText and then cleans and calls encrypt # Parameters: # message (string): String message # encrypted (bool): False = plainText #**************************************************************************************** def setMessage(self, message, encrypted = False): if (not encrypted): self.plainText = message self.cleanData() self.__encrypt() else: self.chipherText = message self.__decrypt() def getPlainText(self): return self.plainText def getCipherText(self): return self.cipherText def setShift(self, shift): self.shift = shift def getShift(self): return self.shift def cleanData(self): self.cleanText = '' for letter in self.plainText: if (not((ord(letter) > 47 and ord(letter) < 58) or (ord(letter) > 64 and ord(letter) < 91) or (ord(letter) > 96 and ord(letter) < 123))): continue if ord(letter) > 96: self.cleanText += chr(ord(letter) - 32) else: self.cleanText += letter def __encrypt(self): self.cipherText = '' if (not self.plainText): return # For each character to be cleaned... for letter in self.cleanText: # ...if it is a letter (a - z, or A - Z), then encrypt if ((ord(letter) > 64 and ord(letter) < 91) or (ord(letter) > 96 and ord(letter) < 123)): self.cipherText += chr((((ord(letter) + self.shift) - 65) % 26) + 65) # ...if it is a number (0 - 9), then encrypt elif (ord(letter) > 47 and ord(letter) < 58): self.cipherText += chr((((ord(letter) + self.shift) - 48) % 10) + 48) def __decrypt(self): self.cleanText = '' # For each character to be cleaned... for letter in self.cipherText: # ...if it is a letter (a - z, or A - Z), then decrypt if ((ord(letter) > 64 and ord(letter) < 91) or (ord(letter) > 96 and ord(letter) < 123)): self.cleanText += chr((((ord(letter) - self.shift) - 65) % 26) + 65) # ...if it is a number (0 - 9), then decrypt elif (ord(letter) > 47 and ord(letter) < 58): self.cleanText += chr((((ord(letter) - self.shift) - 48) % 10) + 48) alice = shiftCipher() alice.getUserMessage() # DEBUGGING # print ("\n***Showing values for Alice***") # print ("Plain Text: " + alice.plainText) # print ("Clean Text: " + alice.cleanText) # print ("Cipher Text: " + alice.cipherText) # rint ("Shift: %d" % (alice.shift)) bob = shiftCipher() bob.cipherText = alice.getCipherText() # DEBUGGING # print ("\n***Showing values for Bob BEFORE setting message***") # print ("Plain Text: " + bob.plainText) # print ("Clean Text: " + bob.cleanText) # print ("Cipher Text: " + bob.cipherText) # print ("Shift: %d" % (bob.shift)) bob.setMessage(bob.cipherText, True) # DEBUGGING # print ("\n***Showing values for Bob AFTER setting message***") # print ("Plain Text: " + bob.plainText) # print ("Clean Text: " + bob.cleanText) # print ("Cipher Text: " + bob.cipherText) # print ("Shift: %d" % (bob.shift))
from tkinter import * root = Tk(className = "button_click_label") root.geometry("200x200") message = StringVar() message.set('hi') l1 = Label(root, text="hi") def press(): l1.config(text="hello") b1 = Button(root, text = "clickhere", command = press).pack() l1.pack() root.mainloop()
""" Binary search algorithm, iterative implementation. A binary search is a method to quickly find a given item in a sorted list. It's important the input list is sorted, or the binary search algorithm won't be useful at all. Sorted lists are things like alphabets (because "A" is always before "B," and so on), or number lines (because "1" is always before "2," and so on). """ from math import floor # We're gonna need to round down. def binary_search_iterative(stuff, item): """ Return the index of ``item`` in ``stuff`` using binary search. Args: stuff (list): A Python list that has already been sorted. item: The value of the item to search for (not its index). Returns: The index of ``item`` or ``None`` if ``item`` is not found. >>> binary_search_iterative([1, 2, 3, 4, 5, 6, 7, 8], 8) Guess number 1 is 4 Guess number 2 is 6 Guess number 3 is 7 Guess number 4 is 8 7 Notice that the final return value is 7, not 8, because Python list indexes start counting from position number 0, not number 1. """ # We will be keeping track of a range of positions instead of # looking at position 0 and then looking at position 1, so we need # to keep track of the lowest and highest positions of that range, # not just the current spot in the list of stuff we're looking at. # The low position always starts at 0. low = 0 # The high position is however much stuff we're looking through. high = len(stuff) - 1 # We also keep track of how many guesses we're making to find it. guess_number = 0 # (This is just for our own edification.) # Eventually, `low` and `high` will converge, because we'll keep # shrinking the range by half (hence, "*binary* search") until we # find the item we're looking for. After each guess, we'll loop # (that is, we'll iterate) over the same list in a narrower range. while low <= high: # The middle spot of our range is always going to be the # current value of low plus high, divided by two. mid = int(floor((low + high) / 2)) # round down, just in case. guess = stuff[mid] # That middle spot will be our next guess, guess_number = guess_number + 1 # so let's count our guesses. # How many guesses have we made so far? print("Guess number " + str(guess_number) + " is " + str(guess)) if guess == item: # If this is the correct guess, return mid # then we've found the item! Yay! :) # If we haven't found the item yet, then our guess was either # too low or too high. Thankfully, our list of stuff is sorted # so, if the guess was too high if guess > item: # then we know the item we're looking for is in the lower # half of our range. This means we can set the high end of # our range to the middle position of our last guess. We # also subtract 1 since we know our last guess was wrong. high = mid - 1 else: # On the other hand, if the guess was too low, then we # know the item is in the higher half of our range, so we # set the low end of our range to the middle position of # our last guess, instead. low = mid + 1 # If we still haven't found the item, then it's not in the list! return None if __name__ == "__main__": num = int(input('Enter a number between 1 and 100: ')) binary_search_iterative(range(1, 101), num)
getal1 = int(input("Geef getal 1 in: ")) getal2 = int(input("Geef getal 2 in: ")) code = int(input("Geef een code in: ")) if code == 1: print(getal1 + getal2) elif code == 2: print(getal1 - getal2) elif code == 3: print(getal1 * getal2) elif code == 4: print(getal1 ** 2) elif code == 5: print(getal2 ** 2) else: print("Foutieve code")
def print_gelijkenissen(): tekst1 = "Georgiouszen" tekst2 = "Giogriiuzzin" for i in range(len(tekst1)): # van 0 tot lengte van "Georgi" if tekst1[i] in tekst2: # als er een letter van "Georgi" terugkomt in "Giogri" for j in range(len(tekst2)): # van 0 tot lengte van "Giogri" if tekst1[i] == tekst2[j] and i == j: # als letters gelijk zijn en indexen "i en j" gelijk zijn print("Letter: " + tekst1[i] + "\nIndex: " + str(i)) def main(): print_gelijkenissen() if __name__ == '__main__': main()
import math diameter_wiel = int(input("Geef de diameter van een wiel in: ")) afgelegde_weg_omwenteling = diameter_wiel * math.pi * 0.0254 print("De omwenteling van het wiel is: " + str(int((afgelegde_weg_omwenteling * 100) + 0.5) / 100))
som = 0 for i in range(28): leeftijd = int(input("Geef leeftijd van student " + str(i+1) + " in: ")) som += leeftijd gemiddelde = som / (i + 1) print("Gemiddelde leeftijd " + str(gemiddelde) + ".")
def teken_rand_rechthoek(aantal_tekens, aantal_rijen): for i in range(aantal_rijen): if i == 0: print("* " * aantal_tekens, end="") print() elif i == aantal_rijen - 1: print("* " * aantal_tekens, end="") else: print("* " + " " * (aantal_tekens - 2) + "*") def main(): aantal_tekens = int(input("Geef het aantal tekens per rij in: ")) aantal_rijen = int(input("Geef het aantal rijen in: ")) teken_rand_rechthoek(aantal_tekens, aantal_rijen) if __name__ == '__main__': main()
def print_driehoek(grootte, begin_letter): tekst = "" for i in range(0, grootte + 1): for j in range(0, i): tekst += chr(ord(begin_letter)) begin_letter = chr(ord(begin_letter) + 1) if ord(begin_letter) > 90: begin_letter = "A" print(tekst) tekst = "" print() def main(): grootte = int(input("Geef grootte in: ")) letter = input("Geef het beginletter in: ") print_driehoek(grootte, letter) if __name__ == '__main__': main()
hoogte = int(input("Geef de grootte van de driehoek in: ")) for i in range(hoogte, 0, -1): print("@" * i)
from typing import Any, Dict, List, Iterable, Optional, Tuple ProductDict = Dict[str, Any] # Initialise an empty list to store product records in product_records: List[ProductDict] = [] def get_product_by_id(product_id: str) -> Optional[ProductDict]: product = next( ( prod for prod in product_records if prod['id'] == product_id ), None ) return product def get_products(page, page_size) -> Tuple[List[ProductDict], int]: start = (page - 1) * page_size end = start + page_size number_of_records = len(product_records) if start > number_of_records: products = [] if end > number_of_records: end = number_of_records products = product_records[start:end] else: products = product_records[start:end] return products, len(product_records) def store_products(products: Iterable[ProductDict]) -> None: product_records.extend(products) def sort_stored_products() -> None: """ Sort stored products by cheapest first, None (null) is assumed as high since price is not known. """ product_records.sort(key=_product_price) def _product_price(product: ProductDict) -> float: price = product['price'] if price is None: return 1E10 return price
''' Este script grafica la superficie de un toro con ecuacion z^2 + (sqrt(x^2+y^2)-3)^2 = 1 y la superficie de un cilindro con ecuacion (x-2)^2 + z^2 = 1. ''' import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d # primer plot, toro angulo = np.linspace(0, 2 * np.pi, 30) theta, phi = np.meshgrid(angulo, angulo) r, R = 1., 3. X = (R + r * np.cos(phi)) * np.cos(theta) Y = (R + r * np.cos(phi)) * np.sin(theta) Z = r * np.sin(phi) fig = plt.figure(1) fig.clf() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, Z, color='g', rstride=1, cstride=1, alpha=0.3, linewidth=0.3) # segundo plot, cilindro x = np.linspace(1, 3, 20) xc = x - 2 y = np.linspace(-6, 6, 20) Xc, Yc = np.meshgrid(xc, y) X = np.meshgrid(x) Zc = np.sqrt(1.0 - Xc**2.0) ax.plot_surface(X, Yc, -Zc, color='g', rstride=1, cstride=1, alpha=0.13) ax.plot_surface(X, Yc, Zc, color='g', rstride=1, cstride=1, alpha=0.13) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.view_init(elev=75, azim=60) plt.show() plt.draw() plt.savefig('volumen.png')
# Python3 # -*- coding: utf-8 -*- # FIFO即First in First Out,先进先出。 # Queue提供了一个基本的FIFO容器,使用方法很简单,maxsize是个整数, # 指明了队列中能存放的数据个数的上限。一旦达到上限,插入会导致阻塞, # 直到队列中的数据被消费掉。如果maxsize小于或者等于0,队列大小没有限制。 import queue q = queue.Queue() for i in range(10): q.put(i) while not q.empty(): print(q.get())
#!/usr/bin/python3 # 出现锁嵌套时,要用threading.RLock建立锁,否则程序会出问题 import time import logging import threading import random import sys from threading import Thread logging.basicConfig( level=logging.DEBUG, format='%(threadName)-10s: %(message)s', ) # format 中的 threadName 可以捕获到线程的名字,所以下边logging.debug()中不需要传入线程名 def countdown(n): while n > 0: logging.debug(f'倒数开始:{n}') n -= 1 time.sleep(1) class MyThread(Thread): def __init__(self, name, count): Thread.__init__(self) self.name = name self.count = count def run(self): try: lock.acquire() # 获取锁 logging.debug('lock....') countdown(self.count) finally: lock.release() logging.debug('open again') # lock = threading.Lock() # 新建一个锁 lock = threading.RLock() # 可以用于锁嵌套 TOTAL = 0 def add_plus_3(): global TOTAL with lock: TOTAL += 3 def add_plus(): global TOTAL with lock: # 锁的新用法,用完之后可以自动关闭 logging.debug(f'before add:{TOTAL}') wait = random.randint(1, 3) time.sleep(wait) print(f'执行了{wait}s之后。。。') TOTAL += 1 logging.debug(f'after add:{TOTAL}') add_plus_3() def main(): thread_list = [] logging.debug('start.....') for i in range(int(sys.argv[1])): t = Thread(target=add_plus) t.start() thread_list.append(t) # 把线程放到列表中 for i in thread_list: # 终止列表中的线程 i.join() logging.debug('end.....') if __name__ == '__main__': main()
from modules.binary_tree import BinaryTree class Node: """Class for storing a node.""" __slots__ = '_element', '_parent', '_left', '_right', 'mark' def __init__(self, element, parent=None, left=None, right=None, mark='unknown'): self.mark = mark self._element = element self._parent = parent self._left = left self._right = right class Position(BinaryTree.Position): """An abstraction representing the location of a single element.""" def __init__(self, container, node): """Constructor should not be invoked by user.""" self._container = container self._node = node def element(self): """Return the element stored at this Position.""" return self._node._element def mark(self): """Return mark of th node at this position""" return self._node.mark def __eq__(self, other): """Return True if other is a Position representing the same location.""" return type(other) is type(self) and other._node is self._node
from helpers.helper import input_data, print_table, pregunta from helpers.menu import Menu from controller.categoria_controller import Categoria_controller from classes.producto import Productos class Productos_controller: def __init__(self): self.categoria_controller = Categoria_controller() self.producto = Productos() self.salir = False def menu(self): while True: try: print(''' ============================ Almacen de Productos ============================ ''') menu = [ 'Listar productos', 'Buscar productos', 'Mantenimiento Categoria Productos', "Salir"] respuesta = Menu(menu).show() if respuesta == 1: self.listar_productos() elif respuesta == 2: self.buscar_productos() elif respuesta == 3: self.categoria_controller.menu() else: self.salir = True break except Exception as e: print(f'{str(e)}') def listar_productos(self): print(''' ========================== Lista de Productos ========================== ''') productos = self.producto.obtener_productos('id_productos') print(print_table(productos, ['ID', 'Nombre Producto', 'ID Categoria', 'Fecha Ingreso', 'Vida Util', 'Valor Unitario Compra', 'Valor Unitario Venta', 'Exogeración', 'Stock'])) input("\nPresione una tecla para continuar...") def buscar_productos(self): print(''' ======================== Buscar Productos ======================== ''') try: self.listar_productos() id_productos = input_data("Ingrese el ID del producto >> ", "int") productos = self.producto.obtener_producto({'id_productos': id_productos}) #print(print_table(productos, ['id_productos', 'Nombre', 'id_categoria', 'fecha_ult_ingreso', 'vida_util', 'valor_unitario_compra', 'valor_unitario_venta', 'exonerado_igv', 'stock'])) #confirmar si debe ir categoria_producto (nombre de la tabla) if productos: if pregunta("¿Deseas dar mantenimiento a los productos?"): opciones = ['Editar productos', 'Eliminar productos', 'Salir'] respuesta = Menu(opciones).show() if respuesta == 1: if pregunta("Que deseas hacer?"): opciones = ['Editar Campos', 'Actualzar Stock', 'Salir'] resp_edit = Menu(opciones).show() if resp_edit == 1: self.editar_productos(id_productos) elif resp_edit == 2: try: while True: stock = input_data("Ingrese la cantidad del producto en existencia >> ", "int") if stock >= productos[8]: self.producto.modificar_productos({ 'id_productos': id_productos }, { 'nombre' : productos[1], 'id_categoria' : productos[2], 'fecha_ult_ingreso' : productos[3], 'vida_util' : productos[4], 'valor_unitario_compra' : productos[5], 'valor_unitario_venta' : productos[6], 'exonerado_igv' : productos[7], 'stock': stock }) print(''' ========================== Producto Editado ! ========================== ''') print(print_table(productos, ['id_productos', 'Nombre', 'id_categoria', 'fecha_ult_ingreso', 'vida_util', 'valor_unitario_compra', 'valor_unitario_venta', 'exonerado_igv', 'stock'])) #confirmar si debe ir categoria_producto (nombre de la tabla) break else: print('Por favor ingresar un numero mayor que el stock actual') except ValueError as e: print(f'{str(e)}') elif respuesta == 2: self.eliminar_productos(id_productos) except Exception as e: print(f'{str(e)}') input("\nPresione una tecla para continuar...") def insertar_producto(self): nombre = input_data("Ingrese el nombre del producto >> ") self.categoria_controller.listar_categorias() id_categoria = input_data("Ingrese el ID categoria del producto >> ", "int") fecha_ult_ingreso = input_data("Ingrese la fecha de ultimo ingreso del producto >> ") vida_util = input_data("Ingrese la vida util del producto en dias >> ", "int") valor_unitario_compra = input_data("Ingrese el valor unitario de compra del producto >> ", "float") valor_unitario_venta = input_data("Ingrese el valor unitario de venta del producto >> ", "float") exonerado_igv = input_data("Confirme si el producto se encuentra exonerado de igv (si o no) >> ") stock = input_data("Ingrese la cantidad del producto en existencia >> ", "int") self.producto.guardar_productos({ 'nombre': nombre, 'id_categoria': id_categoria, 'fecha_ult_ingreso': fecha_ult_ingreso, 'vida_util': vida_util, 'valor_unitario_compra': valor_unitario_compra, 'valor_unitario_venta': valor_unitario_venta, 'exonerado_igv': exonerado_igv, 'stock': stock }) print(''' ================================= Nuevo Producto agregado ! ================================= ''') self.listar_productos() def editar_productos(self, id_productos): nombre = input_data("Ingrese el nombre del producto >> ") self.categoria_controller.listar_categorias() id_categoria = input_data("Ingrese el ID categoria del producto >> ", "int") fecha_ult_ingreso = input_data("Ingrese la fecha de ultimo ingreso del producto >> ") vida_util = input_data("Ingrese la vida util del producto en dias >> ", "int") valor_unitario_compra = input_data("Ingrese el valor unitario de compra del producto >> ", "float") valor_unitario_venta = input_data("Ingrese el valor unitario de venta del producto >> ", "float") exonerado_igv = input_data("Confirme si el producto se encuentra exonerado de igv (si o no) >> ") stock = input_data("Ingrese la cantidad del producto en existencia >> ", "int") self.producto.modificar_productos({ 'id_productos': id_productos }, { 'nombre': nombre, 'id_categoria': id_categoria, 'fecha_ult_ingreso': fecha_ult_ingreso, 'vida_util': vida_util, 'valor_unitario_compra': valor_unitario_compra, 'valor_unitario_venta': valor_unitario_venta, 'exonerado_igv': exonerado_igv, 'stock': stock }) print(''' ========================== Producto Editado ! ========================== ''') def eliminar_productos(self, id_productos): self.producto.eliminar_productos({ 'id_productos': id_productos }) print(''' ============================= Producto Eliminado ! ============================= ''')
# python function def print '************** Function arguments Test Programs **************' print 'keyword arguments' def person(name, age, **kw): print 'name:', name, 'age:', age for name, value in kw.items(): print '{0}: {1}'.format(name, value) person('Remind',6) person('Remind',6,city='shanghai') namedParameters = {'city':'shanghai','job':'Java'} person('Remind',6, city = 'shanghai', job = 'Java') person('Remind',6, **namedParameters) raw_input()
# python function def print '************** Function arguments Test Programs **************' print 'changeable arguments' def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print calc(2,7,0) nums = [1,2,3] print calc(*nums) raw_input()
# python function def print '************** Function arguments Test Programs **************' # Type check def power_001(x): if not isinstance(x,(int,float)): raise TypeError('Bad Operand Type') else: return x*x; print power_001(2) # Default arguments def power_002(x,n=2): if not isinstance(x,(int,float)): raise TypeError('Bad Operand Type') else: sum = 1; while n > 0: sum = x * sum n = n - 1 return sum print power_002(2) print power_002(2,8) def add_end(L=[]): L.append('END') return L print add_end() print add_end() print add_end() # Default argument must be a immutable object like Str, None def add_end_expected(L=None): if L is None: L = [] L.append('END') return L print add_end_expected() print add_end_expected() raw_input()
# Set foundation print '************** Set Test Programs **************' s1 = set([1,2]) print 's1:',s1 #duplicate elements will not be stored s2 = set([1,1,1,1,4,5]) print 's2:',s2 s2.add(3) print 'add 3 to s2:',s2 s2.add(3) print 'add 3 to s2:',s2 s2.remove(3) print 'remove 3 from s2:',s2 #remove non-exist element #s2.remove(10) # throw exception print 'remove non-exist 10 from s2',s2 print 's1 and s2 intersection:',s1&s2 print 's2 and s2 union:',s1|s2 raw_input()
# -*- coding: utf-8 -*- """Calculations (re-scaling, etc.)""" from math import ceil def rescale(data, maximum): """ Crude and simple rescaling of the numeric values of `data` to the maximum number `maximum`. :param data: <dict> in the form of {key: val <float> or <int>} :return: <dict> if the same structure. """ total = float(sum(data.values())) if total <= 0.: return data conv = lambda x: ceil(x) if isinstance(maximum, int) else x scaled = [] for key, val in data.items(): scaled.append({'key': key, 'val': conv(val / total * maximum)}) # Adjust resulting total to maximum integer # (.ceil can raise it a little). if isinstance(maximum, int): scaled = sorted(scaled, key=lambda x: x['val']) scaled_size = len(scaled) i = 0 while (sum(x['val'] for x in scaled) > maximum) and (i < scaled_size): new_val = max(0, scaled[i]['val']-1) scaled[i]['val'] = new_val i += 1 return dict((x['key'], x['val']) for x in scaled)
# The energy in joules released for a particular Richter scale measurement is given by: # Energy = 10 ^ (1.5 x richter + 4.8) # ------------------------------------------ # One ton of exploded TNT yields 4.184x10^9 # joules. Thus, you can relate the energy released in # joules to tons of exploded TNT. richter_scale_value = input("Please enter a Richter scale value:") richter = float(richter_scale_value) tnt_joules = 4.184 * (10 ** 9) richter_joules = 10 ** (1.5 * richter + 4.8) tnt = richter_joules / tnt_joules print("Richter scale value:", richter) print("Equivalence in joules:", richter_joules) print("Equivalence in tons of TNT:", tnt)
def ask_numbers (): while True: try: wall_length = float(input("Type a length of wall:")) break except: print("Data is not a number. Try again!") continue while True: try: flower_distance = float(input("Distance between flowers: ")) break except: print("Data is not a number. Try again!") continue while True: try: flower_depth = float(input("Depth of flowerbed: ")) break except: print("Data is not a number. Try again!") continue while True: try: grayplace_depth = float(input("Depth of gray area: ")) break except: print("Data is not a number. Try again!") continue return wall_length, flower_distance, flower_depth, grayplace_depth def calculate_flowers_count(wall_length, flower_distance): import math steps = wall_length / flower_distance triangle = ((steps / 2) ** 2) / 2 circle = math.pi * (steps / 2) ** 2 flower_total_counts = triangle * 4 + circle return triangle, circle, flower_total_counts def calculate_sands(wall_length, flower_total_counts, flower_depth, grayplace_depth): import math grayplace_area = wall_length / 2
def detect_anagrams(string, array): lst = [] for word in array: if word == string: continue if len(string) != len(word): continue for letter in word: if letter not in string: continue s = set(string) w = set(word) if len(w) == len(s): lst.append(word) return lst
""" Purpose: A program to implement a guessing game. Game rules 1. A game co-ordinator inputs the number of players to a game 2. At the start of the game, all players are asked for their names 3. At the start of each round, a new magic number between 1 and 10 (not visible to the players) is generated 4. Each player is asked for their guess 5. The player(s) with the closest guesses win 1 point 6. The user then has a choice to continue to the next round or stop the game 7. At the end of the game, the total points scored by each player is listed and the winner(s) is announced. Author: Preedhi Vivek Date: 30/07/2019 """ import random from collections import Counter class UserInput(): # Initialize the variables to be used in this class def __init__(self): self.no_of_players = 0 self.player_name = "" self.player_data = {} # method to get the number of users and user names def get_user_input(self): print("Enter the number of players:") while True: try: self.no_of_players = int(input()) if isinstance(self.no_of_players,int) and (self.no_of_players == 1): print("Atleast two players are required to play this guessing game!\n") print("Enter the number of players (between 1 to 5):") elif isinstance(self.no_of_players,int) and (self.no_of_players > 0) and (self.no_of_players <= 5): break elif isinstance(self.no_of_players,int) and (self.no_of_players < 0): print("Please enter a positive integer (between 1 to 5)!") elif isinstance(self.no_of_players,int) and (self.no_of_players > 5): print("Please enter a positive integer (between 1 to 5)!") except ValueError: print("Please enter a positive integer (between 1 to 5)!") for i in range(self.no_of_players): j = i+1 print("Enter the name of player%d: "%j) while True: try: self.player_name = str(input()) if isinstance(self.player_name,str) and (self.player_name.isalpha()): break elif isinstance(self.player_name,str) and (self.player_name.isdigit()): print("Please enter a valid name!") else: print("Please enter a valid name!") except ValueError: print("Please enter a valid name!") self.player_data.update({self.player_name:0}) return self.no_of_players, self.player_data class GenerateRandom(): # Initialize the variables to be used in this class def __init__(self): self.magic_number = 0 def get_random_integer(self): self.magic_number = random.randint(1, 10) return self.magic_number class GetUserGuess(): # Initialize the variables to be used in this class def __init__(self): self.guess_data = {} self.guess_number = 0 def get_user_guess(self, player_info,player_count): i =1 for key in player_info.keys() : print("Player %d - Enter your guess: "%i) while True: try: self.guess_number = int(input()) if isinstance(self.guess_number,int) and self.guess_number > 0 and self.guess_number <= 10: break elif (self.guess_number < 0) : print("Enter a positive integer between 1 and 10 (inclusive) to guess!") elif isinstance(self.guess_number,int) and self.guess_number >10 : print("Enter an integer between 1 and 10 (inclusive) to guess! ") except ValueError: print("Enter a positive integer between 1 and 10 (inclusive) to guess!") i = i+1 self.guess_data.update({key:self.guess_number}) return self.guess_data class ClosestGuesser() : def __init__(self): self.difference = 0 self.difference_info = {} self.closest_guess = () def find_the_closest_guess(self, magic_number, guess_info): for key,value in guess_info.items(): if (magic_number >= value) : self.difference = magic_number - value elif (magic_number < value): self.difference = value - magic_number self.difference_info.update({key:self.difference}) self.closest_guess = min(self.difference_info.items(), key=(lambda k: k[1])) return self.closest_guess class AddPoint() : def add_point_to_score(self, closest_guess_data, player_data): for key,value in player_data.items(): if (closest_guess_data[0] == key) : value = int(value) + 1 player_data.update({key:value}) return player_data # Program starts here if __name__ == "__main__": print("\n PLAY GUESSING GAME!! \n") # obj1 is an object of class UserInput obj1 = UserInput() # Call the method to get the user input player_count, player_info = obj1.get_user_input() #print("Player Info: ", player_info) print ("\nRound 1") round_count = 1 while True: if (round_count > 1): print("Round %d"%round_count) # obj2 is an object of class GenerateRandom obj2 = GenerateRandom() #Call the method to generate a random number between 1 to 10 magic_number = obj2.get_random_integer() #print("Magic Number: ", magic_number) # obj3 is an object of class GetUSerGuess obj3 = GetUserGuess() #Call the method to get the user guesses guess_info = obj3.get_user_guess(player_info, player_count) #print("Guess Info: ", guess_info) # obj4 is an object of class ClosestGuesser obj4 = ClosestGuesser() #Call the method to find the user whose guess was the closest closest_guess_info = obj4.find_the_closest_guess(magic_number,guess_info) #print("Closest Guess Info: ", closest_guess_info) # obj5 is an object of class AddPoint obj5 = AddPoint() #Call the method to add a point to the closest guesser updated_player_info = obj5.add_point_to_score(closest_guess_info, player_info) print("Score Board for round %d: "%round_count,updated_player_info) while True: print("\n Do you wish to continue? Y/N:") try: next_round = str(input()) if isinstance(next_round,str) and (len(next_round)==1) and (next_round.isupper()) and (next_round == 'Y'): round_count += 1 set_exit = 0 break elif isinstance(next_round,str) and (len(next_round)==1) and (next_round.isupper()) and (next_round == 'N'): set_exit = 1 break elif isinstance(next_round,str) and (len(next_round)!=1): print("Enter only Y or N") else : print("Enter only Y or N") except ValueError: print("Enter only Y or N") if (set_exit == 1): break print("\n The Winner of this Guessing Game is: %s"%closest_guess_info[0]) print("\n Congrats %s!!"%closest_guess_info[0])
""" Selenium Test Automation: Scope: 1.To count the number of items listed in the cart. 2.To calculate the total cost of the items in the cart. Author: Preedhi Vivek Date: 14/08/2019 """ import time from selenium import webdriver import weather_shopper_module as m1 # Start of program execution if (__name__ == '__main__') : url = "https://weathershopper.pythonanywhere.com/" cart_items = {} # create an instance of Chrome WebDriver driver = webdriver.Chrome() # create an object of class Navigate nav_obj1 = m1.Navigate(url,driver) # call the method to navigate to weather shopper webapplication nav_obj1.navigate_url() # maximize window driver.maximize_window() #Wait for page to load time.sleep(2) # call the method to verify navigation based on the page title nav_obj1.verify_navigation_on_page_title() # create an object of class Decision_Maker dec_maker1 = m1.Decision_Maker(driver) # call the method to decide the purchase (if moisturizer or sunscreen) flag = dec_maker1.decide_purchase() #Wait for page to load time.sleep(2) # call the method to verify the redirection of webpage based on the purchase decision nav_obj1.verify_url() # create an object of class Items items_obj1 = m1.Items(driver) if(flag==1): #call the method to return the cost of the Aloe Moiturizers item_prices = items_obj1.get_item_prices('Aloe') time.sleep(2) #call the method to add the least priced Aloe Moisturizer to the cart cart_item_name,cart_item_price = items_obj1.add_least_priced_item('Aloe',item_prices) cart_items.update({cart_item_name:cart_item_price}) time.sleep(2) #call the method to return the cost of the Almond Moiturizers item_prices = items_obj1.get_item_prices('Almond') #call the method to add the least priced Almond Moisturizer to the cart cart_item_name,cart_item_price = items_obj1.add_least_priced_item('Almond',item_prices) cart_items.update({cart_item_name:cart_item_price}) time.sleep(2) elif (flag ==2): #call the method to return the cost of the spf50 sunscreens item_prices = items_obj1.get_item_prices('SPF-50') #call the method to add the least priced spf50 sunscreen to the cart cart_item_name,cart_item_price = items_obj1.add_least_priced_item('SPF-50',item_prices) cart_items.update({cart_item_name:cart_item_price}) time.sleep(2) #call the method to return the cost of the spf30 sunscreens item_prices = items_obj1.get_item_prices('SPF-30') #call the method to add the least priced spf30 sunscreen to the cart cart_item_name,cart_item_price = items_obj1.add_least_priced_item('SPF-30',item_prices) cart_items.update({cart_item_name:cart_item_price}) time.sleep(2) # create an object of class Cart cart_obj1 = m1.Cart(driver) #create an object of class common_events com_events1= m1.common_events(driver) #call the method to verify the cart label post addition of items cart_flag = cart_obj1.check_cart() time.sleep(2) try: if (cart_flag==1): #call the method to verify navigation to checkout page cart_flag = nav_obj1.verify_url() if (cart_flag ==2): #call the method to verify the cart content cart_flag = cart_obj1.verify_cart_content(cart_items) time.sleep(2) if (cart_flag == 3): #call the method to get the number of items present in the cart count = cart_obj1.get_cart_item_count(cart_items) print("Number of items listed in the cart: ",count) time.sleep(2) #call the method to calculate the total cost of the items present in the cart total_cost = cart_obj1.get_cart_total_cost(cart_items) print("Total cost of the items listed in the cart is :", total_cost) except Exception as e: print("Exceptions:",e) # Close the browser window driver.close()
__author__ = "Joselito Junior" print("Programa que calcula do valor consumido pelo cliente no restaurante") print("") hamburger = input("Digite a quantidade de Hambúrger: ") batataFritas = input("Digite a quantidade de Batata Fritas: ") milkshake = input("Digite a quantidade de Milkshake: ") print("") print(" O valor total é: ", ((float(hamburger) * 10) + (float(batataFritas) * 8) + (float(milkshake) * 16))) print("") input("Pressione ENTER para sair...")
i = 0 palavra = "palavra" while i < len(palavra): print(palavra[i]) i += 1
__author__ = "Joselito Junior" #Inicio da função media def media(nota1, nota2, nota3): return ((float(nota1) + float(nota2) + float(nota3)) / 3) #Fim da função media print("Este programa faz o cálculo da média de 3 valores") notas = input("Digite os três valores na oredem: nota1, nota2, nota3 (separados por vígula): ") nota1, nota2, nota3 = notas.split(",") print(" O valor da média é: ", media(nota1, nota2, nota3)) input("Pressione ENTER para sair...")
__author__ = "Joselito Junior" #valor = input("Digite dois números inteiros separados por virgula:\n") #valor1, valor2 = valor.split(',') valor1 = int(input("Digite o valor 1: ")) valor2 = int(input("Digite o valor 2: ")) print(sum(range(valor1 + 1, valor2, 1)))
__author__ = "Joselito Junior" ano = float(input("Digite um ano: ")) if((ano % 4) == 0): if((ano % 100) != 0): #Verifica se o ano termina em 00 print("Esse ano é bissexto") elif((ano % 400) == 0): print("Esse ano é bissexto") else: print("Esse ano não é bissexto") else: print("Esse ano não é bissexto")
#Write a function called sum_lists. sum_lists should take #one parameter, which will be a list of lists of integers. #sum_lists should return the sum of adding every number from #every list. # #For example: # # list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] # sum_list(list_of_lists) -> 67 #Add your code here! def sum_lists(sum_of_integers): result = [] for alist in sum_of_integers: total = 0 for number in alist: total += number result.append(total) return sum(result) #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: 78 list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(sum_lists(list_of_lists)) sample answer #First, we define the function: def sum_lists(list_of_lists): #We know that we want to calculate a running total, so #we probably want to create a variable for our total #and start it at 0: total = 0 #Now, we want to go through each list in the list of #lists... for a_list in list_of_lists: #And within each list, we want to go through each #item... for item in a_list: #And then we want to add that item to our #running total: total += item #Then, *after* we've gone through every item in every #list (so outside either loop), we return the result: return total list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(sum_lists(list_of_lists)) ORRR def sum_lists(list_of_lists): result = [] for listnumber in list_of_lists: result.append(sum(listnumber)) return sum(result) orrrr def sum_lists(list_of_lists): return sum([sum(lst) for lst in list_of_lists])
#Write a function called "write_file" that accepts two #parameters: a filename and some data that will either #be an integer or a string to write. The function #should open the file and write the data to the file. # #Hints: # # - Don't forget to close the file when you're done! # - If the data isn't a string already, you may need # to convert it, depending on the approach you # choose. # - Remember, this code has no print statements, so # when you run it, don't expect to see any output # on the right! You could add print statements if # you want a confirmation the code is done running. # - You can put the variable for the filename in the # same place where we put text like OutputFile.txt # in the videos. #Write your function here! def write_file(filename, data): outputFile = open(filename, "w") outputFile.write(str(data)) outputFile.close() #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print nothing. However, if you open WriteFileOutput.txt #in the top left after running it, the contents of the #file should be 1301. write_file("WriteFileOutput.txt", 1301) sample answer def write_file(filename, contents): #First, we need to open the file so we can write to it. #So, we pass in the filename and the argument "w" to the #open() function, and set the results equal to a #variable we'll use to write to the file going forward. file_writer = open(filename, "w") #Next, we'll write the contents. Remember, though, the #write() method can only write strings, so if our #contents is an integer, we need to convert it. However, #converting a string to a string doesn't change it, so #we might as well jsut convert everything to a string: file_writer.write(str(contents)) #Finally, we must close the file: file_writer.close() write_file("WriteFileOutput.txt", 1301)
"""This class provides the necessary classes for agents (general), predators and prey.""" import numpy as np import random as rd from collections import namedtuple, deque from typing import Callable, NamedTuple, Union memory = namedtuple('Memory', ('States', 'Rewards', 'Actions')) class Agent: """ This class provides an agent object. It has the following attributes: - food_reserve - max_food_reserve - generation, a counter, representing the number of parents - p_breed, the breeding probability - kin, a string providing the type of agent - memory, a named tuple of deques saving the agents' states, rewards and actions - kwargs, a dictionary storing every additional property that might find its way into the class call. class constants: - HEIRSHIP, a list of properties to pass down to the next generation Accessing the attributes is done via properties and setter, if necessary. The only necessary argument to specify is the food reserve. The rest is optional. """ # class constants HEIRSHIP = ['max_food_reserve', 'generation', 'p_breed', '_kwargs'] # slots ------------------------------------------------------------------- __slots__ = ['_food_reserve', '_max_food_reserve', '_generation', '_p_breed', '_kin', '_kwargs', '_memory'] # Init -------------------------------------------------------------------- def __init__(self, *, food_reserve: Union[int, float], max_food_reserve: int=None, generation: int=None, p_breed: float=1.0, kin: str=None, mem: tuple=None, **kwargs): """Initialise the agent instance.""" # Initialize values self._food_reserve = 0 self._max_food_reserve = None self._generation = None self._p_breed = 1.0 self._kin = None self._kwargs = kwargs # just set the value directly here. self._memory = None # Set property managed attributes self.food_reserve = food_reserve self.p_breed = p_breed if kin: # if kin is given, set kin self.kin = kin else: # otherwise just set 'Agent' as kin self.kin = self.__class__.__name__ if max_food_reserve: self.max_food_reserve = max_food_reserve if generation is not None: self.generation = generation if mem is not None: self.memory = mem else: self.memory = memory(deque(), deque(), deque()) # initialize empty lists # magic method ------------------------------------------------------------ def __str__(self) -> str: """Return the agents properties.""" props = ("{}\tID: {}\tgeneration: {}\tfood_reserve: {}\t" "max_food_reserve: {}".format(self.kin, # self.uuid, self.generation, self.food_reserve, self.max_food_reserve)) return props # Properties -------------------------------------------------------------- # food_reserve @property def food_reserve(self) -> int: """The food reserve of the agent.""" return self._food_reserve @food_reserve.setter def food_reserve(self, food_reserve: Union[int, float]) -> None: """The food reserve setter.""" if not isinstance(food_reserve, (int, float)): raise TypeError("food_reserve can only be of type integer, but" " type {} was given".format(type(food_reserve))) elif food_reserve < 0: raise ValueError("food_reserve must be positive, but {} was given." "".format(food_reserve)) elif self.max_food_reserve: if food_reserve >= self.max_food_reserve: self._food_reserve = self.max_food_reserve else: self._food_reserve = food_reserve else: self._food_reserve = food_reserve # max_food_reserve @property def max_food_reserve(self) -> Union[int, float]: """The maximal food reserve of the agent.""" return self._max_food_reserve @max_food_reserve.setter def max_food_reserve(self, max_food_reserve: Union[int, float]) -> None: """The maximal food reserve setter.""" if not isinstance(max_food_reserve, (int, float)): raise TypeError("max_food_reserve can only be of type integer, " "but type {} was given" "".format(type(max_food_reserve))) elif max_food_reserve < self.food_reserve: raise ValueError("max_food_reserve must be greater or equal than" " food_reserve={}, but {} was given." "".format(self.food_reserve, max_food_reserve)) elif self.max_food_reserve: raise RuntimeError("max_food_reserve is already set.") else: self._max_food_reserve = max_food_reserve # generation @property def generation(self) -> int: """The generation of the agent.""" return self._generation @generation.setter def generation(self, generation: int) -> None: """The generation setter.""" if not isinstance(generation, int): raise TypeError("generation can only be of type integer, " "but {} was given.".format(type(generation))) elif generation < 0: raise ValueError("generation must be positive but {} was given" "".format(generation)) elif self.generation: raise RuntimeError("generation is already set.") else: self._generation = generation # breeding probability @property def p_breed(self) -> float: """The breeding probability of the Agent.""" return self._p_breed @p_breed.setter def p_breed(self, p_breed: float) -> None: """The breeding probability setter.""" if not isinstance(p_breed, float): raise TypeError("p_breed must be of type float, but {} was given." "".format(type(p_breed))) elif p_breed < 0 or p_breed > 1: raise ValueError("p_breed must be between 0 and 1 but {} was given." "".format(p_breed)) else: self._p_breed = p_breed # kin @property def kin(self) -> str: """Return kin of the agent.""" return self._kin @kin.setter def kin(self, kin: str) -> None: """The kin setter for the agent.""" if not isinstance(kin, str): raise TypeError("kin must be of type str, but {} was given." "".format(type(kin))) # elif self.kin: # raise RuntimeError("kin is alreday set and cannot be changed on the" # " fly.") else: self._kin = kin # memory for learning @property def memory(self) -> NamedTuple: """Hold the history of all states, rewards and actions for a single agent.""" return self._memory @memory.setter def memory(self, memory: NamedTuple) -> None: """Set the NamedTuple for the memory.""" if not isinstance(memory, tuple): raise TypeError("memory must be of type tuple, but {} was given." "".format(type(memory))) elif self._memory is not None: raise RuntimeError("memory already set. This should not have " "happened.") else: self._memory = memory # staticmethods ----------------------------------------------------------- # no staticmethods so far... # classmethods ------------------------------------------------------------ @classmethod def _procreate_empty(cls, *, food_reserve: int) -> Callable: """The classmethod creates a new "empty" instance of `cls`. food_reserve needs to be set explicitely. """ return cls(food_reserve=food_reserve) # methods ----------------------------------------------------------------- def procreate(self, *, food_reserve: int) -> Callable: """Take a class instance and inherit all attributes in `HEIRSHIP` from self. Return a `cls` instance with attributes set. """ # create empty instance offspring = self._procreate_empty(food_reserve=food_reserve) # iterate over all attributes for attr in self.HEIRSHIP: parent_attr = getattr(self, attr) if parent_attr is not None: # adapt generation counter if set in parent if attr == 'generation': setattr(offspring, attr, parent_attr+1) else: setattr(offspring, attr, parent_attr) return offspring class Predator(Agent): """Predator class derived from Agent. This provides (additionally to class Agent): - p_eat, the probability to eat a prey agent (should be defined as 1-p_flee), is here for simplicity. (TODO: fix that) """ # class constants HEIRSHIP = Agent.HEIRSHIP + ['p_eat'] # slots ------------------------------------------------------------------- __slots__ = ['_p_eat'] # init -------------------------------------------------------------------- def __init__(self, *, food_reserve: Union[int, float], p_eat: float=1.0, max_food_reserve: Union[int, float]=None, p_breed: float=1.0, generation: int=None, **kwargs): """Initialise a Predator instance.""" super().__init__(food_reserve=food_reserve, max_food_reserve=max_food_reserve, generation=generation, p_breed=p_breed, kin=self.__class__.__name__, **kwargs) # initialise new attributes self._p_eat = 1.0 # set new (property managed) attributes self.p_eat = p_eat # magic method ------------------------------------------------------------ def __str__(self) -> str: """Return the agents properties.""" props = ("Kin: {}\tgen: {}\tfood_res: {}\t" "max_food_res: {}\t p_eat: {}".format(self.kin, # self.uuid, self.generation, self.food_reserve, self.max_food_reserve, self.p_eat)) return props # properties -------------------------------------------------------------- @property def p_eat(self) -> float: """The eating probability of the predator.""" return self._p_eat @p_eat.setter def p_eat(self, p_eat: float) -> None: """The eating probability setter.""" if not isinstance(p_eat, float): raise TypeError("p_eat must be of type float, but {} was given." "".format(type(p_eat))) elif p_eat < 0 or p_eat > 1: raise ValueError("p_eat must be between 0 and 1 but {} was given." "".format(p_eat)) else: self._p_eat = p_eat class Prey(Agent): """Prey class derived from Agent. This provides (additionally to class Agent): - p_flee, the fleeing probability - got_eaten, boolean flag to specify whether a prey got eaten or not. """ # class constants # _UUID_LENGTH = Agent._UUID_LENGTH HEIRSHIP = Agent.HEIRSHIP + ['p_flee'] # slots ------------------------------------------------------------------- __slots__ = ['_p_flee', '_got_eaten'] # init -------------------------------------------------------------------- def __init__(self, *, food_reserve: Union[int, float], p_breed: float=1.0, max_food_reserve: Union[int, float]=None, p_flee: float=0.0, generation: int=None, **kwargs): """Initialise a Prey instance.""" super().__init__(food_reserve=food_reserve, max_food_reserve=max_food_reserve, generation=generation, p_breed=p_breed, kin=self.__class__.__name__, **kwargs) # initialise new attributes self._p_flee = 0.0 self._got_eaten = False if p_flee is not None: # set new (property managed) attributes self.p_flee = p_flee # magic method ------------------------------------------------------------ def __str__(self) -> str: """Return the agents properties.""" props = ("Kin: {}\tgen: {}\tfood_res: {}\t" "max_food_res: {}\t p_flee: {}\t" " got_eaten: {}".format(self.kin, # self.uuid, self.generation, self.food_reserve, self.max_food_reserve, self.p_flee, self.got_eaten)) return props # properties -------------------------------------------------------------- @property def p_flee(self) -> float: """The fleeing probability of the prey.""" return self._p_flee @p_flee.setter def p_flee(self, p_flee: float) -> None: """The fleeing probability setter.""" if not isinstance(p_flee, float): raise TypeError("p_flee must be of type float, but {} was given." "".format(type(p_flee))) elif p_flee < 0 or p_flee > 1: raise ValueError("p_flee must be between 0 and 1 but {} was given." "".format(p_flee)) else: self._p_flee = p_flee @property def got_eaten(self) -> bool: """Flag if prey was eaten (needed for actor-critic).""" return self._got_eaten @got_eaten.setter def got_eaten(self, got_eaten: bool) -> None: """Set if prey got eaten.""" if not isinstance(got_eaten, bool): raise TypeError("got_eaten must be of type bool, but {} was given." "".format(type(got_eaten))) else: self._got_eaten = got_eaten # ----------------------------------------------------------------------------- class OrientedPredator(Predator): """Predator class derived from Predator class. This class holds an additional feature of having a directed action. In other words, an Agent of this class can only act in the direction it is looking. Additional properties: - orient, a 2-tuple of the (X,Y) coordinates of the agents orientation note, that when using plt.quiver one has to provide x,y coordinates whereas np.where returns y,x values. """ # class constants HEIRSHIP = Predator.HEIRSHIP # slots ------------------------------------------------------------------- __slots__ = ['_orient'] # init -------------------------------------------------------------------- def __init__(self, *, food_reserve: Union[int, float], p_breed: float=1.0, max_food_reserve: Union[int, float]=None, p_eat: float=1.0, generation: int=None, orient: tuple=None, **kwargs): """Initialze a OrientedPredator instance.""" super().__init__(food_reserve=food_reserve, max_food_reserve=max_food_reserve, generation=generation, p_breed=p_breed, p_eat=p_eat, # kin=self.__class__.__name__, **kwargs) # initialize new attributes self._orient = (0, 0) # set new (property managed) attributes self.orient = orient # magic method ------------------------------------------------------------ def __str__(self) -> str: """Return the agents properties.""" props = ("Kin: {}\tgen: {}\tfood_res: {}\t" "max_food_res: {}\t p_eat: {}\t orient: {}" "".format(self.kin, self.generation, self.food_reserve, self.max_food_reserve, self.p_eat, self.orient)) return props # properties -------------------------------------------------------------- @property def orient(self) -> tuple: """The agents' orientation as (Y,X) tuple.""" return self._orient @orient.setter def orient(self, orient: tuple) -> None: """Set the agents orientation.""" if orient is None: self._generate_orient() elif not isinstance(orient, tuple) or len(orient) > 2: raise TypeError("Orientation must be of 2-tuple but {} of length" "{} was given.".format(type(orient), len(orient))) else: self._orient = orient # methods ----------------------------------------------------------------- def _generate_orient(self) -> None: """Generate a random orientation for an agent.""" y = rd.choice([-1, 0, 1]) # first variable x = rd.choice([-1, 1]) if y == 0 else 0 # set x depending on y orient = [y, x] np.random.shuffle(orient) # shuffle the resulting 2-vector to remove any bias self.orient = tuple(orient) class OrientedPrey(Prey): """Prey class derived from Prey class. This class holds an additional feature of having a directed action. In other words, an Agent of this class can only act in the direction it is looking. Additional properties: - orient, a 2-tuple of the (X,Y) coordinates of the agents orientation note, that when using plt.quiver one has to provide x,y coordinates whereas np.where returns y,x values. """ # class constants HEIRSHIP = Prey.HEIRSHIP # slots ------------------------------------------------------------------- __slots__ = ['_orient'] # init -------------------------------------------------------------------- def __init__(self, *, food_reserve: Union[int, float], p_breed: float=1.0, max_food_reserve: Union[int, float]=None, p_flee: float=0.0, generation: int=None, orient: tuple=None, **kwargs): """Initialze a OrientedPredator instance.""" super().__init__(food_reserve=food_reserve, max_food_reserve=max_food_reserve, generation=generation, p_breed=p_breed, p_flee=p_flee, # kin=self.__class__.__name__, **kwargs) # initialize new attributes self._orient = (0, 0) # set new (property managed) attributes self.orient = orient # magic method ------------------------------------------------------------ def __str__(self) -> str: """Return the agents properties.""" props = ("Kin: {}\tgen: {}\tfood_res: {}\t" "max_food_res: {}\t p_flee: {}\t orient: {}" "".format(self.kin, self.generation, self.food_reserve, self.max_food_reserve, self.p_flee, self.orient)) return props # properties -------------------------------------------------------------- @property def orient(self) -> tuple: """The agents' orientation as (Y,X) tuple.""" return self._orient @orient.setter def orient(self, orient: tuple) -> None: """Set the agents orientation.""" if orient is None: self._generate_orient() elif not isinstance(orient, tuple) or len(orient) > 2: raise TypeError("Orientation must be of 2-tuple but {} of length" "{} was given.".format(type(orient), len(orient))) else: self._orient = orient # methods ----------------------------------------------------------------- def _generate_orient(self) -> None: """Generate a random orientation for an agent.""" y = rd.choice([-1, 0, 1]) # first variable x = rd.choice([-1, 1]) if y == 0 else 0 # set x depending on y orient = [y, x] np.random.shuffle(orient) # shuffle the resulting 2-vector to remove any bias self.orient = tuple(orient)
x=input("enter the first no: ") y=input("enter the second no: ") f=str(input("which operation? +,-,/,* : ")) if f=="+": addition=float(x)+float(y) print(addition) elif f=="-": subraction=float(x)-float(y) print(subraction) elif f=="*": multiplication=float(x)*float(y) print(multiplication) elif f=="/": division=float(x)/float(y) if y!=0: print(division) else: print("cannot be determined") else: print("invalid input")
""" Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. """ from typing import List class Solution: def fizzBuzz(self, n: int) -> List[str]: data = [] for i in range(1, n+1): if (not i%15): data.append('FizzBuzz') elif (not i%3): data.append('Fizz') elif (not i%5): data.append('Buzz') else: data.append(str(i)) return data if __name__ == "__main__": solution = Solution() print(solution.fizzBuzz(15)) """ One line solution: return [(not int(i)%3) * 'Fizz' + (not int(i)%5) * 'Buzz' or str(i) for i in range(1,n+1)] """
# -*- coding: utf-8 -*- """ Created on Thu Mar 5 21:08:42 2020 @author: Mike """ #Data Science Capstone #Michael Bassett #This is the first set of code used for the "business.json" yelp dataset import json import pandas as pd #Creating one large dataset with all 8 cities we need #Opening up the actual yelp data, which is not in a true json form/structure with open("business.json", errors="ignore") as file: #Creating an empty list businesses = [] #For each business, append it to the businesses list for line in file: business = json.loads(line) businesses.append(business) #Creating a new file which is in a proper json format with open("business_new.json", "w") as file: json.dump(businesses, file) #Print the first element to see how it looks print(businesses[0]) #Create all_cities_1, which is every BUSINESS that is in our 8 cities of interest all_cities_1 = [business for business in businesses if ((business["state"]=="AB") and ("Calgary" in business["city"])) or ((business["state"]=="ON") and ("Toronto" in business["city"])) or ((business["state"]=="PA") and ("Pittsburgh" in business["city"])) or ((business["state"]=="NC") and ("Charlotte" in business["city"])) or ((business["state"]=="AZ") and ("Phoenix" in business["city"])) or ((business["state"]=="NV") and ("Las Vegas" in business["city"])) or ((business["state"]=="WI") and ("Madison" in business["city"])) or ((business["state"]=="OH") and ("Cleveland" in business["city"]))] #Counting how many businesses there are in the 8 cities #There are 100,261 businesses print(len(all_cities_1)) #Create all_cities_2, which is only restaurants in the 8 cities of interest all_cities_2 = [business for business in all_cities_1 if (business.get("categories")) and ("Restaurants" in business.get("categories"))] #There are 29,558 restaurants. This aligns with your earlier exploratory data analysis print(len(all_cities_2)) #DEALING WITH ATTRIBUTES #Attributes are lists within each business #We need to create new variables for each individual attribute for i, business in enumerate(all_cities_2): #Step 1: Set to N/A if "attribute" doesn't exist if business["attributes"] is None: Alcohol = "N/A" BikeParking = "N/A" BusinessAcceptsCreditCards = "N/A" Caters = "N/A" GoodForKids = "N/A" HasTV = "N/A" NoiseLevel = "N/A" OutdoorSeating = "N/A" RestaurantsAttire = "N/A" RestaurantsDelivery = "N/A" RestaurantsGoodForGroups = "N/A" RestaurantsPriceRange2 = "0" RestaurantsReservations = "N/A" RestaurantsTakeOut = "N/A" WiFi = "N/A" #Step 2: Pull out the existing variable - if it doesn't exist, set to "N/A" else: Alcohol = business["attributes"].get("Alcohol","N/A") BikeParking = business["attributes"].get("BikeParking","N/A") BusinessAcceptsCreditCards = business["attributes"].get("BusinessAcceptsCreditCards","N/A") Caters = business["attributes"].get("Caters","N/A") GoodForKids = business["attributes"].get("GoodForKids","N/A") HasTV = business["attributes"].get("HasTV","N/A") NoiseLevel = business["attributes"].get("NoiseLevel","N/A") OutdoorSeating = business["attributes"].get("OutdoorSeating","N/A") RestaurantsAttire = business["attributes"].get("RestaurantsAttire","N/A") RestaurantsDelivery = business["attributes"].get("RestaurantsDelivery","N/A") RestaurantsGoodForGroups = business["attributes"].get("RestaurantsGoodForGroups","N/A") RestaurantsPriceRange2 = business["attributes"].get("RestaurantsPriceRange2","0") RestaurantsReservations = business["attributes"].get("RestaurantsReservations","N/A") RestaurantsTakeOut = business["attributes"].get("RestaurantsTakeOut","N/A") WiFi = business["attributes"].get("WiFi","N/A") #Step 3: Create the new variable itself all_cities_2[i]["alcohol"] = Alcohol all_cities_2[i]["bikeparking"] = BikeParking all_cities_2[i]["creditcards"] = BusinessAcceptsCreditCards all_cities_2[i]["caters"] = Caters all_cities_2[i]["goodforkids"] = GoodForKids all_cities_2[i]["tv"] = HasTV all_cities_2[i]["noiselevel"] = NoiseLevel all_cities_2[i]["outdoorseating"] = OutdoorSeating all_cities_2[i]["attire"] = RestaurantsAttire all_cities_2[i]["delivery"] = RestaurantsDelivery all_cities_2[i]["goodforgroups"] = RestaurantsGoodForGroups all_cities_2[i]["pricerange"] = RestaurantsPriceRange2 all_cities_2[i]["reservations"] = RestaurantsReservations all_cities_2[i]["takeout"] = RestaurantsTakeOut all_cities_2[i]["wifi"]= WiFi #SAS issue - has trouble reading in the "None" pricerange values #Setting these to 0 for now - will clean up in SAS later if business["pricerange"]=="None": all_cities_2[i]["pricerange"] = "0" #THREE ADDITIONAL ATTRIBUTES #Ambience, BusinessParking, and GoodForMeal are lists within the "attributes" list #These need to be handled differently than the attributes above #Creating a new list for each one. These are the keys in the key/value pair ambience = ['touristy','casual','romantic','intimate','classy','hipster','divey','trendy','upscale'] businessparking = ['garage','street','validated','lot','valet'] goodformeal = ['dessert','latenight','lunch','dinner','brunch','breakfast'] #1. Ambience for i, business in enumerate(all_cities_2): #When there is no "attributes", set them all to "N/A" if business["attributes"] is None: for item in ambience: all_cities_2[i][item] = "N/A" #When "attributes" exists, but "Ambience" does not, set them all to "N/A" elif business["attributes"].get("Ambience") is None: for item in ambience: all_cities_2[i][item] = "N/A" #When "attributes" exists and "Ambience" exists, and is not equal to "None" elif business["attributes"].get("Ambience")!="None": #print(type(business["attributes"]["Ambience"])) New_Ambience = business["attributes"]["Ambience"].replace("'",'"').replace("True",'"True"').replace("False",'"False"') #print(New_Ambience) New_Ambience = json.loads(New_Ambience) #print(type(New_Ambience)) for item in ambience: all_cities_2[i][item] = New_Ambience.get(item) #When "attributes" exists and "Ambience" exists, but is equal to "None", set them all to "N/A" else: for item in ambience: all_cities_2[i][item] = "N/A" #2. BusinessParking for i, business in enumerate(all_cities_2): if business["attributes"] is None: for item in businessparking: all_cities_2[i][item] = "N/A" elif business["attributes"].get("BusinessParking") is None: for item in businessparking: all_cities_2[i][item] = "N/A" elif business["attributes"].get("BusinessParking")!="None": New_BP = business["attributes"]["BusinessParking"].replace("'",'"').replace("True",'"True"').replace("False",'"False"') New_BP = json.loads(New_BP) for item in businessparking: all_cities_2[i][item] = New_BP.get(item) else: for item in businessparking: all_cities_2[i][item] = "N/A" #3. GoodForMeal for i, business in enumerate(all_cities_2): if business["attributes"] is None: for item in goodformeal: all_cities_2[i][item] = "N/A" elif business["attributes"].get("GoodForMeal") is None: for item in goodformeal: all_cities_2[i][item] = "N/A" elif business["attributes"].get("GoodForMeal")!="None": New_GFM = business["attributes"]["GoodForMeal"].replace("'",'"').replace("True",'"True"').replace("False",'"False"') New_GFM = json.loads(New_GFM) for item in goodformeal: all_cities_2[i][item] = New_GFM.get(item) else: for item in goodformeal: all_cities_2[i][item] = "N/A" #Now that we have everything we need, we can output a final json file with open("all_cities_2.json", "w") as file: json.dump(all_cities_2, file, indent=2) #Create a final dataset that can be read into SAS for further data cleaning #First creating an empty list Final_Dataset = [] for business in all_cities_2: temp = {} temp["business_id"] = business["business_id"] temp["stars"] = business["stars"] temp["city"] = business["city"] temp["state"] = business["state"] temp["postal_code"] = business["postal_code"] temp["latitude"] = business["latitude"] temp["longitude"] = business["longitude"] temp["review_count"] = business["review_count"] temp["categories"] = business["categories"] temp["state"] = business["state"] #attributes temp["alcohol"] = business["alcohol"] temp["bikeparking"] = business["bikeparking"] temp["creditcards"] = business["creditcards"] temp["caters"] = business["caters"] temp["goodforkids"] = business["goodforkids"] temp["tv"] = business["tv"] temp["noiselevel"] = business["noiselevel"] temp["outdoorseating"] = business["outdoorseating"] temp["attire"] = business["attire"] temp["delivery"] = business["delivery"] temp["goodforgroups"] = business["goodforgroups"] temp["pricerange"] = business["pricerange"] temp["reservations"] = business["reservations"] temp["takeout"] = business["takeout"] temp["wifi"] = business["wifi"] #the special handling Attributes temp["touristy"] = business["touristy"] temp["casual"] = business["casual"] temp["romantic"] = business["romantic"] temp["intimate"] = business["intimate"] temp["classy"] = business["classy"] temp["hipster"] = business["hipster"] temp["divey"] = business["divey"] temp["trendy"] = business["trendy"] temp["upscale"] = business["upscale"] temp["garage"] = business["garage"] temp["street"] = business["street"] temp["validated"] = business["validated"] temp["lot"] = business["lot"] temp["valet"] = business["valet"] temp["dessert"] = business["dessert"] temp["latenight"] = business["latenight"] temp["lunch"] = business["lunch"] temp["dinner"] = business["dinner"] temp["brunch"] = business["brunch"] temp["breakfast"] = business["breakfast"] #Adding everything to the empty list Final_Dataset.append(temp) #Printing out the first restaurant to see what it looks like print(Final_Dataset[0]) #This dataset will be in a structure that I am more familiar with FD = pd.DataFrame.from_records(Final_Dataset) #Still 29,558 which is what we expect print(len(FD)) #Printing out the first restaurants to see what it looks like print(FD.head()) #Outputting a final csv file, which I will read into SAS for data cleaning FD.to_csv('FD.csv', index=False) #EXTRA - Before data cleaning, looked at yelp "categories" variable to see if there were any common categories #Below steps were run for each of the 8 cities #Creating an empty list categories = [] #Pulling just the category and adding that to the above list for business in all_cities_2: category = business["categories"] categories.append(category) #Within each line, remove the commas categories = [line.replace(",", "") for line in categories] #Creating a dictionary which we need for finding the counts d = dict() #For each word, keep track of the count for line in categories: words = line.split() for w in words: d[w] = d.get(w,0) + 1 #Print the dictionary print(d) #Sorting sorted_d = sorted(d.items(), key=lambda kv: kv[1]) print(sorted_d) #End Result - ended up with 8 common categories: #Bars, Nightlife, Pizza, American, Tea, Sandwiches, Mexican, Burgers #These 8 categories will become new features during SAS data cleaning #Perhaps some of these categories will be significant in predicting star rating
#!/usr/bin/python print("content-type: text/html\n\n") # Import the library with the CGI components and functionality import cgi import random # Use the CGI library to gain access to the information entered in the HTML format form = cgi.FieldStorage() html = "" def roll(num_of_dice): number = [1, 2, 3, 4, 5, 6] rolledNumbers = [] for i in range(0,num_of_dice): rolledNumbers.append(random.choice(number)) # return list of numbers return rolledNumbers dice_Roll = roll(1)[0] try: # All data from a form is a string, convert to an integer to loop through id = int(form.getvalue('number')) except ValueError: html = html + "<p>Please enter only a number.</p>" else: if int(form.getvalue('number')) not in range(1, 7): html = html + "<p>Out of range. Please select and number between 1 and 6.</p>" if id in range(1,7): if id == dice_Roll: html = html + "<p>" + "Congrats! You entered " + str(id) + " and the die rolled a " + str(dice_Roll) + "." + "</p>" else: html = html + "<p>" + "Too bad. You entered " + str(id) + " and the die rolled a " + str(dice_Roll) + "." + "</p>" # Finally output the HTML code and the final html variable print("<html>") print("<body>") print("<h1>Results Page</h1>") print(html) print("<a") print('href="http://www.site03.zourn.com/Week%204/form_GuessDie.html"><font color="blue">Guess/Try Again?</font>') print("</a>") print("<p></p>") print("<a") print('href="http://www.site03.zourn.com/"><font color="blue">home</font>') print("</a>") print("</body>") print("</html>")
# -*- coding: utf-8 -*- """ Created on Tue Jun 12 04:02:50 2018 @author: bjwil Assignment #7 - Test Drive """ # Test Drive 1 - Chapter 3 - Page 113 # instantiating vowel list to search if letters in string match vowels vowels = ['a', 'e', 'i', 'o', 'u'] # create an input prompt for the user to enter a string word = input("Provide a word to search for vowels: ") # empty dictionary found = {} # dictionary keys. You could create a loop like this... for letter in vowels: found[letter] = 0 found['a'] = 0 found['e'] = 0 found['i'] = 0 found['o'] = 0 found['u'] = 0 # check for each letter in the input string if that letter is a vowel in vowels. If so increase the count in the dictionary for that vowel for letter in word: if letter in vowels: found[letter] +=1 # k is the key and v is the value. print for all keys each value. for k, v in sorted(found.items()): print(k, 'was found', v, 'time(s).') # Test Drive 2 - Chapter 3 - Page 131 # instantiating set to search if letters in string match vowels vowels = set('aeiou') # create an input prompt for the user to enter a string word = input("Provide a word to search for vowels: ") # find how many of the vowels in vowels intersect with a leter in string. meaning are the letters in both sets. found = vowels.intersection(set(word)) # print all the vowels that were in both sets. does not count how many however. for vowel in found: print(vowel)
from collections import deque def wallCount(walls, filled, x, y, cellWidth): ''' func: gives the number of walls/ untraversible cells around given cell inp: list of walls, list of cells which are filled, x coord of current cell, y coord of current cell, cellWidth out: count of neighbouring cells which are untraversible ''' left = (x-cellWidth, y) # left neighbour right = (x+cellWidth, y) # right neighbour up = (x, y+cellWidth) # up neighbour down = (x, y-cellWidth) # down neighbour count = 0 # set count to 0 initially if(left in walls or left in filled): # check for left neighbour count+=1 # increase count if(right in walls or right in filled): # check for right neighbour count+=1 # increase count if(up in walls or up in filled): # check for up neighbour count+=1 # increase count if(down in walls or down in filled): # check for down neighbour count+=1 # increase count return count # return the count def start(myTurtle, walls, finish, cellWidth, maze): maze.shape('circle') # set the shape of maze turtle as circle (will be used to mark deadend) maze.color('red') # set the color as red maze.shapesize(cellWidth/48.0) # set the size q = deque() # create a double ended queue visited = [] # list cointaing nodes which are visited filled = [] # list cointaing nodes which are blocked (greyed) deadendList = [] # list of nodes that are deadends x = myTurtle.xcor() # current x coord y = myTurtle.ycor() # current y coord q.append((x,y)) # put current coord in queue # following while loop executes bfs on the maze to look for deadends while (len(q)!=0): x,y = q.popleft() # remove the first entry from the queue left = (x-cellWidth, y) # coord of left neighbour right = (x+cellWidth, y) # coord of right up = (x, y+cellWidth) # coord of up neighbour down = (x, y-cellWidth) # coord of down neighbour if(left not in walls and left not in visited): # left is not a wall and has not been visited q.append(left) # put in queue if(right not in walls and right not in visited): # right is not a wall and has not been visited q.append(right) # put in queue if(up not in walls and up not in visited): # up is not a wall and has not been visited q.append(up) # put in queue if(down not in walls and down not in visited): # down is not a wall and has not been visited q.append(down) # put in queue visited.append((x,y)) # put current node in visited list if(wallCount(walls, filled, x, y, cellWidth)==3 and (x,y) not in finish): # if node is covered from 3 sides and is not the final node deadendList.append((x,y)) # put in the deadend list maze.goto(x,y) # goto that node maze.stamp() # put astemp (red circle) maze.shapesize(cellWidth/24.0) # reset the size of the maze turtle maze.shape('square') # reset shape to square maze.color('grey') # reset color to grey visited = [] # list of all the visited nodes filled = [] # list of all the filled nodes finish.append((myTurtle.xcor(), myTurtle.ycor())) # adding the starting coordinate in finish to avoid blocking it for i in range (len(deadendList)): # loop through deadend list x,y = deadendList[i][0], deadendList[i][1] # set x,y as node's position while(True): # loop if( wallCount(walls, filled, x, y, cellWidth)==3 and (x,y) not in finish): # if node covered from 3 sides and is not the final node visited.append((x,y)) # put node in visited list filled.append((x,y)) # put node in filled list maze.goto(x, y) # goto the node's position maze.stamp() # put a stamp (grey square) left = (x-cellWidth, y) # left neighbour right = (x+cellWidth, y) # right neighbour up = (x, y+cellWidth) # up neighbour down = (x, y-cellWidth) # down neighbour if(left not in walls and left not in visited): # check if left is traversible x, y = left[0], left[1] # update x,y as left neighbour's position if(right not in walls and right not in visited): # check if right is traversible x, y = right[0], right[1] # update x,y as right neighbour's position if(up not in walls and up not in visited): # check if up is traversible x, y = up[0], up[1] # update x,y as up neighbour's position if(down not in walls and down not in visited): # check if down is traversible x, y = down[0], down[1] # update x,y as down neighbour's position else: # if current cell is not blocked from 3 sides break # break the while loop
#!/usr/bin/python3 if __name__ == "__main__": import sys args = sys.argv[1:] count = len(args) sum = 0 for i in range(count): sum = sum + int(args[i]) print(sum)
#!/usr/bin/python3 """Unittest for Base class""" import unittest from models.base import Base from models.rectangle import Rectangle from models.square import Square class TestBase(unittest.TestCase): """ test class""" def setUp(self): """setup for tests""" self.b1 = Base() self.b2 = Base() self.b3 = Base() self.b4 = Base(12) self.b5 = Base() self.r1 = Rectangle(10, 7, 2, 8, 1) self.s1 = Square(10, 7, 2, 8) self.dic1 = self.r1.to_dictionary() self.dic2 = self.s1.to_dictionary() self.dic3 = {} def test_id(self): """ testing the id""" self.assertEqual(self.b1.id, 7) self.assertEqual(self.b2.id, 8) self.assertEqual(self.b3.id, 9) self.assertEqual(self.b4.id, 12) self.assertEqual(self.b5.id, 10) def test_json_str_dic(self): """ testing the json string and...""" self.assertEqual([self.dic1], Rectangle.from_json_string( Rectangle.to_json_string([self.dic1]))) self.assertEqual([self.dic2], Square.from_json_string( Square.to_json_string([self.dic2]))) self.assertEqual([self.dic3], Base.from_json_string( Base.to_json_string([self.dic3]))) self.assertEqual(Base.to_json_string([]), '[]') self.assertEqual(Base.to_json_string(None), '[]') self.assertEqual(Base.to_json_string(3), '3') def test_create(self): """ testing create function """ self.assertEqual(str(Rectangle.create(**self.dic1)), str(self.r1)) self.assertEqual(str(Square.create(**self.dic2)), str(self.s1))
#!/usr/bin/python3 """THis is a rectangle class""" class Rectangle: """rectangle""" @property def width(self): return self.width @width.setter def width(self, value): if not isinstance(
#!/usr/bin/python3 for i in range(8): for j in range(10): if j > i: print("{:d}{:d}, " .format(i, j), end='') print("{:d}".format(89))
#!/usr/bin/python3 class Square: __size = None def __init__(self, new_size=None): self.is_new = True if new_size is not None: self.size = new_size
#!/usr/bin/python3 """ rectangle class """ from models.base import Base class Rectangle(Base): """ rectangle class""" @property def width(self): """ widh getter""" return self.__width @width.setter def width(self, width): """ width setter""" if type(width) != int: raise TypeError("width must be an integer") if width < 1: raise ValueError("width must be > 0") self.__width = width @property def height(self): """height getter""" return self.__height @height.setter def height(self, height): """height setter""" if type(height) != int: raise TypeError("height must be an integer") if height < 1: raise ValueError("height must be > 0") self.__height = height @property def x(self): """ x getter""" return self.__x @x.setter def x(self, x): """x setter""" if type(x) != int: raise TypeError("x must be an integer") if x < 0: raise ValueError("x must be >= 0") self.__x = x @property def y(self): """ y getter""" return self.__y @y.setter def y(self, y): """y setter""" if type(y) != int: raise TypeError("y must be an integer") if y < 0: raise ValueError("y must be >= 0") self.__y = y def area(self): """ area calc""" return (self.__width * self.__height) def display(self): """ displays shape""" for i in range(0, self.__y): print('') for i in range(0, self.__height): for j in range(0, self.__x): print(' ', end='') for j in range(0, self.__width): print('#', end='') if i != self.__height: print('') def __str__(self): """ returns shape discription""" st = "[Rectangle] (" + str(self.id) + ') ' + str(self.__x) + '/' st += str(self.__y) st += " - " + str(self.__width) + '/' + str(self.__height) return st def update(self, *args, **kwargs): """ updates shape""" if (args) and args != (): if len(args) >= 1: super(Rectangle, self).__init__(args[0]) if len(args) >= 2: self.width = args[1] if len(args) >= 3: self.height = args[2] if len(args) >= 4: self.x = args[3] if len(args) >= 5: self.y = args[4] else: for k, v in kwargs.items(): if k == "id": super(Rectangle, self).__init__(v) if k == "width": self.width = v if k == "height": self.height = v if k == "x": self.x = v if k == "y": self.y = v def to_dictionary(self): """ makes dic out of shapes data""" dic = {'x': self.__x, 'y': self.__y, 'id': self.id, 'width': self.__width, 'height': self.__height} return dic def __init__(self, width, height, x=0, y=0, id=None): """ initialization""" super(Rectangle, self).__init__(id) self.width = width self.x = x self.y = y self.height = height
liquor=int(input('请输入一个数字:')) if 100>=liquor>=90: print('A') elif 90>liquor>=80: print('B') elif 80>liquor>=60: print('C') elif 60>liquor>=0: print('D') else: print("输入错误!")
import random x = random.randrange(100,201) #产生一个[100,200]之间的随机数x maxn = x print(x,end="") for i in range(2,11): x = random.randrange(100,201) #再产生一个[100,201]之间的随机数x print(x,end="") if x>maxn: maxn = x; print("最大数:",maxn)
import time ### Source: https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwjZk5fmg6DXAhUCPhQKHVdBDBcQjRwIBw&url=http%3A%2F%2Fwww.woojr.com%2Fsummer-mad-libs%2Ffunny-mad-libs%2F&psig=AOvVaw0Mq2_JCsyidLCX4f6V7TT-&ust=1509716868331291 print("Write an adjective") adjective1 = input() print("Write a nationality") nationality1 = input() print("Write a name") name1 = input() print("Write another noun") noun1 = input() print("Write another adjective") adjective2 = input() print("Write another noun") noun2 = input() print("Write another adjective") adjective3 = input () print("Write another adjective") adjective4 = input () print("Write a plural noun") pluralnoun1 = input() print("Write another noun") noun3 = input () print("Write a number") number1 = input () print("Write a shape") shape1 = input () if number1 != "1": shape1 = shape1 + "s" print("Write a food") food1 = input () print("Write another food") food2 = input () print("Write another number") number2 = input () ### MAD LIB ### print("Pizza was invented by a " + adjective1 + " " + nationality1 + " chef named " + name1 + ". " + "To make pizza, you need to take a lump of " + noun1 + ", make a thin, round " + adjective2 + " " + noun2 + ". Then you cover it with " + adjective3 + " sauce, " + adjective4 + " cheese,and fresh chopped " + pluralnoun1 + ". Next you have to bake it in a very hot " + noun3 + ". When it is done, cut it into " + number1 + " " + shape1 + ". Some kids like " + food1 + " pizza the best, but my favorite is the " + food2 + " pizza. If I could, I would eat pizza " + number2 + " times a day!") time.sleep(100)
class Solution: def longestCommonPrefix(self, m) -> str: if not m: return "" shortest=min(m,key=len) for i, letter in enumerate(shortest): for j in m: if j[i] != letter: return shortest[:i] return shortest func=Solution() strs = ["cir","car"] print(func.longestCommonPrefix(strs))
# count 1s in list and ignore 0s # i.e. [1,0,1,1,0,0,0,0,1,1,1,1,1] = 1, 2, 5 a = [0,0,0,0,0] b = [1,1,1,1,1] c = [0,1,1,1,1,1,0,1,1,1,1] d = [1,1,0,1,0,0,1,1,1,0,0] e = [0,0,0,0,1,1,0,0,1,0,1,1,1] f = [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1] def nonogram(binary_array): nonogram_list = [] one_count = 0 for element in binary_array: if element == 1: one_count += 1 else: if one_count > 0: nonogram_list.append(one_count) one_count = 0 if one_count > 0: nonogram_list.append(one_count) print(nonogram_list) nonogram(a) nonogram(b) nonogram(c) nonogram(d) nonogram(e) nonogram(f)
class hashTable: def __init__(self, length): self.len = length *2 self.buckets = [None] * self.len def getIndex(self, key): index = hash(key) % self.len return index def set(self, key, value): index = self.getIndex(key) if self.buckets[index] is None: self.buckets[index] = [] self.buckets[index].append([key, value]) else: for kvp in self.buckets[index]: if kvp == key: kvp[1] = value else: self.buckets[index].append([key, value]) def get(self, key): index = self.getIndex(key) if self.buckets[index] is None: print('key', key, 'not found') raise KeyError if self.buckets[index][0][0] == key: return self.buckets[index][0][1] else: for kvp in self.buckets[index]: if kvp[0] == key: return kvp[1] else: print('key', key, 'not found') raise KeyError print('key', key, 'not found') raise KeyError def remove(self, key): index = self.getIndex(key) if self.buckets[index] is None: print('key', key, 'not found') raise KeyError for kvp in self.buckets[index]: if kvp[0] == key: del kvp[0] return else: print('key', key, 'not found') raise KeyError # jake = hashTable(25) # # jake.set(33, 'wingus') # jake.set(133, 'bringus') # print(jake.get(33)) # print(jake.get(133)) # jake.set(55, 'amongus') # print(jake.get(55)) # jake.remove(55)