Showing posts with label Python Quiz. Show all posts
Showing posts with label Python Quiz. Show all posts

Thursday, 9 January 2025

Day 83: Python Program to Swap the First and the Last Character of a String

 

def swap_first_last_char(string):

    if len(string) <= 1:

        return string

        swapped_string = string[-1] + string[1:-1] + string[0]

    return swapped_string

user_input = input("Enter a string: ")

result = swap_first_last_char(user_input)

print(f"String after swapping the first and last characters: {result}")

#source code --> clcoding.com 

Code Explanation:

1. The swap_first_last_char Function
def swap_first_last_char(string):
This line defines a function named swap_first_last_char, which takes a single argument, string. This function is intended to swap the first and last characters of the string.

    if len(string) <= 1:
        return string
Condition Check: This checks if the length of the string is 1 or less.
If the string has 1 character (e.g., "a") or no characters at all (empty string ""), swapping the first and last characters wouldn't change anything.
So, in this case, it returns the original string as it is.

    swapped_string = string[-1] + string[1:-1] + string[0]
Swapping Logic:
string[-1]: This accesses the last character of the string.
string[1:-1]: This accesses the middle part of the string (from the second character to the second-last character).
string[0]: This accesses the first character of the string.
The expression:

string[-1] + string[1:-1] + string[0]
Concatenates (combines) the last character, the middle part, and the first character in that order, effectively swapping the first and last characters.

    return swapped_string
After swapping the characters, this line returns the new string that has the first and last characters swapped.

2. Taking User Input
user_input = input("Enter a string: ")
This line prompts the user to input a string.
The user's input is stored in the variable user_input.

3. Calling the Function and Displaying the Result
result = swap_first_last_char(user_input)
This line calls the function swap_first_last_char with the user_input as the argument. It stores the result (the swapped string) in the variable result.

print(f"String after swapping the first and last characters: {result}")
This line prints the result (the string with the first and last characters swapped) to the console using f-string formatting.

Day 81: Python Program to Create a New String Made up of First and Last 2 Characters

 

def create_new_string(input_string):

    if len(input_string) < 2:

        return ""

    return input_string[:2] + input_string[-2:]

user_input = input("Enter a string: ")

result = create_new_string(user_input)

print("New string:", result)

#source code --> clcoding.com 


Code Explanation:

1. Defining the Function
The function create_new_string does the main task of creating the new string.

def create_new_string(input_string):
    if len(input_string) < 2:
        return ""
    return input_string[:2] + input_string[-2:]

Step 1: Check the Length of the String
if len(input_string) < 2:
    return ""
len(input_string) calculates the number of characters in the input string.
If the length is less than 2, the function immediately returns an empty string ("") because there aren’t enough characters to extract the required parts.

Step 2: Extract the First and Last Two Characters
return input_string[:2] + input_string[-2:]
input_string[:2]: Extracts the first two characters of the string.
input_string[-2:]: Extracts the last two characters of the string.
Combine the Parts: The + operator joins the first two and last two characters into a single string.

2. Taking User Input
The program prompts the user to enter a string:
user_input = input("Enter a string: ")
The user’s input is stored in the variable user_input.

3. Generating the New String
The function create_new_string is called with user_input as its argument:
result = create_new_string(user_input)
The resulting new string (or an empty string if the input is too short) is stored in the variable result.

4. Displaying the Output
Finally, the program prints the result:
print("New string:", result)

Python Coding Challange - Question With Answer(01090125)

 


Step 1: Define the lists a and b

  • a = [1, 2]: A list containing integers 1 and 2.
  • b = [3, 4]: A list containing integers 3 and 4.

Step 2: Use the zip() function


zipped = zip(a, b)
  • The zip() function pairs elements from the two lists a and b to create an iterator of tuples.
  • Each tuple contains one element from a and one element from b at the same position.
  • The resulting zipped object is a zip object (iterator).

Result of zip(a, b):

  • The pairs formed are:
    1. (1, 3) (first elements of a and b)
    2. (2, 4) (second elements of a and b)

zipped now holds an iterator, which means the values can only be accessed once.


Step 3: First print(list(zipped))

print(list(zipped))
  • The list() function converts the zip object into a list of tuples.
  • The output of the first print() is:
    [(1, 3), (2, 4)]

Step 4: Second print(list(zipped))

print(list(zipped))
  • Here, the zip object (zipped) is exhausted after the first list(zipped) call.
  • A zip object is an iterator, meaning it can only be iterated over once. After it’s exhausted, trying to access it again will yield no results.
  • The second print() outputs:

    []

Explanation of Output

  1. First print(list(zipped)):

    • The zip object is converted into a list, producing [(1, 3), (2, 4)].
    • This exhausts the iterator.
  2. Second print(list(zipped)):

    • The zip object is now empty because iterators can only be traversed once.
    • The result is an empty list: [].

Key Points to Remember

  1. zip() returns an iterator, which can only be iterated over once.
  2. Once the iterator is consumed (e.g., by converting it to a list), it cannot be reused.

Wednesday, 8 January 2025

Python Coding Challange - Question With Answer(01080125)

 


Step 1: Define the lists a and b

  • a = [1, 2]: A list with two integers: 1 and 2.
  • b = ['a', 'b', 'c']: A list with three characters: 'a', 'b', and 'c'.

Step 2: Use the zip() function

c = zip(a, b)
  • The zip() function takes two or more iterables (in this case, a and b) and combines them into an iterator of tuples.
  • Each tuple contains one element from each iterable at the same position.
  • Since zip() stops when the shortest iterable is exhausted, the resulting iterator will only contain two tuples (as a has only two elements).

Result of zip(a, b):

  • The pairs formed are:
    1. (1, 'a') (first elements of a and b)
    2. (2, 'b') (second elements of a and b)
  • The third element of b ('c') is ignored because a has only two elements.

c is now a zip object, which is an iterator that produces the tuples when iterated.


Step 3: Convert the zip object to a list


print(list(c))
  • The list() function converts the zip object into a list of tuples.
  • The output of list(c) is:

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

Explanation of Output

The code produces the following output:


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

This is a list of tuples where:

  • The first tuple (1, 'a') is formed from the first elements of a and b.
  • The second tuple (2, 'b') is formed from the second elements of a and b.
  • 'c' is not included because the zip() function stops when the shortest iterable (a) is exhausted.

Key Points to Remember:

  1. zip() combines elements from two or more iterables into tuples.
  2. It stops when the shortest iterable is exhausted.
  3. The zip() function returns a zip object (an iterator), which needs to be converted into a list (or another collection) to see the results.

Tuesday, 7 January 2025

Python Coding Challange - Question With Answer(01070125)

 


Explanation:

  1. Define the List nums:

    nums = [1, 2, 3, 4]
    • A list named nums is created with the elements [1, 2, 3, 4].
  2. Using the map() Function:

    result = map(lambda x, y: x + y, nums, nums)
    • map() Function:
      • The map() function applies a given function (in this case, a lambda) to the elements of one or more iterables (like lists, tuples, etc.).
      • Here, two iterables are passed to map()—both are nums.
    • lambda Function:
      • The lambda function takes two arguments x and y and returns their sum (x + y).
    • How It Works:
      • The map() function pairs the elements of nums with themselves because both iterables are the same: [(1,1),(2,2),(3,3),(4,4)][(1, 1), (2, 2), (3, 3), (4, 4)]
      • The lambda function is applied to each pair: x=1,y=11+1=2x = 1, y = 1 \Rightarrow 1 + 1 = 2 x=2,y=22+2=4x = 2, y = 2 \Rightarrow 2 + 2 = 4 x=3,y=33+3=6x = 3, y = 3 \Rightarrow 3 + 3 = 6 x=4,y=44+4=8x = 4, y = 4 \Rightarrow 4 + 4 = 8
  3. Convert the map Object to a List:

    print(list(result))
    • The map() function returns a map object (an iterator-like object) in Python 3.
    • Using list(result), the map object is converted to a list: [2,4,6,8][2, 4, 6, 8]

Final Output:


[2, 4, 6, 8]

Summary:

  • The code adds corresponding elements of the list nums with itself.
  • The map() function applies the lambda function pairwise to the elements of the two nums lists.
  • The result is [2, 4, 6, 8].

Sunday, 5 January 2025

Python Coding Challange - Question With Answer(01060125)

 


Step-by-Step Explanation:

  1. Importing NumPy:


    import numpy as np
    • This imports the NumPy library, which provides support for working with arrays and performing mathematical operations like dot products.
  2. Creating Arrays:

    a = np.array([1, 2, 3, 4])
    b = np.array([4, 3, 2, 1])
    • Two 1D NumPy arrays a and b are created:
        a = [1, 2, 3, 4]
        b = [4, 3, 2, 1]
  3. Dot Product Calculation:


    np.dot(a, b)
    • The dot product of two 1D arrays is calculated as:

      dot product=a[0]b[0]+a[1]b[1]+a[2]b[2]+a[3]b[3]\text{dot product} = a[0] \cdot b[0] + a[1] \cdot b[1] + a[2] \cdot b[2] + a[3] \cdot b[3]
    • Substituting the values of a and b:

      dot product=(14)+(23)+(32)+(41)\text{dot product} = (1 \cdot 4) + (2 \cdot 3) + (3 \cdot 2) + (4 \cdot 1)
    • Perform the calculations:

      dot product=4+6+6+4=20\text{dot product} = 4 + 6 + 6 + 4 = 20
  4. Printing the Result:


    print(np.dot(a, b))
    • The result of the dot product, 20, is printed to the console.

Final Output:

20

Key Points:

  • The dot product of two vectors is a scalar value that represents the sum of the products of corresponding elements.
  • In NumPy, np.dot() computes the dot product of two 1D arrays, 2D matrices, or a combination of arrays and matrices.

Saturday, 4 January 2025

Friday, 3 January 2025

Python Coding Challange - Question With Answer(01030125)

 


Explanation

  1. Line 1:
    array = [21, 49, 15] initializes the list.

  2. Line 2:
    gen = (x for x in array if array.count(x) > 0) creates a generator:

    • It iterates over the current array ([21, 49, 15]).
    • array.count(x) checks the count of each element in the array. Since all elements appear once (count > 0), they all qualify to be in the generator.
  3. Line 3:
    array = [0, 49, 88] reassigns array to a new list. However, this does not affect the generator because the generator already references the original array at the time of its creation.

  4. Line 4:
    print(list(gen)) forces the generator to execute:

    • The generator still uses the original array = [21, 49, 15].
    • The condition array.count(x) > 0 is true for all elements in the original list.
    • Hence, the output is [21, 49, 15].

Thursday, 2 January 2025

Python Coding Challange - Question With Answer(01020125)

 


Line-by-Line Breakdown:

  1. my_list = [5, 10, 15, 20]
    This creates a list called my_list containing the values [5, 10, 15, 20].

  2. for index, item in enumerate(my_list):
    The enumerate() function is used here. It takes the list my_list and returns an enumerate object. This object produces pairs of values:

    • index: The position (index) of each element in the list (starting from 0).
    • item: The value of the element at that index in the list.

    So for my_list = [5, 10, 15, 20], enumerate() will generate:

    • (0, 5)
    • (1, 10)
    • (2, 15)
    • (3, 20)

    These pairs are unpacked into the variables index and item.

  3. print(index, item)
    This prints the index and the item for each pair generated by enumerate().

How the Code Works:

  • On the first iteration, index is 0 and item is 5, so it prints 0 5.
  • On the second iteration, index is 1 and item is 10, so it prints 1 10.
  • On the third iteration, index is 2 and item is 15, so it prints 2 15.
  • On the fourth iteration, index is 3 and item is 20, so it prints 3 20.

