Day1-Day10 Python practice questions

 

Index: Click to Navigate:

 Day 1 

Question 1: 

Write a Python program to find the sum of two numbers entered by the user. However, here's the twist:

  • If either number is negative, multiply it by -1 before adding.
  • If both numbers are even, double their sum.
  • If both numbers are odd, halve their sum.
Solution:
# Taking input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Handling negative numbers
if num1 < 0:
    num1 *= -1
if num2 < 0:
    num2 *= -1

# Calculating the sum
total_sum = num1 + num2

# Applying conditions
if num1 % 2 == 0 and num2 % 2 == 0:  # Both numbers are even
    total_sum *= 2
elif num1 % 2 != 0 and num2 % 2 != 0:  # Both numbers are odd
    total_sum /= 2

# Displaying the result
print("The result is:", total_sum)

Explanation:

This program calculates the sum of two numbers entered by the user, but it includes a few twists based on specific conditions:

Input from the User:

The program asks the user to enter two numbers (num1 and num2).
These numbers are stored as integers using int(input()).
Handling Negative Numbers

If any of the numbers is negative, it is converted to a positive number using num1 *= -1 or num2 *= -1.

Calculating the Basic Sum:

The initial sum of the two numbers is calculated and stored in the variable total_sum.
Applying Conditions

Condition 1: If both numbers are even, their sum is doubled (total_sum *= 2).
Condition 2: If both numbers are odd, their sum is halved (total_sum /= 2).
If one number is odd and the other is even, no additional changes are made to the sum.

Displaying the Result:

Finally, the result is printed with print("The result is:", total_sum).

Example Runs:

Input:

num1 = -4, num2 = 6
After converting negatives: num1 = 4, num2 = 6
Both numbers are even → Double the sum: (4 + 6) * 2 = 20
Output: The result is: 20

Input:

num1 = -3, num2 = -5
After converting negatives: num1 = 3, num2 = 5
Both numbers are odd → Halve the sum: (3 + 5) / 2 = 4.0
Output: The result is: 4.0

This program not only practices conditional logic but also demonstrates working with even/odd numbers and handling user inputs.
-----------------------------------------------------------------------------------------------------------

Day 2 

Question 2: 

Write a Python program to swap two numbers without using a temporary variable, arithmetic operations, or built-in methods. Use the bitwise XOR operator to perform the swap.


# Taking input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

print(f "Before swapping: num1 = {num1}, num2 = {num2}")

# Swapping using XOR

num1 = num1 ^ num2
num2 = num1 ^ num2
num1 = num1 ^ num2

print(f "After swapping: num1 = {num1}, num2 = {num2}")

Explanation:

How XOR Works (Bitwise Explanation)

The XOR (exclusive OR) operation compares each bit of two numbers and follows these rules:

  • If both bits are the same, the result is 0.
  • If the bits are different, the result is 1.

Here’s a simple way to visualize XOR:

Truth Table for XOR

Bit A Bit B A ^ B (Result)
0 0 0
0 1 1
1 0 1
1 1 0

Example with Numbers:

Let’s take two numbers: num1 = 5 (binary: 0101) and num2 = 3 (binary: 0011).

We’ll perform the XOR operation on each corresponding bit:

  num1 = 0101
  num2 = 0011
  ----------------
  result = 0110

Explanation:

  • The first bit (from the right) is 1 in num1 and 1 in num2, so the result is 0.
  • The second bit is 0 in num1 and 1 in num2, so the result is 1.
  • The third bit is 1 in num1 and 0 in num2, so the result is 1.
  • The fourth bit is 0 in num1 and 0 in num2, so the result is 0.

Thus, the XOR of 5 and 3 gives 6 (0110 in binary).

Visualizing the XOR Swap

Let’s break down the XOR swap process using an example.

Assume:

  • num1 = 5 (binary: 0101)
  • num2 = 3 (binary: 0011)

Step 1: num1 = num1 ^ num2

  • num1 = 0101 ^ 0011 = 0110 (Now num1 = 6)

