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.

Program to Left Rotate an Array by K Places.

Given an integer array arr[] of size n, the task is to rotate the array to the left by K steps, where K is a non-negative number.

Example:

Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}  K = 3
Output: arr[] = {4, 5, 6, 7, 8, 1, 2, 3}

Input: arr[] = {4, 6, 1, 5, 2, -2}  k = 2
Output: arr[] = {1, 5, 2, -2, 4, 6}

There are multiple approaches to rotating an array and here we are going to discuss each of them one by one in detail.
Key Note: When the number of rotations (K) is greater than the size of the array (n) for a left rotation, we can handle it by taking the effective number of rotations, which is K % n. This is because, after every n rotation, the array comes back to its original position. So, rotating by K % n is equivalent to rotating by K. (alert-passed)


Approach 1: Brute Force Approach.

This approach takes a straightforward but less efficient approach. It involves repeatedly shifting the entire array to the left by one position K times. While conceptually simple, this method has a time complexity of O(n * k), making it less suitable for large arrays or a high number of rotations.

Step-by-step algorithm:
  • Store the first element in a temporary variable.
  • Shift all elements in the array to the left by one position.
  • Place the temporary variable at the end of the array.
  • Repeat steps 1-3 for K times.

Below is the C++ code implementation of the above approach:
// C++ code to left rotate array by k position 
#include <iostream>
using namespace std;

// function to left rotate an array
void rotateLeftBruteForce(int arr[], int n, int k) {
    for (int i = 0; i < k; ++i) {
        int temp = arr[0];
        for (int j = 1; j < n; ++j) {
            arr[j - 1] = arr[j];
        }
        arr[n - 1] = temp;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;

    rotateLeftBruteForce(arr, n, k);

    // Print the rotated array
    for (int i = 0; i < n; ++i) {
        cout << arr[i] << " ";
    }

    return 0;
}
Output:
3 4 5 6 7 1 2
  • Time Complexity: O(n * k) where n is the number of elements present in the array and k is the number of position the array need to be rotated.
  • Space Complexity: O(1) no extra space is required to solve this problem using the above approach.

Approach 2: Using Extra Space.

In this approach, an auxiliary array is utilized to store the first K elements of the original array. The remaining elements are then shifted to the left in the original array, and the elements from the auxiliary array are placed at the end.

Step-by-step algorithm:
  • Create an auxiliary array of size K.
  • Copy the first K elements of the original array to the auxiliary array.
  • Shift the remaining elements in the original array to the left by K positions.
  • Copy the elements from the auxiliary array to the end of the original array.

Below is the C++ code implementation for the above approach:
// C++ code to left rotate an array using extra space
#include <iostream>
using namespace std;

void rotateLeftExtraArray(int arr[], int n, int k) {
    // Check for the case where k is greater than n
    k = k % n;

    // Create an auxiliary array
    int temp[k];

    // Copy the first k elements to the auxiliary array
    for (int i = 0; i < k; ++i) {
        temp[i] = arr[i];
    }

    // Shift the remaining elements 
    // in the original array to the left
    for (int i = k; i < n; ++i) {
        arr[i - k] = arr[i];
    }

    // Copy the elements from the auxiliary array 
    // to the end of the original array
    for (int i = 0; i < k; ++i) {
        arr[n - k + i] = temp[i];
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;

    rotateLeftExtraArray(arr, n, k);

    // Print the rotated array
    for (int i = 0; i < n; ++i) {
        cout << arr[i] << " ";
    }

    return 0;
}
Output:
4 5 6 7 1 2 3
  • Time Complexity: O(n) where n is the number of elements present in the array and k is the number of position the array need to be rotated.
  • Space Complexity: O(k) k is the size of an auxiliary array that is used in the above algorithm to rotate the array.

Approach 3: Reversal Algorithm.

The Reversal Algorithm reverses specific segments of the array to achieve rotation. First, it reverses the first K elements, then the remaining elements, and finally the entire array. 

Step-by-step algorithm:
  • Reverse the first K elements of the given array.
  • Reverse the remaining elements of the given array.
  • Reverse the entire array.
Illustration:
Reversal Algorithm to Rotate an Array
Below is the C++ code implementation for the above approach:
// C++ code to left rotate an array using reversal method
#include <iostream>
using namespace std;

// function to reverse array
void reverseArray(int arr[], int start, int end) {
    while (start < end) {
        std::swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}

// function to left rotate array
void rotateLeftReversal(int arr[], int n, int k) {
    // Check for the case where k is greater than n
    k = k % n;

    // Reverse the first k elements
    reverseArray(arr, 0, k - 1);

    // Reverse the remaining elements
    reverseArray(arr, k, n - 1);

    // Reverse the entire array
    reverseArray(arr, 0, n - 1);
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;

    rotateLeftReversal(arr, n, k);

    // Print the rotated array
    for (int i = 0; i < n; ++i) {
        cout << arr[i] << " ";
    }

    return 0;
}
Output:
4 5 6 7 1 2 3
  • Time Complexity: O(n) where n is the number of elements present in the array and k is the number of position the array need to be rotated.
  • Space Complexity: O(1) as no extra space is required to resolve the problem.

Approach 4: Juggling Algorithm.

The Juggling Algorithm is an optimization over the reversal method. It uses the concept of finding the greatest common divisor (gcd) of n and k. It then iterates through sets of elements that need to be rotated together, reducing the number of swaps needed.

Step-by-step algorithm:
  • Find the greatest common divisor (gcd) of n and k.
  • Iterate through each set of elements that need to be rotated together.
  • Use temporary variables to swap elements within each set.

Below is the C++ code implementation for the above approach:
// C++ code to rotate array using juggling algorithm
#include <iostream>
using namespace std;

// function to find gcd
int gcd(int a, int b) {
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}

// function to left rotate array
void rotateLeftJuggling(int arr[], int n, int k) {
    // Check for the case where k is greater than n
    k = k % n;

    // Find the greatest common divisor (gcd) of n and k
    int sets = gcd(n, k);

    for (int i = 0; i < sets; ++i) {
        int temp = arr[i];
        int j = i;

        while (true) {
            int d = (j + k) % n;
            if (d == i) {
                break;
            }
            arr[j] = arr[d];
            j = d;
        }

        arr[j] = temp;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;

    rotateLeftJuggling(arr, n, k);

    // Print the rotated array
    for (int i = 0; i < n; ++i) {
        cout << arr[i] << " ";
    }

    return 0;
}
Output:
4 5 6 7 1 2 3
  • Time Complexity: O(n) where n is the number of elements present in the array and k is the number of position the array need to be rotated.
  • Space Complexity: O(1) as no extra space is required.

These are the few algorithms to left rotate an array by K position and you can choose one which is best for your requirement.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson