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

Upst24105 - Problem Solving and Python Programming

The document provides an answer key for a Problem Solving and Python Programming course, covering various topics such as pseudo code, iteration, comments, operators, data types, algorithms, and programming examples. It includes detailed explanations and pseudo code for algorithms like finding averages, minimum values, factorials, and Armstrong numbers, as well as examples of linear and binary search. Additionally, it discusses lists and dictionaries in Python, including their creation, access, modification, and operations.

Uploaded by

Yoga Priya
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 views10 pages

Upst24105 - Problem Solving and Python Programming

The document provides an answer key for a Problem Solving and Python Programming course, covering various topics such as pseudo code, iteration, comments, operators, data types, algorithms, and programming examples. It includes detailed explanations and pseudo code for algorithms like finding averages, minimum values, factorials, and Armstrong numbers, as well as examples of linear and binary search. Additionally, it discusses lists and dictionaries in Python, including their creation, access, modification, and operations.

Uploaded by

Yoga Priya
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/ 10

THE KAVERY ENGINEERING COLLEGE

(AN AUTONOMOUS INSTITUTUTION)

UPST24105 - PROBLEM SOLVING AND PYTHON PROGRAMMING


ANSWER KEY
Part A
1. Characteristics of pseudo code: (2 marks)
• Can be done easily on a word processor
• Easily modified
• Implements structured concepts well
• It can be written easily
• It can be read and understood easily
• Converting pseudo code to programming language is easy as compared with flowchart .
2. Iteration: (2 marks)
Iteration involves repeatedly executing a set of instructions.
Recursion:
Recursion involves a function calling itself repeatedly.
3. Single line comment: (2 marks)
# - for single line comment
Multiline comment:
‘ ‘ and “ “ - for multiline comment.
4. Operators: (2 marks)
 Arithmetic operator
 Comparison
 Logical
 Assignment
 Bitwise
5. Fruitful function: (2 marks)
A fruitful function is a function that returns a value in other words, it produces a result that
can be used by the caller.
6. (2 marks)
num = float(input("Enter a number: "))
result = find_square_root(num)
print(f "The square root of {num} is
{result:.2f}")
7. (2 marks)
Mutable data type:
Mutable data type can be changed after creation.
Immutable Data type:
Immutable data types are cannot be changed after creation.
8. (2 marks)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result) # [1, 2, 3, 4, 5, 6]
9. (2 marks)
Define is a not a valid python keyword. It should be “def” to define a function.
10. (2 marks)
Buffering is a process of temporarily storing data in a memory area, called a buffer.
Part B
11 (a) i Algorithm to Find the Average of a List of Numbers (4 marks)
i Step 1: Start
i Step 2: Initialize sum to 0
i Step 3: Initialize count to 0
Step 4: FOR each number in the list
- Add the number to sum
- Increment count by 1
Step 5: IF count is greater than 0
- Calculate average as sum / count
Step 6: ELSE
- Set average to 0
Step 7: Display average
Step 8: Stop.

Pseudo code: (4 marks)


START
sum ← 0
count ← 0
FOR each number in list
sum ← sum + number
count ← count + 1
ENDFOR
IF count > 0 THEN
average ← sum / count
ELSE
average ← 0
ENDIF
DISPLAY average
STOP

11 a)ii Algorithm: (4 marks)


Step 1: Start
Step 2: IF the list is empty
- Display "List is empty"
- Stop
Step 3: Initialize min to the first element of the list
Step 4: FOR each number in the list starting from the second element
- IF the number is less than min
- Set min to the number
Step 5: Display min
Step 6: Stop

Pseudo code: (4 marks)


START
IF list is empty THEN
DISPLAY "List is empty"
STOP
ENDIF

min ← list[0]

FOR each number in list starting from index 1


IF number < min THEN
min ← number
ENDIF
ENDFOR

DISPLAY min
STOP
11 b(i) Algorithm to Compute the Factorial of a Given Number (2 marks)
Step 1: Start
Step 2: Read the value of n
Step 3: Initialize factorial = 1
Step 4: IF n is 0 or 1, then
- Set factorial = 1
- Display factorial and Stop
Step 5: FOR i from 2 to n
- Multiply factorial by i
Step 6: Display factorial
Step 7: Stop
Pseudocode (2 marks)
START
READ n
factorial ← 1

IF n = 0 OR n = 1 THEN
DISPLAY 1
STOP
ENDIF

FOR i ← 2 TO n DO
factorial ← factorial * i
ENDFOR

DISPLAY factorial
STOP
Flow Chart: (4 marks)

