You are on page 1of 29

33.What are the different function prototypes?

Explain it with a suitable example

In programming, a function prototype declares the function's name, return type, and parameter types
without implementing the actual function. The purpose of a function prototype is to inform the compiler
about the function's existence and its signature before it is used in the program. This allows the compiler
to perform type checking and ensure correct usage of the function throughout the code. Here are
different types of function prototypes along with examples:

1. Function with no parameters:

int getRandomNumber();

This prototype declares a function named `getRandomNumber` that returns an integer. It does not take
any parameters. The actual implementation of the function should be defined elsewhere in the code.

2. Function with parameters:

void greetUser(char name[]);

This prototype declares a function named `greetUser` that does not return a value (`void`). It takes a
single parameter, `name`, which is an array of characters. The actual implementation of the function
should accept a character array and perform some greeting operation.

3. Function with multiple parameters:

float calculateAverage(float num1, float num2, float num3);

This prototype declares a function named `calculateAverage` that returns a float value. It takes three
parameters: `num1`, `num2`, and `num3`, all of which are floating-point numbers. The actual
implementation of the function should accept three float arguments and calculate the average of those
numbers.

4. Function with a pointer parameter:

void swapValues(int* a, int* b);

This prototype declares a function named `swapValues` that does not return a value (`void`). It takes two
parameters, `a` and `b`, which are pointers to integers. The function's implementation should swap the
values of the integers pointed to by `a` and `b`.

5. Function with a variable number of arguments:

int sumNumbers(int count, ...);

This prototype declares a function named `sumNumbers` that returns an integer. It takes a variable
number of arguments using the ellipsis (`...`) notation. The function's implementation can access these
arguments using special macros like `va_start`, `va_arg`, and `va_end`. This allows the function to accept
a different number of arguments each time it is called.

These examples illustrate different types of function prototypes with varying return types, parameter
types, and the presence or absence of parameters. Function prototypes play a crucial role in defining the
functions' interface and ensuring proper program usage.

34. Explain Various String functions used in Python.

In Python, there are several built-in string functions that allow you to perform various operations on
strings. Here are some commonly used string functions in Python:

1. len():

The `len()` function returns a string's length (number of characters).

string = "Hello, World!"

length = len(string)

print(length) # Output: 13

2. lower() and upper():

The `lower()` function converts all characters in a string to lowercase, while the `upper()` function
converts them to uppercase.

string = "Hello, World!"

lowercase = string.lower()

uppercase = string.upper()

print(lowercase) # Output: hello, world!

print(uppercase) # Output: HELLO, WORLD!

3. strip():

The `strip()` function removes leading and trailing whitespace (including newlines) from a string.

string = " Hello, World! "

stripped = string.strip()

print(stripped) # Output: Hello, World!

4. split():

The `split()` function splits a string into a list of substrings based on a specified delimiter (by default,
whitespace).

string = "Hello, World!"

words = string.split(",")

print(words) # Output: ['Hello', ' World!']

5. join():

The `join()` function concatenates elements of an iterable (such as a list) into a single string, using a
specified separator.

words = ['Hello', 'World!']

string = ",".join(words)

print(string) # Output: Hello,World!

6. replace():

The `replace()` function replaces all occurrences of a substring within a string with another substring.

string = "Hello, World!"

new_string = string.replace("World", "Python")

print(new_string) # Output: Hello, Python!

7. find() and index():

The `find()` and `index()` functions search for a substring within a string and return the index of its first
occurrence. The difference is that `find()` returns -1 if the substring is not found, while `index()` raises a
ValueError.

string = "Hello, World!"

index = string.find("World")

print(index) # Output: 7

index = string.index("World")

print(index) # Output: 7

8. count():

The `count()` function counts the number of occurrences of a substring within a string.

string = "Hello, World!"


count = string.count("o")

print(count) # Output: 2

concatenation,repetition,slicing..

These are just a few examples of the string functions available in Python. Python provides a rich set of
string manipulation functions that can be used to perform various operations on strings efficiently.

35.i)Discuss the need and importance of function in python.

Functions play a crucial role in Python programming, offering several benefits and serving multiple
purposes. Here are some key points highlighting the need and importance of functions in Python:

1. Code Reusability: Functions allow you to define a block of reusable code that can be called multiple
times from different parts of the program. This promotes code reusability, reducing redundancy and
making the code more manageable and maintainable. By encapsulating specific functionality within
functions, you can easily reuse and share that code across different projects or within the same project.

2. Modularity and Readability: Functions enhance the modularity and readability of your code. By
breaking down complex tasks into smaller, self-contained functions, you can improve code organization
and structure. Each function focuses on a specific task, making it easier to understand, test, and debug.
Additionally, well-named functions provide a higher level of abstraction, making the code more readable
and easier to comprehend.

