AI Ass 1
AI Ass 1
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):
break
continue
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
"""
Args:
Returns:
"""
total_sum = 0
# Generate each term of the series and add it to the total sum
term = int(str(num) * i)
total_sum += term
return total_sum
Output
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):
"""
Args:
Returns:
"""
steps = 0
while n != 1:
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
# Validate input
if num <= 0:
else:
steps = collatz_conjecture(num)
output
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:
"""
return n
# Validate input
if num <= 0:
else:
result = single_digit_sum(num)
Output
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.
"""
# Initialize attempts
attempts = 5
# Validate input
if not user_guess.isdigit():
continue
user_guess = int(user_guess)
continue
# Decrease attempts
attempts -= 1
# Check guess
if user_guess == target_number:
return
else:
# Game over
number_guessing_game()
Output
Attempts remaining: 4
Attempts remaining: 3
Enter your guess: 23
Attempts remaining: 2
Attempts remaining: 1
Attempts remaining: 0
Q6
Part 1
"""
Args:
"""
print(symbol * i)
inverted_pyramid(n, symbol)
output
*****
****
***
**
Part 2
"""
Args:
"""
output
***
*****
*******
Part 3
"""
Args:
"""
diamond(n, symbol)
output
**
***
****
*****
****
***
**