11 b(ii) Algorithm Find_Sum_Upto_100 (4 marks)


Input: N = 100
Output: sum (the sum of all integers from 1 to N)
Begin
sum ← 0 // Initialize sum to 0
For i ← 1 to N // Loop from 1 to N (100)
sum ← sum + i // Add current number to sum
End For
Return sum // Return the final sum
End
Pseudo Code: (4 marks)
Input: N (an integer)
Output: sum (the sum of all integers from 1 to N)
Begin
sum ← 0 // Initialize sum to 0
For i ← 1 to N // Loop from 1 to N
sum ← sum + i // Add current number to sum
End For
Return sum // Return the final sum
End
12 a(i) Types of operators: (Explain each one) (8 marks)

1. Arithmetic Operators: Perform mathematical operations.


+, -, , /, //, %, *
Example: 5 + 3 = 8

2. Comparison Operators: Compare values.


==, !=, >, <, >=, <=
Example: 5 > 3 → True

3. Logical Operators: Combine conditional statements.


and, or, not
Example: (5 > 3) and (3 > 1) → True

4. Assignment Operators: Assign values to variables.


=, +=, -=, =, /=, //=, %=, *=
Example: a += 3 → a = a + 3

5. Membership Operators: Test if a value exists in a sequence.


in, not in
Example: 'a' in 'apple' → True

6. Identity Operators: Compare memory location of objects.


is, is not
Example: a is b → False

7. Bitwise Operators: Perform bit-level operations.


&, |, ^, ~, <<, >>
Example: 5 & 3 → 1

12 a Program to Exchange the value of two variables: (8 marks)


(ii)
a=5
b = 10

# Print original values


print("Before swapping:")
print("a =", a)
print("b =", b)

# Swap the values using a temporary variable


temp = a
a=b
b = temp

12 b(i) Constant: (2 marks)


In python a constant is a variable that is intended to have a fixed value throughout
the execution of a program.
Variable: (2 marks)
A variable is a symbolic name that is used to reference or store a value in memory.
Expression: (2 marks)

Expression is a combination of variables, constants and operators.


Statements: (2 marks)

Statement is a unit of code that performs an action.


12 b (5 marks)
(ii) Write a program to find whether a given number is Amstrong number or not:
def is_armstrong_number(num):
# Convert the number to string to easily get the number of digits
digits = str(num)
num_digits = len(digits)

# Sum of digits raised to the power of the number of digits


sum_of_powers = sum(int(digit) ** num_digits for digit in digits)

# Check if the sum is equal to the original number


return sum_of_powers == num

# Input from the user


num = int(input("Enter a number: "))

# Check if the number is an Armstrong number


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

Output: (3 marks)
Enter a number: 153
153 is an Armstrong number.
13 a
Write a program that prints all numbers from 1 to 10. (16 marks)
for num in range(1, 11):
print(num) # Print the current number
if num == 5:
break # Stop the loop when the number 5 is reached
Output:
1
2
3
4
5
(5 marks)
b Linear Search:
def linear_search(lst, target):
for index, value in enumerate(lst):
if value == target:
return index # Return the index where the target is found
return -1 # Return -1 if target is not found
# Test the linear search method
lst = [21, 34, 56, 31, 18, 23, 38]
target = 31
result_linear = linear_search(lst, target)
print(f "Linear Search: Target {target} found at index {result_linear}")
Output: (3 marks)
Linear Search: Target 31 found at index 3
Binary Search: (5 marks)
def binary_search(lst, target):
lst.sort() # Sort the list first
low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == target:
return mid # Return the index where the target is found
elif lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1 # Return -1 if target is not found
# Test the binary search method
lst = [21, 34, 56, 31, 18, 23, 38]
target = 31
result_binary = binary_search(lst, target)
print(f"Binary Search: Target {target} found at index {result_binary}")

Output: (3 marks)
Target 31 found at index 3
14 a 1.Creating List: (4 marks)
A list in Python is created by enclosing elements in square brackets []. Elements in the list are
separated by commas.
Syntax:
list_name = [element1, element2, element3, ...]
Example:
my_list = [10, 20, 30, 40, 50]

2.Accessing the List: (4 marks)


You can access elements in a list by using their index. Indexing in Python starts
from 0, meaning the first element has an index of 0, the second element has an index
of 1, and so on.
Syntax:
list_name[index]
Example:
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Access the first element: Output = 10
print(my_list[-1]) # Access the last element: Output = 50

3.Deleting the List: (4 marks)


To delete a list entirely or remove elements from a list, you can use the following
methods:

Deleting the Entire List:


The del keyword can be used to delete the entire list.
Example:
my_list = [10, 20, 30, 40]
del my_list # Deletes the entire list

4. Updating the List: (4 marks)


To update an element in a list, you can simply assign a new value to an existing
index.
Syntax:
list_name[index] = new_value
Example:
my_list = [10, 20, 30, 40]
my_list[1] = 25 # Updates the element at index 1 to 25
print(my_list) # Output: [10, 25, 30, 40]
14 b
Dictionaries in Python: (2 marks)
A dictionary in Python is an unordered collection of data that is stored as key-value pairs.

Syntax: (4 marks)
my_dict = {key1: value1, key2: value2, key3: value3}

Key: The unique identifier for each value (e.g., a string, number, or tuple).

Value: The associated data (e.g., any data type, including lists or other dictionaries).

Operations on Dictionaries: (Explain each one) (Each one 2 marks)

1. Creating a Dictionary

You can create a dictionary using curly braces {} with key-value pairs.

# Example of creating a dictionary

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

2. Accessing Values in a Dictionary

You can access the value associated with a key by using the key inside square brackets [].

print(my_dict["name"])

Output:

Alice

3. Modifying or Updating Dictionary Values

You can modify the value of an existing key by assigning a new value to the key.

my_dict["age"] = 26

print(my_dict)

Output:

{"name": "Alice", "age": 26, "city": "New York"}

You can also use the update() method to add multiple key-value pairs or modify existing ones.

my_dict.update({"city": "Los Angeles", "salary": 50000})

print(my_dict)
Output:

{"name": "Alice", "age": 26, "city": "Los Angeles", "salary": 50000}

4. Adding New Key-Value Pairs

You can add new key-value pairs by assigning a value to a new key.

my_dict["email"] = "[email protected]"

print(my_dict)

Output:

{"name": "Alice", "age": 26, "city": "Los Angeles", "salary": 50000, "email":
"[email protected]"}

5. Removing Key-Value Pairs

You can remove a key-value pair using the del statement or the pop() method.

Using del:

del my_dict["salary"] # Removes the key "salary"


print(my_dict)
Output:
{"name": "Alice", "age": 26, "city": "Los Angeles", "email": "[email protected]"}
15 a 1. Here’s a Python function that reads a file, evaluates the number of words and vowels in
it, and displays the results:
2.
3. Steps: (6 marks)
4.
5. 1. Open the file in read mode.
6.
7.
8. 2. Read the contents of the file.
9.
10.
11. 3. Count the number of words in the file.
12.
13.
14. 4. Count the number of vowels in the file.
15.
16.
17. 5. Print the results.
18.
Displays number of words and vowels in that file: (10 marks)
19.
20. def count_words_and_vowels(file_path):
21. try:
22. # Open the file and read its contents
23. with open(file_path, 'r') as file:
24. content = file.read()
25.
26. # Initialize word and vowel counts
27. word_count = 0
28. vowel_count = 0
29. vowels = "aeiouAEIOU"
30.
31. # Count the number of vowels in the content
32. for char in content:
33. if char in vowels:
34. vowel_count += 1
35.
36. # Display the results
37. print(f "Number of words: {word_count}")
38. print(f "Number of vowels: {vowel_count}")
39.
15 b 40. Python program that prompts the user for input, validates the input to ensure it is within
the range of 0 to 100, and raises an exception if the input is invalid. If an invalid input is entered,
it prompts the user to re-enter the marks.
41. (16 marks)
42. def get_valid_marks():
43. while True:
44. try:
45. # Prompt user for marks input
46. marks = float(input("Please enter your marks (0 to 100): "))
47.
48. # Check if the marks are within the valid range
49. if marks < 0 or marks > 100:
50. raise ValueError("Marks should be between 0 and 100.")
51.
52. # If marks are valid, return the value
53. return marks
54.
55. except ValueError as e:
56. # If there's an error (invalid input or out of range), print the error and ask for re-
entry
57. print(f "Invalid input: {e}")
58. print("Please try again.")
59.
60. # Example usage
61. marks = get_valid_marks()
62. print(f "Valid marks entered: {marks}")
63.
64. Example Interaction:
65.
66. Please enter your marks (0 to 100): 105
67. Invalid input: Marks should be between 0 and 100.
68. Please try again.
69.
70. Please enter your marks (0 to 100): -3
71. Invalid input: Marks should be between 0 and 100.
72. Please try again.
73.
74. Please enter your marks (0 to 100): 75
75. Valid marks entered: 75.0

You might also like