3. Abstraction and Encapsulation: Functions allow you to abstract away the implementation details and
provide a higher-level interface for interacting with your code. This abstraction hides the internal
complexity of the function, enabling other parts of the program to use it without needing to know the
underlying implementation. By encapsulating related code within a function, you can isolate it from the
rest of the program, promoting modularity and reducing potential conflicts or dependencies.

4. Code Organization and Maintainability: Functions help in organizing your code into logical units,
promoting a modular and structured approach. Dividing a large program into smaller functions makes it
more manageable and maintainable, as you can focus on one function at a time, understand its purpose,
and modify it without affecting other parts of the code. This modular structure simplifies debugging,
testing, and maintenance tasks.

5. Code Readability and Documentation: Functions enhance code readability by providing meaningful
names to encapsulated blocks of code. Well-written functions with descriptive names make it easier for
others (including yourself) to understand the purpose and functionality of specific code segments.
Functions also allow you to add documentation in the form of docstrings, which provide detailed
explanations of the function's purpose, parameters, return values, and usage. This documentation
improves code understandability and serves as a reference for future development or collaboration.

6. Code Efficiency and DRY Principle: Functions promote the Don't Repeat Yourself (DRY) principle,
which encourages code efficiency and reduces redundancy. Instead of duplicating the same code in
multiple places, you can define a function and call it whenever needed. This saves development time,
minimizes the chances of introducing bugs, and allows for easy updates or modifications by changing the
function definition in a single place.

7. Code Testing and Debugging: Functions facilitate unit testing and debugging by isolating specific
blocks of code. With functions, you can write test cases to verify the correctness of individual functions
independently, ensuring their behavior matches the expected results. Debugging becomes more
manageable, as you can narrow down issues to specific functions, examine their inputs and outputs, and
identify and fix any problems.

In summary, functions in Python provide code reusability, modularity, readability, encapsulation,


abstraction, and improved code organization and maintainability. They contribute to efficient and
structured development, promote the DRY principle, and facilitate testing and debugging. Functions are
a fundamental building block in Python programming and are essential for creating scalable,
maintainable, and robust applications.

35.ii)Illustrate a program to exchange the value of two variables with temporary variables.

Certainly! Here's a Python program that exchanges the values of two variables using temporary
variables:

# Function to exchange the values of two variables

def exchange_values(a, b):

temp = a

a=b

b = temp

return a, b

# Main program

if __name__ == "__main__":

# Initial values

num1 = 10

num2 = 20

# Displaying initial values

print("Before exchanging:")
print("num1 =", num1)

print("num2 =", num2)

# Exchanging values using the function

num1, num2 = exchange_values(num1, num2)

# Displaying exchanged values

print("\nAfter exchanging:")

print("num1 =", num1)

print("num2 =", num2)

Output:

Before exchanging:

num1 = 10

num2 = 20

After exchanging:

num1 = 20

num2 = 10

In the above program, the `exchange_values` function takes two variables (`a` and `b`) as input. Inside
the function, the value of `a` is stored in a temporary variable `temp`, `a` is assigned the value of `b`, and
`b` is assigned the value of `temp`. Finally, the function returns the updated values of `a` and `b`.

In the main program, two variables `num1` and `num2` are initialized with values 10 and 20, respectively.
The initial values are displayed. Then, the `exchange_values` function is called with `num1` and `num2`
as arguments. The returned values are assigned back to `num1` and `num2`. Finally, the exchanged
values are displayed.

36.Briefly discuss in detail about function prototyping in python. With suitable example program

In Python, function prototyping is not explicitly required or supported like in some other programming
languages. Python uses a dynamic typing system, which means you can define a function without
explicitly declaring its parameter types or return type in advance.

In Python, you can define a function and start using it immediately without any separate prototype
declaration. The function's signature, including parameter names and their order, is defined in the
function definition itself.
Here's an example program to illustrate function prototyping in Python:

# Function to calculate the sum of two numbers

def calculate_sum(a, b):

return a + b

# Main program

if __name__ == "__main__":

# Calling the function with integer arguments

result1 = calculate_sum(5, 10)

print("Sum of 5 and 10 is:", result1)

# Calling the function with floating-point arguments

result2 = calculate_sum(3.14, 2.71)

print("Sum of 3.14 and 2.71 is:", result2)

# Calling the function with string arguments

result3 = calculate_sum("Hello, ", "World!")

print("Concatenated string is:", result3)

Output:

Sum of 5 and 10 is: 15

Sum of 3.14 and 2.71 is: 5.85

Concatenated string is: Hello, World!

In the above program, the `calculate_sum` function takes two parameters `a` and `b` and returns their
sum. The function is defined without any specific type declarations for the parameters. This allows the
function to accept different types of arguments, such as integers, floating-point numbers, or strings.

In the main program, the `calculate_sum` function is called multiple times with different types of
arguments. The function handles each call and performs the appropriate operation based on the
argument types. This flexibility is possible due to Python's dynamic typing system, which allows functions
to accept arguments of different types without the need for explicit prototyping.

