Monday, 23 December 2024

Python Coding Challange - Question With Answer(01231224)

 


What will be the output of the following code?

import numpy as np
arr = np.arange(1, 10).reshape(3, 3)
result = arr.sum(axis=0) - arr.sum(axis=1)
print(result)

[0, 0, 0]
[1, -1, 1]
[3, -3, 3]
[2, 2, -2]

Step 1: Create the array with np.arange(1, 10)

The function np.arange(1, 10) creates a 1D NumPy array containing integers from 1 to 9 (inclusive of 1 but exclusive of 10).

np.arange(1, 10) = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Step 2: Reshape the array to 3x3

The method .reshape(3, 3) converts the 1D array into a 2D array with 3 rows and 3 columns:

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

Step 3: Compute arr.sum(axis=0)

The parameter axis=0 means sum along columns (vertically).
For each column, we add the elements from the top to the bottom:

  • First column: 1+4+7=121 + 4 + 7 = 12
  • Second column: 2+5+8=152 + 5 + 8 = 15
  • Third column: 3+6+9=183 + 6 + 9 = 18

Result of arr.sum(axis=0):

[12, 15, 18]

Step 4: Compute arr.sum(axis=1)

The parameter axis=1 means sum along rows (horizontally).
For each row, we add the elements from left to right:

  • First row: 1+2+3=61 + 2 + 3 = 6
  • Second row: 4+5+6=154 + 5 + 6 = 15
  • Third row: 7+8+9=247 + 8 + 9 = 24

Result of arr.sum(axis=1):

[6, 15, 24]

Step 5: Perform element-wise subtraction

The subtraction operation is element-wise, meaning corresponding elements of the two arrays are subtracted.

  • 126=612 - 6 = 6
  • 1515=015 - 15 = 0
  • 1824=618 - 24 = -6

Result of arr.sum(axis=0) - arr.sum(axis=1):

[6, 0, -6]

Step 6: Print the result

Finally, the result is printed:

[6, 0, -6]

Key Points:

  1. axis=0 computes the sum along columns (vertically).
  2. axis=1 computes the sum along rows (horizontally).
  3. Subtraction is performed element-wise between the two resulting arrays.

Sunday, 22 December 2024

Saturday, 21 December 2024

Day 51: Python Program to Form an Integer that has Number of Digits at 10’s LSD at 1’s Place


 def form_integer(number):

    if number < 0:

        print("Please provide a non-negative integer.")

        return None

    num_str = str(number)

    num_digits = len(num_str)

    last_digit = int(num_str[-1])

    result = num_digits * 10 + last_digit

     return result

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

new_integer = form_integer(number)

if new_integer is not None:

    print(f"The newly formed integer is: {new_integer}")

#source code --> clcoding.com 

Code Explanation:

1. Function Definition
def form_integer(number):
Defines a function named form_integer that accepts one parameter, number. This function processes the given number to generate a new integer.

2. Input Validation
if number < 0:
    print("Please provide a non-negative integer.")
    return None
Checks if the input number is negative. If it is, the function:
Prints a message: "Please provide a non-negative integer."
Returns None to terminate the function early and avoid further processing.

3. Convert Number to String
num_str = str(number)
Converts the input number to a string (num_str) so that its digits can be easily accessed and processed.

4. Count Digits
num_digits = len(num_str)
Calculates the total number of digits in the input number using the len() function. The result is stored in num_digits.

5. Extract the Last Digit
last_digit = int(num_str[-1])
Extracts the last digit of the number by accessing the last character of the string (num_str[-1]) and converting it back to an integer.

6. Form New Integer
result = num_digits * 10 + last_digit
Forms a new integer using the formula:
new integer=(number of digits×10)+(last digit)

7. Return Result
return result
Returns the newly formed integer (result) to the caller.

8. Input and Function Call
number = int(input("Enter a positive integer: "))
Prompts the user to input a positive integer.
Converts the input to an integer and stores it in the variable number.
new_integer = form_integer(number)
Calls the form_integer function with number as the argument.
Stores the returned value in the variable new_integer.

9. Output the Result
if new_integer is not None:
    print(f"The newly formed integer is: {new_integer}")
Checks if the returned value (new_integer) is not None. If valid:
Prints the newly formed integer.

10. Error Handling
If the user enters a negative number, the program handles it gracefully by displaying a message and skipping further processing.

Day 50 : Python Program to Find Gravitational Force Between the Two Object


import math

def calculate_gravitational_force(m1, m2, r):

    """Calculates the gravitational force between two objects."""

    G = 6.67430e-11  

    force = G * (m1 * m2) / (r ** 2)

    return force

def main():

    print("Gravitational Force Calculator")

    try:

        mass1 = float(input("Enter the mass of the first object (kg): "))

        mass2 = float(input("Enter the mass of the second object (kg): "))

        distance = float(input("Enter the distance between the objects (m): "))


        if mass1 <= 0 or mass2 <= 0 or distance <= 0:

            print("Masses and distance must be positive values.")

            return


        force = calculate_gravitational_force(mass1, mass2, distance)

        print(f"The gravitational force between the objects is {force:.2e} N.")

    except ValueError:

        print("Invalid input. Please enter numeric values.")

if __name__ == "__main__":

    main()

#source code --> clcoding.com 

Code Explanation:

Function Definition
1. import math
Imports the math module. While not directly used in the current code, it might be added for future computations or extensions.

2. def calculate_gravitational_force(m1, m2, r):
Defines a function named calculate_gravitational_force that calculates the gravitational force between two objects.
Parameters:
m1: Mass of the first object (in kilograms).
m2: Mass of the second object (in kilograms).
r: Distance between the centers of the two objects (in meters).
3. G = 6.67430e-11
Declares the gravitational constant, G, which has a value of 
6.67430×10−11m3kg−1s−2.

4. force = G * (m1 * m2) / (r ** 2)
Calculates the gravitational force using the formula:
𝐹=𝐺*𝑚1⋅𝑚2/𝑟2
​The masses are multiplied, and the result is divided by the square of the distance.

5. return force
Returns the computed gravitational force to the caller.
Main Program Logic

6. def main():
Defines the main function to interact with the user.

7. print("Gravitational Force Calculator")
Displays a title message to introduce the program.

8. try:
Starts a try block to handle user input and potential errors.

9. mass1 = float(input("Enter the mass of the first object (kg): "))
Prompts the user to input the mass of the first object in kilograms and converts the input to a float.

10. mass2 = float(input("Enter the mass of the second object (kg): "))
Prompts the user to input the mass of the second object in kilograms and converts the input to a float.

11. distance = float(input("Enter the distance between the objects (m): "))
Prompts the user to input the distance between the objects in meters and converts the input to a float.
Validation

12. if mass1 <= 0 or mass2 <= 0 or distance <= 0:
Checks if any of the inputs (mass1, mass2, or distance) are less than or equal to zero.
Gravitational force requires positive values for mass and distance.

13. print("Masses and distance must be positive values.")
If validation fails, prints an error message.

14. return
Exits the function to prevent further computation.
Force Calculation

15. force = calculate_gravitational_force(mass1, mass2, distance)
Calls the calculate_gravitational_force function with the user-provided inputs and stores the result in the variable force.

16. print(f"The gravitational force between the objects is {force:.2e} N.")
Prints the calculated gravitational force in scientific notation with two decimal places, followed by the unit N (Newtons).

Error Handling
17. except ValueError:
Catches any ValueError that occurs if the user inputs invalid (non-numeric) data.

18. print("Invalid input. Please enter numeric values.")
Displays an error message when a ValueError is caught.
Program Entry Point

19. if __name__ == "__main__":
Ensures that the main() function is only executed when the script is run directly, not when imported as a module.

20. main()
Calls the main function to start the program.

 

Python Bitwise Operators: A Comprehensive Guide

 Bitwise operators in Python allow you to perform operations at the bit level. These operators are essential for tasks such as low-level programming, cryptography, and working with hardware. In this guide, we will explore all Python bitwise operators with clear examples to help you master their usage.


1. What Are Bitwise Operators?

Bitwise operators work on binary representations of numbers (bits). These operators directly manipulate the bits and return results based on bitwise operations. Python provides the following bitwise operators:

OperatorNameDescription
&Bitwise ANDSets each bit to 1 if both bits are 1
|Bitwise OR
Sets each bit to 1 if at least one bit is 1


^Bitwise XORSets each bit to 1 if only one bit is 1
~Bitwise NOTInverts all the bits
<<Left ShiftShifts bits to the left
>>Right ShiftShifts bits to the right

2. Understanding Binary Representation

Before diving into examples, it is crucial to understand how numbers are represented in binary.

For example:

  • 5 in binary is 0101

  • 3 in binary is 0011


3. **Bitwise AND (&)

The & operator compares each bit of two numbers. A bit is set to 1 if both corresponding bits are 1.

Syntax:

result = a & b

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011
result = a & b  # Binary: 0001
print(result)  # Output: 1

Truth Table:

Bit 1Bit 2Result
000
010
100
111

4. **Bitwise OR (|)

The | operator compares each bit of two numbers. A bit is set to 1 if at least one of the corresponding bits is 1.

Syntax:

result = a | b

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011
result = a | b  # Binary: 0111
print(result)  # Output: 7

Truth Table:

Bit 1Bit 2Result
000
011
101
111

5. **Bitwise XOR (^)

The ^ operator compares each bit of two numbers. A bit is set to 1 if the corresponding bits are different.

Syntax:

result = a ^ b

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011
result = a ^ b  # Binary: 0110
print(result)  # Output: 6

Truth Table:

Bit 1Bit 2Result
000
011
101
110

6. **Bitwise NOT (~)

The ~ operator inverts all the bits of a number. For positive numbers, it returns the negative value of the number minus one.

Syntax:

result = ~a

Example:

a = 5  # Binary: 0101
result = ~a  # Binary: -0110
print(result)  # Output: -6

Explanation:

In binary, ~5 flips all bits of 0101 to 1010. In two's complement representation, this corresponds to -6.


7. **Left Shift (<<)

The << operator shifts the bits of a number to the left by the specified number of positions. Each left shift doubles the number.

Syntax:

result = a << n

Example:

a = 5  # Binary: 0101
result = a << 2  # Binary: 10100
print(result)  # Output: 20

Explanation:

Shifting 0101 two places to the left gives 10100, which is 20 in decimal.


8. **Right Shift (>>)

The >> operator shifts the bits of a number to the right by the specified number of positions. Each right shift divides the number by two (ignoring the remainder).

Syntax:

result = a >> n

Example:

a = 5  # Binary: 0101
result = a >> 2  # Binary: 0001
print(result)  # Output: 1

Explanation:

Shifting 0101 two places to the right gives 0001, which is 1 in decimal.


9. Combining Bitwise Operators

You can combine bitwise operators to perform complex bit-level operations.

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011

