lnxknl / lnxknl.github.io

1 stars 0 forks source link

Daily thinking #7

Open lnxknl opened 1 year ago

lnxknl commented 1 year ago

Record something

lnxknl commented 1 year ago

-66d3c498b4afdac1.jpg

lnxknl commented 1 year ago

-98be1d8005ea832.jpg

lnxknl commented 1 year ago

image

lnxknl4 commented 1 year ago

Sure! Here's an example of a greedy algorithm in Python. This is a simple implementation of the "coin change" problem, where we need to find the minimum number of coins required to make a certain amount of money, given a set of coin denominations:

python Copy code def coin_change(amount, coins):

Sort coins in descending order

coins.sort(reverse=True)

# Initialize coin count and index
coin_count = 0
i = 0

while amount > 0:
    if coins[i] <= amount:
        # Take the largest coin possible
        amount -= coins[i]
        coin_count += 1
    else:
        # Move to the next smaller coin
        i += 1

    if i == len(coins):
        # No more coins to try
        break

if amount == 0:
    # Amount has been fully covered by coins
    return coin_count
else:
    # Amount could not be covered by coins
    return -1

In this algorithm, we first sort the list of coin denominations in descending order. Then we loop through the coins, starting with the largest denomination, and subtract as many coins as possible from the remaining amount. We keep track of the number of coins used so far, and move on to the next smaller coin if the current coin is too large. If we run out of coins to try, or if there is still some amount remaining after trying all coins, we return -1 to indicate that a valid coin combination could not be found. Otherwise, we return the number of coins used.

jjmutong@gmail.com a Dynamic Programming example in python Sure, here's an example of solving the knapsack problem using dynamic programming in Python:

python Copy code def knapsack(weights, values, capacity): n = len(weights)

Create a table to store the maximum value that can be obtained

# with each combination of items and remaining capacity
table = [[0 for j in range(capacity + 1)] for i in range(n + 1)]

# Fill the table in a bottom-up manner
for i in range(1, n + 1):
    for j in range(1, capacity + 1):
        if weights[i-1] <= j:
            # If the current item can fit in the remaining capacity,
            # choose whether to include it or not based on which choice
            # yields a higher total value
            table[i][j] = max(values[i-1] + table[i-1][j-weights[i-1]], table[i-1][j])
        else:
            # If the current item doesn't fit, just copy the value from
            # the previous row for the same capacity
            table[i][j] = table[i-1][j]

# Return the maximum value that can be obtained with the given capacity
return table[n][capacity]

This function takes three arguments:

weights: a list of the weights of the items values: a list of the values of the items capacity: the maximum capacity of the knapsack The function returns the maximum value that can be obtained by selecting a subset of the items with total weight no greater than the capacity.

The idea behind the dynamic programming solution is to fill in a table where each cell (i, j) represents the maximum value that can be obtained using the first i items and a knapsack with capacity j. The base case is when there are no items and/or no capacity, in which case the maximum value is zero. For each item, we consider two possibilities: either we include it in the knapsack, in which case we add its value to the maximum value that can be obtained with the remaining capacity and the remaining items; or we don't include it, in which case we just use the maximum value that can be obtained with the remaining items and the same capacity. We choose the option that yields a higher total value. Once we've filled in the table, the answer is in the cell (n, capacity), which represents the maximum value that can be obtained using all the items and the full capacity of the knapsack.

jjmutong@gmail.com A Divide and Conquer example in python Here's an example of the Divide and Conquer technique in Python. The following function merge_sort() sorts an array of integers using the divide and conquer approach:

python Copy code def merge_sort(arr): if len(arr) <= 1: return arr

mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]

left = merge_sort(left)
right = merge_sort(right)

return merge(left, right)

def merge(left, right): result = [] i = 0 j = 0

while i < len(left) and j < len(right):
    if left[i] < right[j]:
        result.append(left[i])
        i += 1
    else:
        result.append(right[j])
        j += 1

result += left[i:]
result += right[j:]

return result

In the merge_sort() function, the input array is divided into two halves and each half is recursively sorted using the merge_sort() function. The merge() function is used to merge the two sorted halves to obtain the final sorted array.

This algorithm has a time complexity of O(n log n) in the average and worst case.

jjmutong@gmail.com A Randomized Algorithms example in python Here's an example of a randomized algorithm in Python:

scss Copy code import random

def quicksort(arr): if len(arr) <= 1: return arr pivot = random.choice(arr) left, equal, right = [], [], [] for i in arr: if i < pivot: left.append(i) elif i == pivot: equal.append(i) else: right.append(i) return quicksort(left) + equal + quicksort(right)

arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_arr = quicksort(arr) print(sorted_arr) In this example, we implement the quicksort algorithm using a randomized approach to select the pivot element. Instead of selecting the first or last element of the array as the pivot, we use the random.choice() function to select a random element from the array as the pivot. This helps to avoid worst-case scenarios where the input array is already sorted or nearly sorted.

jjmutong@gmail.com A Backtracking example in python Sure, here's an example of a backtracking algorithm implemented in Python to solve the N-Queens problem:

python Copy code def solve_n_queens(n): def is_valid(board, row, col):

check if there is a queen in the same column

    for i in range(row):
        if board[i] == col:
            return False

    # check if there is a queen on the diagonal from top left to bottom right
    i, j = row - 1, col - 1
    while i >= 0 and j >= 0:
        if board[i] == j:
            return False
        i, j = i - 1, j - 1

    # check if there is a queen on the diagonal from top right to bottom left
    i, j = row - 1, col + 1
    while i >= 0 and j < n:
        if board[i] == j:
            return False
        i, j = i - 1, j + 1

    return True

def backtrack(board, row):
    if row == n:
        # found a valid solution
        result.append(board[:])
        return

    for col in range(n):
        if is_valid(board, row, col):
            board[row] = col
            backtrack(board, row + 1)
            board[row] = -1

result = []
board = [-1] * n
backtrack(board, 0)
return result

In this example, the solve_n_queens function takes an integer n as input and returns a list of lists representing valid solutions to the N-Queens problem for a board of size n x n. The algorithm uses backtracking to explore all possible configurations of the board, and only adds a queen to a row if it is safe to do so (i.e., there are no other queens in the same column or on the same diagonal). Once a valid solution is found, it is added to the result list and the algorithm continues to search for more solutions.

lnxknl commented 1 year ago

IMG_20230408_184546.jpg