Skip to content

Instantly share code, notes, and snippets.

@ansharora28
Created May 9, 2024 05:55
Show Gist options
  • Save ansharora28/ac6699251ec03fdc9ef8d75538939769 to your computer and use it in GitHub Desktop.
Save ansharora28/ac6699251ec03fdc9ef8d75538939769 to your computer and use it in GitHub Desktop.
AI prac
import heapq
def a_star(graph, start, goal, heuristic):
open_list = [(0, start)] # Priority queue with initial node
came_from = {} # Dictionary to store parent nodes
g_score = {node: float('inf') for node in graph} # Initialize g_score to infinity for all nodes
g_score[start] = 0 # Cost from start to start is 0
while open_list:
_, current_node = heapq.heappop(open_list) # Pop node with lowest f_score
if current_node == goal:
path = []
while current_node in came_from:
path.append(current_node)
current_node = came_from[current_node]
return path[::-1] # Reverse path to get it from start to goal
for neighbor in graph[current_node]:
tentative_g_score = g_score[current_node] + graph[current_node][neighbor]
if tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current_node
g_score[neighbor] = tentative_g_score
f_score = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(open_list, (f_score, neighbor))
return None # No path found
# Example graph represented as an adjacency list
graph = {
'A': {'B': 4, 'C': 3},
'B': {'A': 4, 'D': 5},
'C': {'A': 3, 'D': 1},
'D': {'B': 5, 'C': 1}
}
# Example heuristic function (for demonstration purposes)
def heuristic(node, goal):
# Example heuristic: distance from node to goal
distances = {
'A': 2,
'B': 1,
'C': 3,
'D': 0
}
return distances[node]
# Example start and goal nodes
start_node = 'A'
goal_node = 'D'
# Perform A* Search
path = a_star(graph, start_node, goal_node, heuristic)
if path:
print("Path found:", path)
else:
print("No path found.")
from queue import PriorityQueue
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, node, adjacent, cost):
if node not in self.graph:
self.graph[node] = []
self.graph[node].append((adjacent, cost))
def best_first_search(self, start, goal):
visited = set()
pq = PriorityQueue()
pq.put((0, start))
while not pq.empty():
cost, current_node = pq.get()
visited.add(current_node)
print("Visiting node:", current_node)
if current_node == goal:
print("Goal found!")
return True
for neighbor, neighbor_cost in self.graph.get(current_node, []):
if neighbor not in visited:
pq.put((neighbor_cost, neighbor))
print("Goal not found!")
return False
graph = Graph()
num_edges = int(input("Enter the number of edges: "))
for _ in range(num_edges):
node1, node2, cost = input("Enter edge (node1 node2 cost): ").split()
graph.add_edge(node1, node2, int(cost))
start_node = input("Enter the start node: ")
goal_node = input("Enter the goal node: ")
graph.best_first_search(start_node, goal_node)
import heapq
def best_first_search(graph, start, goal):
visited = set()
priority_queue = [(heuristic(start, goal), start)]
while priority_queue:
(cost, current_node) = heapq.heappop(priority_queue)
if current_node not in visited:
visited.add(current_node)
if current_node == goal:
return True
for neighbor in graph[current_node]:
if neighbor not in visited:
heapq.heappush(priority_queue, (heuristic(neighbor, goal), neighbor))
return False
def heuristic(node, goal):
distances = {
'A': 6,
'B': 5,
'C': 4,
'D': 3,
'E': 2,
'F': 1
}
return distances[node]
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
start_node = 'A'
goal_node = 'F'
print("Path exists:", best_first_search(graph, start_node, goal_node))
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
print(vertex, end=' ')
visited.add(vertex)
queue.extend(graph[vertex] - visited)
graph = {
'A': {'B', 'C'},
'B': {'A', 'D', 'E'},
'C': {'A', 'F'},
'D': {'B'},
'E': {'B', 'F'},
'F': {'C', 'E'}
}
print("BFS Traversal:")
bfs(graph, 'A')
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Generate some sample data for binary classification
np.random.seed(0)
X = np.random.rand(100, 2) # Features
y = np.random.randint(0, 2, size=(100,)) # Labels (0 or 1)
# Define the model architecture
model = Sequential([
Dense(32, input_shape=(2,), activation='relu'), # Input layer with 32 neurons and ReLU activation
Dense(1, activation='sigmoid') # Output layer with 1 neuron and Sigmoid activation
])
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X, y, epochs=10, batch_size=32)
# Evaluate the model
loss, accuracy = model.evaluate(X, y)
print(f"Test Loss: {loss}, Test Accuracy: {accuracy}")
nodes = int(input("Enter number of nodes: "))
neighbors_list = []
for i in range(nodes):
neighbors = list(map(int, input(f"Enter neighbors for node {i}: ").split()))
neighbors_list.append(neighbors)
colors = int(input("Enter number of colors: "))
color = [0] * nodes # Initialize color array
# Assign colors to nodes
for i in range(nodes):
color[i] = i % colors
print("Color assignment:", color)
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt
# Load the dataset
home_data = pd.read_csv('Mall_Customers.csv', usecols=['Gender', 'Age', 'Annual Income (k$)', 'Spending Score (1-100)'])
# Visualize the dataset
sns.scatterplot(data=home_data, x='Annual Income (k$)', y='Age', hue='Spending Score (1-100)')
plt.show()
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(home_data[['Annual Income (k$)', 'Age']], home_data['Spending Score (1-100)'], test_size=0.33, random_state=0)
# Normalize the input features
scaler = preprocessing.StandardScaler()
X_train_norm = scaler.fit_transform(X_train)
X_test_norm = scaler.transform(X_test)
# Fit KMeans clustering model
kmeans = KMeans(n_clusters=3, init='k-means++', random_state=0)
kmeans.fit(X_train_norm)
# Visualize clustering results
sns.scatterplot(data=X_train, x='Annual Income (k$)', y='Age', hue=kmeans.labels_)
plt.show()
# Visualize spending score distribution for each cluster
sns.boxplot(x=kmeans.labels_, y=y_train)
plt.show()
# Evaluate clustering performance using silhouette score
silhouette_avg = silhouette_score(X_train_norm, kmeans.labels_, metric='euclidean')
print("Silhouette Score:", silhouette_avg)
# Plot Silhouette scores for different values of K
K = range(2, 8)
silhouette_scores = []
for k in K:
model = KMeans(n_clusters=k, random_state=0).fit(X_train_norm)
silhouette_scores.append(silhouette_score(X_train_norm, model.labels_, metric='euclidean'))
plt.plot(K, silhouette_scores)
plt.xlabel('Number of Clusters (K)')
plt.ylabel('Silhouette Score')
plt.title('Silhouette Score vs Number of Clusters')
plt.show()
class Predicate:
def __init__(self, name, args):
self.name = name
self.args = args
def __str__(self):
return f"{self.name}({', '.join(self.args)})"
def unify_var(var, x, theta):
if var in theta:
return unify(theta[var], x, theta)
elif x in theta:
return unify(var, theta[x], theta)
else:
theta[var] = x
return theta
def unify(x, y, theta):
if theta is None:
return None
elif x == y:
return theta
elif isinstance(x, str) and x.islower():
return unify_var(x, y, theta)
elif isinstance(y, str) and y.islower():
return unify_var(y, x, theta)
elif isinstance(x, Predicate) and isinstance(y, Predicate):
if x.name != y.name or len(x.args) != len(y.args):
return None
else:
for xi, yi in zip(x.args, y.args):
theta = unify(xi, yi, theta)
return theta
else:
return None
def apply_substitution(substitution, expression):
if substitution is None:
return None
if isinstance(expression, str):
return substitution.get(expression, expression)
elif isinstance(expression, Predicate):
return Predicate(expression.name, [apply_substitution(substitution, arg) for arg in expression.args])
else:
return None
def resolve(clause1, clause2):
for literal1 in clause1:
for literal2 in clause2:
if literal1.name == literal2.name and literal1.args != literal2.args:
theta = unify(literal1, literal2, {})
if theta is not None:
new_clause = [apply_substitution(theta, lit) for lit in (clause1 + clause2) if lit != literal1 and lit != literal2]
return new_clause
return None
def resolve_steps(clauses, statements):
new_clauses = clauses[:]
resolved_pairs = []
while True:
for i in range(len(new_clauses)):
for j in range(i + 1, len(new_clauses)):
resolvent = resolve(new_clauses[i], new_clauses[j])
if resolvent is not None and resolvent not in new_clauses:
new_clauses.append(resolvent)
resolved_pairs.append((i, j))
break
else:
continue
break
else:
break
steps = []
for i, j in resolved_pairs:
steps.append((new_clauses[i], new_clauses[j], new_clauses[-1]))
return new_clauses, steps
def display_resolution_steps(steps, statements):
print("Step\tClause 1\tClause 2\tResolvent\tStatement")
for i, step in enumerate(steps):
clause1, clause2, resolvent = step
statement = statements[i] if i < len(statements) else ""
print(f"{i + 1}\t{clause1}\t{clause2}\t{resolvent}\t{statement}")
def main():
clauses = [
[Predicate("p", ["x"]), Predicate("q", ["x"])],
[Predicate("p", ["a"])],
[Predicate("r", ["y"]), Predicate("q", ["y"])]
]
print("Given Clauses:")
for i, clause in enumerate(clauses):
print(f"{i + 1}: {' ∧ '.join(map(str, clause))}")
statements = ["I am hungry", "I am not hungry"]
new_clauses, steps = resolve_steps(clauses, statements)
print("\nResolution Steps:")
display_resolution_steps(steps, statements)
print("\nFinal Clauses:")
for i, clause in enumerate(new_clauses):
print(f"{i + 1}: {' ∧ '.join(map(str, clause))}")
if __name__ == "__main__":
main()
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
# Download the VADER lexicon (if not already downloaded)
nltk.download('vader_lexicon')
# Initialize the VADER sentiment analyzer
sid = SentimentIntensityAnalyzer()
# Sample text for sentiment analysis
text = "NLTK is a great library for natural language processing."
# Perform sentiment analysis
sentiment_scores = sid.polarity_scores(text)
# Interpret sentiment scores
if sentiment_scores['compound'] >= 0.05:
sentiment = "positive"
elif sentiment_scores['compound'] <= -0.05:
sentiment = "negative"
else:
sentiment = "neutral"
# Print sentiment scores and interpretation
print("Sentiment Scores:", sentiment_scores)
print("Sentiment:", sentiment)
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
nltk.download('punkt')
nltk.download('stopwords')
# Sample text
text = "NLTK is a great library for natural language processing."
# Tokenization
tokens = word_tokenize(text)
print(tokens)
# Stopword removal
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word in tokens if word.lower() not in stop_words]
# Print filtered tokens
print("Filtered Tokens:", filtered_tokens)
import random
words = ['rider', 'apple','fruit','penis','banana']
lives = 6
chosen_word = random.choice(words)
print(chosen_word)
display = []
for i in range(len(chosen_word)):
display += '_'
print(display)
game_over = False
while not game_over:
guessed_letter = input("Guess: ").lower()
for j in range(len(chosen_word)):
letter = chosen_word[j]
if guessed_letter == letter:
display[j] = letter
print(display)
if '_' not in display:
print("won")
from sys import maxsize
from itertools import permutations
V = 4
def travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k = s
for j in i:
current_pathweight += graph[k][j]
k = j
current_pathweight += graph[k][s]
min_path = min(min_path, current_pathweight)
return min_path
if __name__ == "__main__":
# matrix representation of graph
graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s = 0
print(travellingSalesmanProblem(graph, s))
import random
def play(choice):
prizes = ['goat', 'car', 'goat']
random.shuffle(prizes)
for door in range(3):
if door != choice - 1 and prizes[door] == 'goat':
opened_door = door
break
print(f"Opening door {opened_door + 1}")
print("Switch?")
answer = input().lower()
if answer == 'yes':
for door in range(3):
if door != choice - 1 and door != opened_door:
choice = door + 1
break
result = choice - 1
print(f"Your prize is {prizes[result]}!")
# Test the function
play(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment