0% found this document useful (0 votes)
6 views38 pages

AI Practical FILE - ............ : B.tech (University of Delhi)

xgbxb xf

Uploaded by

Student Life
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views38 pages

AI Practical FILE - ............ : B.tech (University of Delhi)

xgbxb xf

Uploaded by

Student Life
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

AI Practical FILE - ............

B.tech (University of Delhi)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Student Life
PRACTICAL FILE
ARTIFICIAL
INTELLIGENCE ITITC16

Varun Gupta -
2020UIT3053 Sagar
Goel - 2020UIT3038
Ayush Upadhyay -
2020UIT3035 Ankit
Bhadoria -
2020UIT3040 Kumar
Aniket - 2020UIT3064
IT-1, Group-2

Downloaded by Student Life


Downloaded by Student Life
Practical List

S. No. Date Title Concept


19/8/2022
1 Tile Slide Puzzle Minimize
heuristic
26/8/2002
2 Water Jug Problem Production Rules
2/9/2022
3 Generate and Test Rat in a Maze
9/9/2022
4 Systematic Rat in a Maze
Generate and
Test
16/9/2022
5 Hill Climbing Minimize cost
of Living
23/9/2022
6 Steepest Minimize cost of
Ascent Hill travel
Climbing
30/9/2022
7 Best First Search Shortest path
7/10/2022
8 A* Algorithm Shortest path
14/10/2022
9 AO* Algorithm Shortest path
21/10/2022
10 Tic Tac Toe Minimax with α-β
pruning
28/10/2022
11. NLP Sentiment
Analysis

Downloaded by Student Life


IMPLEMENT 8-TILE PUZZLE PROBLEM
import os
import numpy as np
import time
from copy import deepcopy

def CountMisplacedTiles(puzzle, goal):


cost = np.sum(puzzle != goal) - 1
if (cost > 0):
return cost
else:
return 0

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

def Calculate_Heuristic_Value(puzzle, goal):


steps = np.array([('up', [0, 1, 2], -3), ('down', [6, 7, 8], 3), ('left', [0, 3,
6], -1), ('right', [2, 5, 8], 1)],
dtype=[('move', str, 1), ('position', list), ('head', int)])
dtstate = [('puzzle', list), ('parent', int), ('gn', int), ('hn', int)]
costg = Coordinates_Values(goal)

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()

Downloaded by Student Life


if ((end_time - start_time) > 2):
print(" There doesn't exists a solution for this 8-Puzzle
Game.\n")
break
hn = CountMisplacedTiles(Coordinates_Values(openstates), costg)

q = np.array([(openstates, position, gn, hn)], dtstate)


state = np.append(state, q, 0)
fn = gn + hn

q = np.array([(len(state) - 1, fn)], dtpriority)


priority = np.append(priority, q, 0)
if np.array_equal(openstates, goal):
print(' There exists a solution for this 8-Puzzle Game. \n')
return state, len(priority)

return state, len(priority)

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:

Downloaded by Student Life


WATER JUG PROBLEM
from collections import defaultdict
jug1, jug2, aim = 4, 3, 2
visited = defaultdict(lambda: False)
def waterJugSolver(amt1, amt2):
if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
visited[(amt1, amt2)] = True
return (waterJugSolver(0, amt2) or
waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
waterJugSolver(amt1 + min(amt2, (jug1 - amt1)),
amt2 - min(amt2, (jug1 - amt1))) or
waterJugSolver(amt1 - min(amt1, (jug2 - amt2)),
amt2 + min(amt1, (jug2 - amt2))))
else:
return False
print("Steps: ")
waterJugSolver(0, 0)
OUTPUT:

Downloaded by Student Life


PURE GENERATE AND TEST
N = 1000
adj = [[] for i in range(N)]

def dfs_helper(u, node, visited, path, parent, target):


visited[u] = True
path.append([parent, u])
# print(u, end = " ")
if u == target:
return True

for x in adj[u]:

if (not visited[x]):
if dfs_helper(x, node, visited, path, u, target) == True:
return True

return False

def dfs(node, source, target):


visited = [False for i in range(node)]

path = []
for i in range(node):
visited[i] = False

dfs_helper(source, node, visited, path, -1, target)


for i in path:
print(i)

def insertEdge(u, v):


adj[u].append(v)
adj[v].append(u)

if name == ' main ':


node = 11
edge = 13
insertEdge(0, 1)
insertEdge(0, 2)
insertEdge(1, 5)
insertEdge(1, 6)
insertEdge(2, 4)
insertEdge(2, 9)
insertEdge(6, 7)
insertEdge(6, 8)
insertEdge(7, 8)
insertEdge(2, 3)
insertEdge(3, 9)
insertEdge(3, 10)
insertEdge(9, 10)
Downloaded by Student Life
source = 0

Downloaded by Student Life


target = 9

dfs(node, source, target)

OUTPUT:-
[-1, 0]
[0, 1]
[1, 5]
[1, 6]
[6, 7]
[7, 8]
[0, 2]
[2, 4]
[2, 9]

Downloaded by Student Life


SYSTEMATIC GENERATE AND TEST
# GENERATE AND TEST - DFS with Backtracking
# A 2d empty list.
v = [[] for i in range(100)]

# An utility function to add an edge in an undirected graph.


def addEdge(x, y):
v[x].append(y)
v[y].append(x)

# function to print the path between the given pair of nodes.


def printPath(stack):
for i in range(len(stack) - 1):
print(stack[i], end=" -> ")
print(stack[-1])

# An utility function to do DFS of graph recursively from a given


vertex x.
def DFS(vis,x,y,stack):
stack.append(x)
if (x==y):
# print the path and return on reaching the destination node
printPath(stack)
return
vis[x] = True

# 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)

Downloaded by Student Life


addEdge(3, 7)
addEdge(3, 8)
addEdge(3, 9)

# Function Call
DFSCall(4, 8, n, stack)

Output:
4 -> 2 -> 1 -> 3 -> 8

Downloaded by Student Life


SIMPLE HILL CLIMBING
import random

def routeLength(tsp, solution):


routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength

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 getnextneighbour(tsp, neighbours):


curroutlength = routeLength(tsp, neighbours[0])
nextneighbour = -1
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < curroutlength:
curroutlength = currentRouteLength
nextneighbour = neighbour
break
return nextneighbour, curroutlength

def hillClimbing(tsp):
currentSolution = [3,0,4,1,2]
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
nextneighbour, nextneighbourRouteLength = getnextneighbour(tsp,
neighbours)

while nextneighbourRouteLength < currentRouteLength:


currentSolution = nextneighbour
currentRouteLength = nextneighbourRouteLength
neighbours = getNeighbours(currentSolution)
nextneighbour, nextneighbourRouteLength =
getnextneighbour(tsp, neighbours)
if nextneighbour == -1:
break

return currentSolution, currentRouteLength

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],

Downloaded by Student Life


[1, 40, 5, 100, 2]
]

sol, sum = hillClimbing(tsp)

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))

if name == " main ":


main()

OUTPUT:
Ans:
4->0->3->1->2
shortest route sum: 54

Downloaded by Student Life


STEEPEST ASCENT HILL CLIMBING
#STEEPEST ASCENT HILL CLIMBING ALGO -Travelling Salseman Problem

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 routeLength(tsp, solution):


routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength

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 getBestNeighbour(tsp, neighbours):


bestRouteLength = routeLength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength

def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp,
neighbours)

while bestNeighbourRouteLength < currentRouteLength:


Downloaded by Student Life
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength

Downloaded by Student Life


neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength =
getBestNeighbour(tsp, neighbours)

return currentSolution, currentRouteLength

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])

print("shortest path: ")


print(hillClimbing(tsp))

if name == " main ":


main()

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)

Downloaded by Student Life


BEST FIRST SEARCH
from queue import PriorityQueue
v = 8
graph = [[] for i in range(v)]
Heuristic=dict({
0:40 ,
1:32 ,
2:25 ,
3:35 ,
4:19 ,
5:17 ,
6: 0 ,
7:10
})

# Function For Implementing Best First Search


def best_first_search(source, target, n):
visited = [False] * n

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()

