Python

Program to Find the Missing Number in an arraylist

Python Program to Find the Missing Number in an array/list

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Lists in Python:

Python contains a collection of built-in data types that make typical data-wrangling tasks simple. The list is one of them, a simple but useful collection type. A Python list allows you to collect Python objects in a one-dimensional row that may be accessed by position, added, removed, sorted, and subdivided.

Find the missing number in an array/list of n-1 different numbers in the range of 1 to n in linear time in Python.

Examples:

Example1:

Input:

given list= [ 1 ,3 ,2 , 6 , 5 ]

Output:

The missing number in the given list 4

Example2:

Input:

given list= [ 1 , 9 , 2 ,3 , 5 , 4 , 6 , 7 ]

Output:

The missing number in the given list 8

Program to Find the Missing Number in an array/list in Python

There are several to find the missing number in an array/list in python but to do the same thing in linear time we use either mathematical formula or bit manipulation techniques like below.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using mathematical formula

Approach:

The array’s length is n-1. So, using the formula n*(n+1)/2, the sum of all n elements, i.e. the sum of numbers from 1 to n, can be determined.

The aim is to use the above formula to find the sum of integers between 1 and n+1, where is the size of the array. Calculate the real sum of the integers in the array as well. The difference between the two is now the missing number.

Algorithm:

  • Calculate the length of the array and take a variable to store it say n.
  • Sum the first n natural numbers as totalSum= n*(n+1)/2
  • To hold the sum of array elements, create a variable arraySum.
  • Traverse the array from beginning to end.
  • Sum should be updated as= arraySum+ array[i].
  • Print the missing number as totalSum– arraySum

Below is the implementation:

def findMissingNumb(given_list):

    # calculating the length of the given list
    n = len(given_list)

    # Because a number is missing from the list, the real size is n+1.
    length = n + 1

    # Getting sum of all numbers from 1 to length using mathematical formula
    totalSum = length * (length + 1) / 2
    # calculating the sum of all elements in the given list
    # initializing a variable to store arraysum as 0
    arraysum = 0
    # Traversing the list
    for ele in given_list:
        arraysum = arraysum+ele

    # The difference between the totalsum and arraysum
    # of the integers in the list is the missing number.
    # missing number
    missnum = totalSum-arraysum
    # reeturn the missing number
    return int(missnum)


# Driver code
# given list
given_list = [1, 3, 2, 6, 5]
# passing the given list to findMissingNumb  to print the missing number

print("The missing number in the given list", findMissingNumb(given_list))

Output:

The missing number in the given list 4

Complexity Analysis of the above program:

Time Complexity: O(n)

Because only one traversal / one loop is needed

Space Complexity: O(1)

Because no extra space is needed

Method #2 : Using XOR (bitwise operator )

To overcome the problem, this method use the XOR technique.

Approach:
Certain properties are possessed by XOR like
Assume a1 ^ a2^a3… a^n = a and a1 ^a2^ a3… ^an-1 = b.
Consequently, a ^b = an

We know XOR cancels each other in equal numbers. This is something we can benefit from in the small range array for the missing number.
The aim is to calculate XOR for all items of the array and calculate XOR for all items from 1 through n+1. It is now the XOR between the two that is missing.

Algorithm:

  • Make two variables with the values a = 0 and b = 0.
  • Begin a loop from 1 to n, using i as the counter.
  • For each index, change a to a = a^ i.
  • Now iterate through the array from beginning to end.
  • Update b as b = b ^list[i] for each index.
  • The missing number should be printed as a^b.

Below is the implementation:

def findMissingNumb(given_list):
    # calculating the length of the given list
    n = len(given_list)
    # Calculating xor of all elements in the given list
    totalXor = 0
    # Traverse the given list
    for i in given_list:
        totalXor = totalXor ^ i
    # calculating xor of all elements from 1 to n+1
    # Compute XOR of all the elements from 1 to `n+1`
    for i in range(1, n + 2):
        totalXor = totalXor ^ i
    # initialize the missnum with the totalXor
    missNum = totalXor
    # return the missing number
    return missNum


# Driver code
# given list
given_list = [1, 3, 2, 6, 5]
# passing the given list to findMissingNumb  to print the missing number

print("The missing number in the given list", findMissingNumb(given_list))

Output:

The missing number in the given list 4

Complexity Analysis of the above program:

Time Complexity: O(n)

Because only one traversal / one loop is needed

Space Complexity: O(1)

Because no extra space is needed
Related Programs:

Python Program to Find the Missing Number in an array/list Read More »

Program to Read a List of Words and Return the Length of the Longest Word

Python Program to Read a List of Words and Return the Length of the Longest Word

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Given the list of words, the task is to write a python program that reads the list of words and prints the largest/longest words in the list.

Examples:

Example1:

Input:

given list of words = Hello this is BTechGeeks  online platform

Output:

Printing the longest length word :
BTechGeeks

Example2:

Input:

given list of words = Sky is pink

Output:

Printing the longest length word :
pink

Python Program to Read a List of Words and Return the Length of the Longest Word

There are several ways to read a list of words and return the length of the longest word some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Reading a list of words separated by a new line and comparing the length of words using if statement (User Input)

Approach:

  • Scan the number of elements/strings and store it in a variable
  • Using a for loop, accept the values into the list and put them into the list.
  • Assume that the first element is the one with the longest word.
  • The lengths of the words in the list are then compared with the first element using a for loop and an if statement.
  • In a temporary variable, save the name of the term with the longest length.
  • Print the word that has the longest length.
  • Exit of program

Below is the implementation:

# Taking a empty list
listWords = []
# scanning the number of strings
numb = int(input("enter the total number of strings :"))
# Using for loop
for i in range(numb):
    elem = input("enter some random string or word :\n")
    listWords.append(elem)
# taking the first element length as max length word
maxLength = len(listWords[0])
# Initializing a temp variable which stores the first word
word = listWords[0]
# Traversing the words list
for i in listWords:
    if(len(i) > maxLength):
        maxLength = len(i)
        word = i
print("Printing the longest length word :")
print(word)

Output:

enter the total number of strings :6
enter some random string or word :
hello
enter some random string or word :
this
enter some random string or word :
is
enter some random string or word :
BTechGeeks
enter some random string or word :
online
enter some random string or word :
platform
Printing the longest length word :
BTechGeeks

Method #2: Reading a list of words separated by space and comparing length of words using if statement (User Input)

Approach:

  • Scan the list of words separated by space.
  • Store the above string in the list using the split() function.
  • Assume that the first element is the one with the longest word.
  • The lengths of the words in the list are then compared with the first element using a for loop and an if statement.
  • In a temporary variable, save the name of the term with the longest length.
  • Print the word that has the longest length.
  • Exit of program

Below is the implementation:

# Taking a list of words in list using split
listWords = list(input("Enter the list of words / enter the sentence\n").split())
# taking the first element length as max length word
maxLength = len(listWords[0])
# Initializing a temp variable which stores the first word
word = listWords[0]
# Traversing the words list
for i in listWords:
    if(len(i) > maxLength):
        maxLength = len(i)
        word = i
print("Printing the longest length word :")
print(word)

Output:

Enter the list of words / enter the sentence
hello this is BTechGeeks online Platform
Printing the longest length word :
BTechGeeks

Method #3: Reading a list of words separated by space as static input and comparing length of words using if statement (Static Input)

Approach:

  • Give the list of words separated by space as static input.
  • Assume that the first element is the one with the longest word.
  • The lengths of the words in the list are then compared with the first element using a for loop and an if statement.
  • In a temporary variable, save the name of the term with the longest length.
  • Print the word that has the longest length.
  • Exit of program

Below is the implementation:

# Taking a list of words in list
listWords = ["Hello", "this", "is", "BTechGeeks", "online", "Platform"]
# taking the first element length as max length word
maxLength = len(listWords[0])
# Initializing a temp variable which stores the first word
word = listWords[0]
# Traversing the words list
for i in listWords:
    if(len(i) > maxLength):
        maxLength = len(i)
        word = i
print("Printing the longest length word :")
print(word)

Output:

Printing the longest length word :
BTechGeeks

Related Programs:

Python Program to Read a List of Words and Return the Length of the Longest Word Read More »

Program to Find a Pair with the Given Sum in an Array

Python Program to Find a Pair with the Given Sum in an Array

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Lists in Python:

A list is a data structure or a container that may hold numerous pieces of information at once. There will be an order to the list, and it will be counted. The elements are indexed in a sequential order, with 0 as the initial index. Each element will have its own location in the sequence, and if the same value appears in the sequence numerous times, each will be treated as a separate and different element.

Given a list and a number k the task is to find a pair with the given sum k .

Examples:

Example1:

Input:

given list=[5,9,2,8,7,6]
value=10

Output:

Pair with given sum of elements is found

Example2:

Input:

given list=[4,7,6,1,8,9,3,4,5]
value=2

Output:

Pair with given sum of elements is not found

Program to Find a Pair with the Given Sum in an list in Python

There are several ways to find a pair with the given sum k in a list some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using Nested loops(Brute Force Approach)

For each pair i , j in A[], use two loops and check A[i] + A[j] == K. Return true if there is a pair with a sum equal to K. If you didn’t locate such a pair by the end of both loops, return false.

Below is the implementation:

# function which returns true if the pair with given sum k exists
# else it will return false


def checkPair(givenlist, value):
  # calculating the length of given list
    length = len(givenlist)
   # Traversing all elements in given list except the last
    for i in range(length - 1):

        # iterating from i+1 element to last element
        for j in range(i + 1, length):

            # if the given sum "value" is found then return true
            if givenlist[i] + givenlist[j] == value:
                # pair is found so it should return true
                return True

    # if no pair is found then we should return true
    return False


# given list
given_list = [5, 9, 2, 8, 7, 6]
# given element k
value = 10
# passing the given list and value to checkPair function
if(checkPair(given_list, value)):
    print("Pair with given sum of elements is found")
else:
    print("Pair with given sum of elements is not found")

Output:

Pair with given sum of elements is found

Time Complexity:

Here we use 2 loops so it takes average Time Complexity of O(n^2). To increase the efficiency of the above program we have other methods such as sorting and hashing

sorting technique:

The goal is to sort the provided list in ascending order while maintaining search space by keeping two indices (low and high) that initially point to two array endpoints. Then, for each iteration of the loop, reduce the search space list[low…high] by comparing the total of elements existing at indices low and high to the desired sum. If the sum is less than the expected amount, increment low; otherwise, decrement high if the sum is greater than the desired sum. Return the pair if it is found.

Time Complexity of sorting technique:

It takes O(nlogn) time complexity to achieve this task because we have to sort the given list so there is another best way to solve this question that is using hashing technique which we will discuss below

Method #2:Using Hashing

We can solve this problem in linear time by using a hash table. The plan is to put each array element list[i] into a map. We also check to see if the difference (list[i], sum – list[i]) already exists in the map. If the difference has already been seen, print the pair and return.

Below is the implementation:

# function which returns true if the pair with given sum k exists
# else it will return false


def checkPair(givenlist, value):
  # calculating the length of given list
    length = len(givenlist)
    # taking a empty dictionary
    dictionary = {}

    # using enumerate we check elements in givenlist
    for i, ele in enumerate(givenlist):

        # checking if the pair value-ele exists in guven dictionary
        # if it exists then return true
        if value - ele in dictionary:
            return True

        # storing index of curreent item in given dictionary as key
        dictionary[ele] = i

    # if no pair is found then we will return False
    return False


# given list
given_list = [5, 9, 2, 8, 7, 6]
# given element k
value = 10
# passing the given list and value to checkPair function
if(checkPair(given_list, value)):
    print("Pair with given sum of elements is found")
else:
    print("Pair with given sum of elements is not found")

Output:

Pair with given sum of elements is found

Time Complexity:

This above program takes O(n) Time Complexity which is most efficient way to do the abovee program abut it takes O(n) Space Complexity to achieve this task.

Related Programs:

Python Program to Find a Pair with the Given Sum in an Array Read More »

Program to Move all Zeros present in an ArrayList to the End

Python Program to Move all Zeros present in an Array/List to the End

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

List in Python:

Lists in Python are mutable sequences. They are extremely similar to tuples, except they do not have the immutability constraints. Lists are often used to store collections of homogeneous things, but there is nothing stopping you from storing collections of heterogeneous items as well.

Given a list the task is to move all zeros present in the given list to the end in python

Examples:

Example1:

Input:

given list = [7, 2, 0, 34, 56, 12, 0, 5, 6, 8, 0, 0, 9, 0, 1, 2, 4, 5]

Output:

the list before modification :
[7, 2, 0, 34, 56, 12, 0, 5, 6, 8, 0, 0, 9, 0, 1, 2, 4, 5]
the list after modification :
[7, 2, 34, 56, 12, 5, 6, 8, 9, 1, 2, 4, 5, 0, 0, 0, 0, 0]

Example2:

Input:

given list = [0, 54, 0, 6, 0, 7, 0, 0, 0, 9, 9, 9, 8, 8, 45, 33, 77, 66, 88, 11, 21, 0, 0, 0, 0]

Output:

the list before modification :
[0, 54, 0, 6, 0, 7, 0, 0, 0, 9, 9, 9, 8, 8, 45, 33, 77, 66, 88, 11, 21, 0, 0, 0, 0]
the list after modification :
[54, 6, 7, 9, 9, 9, 8, 8, 45, 33, 77, 66, 88, 11, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Python Program to Move all Zeros present in an Array/List to the End

There are several ways to move all zeros present in the given array/list to the end some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1: Taking New List and using conditional statements

The concept is straightforward, if the current element is non-zero, move it to the next available location in the array. After all of the array’s elements have been processed, increment all remaining indices by 0.

Approach:

  • Create a new list and call it emptylist.
  • Take a count, say zeroCount, and set it to 0 (which counts the total amount of zeros in the given list).
  • Traverse the given array/list using for loop.
  • Using the if condition, determine whether the element is zero or not.
  • If the element is not equal to zero, use the append() function to append it to the emptylist.
  • Otherwise, increase the zeroCount by one.
  • Following the execution of the for loop. Using the append() function, append the 0s to the end of the list zeroCount times.
  • Print the emptylist.

Below is the implementation:

# Create a new list and call it emptylist
emptylist = []
# given list
given_list = [7, 2, 0, 34, 56, 12, 0, 5, 6, 8, 0, 0, 9, 0, 1, 2, 4, 5]
# print the list before modifictaion
print("the list before modification :")
print(given_list)
# Take a count, say zeroCount, and set it to 0 (which counts the
# total amount of zeros in the given list).
zeroCount = 0
# Traverse the given array/list using for loop.
for eleme in given_list:
    # Using the if condition, determine whether the element is zero or not.
    if(eleme != 0):
        # If the element is not equal to zero, use the
        # append() function to append it to the emptylist.
        emptylist.append(eleme)
    # Otherwise, increase the zeroCount by one.
    else:
        zeroCount = zeroCount+1
# adding the zeros to the end of the empty list zeroCount number of times
for i in range(zeroCount):
    emptylist.append(0)
# print the list after modifictaion
print("the list after modification :")
print(emptylist)

Output:

the list before modification :
[7, 2, 0, 34, 56, 12, 0, 5, 6, 8, 0, 0, 9, 0, 1, 2, 4, 5]
the list after modification :
[7, 2, 34, 56, 12, 5, 6, 8, 9, 1, 2, 4, 5, 0, 0, 0, 0, 0]

Method #2: Using Quicksort’s partitioning logic

By changing Quicksort’s partitioning algorithm, we can solve this problem in a single scan of the array. The plan is to use 0 as a pivot element and run the partition procedure once. The partitioning logic scans all elements and swaps every non-pivot element with the pivot’s first occurrence.

Approach:

  • Scan the given list or give list input as static
  • Take a count, say index, and set it to 0 (which counts the total amount of zeros in the given list).
    Traverse the given array/list using for loop.
  • Using the if condition, determine whether the element is zero or not.
  • If the element is not equal to 0 then swap the current element with the index element
  • like  given_list[i],given_list[index]=given_list[index],given_list[i]
  • Increment the index
  • Print the given list

Below is the implementation:

# given list
given_list = [7, 2, 0, 34, 56, 12, 0, 5, 6, 8, 0, 0, 9, 0, 1, 2, 4, 5]
# print the list before modifictaion
print("the list before modification :")
print(given_list)
# Take a count, say zeroCount, and set it to 0
index = 0
# Traverse the given array/list using for loop.
for eleme in range(len(given_list)):
    # Using the if condition, determine whether the element is zero or not.
    if(given_list[eleme] != 0):
        # swappping index element with current index
        given_list[index], given_list[eleme] = given_list[eleme], given_list[index]
        # increment the index value by 1
        index = index+1
# print the list after modifictaion
print("the list after modification :")
print(given_list)

Output:

the list before modification :
[7, 2, 0, 34, 56, 12, 0, 5, 6, 8, 0, 0, 9, 0, 1, 2, 4, 5]
the list after modification :
[7, 2, 34, 56, 12, 5, 6, 8, 9, 1, 2, 4, 5, 0, 0, 0, 0, 0]

Related Programs:

Python Program to Move all Zeros present in an Array/List to the End Read More »

Program to Search the Number of Times a Particular Number Occurs in a List

Python Program to Search the Number of Times a Particular Number Occurs in a List

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Lists in Python:

The Python list is a straightforward ordered list of items. Python lists are extremely powerful since the objects in them do not have to be homogeneous or even of the same type. Strings, numbers, and characters, as well as other lists, can all be found in a Python list. Python lists are also mutable: once stated, they can be easily altered via a variety of list methods. Let’s look at how to use these techniques to handle Python lists.

Given a list and a element, the task is to write a  Python Program to Determine the Number of Occurrences of a Specific Number in a given List

Examples:

Examples1:

Input:

given list = ["my", "name", "is", "BTechGeeks", "coding", "platform", "for", "BTechGeeks"]

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Examples2:

Input:

given list = [5, 9, 1, 3, 6, 9, 2, 12, 8]

Output:

The count of the element ' 9 ' in the list [5, 9, 1, 3, 6, 9, 2, 12, 8] = 2

Python Program to Search the Number of Times a Particular Number Occurs in a List

There are several ways to determine the Number of Occurrences of a Specific Number in a given List some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Using a Counter Variable

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Take a variable which stores the count of the element say countEleme and initialize it to 0.
  • Traverse the given list using for loop.
  • If the iterator element is equal to the given element.
  • Then increment the countEleme value by 1.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Take a variable which stores the count of the element
# say totalCount and initialize it to 0.
countEleme = 0
# Traverse the given list using for loop.
for value in given_list:
    # if the value is equal too given_element then increase the countEleme by 1
    if(value == given_element):
        countEleme = countEleme+1
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #2: Using Count() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Count the given element in the list using count() function.
  • Print the countEleme.

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Count the given element in the list using count() function.
countEleme = given_list.count(given_element)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #3: Using Counter() function

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Use Counter function which stores the frequency as values and element as keys in its dictionary
  • Print the value of the given element

Below is the implementation:

# importing counter function from collections
from collections import Counter
# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using counter function
freqValues = Counter(given_list)
# Count the given element in the list
countEleme = freqValues[given_element]
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Method #4:Using List Comprehension

Approach:

  • Scan the given list or give list input as static.
  • Scan the given element or give given element as static.
  • Using list Comprehension checking if given element is equal to the iterator value
  • The count of the length of this new list gives the required answer

Below is the implementation:

# given list
given_list = ["my", "name", "is", "BTechGeeks",
              "coding", "platform", "for", "BTechGeeks"]
# given element
given_element = "BTechGeeks"
# Using list comprehension
elementlist = [eleme for eleme in given_list if eleme == given_element]

# Count the given element in the list using len function
countEleme = len(elementlist)
# Print the countEleme
print("The count of the element '", given_element,
      "' in the list", given_list, "=", countEleme)

Output:

The count of the element ' BTechGeeks ' in the list ['my', 'name', 'is', 'BTechGeeks', 'coding', 'platform', 'for', 'BTechGeeks'] = 2

Python Program to Search the Number of Times a Particular Number Occurs in a List Read More »

Implementing Sentinel Search

Implementing Sentinel Search in Python

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Sentinel Search:

Sentinel Linear Search, as the name implies, is a form of Linear Search in which the number of comparisons is decreased as compared to a standard linear search. When a linear search is conducted on an array of size N, a complete of N comparisons are made when the element to be searched is compared to all or any the elements of the array and (N + 1) comparisons are made for the index of the element to be compared in order that the index isn’t out of bounds of the array, which can be decreased in a Sentinel Linear Search.

In this search, the last element of the array is replaced with the element to be searched, and then the linear search is performed on the array without checking if the current index is inside the array’s index range or not, since the element to be searched would almost certainly be found within the array even though it was not present in the original array since the last element was replaced with i. As a result, the index to be tested will never be beyond the array’s limits. In the worst-case scenario, the number of comparisons would be (N + 2).

Examples:

Input:

given_elements =[2, 7, 3, 4, 9, 15]   key= 9

Output:

Element 9 is found at index 4

Implementing Sentinel Search in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Algorithm

We will begin by determining the length of the list, and then append the goal at the end.

Following that, we begin a while-loop to determine whether or not the current item is the same as the target. Since we placed the target at the end, the loop will undoubtedly come to an end.

Finally, we search to see if it ended at the last part or not. If yes, the goal is not in the list otherwise, it is. And then we return the required value.

2)Implementation:

Below is the implementation of linear search:

# function which return index if element is present else return -1
def sentinelSearch(given_list, key):
    # getting the last element of the list
    lastelement = given_list[-1]

    # the key which should  be searched is kept at the end of the last index.
    given_list[-1] = key
    i = 0

    while (given_list[i] != key):
        i += 1

    # Put the last element back
    given_list[-1] = lastelement
    # getting length of list
    length = len(given_list)
    if ((i < length - 1) or (given_list[length - 1] == key)):
        return i
    else:
        return -1


# given_list
given_list = [2, 7, 3, 4, 9, 15]

# given key
key = 9
# passing the given_list and key to sentinelSearch function
res = sentinelSearch(given_list, key)
# if result is equal to -1 then element is not present in list
if(res == -1):
    print("Given element(key) is not found in list")
else:
    print("Element", key, "is found at index", res)

Output:

Element 9 is found at index 4

3)Time Complexity

The while loop performs only one comparison per iteration and is guaranteed to terminate since the last element of the list is the search element itself. So, in the worst-case scenario (if the search factor does not exist in the list), there would be no more than N+2 comparisons ( N comparisons in the while loop and 2 comparisons in the if condition). This is superior to the ( 2N+1 ) comparisons used in Simple Linear Search.
It should be noted that both algorithms have a time complexity of O(n).
Related Programs:

Implementing Sentinel Search in Python Read More »

Binary Search Algorithm in Python

Binary Search Algorithm in Python

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Binary Search:

A binary search is an algorithm for finding a specific element in a list. Assume we have a list of a thousand elements and we need to find the index location of a specific element. Using the binary search algorithm, we can quickly determine the index location of an element.

There are several search algorithms, but the binary search is the most widely used.

To use the binary search algorithm, the elements in the list must be sorted. If the elements are not already sorted, sort them first.

Examples:

Input:

given_elements =[2, 7, 3, 4, 9, 15]   key= 9

Output:

Element 9 is found at index 4

Binary Search Algorithm in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Algorithm

  • We write a function that takes two arguments, the first of which is of which is the list and the second of which is the objective to be found.
  • We declare two variables start and end, which point to the list’s start (0) and end (length – 1), respectively.
  • Since the algorithm would not accept items outside of this range, these two variables are responsible for removing items from the quest.
  • The next loop will continue to locate and delete items as long as the start is less than or equal to the end, since the only time the start exceeds the end is if the item is not on the list.
  • We find the integer value of the mean of start and end within the loop and use it as the list’s middle object.

2)Implementation

Below is the implementation of linear search:

# function which return index if element is present else return -1
def binarySearch(given_list, key):
    lowindex = 0
    highindex = len(given_list) - 1
    midindex = 0
    # loop till lowindex is less than or equal to highindex
    while lowindex <= highindex:
       # Modify midindex with average of high index and lowindex
        midindex = (highindex + lowindex) // 2

        # If key is greater than mid element ignore left half side of list
        if given_list[midindex] < key:
            lowindex = midindex + 1

        # If key is less than mid element ignore right half side of list
        elif given_list[midindex] > key:
            highindex = midindex - 1

        # Else the element is present at mid index
        else:
            return midindex

    # if any value is not returned then element is not present in list
    return -1


# given_list
given_list = [2, 7, 3, 4, 9, 15]
# given key
key = 9
# sort the list
given_list.sort()
# passing the given_list and key to binarySearch function
res = binarySearch(given_list, key)
# if result is equal to -1 then element is not present in list
if(res == -1):
    print("Given element(key) is not found in list")
else:
    print("Element", key, "is found at index", res)

Output:

Element 9 is found at index 4

3)Time Complexity

Consider a basic searching algorithm such as linear search, in which we must go through each element one by one before we find what we’re looking for. This means that for larger input sizes, the time it takes to find an element grows in lockstep with the input size. Its time complexity is O measurably (n).

The term “time complexity” refers to the measurement of how quick or efficient an algorithm is. The time complexity of Binary Search is “O(log2n),” which means that if we double the size of the input list, the algorithm can only perform one additional iteration.

In the same way, if the input size is multiplied by a thousand, the loop would only need to run 10 times more.

Remember that half of the list is removed with each iteration, so eliminating the entire list won’t take long.
Related Programs:

Binary Search Algorithm in Python Read More »

Linear Search in Python

Linear Search in Python

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Linear Search works in much the same way as we search for a random list of objects.

If we need to find a word on a specific page, we will begin at the top and go through each word one by one before we find the word we are searching for.

Linear Search:

Linear search is a method for locating elements in a sequence. It’s also known as a sequential scan. It is the most basic searching algorithm since it searches for the desired element sequentially.

It compares each element to the value that we are looking for. If both match, the element is found, and the algorithm returns the index position of the key.

Examples:

Input:

given_elements =[2, 7, 3, 4, 9, 15]   key= 9

Output:

Element 9 is found at index 4

Linear Search in Python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Algorithm

  • Begin with the leftmost element of the given list and compare element “key” with each element of the list one by one.
  • Return the index value if “key” matches any of the elements.
  • If “key” does not match any of the elements in list [], return -1 or the element was not found.

2)Implementation

Below is the implementation of linear search:

# function which return index if element is present else return -1
def linearSearch(given_list, key):
    # Traverse the list
    for index in range(len(given_list)):
        # if the element is equal to key then return index
        if(given_list[index] == key):
            return index
    # if no index is returned then the element is not found in list
    # return -1
    return -1


# given_list
given_list = [2, 7, 3, 4, 9, 15]
# given key
key = 9
# passing the given_list and key to linearSearch function
res = linearSearch(given_list, key)
# if result is equal to -1 then element is not present in list
if(res == -1):
    print("Given element(key) is not found in list")
else:
    print("Element", key, "is found at index", res)

Output:

Element 9 is found at index 4

3)Time Complexity

Linear Search is not an efficient algorithm since it goes through each item in the list, so the number of items in the list has a direct effect on the algorithm.

To put it another way, the algorithm has a time complexity of O. (n). This means that if the number of items in the list is increased by a certain amount, the time required to complete the algorithm will also be multiplied by the same amount.
Related Programs:

Linear Search in Python Read More »

Program to Implement Fibonacci Search in Python

Python Program to Implement Fibonacci Search

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Introduction of searching algorithms:

Searching for data stored in various data structures is an essential aspect of almost any program.

When searching, there are numerous algorithms to choose from, each with its own implementation and dependence on distinct data formats.

The ability to select a specific algorithm for a given task is a critical talent for developers, and it can make the difference between a speedy, dependable, and stable application and one that crumbles due to a simple request.

Program to Implement Fibonacci Search in Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Fibonacci Numbers

Fibonacci search is a divide and conquer technique that is comparable to both binary search and jump search. It derives its name from the fact that it calculates the block size or search range in each step using Fibonacci numbers.

  • It is applicable to sorted arrays.
  • An Algorithm of Divide and Conquer.
  • Has a Time complexity of Log n.

Fibonacci numbers

The Fibonacci Series is made up of Fibonacci numbers. So first, let us define the Fibonacci Series. The series can be defined recursively as follows:

F(n) = F(n-1) + F(n-2)
F(0) = 0
F(1) = 1

We do have a straightforward means of calculating Fibonacci numbers using exponents and the Golden Ratio, but this is how the series is intended to be understood.

F(n) is defined as the “nth Fibonacci Number” in the preceding definition.

Thus, the 0th number is 0, the 1st numbers is 1, the 2nd is the total 1st and 0th numbers of Fibonacci, the 3rd is the sum 2nd and 1st numbers of Fibonacci and so on.

Fibonacci numbers begin with zero and go in the following order: 0, 1, 1, 2, 3, 5, 8, 13, 21,…, where each element is the sum of the two numbers that come before it.

  • It is applicable to sorted arrays.
  • An Algorithm of Divide and Conquer.
  • Has a Time complexity of Log n.

Fibonacci Search splits the array into different portions
Divided range is used by Binary Search. Search is not used by Fibonacci, but employs + and -. Some CPUs could be expensive for the division operator.
Fibonacci Search reviews in succeeding steps relatively closer items. So Fibonacci Search can be helpful if the input array is large that does not fit into the CPU cache or even in ram.

Fibonacci search, like binary search, is a divide and conquer method that requires a sorted list. It also divides the list into two sections, compares the target to the item in the middle of the two sections, and eliminates one side based on the comparison. So, how does it differ from binary search?

The Fibonacci numbers are used to divide the list into two parts in the Fibonacci search, therefore it will divide the list into two portions of different lengths. Furthermore, instead of conducting division, it conducts addition, which is less costly on the CPU. Let’s get into the specifics now.

First, we need to know how long the given list is. Then we look for the smallest Fibonacci number that is bigger than or equal to the length of the list. That is, if the list has 100 items, the least Fibonacci number greater than 100 is 144. Assume this is the nth Fibonacci number. In the preceding example, the 12th Fibonacci number is 144.

Following that, we go back twice in the Fibonacci sequence from that number. Essentially, we are looking for the

(n-2)th Fibonacci number. So, in the preceding example, we discovered the 12th Fibonacci number, which is 144, and now we need the 10th, which is 55.

This is used as the index to divide the list into two sections. That is, we examine at this index in the list, and assuming the list is sorted in increasing order, we eliminate the left side if the item at this index is smaller than the target, else we eliminate the right side. We repeat this process until we locate the item we’re seeking for, which will occur when the calculated index’s item matches the target.

Below is the implementation:

# function which implements the fibonacci search
def fib_search(givenlist, givenelement):
    # ffinding the length of given list
    length = len(givenlist)

    first = -1

    x0 = 0
    x1 = 1
    x2 = 1
    while(x2 < length):
        x0 = x1
        x1 = x2
        x2 = x1 + x0

    while(x2 > 1):
        eleIndex = min(first + x0, length - 1)
        if givenlist[eleIndex] < givenelement:
            x2, x1 = x1, x0
            x0 = x2 - x1
            start = eleIndex
        elif givenlist[eleIndex] > givenelement:
            x2 = x0
            x1 = x1 - x0
            x0 = x2 - x1
        else:
            return eleIndex
    if (x1) and (givenlist[length - 1] == givenelement):
        return length - 1
    return None


# given list
given_list = [1, 9, 4, 7, 2, 8, 6]
# sorting the given list
given_list.sort()
# given element to search
given_element = 4
# passing given list and given element to fibonacci search function to check whether
# the given element is present in list or not
print(fib_search(given_list, given_element))

Output:

2

Conclusion:

In this tutorial, we reviewed the Fibonacci numbers, how they are employed in the Fibonacci search algorithm, the functioning of the method, and the implementation of the python code.
Related Programs:

Python Program to Implement Fibonacci Search Read More »

Python Program to Print Square Pattern with Numbers

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Given the number of rows, the task is to print Square Pattern with Numbers in C, C++, and Python

Examples:

Example1:

Input:

Given number of rows = 9

Output:

1 2 3 4 5 6 7 8 9 
2 2 3 4 5 6 7 8 9 
3 3 3 4 5 6 7 8 9 
4 4 4 4 5 6 7 8 9 
5 5 5 5 5 6 7 8 9 
6 6 6 6 6 6 7 8 9 
7 7 7 7 7 7 7 8 9 
8 8 8 8 8 8 8 8 9 
9 9 9 9 9 9 9 9 9

Example2:

Input:

Given number of rows = 6

Output:

1 2 3 4 5 6 
2 2 3 4 5 6 
3 3 3 4 5 6 
4 4 4 4 5 6 
5 5 5 5 5 6 
6 6 6 6 6 6

Program to Print Square Pattern with Numbers in C, C++, and Python

Below are the ways to print Square Pattern with Numbers in C, C++, and Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number of rows as static input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from 1 to the number of rows using another for loop(Nested For loop).
  • Check if the iterator value of the inner For loop is less than or equal to the parent loop iterator value of theFor Loop using the If conditional Statement.
  • If it is true then print the iterator value of the parent For loop.
  • Else print the iterator value of the inner For loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Below is the implementation:

