0% found this document useful (0 votes)
19 views27 pages

Artificial Intelligence

Uploaded by

12dcsbest
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)
19 views27 pages

Artificial Intelligence

Uploaded by

12dcsbest
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/ 27

Artificial Intelligence

1. Write a Program to Perform Basic Arithmetic Operations


Question: Write a program to accept two numbers from the user and
perform the following operations:
 Addition
 Subtraction
 Multiplication
 Division
 Modulus
 Floor Division
 Exponentiation
Ans: # Program to perform basic arithmetic operations

# Accepting two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Performing and displaying arithmetic operations

# Addition
addition = num1 + num2
print(f"The sum of {num1} and {num2} is: {addition}")

# Subtraction
subtraction = num1 - num2
print(f"The difference of {num1} and {num2} is: {subtraction}")

# Multiplication
multiplication = num1 * num2
print(f"The product of {num1} and {num2} is: {multiplication}")

# Division
if num2 != 0: # Checking if the divisor is not zero
division = num1 / num2
print(f"The division of {num1} by {num2} is: {division}")
else:
print("Division by zero is not allowed.")

# Modulus
if num2 != 0: # Checking if the divisor is not zero
modulus = num1 % num2
print(f"The modulus of {num1} and {num2} is: {modulus}")
else:
print("Modulus by zero is not allowed.")

# Floor Division
if num2 != 0: # Checking if the divisor is not zero
floor_division = num1 // num2
print(f"The floor division of {num1} by {num2} is: {floor_division}")
else:
print("Floor division by zero is not allowed.")

