Unit-3 Python
Unit-3 Python
Unit-3 Python
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:
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.
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.
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.
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`.
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.
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():
length = len(string)
print(length) # Output: 13
The `lower()` function converts all characters in a string to lowercase, while the `upper()` function
converts them to uppercase.
lowercase = string.lower()
uppercase = string.upper()
3. strip():
The `strip()` function removes leading and trailing whitespace (including newlines) from a string.
stripped = string.strip()
4. split():
The `split()` function splits a string into a list of substrings based on a specified delimiter (by default,
whitespace).
words = string.split(",")
5. join():
The `join()` function concatenates elements of an iterable (such as a list) into a single string, using a
specified separator.
string = ",".join(words)
6. replace():
The `replace()` function replaces all occurrences of a substring within a string with another substring.
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.
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.
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.
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.
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:
temp = a
a=b
b = temp
return a, b
# Main program
if __name__ == "__main__":
# Initial values
num1 = 10
num2 = 20
print("Before exchanging:")
print("num1 =", num1)
print("\nAfter exchanging:")
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:
return a + b
# Main program
if __name__ == "__main__":
Output:
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.
Local variables:
- 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:
- 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.
def circulate_values(*args):
first_value = args[0]
args[i] = args[i + 1]
args[-1] = first_value
# Main program
if __name__ == "__main__":
a=1
b=2
c=3
d=4
circulate_values(a, b, c, 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.
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):
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.
- Example:
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:
greet("Jane", "Nice to meet you!") # Output: Hello, Jane! Nice to meet you!
4. Variable-length Arguments:
def greet(*names):
print(f"Hello, {name}!")
greet("John", "Jane", "Alice") # Output: Hello, John! Hello, Jane! Hello, Alice!
def print_info(**details):
print(f"{key}: {value}")
# Output:
# name: John
# age: 25
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)
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.
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.
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.
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
numbers = [1, 2, 3, 4, 5]
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.
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.
multiply = lambda x, y: x * y
result = multiply(5, 3)
print(result) # Output: 15
numbers = [1, 2, 3, 4, 5]
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
i) example program to calculate the average of its arguments using a function in Python:
def average(*args):
if len(args) == 0:
return 0
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.
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):
print(num)
total = sum(numbers)
print("Sum:", total)
max_num = max(numbers)
print("Maximum:", max_num)
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
min_idx = j
# 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)
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.
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.
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.
return result
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.
total = sum(numbers)
return avg
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.
def fibonacci_series(n):
return fib_list
fibonacci_numbers = fibonacci_series(limit)
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)`.
def reverse_string(string):
reversed_string = ""
return reversed_string
reversed_string = reverse_string(input_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]
x2, y2 = polygon[i + 1]
area += cross_product
area = abs(area)
return area / 2
area = compute_area(polygon)
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.
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:
length = len(string)
lowercase = string.lower()
uppercase = string.upper()
count = string.count("o")
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.
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"
- 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:
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!"`.
Here's a program that counts the number of common characters in a pair of strings:
common_count = 0
set1 = set(str1)
set2 = set(str2)
if char in set2:
common_count += 1
return common_count
string1 = "hello"
string2 = "world"
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.
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
if char in vowels:
vowel_count += 1
return vowel_count
result = count_vowels(user_input)
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.
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)
Output:
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
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:
substring1 = my_string[7:12]
substring2 = my_string[-6:-1]
substring3 = my_string[::2]
substring4 = my_string[::-1]
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:
if string in item:
return True
return False
search_string = "an"
if found:
else:
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()
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".
def is_palindrome(string):
if string == string[::-1]:
return True
else:
return False
if is_palindrome(input_string):
else:
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.
set1 = set(str1)
set2 = set(str2)
common_characters = set1.intersection(set2)
return len(common_characters)
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.
def reverse_string(string):
return reversed_string
reversed_string = reverse_string(input_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.