# Give the number of rows as static input and store it in a variable.
numbrrows = 9
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows+1):
    # Loop from 1 to the number of rows using another for loop(Nested For loop).
    for n in range(1, numbrrows+1):
        ''' Check if the iterator value of the inner For loop is less than or equal 
            to the parent loop iterator value of the
            For Loop using the If conditional Statement.'''
        if(n <= m):
            # If it is true then print the iterator value of the parent For loop.
            print(m, end=' ')
        else:
            print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

1 2 3 4 5 6 7 8 9 
2 2 3 4 5 6 7 8 9 
3 3 3 4 5 6 7 8 9 
4 4 4 4 5 6 7 8 9 
5 5 5 5 5 6 7 8 9 
6 6 6 6 6 6 7 8 9 
7 7 7 7 7 7 7 8 9 
8 8 8 8 8 8 8 8 9 
9 9 9 9 9 9 9 9 9

2) C++ Implementation

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 5;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numbrrows; m++) {
        // Loop from 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                cout << m << " ";
            else
                cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }
    return 0;
}

Output:

1 2 3 4 5 
2 2 3 4 5 
3 3 3 4 5 
4 4 4 4 5 
5 5 5 5 5

3) C Implementation

Below is the implementation:

#include <stdio.h>

int main()
{

    // Give the number of rows as static input and store it
    // in a variable.
    int numbrrows = 3;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numbrrows; m++) {
        // Loop from 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                printf("%d ", m);
            else
                printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

1 2 3 
2 2 3 
3 3 3

Method #2: Using For Loop (User Input)

Approach:

  • Give the number of rows as user input and store it in a variable.
  • Loop from 1 to the number of rows using For loop.
  • Loop from 1 to the number of rows using another for loop(Nested For loop).
  • Check if the iterator value of the inner For loop is less than or equal to the parent loop iterator value of theFor Loop using the If conditional Statement.
  • If it is true then print the iterator value of the parent For loop.
  • Else print the iterator value of the inner For loop.
  • Print the Newline character after the end of the inner loop.
  • The Exit of the Program.

1) Python Implementation

Give the number of rows as user input using int(input()) and store it in a variable.

Below is the implementation:

# Give the number of rows as user input using int(input()) and store it in a variable.
numbrrows = int(input('Enter some random number of rows = '))
# Loop from 1 to the number of rows using For loop.
for m in range(1, numbrrows+1):
    # Loop from 1 to the number of rows using another for loop(Nested For loop).
    for n in range(1, numbrrows+1):
        ''' Check if the iterator value of the inner For loop is less than or equal 
            to the parent loop iterator value of the
            For Loop using the If conditional Statement.'''
        if(n <= m):
            # If it is true then print the iterator value of the parent For loop.
            print(m, end=' ')
        else:
            print(n, end=' ')
    # Print the Newline character after the end of the inner loop.
    print()

Output:

Enter some random number of rows = 7
1 2 3 4 5 6 7 
2 2 3 4 5 6 7 
3 3 3 4 5 6 7 
4 4 4 4 5 6 7 
5 5 5 5 5 6 7 
6 6 6 6 6 6 7 
7 7 7 7 7 7 7

2) C++ Implementation

Give the number of rows as user input using cin and store it in a variable.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{

    // Give the number of rows as user input using
    // int(input()) and store it in a variable.
    int numbrrows;
    cin >> numbrrows;
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numbrrows; m++) {
        // Loop from 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                cout << m << " ";
            else
                cout << n << " ";
        }
        // Print the Newline character after the end of the
        // inner loop.
        cout << endl;
    }
    return 0;
}

Output:

4
1 2 3 4 
2 2 3 4 
3 3 3 4 
4 4 4 4

3) C Implementation

Give the number of rows as user input using scanf and store it in a variable.

Below is the implementation:

#include <math.h>
#include <stdio.h>
int main()
{

    // Give the number of rows as user input using scanf and
    // store it in a variable.
    int numbrrows;
    scanf("%d", &numbrrows);
    // Loop from 1 to the number of rows using For loop.
    for (int m = 1; m <= numbrrows; m++) {
        // Loop from 1 to the number of rows using another
        // for loop(Nested For loop).
        for (int n = 1; n <= numbrrows; n++) {
            /*Check if the iterator value of the inner For
            loop is less than or equal to the parent loop
            iterator value of the For Loop using the If
            conditional Statement.*/
            if (n <= m)
                // If it is true then print the iterator
                // value of the parent For loop.
                printf("%d ", m);
            else
                printf("%d ", n);
        }
        // Print the Newline character after the end of the
        // inner loop.
        printf("\n");
    }
    return 0;
}

Output:

6
1 2 3 4 5 6 
2 2 3 4 5 6 
3 3 3 4 5 6 
4 4 4 4 5 6 
5 5 5 5 5 6 
6 6 6 6 6 6 

Related Programs:

Python Program to Print Square Pattern with Numbers Read More »