Output:

0 5
1 10 2 15 3 20

This code is useful for iterating over both the index and value of items in a list, which can be handy when you need both pieces of information during the iteration.

Monday, 30 December 2024

Python Coding Challange - Question With Answer(01301224)

 


Step-by-Step Explanation:

  1. Assign x = 5:

    • The variable x is assigned the value 5.
  2. Assign y = (z := x ** 2) + 10:

    • The expression uses the walrus operator (:=) to:
      • Compute x ** 2 (the square of x), which is 5 ** 2 = 25.
      • Assign this value (25) to the variable z.
    • The entire expression (z := x ** 2) evaluates to 25, which is then added to 10.
    • So, y = 25 + 10 = 35.

    After this line:

      z = 25y = 35
  3. Print Statement:

    • The print function uses an f-string to display the values of x, y, and z:
      • {x=} outputs: x=5
      • {y=} outputs: y=35
      • {z=} outputs: z=25
  4. Output: The program prints:


    x=5 y=35 z=25

Key Points:

  • Walrus Operator (:=):

    • Assigns x ** 2 (25) to z and evaluates to 25 in the same expression.
    • This reduces the need for a separate assignment line for z.
  • Order of Operations:

    • First, z is assigned the value x ** 2 (25).
    • Then, y is computed as z + 10 (25 + 10 = 35).
  • Unrelated Variables:

    • x is not affected by the assignments to y or z. It remains 5 throughout.

Equivalent Code Without the Walrus Operator:

If we didn’t use the walrus operator, the code could be written as:


x = 5
z = x ** 2 y = z + 10print(f"{x=} {y=} {z=}")

This would produce the same output:

x=5 y=35 z=25

Why Use the Walrus Operator Here?

Using the walrus operator is helpful for:

  • Conciseness: It combines the assignment of z and the computation of y in one line.
  • Efficiency: It eliminates redundant code by directly assigning z during the computation.

Sunday, 29 December 2024

Python Coding Challange - Question With Answer(01291224)

 

Step-by-Step Explanation

  1. List Initialization:

    • my_list = [7, 2, 9, 4]
      This creates a list with the elements [7, 2, 9, 4] and assigns it to the variable my_list.
  2. Using the .sort() Method:

    • my_list.sort() sorts the list in place, meaning it modifies the original list directly and does not return a new list.
    • The .sort() method returns None, which is a special Python value indicating that no meaningful value was returned.

    So, when you assign the result of my_list.sort() back to my_list, you are overwriting the original list with None.

  3. Printing the Result:

    • print(my_list) will print None because the variable my_list now holds the return value of the .sort() method, which is None.

Saturday, 28 December 2024

Friday, 27 December 2024

Python Coding Challange - Question With Answer(01271224)

 


1. Understanding any() Function

  • The any() function in Python returns True if at least one element in an iterable evaluates to True. Otherwise, it returns False.
  • An empty iterable (e.g., []) always evaluates to False.

2. Evaluating Each Expression

a. 5 * any([])

  • any([]) → The list is empty, so it evaluates to False.
  • 5 * False → False is treated as 0 when used in arithmetic.
  • Result: 0

b. 6 * any([[]])

  • any([[]]) → The list contains one element: [[]].
    • [[]] is a non-empty list, so it evaluates to True.
  • 6 * True → True is treated as 1 in arithmetic.
  • Result: 6

c. 7 * any([0, []])

  • any([0, []]) →
    • 0 and [] are both falsy, so the result is False.
  • 7 * False → False is treated as 0 in arithmetic.
  • Result: 0

d. 8

  • This is a constant integer.
  • Result: 8

3. Summing Up the Results

The sum() function adds all the elements of the list:

sum([0, 6, 0, 8]) = 14

Final Output

The code outputs : 14

Popular Posts

Categories

100 Python Programs for Beginner (83) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (179) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (953) Python Coding Challenge (398) Python Quiz (53) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses