0% found this document useful (0 votes)
3 views9 pages

Python Programming Unit3 Solutions

The document is a question bank for a Python programming course (BCC402) covering various topics such as search algorithms, function arguments, loops, variable types, and data structures. It includes important questions along with complete solutions, illustrating concepts like linear vs binary search, lambda functions, argument-passing methods, and dictionary operations. Each question is accompanied by code examples to demonstrate the concepts effectively.

Uploaded by

tanvirai90807
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)
3 views9 pages

Python Programming Unit3 Solutions

The document is a question bank for a Python programming course (BCC402) covering various topics such as search algorithms, function arguments, loops, variable types, and data structures. It includes important questions along with complete solutions, illustrating concepts like linear vs binary search, lambda functions, argument-passing methods, and dictionary operations. Each question is accompanied by code examples to demonstrate the concepts effectively.

Uploaded by

tanvirai90807
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

PYTHON PROGRAMMING (BCC402)

Unit 3 Important Question Bank & Complete Solutions

Q1. Describe the differences between linear search and binary search.

Both algorithms are used to find a target value inside a list, but their search strategies and performance
differ:

Feature Linear Search Binary Search

Sequentially checks every single index Repeatedly splits the sorted interval in half
Principle
from start to end. (Divide-and-Conquer).

Works on both sorted and unsorted


Array order Strictly requires the list to be sorted.
lists.

Time
Worst-case: O(n) Worst-case: O(log n) (extremely fast)
Complexity

Suitability Best for short, unsorted arrays. Best for large, sorted datasets.

Q2. Show an example where both Keyword arguments and Default arguments are used
for the same function.

def generate_bill(item, quantity=1, price=100):


total = quantity * price
print(f"Item: {item} | Quantity: {quantity} | Price: {price} | Total: {total}")

# 1. quantity defaults to 1, price defaults to 100


generate_bill("Notebook")

# 2. Combining positional ("Calculator") and keyword argument (price=250)


generate_bill("Calculator", price=250)

# 3. Passing all values as keyword arguments


generate_bill(price=50, item="Pen", quantity=10)

Python Programming (BCC402) | Unit 3 Question Bank Page 1 of 9


Q3. Write a Python program triangle(N) that prints a right triangle pattern using *.

def triangle(N):
for i in range(1, N + 1):
print("*" * i)

# Test call for N = 5


triangle(5)

Q4. Explain the lambda function.

A lambda function is a small, anonymous, one-line function defined without a name using the lambda
keyword.

• Syntax: lambda arguments : expression


• They can take any number of input variables but only support a single expression.
• No explicit return keyword is used; the expression is returned automatically.

# Standard function
def square(x):
return x * x

# Equivalent lambda function


square_lambda = lambda x: x * x

print(square_lambda(5)) # Output: 25

Python Programming (BCC402) | Unit 3 Question Bank Page 2 of 9


Q5. Discuss different types of argument-passing methods in Python. Explain variable-
length arguments with an example.

Python parameters can be passed in several ways:

1. Positional Arguments: Bound strictly by position index order.


2. Keyword Arguments: Bound explicitly using parameter names.
3. Default Arguments: Uses fallback values defined in parameter signatures if omitted.
4. Variable-Length Arguments: Allows arbitrary arguments:
◦ *args : Receives arbitrary positional arguments as a Tuple.
◦ **kwargs : Receives arbitrary keyword arguments as a Dictionary.

def print_student_info(section, *marks, **details):


print("Section:", section)
print("Marks (Tuple):", marks)
print("Details (Dict):", details)

print_student_info("CSE-A", 85, 90, 95, name="Vishu", city="Mainpuri")

Q6. Describe the while loop in Python.

The while loop repeatedly executes blocks of statement scopes as long as its evaluation condition
returns True .

# Simple iteration counting numbers 1 to 5


count = 1 # 1. Initialization

while count <= 5: # 2. Condition Check


print("Count is:", count)
count += 1 # 3. Increment/Update (prevents infinite loop)

Python Programming (BCC402) | Unit 3 Question Bank Page 3 of 9


Q7. Differentiate between global and local variables.

• Local Variables: Defined inside function scopes. Accessible only inside that specific function and
destroyed once execution completes.
• Global Variables: Defined outside functions at the main module scope level. Accessible across the
entire script.

y = 100 # Global

def my_func():
x = 50 # Local
print("Local x:", x)
print("Global y:", y)

my_func()

Q8. Write a recursive Python program to compute the factorial of a number.

def factorial(n):
# Base Case
if n == 0 or n == 1:
return 1
# Recursive Step
else:
return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Q9. What is a List? Explain with an example.

A List is an ordered, mutable, indexed, and heterogeneous collection of data elements. It allows
duplicates and is defined using square brackets [] .

# Creating a heterogeneous list


my_list = ["Python", 101, 3.14, True]

# Index access
print(my_list[0]) # Output: Python

# Modifying (lists are mutable)


my_list[1] = 202
print(my_list) # ["Python", 202, 3.14, True]

Python Programming (BCC402) | Unit 3 Question Bank Page 4 of 9


Q10. Write a Python program to check if a 3-digit number is an Armstrong number.

A 3-digit Armstrong number matches the sum of the cubes of its individual digits (e.g., 153 = 1^3 + 5^3 +
3^3).

def check_armstrong(num):
if num < 100 or num > 999:
print("Not a 3-digit number!")
return

temp = num
digit_sum = 0
while temp > 0:
digit = temp % 10
digit_sum += digit ** 3
temp //= 10

if num == digit_sum:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")

check_armstrong(153)

Q11. Write a Python program to remove all duplicates from a list without using set(). Print
the original and the modified list.

def remove_duplicates(original_list):
unique_list = []
for item in original_list:
if item not in unique_list:
unique_list.append(item)
return unique_list

sample = [1, 2, 2, 3, 4, 4, 5, 1, 6]
print("Original:", sample)
print("Modified:", remove_duplicates(sample))

Python Programming (BCC402) | Unit 3 Question Bank Page 5 of 9


Q12. Explain how to create a Dictionary in Python. Write a program to count the
frequency of each character in a given string using a dictionary.

A Dictionary is a mutable, unordered collection of key-value pairs written with curly braces {} where
keys are unique and immutable.

# Dictionary Initialization
my_dict = {"name": "Vishu", "age": 21}

def char_frequency(input_string):
frequency_dict = {}
for char in input_string:
if char in frequency_dict:
frequency_dict[char] += 1
else:
frequency_dict[char] = 1
return frequency_dict

print(char_frequency("hello google"))

Q13. Write a Python function that accepts a list of numbers and returns both the
maximum and minimum values (without using built-in functions like max() or min()).

def find_extremes(numbers):
if not numbers:
return None, None

maximum = numbers[0]
minimum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
if num < minimum:
minimum = num
return maximum, minimum

sample = [23, 45, 12, 89, 4, 56]


max_val, min_val = find_extremes(sample)
print(f"Max: {max_val}, Min: {min_val}")

Python Programming (BCC402) | Unit 3 Question Bank Page 6 of 9


Q14. What is list comprehension? Write a Python program to create a list of squares of
even numbers from 1 to 20 using list comprehension.

List Comprehension provides a concise syntax to create new lists from existing sequences in a single,
readable line.

# Squares of even numbers from 1 to 20


even_squares = [x**2 for x in range(1, 21) if x % 2 == 0]
print(even_squares)

Q15. Explain the difference between mutable and immutable data types in Python with
suitable examples for each.

• Mutable: Values/states can be directly modified in place without shifting their underlying memory
location ID (e.g., Lists, Dictionaries, Sets).
• Immutable: Values cannot be modified after instantiation; modifying operations generate a new
memory pointer ID (e.g., Strings, Tuples, Integers).

# Mutable Example
list_a = [1, 2]
print(id(list_a))
list_a.append(3)
print(id(list_a)) # ID is exactly the same

# Immutable Example
str_a = "hi"
print(id(str_a))
str_a += "!"
print(id(str_a)) # ID changes! New object created

Q16. Write a Python program to merge two dictionaries into one. Demonstrate with an
example.

dict1 = {'a': 1, 'b': 2}


dict2 = {'b': 99, 'c': 3}

# Merging using keyword argument dictionary unpacking


merged_dict = {**dict1, **dict2}

print("Merged Dictionary:", merged_dict) # overlapping key 'b' resolves to dict2 value

Python Programming (BCC402) | Unit 3 Question Bank Page 7 of 9


Q17. Develop a Python function to accept a tuple of numbers and return a new tuple
containing only the even numbers.

def filter_even_tuple(input_tuple):
# Construct list and cast back to tuple since tuples are immutable
even_list = [num for num in input_tuple if num % 2 == 0]
return tuple(even_list)

original = (1, 2, 3, 4, 5, 6, 7, 8)
print(filter_even_tuple(original))

Q18. Explain the concept of a Python set. Write a program to perform union, intersection,
and difference operations on two sets.

A Set is an unordered, unindexed, mutable collection containing exclusively unique elements. Duplicates
are filtered out automatically.

set_A = {1, 2, 3, 4, 5}
set_B = {4, 5, 6, 7, 8}

print("Union (A | B): ", set_A | set_B)


print("Intersection (A & B):", set_A & set_B)
print("Difference (A - B): ", set_A - set_B)

Q19. What is a lambda function in Python? Write a Python program to filter out all
numbers greater than 10 from a list using lambda and filter().

numbers = [5, 12, 3, 21, 8, 10, 15, 7]

# filter() takes a lambda function condition expression


filtered_nums = list(filter(lambda x: x > 10, numbers))

print("Numbers > 10:", filtered_nums)

Python Programming (BCC402) | Unit 3 Question Bank Page 8 of 9


Q20. Create a Python function that accepts any number of positional arguments and
returns their sum. Demonstrate by calling the function with 3, 5, 10, and 15 as arguments.

def sum_all_arguments(*args):
# args collects arguments as a tuple
return sum(args)

print(sum_all_arguments(3, 5))
print(sum_all_arguments(3, 5, 10, 15))

Python Programming (BCC402) | Unit 3 Question Bank Page 9 of 9

You might also like