Python Program to Check Leap Year.

A leap year is a year that is one day longer than a standard year, containing an additional day to keep the calendar year synchronized with the astronomical or seasonal year. This extra day, February 29th, is added every four years to ensure that the calendar year remains close to the length of the solar year.


Problem Statement: Write a Python program to determine if a given year is a leap year or not.

Example:

Input: 2000
Output: 2000 is a Leap Year

Input: 2021
Output: 2021 is not a Leap Year

Process to Find Leap Year in Python.

Below are the steps that you can follow to check if the given year is a leap year or not:
  • STEP 1: Take a year as input from the user.
  • STEP 2: Check if the year is divisible by 4, then move to the next step. If the year is not divisible by 4 then the year is not a Leap Year.
  • STEP 3: Check if the year is divisible by 100, then move to the next step. If the year is divisible by 4 but not divisible by 100 then the year is not a Leap Year.
  • STEP 4: Check if the year is divisible by 400, then the year is a Leap Year. If the year is divisible by 100 but not divisible by 400 then it is not a Leap Year.

Example:
  • The year 2000 was a leap year because it is divisible by 4 and 400.
  • The year 1900 was not a leap year because, while divisible by 4, it is also divisible by 100 and not by 400.

Python Program to Find Leap Year.

# Function to check leap year
def is_leap_year(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        print(f"{year} is a leap year.")
    else:
        print(f"{year} is not a leap year.")

# Input
year = int(input("Enter a year: "))

# Check and display result
is_leap_year(year)
Output:
Enter a year: 2000
2000 is a leap year.

Explanation:
In the above Python code, the is_leap_year function takes a year as an argument. It checks if the year is divisible by 4 but not by 100, or if it is divisible by 400. If either condition is true, it prints that the year is a leap year; otherwise, it prints that it's not.


Python Program to Check If a Number is Even or Odd.

Problem Statement: Write a Python program that checks whether a given integer is even or odd.

Example:
Input: number = 7
Output: 7 is Odd Number

Input: number = 10
Output: 10 is Even Number

Algorithm to Check Even or Odd Number.

STEP 1: Accept an integer as input from the user.
STEP 2: Use the modulo operator (%) to check if the number is divisible by 2.
  • If the result is 0, the number is even.
  • If the result is 1, the number is odd.
STEP 3: Print the result in output.

Python Code to check Even or Odd Numbers:
# Function to check even or odd
def check_even_odd(num):
    if num % 2 == 0:
        print(f"{num} is an even number.")
    else:
        print(f"{num} is an odd number.")

# Input
number = int(input("Enter an integer: "))

# Check and display result
check_even_odd(number)
Output:
Enter an integer: 12
12 is an even number.

Explanation:
In the above example, the check_even_odd function takes an integer as an argument and uses the modulo operator to check if it's divisible by 2. If the result is 0, it prints that the number is even; otherwise, it prints that the number is odd.

Python Program to Generate Random Number.

Random numbers are essential in various applications, from simulations to cryptography. In Python, the random module provides functions for generating random numbers. The random module uses algorithms to produce pseudo-random numbers, which are deterministic but appear random.


Generating Random Number in Python.

The random module provides several functions for generating random numbers:

  • random(): Returns a random floating-point number in the range [0.0, 1.0).
  • randrange(start, stop, step): Returns a randomly selected element from the specified range.
  • randint(a, b): Returns a random integer between a and b (inclusive).
  • uniform(a, b): Returns a random floating-point number in the range [a, b).
  • choice(seq): Returns a randomly selected element from the given sequence.

Python Code Implementation.

# Python code to generate random number
import random

# Generate a random floating-point number between 0 and 1
random_float = random.random()
print("Random Float:", random_float)

# Generate a random integer between 1 and 10
random_int = random.randint(1, 10)
print("Random Integer:", random_int)

# Generate a random element from a sequence
my_list = [1, 2, 3, 4, 5]
random_element = random.choice(my_list)
print("Random Element:", random_element)
Output:
Random Float: 0.5481041832741018
Random Integer: 3
Random Element: 2
Note: Pseudo-random numbers are generated using algorithms and depend on an initial seed value. To produce different sequences of random numbers, you can change the seed using random.seed(). (alert-passed)

Now I hope you understand the process of generating random numbers in Python. Generating random numbers is crucial for applications involving simulations, games, or any scenario where unpredictability is needed. The random module in Python simplifies the process of incorporating randomness into your programs.

Python Program to Swap Two Variables.

Write a Python program that swaps the values of two variables. For example, if a = 5 and b = 10, after swapping, a should be 10 and b should be 5. This simple task is useful in various algorithms and programming scenarios.


There are multiple ways to swap two variables, let's discuss each of them one by one:


Approach 1: Using a Temporary Variable.

The first approach uses a temporary variable to store one of the values, allowing us to perform the swap.

Step-by-step Algorithm:

  • Store the value of an in a temporary variable (temp).
  • Assign the value of b to a.
  • Assign the value of temp to b.

Python Code Implementation.

# Python program to swap two variables using temp variable
# Before swapping
a = 5
b = 10
print(f"Before swapping: a = {a}, b = {b}")

# Swap logic
temp = a
a = b
b = temp

# After swapping
print(f"After swapping: a = {a}, b = {b}")
Output:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

Approach 2: Without Using a Temporary Variable.

The second approach swaps values without using a temporary variable, using arithmetic operations.

Step-by-step Algorithm:
  • Add the values of a and b and store the result in a.
  • Subtract the original value of a (now stored in b) from a.
  • Subtract the original value of b from a to get the original value of a in b.

Python Code Implementation.

# Python program to swap two variables
a = 5
b = 10
print(f"Before swapping: a = {a}, b = {b}")

# Without using a temporary variable
a = a + b
b = a - b
a = a - b

# After swapping
print(f"After swapping: a = {a}, b = {b}")
Output:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

Approach 3: Using Tuple Unpacking.

The third approach leverages the Pythonic way of swapping values using tuple unpacking.

Step-by-step Algorithm:
  • Create a tuple with the values of a and b.
  • Unpack the tuple into variables a and b.

Python Code Implementation.

# Python program to swap two variables using tuple
a = 5
b = 10
print(f"Before swapping: a = {a}, b = {b}")

# Using tuple unpacking
a, b = b, a

# After swapping
print(f"After swapping: a = {a}, b = {b}")
Output:
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

These are a few ways to swap two variables you can choose any method based on your requirements and convenience.

Python Program to Find Square Root of Number.

Calculating the square root of a number is a common mathematical operation. In Python, there are multiple ways to find the square root, offering flexibility based on the requirements of your program. In this article, we have discussed different approaches to calculating the square root of a given number.


Problem Statement: Write a Python program to find the square root of a given number.


Approach 1: Using the ** operator.

In Python, the ** operator is used for exponentiation, meaning it raises the left operand to the power of the right operand.


Below are the steps of the Algorithm to follow:

  • STEP 1: Take user input for the number.
  • STEP 2: Calculate the square root using the ** operator.
  • STEP 3: Display the result.

Python Code Implementation.

# Python Program to Find Square Root of a Number using ** Operator

number = float(input("Enter a number: "))

# Calculate square root
result = number ** 0.5

print(f"The square root of {number} is {result}")
Output:
Enter a number: 6
The square root of 6.0 is 2.449489742783178

Approach 2: Using the math.sqrt() Function.

The math.sqrt() function in Python is part of the math module and is used for finding the square root of a given number.

Below are the steps to follow:
  • STEP 1: Import the math module in code.
  • STEP 2: Take user input for the number.
  • STEP 3: Use the math.sqrt() function to calculate the square root.
  • STEP 4: Display the square root of the given number.

Python Code Implementation.

# Python Program to Find Square Root using math.sqrt()
import math

number = float(input("Enter a number: "))

#  Calculate square root
result = math.sqrt(number)

print(f"The square root of {number} is {result}")
Output:
Enter a number: 25
The square root of 25.0 is 5.0

Conclusion:

Both approaches provide a way to find the square root of a number in Python. The first approach uses the ** operator, and the second approach uses the math.sqrt() function. Choose the one that fits your coding style and requirements.

Python Program to Print 'Hello World'.

Python, known for its simplicity and readability, is an excellent language for beginners and professionals alike. One of the traditional first steps in learning any programming language is to write a program that prints "Hello, World!" to the console. In Python, achieving this is wonderfully straightforward.


Problem Statement: Write a Python program that prints the classic "Hello, World!" message to the console.


Python Code:

# Python Program to Print 'Hello, World!'
print("Hello, World!")
Output:
Hello, World!

Explanation: The print function is used to display text. In this case, it prints the string "Hello, World!" to the console.

You've just written and executed your first Python program. This simple exercise serves as a foundation for more complex programming concepts you'll encounter in your Python journey.

Related Articles:

Program to Find Union of Two Array.

Given two integer arrays, arr1[] and arr2[], the task is to find the union of the two arrays. The output should contain only distinct elements and the order of the elements in the output may vary. 

Union of Array.
The union of two arrays is defined as the set of distinct elements that are present in either of the arrays. The resulting array must contain only unique elements, and the order of elements in the output may vary.

Example:
Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {3, 4, 5, 6, 7}
Output: Union[] = {1, 2, 3, 4, 5, 6, 7}

Input: arr1[] = {4, 7, 9, 1}, arr2[] = {1, 5}
Output: Union[] = {1, 4, 5, 7, 9}

There are multiple methods to find the union of two arrays and here we are going to discuss a few of them in detail with code. 

Approach 1: Brute Force.

The brute force approach involves iterating through both arrays and checking for each element if it's already in the result array. If not, add it to the result. This method ensures that the result contains only unique elements.

Step-by-step Algorithm to find the Union of Two Arrays:
  • STEP 1: Initialize an empty result[] array.
  • STEP 2: Iterate through arr1[] and arr2[].
  • STEP 3: For each element, check if it is not already in the result array.
  • STEP 4: If not, add it to the result[] array.
  • STEP 5: The result array is the union of arr1[] and arr2[].

C++ Code Implementation.

// C++ code to find Union of two arrays
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// function to find union of two arrays
vector<int> findUnionOfArrays(vector<int>& arr1, vector<int>& arr2) {
    vector<int> result;
    
    //insert the elements which are not present in result array
    for (int num : arr1) {
        if (find(result.begin(), result.end(), num) == result.end()) {
            result.push_back(num);
        }
    }

    for (int num : arr2) {
        if (find(result.begin(), result.end(), num) == result.end()) {
            result.push_back(num);
        }
    }

    return result;
}


int main() {
    vector<int> arr1 = {4, 9, 5, 1, 0};
    vector<int> arr2 = {9, 4, 9, 8, 4, 1};

    vector<int> result = findUnionOfArrays(arr1, arr2);

    // Print the Union of Two Arrays 
    for (int i = 0; i < result.size(); ++i) {
        cout << result[i] << " ";
    }

    return 0;
}
Output:
4 9 5 1 0 8 
  • Time Complexity: O(m * n) where m and n are the sizes of arr1 and arr2.
  • Space Complexity: O(k) where k is the size of the result array.

Approach 2: Using Hash Map.

In this approach, we are using a Hash Map to keep track of unique elements.

Step-by-step to find the Union of Two Arrays.
  • STEP 1: Create a hash map to count occurrences of elements.
  • STEP 2: Iterate through arr1 and arr2, updating counts in the hash map.
  • STEP 3: Extract keys from the hash map to get the result.

C++ Code Implementation.

// C++ code to find Union of two arrays
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

// function to find union of two arrays
vector<int> findUnionUsingHashMap(vector<int>& arr1, vector<int>& arr2) {
    unordered_map<int, int> countMap;

    for (int num : arr1) {
        countMap[num]++;
    }

    for (int num : arr2) {
        countMap[num]++;
    }

    vector<int> result;
    // store all unique elements to resultant array
    for (const auto& entry : countMap) {
        result.push_back(entry.first);
    }

    return result;
}

int main() {
    vector<int> arr1 = {4, 9, 5, 1, 0};
    vector<int> arr2 = {9, 4, 9, 8, 4, 1};

    vector<int> result = findUnionUsingHashMap(arr1, arr2);

    // Print the Union of Two Arrays 
    for (int i = 0; i < result.size(); ++i) {
        cout << result[i] << " ";
    }

    return 0;
}
Output:
8 0 1 5 9 4 
  • Time Complexity: O(m + n) due to hash map operations.
  • Space Complexity: O(k) where k is the size of the result array.

Program to Find Intersection of Two Arrays.

Given two integer arrays arr1[] and arr2[], the task is to find the intersection of two given arrays. The resulting array must contain only unique elements and you may return the result in any order.

Example:

Input: arr1 = [1, 2, 2, 1], arr2 = [2, 2]
Output: [2]

Input: arr1 = [4, 9, 5], arr2 = [9, 4, 9, 8, 4]
Output: [9, 4]

Input: arr1 = [1, 2, 3, 4], arr2 = [5, 6, 7, 8]
Output: []

Note: The intersection of two arrays is the set of elements that are common to both arrays, without any duplicates.

There are many approaches to finding the intersection of two arrays and here we are going to discuss each approach in detail with code. 

Approach 1: Brute Force Approach.

This is a straightforward approach to find the intersection where each element in the first array (arr1) is checked against every element in the second array (arr2). If a match is found, the element is added to the result array.

Step-by-step Algorithm:
  • Initialize an empty array to store the result.
  • Iterate through each element in arr1[].
  • For each element in arr1[], check if it exists in arr2[].
  • If it does, add it to the result array.

C++ code Implementation.

// C++ code to find intersection of two array (Brute Force)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> intersectionArrays(vector<int>& arr1, vector<int>& arr2) {
    
    vector<int> result;

    for (int num1 : arr1) {
        // for each element of arr1 check if exist in arr2
        if (find(arr2.begin(), arr2.end(), num1) != arr2.end()) {
            result.push_back(num1);
        }
    }
    
    return result;
}