# Function for adding edges to graph


def addedge(x, y):
graph[x].append(y)
graph[y].append(y)

#Add edges to graph


addedge(0, 1)
addedge(0, 2)
addedge(0, 3)
addedge(1, 4)
addedge(2, 5)
addedge(2, 4)
addedge(3, 5)
addedge(4, 7)
addedge(5, 6)
addedge(6, 7)

source = int(input("Enter Source node(0-7): "))


Downloaded by Student Life
target = 6

Downloaded by Student Life


print(“Path:”)
best_first_search(source, target, v)

OUTPUT:

Enter Source node(0-7): 0


Path:
0->2->5->6->

Downloaded by Student Life


IMPLEMENT A* ALGORITHM
from queue import PriorityQueue
v = 7
rows,cols=(v,v)
graph =[[0]*cols]*rows
hn=dict({
0:14 ,
1:20 ,
2:11 ,
3:6 ,
4:4 ,
5:11 ,
6: 0
})

gn=dict({
0:0,
1:3,
2:3,
3:10,
4:12,
5:9,
6:17
})

def A_Star(source, target, n):


visited = [False] * n

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()

# Function for adding edges to graph


def addedge(x, y, cost): graph[x]
[y]=cost

#Add edges to graph


addedge(0, 1, 4)
addedge(0, 2, 3)
addedge(1, 4, 12)
addedge(1, 5, 5)
addedge(2, 3, 7)
addedge(2, 4, 10)
addedge(3, 4, 2)
addedge(4, 6, 5)
addedge(5, 6, 16)

print("Source Node: 0", )


Downloaded by Student Life
print("Taget Node: 6")
source=0
target=6
print("Path: ")
A_Star(source, target, v)

OUTPUT:

Downloaded by Student Life


IMPLEMENTATION OF AO* ALGORITHM
class Graph:
def init (self, graph, heuristicNodeList,startNode):
self.graph = graph
self.H = heuristicNodeList
self.start = startNode
self.parent = {}
self.status = {}
self.solutionGraph = {}

def applyAOStar(self):
self.aoStar(self.start, False)

def getNeighbors(self, v):


return self.graph.get(v, '')

def getStatus(self, v):


return self.status.get(v, 0)

def setStatus(self, v, val):


self.status[v] = val

def getHeuristicNodeValue(self, n):


return self.H.get(n, 0)

def setHeuristicNodeValue(self, n, value):


self.H[n] = value

def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE:",
self.start)
print(" ")
print(self.solutionGraph)
print(" ")

def computeMinimumCostChildNodes(self, v):


minimumCost = 0
costToChildNodeListDict = {}
costToChildNodeListDict[minimumCost] = []
flag = True
for nodeInfoTupleList in self.getNeighbors(v):
cost = 0
nodeList = []
for c, weight in nodeInfoTupleList:
cost = cost + self.getHeuristicNodeValue(c) + weight
nodeList.append(c)
if flag == True:
minimumCost = cost
costToChildNodeListDict[minimumCost] = nodeList
flag = False
else:
if minimumCost > cost:
minimumCost = cost
costToChildNodeListDict[minimumCost] = nodeList
return minimumCost, costToChildNodeListDict[minimumCost]

def aoStar(self, v, backTracking):


print("HEURISTIC VALUES :", self.H)
print("SOLUTION GRAPH :", self.solutionGraph)
print("PROCESSING NODE :", v)
print("
")
Downloaded by Student Life
if self.getStatus(v) >= 0:
minimumCost, childNodeList = self.computeMinimumCostChildNodes(v)
print(minimumCost, childNodeList)

Downloaded by Student Life


self.setHeuristicNodeValue(v, minimumCost)
self.setStatus(v, len(childNodeList))
solved = True
for childNode in childNodeList:
self.parent[childNode] = v
if self.getStatus(childNode) != -1:
solved = solved & False
if solved == True:
self.setStatus(v, -1)
self.solutionGraph[v] = childNodeList
if v != self.start:
self.aoStar(self.parent[v],True)
if backTracking == False:
for childNode in childNodeList:
self.setStatus(childNode,0)
self.aoStar(childNode,False)

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)]]
}

G1= Graph(graph1, h1, 'A')


G1.applyAOStar()
G1.printSolution()

OUTPUT:

Downloaded by Student Life


Downloaded by Student Life
IMPLEMENTATION OF TIC TAC TOE
import numpy as np
import random
from time import sleep

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)

def random_place(board, player):


selection =
possibilities(board)
current_loc =
random.choice(selection)
board[current_loc] = player
return(board)

def row_win(board, player):


for x in
range(len(board
)): win = True

for y in range(len(board)):
if board[x, y] != player:
win =
False
continue

if win == True:
return(win)
return(win)

def col_win(board, player):


for x in
range(len(board
)): win = True

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

Downloaded by Student Life


if board[x, y] != player:
win = False
return win

def
evaluate(board):
winner = 0

for player in [1, 2]:


if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):

winner = player

if np.all(board != 0) and winner


== 0: winner = -1
return winner

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)

print("Winner is: " + str(play_game()))

Downloaded by Student Life


OUTPUT:

Downloaded by Student Life


IMPLEMENTATION OF NLP-Sentiment Analysis
import re

import tweepy

from tweepy import OAuthHandler

from textblob import TextBlob

class TwitterClient(object):

'''

Generic Twitter Class for sentiment analysis.

'''

def init (self):

'''

Class constructor or initialization method.

'''

# keys and tokens from the Twitter Dev Console

consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'

consumer_secret =

'XXXXXXXXXXXXXXXXXXXXXXXXXXXX' access_token =

'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'

access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'

# attempt

authentication try:

# create OAuthHandler object

self.auth = OAuthHandler(consumer_key,

consumer_secret) # set access token and secret

self.auth.set_access_token(access_token, access_token_secret)

# create tweepy API object to fetch tweets

self.api =

tweepy.API(self.auth) except:

print("Error: Authentication Failed")

def clean_tweet(self,

tweet): '''

Utility function to clean tweet text by removing links, special characters

using simple regex statements.

'''
Downloaded by Student Life
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])

|(\w+:\/\/\S+)", " ", tweet).split())

def get_tweet_sentiment(self,

tweet): '''

Utility function to classify sentiment of passed tweet

using textblob's sentiment method

'''

# create TextBlob object of passed 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'

def get_tweets(self, query, count = 10):

'''

Main function to fetch tweets and parse them.

'''

# empty list to store parsed tweets

tweets = []

try:

# call twitter api to fetch tweets

fetched_tweets = self.api.search(q = query, count = count)

# parsing tweets one by one

for tweet in fetched_tweets:

# empty dictionary to store required params of a tweet

parsed_tweet = {}

# saving text of tweet

parsed_tweet['text'] =

# savingDownloaded
sentiment of tweet
by Student Life
tweet.text

Downloaded by Student Life


parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)

# appending parsed tweet to tweets list

if tweet.retweet_count > 0:

# if tweet has retweets, ensure that it is appended only

once if parsed_tweet not in tweets:

tweets.append(parsed_tweet)

else:

tweets.append(parsed_tweet)

# return parsed tweets

return tweets

except tweepy.TweepError as e:

# print error (if any)

print("Error : " + str(e))

def main():

# creating object of TwitterClient Class

api = TwitterClient()

# calling function to get tweets

tweets = api.get_tweets(query = 'Donald Trump', count = 200)

# picking positive tweets from tweets

ptweets = [tweet for tweet in tweets if tweet['sentiment'] ==

'positive'] # percentage of positive tweets

print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))

# picking negative tweets from tweets

ntweets = [tweet for tweet in tweets if tweet['sentiment'] ==

'negative'] # percentage of negative tweets

print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))

# percentage of neutral tweets

print("Neutral tweets percentage: {} % \

".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))

# printing first 5 positive tweets

print("\n\nPositive tweets:")

Downloaded by Student Life


for tweet in ptweets[:10]:

print(tweet['text'])

# printing first 5 negative

tweets print("\n\nNegative

tweets:") for tweet in

ntweets[:10]:

print(tweet['text'])

if name == " main ":

# calling main function

main()

OUTPUT:

Downloaded by Student Life

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy