Lab 1 – Answers
1. Swap Two Variables Without a Third Variable
a = 5
b = 10
print ("Before swapping: ")
print("Value of a : ", a, " and b : ", b)
# code to swap 'a' and 'b'
a, b = b, a
print ("After swapping: ")
print("Value of a : ", a, " and b : ", b)
2. Count the Frequency of Words in a String
# Input string
s = "AI is the future of AI"
# Initialize an empty dictionary to store word frequencies
w_freq = {}
# Calculate word frequencies using a for loop
for word in s.split():
w_freq[word] = w_freq.get(word, 0) + 1
# Print the result
print(w_freq)
3. Check if Two Strings are Anagrams
s1 = "listen"
s2 = "silent"
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
4. Convert a List of Strings to Integers
a = ['1', '2', '3', '4']
for i in range(len(a)):
a[i] = int(a[i])
print(a)
5. Write a Python program to convert a list of floating-point numbers to integers.
f = [1.5, 2.3, 3.6, 4.0]
for i in range(len(f)):
f[i] = int(f[i])
print(f)
6. Take Multiple Inputs in One Line
# Take space-separated inputs and convert them to integers
a = map(int, input().split())
# Convert the map object to a list and print it
b = list(a)
print(b)
7. Write a Program to Print Formatted Output
value = 123.4567
formatted_value = f"{value:.2f}"
print(formatted_value)
8. Compute (a+b)^2 Without Using ** Operator
a, b = 2, 3
value = a + b
ans = value * value
print("Output: ", ans)
9. Given a string mathematical expression, evaluate it (search for a function that can help you!)
expression = "3 + 2 * (4 - 1)"
result = eval(expression)
print(result)
10. Write a Python program that searches for the first multiple of 7 in a list using a while loop and stops
immediately when found (using break).
numbers = [2, 4, 10, 14, 22, 35, 40]
for i in range(len(numbers)):
if numbers[i] % 7 == 0:
print(f"First multiple of 7 found: {numbers[i]}")
break
11. Create a secret code-breaking game where the player has three attempts to guess the correct password
"AI2024".
a. If the user guesses correctly, print "Access Granted!" and exit.
b. If they run out of attempts, print "Access Denied!"
password = "AI2024"
attempts = 3
while attempts > 0:
guess = input("Enter the password: ")
# Check if the guess is correct
if guess == password:
print("Access Granted!")
break
else:
attempts -= 1
print(f"Incorrect password. You have {attempts} attempt(s) left.")
if attempts == 0:
print("Access Denied!")
12. Write a Python function called calculate_total that accepts a list of prices:
a. Takes prices (price1, price2, price3,...) and returns their total sum
b. Includes a default argument (discount) that subtracts a discount from the total.
c. Accepts a keyword argument (detailed): If detailed=True, return a formatted breakdown instead of
just the total price.
def calculate_total(prices, discount=0, detailed=False):
total = sum(prices)
total_after_discount = total - discount
# If detailed is True, return a breakdown of the calculation
if detailed:
breakdown = f"Prices: {prices}\nTotal before discount:
${total:.2f}\nDiscount: ${discount:.2f}\nTotal after discount:
${total_after_discount:.2f}"
return breakdown
else:
return total_after_discount
prices = [20, 300, 400, 700]
discount = 30
print(calculate_total(prices, discount, detailed=True))
# Call without detailed breakdown
print(calculate_total(prices, discount))
13. Given the following NumPy array representing a dataset of student scores across different subjects:
a. Extract the scores of the first two students.
b. Sort the scores of each student in descending order.
c. Extract all scores greater than 85.
import numpy as np
# Create a NumPy array representing student scores across subjects
scores = np.array([
[85, 90, 78],
[88, 76, 92],
[91, 87, 85],
[79, 81, 89]
])
# 1. Extract the scores of the first two students
first_two_students_scores = scores[:2]
print("Scores of the first two students:")
print(first_two_students_scores)
# 2. Sort the scores of each student in descending order
sorted_scores = np.sort(scores, axis=1)[:, ::-1]
print("\nScores sorted in descending order for each student:")
print(sorted_scores)
# 3. Extract all scores greater than 85
scores_greater_than_85 = scores[scores > 85]
print("\nScores greater than 85:")
print(scores_greater_than_85)