int main() {
    vector<int> arr1 = {4, 9, 5, 1};
    vector<int> arr2 = {9, 4, 9, 8, 4};

    vector<int> result = intersectionArrays(arr1, arr2);

    // Print the intersection array
    for (int i = 0; i < result.size(); ++i) {
        cout << result[i] << " ";
    }

    return 0;
}
Output:
4 9
  • Time Complexity: The worst-case time complexity is O(n^2) since, in the worst case, each element of arr1 needs to be compared with each element of arr2.
  • Space Complexity: O(m), where m is the number of elements in the result array.

Approach 2: Using Sorting.

This approach involves sorting both input arrays (arr1 and arr2). Then, two pointers traverse both arrays simultaneously, identifying common elements.

Step-by-step Algorithm:
  • Sort both arrays, arr1[], and arr2[].
  • Initialize pointers i and j to traverse arr1[] and arr2[], respectively.
  • Compare elements at indices i and j.
  • If the elements are equal, add the element to the result and move both pointers forward.
  • If the element at arr1[i] is smaller, move the i pointer forward; otherwise, move the j pointer forward.

C++ Code Implementation.

// C++ code to find intersection of two array
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// function to find intersection of arrays
vector<int> intersectionArrays(vector<int>& arr1, vector<int>& arr2) {
    vector<int> result;
    //sorting both the array
    sort(arr1.begin(), arr1.end());
    sort(arr2.begin(), arr2.end());
    
    int i = 0, j = 0;
    while (i < arr1.size() && j < arr2.size()) {
        if (arr1[i] == arr2[j]) {
            result.push_back(arr1[i]);
            i++;
            j++;
        } else if (arr1[i] < arr2[j]) {
            i++;
        } else {
            j++;
        }
    }
    return result;
}



int main() {
    vector<int> arr1 = {4, 9, 5, 1};
    vector<int> arr2 = {9, 4, 9, 8, 4};

    vector<int> result = intersectionArrays(arr1, arr2);

    // Print the intersection array
    for (int i = 0; i < result.size(); ++i) {
        cout << result[i] << " ";
    }

    return 0;
}
Output:
4 9
  • Time Complexity: O(n log n + m log m), where n and m are the sizes of arr1 and arr2, respectively, accounting for sorting.
  • Space Complexity: O(1) as no additional space is required except for pointers and the result array.

Approach 3: Using Hash Set.

In this approach, a hash set is employed to store unique elements from the first array (arr1). The second array (arr2) is then traversed, and common elements are added to the result array.

Step-by-step Algorithm:
  • Initialize an empty hash set to store unique elements from arr1[].
  • Iterate through arr1[] and add each element to the hash set.
  • Initialize an empty array to store the result.
  • Iterate through arr2[].
  • If an element in arr2[] is present in the hash set, add it to the result array.

C++ code Implementation.

// C++ code to find intersection of two array
// using hash table
#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;

// function to find intersection of arrays
vector<int> intersectionArrays(vector<int>& arr1, vector<int>& arr2) {
    //adding unique elements of arr1 to hash set
    unordered_set<int> set1(arr1.begin(), arr1.end());
    vector<int> result;
    
    for (int num : arr2) {
        if (set1.count(num)) {
            result.push_back(num);
            // To avoid duplicates in result
            set1.erase(num); 
        }
    }
    
    return result;
}

int main() {
    vector<int> arr1 = {4, 9, 5, 1, 0};
    vector<int> arr2 = {9, 4, 9, 8, 4, 1};

    vector<int> result = intersectionArrays(arr1, arr2);

    // Print the intersection array
    for (int i = 0; i < result.size(); ++i) {
        cout << result[i] << " ";
    }

    return 0;
}
Output:
4 9 1
  • Time Complexity: O(n + m), where n and m are the sizes of arr1 and arr2, respectively.
  • Space Complexity: O(1) as no additional space is required except for pointers and the result array.

All the above approaches have different space and time complexities so you can choose which one is best for you based on your requirement to find a common intersection of two arrays.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson