Add files via upload

This commit is contained in:
Aditya
2025-10-08 22:11:08 +05:30
committed by GitHub
commit 27c0b513f6
5 changed files with 193 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
def fibonacci_recursive_series(n):
series = []
def fib_recursive(num):
if num <= 0:
return 0
elif num == 1:
return 1
else:
return fib_recursive(num - 1) + fib_recursive(num - 2)
for i in range(n + 1):
series.append(fib_recursive(i))
print(f"Recursive Fibonacci Series up to {n}:")
print(series)
def fibonacci_iterative_series(n):
series = []
if n >= 0:
series.append(0)
if n >= 1:
series.append(1)
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
series.append(b)
print(f"Iterative Fibonacci Series up to {n}:")
print(series)
# Menu-driven program
def menu():
while True:
print("\n=== Fibonacci Calculator ===")
print("1. Recursive Fibonacci Series")
print("2. Iterative Fibonacci Series")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == '1':
n = int(input("Enter the value of n: "))
fibonacci_recursive_series(n)
elif choice == '2':
n = int(input("Enter the value of n: "))
fibonacci_iterative_series(n)
elif choice == '3':
print("Exiting program...")
sys.exit()
else:
print("Invalid choice! Please enter 1, 2, or 3.")
# Run the menu
menu()
+42
View File
@@ -0,0 +1,42 @@
import heapq
import itertools
def build_huffman_tree(freq):
heap = []
counter = itertools.count() # unique sequence count
for ch, weight in freq.items():
heap.append([weight, next(counter), [ch]]) # add counter as second element
heapq.heapify(heap)
while len(heap) > 1:
low = heapq.heappop(heap)
high = heapq.heappop(heap)
combined_weight = low[0] + high[0]
combined_node = [low[2], high[2]]
heapq.heappush(heap, [combined_weight, next(counter), combined_node])
return heap[0]
def assign_codes(node, prefix="", codebook={}):
# node is [char] for leaf, or [left, right] for internal node
if len(node) == 1 and isinstance(node[0], str):
codebook[node[0]] = prefix
else:
assign_codes(node[0], prefix + "0", codebook)
assign_codes(node[1], prefix + "1", codebook)
return codebook
def huff_en(txt):
freq = {}
for c in txt:
freq[c] = freq.get(c, 0) + 1
root = build_huffman_tree(freq)
codes = assign_codes(root[2]) # Note: root[2] because of tie-breaker
print("Huffman Codes:")
for ch in sorted(codes):
print(f"{ch}: {codes[ch]}")
txt="abbbbbbcccddddddddee"
huff_en(txt)
+31
View File
@@ -0,0 +1,31 @@
def fractional_knapsack(weights, values, capacity):
n = len(values)
ratio = [(values[i] / weights[i], weights[i], values[i]) for i in range(n)]
ratio.sort(reverse=True)
total_value = 0.0
knapsack_items = []
for r, w, v in ratio:
if capacity == 0:
break
if w <= capacity:
capacity -= w
total_value += v
knapsack_items.append((w, v, 1)) # 1 = full item taken
else:
# Take fraction of the item
fraction = capacity / w
total_value += v * fraction
knapsack_items.append((w, v, fraction))
capacity = 0
return total_value, knapsack_items
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
max_value, items_taken = fractional_knapsack(weights, values, capacity)
print("Maximum Value in Knapsack:", max_value)
print("Items taken (weight, value, fraction):")
for item in items_taken:
print(item)
+31
View File
@@ -0,0 +1,31 @@
def knapsack_01(weights, values, capacity):
n = len(values)
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i - 1] <= w:
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w])
else:
dp[i][w] = dp[i - 1][w]
w = capacity
items_taken = []
for i in range(n, 0, -1):
if dp[i][w] != dp[i - 1][w]:
items_taken.append((weights[i - 1], values[i - 1]))
w -= weights[i - 1]
items_taken.reverse() # optional: maintain original order
return dp[n][capacity], items_taken
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
max_value, items = knapsack_01(weights, values, capacity)
print("Maximum Value in Knapsack:", max_value)
print("Items taken (weight, value):")
for item in items:
print(item)
+36
View File
@@ -0,0 +1,36 @@
def is_safe(board, row, col):
for i in range(row):
if board[i] == col or abs(board[i] - col) == abs(i - row):
return False
return True
def solve_n_queens_first(board, row, n):
if row == n:
return board[:] # Return the first solution found
for col in range(n):
if is_safe(board, row, col):
board[row] = col
result = solve_n_queens_first(board, row + 1, n)
if result: # If solution found, return immediately
return result
board[row] = -1 # Backtrack
return None # No solution in this path
def print_solution(board, n):
for row in range(n):
line = ['Q' if i == board[row] else '.' for i in range(n)]
print(" ".join(line))
print()
def n_queens_one_solution(n):
board = [-1] * n
solution = solve_n_queens_first(board, 0, n)
if solution:
print("One valid n-Queens solution:")
print_solution(solution, n)
else:
print("No solution exists.")
# Example: 8-Queens
n_queens_one_solution(8)