Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Unit II Icup Answer Key

Uploaded by

riyass.ug.24.cb
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 views13 pages

Unit II Icup Answer Key

Uploaded by

riyass.ug.24.cb
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/ 13

FRANCIS XAVIER ENGINEERING COLLEGE, TIRUNELVELI

(An Autonomous Institution)

DEPARTMENT OF INFORMATION TECHNOLOGY

ACADEMIC YEAR: 2024-25/EVEN BATCH: 2024 – 2028 SEM: II

Course Code | Name: 24CS2501 INTRODUCTION TO COMPUTING USING PYTHON

Unit II –Data structures and Functions

Data structures: Lists – Tuples – Dictionaries - sets – Stack – Queue - Working with
Strings Functions: Definition, Function call, Parameters, return values – Recursion –
Anonymous and Lambda Function– Scope of variables.

Course Outcome – CO2: Apply data structures like lists, tuples, dictionaries, and sets,
along with functions including recursion and lambda functions effectively.

Important topics

 Topic 1 –List and tuples,


 Topic 2 –Dictionaries and sets,
 Topic 3 –Stack and queues and
 Topic 4 – working with string function
 Topic 5- Function- Recursion function
Answer all the Questions
PART – A
Q.No Question
Write an output for the following code:
k=[2,1,0,3,0,2,1]
print(k.count(k.index(0)))
The output will be: 2
Explanation:
k.index(0) returns the index of the first occurrence of 0 in the list k, which is 2.
k.count(2) counts the number of occurrences of 2 in the list k, which is 2.
1. B) Write an output for the following code:
l = [1, 0, 2, 0, "hello", " ", []]
print(list(filter(bool, l)))
The output will be: [1, 2, 'hello', ' ']
Explanation:
filter (bool, l) filters the elements of the list l using the bool function, which removes falsy values
(like 0, "", [], etc.).
The resulting list contains all the truthy elements from the original list l.
what is the output of the following python code?
Numbers =[12,5,8,13,4]
Num=Numbers[::2]
2. print(Num)
Output
[12, 8, 4]
Numbers[::2] slices the list with a step of 2, meaning it picks every second element starting from
index 0.
The elements selected: Numbers[0] = 12, Numbers[2] = 8 and Numbers[4] = 4
a = [1,2,3,4,5]
print(a[:4].pop( ) )
Output
4
a[:4] creates a new list [1, 2, 3, 4] (excluding the last element 5).
.pop() removes and returns the last element of this new list (4).
However, a[:4] creates a copy, so the original list a remains unchanged.
Suppose you have a dictionary 'inventory' with items and their quantities.
inventory = {'apple': 50, 'banana': 30, 'orange': 40}
How can you check if 'banana' is present in the inventory
inventory = {'apple': 50, 'banana': 30, 'orange': 40}
if 'banana' in inventory:
3.
print("'banana' is present in the inventory.")
else:
print("'banana' is not present in the inventory.")
Output
'banana' is present in the inventory.
What will be the output of the program?
stack = []
# Push elements onto the stack
stack.append(10)
stack.append(20)
# Pop an element
4. print(stack.pop())
Output
20
stack.append(10) → Stack becomes [10]
stack.append(20) → Stack becomes [10, 20]
stack.pop() → Removes 20 (Last In, First Out) and prints it.
Fill in the Blank:
Question 1:
sentence = "Python is a powerful programming language."
length = _______________
print("Length of the sentence:", length)
Answer:
sentence = "Python is a powerful programming language."
length = len(sentence)
print("Length of the sentence:", length)
Length of the sentence: 42
5. Question 2:
text = "Hello, World! How are you today?"
count_o = text.____________________
print("Occurrences of 'o':", count_o)
Answer:
text = "Hello, World! How are you today?"
count_o = text.count("o")
print("Occurrences of 'o':", count_o)
Occurrences of 'o': 5
Question 3:
word = "python"
uppercase_word = word.__________________
print("Uppercase word:", uppercase_word)
Answer:
word = "python"
uppercase_word = word.upper()
print("Uppercase word:", uppercase_word)
Uppercase word: PYTHON
Question 4:
quote = "To be or not to be, that is the question."
starts_with_to = quote.____________________
print("Starts with 'To':", starts_with_to)
Answer:
quote = "To be or not to be, that is the question."
starts_with_to = quote.startswith("To")
print("Starts with 'To':", starts_with_to)
Starts with 'To': True
What will be the output of the program, provide your answer by observing the following
flowchart?

6.

The output of the provided code is the sum of all elements in the list [1, 3, 67, 3, 4, 20], which is
98.
Here's how the code works:
 Initialize the variable total to 0.
 Iterate over each element in the list a.
 Add each element to the total variable.
 After iterating through all elements, print the value of total, which is the sum of all elements
in the list a.
Therefore, the output of the code is 98, which is the sum of all elements in the list [1, 3, 67, 3, 4,
20].

PART – B

Q.No Question
Let’s say you wanted to create a list using python that holds the name of a bunch of smoothies
1 i)
Q.No Question

1)Access the values of smoothies list at the index [2]


smoothie_at_index_2 = smoothies[2]
print(smoothie_at_index_2)
Output
Banana
2)set the value of item at index 3 to “tropical”
smoothies[3] = "tropical"
print(smoothies)
Output (updated list)
["coconut", "strawberry", "banana", "tropical", "acai berry"]
3)provide number of items present in the list
number_of_items = len(smoothies)
print("Number of items present in the list:", number_of_items)
Output
Number of items present in the list: 5
4)print last 3 smoothies on the list using negative indices
last_three_smoothies = smoothies[-3:]
print("Last 3 smoothies on the list:", last_three_smoothies)
Output
Last 3 smoothies on the list: ['banana', 'tropical', 'acai berry']
What are the build-in methods used to produce the following output for the given input

ii)

1. Append() method: Adds an element to the end of the list.


2. Count(): Returns the number of occurrences of a specified element in the list.
Q.No Question
3. Copy(): Returns a copy of the list.
4. Index(): Returns the index of the first occurrence of a specified value in the list.
5. Reverse(): Reverses the order of the elements in the list.
6. Remove(): Removes the first occurrence of a specified value from the list.
7. Insert(): Inserts an element at the specified position in the list.
8. Pop(1): Removes the element at the specified position in the list and returns it.
9. Pop(): Removes the last element from the list and returns it.
You are given a dictionary representing the grades of students. Each key is a student
name, and the corresponding value is a list of their grades. Write a Python program to
perform the following operations:
 Add a new student "Alice" with grades [90, 95, 88].
 Modify the grades of the student "Bob" to [85, 92, 78].
 Delete the student "Charlie" from the dictionary.
 Print the names of all students along with their average grades
# Given dictionary representing grades of students
grades = {
'John': [85, 90, 88],
'Emma': [92, 89, 94],
'Michael': [78, 85, 80]
}
# Add a new student "Alice" with grades [90, 95, 88]
grades['Alice'] = [90, 95, 88]
# Print the updated dictionary
print("Updated grades dictionary:")
print(grades)
Output
Updated grades dictionary:
2 i) {'John': [85, 90, 88], 'Emma': [92, 89, 94], 'Michael': [78, 85, 80], 'Alice': [90, 95, 88]}
explanation
We simply use square brackets ([]) to add a new key-value pair to the grades dictionary.
The key 'Alice' is added with the corresponding value [90, 95, 88], representing her grades.
After adding the new entry, we print the updated grades dictionary to verify the addition of the
new student.
Modify the grades of the student "Bob" to [85, 92, 78].
Code:
# Given dictionary representing grades of students
grades = {
'John': [85, 90, 88],
'Emma': [92, 89, 94],
'Michael': [78, 85, 80],
'Bob': [90, 85, 80] # Bob's original grades
}
# Modify the grades of the student "Bob" to [85, 92, 78]
grades['Bob'] = [85, 92, 78]
# Print the updated dictionary
print("Updated grades dictionary:")
print(grades)
Output
Q.No Question
Updated grades dictionary:
{'John': [85, 90, 88], 'Emma': [92, 89, 94], 'Michael': [78, 85, 80], 'Bob': [85, 92, 78]}
explanation
We use square brackets ([]) to access the value associated with the key 'Bob'.
Then, we assign the new grades [85, 92, 78] to the key 'Bob', effectively modifying his grades.
After modifying the grades, we print the updated grades dictionary to verify the changes.
Delete the student "Charlie" from the dictionary.
# Given dictionary representing grades of students
grades = {
'John': [85, 90, 88],
'Emma': [92, 89, 94],
'Michael': [78, 85, 80],
'Charlie': [85, 92, 78] # Charlie's grades
}
# Delete the student "Charlie" from the dictionary
del grades['Charlie']
# Print the updated dictionary
print("Updated grades dictionary:")
print(grades)
Output
Updated grades dictionary:
{'John': [85, 90, 88], 'Emma': [92, 89, 94], 'Michael': [78, 85, 80]}
explanation
We use the del statement followed by the dictionary name and the key 'Charlie' to delete the
entry associated with the student "Charlie".
After deleting the entry, we print the updated grades dictionary to verify that the student
"Charlie" has been removed.
Print the names of all students along with their average grades
To print the names of all students along with their average grades, you can iterate over the
grades dictionary, calculate the average grade for each student, and then print the student's
name along with their average grade.
# Given dictionary representing grades of students
grades = {
'John': [85, 90, 88],
'Emma': [92, 89, 94],
'Michael': [78, 85, 80],
'Bob': [85, 92, 78]
}
# Iterate over the dictionary
for student, student_grades in grades.items():
# Calculate the average grade for each student
average_grade = sum(student_grades) / len(student_grades)
# Print the student's name along with their average grade
print(f"{student}: {average_grade}")
Output
John: 87.66666666666667
Emma: 91.66666666666667
Michael: 81.0
Bob: 85.0
Explanation
Q.No Question
We iterate over the grades dictionary using the items() method, which gives us access to both
the student's name (student) and their grades (student_grades).
For each student, we calculate the average grade by summing up all the grades and dividing by
the total number of grades.
Finally, we print the student's name along with their average grade using an f-string
Consider the following dictionary representing the scores of students in a class:
scores = {
'Alice': 85,
'Bob': 90,
'Charlie': 75,
'David': 80,
'Emma': 95
}
Write a Python code snippet to perform the following operations using dictionary
methods:
 Add a new student 'Frank' with a score of 88.
 Remove the student 'David' from the dictionary.
 Update the score of 'Emma' to 92.
scores = {
'Alice': 85,
'Bob': 90,
'Charlie': 75,
'David': 80,
'Emma': 95
}
ii)
# Add a new student 'Frank' with a score of 88
scores['Frank'] = 88
# Remove the student 'David' from the dictionary
if 'David' in scores:
del scores['David']
# Update the score of 'Emma' to 92
scores['Emma'] = 92
print("Updated scores dictionary:")
print(scores)
Output
Updated scores dictionary:
{'Alice': 85, 'Bob': 90, 'Charlie': 75, 'Emma': 92, 'Frank': 88}
Explanation
Adding 'Frank': We use the square brackets [] to add a new student 'Frank' to the scores
dictionary and assign him a score of 88.
Removing 'David': We check if 'David' is in the dictionary using an if statement. If 'David'
exists in the dictionary, we remove him using the del keyword.
Updating 'Emma's score: Again, we use square brackets [] to access 'Emma' in the scores
dictionary and update her score to 92.
Finally, we print out the updated scores dictionary to see the changes.
Write a Python program to implement the following:
Create a stack and perform the following operations:
3 i)  Push elements 10, 20, and 30 onto the stack.
 Pop the top element and display it.
 Display the remaining elements in the stack.
Q.No Question
Create a queue and perform the following operations:
 Enqueue elements 5, 15, and 25.
 Dequeue the front element and display it.
 Display the remaining elements in the queue.
from collections import deque
# Stack Implementation (LIFO)
stack = []
# Push elements onto the stack
stack.append(10)
stack.append(20)
stack.append(30)
# Pop the top element and display it
print("Popped from stack:", stack.pop())
# Display the remaining elements in the stack
print("Remaining stack:", stack)
# Queue Implementation (FIFO)
queue = deque()
# Enqueue elements
queue.append(5)
queue.append(15)
queue.append(25)
# Dequeue the front element and display it
print("Dequeued from queue:", queue.popleft())
# Display the remaining elements in the queue
print("Remaining queue:", list(queue))
output
Popped from stack: 30
Remaining stack: [10, 20]
Dequeued from queue: 5
Remaining queue: [15, 25]
Explanation:
Stack (LIFO - Last In, First Out)
Push 10, 20, 30 → stack = [10, 20, 30]
Pop 30 (last added element) → stack = [10, 20]
Display remaining stack: [10, 20]
Queue (FIFO - First In, First Out)
Enqueue 5, 15, 25 → queue = [5, 15, 25]
Dequeue 5 (first added element) → queue = [15, 25]
Display remaining queue: [15, 25]
4 i) Write the output for the following built-in string methods
Q.No Question

Answer
"Hello world".capitalize() - Hello world
"Hello world".casefold() - hello world
"Hello world".count("o") - 2
"Hello world".find("World") - -1
"Hello world".index("Hello") - 0
"Hello world".isalnum() - False
"Hello world".isalpha() - False
"Hello world".isascii() - True
"Hello world".isdecimal() - False
"Hello world".isdigit() - False
"Hello world".isidentifier() - False
"Hello world".islower() - False
"Hello world".isnumeric() - False
"Hello world".isprintable() - True
Consider the following Python code snippet:
word = "programming"
Which of the following options correctly counts the occurrences of 'r' in the 'word' variable?
A. word.count('r')
B. word.find('r')
C. word.upper()
D. word.isalpha()
Choose the correct option(s):
ii) 1. A and B
2. A and C
3. A and D
4. B and C
5. All of the above
Provide a brief explanation of why you chose the particular answer.
The correct option is:
A and B
Explanation:
Q.No Question
Option A (word.count('r')) correctly counts the occurrences of the character 'r' in the string
variable word. It returns the count of occurrences, which is the desired behavior.
Option B (word.find('r')) does not count the occurrences of the character 'r'. Instead, it finds the
index of the first occurrence of 'r' in the string. Therefore, it is not the correct option for
counting occurrences.
So, the correct option for counting the occurrences of 'r' in the word variable is A
You are tasked with designing a Python program that includes a function to calculate the
area of different shapes. Write a program with the following specifications:
 Implement a function named calculate_area that takes two parameters: shape
(string) and dimension (float).
 The function should calculate and return the area based on the provided shape. The
program should support two shapes: "circle" and "rectangle".
 For a circle, the area is calculated using the formula:
𝑨𝒓𝒆𝒂 = 𝝅𝒓𝟐
 For a rectangle, the area is calculated using the formula:
Area=length×width.
 In the main part of the program, create a list of shape-dimension pairs and use the
calculate_area function to print the area for each pair.
Code:
import math
def calculate_area(shape, dimension):
"""Function to calculate the area based on the provided shape."""
if shape == "circle":
area = math.pi * dimension ** 2
elif shape == "rectangle":
5 i)
length, width = dimension
area = length * width
else:
area = None
print("Invalid shape! Please provide either 'circle' or 'rectangle'.")
return area
# List of shape-dimension pairs
shape_dimensions = [("circle", 3), ("rectangle", (4, 5)), ("triangle", 3)]
# Calculate and print area for each shape-dimension pair
for shape, dimension in shape_dimensions:
area = calculate_area(shape, dimension)
if area is not None:
print(f"The area of {shape} with dimension(s) {dimension} is: {area}")
In this program:
• We define a function calculate_area that takes two parameters: shape (string) and
dimension (float for circle, tuple of length and width for rectangle).
• Inside the function, we calculate the area based on the provided shape using the
appropriate formula.
• We then create a list of shape-dimension pairs.
Q.No Question
• We iterate over each pair, calculate the area using the calculate_area function, and print
the result.
Output
The area of circle with dimension(s) 3 is: 28.274333882308138
The area of rectangle with dimension(s) (4, 5) is: 20
Invalid shape! Please provide either 'circle' or 'rectangle'.
a).Complete the following Python code to calculate the factorial of a given positive integer
using recursion:
def factorial(n):
if ________________:
return ____
else:
return ______ * factorial(____)
result = factorial(4)
print("Factorial:", result)
Code:
Recursion is the process of defining something in terms of itself.
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
ii)
Output
The factorial of 3 is 6
b). Complete the following Python code to calculate the power of a number using
recursion:
def power(base, exponent):
if ________________:
return ____
else:
return base * power(base, ______)
result = power(2, 3)
print("Power:", result)
def power(base, exponent):
if exponent == 0: # Base case: any number raised to 0 is 1
return 1
else:
return base * power(base, exponent - 1) # Recursive case
result = power(2, 3)
print("Power:", result)
output
Power: 8
PART – C

Q.No
Write the python program for following scenario

Code:
def check_integer_string(input_string):
if input_string.isdigit():
return "The string is an integer string"
else:
for char in input_string:
if not char.isdigit():
return "Alphabet or special character found, the string is not an integer string"
return "Alphabet not found, the string is an integer string"
# Get input from the user
1 i) input_string = input("Enter a string: ")
# Check if the input string is an integer string
result = check_integer_string(input_string)
print(result)

Output

Enter a string: 0123456789


The string is an integer string

Enter a string: 0123456a8b


Alphabet or special character found, the string is not an integer string
This program defines a function check_integer_string() that takes a string as input and checks
if it is an integer string or not. It first checks if the entire string consists of digits using the
isdigit() method. If it does, the function returns "The string is an integer string". If not, it iterates
through each character and checks if it is a digit. If it finds a non-digit character, it returns
"Alphabet or special character found, the string is not an integer string". Otherwise, it returns
"Alphabet not found, the string is an integer string".

Write a python program that will take one string as input. The program will then remove vowel
ii)
a,e,i,o,u (in lower and upper case) print the output
Q.No

Code:

def remove_vowels(input_string):
vowels = "aeiouAEIOU"
output_string = ""
for char in input_string:
if char not in vowels:
output_string += char
return output_string
# Example usage
input_string = input("Enter a string: ")
result = remove_vowels(input_string)
print("Output:", result)
Output
Enter a string: Python is Awesome!
Output: Pythn s wsm!
Function Definition (remove_vowels):
This function takes one parameter input_string, which is the input string provided by the user.
It initializes a string variable vowels containing all lowercase and uppercase vowels.
It initializes an empty string output_string to store the result.
It iterates over each character in the input string.
For each character, it checks if the character is not present in the vowels string.
If the character is not a vowel, it appends it to the output_string.
Finally, it returns the output_string containing the input string with vowels removed.
Example Usage:
It prompts the user to enter a string using input().
It calls the remove_vowels function with the input string provided by the user.
It assigns the result to the variable result.
Finally, it prints the result

You might also like