Computer Science Question paper
1. a) Code Fragment to Generate a Random Float and its Nearest Integer (Greater Than)
Python
import random
import math
random_float = random.uniform(45.0, 95.0) # Generates a random float between 45.0 and 95.0 (inclusive)
nearest_integer = math.ceil(random_float) # math.ceil rounds up to the nearest integer
print("Random Float:", random_float)
print("Nearest Integer (Greater Than):", nearest_integer)
1. b) Python Program to Calculate Mean, Median, and Mode
Python
from collections import Counter
def calculate_stats(M):
n = len(M)
# Mean
mean = sum(M) / n
# Median
sorted_M = sorted(M)
if n % 2 == 0:
median = (sorted_M[n // 2 - 1] + sorted_M[n // 2]) / 2
else:
median = sorted_M[n // 2]
# Mode
count = Counter(M)
mode = count.most_common(1)[0][0] # Gets the most frequent element
return mean, median, mode
# Example usage:
M = [1, 2, 2, 3, 4, 5, 5, 5]
mean, median, mode = calculate_stats(M)
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
1. c) What is Anti-Virus Software?
Anti-virus software is a program or set of programs that are designed to detect, prevent, and take action to disarm or remove malicious software programs, known as viruses, worms, Trojan horses, adware, spyware, and other forms of malware.
1. d) Cyber Crimes:
a) Cyber Bullying: Cyber bullying is the use of electronic communication to bully a person, typically by sending messages of an intimidating or threatening
b) Cyber Stalking: Cyber stalking is a form of harassment where the perpetrator uses electronic communication to repeatedly harass or threaten a victim. It can include monitoring online activity, sending unwanted messages, making false accusations, and even threats of physical harm.
1. e) What is Digital Property?
Digital property refers to anything that exists in a digital format and that an individual or organization has exclusive rights to use. Just like physical property, digital property can be owned, leased, and protected.
Examples:
- E-books: Literary works in digital format.
- Music files: Audio recordings in digital format.
- Software licenses: Permissions to use specific software.
- Digital photographs: Images stored in digital format.
- Domain names: Unique web addresses.
1. f) i) Importance of the Statement:
The statement highlights the crucial link between privacy and trust in e-commerce. When customers share personal data online, they expect businesses to handle it responsibly. Clear privacy policies build trust, encouraging customers to engage in online transactions.
1. f) ii) Need to Safeguard User Privacy:
Safeguarding user privacy is essential for several reasons:
- Ethical obligation: Respecting individuals’ control over their personal information is a fundamental ethical principle.
- Legal compliance: Many countries have laws and regulations (e.g., GDPR, CCPA) that mandate the protection of personal data.
- Maintaining trust: Data breaches and privacy violations can severely damage a company’s reputation and erode customer trust.
- Preventing misuse: Protecting privacy prevents identity theft, fraud, and other harms that can arise from the misuse of personal data.
1. g) Matching
- i) Plagiarism – ii) Copy and paste information from the Internet into your report and then organize it.
- ii) Hacking – iv) Breaking into computers to read private emails and other files.
- iii) Credit card fraud – i) Fakers, by offering special rewards or money prize asked for personal information, such as bank account information. (This appears to describe a phishing scam rather than direct credit card fraud, but it’s the closest match provided.)
- iv) Digital Foot Print – iii) The trail that is created when a person uses the internet.
1. h) Internet Security Issues:
- Viruses: Malicious programs that can replicate themselves and spread to other computers, often causing damage or stealing information.
- Pharming: A type of online fraud where malicious code is installed on a computer or server, redirecting users to fake websites to steal personal information.
- Phishing: A deceptive attempt to obtain sensitive information (such as usernames, passwords, and credit card details) by disguising as a trustworthy entity in
electronic communication.
1. i) Measures to Keep Data Secure:
- Use strong passwords: Create unique, complex passwords and store them securely.
- Keep software updated: Regularly install updates for operating systems and applications to patch security vulnerabilities.
- Be cautious of suspicious emails and links: Avoid clicking on links or opening attachments from unknown or untrusted sources.
- Use antivirus and anti-malware software: Install and keep updated security software to protect against malware.
- Enable a firewall: Use a firewall to control network traffic and block unauthorized access.
- Back up data regularly: Create backups of important data to protect against data loss from hardware failure or cyberattacks.
2. a) List Methods: remove()
and reverse()
i. remove()
-
Question: Explain the use of the
remove()
method with an example. -
Answer: The
remove()
method removes the first occurrence of a specified value from the list. If the value is not found, it raises aValueError
.Example:
PythonM = ['p', 'e', 'o', 'b', 'l', 'e', 'm'] M.remove('e') # Removes the first 'e' print(M) # Output: ['p', 'o', 'b', 'l', 'e', 'm'] # M.remove('z') # This would raise a ValueError because 'z' is not in the list.
ii. reverse()
-
Question: Explain the use of the
reverse()
method with an example. -
Answer: The
reverse()
method reverses the elements of the list in place. This means it modifies the original list directly and doesn’t return a new list.-
Example:
Python
M = ['p', 'e', 'o', 'b', 'l', 'e', 'm'] M.reverse() print(M) # Output: ['m', 'e', 'l', 'b', 'o', 'e', 'p']
-
2. b) append()
vs. extend()
-
Question: What is the difference between the
append()
andextend()
functions? Illustrate with an example. -
Answer: Both
append()
andextend()
add elements to the end of a list, but they do it differently:append()
: Adds a single element to the end of the list. This element can be of any data type, including another list. The original list’s length increases by one.extend()
: Adds multiple elements from an iterable (like another list, tuple, or string) to the end of the list. It effectively unpacks the iterable and adds its individual items. The original list’s length increases by the number of elements in the iterable.
-
Example:
Python
M = ['p', 'e', 'o'] # append() example: M.append(['b', 'l', 'e']) # Adds a list as a single element print(M) # Output: ['p', 'e', 'o', ['b', 'l', 'e']] # Length increases by 1 # extend() example: M = ['p', 'e', 'o'] # Reset M M.extend(['b', 'l', 'e']) # Adds individual elements from the list print(M) # Output: ['p', 'e', 'o', 'b', 'l', 'e'] # Length increases by 3 M = ['p', 'e', 'o'] # Reset M M.extend("xyz") # Adds individual characters from string print(M) # Output: ['p', 'e', 'o', 'x', 'y', 'z'] # Length increases by 3
2. c) Predicting Output
i.
- Question: Predict the output of the following code:
Python
M = ['p', 'e', 'o', 'b', 'l', 'e', 'm']
M[2:3] = []
print(M)
M[2:5] = []
print(M)
- Answer:
['p', 'e', 'b', 'l', 'e', 'm']
['p', 'e', 'm']
- Explanation:
M[2:3] = []
removes the element at index 2 (‘o’).M[2:5] = []
then removes the elements from index 2 up to (but not including) index 5 (‘b’, ‘l’, ‘e’).
ii.Question: Predict the output of the following code:
Python
a, b, c = [1, 2], [1, 2], [1, 2]
print(a == b)
print(a is b)
- Answer:
True
False
- Explanation:
==
checks for value equality (whether the lists have the same elements).is
checks for object identity (whether the variables refer to the same object in memory).a
andb
have the same value, but they are distinct objects in memory.
2. d) Max and Min in a Range
- Question: Write a program to display the maximum and minimum values from a specified range of indices in the list
M = [12, 13, 45, 67, 123, 4, 90, 1, 62, 18]
. - Answer:
Python
M = [12, 13, 45, 67, 123, 4, 90, 1, 62, 18]
def find_max_min_in_range(lst, start_index, end_index):
if not (0 <= start_index <= end_index < len(lst)):
raise ValueError("Invalid range of indices")
sub_list = lst[start_index : end_index+1] # Added 1 to include the end_index element
if not sub_list: # Check if the sublist is empty
return None, None
maximum = max(sub_list)
minimum = min(sub_list)
return maximum, minimum
# Example usage:
maximum, minimum = find_max_min_in_range(M, 2, 6)
print("Maximum:", maximum)
print("Minimum:", minimum)
2. e) Sum of Even Indexed Minus Sum of Odd Indexed
-
Question: Write a program that prints the sum of the even-indexed elements of a list
L
minus the sum of the odd-indexed elements. For example, ifL = [1, 2, 3, 4, 5, 6, 7, 8, 9]
, the result should be 5. -
Answer:
Python
L = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sum_even = 0
sum_odd = 0
for i in range(len(L)):
if i % 2 == 0: # Even index
sum_even += L[i]
else: # Odd index
sum_odd += L[i]
result = sum_even - sum_odd
print("Result:", result)
OR (Swapping Even and Odd Indexed Elements)
- Question: Write a program to input a list of numbers and swap elements at the even locations with the elements at the odd locations. For example, if the original list is
[12, 23, 45, 16, 22, 34]
, the altered list should be[23, 12, 16, 45, 34, 22]
. - Answer:
Python
def swap_even_odd(lst):
for i in range(0, len(lst) - 1, 2): # Iterate through even indices
lst[i], lst[i + 1] = lst[i + 1], lst[i] # Swap with the next element (odd index)
# Example:
original_list = [12, 23, 45, 16, 22, 34]
swap_even_odd(original_list)
print("Altered List:", original_list)
3. a) Tuples vs. Lists
-
Question: How are tuples different from lists when both are sequences?
-
Answer: Both tuples and lists are ordered sequences in Python, but they have key distinctions:
- Mutability: Lists are mutable, meaning you can change their elements after creation (add, remove, modify). Tuples are immutable; once created, their elements cannot be altered.
- Syntax: Lists are defined using square brackets
[]
, while tuples use parentheses()
. - Performance: Tuples are generally slightly more memory-efficient and can be faster for iteration than lists due to their immutability.
- Use Cases: Lists are used for collections of items that might need modification. Tuples are suitable for representing fixed collections of items (like records), where immutability is beneficial for data integrity.
3. b) Unpacking a Tuple
-
Question: What do you mean by unpacking a tuple? Give a suitable example.
-
Answer: Unpacking a tuple involves assigning the individual elements of the tuple to separate variables.
-
Example:
Pythonperson = ("Alice", 30, "New York") name, age, city = person # Unpacking the tuple print(name) # Output: Alice print(age) # Output: 30 print(city) # Output: New York
-
3. c) Fibonacci Series Tuple
- Question: Write a program to create a tuple storing the first 9 terms of the Fibonacci series.
- Answer:
def fibonacci(n):
fib_list = []
a, b = 0, 1
for _ in range(n):
fib_list.append(a)
a, b = b, a + b
return tuple(fib_list)
fibonacci_tuple = fibonacci(9)
print(fibonacci_tuple) # Output: (0, 1, 1, 2, 3, 5, 8, 13, 21)
3. d) Predicting Output
i.
- Question: Predict the output:
t1 = (23, 1, 45, 67, 45, 9, 55, 45)
t2 = (100, 200)
print(t1.index(45))
print(t1 + t2)
print(min(t1))
- Answer:
2
(23, 1, 45, 67, 45, 9, 55, 45, 100, 200)
1
- Explanation:
t1.index(45)
returns the index of the first occurrence of 45.t1 + t2
concatenates the two tuples.min(t1)
returns the smallest element int1
.
ii.
- Question: Predict the output:
T1 = (6, 7)
T2 = T1 * 3
T3 = T2 * (3) # Note: parentheses are crucial here!
print(T1, T2, T3)
- Answer:
(6, 7) (6, 7, 6, 7, 6, 7) (6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7)
- Explanation:
T1 * 3
creates a new tuple by repeatingT1
three times.T2 * (3)
also repeatsT2
three times. If you wroteT2 * 3
without the parentheses, you’d get the same result because the * operator has higher precedence than the comma in tuple creation.
3. e) Nested Tuple and Conditional Display
- Question: Given the nested tuple
stud = (("Anish", 67.8), ("shourya", 90.7), ("Rehan", 77.5), ("Bidisha", 78.6), ("Manay", 66))
, write a program that displays the names of students along with their percentages if their percentage is greater than or equal to 75. - Answer:
stud = (("Anish", 67.8), ("shourya", 90.7), ("Rehan", 77.5), ("Bidisha", 78.6), ("Manay", 66))
for name, percentage in stud:
if percentage >= 75:
print(f"{name}: {percentage}%")
OR (Checking Ascending Order in First Half)
- Question: Write a program to check if the elements in the first half of a tuple are in ascending order. If not, then report with a suitable message. Eg.
T = [11, 12, 13, 45, 10, 56, 1, 24]
- Answer:
def check_ascending_half(tup):
half_len = len(tup) // 2
first_half = tup[:half_len]
for i in range(half_len - 1):
if first_half[i] > first_half[i + 1]:
print("Tuple does not have first half elements in ascending order")
return
print("Tuple has first half elements in ascending order")
T = (11, 12, 13, 45, 10, 56, 1, 24) # Note: It's a tuple now
check_ascending_half(T) # Output: Tuple does not have first half elements in ascending order
T = (1, 2, 3, 4, 10, 56, 1, 24)
check_ascending_half(T) # Output: Tuple has first half elements in ascending order
4. a) Dictionary Methods: get()
and update()
-
Question: Explain the use of
get()
andupdate()
used in dictionaries with suitable examples. (2+2 marks) -
Answer:
-
get(key, default)
: Retrieves the value associated with a specifiedkey
. If thekey
is not found, it returns thedefault
value (if provided) orNone
. This preventsKeyError
exceptions.Python
my_dict = {"a": 1, "b": 2} value = my_dict.get("a") # Returns 1 value = my_dict.get("c", 0) # Returns 0 (default value) value = my_dict.get("c") # Returns None
-
update(other_dict)
: Adds or updates key-value pairs fromother_dict
into the original dictionary. If akey
already exists, its value is updated; otherwise, the newkey-value
pair is added.Python
my_dict = {"a": 1, "b": 2} other_dict = {"b": 3, "c": 4} my_dict.update(other_dict) # my_dict becomes {"a": 1, "b": 3, "c": 4} my_dict.update({"d":5}) # my_dict becomes {"a": 1, "b": 3, "c": 4, "d": 5}
-
4. b) Predicting Dictionary Output
i.
- Question: Predict the output:
Python
d1 = {5: "number", "a": "string", (1, 2): 'tuple'}
print("Dictionary contents")
for x in d1.keys():
print(x, ",", d1[x], end=" ")
print(d1[x] * 3)
print()
- Answer:
Dictionary contents
5 , number numbernumbernumber
a , string stringstringstringstringstring
(1, 2) , tuple tupletupletupletupletupletuple
- Explanation: The code iterates through the keys of the dictionary
d1
. For each key, it prints the key, a comma, the corresponding value, and then the value repeated three times.
ii.
- Question: Predict the output:
Python
num = {33: 455, 23: 670, 13: 500, 3: 311}
s = len(num)
for i in range(s):
x = num.popitem()
if len(num) > 0:
print("Key-value pair", x)
print("Now dictionary size is", len(num))
- Answer:
Key-value pair (3, 311)
Now dictionary size is 3
Key-value pair (13, 500)
Now dictionary size is 2
Key-value pair (23, 670)
Now dictionary size is 1
- Explanation:
popitem()
removes and returns an arbitrary key-value pair from the dictionary. The loop continues as long as the dictionary is not empty.
4. c) Letter Frequency Dictionary
-
Question: Write a program to read a sentence and then create a dictionary containing the frequency of letters in the sentence. Ignore other symbols. Eg. S = “This is sentence” Output: {“T”: 1, “h”: 1, “i”: 3, “s”: 3, “e”: 3, “n”: 2, “c”: 1}
-
Answer:
Python
def letter_frequency(sentence):
freq_dict = {}
for char in sentence.lower(): # Convert to lowercase to count 'T' and 't' together
if 'a' <= char <= 'z': # Check if it's a letter
freq_dict[char] = freq_dict.get(char, 0) + 1
return freq_dict
S = "This is sentence"
result = letter_frequency(S)
print(result)
OR (Overlapping Keys)
-
Question: Given two dictionaries D1 and D2. Write a program that lists the overlapping keys of the two dictionaries, i.e., if a key of D1 is also a key of D2, then
1 print the list; otherwise, display a suitable message. -
Answer:
Python
def overlapping_keys(d1, d2):
common_keys = list(d1.keys() & d2.keys()) # Use set intersection to find common keys
if common_keys:
print("Overlapping keys:", common_keys)
else:
print("No overlapping keys found.")
D1 = {"a": 1, "b": 2, "c": 3}
D2 = {"b": 4, "d": 5, "a": 6}
overlapping_keys(D1, D2) # Output: Overlapping keys: ['b', 'a']
D3 = {"a": 1, "b": 2}
D4 = {"c": 3, "d": 4}
overlapping_keys(D3, D4) # Output: No overlapping keys found.
4. d) Students’ Age Dictionary
-
Question: Assign a dictionary with the name and age of any 10 students in the program itself and then print the names of students along with their ages whose age is more than 15 years.
-
Answer:
Python
students = {
"Alice": 16,
"Bob": 14,
"Charlie": 17,
"David": 15,
"Eve": 18,
"Frank": 13,
"Grace": 16,
"Henry": 17,
"Ivy": 15,
"Jack": 19
}
for name, age in students.items():
if age > 15:
print(f"{name}: {age}")
5. a) Insertion Sort
-
Question: What will the following list look like after 2 passes of the insertion sort algorithm (ascending order)? Show the list after every pass. M = [16, 19, 11, 15, 10]
-
Answer:
Initial List: M = [16, 19, 11, 15, 10]
Pass 1:
- Compare 19 with 16. 19 is greater, so no swap.
- List after Pass 1: [16, 19, 11, 15, 10]
Pass 2:
- Compare 11 with 19. 11 is smaller, so swap. [16, 11, 19, 15, 10]
- Compare 11 with 16. 11 is smaller, so swap. [11, 16, 19, 15, 10]
- List after Pass 2: [11, 16, 19, 15, 10]
OR (Bubble Sort)
-
Question: Write a program to illustrate Bubble Sort.
-
Answer:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Swap
return arr
# Example
data = [5, 1, 4, 2, 8]
sorted_data = bubble_sort(data)
print("Sorted array:", sorted_data) # Output: Sorted array: [1, 2, 4, 5, 8]
5. b) Sorting Strings by Length
-
Question: Write a program to sort a list of strings based on the length of the strings. That is, the smallest-length string should be the first string and the largest length string the last. Eg: Original List: [‘HELLO’, ‘HI’, ‘HOLA’, ‘Namastey’, ‘Hi!’] Sorted List: [‘Hi’, ‘HI!’, ‘HOLA’, ‘HELLO’, ‘Namastey’]
-
Answer:
def sort_strings_by_length(string_list):
return sorted(string_list, key=len)
# Example
original_list = ['HELLO', 'HI', 'HOLA', 'Namastey', 'Hi!']
sorted_list = sort_strings_by_length(original_list)
print("Sorted List", sorted_list) # Output: Sorted List ['Hi', 'Hi!', 'HOLA', 'HELLO', 'Namastey']
Explanation:
- The
sorted()
function is used with akey
argument. - The
key=len
specifies that the sorting should be based on the length of each string. sorted()
returns a new sorted list, leaving the original list unchanged.