37.i) Analyze the difference between local and global variables.


ii) Explain with an example program to circulate the values of n variables.

i) Difference between local and global variables:

Local variables:

- Local variables are defined within a specific function or block.

- They have limited scope and can only be accessed within the function or block in which they are
defined.

- Local variables are created when a function is called and destroyed when the function finishes its
execution.

- Each function call creates a separate instance of local variables, and changes to these variables do not
affect other instances or global variables.

- Local variables can have the same name as global variables, but they will be treated as separate
variables within the function or block.

Global variables:

- Global variables are defined outside of any function or block.

- They have a global scope and can be accessed from any part of the program.

- Global variables are created when the program starts and exist throughout the program's execution.

- Changes to global variables are visible and affect all parts of the program.

- Global variables can be accessed and modified within functions, but to modify a global variable from
within a function, it must be explicitly declared as a global variable using the `global` keyword.

ii) Example program to circulate the values of n variables:

def circulate_values(*args):

first_value = args[0]

for i in range(len(args) - 1):

args[i] = args[i + 1]

args[-1] = first_value

# Main program

if __name__ == "__main__":
a=1

b=2

c=3

d=4

print("Original values: a =", a, "b =", b, "c =", c, "d =", d)

circulate_values(a, b, c, d)

print("Circulated values: a =", a, "b =", b, "c =", c, "d =", d)

Output:

Original values: a = 1 b = 2 c = 3 d = 4

Circulated values: a = 2 b = 3 c = 4 d = 1

In the above program, the `circulate_values` function takes multiple arguments using the `*args` syntax,
which allows passing a variable number of arguments. It assumes that at least one argument is passed.

Inside the function, the first value is stored in a local variable `first_value`. Then, using a loop, each
argument is assigned the value of the next argument in a cyclic manner. Finally, the `first_value` is
assigned to the last argument, completing the circular circulation of values.

In the main program, four variables `a`, `b`, `c`, and `d` are defined with initial values. The original values
are printed, and then the `circulate_values` function is called with these variables as arguments. After
the function call, the circulated values are printed, demonstrating the circular circulation of values
among the variables.

38 .Discuss Function arguments in Python

In Python, function arguments allow you to pass data to a function for processing. There are different
types of function arguments that you can use depending on your requirements. Here are the commonly
used types of function arguments in Python:

1. Positional Arguments:

- Positional arguments are passed to a function in the order they are defined.

- The number of arguments and their positions must match between the function definition and the
function call.

- The values are assigned to the corresponding parameter names in the function definition.

- Example:
def greet(name, message):

print(f"Hello, {name}! {message}")

greet("John", "How are you?") # Output: Hello, John! How are you?

2. Keyword Arguments:

- Keyword arguments are passed with parameter names explicitly specified during the function call.

- The order of keyword arguments does not matter.

- You can mix positional and keyword arguments in a function call.

- Example:

def greet(name, message):

print(f"Hello, {name}! {message}")

greet(message="How are you?", name="John") # Output: Hello, John! How are you?

3. Default Arguments:

- Default arguments have a predefined value assigned to them in the function definition.

- If a value is not provided for a default argument during the function call, the default value is used.

- Default arguments are useful when you want a parameter to have a commonly used value unless
specified otherwise.

- Example:

def greet(name, message="How are you?"):

print(f"Hello, {name}! {message}")

greet("John") # Output: Hello, John! How are you?

greet("Jane", "Nice to meet you!") # Output: Hello, Jane! Nice to meet you!

4. Variable-length Arguments:

- Variable-length arguments allow a function to accept a variable number of arguments.

- There are two types of variable-length arguments: `*args` and `**kwargs`.

- `*args` allows passing a variable number of positional arguments to a function as a tuple.

- `**kwargs` allows passing a variable number of keyword arguments to a function as a dictionary.


- Example:

def greet(*names):

for name in names:

print(f"Hello, {name}!")

greet("John", "Jane", "Alice") # Output: Hello, John! Hello, Jane! Hello, Alice!

def print_info(**details):

for key, value in details.items():

print(f"{key}: {value}")

print_info(name="John", age=25, city="New York")

# Output:

# name: John

# age: 25

# city: New York

Function arguments in Python provide flexibility in passing data to functions, allowing you to create
more dynamic and reusable code. Choose the appropriate type of argument based on the specific
requirements of your function.

39. Write a Python program to compute the factorial of a given number using recursion

Python program that computes the factorial of a given number using recursion:

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

# Test the factorial function

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

result = factorial(number)
print(f"The factorial of {number} is {result}")

In this program, we define a recursive function called `factorial` that takes a number `n` as an argument.
The base case is when `n` is equal to 0, in which case we return 1 since the factorial of 0 is defined as 1.
For any other positive number, we calculate the factorial by multiplying `n` with the factorial of `n-1`.
This process continues until we reach the base case.

