function
stringlengths 18
3.86k
| intent_category
stringlengths 5
24
|
---|---|
def _is_unbound(self, index):
return bool(0.0 < self.alphas[index] < self._c) | machine_learning |
def _is_support(self, index):
return bool(self.alphas[index] > 0) | machine_learning |
def unbound(self):
return self._unbound | machine_learning |
def support(self):
return [i for i in range(self.length) if self._is_support(i)] | machine_learning |
def length(self):
return self.samples.shape[0] | machine_learning |
def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0):
self.degree = np.float64(degree)
self.coef0 = np.float64(coef0)
self.gamma = np.float64(gamma)
self._kernel_name = kernel
self._kernel = self._get_kernel(kernel_name=kernel)
self._check() | machine_learning |
def _polynomial(self, v1, v2):
return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree | machine_learning |
def _linear(self, v1, v2):
return np.inner(v1, v2) + self.coef0 | machine_learning |
def _rbf(self, v1, v2):
return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) | machine_learning |
def _check(self):
if self._kernel == self._rbf and self.gamma < 0:
raise ValueError("gamma value must greater than 0") | machine_learning |
def _get_kernel(self, kernel_name):
maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf}
return maps[kernel_name] | machine_learning |
def __call__(self, v1, v2):
return self._kernel(v1, v2) | machine_learning |
def __repr__(self):
return self._kernel_name | machine_learning |
def call_func(*args, **kwargs):
import time
start_time = time.time()
func(*args, **kwargs)
end_time = time.time()
print(f"smo algorithm cost {end_time - start_time} seconds") | machine_learning |
def test_cancel_data():
print("Hello!\nStart test svm by smo algorithm!")
# 0: download dataset and load into pandas' dataframe
if not os.path.exists(r"cancel_data.csv"):
request = urllib.request.Request(
CANCER_DATASET_URL,
headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"},
)
response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
with open(r"cancel_data.csv", "w") as f:
f.write(content)
data = pd.read_csv(r"cancel_data.csv", header=None)
# 1: pre-processing data
del data[data.columns.tolist()[0]]
data = data.dropna(axis=0)
data = data.replace({"M": np.float64(1), "B": np.float64(-1)})
samples = np.array(data)[:, :]
# 2: dividing data into train_data data and test_data data
train_data, test_data = samples[:328, :], samples[328:, :]
test_tags, test_samples = test_data[:, 0], test_data[:, 1:]
# 3: choose kernel function,and set initial alphas to zero(optional)
mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5)
al = np.zeros(train_data.shape[0])
# 4: calculating best alphas using SMO algorithm and predict test_data samples
mysvm = SmoSVM(
train=train_data,
kernel_func=mykernel,
alpha_list=al,
cost=0.4,
b=0.0,
tolerance=0.001,
)
mysvm.fit()
predict = mysvm.predict(test_samples)
# 5: check accuracy
score = 0
test_num = test_tags.shape[0]
for i in range(test_tags.shape[0]):
if test_tags[i] == predict[i]:
score += 1
print(f"\nall: {test_num}\nright: {score}\nfalse: {test_num - score}")
print(f"Rough Accuracy: {score / test_tags.shape[0]}") | machine_learning |
def test_demonstration():
# change stdout
print("\nStart plot,please wait!!!")
sys.stdout = open(os.devnull, "w")
ax1 = plt.subplot2grid((2, 2), (0, 0))
ax2 = plt.subplot2grid((2, 2), (0, 1))
ax3 = plt.subplot2grid((2, 2), (1, 0))
ax4 = plt.subplot2grid((2, 2), (1, 1))
ax1.set_title("linear svm,cost:0.1")
test_linear_kernel(ax1, cost=0.1)
ax2.set_title("linear svm,cost:500")
test_linear_kernel(ax2, cost=500)
ax3.set_title("rbf kernel svm,cost:0.1")
test_rbf_kernel(ax3, cost=0.1)
ax4.set_title("rbf kernel svm,cost:500")
test_rbf_kernel(ax4, cost=500)
sys.stdout = sys.__stdout__
print("Plot done!!!") | machine_learning |
def test_linear_kernel(ax, cost):
train_x, train_y = make_blobs(
n_samples=500, centers=2, n_features=2, random_state=1
)
train_y[train_y == 0] = -1
scaler = StandardScaler()
train_x_scaled = scaler.fit_transform(train_x, train_y)
train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled))
mykernel = Kernel(kernel="linear", degree=5, coef0=1, gamma=0.5)
mysvm = SmoSVM(
train=train_data,
kernel_func=mykernel,
cost=cost,
tolerance=0.001,
auto_norm=False,
)
mysvm.fit()
plot_partition_boundary(mysvm, train_data, ax=ax) | machine_learning |
def test_rbf_kernel(ax, cost):
train_x, train_y = make_circles(
n_samples=500, noise=0.1, factor=0.1, random_state=1
)
train_y[train_y == 0] = -1
scaler = StandardScaler()
train_x_scaled = scaler.fit_transform(train_x, train_y)
train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled))
mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5)
mysvm = SmoSVM(
train=train_data,
kernel_func=mykernel,
cost=cost,
tolerance=0.001,
auto_norm=False,
)
mysvm.fit()
plot_partition_boundary(mysvm, train_data, ax=ax) | machine_learning |
def plot_partition_boundary(
model, train_data, ax, resolution=100, colors=("b", "k", "r")
):
train_data_x = train_data[:, 1]
train_data_y = train_data[:, 2]
train_data_tags = train_data[:, 0]
xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution)
yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution)
test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape(
resolution * resolution, 2
)
test_tags = model.predict(test_samples, classify=False)
grid = test_tags.reshape((len(xrange), len(yrange)))
# Plot contour map which represents the partition boundary
ax.contour(
xrange,
yrange,
np.mat(grid).T,
levels=(-1, 0, 1),
linestyles=("--", "-", "--"),
linewidths=(1, 1, 1),
colors=colors,
)
# Plot all train samples
ax.scatter(
train_data_x,
train_data_y,
c=train_data_tags,
cmap=plt.cm.Dark2,
lw=0,
alpha=0.5,
)
# Plot support vectors
support = model.support
ax.scatter(
train_data_x[support],
train_data_y[support],
c=train_data_tags[support],
cmap=plt.cm.Dark2,
) | machine_learning |
def collect_dataset():
response = requests.get(
"https://raw.githubusercontent.com/yashLadha/The_Math_of_Intelligence/"
"master/Week1/ADRvsRating.csv"
)
lines = response.text.splitlines()
data = []
for item in lines:
item = item.split(",")
data.append(item)
data.pop(0) # This is for removing the labels from the list
dataset = np.matrix(data)
return dataset | machine_learning |
def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta):
n = len_data
prod = np.dot(theta, data_x.transpose())
prod -= data_y.transpose()
sum_grad = np.dot(prod, data_x)
theta = theta - (alpha / n) * sum_grad
return theta | machine_learning |
def sum_of_square_error(data_x, data_y, len_data, theta):
prod = np.dot(theta, data_x.transpose())
prod -= data_y.transpose()
sum_elem = np.sum(np.square(prod))
error = sum_elem / (2 * len_data)
return error | machine_learning |
def run_linear_regression(data_x, data_y):
iterations = 100000
alpha = 0.0001550
no_features = data_x.shape[1]
len_data = data_x.shape[0] - 1
theta = np.zeros((1, no_features))
for i in range(0, iterations):
theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta)
error = sum_of_square_error(data_x, data_y, len_data, theta)
print(f"At Iteration {i + 1} - Error is {error:.5f}")
return theta | machine_learning |
def mean_absolute_error(predicted_y, original_y):
total = sum(abs(y - predicted_y[i]) for i, y in enumerate(original_y))
return total / len(original_y) | machine_learning |
def data_handling(data: dict) -> tuple:
# Split dataset into features and target. Data is features.
return (data["data"], data["target"]) | machine_learning |
def xgboost(
features: np.ndarray, target: np.ndarray, test_features: np.ndarray
) -> np.ndarray:
xgb = XGBRegressor(verbosity=0, random_state=42)
xgb.fit(features, target)
# Predict target for test data
predictions = xgb.predict(test_features)
predictions = predictions.reshape(len(predictions), 1)
return predictions | machine_learning |
def main() -> None:
# Load California house price dataset
california = fetch_california_housing()
data, target = data_handling(california)
x_train, x_test, y_train, y_test = train_test_split(
data, target, test_size=0.25, random_state=1
)
predictions = xgboost(x_train, y_train, x_test)
# Error printing
print(f"Mean Absolute Error : {mean_absolute_error(y_test, predictions)}")
print(f"Mean Square Error : {mean_squared_error(y_test, predictions)}") | machine_learning |
def wrapper(y):
return list(y) | machine_learning |
def viz_polymonial():
plt.scatter(X, y, color="red")
plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color="blue")
plt.title("Truth or Bluff (Linear Regression)")
plt.xlabel("Position level")
plt.ylabel("Salary")
plt.show()
return | machine_learning |
def weighted_matrix(
point: np.array, training_data_x: np.array, bandwidth: float
) -> np.array:
m, _ = np.shape(training_data_x) # m is the number of training samples
weights = np.eye(m) # Initializing weights as identity matrix
# calculating weights for all training examples [x(i)'s]
for j in range(m):
diff = point - training_data_x[j]
weights[j, j] = np.exp(diff @ diff.T / (-2.0 * bandwidth**2))
return weights | machine_learning |
def local_weight(
point: np.array,
training_data_x: np.array,
training_data_y: np.array,
bandwidth: float,
) -> np.array:
weight = weighted_matrix(point, training_data_x, bandwidth)
w = np.linalg.inv(training_data_x.T @ (weight @ training_data_x)) @ (
training_data_x.T @ weight @ training_data_y.T
)
return w | machine_learning |
def local_weight_regression(
training_data_x: np.array, training_data_y: np.array, bandwidth: float
) -> np.array:
m, _ = np.shape(training_data_x)
ypred = np.zeros(m)
for i, item in enumerate(training_data_x):
ypred[i] = item @ local_weight(
item, training_data_x, training_data_y, bandwidth
)
return ypred | machine_learning |
def load_data(
dataset_name: str, cola_name: str, colb_name: str
) -> tuple[np.array, np.array, np.array, np.array]:
import seaborn as sns
data = sns.load_dataset(dataset_name)
col_a = np.array(data[cola_name]) # total_bill
col_b = np.array(data[colb_name]) # tip
mcol_a = col_a.copy()
mcol_b = col_b.copy()
one = np.ones(np.shape(mcol_b)[0], dtype=int)
# pairing elements of one and mcol_a
training_data_x = np.column_stack((one, mcol_a))
return training_data_x, mcol_b, col_a, col_b | machine_learning |
def get_preds(training_data_x: np.array, mcol_b: np.array, tau: float) -> np.array:
ypred = local_weight_regression(training_data_x, mcol_b, tau)
return ypred | machine_learning |
def plot_preds(
training_data_x: np.array,
predictions: np.array,
col_x: np.array,
col_y: np.array,
cola_name: str,
colb_name: str,
) -> plt.plot:
xsort = training_data_x.copy()
xsort.sort(axis=0)
plt.scatter(col_x, col_y, color="blue")
plt.plot(
xsort[:, 1],
predictions[training_data_x[:, 1].argsort(0)],
color="yellow",
linewidth=5,
)
plt.title("Local Weighted Regression")
plt.xlabel(cola_name)
plt.ylabel(colb_name)
plt.show() | machine_learning |
def linear_regression_prediction(
train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list
) -> float:
x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)])
y = np.array(train_usr)
beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y)
return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]) | machine_learning |
def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float:
order = (1, 2, 1)
seasonal_order = (1, 1, 0, 7)
model = SARIMAX(
train_user, exog=train_match, order=order, seasonal_order=seasonal_order
)
model_fit = model.fit(disp=False, maxiter=600, method="nm")
result = model_fit.predict(1, len(test_match), exog=[test_match])
return result[0] | machine_learning |
def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float:
regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1)
regressor.fit(x_train, train_user)
y_pred = regressor.predict(x_test)
return y_pred[0] | machine_learning |
def interquartile_range_checker(train_user: list) -> float:
train_user.sort()
q1 = np.percentile(train_user, 25)
q3 = np.percentile(train_user, 75)
iqr = q3 - q1
low_lim = q1 - (iqr * 0.1)
return low_lim | machine_learning |
def data_safety_checker(list_vote: list, actual_result: float) -> bool:
safe = 0
not_safe = 0
for i in list_vote:
if i > actual_result:
safe = not_safe + 1
else:
if abs(abs(i) - abs(actual_result)) <= 0.1:
safe += 1
else:
not_safe += 1
return safe > not_safe | machine_learning |
def xnor_gate(input_1: int, input_2: int) -> int:
return 1 if input_1 == input_2 else 0 | boolean_algebra |
def test_xnor_gate() -> None:
assert xnor_gate(0, 0) == 1
assert xnor_gate(0, 1) == 0
assert xnor_gate(1, 0) == 0
assert xnor_gate(1, 1) == 1 | boolean_algebra |
def compare_string(string1: str, string2: str) -> str | Literal[False]:
list1 = list(string1)
list2 = list(string2)
count = 0
for i in range(len(list1)):
if list1[i] != list2[i]:
count += 1
list1[i] = "_"
if count > 1:
return False
else:
return "".join(list1) | boolean_algebra |
def check(binary: list[str]) -> list[str]:
pi = []
while True:
check1 = ["$"] * len(binary)
temp = []
for i in range(len(binary)):
for j in range(i + 1, len(binary)):
k = compare_string(binary[i], binary[j])
if k is False:
check1[i] = "*"
check1[j] = "*"
temp.append("X")
for i in range(len(binary)):
if check1[i] == "$":
pi.append(binary[i])
if len(temp) == 0:
return pi
binary = list(set(temp)) | boolean_algebra |
def decimal_to_binary(no_of_variable: int, minterms: Sequence[float]) -> list[str]:
temp = []
for minterm in minterms:
string = ""
for _ in range(no_of_variable):
string = str(minterm % 2) + string
minterm //= 2
temp.append(string)
return temp | boolean_algebra |
def is_for_table(string1: str, string2: str, count: int) -> bool:
list1 = list(string1)
list2 = list(string2)
count_n = 0
for i in range(len(list1)):
if list1[i] != list2[i]:
count_n += 1
return count_n == count | boolean_algebra |
def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:
temp = []
select = [0] * len(chart)
for i in range(len(chart[0])):
count = 0
rem = -1
for j in range(len(chart)):
if chart[j][i] == 1:
count += 1
rem = j
if count == 1:
select[rem] = 1
for i in range(len(select)):
if select[i] == 1:
for j in range(len(chart[0])):
if chart[i][j] == 1:
for k in range(len(chart)):
chart[k][j] = 0
temp.append(prime_implicants[i])
while True:
max_n = 0
rem = -1
count_n = 0
for i in range(len(chart)):
count_n = chart[i].count(1)
if count_n > max_n:
max_n = count_n
rem = i
if max_n == 0:
return temp
temp.append(prime_implicants[rem])
for i in range(len(chart[0])):
if chart[rem][i] == 1:
for j in range(len(chart)):
chart[j][i] = 0 | boolean_algebra |
def prime_implicant_chart(
prime_implicants: list[str], binary: list[str]
) -> list[list[int]]:
chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))]
for i in range(len(prime_implicants)):
count = prime_implicants[i].count("_")
for j in range(len(binary)):
if is_for_table(prime_implicants[i], binary[j], count):
chart[i][j] = 1
return chart | boolean_algebra |
def main() -> None:
no_of_variable = int(input("Enter the no. of variables\n"))
minterms = [
float(x)
for x in input(
"Enter the decimal representation of Minterms 'Spaces Separated'\n"
).split()
]
binary = decimal_to_binary(no_of_variable, minterms)
prime_implicants = check(binary)
print("Prime Implicants are:")
print(prime_implicants)
chart = prime_implicant_chart(prime_implicants, binary)
essential_prime_implicants = selection(chart, prime_implicants)
print("Essential Prime Implicants are:")
print(essential_prime_implicants) | boolean_algebra |
def or_gate(input_1: int, input_2: int) -> int:
return int((input_1, input_2).count(1) != 0) | boolean_algebra |
def test_or_gate() -> None:
assert or_gate(0, 0) == 0
assert or_gate(0, 1) == 1
assert or_gate(1, 0) == 1
assert or_gate(1, 1) == 1 | boolean_algebra |
def not_gate(input_1: int) -> int:
return 1 if input_1 == 0 else 0 | boolean_algebra |
def test_not_gate() -> None:
assert not_gate(0) == 1
assert not_gate(1) == 0 | boolean_algebra |
def nor_gate(input_1: int, input_2: int) -> int:
return int(input_1 == input_2 == 0) | boolean_algebra |
def main() -> None:
print("Truth Table of NOR Gate:")
print("| Input 1 | Input 2 | Output |")
print(f"| 0 | 0 | {nor_gate(0, 0)} |")
print(f"| 0 | 1 | {nor_gate(0, 1)} |")
print(f"| 1 | 0 | {nor_gate(1, 0)} |")
print(f"| 1 | 1 | {nor_gate(1, 1)} |") | boolean_algebra |
def nand_gate(input_1: int, input_2: int) -> int:
return int((input_1, input_2).count(0) != 0) | boolean_algebra |
def test_nand_gate() -> None:
assert nand_gate(0, 0) == 1
assert nand_gate(0, 1) == 1
assert nand_gate(1, 0) == 1
assert nand_gate(1, 1) == 0 | boolean_algebra |
def and_gate(input_1: int, input_2: int) -> int:
return int((input_1, input_2).count(0) == 0) | boolean_algebra |
def test_and_gate() -> None:
assert and_gate(0, 0) == 0
assert and_gate(0, 1) == 0
assert and_gate(1, 0) == 0
assert and_gate(1, 1) == 1 | boolean_algebra |
def xor_gate(input_1: int, input_2: int) -> int:
return (input_1, input_2).count(0) % 2 | boolean_algebra |
def test_xor_gate() -> None:
assert xor_gate(0, 0) == 0
assert xor_gate(0, 1) == 1
assert xor_gate(1, 0) == 1
assert xor_gate(1, 1) == 0 | boolean_algebra |
def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]:
result: list[list[int]] = []
path: list[int] = []
num_index = 0
remaining_nums_sum = sum(nums)
create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)
return result | backtracking |
def create_state_space_tree(
nums: list[int],
max_sum: int,
num_index: int,
path: list[int],
result: list[list[int]],
remaining_nums_sum: int,
) -> None:
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
return
if sum(path) == max_sum:
result.append(path)
return
for index in range(num_index, len(nums)):
create_state_space_tree(
nums,
max_sum,
index + 1,
[*path, nums[index]],
result,
remaining_nums_sum - nums[index],
) | backtracking |
def valid_coloring(
neighbours: list[int], colored_vertices: list[int], color: int
) -> bool:
# Does any neighbour not satisfy the constraints
return not any(
neighbour == 1 and colored_vertices[i] == color
for i, neighbour in enumerate(neighbours)
) | backtracking |
def util_color(
graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int
) -> bool:
# Base Case
if index == len(graph):
return True
# Recursive Step
for i in range(max_colors):
if valid_coloring(graph[index], colored_vertices, i):
# Color current vertex
colored_vertices[index] = i
# Validate coloring
if util_color(graph, max_colors, colored_vertices, index + 1):
return True
# Backtrack
colored_vertices[index] = -1
return False | backtracking |
def minimax(
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
) -> int:
if depth < 0:
raise ValueError("Depth cannot be less than 0")
if len(scores) == 0:
raise ValueError("Scores cannot be empty")
if depth == height:
return scores[node_index]
if is_max:
return max(
minimax(depth + 1, node_index * 2, False, scores, height),
minimax(depth + 1, node_index * 2 + 1, False, scores, height),
)
return min(
minimax(depth + 1, node_index * 2, True, scores, height),
minimax(depth + 1, node_index * 2 + 1, True, scores, height),
) | backtracking |
def main() -> None:
scores = [90, 23, 6, 33, 21, 65, 123, 34423]
height = math.log(len(scores), 2)
print("Optimal value : ", end="")
print(minimax(0, 0, True, scores, height)) | backtracking |
def depth_first_search(
possible_board: list[int],
diagonal_right_collisions: list[int],
diagonal_left_collisions: list[int],
boards: list[list[str]],
n: int,
) -> None:
# Get next row in the current board (possible_board) to fill it with a queen
row = len(possible_board)
# If row is equal to the size of the board it means there are a queen in each row in
# the current board (possible_board)
if row == n:
# We convert the variable possible_board that looks like this: [1, 3, 0, 2] to
# this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . ']
boards.append([". " * i + "Q " + ". " * (n - 1 - i) for i in possible_board])
return
# We iterate each column in the row to find all possible results in each row
for col in range(n):
# We apply that we learned previously. First we check that in the current board
# (possible_board) there are not other same value because if there is it means
# that there are a collision in vertical. Then we apply the two formulas we
# learned before:
#
# 45º: y - x = b or 45: row - col = b
# 135º: y + x = b or row + col = b.
#
# And we verify if the results of this two formulas not exist in their variables
# respectively. (diagonal_right_collisions, diagonal_left_collisions)
#
# If any or these are True it means there is a collision so we continue to the
# next value in the for loop.
if (
col in possible_board
or row - col in diagonal_right_collisions
or row + col in diagonal_left_collisions
):
continue
# If it is False we call dfs function again and we update the inputs
depth_first_search(
[*possible_board, col],
[*diagonal_right_collisions, row - col],
[*diagonal_left_collisions, row + col],
boards,
n,
) | backtracking |
def n_queens_solution(n: int) -> None:
boards: list[list[str]] = []
depth_first_search([], [], [], boards, n)
# Print all the boards
for board in boards:
for column in board:
print(column)
print("")
print(len(boards), "solutions were found.") | backtracking |
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
result: list[list[int]] = []
create_all_state(1, n, k, [], result)
return result | backtracking |
def create_all_state(
increment: int,
total_number: int,
level: int,
current_list: list[int],
total_list: list[list[int]],
) -> None:
if level == 0:
total_list.append(current_list[:])
return
for i in range(increment, total_number - level + 2):
current_list.append(i)
create_all_state(i + 1, total_number, level - 1, current_list, total_list)
current_list.pop() | backtracking |
def print_all_state(total_list: list[list[int]]) -> None:
for i in total_list:
print(*i) | backtracking |
def solve_maze(maze: list[list[int]]) -> bool:
size = len(maze)
# We need to create solution object to save path.
solutions = [[0 for _ in range(size)] for _ in range(size)]
solved = run_maze(maze, 0, 0, solutions)
if solved:
print("\n".join(str(row) for row in solutions))
else:
print("No solution exists!")
return solved | backtracking |
def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool:
size = len(maze)
# Final check point.
if i == j == (size - 1):
solutions[i][j] = 1
return True
lower_flag = (not i < 0) and (not j < 0) # Check lower bounds
upper_flag = (i < size) and (j < size) # Check upper bounds
if lower_flag and upper_flag:
# check for already visited and block points.
block_flag = (not solutions[i][j]) and (not maze[i][j])
if block_flag:
# check visited
solutions[i][j] = 1
# check for directions
if (
run_maze(maze, i + 1, j, solutions)
or run_maze(maze, i, j + 1, solutions)
or run_maze(maze, i - 1, j, solutions)
or run_maze(maze, i, j - 1, solutions)
):
return True
solutions[i][j] = 0
return False
return False | backtracking |
def generate_all_subsequences(sequence: list[Any]) -> None:
create_state_space_tree(sequence, [], 0) | backtracking |
def create_state_space_tree(
sequence: list[Any], current_subsequence: list[Any], index: int
) -> None:
if index == len(sequence):
print(current_subsequence)
return
create_state_space_tree(sequence, current_subsequence, index + 1)
current_subsequence.append(sequence[index])
create_state_space_tree(sequence, current_subsequence, index + 1)
current_subsequence.pop() | backtracking |
def minimax(
depth: int, node_index: int, is_max: bool, scores: list[int], height: float
) -> int:
if depth < 0:
raise ValueError("Depth cannot be less than 0")
if not scores:
raise ValueError("Scores cannot be empty")
if depth == height:
return scores[node_index]
return (
max(
minimax(depth + 1, node_index * 2, False, scores, height),
minimax(depth + 1, node_index * 2 + 1, False, scores, height),
)
if is_max
else min(
minimax(depth + 1, node_index * 2, True, scores, height),
minimax(depth + 1, node_index * 2 + 1, True, scores, height),
)
) | backtracking |
def main() -> None:
scores = [90, 23, 6, 33, 21, 65, 123, 34423]
height = math.log(len(scores), 2)
print(f"Optimal value : {minimax(0, 0, True, scores, height)}") | backtracking |
def is_safe(board: list[list[int]], row: int, column: int) -> bool:
for i in range(len(board)):
if board[row][i] == 1:
return False
for i in range(len(board)):
if board[i][column] == 1:
return False
for i, j in zip(range(row, -1, -1), range(column, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, -1, -1), range(column, len(board))):
if board[i][j] == 1:
return False
return True | backtracking |
def solve(board: list[list[int]], row: int) -> bool:
if row >= len(board):
solution.append(board)
printboard(board)
print()
return True
for i in range(len(board)):
if is_safe(board, row, i):
board[row][i] = 1
solve(board, row + 1)
board[row][i] = 0
return False | backtracking |
def printboard(board: list[list[int]]) -> None:
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 1:
print("Q", end=" ")
else:
print(".", end=" ")
print() | backtracking |
def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
return False
for i in range(3):
for j in range(3):
if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
return False
return True | backtracking |
def find_empty_location(grid: Matrix) -> tuple[int, int] | None:
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return i, j
return None | backtracking |
def sudoku(grid: Matrix) -> Matrix | None:
if location := find_empty_location(grid):
row, column = location
else:
# If the location is ``None``, then the grid is solved.
return grid
for digit in range(1, 10):
if is_safe(grid, row, column, digit):
grid[row][column] = digit
if sudoku(grid) is not None:
return grid
grid[row][column] = 0
return None | backtracking |
def print_solution(grid: Matrix) -> None:
for row in grid:
for cell in row:
print(cell, end=" ")
print() | backtracking |
def get_point_key(len_board: int, len_board_column: int, row: int, column: int) -> int:
return len_board * len_board_column * row + column | backtracking |
def exits_word(
board: list[list[str]],
word: str,
row: int,
column: int,
word_index: int,
visited_points_set: set[int],
) -> bool:
if board[row][column] != word[word_index]:
return False
if word_index == len(word) - 1:
return True
traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
len_board = len(board)
len_board_column = len(board[0])
for direction in traverts_directions:
next_i = row + direction[0]
next_j = column + direction[1]
if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
continue
key = get_point_key(len_board, len_board_column, next_i, next_j)
if key in visited_points_set:
continue
visited_points_set.add(key)
if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set):
return True
visited_points_set.remove(key)
return False | backtracking |
def word_exists(board: list[list[str]], word: str) -> bool:
# Validate board
board_error_message = (
"The board should be a non empty matrix of single chars strings."
)
len_board = len(board)
if not isinstance(board, list) or len(board) == 0:
raise ValueError(board_error_message)
for row in board:
if not isinstance(row, list) or len(row) == 0:
raise ValueError(board_error_message)
for item in row:
if not isinstance(item, str) or len(item) != 1:
raise ValueError(board_error_message)
# Validate word
if not isinstance(word, str) or len(word) == 0:
raise ValueError(
"The word parameter should be a string of length greater than 0."
)
len_board_column = len(board[0])
for i in range(len_board):
for j in range(len_board_column):
if exits_word(
board, word, i, j, 0, {get_point_key(len_board, len_board_column, i, j)}
):
return True
return False | backtracking |
def backtrack(
candidates: list, path: list, answer: list, target: int, previous_index: int
) -> None:
if target == 0:
answer.append(path.copy())
else:
for index in range(previous_index, len(candidates)):
if target >= candidates[index]:
path.append(candidates[index])
backtrack(candidates, path, answer, target - candidates[index], index)
path.pop(len(path) - 1) | backtracking |
def combination_sum(candidates: list, target: int) -> list:
path = [] # type: list[int]
answer = [] # type: list[int]
backtrack(candidates, path, answer, target, 0)
return answer | backtracking |
def main() -> None:
print(combination_sum([-8, 2.3, 0], 1)) | backtracking |
def generate_all_permutations(sequence: list[int | str]) -> None:
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))]) | backtracking |
def create_state_space_tree(
sequence: list[int | str],
current_sequence: list[int | str],
index: int,
index_used: list[int],
) -> None:
if index == len(sequence):
print(current_sequence)
return
for i in range(len(sequence)):
if not index_used[i]:
current_sequence.append(sequence[i])
index_used[i] = True
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
current_sequence.pop()
index_used[i] = False | backtracking |
def valid_connection(
graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int]
) -> bool:
# 1. Validate that path exists between current and next vertices
if graph[path[curr_ind - 1]][next_ver] == 0:
return False
# 2. Validate that next vertex is not already in path
return not any(vertex == next_ver for vertex in path) | backtracking |
def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool:
# Base Case
if curr_ind == len(graph):
# return whether path exists between current and starting vertices
return graph[path[curr_ind - 1]][path[0]] == 1
# Recursive Step
for next_ver in range(0, len(graph)):
if valid_connection(graph, next_ver, curr_ind, path):
# Insert current vertex into path as next transition
path[curr_ind] = next_ver
# Validate created path
if util_hamilton_cycle(graph, path, curr_ind + 1):
return True
# Backtrack
path[curr_ind] = -1
return False | backtracking |
def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]:
y, x = position
positions = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
permissible_positions = []
for position in positions:
y_test, x_test = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(position)
return permissible_positions | backtracking |
def is_complete(board: list[list[int]]) -> bool:
return not any(elem == 0 for row in board for elem in row) | backtracking |
def open_knight_tour_helper(
board: list[list[int]], pos: tuple[int, int], curr: int
) -> bool:
if is_complete(board):
return True
for position in get_valid_pos(pos, len(board)):
y, x = position
if board[y][x] == 0:
board[y][x] = curr + 1
if open_knight_tour_helper(board, position, curr + 1):
return True
board[y][x] = 0
return False | backtracking |
def open_knight_tour(n: int) -> list[list[int]]:
board = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
for j in range(n):
board[i][j] = 1
if open_knight_tour_helper(board, (i, j), 1):
return board
board[i][j] = 0
raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}") | backtracking |
def get_data(source_data: list[list[float]]) -> list[list[float]]:
data_lists: list[list[float]] = []
for data in source_data:
for i, el in enumerate(data):
if len(data_lists) < i + 1:
data_lists.append([])
data_lists[i].append(float(el))
return data_lists | other |