AI Practical FILE - ............ : B.tech (University of Delhi)
AI Practical FILE - ............ : B.tech (University of Delhi)
Varun Gupta -
2020UIT3053 Sagar
Goel - 2020UIT3038
Ayush Upadhyay -
2020UIT3035 Ankit
Bhadoria -
2020UIT3040 Kumar
Aniket - 2020UIT3064
IT-1, Group-2
def MostEffectiveSolutionTillNow(state):
bestsol = np.array([], int).reshape(-1, 9)
count = len(state) - 1
while count != -1:
bestsol = np.insert(bestsol, 0, state[count]['puzzle'], 0)
count = (state[count]['parent'])
return bestsol.reshape(-1, 3, 3)
def Coordinates_Values(puzzle):
pos = np.array(range(9))
for p, q in enumerate(puzzle):
pos[q] = p
return pos
parent = -1
gn = 0
hn = CountMisplacedTiles(Coordinates_Values(puzzle), costg)
state = np.array([(puzzle, parent, gn, hn)], dtstate)
dtpriority = [('position', int), ('fn', int)]
priority = np.array([(0, hn)], dtpriority)
while 1:
priority = np.sort(priority, kind='mergesort', order=['fn', 'position'])
position, fn = priority[0]
priority = np.delete(priority, 0, 0)
puzzle, parent, gn, hn = state[position]
puzzle = np.array(puzzle)
blank = int(np.where(puzzle == 0)[0])
gn = gn + 1
c = 1
start_time = time.time()
for s in steps:
c = c + 1
if blank not in s['position']:
openstates = deepcopy(puzzle)
openstates[blank], openstates[blank + s['head']] = openstates[blank
+ s['head']], openstates[blank]
Downloaded by Student Life
if ~(np.all(list(state['puzzle']) == openstates, 1)).any():
end_time = time.time()
puzzle = []
print("Enter Initial Configuration of the Puzzle: ")
for i in range(0, 9):
puzzle.append(int(input()))
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
state, visited = Calculate_Heuristic_Value(puzzle, goal)
efficientpath = MostEffectiveSolutionTillNow(state)
print(str(efficientpath).replace('[', ' ').replace(']', ''))
print('Total No. Steps to reach goal State:', len(efficientpath) - 1)
OUTPUT:
for x in adj[u]:
if (not visited[x]):
if dfs_helper(x, node, visited, path, u, target) == True:
return True
return False
path = []
for i in range(node):
visited[i] = False
OUTPUT:-
[-1, 0]
[0, 1]
[1, 5]
[1, 6]
[6, 7]
[7, 8]
[0, 2]
[2, 4]
[2, 9]
# backtracking
if (len(v[x]) > 0):
for j in v[x]:
# if the node is not visited
if (vis[j] == False):
DFS(vis, j, y, stack)
del stack[-1]
# function to initialise visited for the node and call DFS function
for a given vertex x.
def DFSCall(x, y, n, stack):
# visited array
vis = [0 for i in range(n + 1)]
# DFS function call
DFS(vis, x, y, stack)
# Driver Code
n = 10
stack = []
# Vertex numbers should be from 1 to 9.
addEdge(1, 2)
addEdge(1, 3)
addEdge(2, 4)
addEdge(2, 5)
Downloaded by Student Life
addEdge(2, 6)
# Function Call
DFSCall(4, 8, n, stack)
Output:
4 -> 2 -> 1 -> 3 -> 8
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def hillClimbing(tsp):
currentSolution = [3,0,4,1,2]
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
nextneighbour, nextneighbourRouteLength = getnextneighbour(tsp,
neighbours)
def main():
tsp = [
[0, 12, 8, 21, 5],
[0, 0, 30, 54, 1],
Downloaded by Student Life
[20, 10, 0, 2, 0],
[300, 2, 8, 6, 100],
print('Ans: ')
for i in range(len(sol)):
print(sol[i], end="")
if i != len(sol)-1:
print('->',end="")
print('\nshortest route sum: {}'.format(sum))
OUTPUT:
Ans:
4->0->3->1->2
shortest route sum: 54
import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)
return solution
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp,
neighbours)
def problemGenerator(nCities):
tsp = [] #tsp is a 2d list
for i in range(nCities):
distances = []
for j in range(nCities):
if j == i:
distances.append(0)
elif j < i:
distances.append(tsp[j][i])
else:
distances.append(random.randint(10, 50))
tsp.append(distances)
return tsp
def main():
print("Enter Number of Cities: ")
n = int(input())
tsp = problemGenerator(n)
for i in range(n):
print(tsp[i])
OUTPUT
Enter Number of Cities:
4
[0, 36, 40, 48]
[36, 0, 26, 36]
[40, 26, 0, 50]
[48, 36, 50, 0]
shortest path:
([3, 1, 2, 0], 150)
pq = PriorityQueue()
pq.put((Heuristic[source], source))
while pq.empty() == False:
u = pq.get()[1]
# Displaying the path having lowest cost
print(u, end="->")
if u == target:
break
for v in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((Heuristic[v], v))
print()
OUTPUT:
gn=dict({
0:0,
1:3,
2:3,
3:10,
4:12,
5:9,
6:17
})
pq = PriorityQueue() pq.put((hn[source]
+gn[source], source)) visited[source]= True
while pq.empty() == False:
u = pq.get()[1]
# Displaying the path having lowest cost
print(u, end="->")
if u == target:
break
for i in range(rows):
for j in range(cols):
if i==u and graph[i][j] != 0 and visited[j]== False :
visited[j] = True
pq.put((hn[j]+gn[j], j))
print()
OUTPUT:
def applyAOStar(self):
self.aoStar(self.start, False)
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE:",
self.start)
print(" ")
print(self.solutionGraph)
print(" ")
print ("Graph")
h1 = {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J':
1}
graph1 = {
'A': [[('B', 1), ('C', 1)], [('D', 1)]],
'B': [[('G', 1)], [('H', 1)]],
'C': [[('J', 1)]],
'D': [[('E', 1), ('F', 1)]],
'G': [[('I', 1)]]
}
OUTPUT:
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))
def
possibilities(bo
ard): l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
for y in range(len(board)):
if board[x, y] != player:
win =
False
continue
if win == True:
return(win)
return(win)
for y in range(len(board)):
if board[y][x] != player:
win =
False
continue
if win == True:
return(win)
return(win)
def diag_win(board,
player): win = True
y=0
for x in range(len(board)):
Downloaded by Student Life
if board[x, x] != player:
win = False
if win:
return win
win =
True if
win:
for x in range(len(board)):
y = len(board) - 1 - x
def
evaluate(board):
winner = 0
winner = player
def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + "
move") print(board)
sleep(2)
counter +=
1
winner =
evaluate(board) if
winner != 0:
break
return(winner)
import tweepy
class TwitterClient(object):
'''
'''
'''
'''
consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'
consumer_secret =
'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' access_token =
'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'
# attempt
authentication try:
self.auth = OAuthHandler(consumer_key,
self.auth.set_access_token(access_token, access_token_secret)
self.api =
tweepy.API(self.auth) except:
def clean_tweet(self,
tweet): '''
'''
Downloaded by Student Life
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
def get_tweet_sentiment(self,
tweet): '''
'''
text analysis =
TextBlob(self.clean_tweet(tweet)) # set
sentiment
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative'
'''
'''
tweets = []
try:
parsed_tweet = {}
parsed_tweet['text'] =
# savingDownloaded
sentiment of tweet
by Student Life
tweet.text
if tweet.retweet_count > 0:
tweets.append(parsed_tweet)
else:
tweets.append(parsed_tweet)
return tweets
except tweepy.TweepError as e:
def main():
api = TwitterClient()
print("\n\nPositive tweets:")
print(tweet['text'])
tweets print("\n\nNegative
ntweets[:10]:
print(tweet['text'])
main()
OUTPUT: