Let's create a function (with docstring)
Example 1
Explanation
- Defines a function named
is_eventhat takes one parameter callednum - Uses the modulo operator
%to check if the input number is divisible by 2 with no remainder - Returns the string 'even' when the condition
num % 2 == 0is true, otherwise returns 'odd' - The function documentation explains it accepts any integer and returns whether it's odd or even
- When called with an integer like
is_even(4)it will return'even'andis_even(3)will return'odd'
Example 2
Explanation
- The code calls a function named
is_evenwith numbers from 1 to 10 as input - It uses a for loop with
range(1,11)to iterate through integers 1 through 10 - The
is_evenfunction is likely checking if each number is even or odd and returning True/False - Each result from
is_even(i)gets printed to the console on a separate line - The output shows the boolean results of whether each number from 1 to 10 is even (True) or odd (False)
Output
Example 3
Explanation
- This code accesses the docstring attribute of a function named
is_evenusing the__doc__special attribute - It retrieves and displays the documentation string that was defined when the
is_evenfunction was created - The
__doc__attribute is a built-in Python feature that stores documentation for functions, classes, and modules - This is commonly used for inspecting function documentation during development or debugging
- The output will be the actual text content of the function's docstring if one exists, or None if no docstring was defined
Output
Example 4
Explanation
- Prints the docstring of the
is_evenfunction to the console - Uses the
__doc__attribute to access the function's documentation string - Displays any descriptive text written by the function author explaining what
is_evendoes - Likely shows information about the function's purpose, parameters, and return value
- Side effect is simply printing text output to the terminal/console
Output
2 Point of views
Example 5
Explanation
- This function named
is_eventakes one parameter callednumand determines whether it's an even or odd integer - It first checks if the input is actually an integer using
type(num) == int, returning an error message if not - If the input is an integer, it uses the modulo operator
%to check if the number is divisible by 2 with no remainder - The function returns the string 'even' when the number is divisible by 2, otherwise returns 'odd'
- If the input isn't an integer, it returns the string 'Enter a valid number' as an error message
Parameters vs Arguments
Types of Arguments:
- Default Argument
- Positional Argument
- Keyword Argument
Example 6
Explanation
- Defines a function named
powerthat takes two parametersaandb - Uses the exponentiation operator
**to calculatearaised to the power ofb - Returns the result of the exponential calculation
- No side effects or external dependencies
- Example usage:
power(2, 3)would return8
Example 7
Explanation
- Calls a function named
powerwith the argument2 - Likely raises a TypeError since the
powerfunction is not defined in the standard library - The function name suggests it might be intended to calculate powers (like 2^2), but requires proper implementation
- Could also be a typo for built-in functions like
pow()or**operator - Would produce an error unless
poweris defined elsewhere in the code
Output
Example 8
Explanation
- Defines a function called
powerthat takes two parametersaandbwith default values of 1 - Uses Python's default argument feature so the function can be called with fewer arguments than defined
- The function calculates and returns the result of raising
ato the power ofbusing the**operator - If no arguments are provided when calling the function, it will use the default values (1^1 = 1)
- Key APIs/functions used:
deffor function definition,**for exponentiation operator
Example 9
Explanation
- Calls a function named
power()without any arguments - Likely calculates or returns some power-related value based on the function's implementation
- No parameters are passed, so it probably uses default values or global variables
- The function name suggests it might perform exponentiation or return power measurements
- Output depends entirely on how the
power()function is defined elsewhere in the code
Output
Example 10
Explanation
- This code demonstrates positional argument passing to a function called
power - The function call
power(2,3)passes 2 as the first argument and 3 as the second argument - In positional arguments, arguments must be passed in the exact order of the function's parameters
- The first argument (2) maps to the first parameter, and the second argument (3) maps to the second parameter
- This is the standard way to pass arguments where position matters for parameter assignment
Output
Example 11
Explanation
- Calls the power function with keyword arguments instead of positional arguments
- Passes b=3 and a=2, which means the function will use 3 as the base and 2 as the exponent
- Uses keyword arguments to make the code more readable and explicit about what each value represents
- The function likely returns 2 raised to the power of 3 (2^3 = 8) based on typical power function behavior
- This approach allows arguments to be passed in any order since they're explicitly named
Output
*args and **kwargs
*args and **kwargs are special Python keywords that are used to pass the variable length of arguments to a function
Example 12
Explanation
- This code defines a simple multiplication function that takes exactly two parameters (a and b)
- The function returns the product of these two numbers when called
- The comment explains that *args is used for passing variable numbers of non-keyword arguments, though it's not actually used in this specific function
- This function will raise an error if called with more or fewer than two arguments
- The function has no side effects and simply performs mathematical multiplication on its inputs
Example 13
Explanation
- Calls a function named multiply with arguments 2 and 3
- The multiply function likely performs multiplication operation on the two input numbers
- Key API/function used is the multiply function (assumed to be defined elsewhere)
- Expected side effect is returning the result of 2 times 3, which would be 6
- Output value would be 6 if the function works as intended for multiplication
Output
Example 14
Explanation
- Defines a function named
multiplythat takes three parameters:a,b, andc - Uses the multiplication operator
*to calculate the product of all three input values - Returns the result of multiplying the three numbers together
- No side effects occur during execution - it simply performs calculation and returns value
- Function can be called with any three numeric arguments like
multiply(2, 3, 4)to get result 24
Example 15
Explanation
- Calls a function named multiply with three arguments: 2, 3, and 4
- The multiply function likely performs multiplication operation on all provided arguments
- Key API/function used is the multiply function (not built-in Python function)
- Expected output would be the product of 2 × 3 × 4 = 24
- Side effect depends on implementation but typically returns the calculated result
Output
Example 16
Explanation
- Defines a function that accepts any number of arguments using *args syntax
- Initializes a product variable to 1 for multiplication
- Loops through each argument and multiplies it with the running product
- Prints the arguments as a tuple (shows how *args collects them)
- Returns the final multiplied result of all input numbers
Example 17
Explanation
- Calls a multiply function with two arguments (1,2) and prints the result
- Calls the same multiply function with five arguments (2,3,4,5,6) and prints that result
- Uses a function named multiply that likely accepts variable number of arguments
- The function probably performs multiplication operation on all provided numbers
- Output would show 2 followed by 720 (2×3×4×5×6) on separate lines
Output
Example 18
Explanation
- This function accepts any number of arguments using
*madhuwhich collects them into a tuple - It initializes a
productvariable to 1 and multiplies each argument in the tuple by this variable - The function prints the entire tuple of arguments before returning the final calculated product
- Key Python features used include variable-length arguments (
*args), loop iteration, and arithmetic multiplication - When called with numbers like
multiply(2, 3, 4), it would print(2, 3, 4)and return24
Example 19
Explanation
- Calls the
multiplyfunction with the arguments 1 through 9. - The
multiplyfunction is expected to compute the product of all the provided numbers. - The result of the multiplication is printed to the console.
- If
multiplyis not defined, this will raise aNameError.
Output
Example 20
Explanation
- Defines a function
displaythat accepts any number of keyword arguments using**kwargs. - Iterates through the keyword arguments, unpacking each key-value pair.
- Prints each key followed by an arrow and its corresponding value.
- Allows flexible input, enabling the function to handle varying numbers of named arguments.
Example 21
Explanation
- Calls the
displayfunction with three keyword arguments:india,srilanka, andnepal, each assigned a corresponding city name. - The
displayfunction is likely designed to output or visualize the provided data in a user-friendly format. - The expected output would show the cities associated with each country in a structured manner, such as a table or formatted text.
- This code assumes that the
displayfunction is defined elsewhere in the code or imported from a library.
Output
Example 22
Explanation
- This function accepts any number of keyword arguments using
**madhusyntax - It iterates through the dictionary created from keyword arguments using
.items() - For each key-value pair, it prints the key followed by '->' and then the value
- The function can handle any number of named parameters when called
- When called with arguments like
display(name="Alice", age=30), it would print each parameter name and its value on separate lines
Example 23
Explanation
- Calls the
displayfunction with three keyword arguments:india,srilanka, andnepal, each assigned a corresponding city name. - The
displayfunction is likely designed to output or visualize the provided data in a user-friendly format. - The expected output would show the cities associated with each country in a structured manner, such as a table or formatted text.
- This code assumes that the
displayfunction is defined elsewhere in the code or imported from a library.
Output
Points to remember while using *args and **kwargs
- order of the arguments matter(normal ->
*args->**kwargs) - The words “args” and “kwargs” are only a convention, you can use any name of your choice
Without return statement
Example 24
Explanation
- The code creates a list L with initial elements [1, 2, 3] and then calls the append() method to add the number 4 to the end of the list
- The append() method modifies the original list in-place by adding the new element to the end
- The print() function displays the return value of append(), which is None since append() doesn't return anything useful
- After execution, the list L will contain [1, 2, 3, 4] but the print statement shows None because that's what append() returns
- This demonstrates that list methods modify the original object directly rather than returning a new modified object
Output
Example 25
Explanation
- Creates a list L with initial elements [1, 2, 3]
- Uses the append() method to add the value 4 to the end of the list
- Calls print() function to display the updated list contents
- The list is modified in-place by the append operation
- Output will be [1, 2, 3, 4]
Output
Variable Scope
Example 26
Explanation
- Function
gtakes parameteryand tries to access global variablexwithout declaring it as local - When
g(x)is called, it prints the global variablexvalue (5), then printsx+1which equals 6 - Global variable
xis defined outside the function with value 5 before calling the function - The function execution shows that local variables don't override global ones when not explicitly declared inside the function
- Final
print(x)outputs the original global variable value which remains unchanged at 5
Output
Example 27
Explanation
- The code defines a function
fthat tries to increment and print a variablexby 1 - It uses the
+=operator to add 1 toxand then prints the result - The global variable
xis initially set to 5 before calling the function - When
f(x)is called, it will cause an error becausexis referenced before assignment inside the function - After the function call, it prints the original value of
xwhich remains unchanged at 5
Output
Example 28
Explanation
- Function
ftakes parameterybut doesn't use it, instead creates local variablexinitialized to 1 - Inside function,
xis incremented by 1, making it equal to 2, then printed - Global variable
xis set to 5 before calling functionf - Function call prints 2 because local variable
xinside function shadows globalx - After function call, global
xremains unchanged at 5 and gets printed as 5
Output
Example 29
Explanation
- Function
ftakes parameterx, increments it by 1, prints the local value, and returns the new value - Variable
xis initialized to 3 in the main scope before calling functionf - Function call
f(x)passes the value 3 tof, which creates a local copy ofxand modifies it to 4 - The returned value 4 is assigned to variable
zin the main scope - Prints show that
z = 4and originalx = 3remains unchanged due to Python's pass-by-object-reference behavior
Output
Nested Functions
Example 30
Explanation
- Defines an outer function
fthat contains a nested inner functiong - Function
gis defined insidefbut never called or executed - Function
fprints 'inside function f' when called - Function
gwould print 'inside function g' if it were called - Both functions are defined but nothing is executed until
f()is called
Example 31
Explanation
- Calls a function named
f()with no arguments - The function
f()is defined elsewhere in the codebase or imported from a module - No return value is captured or used in this line
- This will execute whatever code is inside the function definition of
f() - Side effects depend on what the function
f()actually does internally
Output
Example 32
Explanation
- Defines an outer function
fthat contains a nested inner functiong - Inner function
gprints 'inside function g' when called - When
f()is executed, it callsg()first, then prints 'inside function f' - Function
print()is used to display text output to console - The nested structure demonstrates how inner functions can be defined and called within outer functions
Example 33
Explanation
- Calls a function named
f()with no arguments - The function
f()is defined elsewhere in the codebase or imported from a module - No return value is captured or used in this line
- This will execute whatever code is inside the function definition of
f() - Side effects depend on what the function
f()actually does internally
Output
Example 34
Explanation
- The function
gtakes a parameterxand defines an inner functionhthat tries to assign'abc'tox, but this doesn't affect the outer scope due to Python's scoping rules - Inside
g, the variablexis incremented by 1, so ifxwas 3, it becomes 4 - The function prints the value of
xas 4 within the function scope - The inner function
his called but has no effect on the outerxvariable because it creates its own local scope - The final value of
x(which is 4) is returned and assigned toz, sozequals 4
Output
Example 35
Explanation
- The code defines nested functions
hinsideg, where both functions modify and print the value ofx - Function
gtakes parameterx, increments it by 1, prints the local value, calls inner functionhwith the updated value, then returns the final value ofx - Function
htakes parameterx, increments it by 1, and prints the local value beforehfinishes - Variable
xis initialized to 3 in the global scope, then passed to functiongwhich creates its own local copy ofx - The output shows the flow of execution with multiple print statements showing values at different scopes, ending with
x = 3and in the main program
Output
Functions are 1st class citizens
Example 36
Explanation
- The code defines a simple function called
squarethat takes one parameternumand returns its square using the**operator - It then prints the type of the
squarefunction usingtype()which will show<class 'function'> - It prints the identity (memory address) of the
squarefunction usingid()which shows a unique integer identifier - The
type()function reveals thatsquareis indeed a function object in Python - The
id()function shows where in memory this function object is stored, helping understand Python's object model
Output
Example 37
Explanation
- The code reassigns the variable x to reference the function named 'square' (which must be defined elsewhere)
- It prints the value of x, which will show the function object's memory address or representation
- It prints the memory id of x using the id() function to show the object's unique identifier
- It calls the function x(3) which executes the square function with argument 3, returning 9
- The side effect is that x now points to the same function as the variable square, so both names refer to the same function object
Output
Example 38
Explanation
- Removes the variable name
squarefrom the current namespace, making it unavailable for use - If
squarewas a function, this deletes the function reference but doesn't affect the actual function object if other references exist - Results in a NameError if you try to call
square()after this deletion - Key API used is Python's built-in
delstatement for removing references - Side effect is that any subsequent attempts to access
squarewill raise an exception
Example 39
Explanation
- Calls a function named
squarewith the argument3 - The function likely calculates the square of the input number (3² = 9)
- Uses a function call syntax with parentheses to pass the value 3 as input
- No built-in Python functions are used directly - relies on a custom
squarefunction - Expected output would be the numeric value 9 if the function is implemented correctly
Output
Example 40
Explanation
- Calls a function named
xwith the integer3as its argument - The function
xmust be defined elsewhere in the code for this to work - Likely returns some value based on the input
3, though exact behavior depends on the function definition - This is a simple function call that passes a numeric literal as parameter
- If function
xisn't defined, this would raise aNameErrorexception
Output
Example 41
Explanation
- Assigns the value of variable
xto a new variable namedsquare. - The code does not perform any calculations; it simply creates a reference to the value of
x. - If
xis not defined prior to this line, it will raise aNameError. - The expected output is that
squarewill hold the same value asxafter this assignment.
Example 42
Explanation
- Creates a list
Lcontaining integers 1 to 4 and a reference to a functionsquare. - The
squarefunction is expected to be defined elsewhere in the code, which squares its input. - Prints the entire list
L, showing the integers and the function reference. - Calls the last element of the list (the
squarefunction) with an argument of 3, printing the result of squaring 3 (which is 9).
Output
Example 43
Explanation
- Creates a set
scontaining the variablesquare, which is expected to be defined elsewhere in the code. - The comment indicates that sets in Python do not allow mutable data types, implying that
squareshould be an immutable type (like an integer or a string). - The output of the cell will display the contents of the set
s, which will show the value ofsquareif it is defined correctly. - If
squareis not defined, this code will raise aNameError.
Output
Example 44
Explanation
- Defines a function
fthat returns another functionx, which takes two arguments and returns their sum. - The inner function
xis called with the arguments3and4, returning7. - The outer function
fis called again with the same arguments3and4, but this is incorrect asxis not callable again. - The code will raise a
TypeErrorbecause the result off()(3, 4)is an integer, and integers are not callable. - The expected output is an error message indicating that an integer object is not callable.
Output
Example 45
Explanation
- Defines a function
fthat returns another functionx, which takes two parametersaandb. - Inside
x, another functionyis defined, which takes two parameters and returns their product. - The outer function
fis called, which returnsx, and thenxis immediately called with arguments3and4. - The result of
x(3, 4)is the functiony, which is then called with the same arguments3and4.
Output
Example 46
Explanation
- Defines two functions:
func_aprints a message andfunc_btakes a function as an argument and calls it. func_bprints a message before executing the passed functionz, which isfunc_ain this case.- When
func_b(func_a)is called, it first prints "inside func_c" and then callsfunc_a, which prints "inside func_a". - The output of the entire code cell will be:
- "inside func_c"
- "inside func_a"
- The return value of
func_bis the result of callingfunc_a, which isNonesincefunc_adoes not return anything.
Output
Benefits of using a Function
- Code Modularity
- Code Readibility
- Code Reusability
Lambda Function A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Example 47
Explanation
- Defines a lambda function
athat takes an inputxand returns its square (x^2). - Calls the lambda function
awith the argument4. - The
printfunction outputs the result of the lambda function, which is16(since 4 squared is 16).
Output
Example 48
Explanation
- Creates an anonymous lambda function that takes two parameters x and y and returns their sum
- Assigns this lambda function to variable a
- Calls the lambda function with arguments 2 and 3, which returns 5
- Prints the result of the lambda function call to the console
- The lambda function behaves exactly like a regular function defined with def keyword but in a single line
Output
Diff between lambda vs Normal Function
- No name
- lambda has no return value(infact,returns a function)
- lambda is written in 1 line
- not reusable
Then why use lambda functions? They are used with HOF (Higher Order Functions)
Example 49
Explanation
- Creates an anonymous function that checks if the character 'a' exists in any given string
- Takes a string input and returns True if 'a' is found, False otherwise
- Uses the
inoperator to search for the substring 'a' within the input string - The lambda function is assigned to variable
aand then called with the string 'Madhu' - Output will be False since the string 'Madhu' does not contain the character 'a'
Output
Example 50
Explanation
- Creates a lambda function that takes a number x and returns 'even' if x is divisible by 2, otherwise returns 'odd'
- Uses the modulo operator % to check if a number is even or odd
- Takes the number 6 as input and evaluates whether it's even or odd
- Prints the result of the lambda function call with input 6
- Output will be 'even' since 6 is divisible by 2 with no remainder
Output
Higher Order Functions
- If a function returns another function
- A function uses another function as input
Example 51
Explanation
- Defines a function
squarethat takes a number and returns its square using the**operator - Creates a
transformfunction that applies any given functionfto every element in a listL - Uses a for loop to iterate through each element in the input list
L - Calls
transformwithsquarefunction and list[1,2,3,4,5]as arguments - Prints the transformed list
[1, 4, 9, 16, 25]showing each original number squared
Output
Example 52
Explanation
- Applies a lambda function that cubes each element (x**3) to every item in list L
- Uses the transform function to execute the lambda operation across all elements
- Key APIs: lambda for anonymous function creation, transform for applying function to iterable
- Expected output: new list with each original element raised to the power of 3
- Side effect: modifies the original list L in-place if transform works in-place, otherwise returns new transformed list
Output
Map
Example 53
Explanation
- Maps each element in the list [1,2,3,4,5] to its square using lambda function
- Uses built-in map() function with lambda expression to apply squaring operation
- Returns a map object (iterator) containing squared values
- Equivalent to creating new list [1, 4, 9, 16, 25] without explicit loop
- Requires converting result to list to see actual squared numbers: list(map(...))
Output
Example 54
Explanation
- Takes a list of numbers [1,2,3,4,5] and applies the square operation to each element using map and lambda
- The lambda function x**2 squares each input value x
- map() applies this squaring operation to every item in the input list
- list() converts the map object returned by map() into an actual list
- Output is [1, 4, 9, 16, 25] - each original number squared
Output
Example 55
Explanation
- Maps over each element in list L and applies a lambda function to determine if the number is even or odd
- Uses the modulo operator (%) to check if numbers are divisible by 2 without remainder
- Returns a new list with string labels 'even' or 'odd' corresponding to each number in the original list
- The map() function processes all elements and returns a map object that gets converted to a list
- Expected output is ['odd', 'even', 'odd', 'even', 'odd'] for the given input list
Output
Example 56
Explanation
- The code extracts the 'gender' field from each dictionary in the users list using map() and a lambda function
- It applies the lambda function to every item in the users list, which accesses the 'gender' key of each dictionary
- The map() function returns a map object containing all the gender values from the dictionaries
- The result would be an iterable containing ['male', 'male', 'female'] in Python 3
- This is a functional programming approach to transform data by extracting specific keys from a collection of dictionaries
Output
Filter
Example 57
Explanation
- Filters the list L to keep only elements greater than 5 using the filter function with a lambda expression
- The lambda function
lambda x:x>5acts as a boolean test that returns True for numbers greater than 5 - The filter function applies this test to each element in the list and returns an iterator of matching elements
- Converts the filtered iterator back to a list format using list() constructor
- Expected output is
[6, 7]since these are the only numbers in the original list that are greater than 5
Output
Example 58
Explanation
- Maps over list L and applies a lambda function that checks if each element is greater than 5
- The lambda function returns True/False for each comparison
- Returns a map object containing boolean values indicating which elements satisfy the condition
- Key APIs used: map() function and lambda expression for inline function definition
- Expected output is a map object (in Python 3) with boolean results for each element comparison
Output
Example 59
Explanation
- Filters the fruits list to keep only items that contain the letter 'a'
- Uses lambda function as the filtering condition to check if 'a' exists in each fruit name
- Applies the filter() function which returns an iterator of matching elements
- The result is converted to a list showing fruits that contain the letter 'a'
- Expected output: ['apple', 'guava'] since these are the only fruits containing 'a'
Output
Example 60
Explanation
- Checks each fruit name in the fruits list to see if the letter 'a' is present
- Uses map() function to apply a lambda function to every item in fruits
- Lambda function returns True/False for each fruit based on whether 'a' exists in the string
- Returns a list of boolean values indicating presence of 'a' in each fruit name
- Expected output is something like [True, False, True, False] depending on the fruits list contents
Output
Reduce
Example 61
Explanation
- Uses functools.reduce to apply a lambda function that adds two numbers together across the entire list [1,2,3,4,5]
- The lambda function takes two arguments x and y and returns their sum x+y
- Processes the list sequentially: first adds 1+2=3, then 3+3=6, then 6+4=10, then 10+5=15
- Key API is functools.reduce which repeatedly applies a function to reduce a sequence to a single value
- Expected output is the integer 15, which is the sum of all numbers in the list
Output
Example 62
Explanation
- Filters the list [1,2,3,4,5] to keep only elements greater than 2
- Uses lambda function
lambda x:x>2as the filtering condition - Applies the built-in
filter()function to process the list - Returns a filter object containing [3, 4, 5] as elements greater than 2
- Converts the filter object to a list for final output [3, 4, 5]
Output
Example 63
Explanation
- Maps each element in the list [1,2,3,4,5] to a boolean value indicating if it's greater than 2
- Uses lambda function
x>x>2as the transformation rule for each element - Applies the map function to transform all elements simultaneously
- Returns a map object containing [False, False, True, True, True]
- Converts the map object to a list for final output display
Output
Example 64
Explanation
- Uses functools.reduce to apply a lambda function that compares two values and returns the smaller one
- The lambda function takes two arguments x and y, returning x if x is less than y, otherwise returning y
- Processes the list [11,21,31,4,51] by repeatedly comparing pairs of elements
- Finds and returns the minimum value from the list, which is 4
- This is an alternative way to find the minimum value without using the built-in min() function
Output
Problem-1: Write a Python function that takes a list and returns a new list with unique elements of the first list.
Exercise 1:
Input:
Output:
Example 65
Explanation
- Defines a function
return_uniquethat takes a listLas input and returns a new list with unique elements. - Initializes an empty list
resto store unique values found inL. - Iterates through each element
iin the input listL, checking if it is already inres; if not, it appendsitores. - Calls the function with a sample list
Lcontaining duplicates,[1,2,3,3,3,3,4,5]. - The expected output is a list of unique elements:
[1, 2, 3, 4, 5].
Output
Problem-2: Write a Python function that accepts a hyphen-separated sequence of words as parameter and returns the words in a hyphen-separated sequence after sorting them alphabetically.
Example 1:
Input:
Output:
Example 66
Explanation
- Defines a function
sort_sequencethat takes a stringseqcontaining color names separated by hyphens. - Splits the input string into a list using
split('-'), sorts the list alphabetically withsorted(), and appends each color to a temporary listtemp. - Joins the sorted colors back into a single string with hyphens using
"-".join(temp)and returns the result. - When called with the string
'green-red-yellow-black-white', it returns the sorted string'black-green-red-white-yellow'.
Output
Problem 3: Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters.
Example 67
Explanation
- Defines a function
lower_upper(s)that counts the number of lowercase and uppercase letters in a given strings. - Uses a for loop to iterate through each character in the string and checks if it's lowercase or uppercase using the
islower()andisupper()methods. - Increments
lower_countfor lowercase letters andupper_countfor uppercase letters, ignoring non-alphabetic characters. - Returns a tuple containing the counts of lowercase and uppercase letters.
- The output prints the counts of lowercase and uppercase characters from the provided string
s.
Output
Problem 4: Write a Python program to print the even numbers from a given list.
Example 68
Explanation
- Defines a function
is_eventhat takes a listLas input and returns a new list containing only the even numbers fromL. - Uses a for loop to iterate through each element
iin the input listL. - Checks if each element
iis even by using the modulus operator%to see ifi % 2equals 0. - Appends even numbers to the result list
res. - Calls the function with the list
[1,2,3,4,5,6,7], which returns[2, 4, 6].
Output
Problem 5: Write a Python function to check whether a number is perfect or not.
A Perfect number is a number that is half the sum of all of its positive divisors (including itself).
Example :
Example 69
Explanation
- Defines a function
perfect_numthat checks if a given number is a perfect number (equal to the sum of its divisors). - Initializes a variable
sumto zero, which will accumulate the divisors ofnum. - Uses a
forloop to iterate through numbers from 1 tonum - 1, checking if each number is a divisor ofnum. - If a divisor is found, it adds that divisor to
sum. - Calls the function with the argument
29, which will returnFalsesince 29 is not a perfect number.
Output
Problem-6: Write a Python function to concatenate any no of dictionaries to create a new one.
Example 70
Explanation
- Defines a function
merge_dictthat takes multiple dictionaries as arguments and merges them into a single dictionary. - Uses the
update()method to add key-value pairs from each input dictionary to a new dictionaryd. - The function returns the merged dictionary containing all key-value pairs from the input dictionaries.
- Example input dictionaries are
dic1,dic2, anddic3, which are merged when the function is called. - The expected output is a single dictionary:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}.
Output
Problem-7 Write a python function that accepts a string as input and returns the word with most occurence.
Example 71
Explanation
- Defines a function
most_usedthat takes a stringsas input and counts the occurrences of each word. - Uses a dictionary
dto store words as keys and their counts as values, updating counts as it iterates through the split words. - Finds the maximum count of occurrences using
max(d.values()). - Iterates through the dictionary to find and print the first word with the maximum count along with its occurrence.
- Expected output for the input string is
hello -> 3, indicating "hello" is the most frequently used word.
Output
Problem-8 Write a python function that receives a list of integers and prints out a histogram of bin size 10
Example 72
Explanation
- Imports the
mathmodule to use mathematical functions for rounding. - Defines a function
histogram(L)that creates a frequency distribution of values in the listLwithin specified bins of width 10. - Calculates the minimum and maximum bin edges based on the smallest and largest values in
L, rounding them to the nearest tens. - Iterates through each bin, counting how many values from
Lfall within each bin range and stores the counts in a dictionary. - Returns a dictionary where keys are bin ranges (e.g., '11-20') and values are the counts of numbers in those ranges; for the input
[13,42,15,37,22,39,41,50], it outputs{'11-20': 2, '21-30': 1, '31-40': 3, '41-50': 2}.
Output
Problem-9 Write a python function that accepts a list of 2D co-ordinates and a query point, and then finds the the co-ordinate which is closest in terms of distance from the query point.
Example 73
Explanation
- Function calculates the point closest to a query point by computing Euclidean distances between all points and the query
- Uses nested loop to calculate distance for each point using the formula √[(x₂-x₁)² + (y₂-y₁)²]
- Sorts distances with their original indices to find the minimum distance point
- Returns the actual coordinates of the nearest point from the original list
- Output is (1,4) since it's the closest point to query (0,0) among the given points
Output
Problem-10:Write a python program that receives a list of strings and performs bag of word operation on those strings
https://en.wikipedia.org/wiki/Bag-of-words_model
Example 74
Explanation
- The function
bowcreates a bag-of-words representation by first building a vocabulary set from all unique words across all strings in the input list - It then processes each string to count how many times each vocabulary word appears in that string, creating a frequency vector for each string
- The
set()andupdate()methods are used to efficiently collect all unique words, whilesplit()breaks strings into individual words - For each string,
count()method counts occurrences of each vocabulary word to build the numerical frequency vectors - The function prints the vocabulary set and returns a list of lists where each inner list represents the word frequencies for the corresponding input string
Output
###Problem 11: Write a Python program to add three given lists using Python map and lambda.
Example 75
Explanation
- Combines three lists element-wise using map and lambda function to add corresponding elements together
- Uses
map()with a lambda that takes three parameters (x, y, z) representing elements from each list at the same position - Applies the addition operation across all three lists simultaneously, creating pairs of elements at index 0, then index 1, etc.
- The result is a new list containing the sum of each set of corresponding elements: [12, 15, 18]
- Returns an iterator object that needs to be converted to a list to see the final result
Output
###Problem-12:Write a Python program to create a list containing the power of said number in bases raised to the corresponding number in the index using Python map.
Input:
Output:
Example 76
Explanation
- Creates a list of numbers [1,2,3,4,5,6] and applies a lambda function to each element with its index position
- Uses
map()function with a lambda that raises each number to the power of its position (0,1,2,3,4,5) - The
range(len(list1))generates indices 0 through 5 corresponding to each list element - Results in [1^0, 2^1, 3^2, 4^3, 5^4, 6^5] = [1, 2, 9, 64, 625, 7776]
- Returns a map object containing the computed exponential values
Output
###Problem-13 Using filter() and list() functions and .lower() method filter all the vowels in a given string.
Example 77
Explanation
- The code filters characters from the string
str1to keep only vowels (a, e, i, o, u) regardless of case - It uses
filter()function with a lambda expression that checks if each character converted to lowercase exists in the string 'aeiou' - The
lambda x: True if x.lower() in 'aeiou' else Falsecondition converts each character to lowercase and tests membership in vowels - The result is a filter object containing only the vowel characters from the original string
- Expected output shows all vowels found in "FIFA world cup in 2022 will take place in Qatar" as a filter object with elements: ['I', 'A', 'o', 'u', 'i', '2', '2', 'i', 'e', 'a', 'e', 'i']
Output
Problem-14: Use reduce to convert a 2D list to 1D
Example 78
Explanation
- The code flattens a 2D list (list of lists) into a single list by concatenating all sublists together
- It uses
functools.reduce()with a lambda function that adds two lists together (x+y) to combine all elements - The
lambda x,y:x+yfunction takes two arguments and returns their concatenation, effectively joining lists - Input is a nested list structure:
[[1, 2, 3], [3, 6, 7], [7, 5, 4]] - Output is a flattened list:
[1, 2, 3, 3, 6, 7, 7, 5, 4]
Output
Problem 15- A dictionary contains following information about 5 employees:
- First name
- Last name
- Age
- Grade(Skilled,Semi-skilled,Highly skilled) Write a program using map/filter/reduce to a list of employees(first name + last name) who are highly skilled
Example 79
Explanation
- Creates a list of dictionaries representing employee data with fields for first name, last name, age, and skill grade
- Each dictionary contains personal and professional information about individual employees
- Defines structured data that can be easily accessed and manipulated later in the program
- Sets up a dataset for potential filtering, sorting, or analysis operations
- Provides a clear data structure for working with employee records in subsequent code
Example 80
Explanation
- Filters the employees list to keep only those with grade equal to 'highly-skilled'
- Maps each filtered employee dictionary to a full name string combining first and last names
- Uses lambda functions for both filtering and mapping operations in a functional programming style
- The filter function evaluates each employee's grade attribute and returns True/False
- Returns a list of full names (strings) for all highly-skilled employees
Output