# Combining operators
result = (a & b) | (~a)
print(result)  # Output: -2

10. Practical Applications of Bitwise Operators

1. Setting and Clearing Bits

# Setting a bit
number = 0b1010
position = 1
number |= (1 << position)
print(bin(number))  # Output: 0b1011

# Clearing a bit
number &= ~(1 << position)
print(bin(number))  # Output: 0b1010

2. Checking if a Bit is Set

number = 0b1010
position = 2
is_set = (number & (1 << position)) != 0
print(is_set)  # Output: True

3. Swapping Two Numbers Without a Temporary Variable

a = 5
b = 3

a = a ^ b
b = a ^ b
a = a ^ b

print(a, b)  # Output: 3, 5

11. Common Mistakes with Bitwise Operators

Mistake 1: Confusing Bitwise Operators with Logical Operators

a = 5
b = 3
# Incorrect: Using 'and' instead of '&'
result = a and b  # Logical AND, not Bitwise AND
print(result)  # Output: 3

Mistake 2: Ignoring Operator Precedence

result = ~a & b  # Not the same as ~(a & b)

Use parentheses to make the precedence clear.


Conclusion

Bitwise operators are powerful tools in Python for performing low-level operations. They are invaluable in fields like cryptography, network programming, and embedded systems. By mastering these operators, you can write more efficient and optimized code.

Python Logical Operators: A Comprehensive Guide

Logical operators in Python are essential tools for combining and manipulating conditional statements. They allow you to evaluate multiple conditions and return a boolean result (‘True’ or ‘False’). In this guide, we will delve deep into Python's logical operators: and, or, and not, along with practical examples.


1. What are Logical Operators?

Logical operators are used to combine conditional expressions. The result of a logical operation depends on the truth values (‘True’ or ‘False’) of the individual expressions involved. Python provides three logical operators:

    1. and
    2. or
    3. not

2. The and Operator

The and operator returns True if both conditions are True. If either condition is False, the result is False.

Syntax:

condition1 and condition2

Truth Table:

Condition 1Condition 2Result
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Example:

age = 25
is_employed = True

# Check if the person is above 18 and employed
if age > 18 and is_employed:
    print("Eligible for the job.")
else:
    print("Not eligible for the job.")

Output:

Eligible for the job.

3. The or Operator

The or operator returns True if at least one of the conditions is True. It only returns False if both conditions are False.

Syntax:

condition1 or condition2

Truth Table:

Condition 1Condition 2Result
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Example:

age = 16
has_permission = True

# Check if the person is above 18 or has permission
if age > 18 or has_permission:
    print("Access granted.")
else:
    print("Access denied.")

Output:

Access granted.

4. The not Operator

The not operator is a unary operator that reverses the truth value of the condition. If the condition is True, it returns False, and vice versa.

Syntax:

not condition

Truth Table:

ConditionResult
TrueFalse
FalseTrue

Example:

is_raining = False

# Check if it is not raining
if not is_raining:
    print("You can go for a walk.")
else:
    print("Better stay indoors.")

Output:

You can go for a walk.

5. Combining Logical Operators

Logical operators can be combined to evaluate complex conditions. Python evaluates them based on operator precedence:

  1. not (highest precedence)

  2. and

  3. or (lowest precedence)

You can use parentheses () to control the order of evaluation.

Example:

age = 20
has_permission = False
is_employed = True

# Complex condition
if (age > 18 and is_employed) or has_permission:
    print("Eligible for the program.")
else:
    print("Not eligible for the program.")

Output:

Eligible for the program.

6. Practical Use Cases of Logical Operators

Case 1: Login Authentication

username = "admin"
password = "1234"

# Check if username and password match
if username == "admin" and password == "1234":
    print("Login successful.")
else:
    print("Invalid credentials.")

Case 2: Traffic Signal

light_color = "green"
car_stopped = True

# Check if it is safe to cross the road
if light_color == "green" and car_stopped:
    print("You can cross the road.")
else:
    print("Wait until it is safe.")

Case 3: Discount Eligibility

age = 65
is_member = True

# Check if eligible for a discount
if age > 60 or is_member:
    print("Eligible for a discount.")
else:
    print("Not eligible for a discount.")

7. Common Pitfalls with Logical Operators

Mistake 1: Forgetting Operator Precedence

x = True
y = False
z = True

# Misunderstanding precedence
result = x or y and z  # Evaluates as x or (y and z)
print(result)  # Output: True

Mistake 2: Using = Instead of ==

x = 10

# Incorrect condition
if x = 10:  # This will throw a SyntaxError
    print("x is 10")

Conclusion

Logical operators are powerful tools in Python for building complex conditional statements. Understanding how to use and, or, and not, along with their precedence rules, will enable you to write efficient and clear code. Practice combining logical operators with real-world scenarios to master their usage!

Python Operators: A Comprehensive Guide

 

Python Operators: A Comprehensive Guide

Operators are fundamental building blocks of programming, and Python provides a rich set of operators to perform various operations on variables and values. This guide will walk you through the different types of operators available in Python, complete with examples to help you understand how they work.


1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division5 / 2 = 2.5
%Modulus5 % 2 = 1
**Exponentiation5 ** 2 = 25
//Floor Division5 // 2 = 2

Example:

x = 10 
y = 3 
print("Addition:", x + y) 
print("Subtraction:", x - y) 
print("Multiplication:", x * y) 
print("Division:", x / y) 
print("Modulus:", x % y) 
print("Exponentiation:", x ** y) 
print("Floor Division:", x // y)

2. Comparison Operators

Comparison operators are used to compare two values and return a boolean result (‘True’ or ‘False’).

OperatorDescriptionExample
==Equal to5 == 3 (False)
!=Not equal to5 != 3 (True)
>Greater than5 > 3 (True)
<Less than5 < 3 (False)
>=Greater than or equal to5 >= 3 (True)
<=Less than or equal to5 <= 3 (False)

Example:

a = 7
b = 4
print("Equal to:", a == b)
print("Not equal to:", a != b) 
print("Greater than:", a > b)
print("Less than:", a < b)
print("Greater than or equal to:", a >= b)
print("Less than or equal to:", a <= b)

3. Logical Operators

Logical operators are used to combine conditional statements.

OperatorDescriptionExample
andReturns True if both statements are True(5 > 3 and 7 > 4)
orReturns True if one of the statements is True(5 > 3 or 7 < 4)
notReverses the resultnot(5 > 3)

Example:

x = True
y = False
print("AND Operator:", x and y)
print("OR Operator:", x or y)
print("NOT Operator:", not x)

4. Assignment Operators

Assignment operators are used to assign values to variables.

OperatorDescriptionExample
=Assignx = 5
+=Add and assignx += 3 (x=x+3)
-=Subtract and assignx -= 3 (x=x-3)
*=Multiply and assignx *= 3 (x=x*3)
/=Divide and assignx /= 3 (x=x/3)
%=Modulus and assignx %= 3 (x=x%3)
//=Floor divide and assignx //= 3
**=Exponentiate and assignx **= 3

Example:

x = 10
x += 5
print("Add and assign:", x)
x *= 2
print("Multiply and assign:", x)

5. Bitwise Operators

Bitwise operators work on bits and perform operations bit by bit.

OperatorDescriptionExample
&AND5 & 3
``OR`53`
^XOR5 ^ 3
~NOT~5
<<Left shift5 << 1
>>Right shift5 >> 1

Example:

a = 5
b = 3
print("Bitwise AND:", a & b)
print("Bitwise OR:", a | b)
print("Bitwise XOR:", a ^ b)
print("Bitwise NOT:", ~a)
print("Left shift:", a << 1)
print("Right shift:", a >> 1)

6. Membership Operators

Membership operators are used to test if a sequence contains a specified value.

OperatorDescriptionExample
inReturns True if a value is found in a sequence'a' in 'apple'
not inReturns True if a value is not found in a sequence'b' not in 'apple'

Example:

string = "hello"
print("'h' in string:", 'h' in string)
print("'z' not in string:", 'z' not in string)

7. Identity Operators

Identity operators are used to compare the memory location of two objects.

OperatorDescriptionExample
isReturns True if both variables are the same objectx is y
is notReturns True if both variables are not the same objectx is not y

Example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]
print("a is b:", a is b)
print("a is not c:", a is not c)

8. Special Operators: Operator Precedence

Operator precedence determines the order in which operations are performed. For example, multiplication has a higher precedence than addition.

Example:

result = 5 + 3 * 2
print("Result:", result)  # Output: 11 (Multiplication first, then addition)

You can use parentheses () to override the precedence.

Example:

result = (5 + 3) * 2
print("Result:", result)  # Output: 16

Conclusion

Understanding Python operators is essential for writing efficient and readable code. This guide covered arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators with examples. By mastering these operators, you can manipulate data effectively and create more complex programs.

Day 48: Python Program To Clear Rightmost Set Bit of a Number

 



def clear_rightmost_set_bit(n):
    """
    Clears the rightmost set bit of the given number.
    :param n: The input number
    :return: The number with the rightmost set bit cleared
    """
    return n & (n - 1)
num = int(input("Enter a non-negative integer: "))  
result = clear_rightmost_set_bit(num)

print(f"Original number: {num} (Binary: {bin(num)})")
print(f"Number after clearing rightmost set bit: {result} (Binary: {bin(result)})")

#source code --> clcoding.com 


Code Explanation:

1. Function Definition
def clear_rightmost_set_bit(n):
    """
    Clears the rightmost set bit of the given number.
    :param n: The input number
    :return: The number with the rightmost set bit cleared
    """
    return n & (n - 1)

Key Points:
Rightmost Set Bit:
The rightmost set bit is the first 1 from the right in the binary representation of the number.
For example:
10 (binary: 1010) → The rightmost set bit is the second position from the right (2^1).
18 (binary: 10010) → The rightmost set bit is the fifth position from the right (2^4).

Clearing the Rightmost Set Bit:
The operation n & (n - 1) clears the rightmost set bit. Here's how:
Subtracting 1 from n flips all bits to the right of the rightmost set bit and flips the rightmost set bit to 0.
The & operation (bitwise AND) keeps all other bits unchanged but ensures the rightmost set bit is cleared.

Example:
For n = 10 (binary: 1010):
n - 1 = 9 (binary: 1001)
n & (n - 1) = 1010 & 1001 = 1000 (decimal: 8)

2. Input Handling
num = int(input("Enter a non-negative integer: "))  
Prompts the user to input a non-negative integer and stores it in num.

3. Call the Function
result = clear_rightmost_set_bit(num)
Calls the function clear_rightmost_set_bit with the input number num.
Stores the result (the number after clearing the rightmost set bit) in result.

4. Display the Results
print(f"Original number: {num} (Binary: {bin(num)})")
print(f"Number after clearing rightmost set bit: {result} (Binary: {bin(result)})")
bin():
Converts the integer into its binary representation (as a string prefixed with 0b).

For example:
bin(10) → '0b1010'
bin(8) → '0b1000'

Displays:
The original number and its binary representation.
The result after clearing the rightmost set bit and its binary representation.

Output:
Original number: 18 (Binary: 0b10010)
Number after clearing rightmost set bit: 16 (Binary: 0b10000)
Source

Day 49 : Python Program to Test Collatz Conjecture for a Given Number


def collatz_conjecture(n):

    if n <= 0:

        print("Please enter a positive integer.")

        return

     print(f"Starting number: {n}")

    while n != 1:

        if n % 2 == 0:

            n = n // 2

        else:

            n = 3 * n + 1

        print(n, end=" ")

    print("\nReached 1!")

try:

    number = int(input("Enter a positive integer to test the Collatz conjecture: "))

    collatz_conjecture(number)

except ValueError:

    print("Invalid input! Please enter a valid integer.")

#source code --> clcoding.com 

Code Explanation:

1. Function Definition
def collatz_conjecture(n):
This function implements the Collatz sequence starting from the number n.

2. Input Validation
if n <= 0:
    print("Please enter a positive integer.")
    return
The Collatz Conjecture only applies to positive integers.
If the input n is not a positive number (e.g., 0 or a negative number), the function prints an error message and exits using return.

3. Start the Sequence
print(f"Starting number: {n}")
Prints the starting number to indicate the beginning of the Collatz sequence.

4. Collatz Algorithm
while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1
    print(n, end=" ")
while n != 1:

The loop runs until the number n becomes 1.
if n % 2 == 0:

Checks if n is even. If true, divide n by 2 (n = n // 2).
else:

If n is odd, apply the formula 3 * n + 1.
print(n, end=" "):

Prints the value of n after each step.
end=" " ensures all numbers are printed on the same line, separated by spaces.

5. Reached the End
print("\nReached 1!")
Once the loop ends (i.e., n == 1), this message is printed.

Error Handling
try:
    number = int(input("Enter a positive integer to test the Collatz conjecture: "))
    collatz_conjecture(number)
except ValueError:
    print("Invalid input! Please enter a valid integer.")

try-except Block:
Handles errors if the user enters invalid input (e.g., letters or symbols instead of numbers).
int(input()):
Prompts the user to enter a number and converts it to an integer.

ValueError:
If the user enters non-numeric input, Python raises a ValueError.
The program catches this error and prints an error message.

Python Coding challenge - Day 16 | What is the output of the following Python Code?

 


Explanation:

The .istitle() method:

This method checks whether a string follows title case formatting.

A string is considered title case if:

The first character of each word is uppercase.

All other characters in each word are lowercase.

Words are separated by non-alphanumeric characters (like spaces, punctuation, or special symbols).

Breaking down the input string:

'Hello!2@#World' is split into words at non-alphanumeric boundaries.

The "words" identified in this string are:

'Hello' (first character uppercase, rest lowercase → valid title case).

'World' (first character uppercase, rest lowercase → valid title case).

Special characters and numbers:

Special characters (!2@#) are ignored in determining title case.

As long as the alphanumeric words follow the title case rules, .istitle() will return True.

Why the result is True:

The string 'Hello!2@#World' meets the criteria for title case:

The two words (Hello and World) follow title case rules.

Non-alphanumeric characters and numbers do not break the title case structure.

Final Output:

True

Python Coding challenge - Day 15 | What is the output of the following Python Code?

 


Code Explanation:

The copy method:

a.copy() creates a shallow copy of the list a.

A shallow copy means that a new list object is created, but the elements inside the list (if mutable) are not deeply copied.

The is operator:

is checks for object identity, i.e., whether two variables refer to the same object in memory.

What happens here:

a and b are two distinct list objects in memory because a.copy() created a new list.

Even though the contents of the two lists are the same, they are not the same object.

Verification:

print(a == b) would return True because == checks for value equality, and both lists contain the same elements.

print(a is b) returns False because they are two different objects in memory.

Final Output:

False

Friday, 20 December 2024

Tic Tac Toe Game using Gui

 


import tkinter as tk

from tkinter import messagebox


def check_winner():

    """Checks if there is a winner or if the game is a draw."""

    for row in board:

        if row[0]["text"] == row[1]["text"] == row[2]["text"] != "":

            return row[0]["text"]


    for col in range(3):

        if board[0][col]["text"] == board[1][col]["text"] == board[2][col]["text"] != "":

            return board[0][col]["text"]


    if board[0][0]["text"] == board[1][1]["text"] == board[2][2]["text"] != "":

        return board[0][0]["text"]


    if board[0][2]["text"] == board[1][1]["text"] == board[2][0]["text"] != "":

        return board[0][2]["text"]


    if all(board[row][col]["text"] != "" for row in range(3) for col in range(3)):

        return "Draw"


    return None


def on_click(row, col):

    """Handles button click events."""

    global current_player


    if board[row][col]["text"] == "":

        board[row][col]["text"] = current_player

        winner = check_winner()


        if winner:

            if winner == "Draw":

                messagebox.showinfo("Game Over", "It's a draw!")

            else:

                messagebox.showinfo("Game Over", f"Player {winner} wins!")

            reset_board()

        else:

            current_player = "O" if current_player == "X" else "X"


def reset_board():

    """Resets the game board for a new game."""

    global current_player

    current_player = "X"

    for row in range(3):

        for col in range(3):

            board[row][col]["text"] = ""


# Create the main window

root = tk.Tk()

root.title("Tic-Tac-Toe")


# Initialize variables

current_player = "X"

board = [[None for _ in range(3)] for _ in range(3)]


# Create the game board (3x3 buttons)

for row in range(3):

    for col in range(3):

        button = tk.Button(

            root, text="", font=("Helvetica", 20), height=2, width=5,

            command=lambda r=row, c=col: on_click(r, c)

        )

        button.grid(row=row, column=col)

        board[row][col] = button


# Run the application

root.mainloop()


Thursday, 19 December 2024

Python Coding challenge - Day 14| What is the output of the following Python Code?

 


Explanation:

1. Creating a List
x = [1, 2, 3]
A list x is created with elements [1, 2, 3].
This creates an object in memory, and the variable x refers to that object.

2. Assigning y = x
y = x
Here, y is assigned the same reference as x.
Both x and y now refer to the same object in memory.
No new object is created during this assignment.
3. Checking Identity with is
print(x is y)
The is operator checks if two variables refer to the same object in memory.
Since y is assigned directly to x, they share the same memory reference.
The result of x is y is True.

Key Concepts
1. Object Identity (is)
is:
Checks if two variables point to the same object in memory.
It does not compare the values of the objects.

2. Example of is vs ==
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y)  # True: Values of x and y are the same.
print(x is y)  # False: x and y are different objects in memory.
== checks for value equality, while is checks for object identity.

3. Shared Reference
Since x and y point to the same object, changes to the list through one variable affect the other:
x = [1, 2, 3]
y = x
x.append(4)
print(y)  # Output: [1, 2, 3, 4]

Output
True

Python Coding challenge - Day 13| What is the output of the following Python Code?



 


Code Explanation:

1. Creating Sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set1: Contains the elements {1, 2, 3, 4, 5}.
set2: Contains the elements {4, 5, 6, 7, 8}.

Sets in Python:
Unordered collections of unique elements.
Duplicate elements are not allowed.
Supports set operations like union, intersection, difference, etc.

2. Using difference()
result = set1.difference(set2)
The difference() method finds elements that are in set1 but not in set2.
It compares set1 and set2 element by element:
In set1 but not in set2: {1, 2, 3}.

Shared elements: {4, 5} (ignored in the result).
Only in set2: {6, 7, 8} (irrelevant for this operation).

Result:
result = {1, 2, 3} (a new set containing only the unique elements from set1 that are not in set2).

3. Output (if printed)
If you add:
print(result)

The output would be:
{1, 2, 3}

Day 47: Python Program to Set Bit of an Integer




def count_set_bits(n):

    count=0

    while n > 0:

        count += n & 1

        n >>= 1

        return count

num=int(input("Enter an integer"))

print(f"The number of set bits in {num}is{count_set_bits(num)}.")

#source code --> clcoding.com 

 Code Explanation:

Function: count_set_bits
def count_set_bits(n):
    count = 0
    while n > 0:
        count += n & 1
        n >>= 1
        return count

Initialization:
count = 0: Initializes a variable count to store the number of set bits.

Logic:
n & 1: This operation checks if the least significant bit (LSB) of n is 1.
& is a bitwise AND operator. It returns 1 only if both corresponding bits are 1.
For example:
5 (binary: 101) & 1 (binary: 001) = 1 (LSB is 1).
4 (binary: 100) & 1 (binary: 001) = 0 (LSB is 0).
count += n & 1: Adds 1 to count if the LSB of n is 1.
n >>= 1: Right-shifts n by 1 bit to examine the next bit.
For example:
If n = 5 (binary: 101), n >> 1 = 2 (binary: 10).
If n = 2 (binary: 10), n >> 1 = 1 (binary: 1).

Loop Condition:
The loop continues as long as n > 0, meaning there are more bits to check.
Return Value:
The function returns count, which is the total number of set bits in the binary representation of n.
num = int(input("Enter an integer"))
Prompts the user to input an integer (num).
Converts the input string to an integer using int().
print(f"The number of set bits in {num} is {count_set_bits(num)}.")
Calls the count_set_bits function with num as input.
Prints the number of set bits.

Input:
Enter an integer: 5
Execution of count_set_bits(5)
Initial value: n = 5 (binary: 101), count = 0.

First iteration:
n & 1: 101 & 001 = 1 (LSB is 1).
count += 1: count = 1.
n >>= 1: n = 2 (binary: 10).

Second iteration:
n & 1: 10 & 01 = 0 (LSB is 0).
count = 1 (no increment).
n >>= 1: n = 1 (binary: 1).

Third iteration:
n & 1: 1 & 1 = 1 (LSB is 1).
count += 1: count = 2.
n >>= 1: n = 0 (loop exits).
Return count = 2.

Output:
The number of set bits in 5 is 2.

Day 46: Python Program to Swap Two Numbers Without Using The Third Variable

 

def swap_numbers(a, b):

    a = a + b

    b = a - b

    a = a - b

    return a, b

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

b = int(input("Enter the second number: "))

a, b = swap_numbers(a, b)

print(f"After swapping: First number = {a} and Second number = {b}")

#source code --> clcoding.com 

Code Explanation:

Function: swap_numbers
def swap_numbers(a, b):
    a = a + b
    b = a - b
    a = a - b
    return a, b
Purpose: This function swaps the values of a and b using arithmetic operations.
Process:
a = a + b: The sum of a and b is stored in a.
b = a - b: The new value of b becomes the original value of a.
a = a - b: The new value of a becomes the original value of b.

Return Value: The function returns the swapped values of a and b.

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
Input:
Prompts the user to enter two integers (a and b).
Converts the inputs into integers using int().
a, b = swap_numbers(a, b)

Function Call: Passes the user-provided values of a and b to the swap_numbers function.
Result: After the function executes, the values of a and b are swapped.

print(f"After swapping: First number = {a} and Second number = {b}")

Output: 
Prints the swapped values of a and b.

Python Coding Challange - Question With Answer(01201224)

 


What will be the output of the following code?

import numpy as np
arr = np.array([1, 2, 3, 4])
result = arr * arr[::-1]
print(result)


[1, 4, 9, 16]
[4, 6, 6, 4]
[4, 6, 6]
[4, 4, 4, 4]

Step 1: Create the NumPy array

The line:

arr = np.array([1, 2, 3, 4])

creates a 1D NumPy array:

arr = [1, 2, 3, 4]

Step 2: Reverse the array using arr[::-1]

The slicing operation arr[::-1] reverses the array:


arr[::-1] = [4, 3, 2, 1]

Step 3: Element-wise multiplication

In NumPy, when you multiply two arrays of the same shape, the multiplication is element-wise. This means each element in one array is multiplied by the corresponding element in the other array.


result = arr * arr[::-1]

Here:

arr = [1, 2, 3, 4]
arr[::-1] = [4, 3, 2, 1]

Performing the element-wise multiplication:

result = [1*4, 2*3, 3*2, 4*1]
= [4, 6, 6, 4]

Step 4: Print the result

Finally:

print(result)

outputs:

[4, 6, 6, 4]

Key Points:

  1. arr[::-1] reverses the array.
  2. Element-wise operations are default behavior in NumPy when performing arithmetic on arrays of the same size.
  3. The multiplication here computes each element as arr[i] * arr[len(arr)-i-1]

Python Tips of the day - 19122024

 


Python Tip: Use List Comprehensions for Simplicity

When working with lists in Python, you’ll often find yourself creating a new list by performing some operation on each element of an existing iterable, such as a list or range. While you can use a traditional for loop to achieve this, Python offers a cleaner and more concise way: list comprehensions.

The Traditional Way: Using a for Loop

Here’s how you might traditionally create a list of squares using a for loop:

# The traditional way
result = []
for x in range(10):
      result.append(x**2)

In this code:

  • An empty list, result, is initialized.

  • A for loop iterates through numbers from 0 to 9 (using range(10)).

  • Each number, x, is squared (x**2) and appended to the result list.

While this code works, it’s somewhat verbose and introduces multiple lines of code for a simple operation.

The Pythonic Way: Using List Comprehensions

With a list comprehension, you can achieve the same result in a single, elegant line of code:

# The Pythonic way
result = [x**2 for x in range(10)]

How It Works:

The syntax of a list comprehension is:

[expression for item in iterable]

Breaking it down for our example:

  • Expression: x**2 – This is the operation applied to each item in the iterable.

  • Item: x – Represents each value in the iterable.

  • Iterable: range(10) – Generates numbers from 0 to 9.

For each number in the range, Python calculates x**2 and adds it to the resulting list, all in a single line.

Comparing the Outputs

Both methods produce the same result:

print(result) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Why Use List Comprehensions?

  1. Conciseness: List comprehensions reduce multiple lines of code to a single line, making your code shorter and easier to read.

  2. Readability: Once you’re familiar with the syntax, list comprehensions are more intuitive than traditional loops.

  3. Performance: List comprehensions are generally faster than for loops because they are optimized at the C level in Python.

Advanced Example: Adding Conditions

You can enhance list comprehensions by adding conditional statements. For example, to include only the squares of even numbers:

result = [x**2 for x in range(10) if x % 2 == 0]
print(result) # Output: [0, 4, 16, 36, 64]

Here:

  • The condition if x % 2 == 0 filters the numbers, including only those divisible by 2.

Practical Applications

List comprehensions are not just limited to simple operations. Here are a few practical examples:

1. Convert Strings to Uppercase

words = ['hello', 'world']
uppercase_words = [word.upper() for word in words]
print(uppercase_words) # Output: ['HELLO', 'WORLD']

2. Flatten a Nested List

nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [num for sublist in nested_list for num in sublist]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]

3. Generate a List of Tuples

pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)
# Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Conclusion

List comprehensions are a powerful tool in Python that make your code more concise, readable, and efficient. Whenever you find yourself writing a loop to create a list, consider using a list comprehension instead. It’s one of the many features that makes Python both elegant and practical.

Intermediate Selenium WebDriver and Automation

 


In today’s fast-paced software development environment, automation testing is no longer a luxury but a necessity. With increasing competition and user expectations for flawless digital experiences, ensuring the reliability of web applications has become a critical priority. Selenium WebDriver, a powerful tool for web application testing, has emerged as a cornerstone for modern quality assurance engineers and developers.

However, mastering Selenium WebDriver requires more than just understanding the basics. To create robust, efficient, and scalable automation frameworks, professionals need to delve into advanced techniques and real-world applications. This is where the Intermediate Selenium WebDriver and Automation course on Coursera, offered by Packt Publishing, comes into play.

This course is a meticulously designed learning journey that bridges the gap between foundational knowledge and expert-level proficiency. Whether you are looking to tackle dynamic web elements, optimize your test execution, or integrate Selenium with other essential tools, this course equips you with the skills to succeed.

Course Overview

The "Intermediate Selenium WebDriver and Automation" course is tailored for individuals who already have a basic understanding of Selenium and are ready to explore its more advanced functionalities. It’s a structured, hands-on program that delves into sophisticated concepts, enabling learners to manage complex automation challenges effectively.

Key Features of the Course

Platform: Coursera, known for its diverse range of professional courses.

Provider: Packt Publishing, a trusted name in tech education.

Level: Intermediate, ideal for those with prior Selenium experience.

Duration: Flexible pacing, allowing you to learn at your convenience.

Focus Areas: Advanced Selenium techniques, real-world scenarios, integration with tools, and best practices in test automation.

Who Should Take This Course?

This course is suitable for:

Quality Assurance Engineers: QA professionals looking to refine their automation skills to tackle more complex testing scenarios.

Developers: Software engineers who want to incorporate automated testing into their development workflows.

Students and Career Changers: Individuals transitioning into a testing role or expanding their skill set in software quality assurance.

Prerequisites

To maximize your learning experience, you should have:

A foundational understanding of Selenium WebDriver.

Basic knowledge of programming languages like Java, Python, or C#.

Familiarity with web technologies such as HTML, CSS, and JavaScript.

What you'll learn

  • Understand the installation and configuration of Selenium WebDriver for multiple browsers
  • Apply skills to automate web tests across different operating systems
  • Analyze and locate web elements using advanced XPath and CSS Selectors
  • Evaluate and implement efficient wait strategies for reliable test execution

Why Choose This Course?

1. Industry-Relevant Content

Packt Publishing’s courses are crafted by experts with real-world experience. This course not only teaches theory but emphasizes practical, applicable skills that can be directly implemented in your projects.

2. Hands-On Learning

The course includes extensive hands-on exercises and assignments. These practical components ensure you’re not just learning concepts but actively applying them to build expertise.

3. Flexible Learning

Coursera’s platform allows you to learn at your own pace, making it ideal for busy professionals. You can revisit modules, replay lectures, and practice as needed.

4. Career Boost

With Selenium being one of the most sought-after skills in the QA and development domains, this course can significantly enhance your career prospects. Whether you’re aiming for a promotion, transitioning to automation, or simply staying competitive, this course is a valuable asset.

Future Enhancements for the Course

To remain at the forefront of automation testing education, here are potential enhancements for the "Intermediate Selenium WebDriver and Automation" course:

Inclusion of AI-Powered Testing Tools:

Covering AI-driven tools like Testim or Applitools for smarter test generation and visual testing.

Advanced Debugging Techniques:

Modules on leveraging machine learning for log analysis and bug prediction.

Cloud-Based Test Execution:

Detailed insights into running tests on cloud platforms like AWS Device Farm or Azure DevOps.

Integration with DevOps Ecosystem:

Enhanced focus on integrating Selenium tests into comprehensive DevOps workflows.

Support for Emerging Frameworks:

Tutorials on using Selenium with modern web frameworks like Angular, React, or Vue.js.

Interactive Community Features:

Creating a collaborative space for learners to share their projects and solve challenges together.

Expanded Real-World Scenarios:

Additional case studies and exercises reflecting cutting-edge industry practices.

Video Tutorials on Advanced Concepts:

Step-by-step walkthroughs of complex Selenium setups and configurations.

How to Get the Most Out of This Course

Brush Up on Basics: Before starting, ensure you’re comfortable with Selenium basics and your chosen programming language.

Engage Actively: Participate in quizzes, assignments, and discussion forums to reinforce your learning.

Build Projects: Use the knowledge gained to create your own automation projects, experimenting with new tools and frameworks.

Leverage Additional Resources: Complement the course material with books, blogs, and the official Selenium documentation.

Join Free: Intermediate Selenium WebDriver and Automation

Conclusion:

Automation testing is a cornerstone of modern software development, and mastering it can unlock countless opportunities. The "Intermediate Selenium WebDriver and Automation" course on Coursera stands out as an excellent resource for those looking to elevate their skills.

With a focus on advanced techniques, integration, and practical applications, this course equips you to tackle real-world challenges confidently. Whether you’re enhancing your current skills or paving the way for a new career direction, this course is a step in the right direction.


Python Coding Challange - Question With Answer(01191224)

 


What does the following Python code do?

arr = [10, 20, 30, 40, 50]
result = arr[1:4]
print(result)

[10, 20, 30]
[20, 30, 40]
[20, 30, 40, 50]
[10, 20, 30, 40]

Step 1: Understand arr[1:4]

The slicing syntax arr[start:end] extracts a portion of the list from index start to end-1.

  • start (1): This is the index where slicing begins (inclusive).
  • end (4): This is the index where slicing ends (exclusive).

Step 2: Index Positions in the Array

The array arr is:


Index: 0 1 2 3 4
Values: [10, 20, 30, 40, 50]
  • start = 1: The slicing starts at index 1, which is 20.
  • end = 4: The slicing stops before index 4, so it includes elements up to index 3 (40).

The sliced portion is:


[20, 30, 40]

Step 3: Assigning to result

The sliced subarray [20, 30, 40] is stored in result.


Step 4: Printing the Result

When you print result, the output is:


[20, 30, 40]

Key Takeaways:

  1. Slicing includes the start index but excludes the end index.
    So arr[1:4] includes indices 1, 2, and 3 but not 4.
  2. The result is [20, 30, 40], the portion of the array between indices 1 and 3.


Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) 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&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (364) Python Quiz (25) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

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