We then prompt the user to enter a number, compute its factorial using the `factorial` function, and
print the result.

40.i) Describe in detail about lambda functions or anonymous function.

ii) Describe in detail about the rules to be followed while using Lambda function

i) Lambda functions, also known as anonymous functions, are small and anonymous functions in Python
that are defined without a name. They are useful when you need to create a function quickly without
the need for a formal function definition. Lambda functions can take any number of arguments but can
only have one expression.

The syntax of a lambda function is as follows:

lambda arguments: expression

Lambda functions are typically used when you need a simple function that is used only once and doesn't
require a separate function definition. They are commonly used in combination with built-in functions
like `map()`, `filter()`, and `reduce()`, where a small function is required as an argument.

Here's an example that demonstrates the usage of a lambda function:

# Example 1: Adding two numbers using a lambda function

add = lambda x, y: x + y

result = add(5, 3)

print(result) # Output: 8

# Example 2: Using a lambda function with map()

numbers = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x**2, numbers))

print(squared) # Output: [1, 4, 9, 16, 25]

In the first example, a lambda function is defined to add two numbers. The lambda function takes two
arguments `x` and `y` and returns their sum. The result is obtained by calling the lambda function with
the arguments `5` and `3`.
In the second example, a lambda function is used with the `map()` function to calculate the squares of a
list of numbers. The lambda function takes a single argument `x` and returns its square. The `map()`
function applies this lambda function to each element of the `numbers` list and returns a new list
containing the squared values.

ii) While using lambda functions in Python, there are a few rules to follow:

1. Lambda functions can take any number of arguments but can only have one expression.

2. The lambda function syntax consists of the `lambda` keyword, followed by a comma-separated list of
arguments (if any), a colon `:`, and the expression to be evaluated.

3. Lambda functions are often used with built-in functions like `map()`, `filter()`, and `reduce()`, or in
situations where a small function is required as an argument.

4. The result of a lambda function is the value of the evaluated expression.

5. Unlike regular functions, lambda functions do not have a return statement. The result is automatically
returned based on the expression.

6. Lambda functions can be assigned to variables, used as an argument in a function call, or defined
inline.

Here's an example that demonstrates these rules:

# Assigning a lambda function to a variable

multiply = lambda x, y: x * y

result = multiply(5, 3)

print(result) # Output: 15

# Using a lambda function as an argument in a function call

numbers = [1, 2, 3, 4, 5]

filtered = list(filter(lambda x: x % 2 == 0, numbers))

print(filtered) # Output: [2, 4]

# Defining a lambda function inline

result = (lambda x: x**2)(4)

print(result) # Output: 16

In the above examples, the lambda function follows the rules mentioned earlier. It takes the required
number of arguments, uses a single expression, and returns the evaluated result.
41.i) Explain with an example program to return the average of its argument

ii) Explain the various features of functions in python.

i) example program to calculate the average of its arguments using a function in Python:

def average(*args):

if len(args) == 0:

return 0

return sum(args) / len(args)

result = average(5, 10, 15, 20)

print(result) # Output: 12.5

In the above example, the `average()` function is defined to calculate the average of its arguments. The
function uses variable-length arguments `*args`, which allows it to accept any number of arguments. The
function checks if there are no arguments provided and returns 0 in such cases. Otherwise, it calculates
the sum of the arguments using the `sum()` function and divides it by the length of the arguments to
obtain the average. Finally, the average value is printed.

ii) Functions in Python have various features that make them powerful and flexible. Some of the key
features of functions in Python include:

1. **Reusability**: Functions allow you to define a block of code that can be reused multiple times
within a program. This helps in avoiding code repetition and promotes modular programming.

2. **Modularity**: Functions enable you to break down complex problems into smaller, manageable
parts. Each function can focus on a specific task, making the overall code more organized and easier to
understand.

3. **Code Abstraction**: Functions provide a level of abstraction by encapsulating a set of instructions


into a single entity. This allows you to hide the implementation details and focus on the functionality
provided by the function.

4. **Parameter Passing**: Functions can accept parameters or arguments, which allow you to pass
values to the function for processing. Parameters can be of different types such as required positional
arguments, default arguments, variable-length arguments, or keyword arguments.

5. **Return Values**: Functions can return values back to the caller using the `return` statement. The
return statement terminates the function execution and passes the result back to the caller. Functions
can return multiple values as tuples, and the returned values can be stored in variables or used directly.

6. **Scope**: Functions have their own scope, meaning variables defined inside a function are local to
that function and cannot be accessed outside unless specifically returned. Similarly, global variables can
be accessed within a function using the `global` keyword.

7. **Lambda Functions**: Python supports lambda functions, also known as anonymous functions,
which are small, single-line functions that don't require a formal function definition. Lambda functions
are useful for creating simple functions on the fly.

8. **Function Decorators**: Python provides the concept of function decorators, which allow you to
modify the behavior of a function without changing its source code. Decorators are functions that take
another function as input and return a modified version of it.

9. **Recursion**: Functions in Python can call themselves recursively, allowing for the implementation
of recursive algorithms. Recursion is a powerful technique for solving problems that can be naturally
divided into smaller subproblems.

These features make functions a fundamental building block in Python programming, enabling code
reusability, modularity, and abstraction, leading to more efficient and maintainable code.

42. i)Explain with an example program to pass the list arguments to a function.

ii)Write a program to perform selection sort from a list of numbers using python

i) example program that demonstrates how to pass a list as an argument to a function in Python:

def process_list(numbers):

for num in numbers:

print(num)

total = sum(numbers)

print("Sum:", total)

max_num = max(numbers)

print("Maximum:", max_num)

my_numbers = [5, 10, 15, 20, 25]

process_list(my_numbers)

In the above example, the `process_list()` function takes a list of numbers as an argument. Inside the
function, we can perform various operations on the list. In this case, the function prints the elements of
the list using a loop, calculates the sum of the numbers using the `sum()` function, and finds the
maximum number using the `max()` function. You can add any other desired operations within the
function. Finally, we create a list `my_numbers` and pass it as an argument to the `process_list()`
function.
ii) Here's a program to perform selection sort on a list of numbers using Python:

def selection_sort(numbers):

n = len(numbers)

for i in range(n):

min_idx = i

for j in range(i+1, n):

if numbers[j] < numbers[min_idx]:

min_idx = j

numbers[i], numbers[min_idx] = numbers[min_idx], numbers[i]

# Example usage:

my_numbers = [9, 5, 7, 1, 3, 2, 6, 8, 4]

selection_sort(my_numbers)

print(my_numbers)

In the above program, the `selection_sort()` function implements the selection sort algorithm. It takes a
list of numbers as an argument and sorts the list in ascending order. The outer loop iterates over the
elements of the list, and for each element, the inner loop finds the minimum element from the
remaining unsorted portion of the list. The minimum element is then swapped with the current element.
This process is repeated until the entire list is sorted.

The program demonstrates the usage of the `selection_sort()` function by creating a list of numbers
`my_numbers`. The function is called with this list as an argument, and after the function call, the sorted
list is printed using `print(my_numbers)`. The output will be the sorted list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`.

43.i) Explain the different types of the function prototype with an example(5) (K2)

ii). Examine the program on Fibonacci series(6)

i) Different Types of Function Prototypes:

1. Function Prototype with No Arguments and No Return Value:

def greet():

print("Hello, World!")

greet()
In this type of function prototype, the function `greet()` does not take any arguments and does not
return any value. It simply prints a greeting message.

2. Function Prototype with Arguments and No Return Value:

def add_numbers(a, b):

sum = a + b

print("Sum:", sum)

add_numbers(10, 20)

Here, the function `add_numbers()` takes two arguments `a` and `b`, calculates their sum, and prints the
result. The function does not return any value.

3. Function Prototype with Arguments and Return Value:

def multiply(a, b):

product = a * b

return product

result = multiply(5, 6)

print("Result:", result)

In this case, the function `multiply()` takes two arguments `a` and `b`, multiplies them, and returns the
product. The returned value is stored in the variable `result` and then printed.

4. Function Prototype with Default Arguments:

def power(base, exponent=2):

result = base ** exponent

return result

print(power(3)) # Uses default exponent value (2)

print(power(2, 3)) # Overrides default exponent value with 3

Here, the function `power()` has a default argument `exponent` set to 2. If the `exponent` value is not
provided during the function call, it uses the default value. However, you can override the default value
by providing a different `exponent` value.

5. Function Prototype with Variable Number of Arguments:


def average(*numbers):

total = sum(numbers)

avg = total / len(numbers)

return avg

print(average(10, 20, 30)) # Calculates average of 3 numbers

print(average(5, 7, 8, 2, 4)) # Calculates average of 5 numbers

In this case, the function `average()` accepts a variable number of arguments using the `*` operator. It
calculates the average of all the passed numbers by summing them and dividing by the count of
numbers.

ii) Program for Fibonacci Series:

Here's a Python program to generate the Fibonacci series up to a given number:

def fibonacci_series(n):

fib_list = [0, 1] # Initialize the list with first two numbers

while len(fib_list) < n:

next_num = fib_list[-1] + fib_list[-2] # Calculate the next Fibonacci number

fib_list.append(next_num) # Add the number to the list

return fib_list

limit = int(input("Enter the limit for Fibonacci series: "))

fibonacci_numbers = fibonacci_series(limit)

print("Fibonacci Series:", fibonacci_numbers)

In this program, the `fibonacci_series()` function takes a number `n` as an argument and generates the
Fibonacci series up to that number. It uses a while loop to generate the series by calculating each next
Fibonacci number and appending it to the list `fib_list`. The function returns the generated Fibonacci
series.

The program prompts the user to enter a limit for the Fibonacci series, calls the `fibonacci_series()`
function with the given limit, and stores the returned series in the variable `fibonacci_numbers`. Finally,
it prints the Fibonacci series using `print("Fibonacci Series:", fibonacci_numbers)`.

44. Create a program to reverse a string without using recursion


Here's a Python program to reverse a string without using recursion:

def reverse_string(string):

reversed_string = ""

for char in string:

reversed_string = char + reversed_string

return reversed_string

input_string = input("Enter a string: ")

reversed_string = reverse_string(input_string)

print("Reversed string:", reversed_string)

In this program, the `reverse_string()` function takes a string as an argument and returns the reversed
string. It initializes an empty string `reversed_string`. Then, it iterates over each character in the input
string using a for loop. During each iteration, it concatenates the current character with the existing
reversed string, ensuring that the current character comes before the existing reversed string. Finally, it
returns the reversed string.

To use the program, you can input a string by running `input("Enter a string: ")`, and the program will
output the reversed string using `print("Reversed string:", reversed_string)`.

45.A polygon can be represented by a list of (x, y) pairs where each pair is a tuple: [ (x1, y1), (x2,
y2), (x3, y3) , ... (xn, yn)].Write aRecursive function to compute the area of a polygon. This can be
accomplished by “cutting off” a triangle, using theExploring Python– Chapter 4 - Strings, Lists and
Tuples 24 fact that a triangle withcorners (x1, y1), (x2, y2), (x3, y3) has area(x1y1 + x2y2 + x3y2 – y1x2
–y2x3 – y3x1) / 2.

Here's a recursive function in Python to compute the area of a polygon represented by a list of (x, y)
pairs:

def compute_area(polygon):

if len(polygon) < 3:

return 0

area = 0

x0, y0 = polygon[0]

for i in range(1, len(polygon) - 1):


x1, y1 = polygon[i]

x2, y2 = polygon[i + 1]

cross_product = (x1 * y2) - (x2 * y1)

area += cross_product

area = abs(area)

return area / 2

polygon = [(0, 0), (0, 4), (4, 0), (2, 2)]

area = compute_area(polygon)

print("Area of the polygon:", area)

In this program, the `compute_area()` function takes a polygon represented as a list of (x, y) pairs. It first
checks if the polygon has at least three points. If not, it returns 0 since a polygon with less than three
points cannot have an area.

Next, it initializes the `area` variable to 0 and assigns the coordinates of the first point to `(x0, y0)`. Then,
it iterates over the remaining points in the polygon using a for loop. For each iteration, it calculates the
cross product between consecutive points `(x1, y1)` and `(x2, y2)`. It accumulates the cross product
values in the `area` variable.

Finally, it takes the absolute value of the accumulated area and divides it by 2 to get the final area of the
polygon. The absolute value is taken to handle polygons with points specified in clockwise or
counterclockwise order.

In the example usage, a polygon represented by the list of points `[(0, 0), (0, 4), (4, 0), (2, 2)]` is passed to
the `compute_area()` function, and the resulting area is printed.

46. i) Define methods in a string with an example program using at least 5 methods.

ii) How to access characters of a string?

i) Methods in a string are built-in functions that can be used to perform various operations on strings.
Here's an example program that demonstrates the usage of five different string methods:

string = "Hello, World!"

1. len(): Returns the length of the string

length = len(string)

print("Length of the string:", length)


# 2. lower(): Converts the string to lowercase

lowercase = string.lower()

print("Lowercase string:", lowercase)

# 3. upper(): Converts the string to uppercase

uppercase = string.upper()

print("Uppercase string:", uppercase)

# 4. count(): Counts the occurrences of a substring within the string

count = string.count("o")

print("Occurrences of 'o' in the string:", count)

# 5. replace(): Replaces a substring with another substring

new_string = string.replace("World", "Python")

print("Updated string:", new_string)

In this example, we have a string `"Hello, World!"` that we apply different methods on:

1. `len()` method is used to determine the length of the string. It returns 13.

2. `lower()` method converts the string to lowercase. It returns `"hello, world!"`.

3. `upper()` method converts the string to uppercase. It returns `"HELLO, WORLD!"`.

4. `count()` method counts the occurrences of a substring within the string. Here, we count the
occurrences of the letter `'o'`, which returns 2.

5. `replace()` method replaces a substring with another substring. We replace the substring "World" with
"Python", resulting in the string `"Hello, Python!"`.

ii) To access individual characters of a string, you can use indexing or slicing.

- Indexing: You can access a specific character at a particular index by using square brackets `[]`. Indexing
starts from 0 for the first character.

Example:

string = "Hello"

print(string[0]) # Output: 'H'

print(string[1]) # Output: 'e'


print(string[2]) # Output: 'l'

print(string[3]) # Output: 'l'

print(string[4]) # Output: 'o'

- Slicing: You can also extract a portion of the string using slicing. Slicing is done by specifying the start
and end indices, separated by a colon `:`. The slice includes the start index and goes up to, but does not
include, the end index.

Example:

string = "Hello, World!"

print(string[7:12]) # Output: "World"

print(string[::2]) # Output: "Hlo ol!"

In the first example, we use slicing to extract the substring `"World"` from the original string.

In the second example, we use slicing with a step size of 2 (`[::2]`) to extract every second character of
the string, resulting in the string `"Hlo ol!"`.

47.Write a program to count the number of common characters in a pair of strings

Here's a program that counts the number of common characters in a pair of strings:

def count_common_characters(str1, str2):

common_count = 0

set1 = set(str1)

set2 = set(str2)

for char in set1:

if char in set2:

common_count += 1

return common_count

string1 = "hello"

string2 = "world"

result = count_common_characters(string1, string2)

print("Number of common characters:", result)


In this program, we define a function `count_common_characters` that takes two strings as input. Inside
the function, we convert both strings into sets using the `set()` function. This allows us to easily check for
common characters.

We then iterate over each character in the first string (`str1`) and check if it is present in the second
string (`str2`) by using the `in` operator. If a character is found in both strings, we increment the
`common_count` variable.

Finally, we return the `common_count` as the result.

In the example usage, we provide two strings `"hello"` and `"world"`. The program calculates the number
of common characters between these strings and prints the result, which is 3 in this case.

48.Write a Python program to count the number of vowels in a string provided by the user.(

Here's a Python program that counts the number of vowels in a string provided by the user:

def count_vowels(string):

vowels = set("aeiouAEIOU")

vowel_count = 0

for char in string:

if char in vowels:

vowel_count += 1

return vowel_count

user_input = input("Enter a string: ")

result = count_vowels(user_input)

print("Number of vowels:", result)

In this program, we define a function `count_vowels` that takes a string as input. Inside the function, we
initialize a set of vowels containing both lowercase and uppercase letters. We also initialize a counter
variable `vowel_count` to keep track of the number of vowels found.

We then iterate over each character in the input string and check if it is present in the set of vowels. If a
character is found to be a vowel, we increment the `vowel_count` variable.

After processing the entire string, we return the `vowel_count` as the result.

In the main part of the program, we use the `input()` function to get a string from the user. We then call
the `count_vowels` function with the user-provided string as an argument. Finally, we print the result,
which is the number of vowels in the string.

49.Python strings are immutable. Justify with an example program

Python strings are immutable, meaning they cannot be modified once they are created. Here's an
example program that demonstrates the immutability of strings:

def modify_string(string):

string += " World" # Attempt to modify the string by concatenating another string

return string

my_string = "Hello"

modified_string = modify_string(my_string)

print("Original string:", my_string)

print("Modified string:", modified_string)

Output:

Original string: Hello

Modified string: Hello World

In this program, we have a function `modify_string` that attempts to modify a string by concatenating
another string (" World") to it. However, when we pass the `my_string` to the function and try to modify
it inside the function, the original string remains unchanged.

This behavior occurs because strings are immutable in Python. When we perform string concatenation, it
creates a new string object instead of modifying the original string. Therefore, even though we assign the
modified string to a new variable `modified_string`, the original `my_string` remains unaffected.

This immutability property of strings ensures that they are safe from accidental modification, making
them reliable for various operations like hashing, comparison, and use as dictionary keys.

50.i) Analyze string slicing. Illustrate how it is done in python with an example

ii)Write a python code to search a string in the given list

String slicing in Python allows you to extract a portion of a string by specifying a range of indices. The
syntax for string slicing is `string[start:end:step]`, where:

- `start` is the starting index of the slice (inclusive).

- `end` is the ending index of the slice (exclusive).


- `step` is an optional parameter that specifies the increment between indices (default is 1).

Here's an example that illustrates string slicing in Python:

my_string = "Hello, World!"

substring1 = my_string[7:12]

print(substring1) # Output: World

substring2 = my_string[-6:-1]

print(substring2) # Output: World

substring3 = my_string[::2]

print(substring3) # Output: Hlo ol!

substring4 = my_string[::-1]

print(substring4) # Output: !dlroW ,olleH

In this example, we have a string `my_string` containing the phrase "Hello, World!". We use string slicing
to extract specific substrings:

1. `substring1` is obtained by slicing the original string from index 7 to 12, resulting in "World".

2. `substring2` is obtained by using negative indices to slice the string from index -6 to -1, also resulting
in "World".

3. `substring3` is obtained by using a step of 2, which extracts every second character from the string,
resulting in "Hlo ol!".

4. `substring4` is obtained by using a negative step of -1, effectively reversing the string.

String slicing provides a flexible and convenient way to extract substrings from a string based on specific
indices or patterns. It is a powerful technique that is widely used in Python for various string
manipulation tasks.

ii)Certainly! Here's an example Python code that searches for a specific string in a given list:

def search_string_in_list(string, lst):

for item in lst:

if string in item:

return True
return False

my_list = ["apple", "banana", "cherry", "orange"]

search_string = "an"

found = search_string_in_list(search_string, my_list)

if found:

print(f"The string '{search_string}' was found in the list.")

else:

print(f"The string '{search_string}' was not found in the list.")

In this code, we define a function `search_string_in_list` that takes a string and a list as parameters. It
iterates over each item in the list and checks if the given string is present in any of the items using the
`in` operator. If a match is found, the function returns `True`. If no match is found after checking all
items, the function returns `False`.

We then create an example list called `my_list` containing some fruits. We specify the `search_string` we
want to search for, which in this case is "an". We call the `search_string_in_list` function with the search
string and the list, and store the result in the variable `found`.

Finally, we check the value of `found` and print an appropriate message to indicate whether the search
string was found in the list or not.

Note that this code performs a case-sensitive search. If you want to perform a case-insensitive search,
you can modify the code by converting both the search string and the items in the list to lowercase or
uppercase before comparison.

51. Write a function that takes a string as a parameter and replaces the first letter of every word with
the corresponding uppercase letter.

Sure! Here's an example of a Python function that takes a string as a parameter and replaces the first
letter of every word with its corresponding uppercase letter:

def capitalize_first_letter(sentence):

words = sentence.split()

capitalized_words = [word[0].upper() + word[1:] for word in words]

capitalized_sentence = ' '.join(capitalized_words)

return capitalized_sentence
input_sentence = "this is a sample sentence"

result = capitalize_first_letter(input_sentence)

print(result)

In this code, the `capitalize_first_letter` function takes a sentence as a parameter. It splits the sentence
into individual words using the `split` method, which splits the string at every whitespace.

Next, it creates a new list called `capitalized_words` using a list comprehension. For each word in the
`words` list, it takes the first letter `word[0]`, converts it to uppercase using the `upper` method, and
concatenates it with the rest of the word `word[1:]`. This creates a new word with the first letter
capitalized.

Then, the `capitalized_words` list is joined back into a string using the `join` method, with each word
separated by a whitespace. The resulting string, where the first letter of every word is capitalized, is
returned.

In the example usage, the function is called with the input sentence "this is a sample sentence". The
result is stored in the `result` variable and then printed, producing the output "This Is A Sample
Sentence".

52.Create a program to determine whether a string is a palindrome or not.

def is_palindrome(string):

string = string.replace(" ", "").lower()

if string == string[::-1]:

return True

else:

return False

input_string = input("Enter a string: ")

if is_palindrome(input_string):

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

In this program, the `is_palindrome` function takes a string as input. It first removes any whitespace from
the string using the `replace` method and converts it to lowercase using the `lower` method. This
ensures that the comparison is case-insensitive and ignores whitespace.

The function then compares the string with its reverse by using slicing with a step of -1 (`[::-1]`). If the
reversed string is the same as the original string, it returns `True`, indicating that the string is a
palindrome. Otherwise, it returns `False`.

In the example usage, the program prompts the user to enter a string. It then calls the `is_palindrome`
function with the input string and prints the corresponding message based on whether the string is a
palindrome or not.

53.i) Write a function to find the number of common characters in two strings.

ii) Write a program to reverse a string.

Here are the solutions to your questions:

i) Function to find the number of common characters in two strings:

def count_common_characters(str1, str2):

set1 = set(str1)

set2 = set(str2)

common_characters = set1.intersection(set2)

return len(common_characters)

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

common_count = count_common_characters(string1, string2)

print("Number of common characters:", common_count)

In this program, the `count_common_characters` function takes two strings as input. It converts both
strings into sets using the `set` function, which eliminates duplicate characters and gives us unique
characters from each string. Then, it finds the intersection of the two sets using the `intersection`
method, which gives us the common characters.

The function returns the count of common characters using the `len` function on the resulting set of
common characters.

ii) Program to reverse a string:

def reverse_string(string):

# Using string slicing with a step of -1 to reverse the string


reversed_string = string[::-1]

return reversed_string

input_string = input("Enter a string: ")

reversed_string = reverse_string(input_string)

print("Reversed string:", reversed_string)

In this program, the `reverse_string` function takes a string as input. It uses string slicing with a step of -1
(`[::-1]`) to reverse the string. This creates a new string that contains the characters of the original string
in reverse order.

The function then returns the reversed string. In the example usage, the program prompts the user to
enter a string. It calls the `reverse_string` function with the input string and prints the reversed string.

You might also like