TASK:7
Implementation of Monkey Banana Problem in Goal Stack planning using python by applying
following constraints.
AIM:
To Implement the Monkey Banana Problem in Goal Stack planning using python
ALGORITHM:
1. Start:
Begin with the initial state of the monkey, box, and banana.
2. Check Monkey's Position:
If the monkey is not at the banana's position, move the monkey to the banana's
position.
3. Move Monkey to Banana:
Move the monkey from its current position to where the banana is.
4. Check Box Position:
If the box is not at the banana's position, move the box to where the banana is.
5. Move Monkey to Box:
Move the monkey to the position of the box.
6. Climb on Box:
Have the monkey climb on top of the box.
7. Check Monkey's Level:
Ensure the monkey is now on top of the box.
8. Reach for Banana:
Have the monkey take the banana.
9. Verify Goal:
Check if the monkey has the banana.
10. End:
The goal is achieved; the monkey has the banana. Output the sequence of actions.
PROGRAM:
# Operators def move(subject,
x1, x2):
return f"Move {subject} from {x1} to {x2}"
def push_box(x1, x2):
return f"Push box from {x1} to {x2}"
def climb_box(x, direction):
return f"Climb box at {x} {direction}"
def have_banana(x):
return f"Have banana at {x}"
# Initial State initial_state
={
'monkeyAt0': True,
'monkeyLevel': 'Down',
'bananaAt1': True,
'boxAt2': True
}
# Goal State goal_state
={
'GetBanana': True,
'at': 1
}
# Planning Algorithm def plan_actions(initial_state,
goal_state):
actions = []
# Example planning algorithm to achieve the goal state if
initial_state['monkeyAt0'] and initial_state['bananaAt1']:
actions.append(move('Monkey', 0, 1))
actions.append(climb_box(1, 'Up'))
actions.append(have_banana(1))
return actions
# Execute the planning algorithm actions = plan_actions(initial_state,
goal_state)
# Print the actions in the plan
print("Plan:") for action in actions:
print(action)
OUTPUT:
RESULT:
Thus, the Implementation the Monkey Banana Problem in Goal Stack planning using
python was successfully executed and output was
TASK:10
Implement simple facts using python
AIM:
To implement simple facts and verify using python
ALGORITHM:
Step:1Define a list of facts containing the statements to be verified.
Step:2 Create a function named verify_fact that takes a fact as input and returns a boolean value
indicating whether the fact is true or false.
Step:3 In the verify_fact function:
a. Remove the trailing period from the fact using the rstrip function.
b. Check the fact against the known conditions to determine its truth value. You can use conditional
statements (if, elif, else) for this.
• If the fact matches a known condition, return True to indicate that the fact is true.
• If the fact does not match any known condition, return False to indicate that the fact is false.
Step:4 Iterate over each fact in the list of facts: a.
Call the verify_fact function for each fact.
b. Print the fact and the corresponding "Yes" or "No" based on its truth value.
PROGRAM:
# Define a list of facts facts
=[
"john_is_cold.", # john is cold
"raining.", # it is raining
"john_Forgot_His_Raincoat.", # john forgot his raincoat
"fred_lost_his_car_keys.", # fred lost his car keys
"peter_footballer." # peter plays football
]
# Function to check if a fact is true def
verify_fact(fact):
# Remove the trailing period
fact = fact.rstrip(".")
# Perform some logic to verify the
fact if fact ==
"john_Forgot_His_Raincoat":
return True elif fact == "raining":
return True elif fact
== "foggy":
return True elif fact
== "Cloudy":
return False # Assume it's not cloudy
else:
return False
# Verify each fact for fact
in facts: if
verify_fact(fact):
print(f"{fact} - Yes")
else:
print(f"{fact} - No")
OUTPUT:
RESULT:
Thus, the implementation of simple facts using python was successfully executed and
output was verified.
TASK:9
To Build an Intelligent Chatbot system with Python and Dialog-flow using Interactive Text Mining
Framework for Exploration of Semantic Flows in Large Corpus of Text.
AIM:
To build an intelligent chatbox system with Python and dialog-flow using interactive text mining
framework for exploration of semantic flow in large corpus of Text
ALGORITHM:
1.Sign up for OpenAI API access at https://beta.openai.com/signup/. Once you sign up, you will
receive your API key.
2.Choose the type of chatbot you want to create. For example, you can create an FAQ chatbot, a
customer support chatbot, or a conversational chatbot.
3.Use OpenAI's GPT-3 language model to generate responses to user input. You can use the API to train
the language model on your chatbot's intended use case/s.
4.Use Natural Language Processing (NLP) techniques to understand user input and provide relevant
responses. You can use OpenAI's API to extract entities (such as dates and names) from user input.
5.Use Machine Learning to continually improve the chatbot's ability to understand and respond to user
input.
6.Integrate the chatbot with your preferred messaging platform or channel (e.g., web chat, social media,
etc.) using API connectors.
7.Test your chatbot frequently, and use user feedback to improve its performance and provide the best
possible experience for your users.
A. SIMPLE CHATGPT USING OPENAI CODE:
Pip install openai import openai
openai.api_key = "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"
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user",
"content": "Give me 3 ideas that i could build using openai apis"}])
print(completion.choices[0].message.content)
OUTPUT:
1.Personalized Content Recommendation System: Develop an AI-powered content recommendation
system that suggests personalized content to users based on their interests and search history. Use
OpenAI's language generation APIs to generate relevant content descriptions and summaries, and
employ their natural language processing (NLP) APIs to understand user preferences and interests.
2.Intelligent Chatbot: Build a conversational AI-enabled chatbot that can answer customer queries,
provide helpful recommendations, and complete transactions seamlessly. Use OpenAI's language
processing APIs to train the chatbot to understand user inputs and respond in natural language.
Integration with other APIs such as payment gateways and customer databases can make the chatbot
efficient and effective.
3.Fraud Detection System: Develop a machine learning model that can identify and prevent fraudulent
activities using OpenAI's anomaly detection and classification APIs. Train the model using historical
data of fraudulent transactions, and use the APIs to continuously scan for and identify suspicious
activities. Such a system can be deployed in a range of applications such as finance or e-commerce
platforms.
B. CHATGPT ASSISTANT USING OPENAI
CODE:
import openai
openai.api_key = "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"
messages = []
system_msg = input("What type of chatbot would you like to create?\n") messages.append({"role":
"system", "content": system_msg})
print("Your new assistant is ready! Type your query") while input !=
"quit()": message = input()
messages.append({"role": "user", "content": message})
response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages) reply =
response["choices"][0]["message"]["content"] messages.append({"role": "assistant", "content": reply})
print("\n" + reply + "\n")
OUTPUT:
C. CHATBOT CHAT ASSISTANT WEBSITE CODE:
import openai import gradio openai.api_key = "sk-
T7oiyeMfqS8iua5RcpAaT3BlbkFJt0TJ7dUGBlYG9EYubsJc"
messages = [{"role": "system", "content": "You are a financial experts that specializes in real estate investment and
negotiation"}] def CustomChatGPT(user_input):
messages.append({"role": "user", "content": user_input}) response =
openai.ChatCompletion.create( model = "gpt-3.5-turbo", messages =
messages
ChatGPT_reply = response["choices"][0]["message"]["content"]
messages.append({"role": "assistant", "content": ChatGPT_reply}) return ChatGPT_reply
demo = gradio.Interface(fn=CustomChatGPT, inputs = "text", outputs = "text", title =
"INTELLIGENT CHATBOT")
demo.launch(share=True)
OUTPUT:
OUTPUT:
RESULT:
Thus, to build an intelligent chatbox system with Python and dialogue flow was successfully completed
and output was verified
PROGRAM
def get_age():
while True:
try:
age = int(input("Please enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative.")
return age
except ValueError as ve:
print("Invalid input:", ve)
try:
age = get_age()
print("Your age is:", age)
except ValueError as ve:
print("An error occurred:", ve)
RESULT:
Hence the given task is done successfully and outputs are verified.
PROGRAM
def view_seat_details(seat_list, index):
try:
seat = seat_list[index]
print("Seat Details:")
print("Seat Number:", seat.get("number"))
print("Section:", seat.get("section"))
print("Availability:", "Booked" if seat.get("is_booked") else "Available")
except IndexError:
print("Invalid seat index. Please select a valid seat.")
seats = [
{"number": "A1", "section": "VIP", "is_booked": False},
{"number": "A2", "section": "VIP", "is_booked": True},
{"number": "B1", "section": "General", "is_booked": False},
{"number": "B2", "section": "General", "is_booked": False}
]
try:
seat_index = int(input("Enter the index of the seat you want to view: "))
view_seat_details(seats, seat_index)
except ValueError:
print("Invalid input. Please enter a valid seat index (integer).")
RESULT:
Hence the given task is done successfully and outputs are verified.
PROGRAM
def open_file(filename):
try:
file = open(filename, 'r')
contents = file.read()
print("File contents:")
print(contents)
file.close()
except FileNotFoundError:
print("Error: File not found.")
file_name = input("Input a file name: ")
open_file(file_name)
RESULT:
Hence the given task is done successfully and outputs are verified.
PROGRAM
try:
initial_investment = float(input("Enter the initial investment amount: "))
final_investment = float(input("Enter the final investment amount: "))
roi = (final_investment - initial_investment) / initial_investment * 100
print("Return on Investment (ROI): {:.2f}".format(roi))
except ValueError:
print("Error: Please enter a valid numeric value for the investment amount.")
except ZeroDivisionError:
print("Error: Initial investment amount cannot be zero.")
RESULT:
Hence the given task is done successfully and outputs are verified.
PROGRAM
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 1000) # This line generates an array of
1000 evenly spaced values between
0 and 2π. It takes three arguments: the starting point (0 in this case),
the ending point (2*np.pi which is approximately 6.28319 and the
number of points to generate (1000). It returns an array of equally
spaced points between the start and end points, inclusive.
y = np.sin(x)
plt.plot(x, y)
plt.title('Sine Wave')
plt.xlabel('x')
plt.ylabel('sin(x)')
plt.grid(True)
plt.show()
RESULT:
Hence the given task is done successfully and outputs are verified.
.
PROGRAM
import matplotlib.pyplot as plt
intervals = ['140-145', '145-150', '151-156', '157-162', '163-168',
'168-173', '173-178', '179-184', '185-190', '190-195']
frequencies = [2, 5, 15, 31, 46, 53, 45, 28, 21, 4]
plt.bar(intervals, frequencies, edgecolor='red')
plt.xlabel('Height Intervals (cm)')
plt.ylabel('Frequency')
plt.title('Height Distribution Histogram')
plt.grid(True)
plt.show()
RESULT:
Hence the given task is done successfully and outputs are verified.
PROGRAM
import matplotlib.pyplot as plt
# Define the data
x= [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]
# Plot the scatter graph
plt.scatter(x, y, color='blue')
plt.xlabel('X AXIS')
plt.ylabel('Y AXIS')
plt.title('Scatter Plot')
plt.show()
RESULT:
Hence the given task is done successfully and outputs are verified.
PROGRAM
import matplotlib.pyplot as plt
sizes = [35, 25, 25, 15]
mylabels = ['w', 'x', 'y', 'z']
myexplode = [0.2, 0, 0, 0]
plt.pie(sizes, labels=mylabels, explode=myexplode, shadow = True,
autopct='%1.1f%%')
plt.title('Pie Chart')
plt.show()
RESULT:
Hence the given task is done successfully and outputs are verified.
Program:
mport tkinter as tk
from datetime import datetime
def calculate_age():
today = datetime.now()
birth_date = datetime(int(year_entry.get()), int(month_entry.get()), int(day_entry.get()))
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
result_label.config(text=f"Your age is {age}")
root = tk.Tk()
root.title("Age Calculator")
tk.Label(root, text="Name:",width=50).pack()
name_entry = tk.Entry(root)
name_entry.pack()
tk.Label(root, text="Year of Birth:").pack()
year_entry = tk.Entry(root)
year_entry.pack()
tk.Label(root, text="Month of Birth:").pack()
month_entry = tk.Entry(root)
month_entry.pack()
tk.Label(root, text="Day of Birth:").pack()
day_entry = tk.Entry(root)
day_entry.pack()
tk.Button(root, text="Calculate Age",
background='pink',foreground='black',command=calculate_age).pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
RESULT:
Hence the given task is done successfully and outputs are verified.
Program:
import tkinter as tk
from datetime import datetime
def update_time():
current_time = datetime.now().strftime("%H:%M:%S")
time_label.config(text=current_time)
time_label.after(1000, update_time)
root = tk.Tk()
root.title("Digital Clock")
style = "calibri"
size = 40
font_style = (style, size, "bold")
time_label = tk.Label(root, font=font_style, anchor="center",
background='purple',foreground='white')
time_label.pack(fill=tk.BOTH, expand=True)
update_time()
root.mainloop()
RESULT:
Hence the given task is done successfully and outputs are verified.