# Exponentiation
exponentiation = num1 ** num2
print(f"The result of {num1} raised to the power of {num2} is:
{exponentiation}")
Enter the first number: 10
Enter the second number: 3
The sum of 10.0 and 3.0 is: 13.0
The difference of 10.0 and 3.0 is: 7.0
The product of 10.0 and 3.0 is: 30.0
The division of 10.0 by 3.0 is: 3.3333333333333335
The modulus of 10.0 and 3.0 is: 1.0
The floor division of 10.0 by 3.0 is: 3.0
The result of 10.0 raised to the power of 3.0 is: 1000.0
2. Write a Program to Find the Largest of Three Numbers
Question: Write a program to input three numbers and find the
largest of the three using if-elif-else statements.
Ans: # Program to find the largest of three numbers

# Accepting three numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Using if-elif-else to determine the largest number


if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3

# Displaying the largest number


print(f"The largest number among {num1}, {num2}, and {num3} is:
{largest}")
Enter the first number: 9
Enter the second number: 7
Enter the third number: 5
The largest number among 9.0, 7.0, and 5.0 is: 9.0
3. Write a Program to Check Whether a Number is Prime or Not
Question: Write a program to check if a given number is a prime
number.
Ans: # Program to check if a number is prime

# Function to check if a number is prime


def is_prime(number):
# Check for numbers less than 2 (not prime)
if number <= 1:
return False
# Check divisibility from 2 to the square root of the number
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True

# Accepting user input


num = int(input("Enter a number: "))

# Checking if the number is prime


if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Enter a number: 7
7 is a prime number.
4. Write a Program to Display the Fibonacci Sequence
Question: Write a program to display the Fibonacci sequence up to n
terms, where n is provided by the user.
Ans: # Program to display the Fibonacci sequence up to n terms

# Function to generate the Fibonacci sequence


def fibonacci(n):
# Starting values for the Fibonacci sequence
a, b = 0, 1
# Displaying the Fibonacci sequence
for _ in range(n):
print(a, end=" ")
a, b = b, a + b # Update values of a and b

# Accepting user input


n_terms = int(input("Enter the number of terms for the Fibonacci
sequence: "))

# Checking if the input is valid (positive integer)


if n_terms <= 0:
print("Please enter a positive integer.")
else:
print(f"Fibonacci sequence up to {n_terms} terms:")
fibonacci(n_terms)
Enter the number of terms for the Fibonacci sequence: 6
Fibonacci sequence up to 6 terms:
011235
5. Write a Program to Count the Occurrences of Each Character in
a String
Question: Write a program to count the number of occurrences of
each character in a given string.
Ans # Program to count occurrences of each character in a given
string

# Function to count character occurrences


def count_characters(input_string):
# Creating an empty dictionary to store character counts
char_count = {}

# Looping through each character in the string


for char in input_string:
# If the character is already in the dictionary, increment its count
if char in char_count:
char_count[char] += 1
# Otherwise, add the character to the dictionary with a count of
1
else:
char_count[char] = 1

# Returning the dictionary with character counts


return char_count
# Accepting user input
input_string = input("Enter a string: ")

# Counting the occurrences of each character


result = count_characters(input_string)

# Displaying the result


print("Character occurrences:")
for char, count in result.items():
print(f"'{char}': {count}")
Enter a string: 5
Character occurrences:
'5': 1
6. Write a Program to Check Whether a String is a Palindrome
Question: Write a program to check if a given string is a palindrome
(the string reads the same backward as forward).
Ans # Program to check if a given string is a palindrome

# Function to check palindrome


def is_palindrome(input_string):
# Remove spaces and convert to lowercase for uniform comparison
formatted_string = input_string.replace(" ", "").lower()

# Check if the string is equal to its reverse


if formatted_string == formatted_string[::-1]:
return True
else:
return False

# Accepting user input


input_string = input("Enter a string: ")

# Checking if the input string is a palindrome


if is_palindrome(input_string):
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")
Enter a string: 5
'5' is a palindrome.
7. Write a Program to Sort a List of Numbers in Ascending Order
Question: Write a program to sort a list of numbers entered by the
user in ascending order.
Ans # Program to sort a list of numbers in ascending order

# Accepting user input


numbers = input("Enter numbers separated by spaces: ")

# Converting the input string into a list of numbers


num_list = [int(num) for num in numbers.split()]

# Sorting the list in ascending order


num_list.sort()

# Displaying the sorted list


print("Sorted list in ascending order:", num_list)
Enter numbers separated by spaces: 10 27 34 8
Sorted list in ascending order: [8, 10, 27, 34]
8. Write a Program to Create a Simple Calculator Using Functions
Question: Write a program to create a simple calculator that can
perform addition, subtraction, multiplication, and division using
functions.
Ans # Simple Calculator Program using functions

# Function to add two numbers


def add(x, y):
return x + y

# Function to subtract two numbers


def subtract(x, y):
return x - y

# Function to multiply two numbers


def multiply(x, y):
return x * y

# Function to divide two numbers


def divide(x, y):
# Check if the denominator is zero
if y == 0:
return "Error! Division by zero."
else:
return x / y

# Main program to execute the calculator


def calculator():
# Accepting user input for the operation
print("Select operation:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")

# Getting user choice


choice = input("Enter choice (1/2/3/4): ")

# Getting user input for the numbers


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform operation based on user choice


if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input! Please choose a valid operation.")
# Calling the calculator function to run program the
calculator()
Select operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter choice (1/2/3/4):
9. Write a Program to Find the Sum of Digits of a Number
Question: Write a program to find the sum of digits of a given
number.
Ans # Program to find the sum of digits of a given number

# Function to calculate the sum of digits


def sum_of_digits(number):
# Initialize the sum to 0
total_sum = 0

# Convert the number to positive if it's negative


number = abs(number)

# Loop through each digit in the number


while number > 0:
# Add the last digit to the total sum
total_sum += number % 10
# Remove the last digit
number //= 10

return total_sum

# Accepting user input


num = int(input("Enter a number: "))
# Calculate the sum of digits
result = sum_of_digits(num)

# Display the result


print(f"The sum of digits of {num} is: {result}")
Enter a number: 5
The sum of digits of 5 is: 5

10. Write a Program to Convert Celsius to Fahrenheit


Question: Write a program to convert a temperature given in Celsius
to Fahrenheit.
Ans # Program to convert Celsius to Fahrenheit

# Function to convert Celsius to Fahrenheit


def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit

# Accepting user input for temperature in Celsius


celsius = float(input("Enter temperature in Celsius: "))

# Convert Celsius to Fahrenheit


fahrenheit = celsius_to_fahrenheit(celsius)

# Display the result


print(f"{celsius}°C is equal to {fahrenheit}°F")
Enter temperature in Celsius: 69
69.0°C is equal to 156.2°F

11. Program to check if a given number is prime or not:


python
Copy code
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

num = int(input("Enter a number: "))


if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

12. Program to find the factorial of a number:


python
Copy code
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

num = int(input("Enter a number: "))


print(f"The factorial of {num} is {factorial(num)}.")

13. Program to find whether a string is a palindrome:


python
Copy code
def is_palindrome(s):
return s == s[::-1]

string = input("Enter a string: ")


if is_palindrome(string):
print(f"{string} is a palindrome.")
else:
print(f"{string} is not a palindrome.")
14. Program to merge two lists:
python
Copy code
def merge_lists(list1, list2):
return list1 + list2

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = merge_lists(list1, list2)
print("Merged list:", merged_list)

15. Program to create a simple calculator:


python
Copy code
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y
def divide(x, y):
if y == 0:
return "Cannot divide by zero"
return x / y

print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice(1/2/3/4): ")

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input")

16. Program to print all the prime numbers up to n:


python
Copy code
def print_primes(n):
for num in range(2, n+1):
if is_prime(num):
print(num, end=" ")

n = int(input("Enter a number: "))


print(f"Prime numbers up to {n}:")
print_primes(n)

17. Program to find the common elements between two lists:


python
Copy code
def common_elements(list1, list2):
return list(set(list1) & set(list2))
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7]
common = common_elements(list1, list2)
print("Common elements:", common)

18. Program to generate a multiplication table of a number:


python
Copy code
def multiplication_table(num, limit=10):
for i in range(1, limit + 1):
print(f"{num} x {i} = {num * i}")

num = int(input("Enter a number: "))


multiplication_table(num)

19. Program to print a pyramid pattern:


python
Copy code
def print_pyramid(n):
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))

rows = int(input("Enter the number of rows: "))


print_pyramid(rows)

20. Program to convert a binary number to decimal:


python
Copy code
def binary_to_decimal(binary):
return int(binary, 2)

binary = input("Enter a binary number: ")


decimal = binary_to_decimal(binary)
print(f"Decimal equivalent of {binary} is {decimal}.")

You might also like