Step 2: num2 = num1 ^ num2

  • num2 = 0110 ^ 0011 = 0101 (Now num2 = 5, original num1 value)

Step 3: num1 = num1 ^ num2

  • num1 = 0110 ^ 0101 = 0011 (Now num1 = 3, original num2 value)

Final Result:

  • num1 = 3
  • num2 = 5

The two numbers have been swapped using XOR!

-----------------------------------------------------------------------------------------------------------

 Day 3 

Question 3: 

Check if a Number is an Armstrong Number Using Generator Expression

An Armstrong number  is a number that is equal to the sum of its own digits, each raised to the power of the total number of digits.

For example:

153 is an Armstrong number because 13+53+33=153153 \text{ is an Armstrong number because } 1^3 + 5^3 + 3^3 = 153

What is a Generator Expression?

A generator expression is a concise way to create a series of values to iterate over, without storing them in memory. Unlike lists, which hold all values in memory, generator expressions calculate each value only when needed, making them more efficient for large datasets.

Solution:

# Input from the user

num = input("Enter a number to check if it's an Armstrong number: ")

# Calculate the number of digits
num_digits = len(num)

# Use generator expression to compute the Armstrong sum
armstrong_sum = sum(int(digit) ** num_digits for digit in num)

# Compare the sum with the original number
if armstrong_sum == int(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is NOT an Armstrong number.")

Explanation:

1. Take User Input

num = input("Enter a number to check if it's an 
             Armstrong number: ")
  • The user is prompted to input a number.
  • The input is treated as a string to make it easy to iterate over the digits later.

2. Calculate the Number of Digits

num_digits = len(num)
  • len(num) calculates the number of digits in the input number (as a string).

3. Compute the Armstrong Sum

armstrong_sum = sum(int(digit) ** num_digits for digit in num)
  • This uses a generator expression inside the sum() function:
    • for digit in num: Iterates over each digit of the number (as a string).
    • int(digit): Converts the string digit back to an integer.
    • int(digit) ** num_digits: Raises the digit to the power of num_digits.
    • sum(...): Adds up these values to compute the Armstrong sum.

4. Compare the Armstrong Sum with the Original Number

if armstrong_sum == int(num):
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is NOT an Armstrong number.")
  • The Armstrong sum (armstrong_sum) is compared to the original number (converted back to an integer using int(num)).
  • If they are equal, the number is an Armstrong number. Otherwise, it is not.

How It Works (Example Walkthrough)

Let’s say the user inputs 153:

  1. Input and Digits Count

    • num = "153"
    • num_digits = len(num) = 3
  2. Compute Armstrong Sum

    • armstrong_sum = sum(int(digit) ** 3 for digit in "153")
    • Step-by-step:
      • For digit = "1"13=11^3 = 1
      • For digit = "5"53=1255^3 = 125
      • For digit = "3"33=273^3 = 27
    • armstrong_sum = 1 + 125 + 27 = 153
  3. Compare and Output

    • armstrong_sum == int(num):
      • 153==153153 == 153: True
    • Output: 153 is an Armstrong number.

Edge Cases

  • Single-digit numbers: Every single-digit number is an Armstrong number because x1=xx^1 = x.
  • Large numbers: The code works for large numbers but may slow down if the number of digits is very high because of the power operation.

----------------------------------------------------------------------------------------------------------

Day 4

Question 4: 

write a python porgram to check if all characters in a given string are unique without using built-in functions and solve this using functions.

Solution:

def check_unique_characters(string):
    # Compare each character with every other character
    for i in range(len(string)):
        for j in range(i + 1, len(string)):
            if string[i] == string[j]:  # Check for duplicate characters
                return False
    return True

# Input from the user
string = input("Enter a string: ")

# Check if the string has unique characters
if check_unique_characters(string):
    print("All characters in the string are unique.")
else:
    print("The string contains duplicate characters.")
    

Explanation:

This implementation of checking if all characters in a string are unique uses a brute force approach, where each character is compared with every other character in the string.

  1. Outer Loop:

    • The outer loop iterates through each character in the string by its index i.
    • For example, if the string is "hello", the outer loop starts with the first character 'h' (index 0).
  2. Inner Loop:

    • The inner loop starts from the next character (index i + 1) and iterates through the remaining characters of the string.
    • For each character in the outer loop, the inner loop compares it with all subsequent characters.
    • For instance, when the outer loop is at 'h' (index 0), the inner loop compares 'h' with 'e''l''l', and 'o'.
  3. Comparison:

    • In each iteration of the inner loop, the two characters (from indices i and j) are compared.
    • If a match is found (string[i] == string[j]), the function immediately returns False, indicating that the string has duplicate characters.
  4. No Duplicates:

    • If no duplicates are found after all comparisons, the function returns True.

Code Walkthrough:

Input:

Enter a string: hello
  • Outer loop starts with i = 0 (string[i] = 'h'):

    • Inner loop starts with j = 1 (string[j] = 'e'): 'h' != 'e', continue.
    • j = 2 (string[j] = 'l'): 'h' != 'l', continue.
    • j = 3 (string[j] = 'l'): 'h' != 'l', continue.
    • j = 4 (string[j] = 'o'): 'h' != 'o', continue.
  • Outer loop moves to i = 1 (string[i] = 'e'):

    • Inner loop starts with j = 2 (string[j] = 'l'): 'e' != 'l', continue.
    • j = 3 (string[j] = 'l'): 'e' != 'l', continue.
    • j = 4 (string[j] = 'o'): 'e' != 'o', continue.
  • Outer loop moves to i = 2 (string[i] = 'l'):

    • Inner loop starts with j = 3 (string[j] = 'l'): 'l' == 'l'return False.

Output:

The string contains duplicate characters.
Note:
This solution is helpful for beginners to understand nested loops 
and how comparisons work between indices.

---------------------------------------------------------------------------------
Day 5

Question 5: 

Write a function custom_zip that mimics Python's built-in zip(). It should take multiple iterables, combine their elements by index into tuples, and stop when the shortest iterable is exhausted.

Solution:

def custom_zip(*iterables):
    # Find the length of the shortest iterable
    min_length = min(len(it) for it in iterables)
    
    # Create an empty list to store the result
    result = []
    
    # Loop through the indices of the shortest iterable
    for i in range(min_length):
        # Create a tuple by picking the i-th element from each iterable
        result.append(tuple(it[i] for it in iterables))
    
    # Return the list of tuples
    return result

# Example usage:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False]

# Call the function and print the result
zipped = custom_zip(list1, list2, list3)
print(zipped)  # Output: [(1, 'a', True), (2, 'b', False)]

Explanation:

Function Definition: custom_zip(*iterables)

  1. *iterables:
    • The * before iterables allows the function to accept any number of input iterables (such as lists, tuples, etc.).
    • For example, you can pass two lists, three lists, or even more, and the function will work with them all.

Step 1: Find the Length of the Shortest Iterable

min_length = min(len(it) for it in iterables)
  • Here, min() is used to find the length of the shortest iterable.
  • len(it) calculates the length of each iterable (it stands for each individual iterable passed).
  • min() takes the smallest length, so the loop will stop when the shortest iterable is exhausted. This ensures that the function doesn't try to access elements that don't exist in shorter iterables.

For example, if you have:

  • list1 = [1, 2, 3] (length = 3)
  • list2 = ['a', 'b', 'c'] (length = 3)
  • list3 = [True, False] (length = 2)

The min_length will be 2 because list3 is the shortest iterable.

Step 2: Initialize an Empty Result List

result = []

Step 3: Loop Through the Indices of the Shortest Iterable

for i in range(min_length):
  • The for loop iterates from 0 to min_length - 1. In this case, the loop runs 2 times because min_length is 2 (from the previous step).
  • The variable i represents the index in the iterables.

Step 4: Create a Tuple from Each Iterable

result.append(tuple(it[i] for it in iterables))
  • Inside the loop, we use a generator expression ((it[i] for it in iterables)) to extract the i-th element from each iterable.
  • The tuple() function takes these elements and combines them into a tuple.
  • This tuple is then appended to the result list.

For each iteration:

  • On the first iteration (i = 0), we pick the first element from each iterable: 1 from list1'a' from list2, and True from list3, creating the tuple (1, 'a', True).
  • On the second iteration (i = 1), we pick the second element: 2 from list1'b' from list2, and False from list3, creating the tuple (2, 'b', False).

Step 5: Return the Final Result

return result
  • After the loop finishes, the function returns the result list, which contains all the tuples formed from the input iterables.

Example Execution:

Input:

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = [True, False]

Execution Steps:

  1. The length of the shortest iterable (list3) is 2. So, the loop will run two times.
  2. The first iteration will create the tuple (1, 'a', True).
  3. The second iteration will create the tuple (2, 'b', False).
  4. After the loop finishes, the result list is [(1, 'a', True), (2, 'b', False)].

Output:

[(1, 'a', True), (2, 'b', False)]

-----------------------------------------------------------------------------------------------

Day 6

Question 6: 

Write a function that takes a number n as input and generates the first n prime numbers. The function should return a list containing these primes.

Tip: To check if a number is prime, use the fact that you only need to check for divisibility up to the square root of that number.

Solution:

def primes(n = 100):
        
    prime_list = []

    start = 2

    while len(prime_list)<n:
        is_prime = True
        for i in range(2,int(start**0.5)+1):  
            if start%i == 0:
                is_prime = False
                break
        if is_prime:
            prime_list.append(start)
            
        start+=1
    return prime_list          
        
print(primes(10))

Explanation:

def primes(n = 100):

This function generates the first n prime numbers. By default, it generates 100 prime numbers unless a different value for n is provided.

Initialize an Empty List:

prime_list = []

This list will store the prime numbers as they are found.

Start with the First Prime Number:

start = 2

The variable start begins at 2 because 2 is the smallest prime number.

While Loop:

while len(prime_list) < n:

The loop continues until the list prime_list contains n prime numbers.

Check if start is Prime:

is_prime = True
for i in range(2, int(start**0.5) + 1):
    if start % i == 0:
        is_prime = False
        break
  • is_prime = True: Assume start is a prime number initially.
  • The for loop checks divisibility of start by numbers from 2 to int(start**0.5) + 1.
  • Why int(start**0.5) + 1?
    • If a number start has a divisor, one of its divisors will always be less than or equal to its square root.
    • For example, for 36, the divisors are (1, 36), (2, 18), (3, 12), (4, 9), (6, 6). Beyond 6, divisors repeat as pairs.
    • This reduces the number of checks significantly, making the algorithm faster.
  • If start % i == 0, the number is not prime (is_prime = False), and the loop exits early with break.

Add Prime Numbers to the List:

if is_prime:
    prime_list.append(start)

If start is still marked as prime, it is added to prime_list.

Move to the Next Number:

start += 1

Increment start to check the next number.

Return the List of Primes:

return prime_list

Why Use Square Root Optimization?

Without Square Root:

  • The inner loop would check all numbers from 2 to start - 1.
  • If we were generating prime numbers for a large value like n = 100,000, the number of iterations grows significantly as start increases. For example:
    • For start = 1,000,000, it would require ~1,000,000 checks for divisors, making the algorithm slow.

With Square Root:

  • Instead of checking up to start - 1, we only check up to sqrt(start).
  • Example:
    • For start = 1,000,000, the maximum divisor to check is sqrt(1,000,000) = 1,000. This reduces the number of checks by almost 1,000 times for large numbers.

Performance Difference: Example with Large Numbers

Without Square Root:

  • Generating primes for n = 100,000 could take hours as every number is checked for divisibility up to start - 1.

With Square Root:

  • Using sqrt(start) optimization reduces the time dramatically, making it feasible to generate primes up to n = 100,000 in minutes or seconds, depending on the implementation.

This is why using the square root is essential for efficient prime number generation.

-------------------------------------------------------------------------------------------------------------

Day-7

Question7:

Write a function swap_case that takes a string as input and swaps the case of each letter. For example:

"pYtHoN bUzZ" should become "PyThOn BuZz".

Note: You should not use Python's built-in swapcase() function. Instead, implement the case swap manually using conditional statements.

Solution:

def manual_swapcase(s):

    result = ""

    for char in s:

        if 'a' <= char <= 'z':  # If lowercase, convert to uppercase

            result += chr(ord(char) - 32)

        elif 'A' <= char <= 'Z':  # If uppercase, convert to lowercase

            result += chr(ord(char) + 32)

        else:

            result += char  # Keep non-alphabetic characters unchanged

    return result

input_string = "pYtHoN bUzZ"

output_string = manual_swapcase(input_string)

print(output_string)  

Explanation:

Step 1: Understanding the Problem

We want to change:

  • Lowercase letters (a-z) to uppercase (A-Z)
  • Uppercase letters (A-Z) to lowercase (a-z)
  • Numbers and special characters should remain unchanged

Example

Input: "pYtHoN bUzZ23"

Expected Output: "PyThOn BuZz23"

Step 2: Breaking Down the Code

Function Definition

def manual_swapcase(s):
    result = ""
  • s is the input string (e.g., "pYtHoN bUzZ23").
  • result is an empty string ("") that will store the final modified output.

Loop Through Each Character

for char in s:
  • This loop goes one character at a time through the input string.

Checking If a Character is Lowercase (a-z)

if 'a' <= char <= 'z':  # If lowercase, convert to uppercase
    result += chr(ord(char) - 32)
  • 'a' <= char <= 'z' checks if the character is a lowercase letter.
  • If it is, we convert it to uppercase using:
    chr(ord(char) - 32)
    
    • ord(char): Converts the letter to its ASCII code.
    • Subtracting 32 from this shifts it to uppercase.
    • chr(...): Converts it back to a character.
Character ASCII (ord()) Convert (-32) New ASCII New Character
'p' 112 112 - 32 = 80 80 'P'
'y' 121 121 - 32 = 89 89 'Y'

Checking If a Character is Uppercase (A-Z)

elif 'A' <= char <= 'Z':  # If uppercase, convert to lowercase
    result += chr(ord(char) + 32)
  • 'A' <= char <= 'Z' checks if the character is an uppercase letter.
  • If it is, we convert it to lowercase using:
    chr(ord(char) + 32)
    
    • ord(char): Converts the letter to its ASCII code.
    • Adding 32 shifts it to lowercase.
    • chr(...): Converts it back to a character.
Character ASCII (ord()) Convert (+32) New ASCII New Character
'Y' 89 89 + 32 = 121 121 'y'
'H' 72 72 + 32 = 104 104 'h'

Keeping Non-Alphabetic Characters Unchanged

else:
    result += char  # Keep non-alphabetic characters unchanged
  • If the character is not a letter (like space, numbers, or special characters), we simply add it to result without modification.

Returning the Final String

return result
  • After processing all characters, we return the final modified string.

Step 3: Running the Function

input_string = "pYtHoN bUzZ23"
output_string = manual_swapcase(input_string)
print(output_string)
  1. We pass "pYtHoN bUzZ23" as input.
  2. The function converts the case of each letter.
  3. The result is stored in output_string and printed.

Step 4: Understanding the Output

Character-by-Character Transformation

Input->converted
  p   →   P
  Y  →   y
  t  →   T
  H →   h
  o  →   O
  N  →  n
(space) → stays the same
  b  →   B
  U →   u
  z  →   Z
  Z  →  z
  2 →  stays the same
  3 → stays the same

Final Output

PyThOn BuZz23

--------------------------------------------------------------------------------

Day-8

Question8:

Write a function that moves all the 0s in a list to the end, and sorts the remaining non-zero numbers in ascending order.

Example:

input : [0, 4,1, 0, 3, 6]

output: [1, 3, 4,6, 0, 0]

Solution:

def move_zeros_and_sort(nums):

    # Extract and sort non-zero numbers

    non_zero_sorted = sorted([num for num in nums if num != 0])  

    # Create a list of zeros

    zeros = [0] * nums.count(0)  

    # Concatenate sorted non-zero numbers with zeros

    return non_zero_sorted + zeros  

input_list = [0, 4, 1, 0, 3, 6]

output_list = move_zeros_and_sort(input_list)

print(output_list)

Explanation:

def move_zeros_and_sort(nums):
  • This defines a function named move_zeros_and_sort, which takes a list of numbers (nums) as input.

Step 1: Extract and Sort Non-Zero Numbers

non_zero_sorted = sorted([num for num in nums if num != 0])
  • List comprehension is used to extract all numbers from nums that are not zero (!= 0).
    • For example, if nums = [0, 4, 1, 0, 3, 6], then [num for num in nums if num != 0] will give [4, 1, 3, 6].
  • sorted() is used to sort these numbers in ascending order.
    • sorted([4, 1, 3, 6]) gives [1, 3, 4, 6].
  • Now, non_zero_sorted = [1, 3, 4, 6].

Step 2: Count Zeros and Create a List of Zeros

zeros = [0] * nums.count(0)
  • nums.count(0) counts how many zeros are in the list.
    • In [0, 4, 1, 0, 3, 6], there are 2 zeros.
  • [0] * 2 creates a list containing two zeros: [0, 0].
  • Now, zeros = [0, 0].

Step 3: Combine Sorted Numbers and Zeros

return non_zero_sorted + zeros
  • The + operator concatenates the two lists:
    • non_zero_sorted = [1, 3, 4, 6]
    • zeros = [0, 0]
    • non_zero_sorted + zeros results in [1, 3, 4, 6, 0, 0].

Putting It All Together

input_list = [0, 4, 1, 0, 3, 6]
output_list = move_zeros_and_sort(input_list)
print(output_list)
  • move_zeros_and_sort([0, 4, 1, 0, 3, 6]) returns [1, 3, 4, 6, 0, 0].
  • The output is printed:
    [1, 3, 4, 6, 0, 0].

Final Output:

[1, 3, 4, 6, 0, 0]
----------------------------------------------------------------------------

Day -9 


Question 9:
Write a function that takes a list of 100 random integers and finds the longest consecutive sequence in the list.

Example:
input:[14, 14, 7, 5, 1, 15, 2, 10, 1, 2, 3, 4, 5, 13, 8, 6, 3]

output: 4

In the given list, the longest consecutive sequence is [1, 2, 3, 4], which has a length of 4.
Solution:

from random import randint

li= []
for i in range(100):
    li.append(randint(1,20)) #you can generate any random numbers
print(li)

longest = 1
current_streak = 1
for i in range(1, len(li)):
        # Check if the current number is consecutive to the previous one
        if li[i] == li[i - 1] + 1:
            current_streak += 1
        elif li[i] != li[i - 1]:  # Skip duplicates
            current_streak = 1  # Reset streak for a new sequence

        longest = max(longest, current_streak)  # Update longest sequence length
        
print(longest)


Explanation:

1. Generate a List of Random Numbers

from random import randint

li= []
for i in range(100):
    li.append(randint(1,20)) # Generate a random number between 1 and 20
print(li)
  • This creates a list li of 100 random integers ranging from 1 to 20.
  • The list is printed for reference.

2. Initialize Variables for Tracking the Longest Consecutive Sequence

longest = 1
current_streak = 1
  • longest: Stores the length of the longest consecutive sequence found so far.
  • current_streak: Tracks the length of the current consecutive sequence.

3. Iterate Through the List to Find Consecutive Sequences

for i in range(1, len(li)):
  • This loop starts from index 1 (second element) and iterates through the list.

4. Check If the Current Number is Consecutive to the Previous One

if li[i] == li[i - 1] + 1:
    current_streak += 1
  • If the current number is exactly 1 more than the previous number, it means the sequence is continuing.
  • The current_streak counter is increased.

5. Reset Streak If Sequence is Broken (Handling Duplicates)

elif li[i] != li[i - 1]:  # Skip duplicates
    current_streak = 1  # Reset streak for a new sequence
  • If the current number is not consecutive and not a duplicate, the sequence is broken.
  • current_streak is reset to 1 because a new sequence may start from here.

6. Update the Longest Sequence Found

longest = max(longest, current_streak)
  • After each iteration, the program updates longest to store the maximum consecutive sequence found so far.

7. Print the Longest Consecutive Sequence Length

print(longest)
  • Displays the longest consecutive sequence length found in the list.
---------------------------------------------------------------------------------------------------------------
Day-10

Question10:

Write a function that takes a list of strings and performs the following tasks:
  • Filter out the strings that have less than 4 characters.
  • Convert all remaining strings to uppercase.
  • Concatenate the those strings 
  • Return the final concatenated string.
Hint: Do this using map,filter,reduce

Solution:

from functools import reduce

def process_strings(string_list):
    # Step 1: Filter out strings that have less than 4 characters
    filtered_strings = filter(lambda x: len(x) >= 4, string_list)

    # Step 2: Convert all remaining strings to uppercase
    uppercase_strings = map(lambda x: x.upper(), filtered_strings)

    # Step 3: Concatenate the strings
    concatenated_string = reduce(lambda x, y: x + y, uppercase_strings)
    
    return concatenated_string

input_list = ["hello", "to", "the", "world", "this", "is", "python"]
result = process_strings(input_list)
print(result)  

Explanation:

1. filter Function:

filtered_strings = filter(lambda x: len(x) >= 4, string_list)
  • What is filter?

    • The filter function helps us select certain items from a list based on a condition.
    • It filters out the items that don't meet the condition.
  • How does it work here?

    • We pass the list string_list to the filter function.
    • The condition we use is lambda x: len(x) >= 4. This means "keep only the strings whose length is greater than or equal to 4."
    • Example: If the list contains "hello", "to", "world", it will keep "hello" and "world", but remove "to" because it has fewer than 4 characters.

2. map Function:

uppercase_strings = map(lambda x: x.upper(), filtered_strings)
  • What is map?

    • The map function allows us to apply a function to each item in a list and change each item according to that function.
  • How does it work here?

    • After filtering, we pass the filtered strings to the map function.
    • The function we use is lambda x: x.upper(). This means "convert each string to uppercase."
    • Example: If we had "hello" and "world", the map function will change them to "HELLO" and "WORLD".

3. reduce Function:

concatenated_string = reduce(lambda x, y: x + y, uppercase_strings)
  • What is reduce?

    • The reduce function takes two elements at a time and applies a function to them. It continues applying the function to the result and the next item in the list, until only one value remains.
  • How does it work here?

    • We use reduce to combine all the strings together.
    • The function lambda x, y: x + y says "take two strings and combine them (concatenate) into one."
    • For example, if we have "HELLO" and "WORLD", reduce will first combine "HELLO" and "WORLD" into "HELLOWORLD", then it will continue if there are more strings to combine.
    • At the end, you'll get one long string made of all the uppercase words combined together.

Putting it All Together:

For the input list ["hello", "to", "the", "world", "this", "is", "python"], here’s how each step works:

  1. Filtering:

    • Strings shorter than 4 characters ("to", "the", "is") are removed.
    • Remaining list: ["hello", "world", "this", "python"].
  2. Converting to Uppercase:

    • Convert each string to uppercase.
    • New list: ["HELLO", "WORLD", "THIS", "PYTHON"].
  3. Concatenating the Strings:

    • Join (concatenate) all the uppercase strings together.
    • Final result: "HELLOWORLDTHISPYTHON".

Final Output:

"HELLOWORLDTHISPYTHON"

Summary:

  • filter: Removes strings shorter than 4 characters.
  • map: Converts the remaining strings to uppercase.
  • reduce: Joins (concatenates) all the strings into one long string.

This is how we transform the list into one string according to the given requirements.


Comments