[go: up one dir, main page]

0% found this document useful (0 votes)
7 views11 pages

AI Ass 1

The document contains six programming tasks in Python, each with a description and code implementation. Tasks include filtering numbers based on divisibility, calculating a series sum, simulating the Collatz Conjecture, computing a single-digit sum from a number, creating a number guessing game, and printing various patterns (inverted pyramid, pyramid, diamond). Each task is accompanied by example outputs demonstrating the expected results.

Uploaded by

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

AI Ass 1

The document contains six programming tasks in Python, each with a description and code implementation. Tasks include filtering numbers based on divisibility, calculating a series sum, simulating the Collatz Conjecture, computing a single-digit sum from a number, creating a number guessing game, and printing various patterns (inverted pyramid, pyramid, diamond). Each task is accompanied by example outputs demonstrating the expected results.

Uploaded by

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

Q1

Write a Python program to display only those numbers from a list that satisfy the following conditions •
The number must be divisible by five and three. • If the number is greater than 150, then skip it and
move to the following number • If the number is greater than 500, then stop the loop

def display_numbers(num_list):

for num in num_list:

if num > 500:

break

elif num > 150:

continue

elif num % 5 == 0 and num % 3 == 0:

print(num)

# Example list

numbers = [15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180, 200, 300, 450, 600]

display_numbers(numbers)

Output

15

30

45

60

75

90

105

120

135

150
Q2

Write a program to calculate the sum of series up to n terms. For example, if n = 5 and user input is 2,
then series will become 2 + 22 + 222 + 2222 + 22222 = 24690

Code

def calculate_series(n, num):

"""

Calculate the sum of series up to n terms.

Args:

n (int): Number of terms in the series.

num (int): The number to be repeated in the series.

Returns:

int: The sum of the series.

"""

total_sum = 0

# Generate each term of the series and add it to the total sum

for i in range(1, n + 1):

term = int(str(num) * i)

total_sum += term

return total_sum

# Get user input

n = int(input("Enter the number of terms (n): "))

num = int(input("Enter the number to be repeated: "))

# Calculate and print the sum of the series


result = calculate_series(n, num)

print(f"The sum of the series up to {n} terms is: {result}")

Output

Enter the number of terms (n): 45

Enter the number to be repeated: 34

The sum of the series up to 45 terms is:


34690337720640750943781246811549841852872155902458932761963064993368023671053974084
2771130

Q3 Create a program that simulates the Collatz Conjecture for a user-input number. For any number n: if
n is even, divide it by 2; if n is odd, multiply it by 3 and add 1. Repeat this until n becomes 1 and count
how many steps it took.

def collatz_conjecture(n):

"""

Simulate the Collatz Conjecture for a given number.

Args:

n (int): The number to start the simulation.

Returns:

int: The number of steps to reach 1.

"""

steps = 0

while n != 1:

print(n, end=" -> ")

if n % 2 == 0: # n is even

n = n // 2

else: # n is odd

n=3*n+1

steps += 1
print(n) # print the final 1

return steps

# Get user input

num = int(input("Enter a positive integer: "))

# Validate input

if num <= 0:

print("Please enter a positive integer.")

else:

# Run the simulation and print the result

steps = collatz_conjecture(num)

print(f"\nSteps to reach 1: {steps}")

output

Enter a positive integer: 3

3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1

Steps to reach 1: 7

Q4 Write a program that uses a loop to compute the sum of all digits of a user-input number until the
sum becomes a single digit. For example, input 9875 would give a final result of 2 (9 + 8 + 7 + 5 = 29; 2
+ 9 = 11; 1 + 1 = 2)

CODE

def single_digit_sum(n):

"""

Compute the sum of all digits of a number until the sum becomes a single digit.

Args:

n (int): The input number.


Returns:

int: The single-digit sum.

"""

while n >= 10: # Continue until n is a single digit

n = sum(int(digit) for digit in str(n)) # Sum of digits

print(f"Sum: {n}") # Print intermediate sums

return n

# Get user input

num = int(input("Enter a positive integer: "))

# Validate input

if num <= 0:

print("Please enter a positive integer.")

else:

# Compute and print the single-digit sum

result = single_digit_sum(num)

print(f"Single-digit sum: {result}")

Output

Enter a positive integer: 34

Sum: 7

Single-digit sum: 7

Q5

Create a program that simulates a number guessing game. The user has 5 attempts to guess a randomly
generated number between 1 and 50. Provide feedback (too high, too low) after each guess.

CODE

def number_guessing_game():

"""
Simulate a number guessing game.

The user has 5 attempts to guess a randomly generated number between 1 and 50.

"""

# Generate a random number between 1 and 50

target_number = random.randint(1, 50)

# Initialize attempts

attempts = 5

print("Welcome to the number guessing game!")

print("You have 5 attempts to guess a number between 1 and 50.")

while attempts > 0:

# Get user guess

user_guess = input("Enter your guess: ")

# Validate input

if not user_guess.isdigit():

print("Please enter a whole number.")

continue

user_guess = int(user_guess)

# Check if guess is within range

if user_guess < 1 or user_guess > 50:

print("Please enter a number between 1 and 50.")

continue
# Decrease attempts

attempts -= 1

# Check guess

if user_guess == target_number:

print(f"Congratulations! You guessed the number in {5 - attempts} attempts.")

return

elif user_guess < target_number:

print("Too low! Try again.")

else:

print("Too high! Try again.")

# Display remaining attempts

print(f"Attempts remaining: {attempts}")

# Game over

print(f"Game over! The number was {target_number}.")

# Run the game

number_guessing_game()

Output

Welcome to the number guessing game!

You have 5 attempts to guess a number between 1 and 50.

Enter your guess: 44

Too high! Try again.

Attempts remaining: 4

Enter your guess: 5

Too low! Try again.

Attempts remaining: 3
Enter your guess: 23

Too high! Try again.

Attempts remaining: 2

Enter your guess: 15

Too low! Try again.

Attempts remaining: 1

Enter your guess: 20

Too high! Try again.

Attempts remaining: 0

Game over! The number was 18.

Q6

Part 1

def inverted_pyramid(n, symbol):

"""

Print an inverted pyramid pattern.

Args:

n (int): Number of rows.

symbol (str): Symbol to use.

"""

for i in range(n, 0, -1):

print(symbol * i)

# Get user input

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

symbol = input("Enter the symbol: ")


# Print the inverted pyramid

inverted_pyramid(n, symbol)

output

*****

****

***

**

Part 2

def pyramid(n, symbol):

"""

Print a pyramid pattern.

Args:

n (int): Number of rows.

symbol (str): Symbol to use.

"""

for i in range(1, n + 1):

print(" " * (n - i) + symbol * (2 * i - 1))

# Get user input

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

symbol = input("Enter the symbol:)

output

***

*****
*******

Part 3

def diamond(n, symbol):

"""

Print a diamond pattern.

Args:

n (int): Number of rows in the top half.

symbol (str): Symbol to use.

"""

# Print top half (pyramid)

for i in range(1, n + 1):

print(" " * (n - i) + symbol * (2 * i - 1))

# Print bottom half (inverted pyramid)

for i in range(n - 1, 0, -1):

print(" " * (n - i) + symbol * (2 * i - 1))

# Get user input

n = int(input("Enter the number of rows in the top half: "))

symbol = input("Enter the symbol: ")

# Print the diamond

diamond(n, symbol)

output

**

***

****
*****

****

***

**

You might also like