Vikram Chiluka

Python Program to Solve Quadratic Equation

Python Program to Solve Quadratic Equation

Solve Quadratic Equation using 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)Quadratic Equation

Quadratics or quadratic equations are polynomial equations of the second degree, which means that they contain at least one squared word.

ax2 + bx + c = 0

where x is an unknown variable and the numerical coefficients a , b , c.

2)Discriminant value

Discriminant = b ^ 2 - 4 * a *c

Based on the value of discriminant there are three types of roots for Quadratic Equation

3)Calculating roots of Quadratic Equation

roots = ( -b + sqrt(b ^ 2 - 4 * a *c) ) / (2 * a)   , ( -b - sqrt(b ^ 2 - 4 * a *c) ) / (2 * a)

Where sqrt is square root.

4)Types of roots

i)Real and distinct roots

When the Value of discriminant is greater than 0 then there exist two distinct roots for the quadratic equation

which can be calculated using the above roots formula.

Examples:

Input:

a = 2
b = -7
c = 6

Output:

The two distinct roots are : 
(2+0j)
(1.5+0j)

ii)Real and equal roots

When the Value of discriminant is equal to 0 then there exist two equal roots for the quadratic equation .

which can be calculated using the above roots formula.

Examples:

Input:

a = 1
b = -4
c = 4

Output:

The two equal roots are : 
2.0 2.0

iii)Complex roots

When the Value of discriminant is greater than 0 then there exist two complex roots for the quadratic equation .

which can be calculated using the above roots formula.

Examples:

Input:

a = 5
b = 2
c = 3

Output:

There exists two complex roots:
(-1+1.7320508075688772j)
(-1-1.7320508075688772j)

5)Approach

  • To perform complex square root, we imported the cmath module.
  • First, we compute the discriminant.
  • Using if..elif..else we do the below steps
  • If the value of discriminant is  greater than 0 then we print real roots using mathematical formula.
  • If the value of discriminant is  equal to 0 then we print two equal roots using mathematical formula.
  • If the value of discriminant is  less than 0 then we print two complex roots using mathematical formula.

6)Implementation:

Below is the implementation:

# importing cmath
import cmath
# given a,b,c values
a = 2
b = -7
c = 6
discriminant = (b**2) - (4*a*c)
# checking if the value of discriminant is greater than 0
if(discriminant > 0):
    # here exist the two distinct roots and we print them
    # calculating the roots
    root1 = (-b+discriminant) / (2 * a)
    root2 = (-b-discriminant) / (2 * a)
    # printing the roots

    print("The two distinct roots are : ")
    print(root1)
    print(root2)
# checking if the value of discriminant is equal to 0
elif(discriminant == 0):
    # here exist the two equal roots
    # calculating single root here discriminant is 0 so we dont need to write full formulae
    root = (-b)/(2*a)
    # printing the root
    print("The two equal roots are : ")
    print(root, root)
# else there exists complex roots
else:
    # here exist the two complex roots
    # calculating complex roots
    realpart = -b/(2*a)
    complexpart = discriminant/(2*a)*(-1)
    # printing the roots
    print("There exists two complex roots:")
    print(realpart, "+", complexpart, "i")
    print(realpart, "-", complexpart, "i")

Output:

The two distinct roots are : 
(2+0j)
(1.5+0j)

Related Programs:

Python Reverse String

How to Reverse a String in Python

String:

Arrays are Strings. Strings in Python, like many other common programming languages, are sequences of bytes that represent unicode characters. However, since Python lacks a character data form, a single character is simply a one-length string. Square brackets may be used to access the string’s components.

Given a string , the task is to reverse the given string in Python.

Examples:

Example1:

Input:

given_string="vikram"

Output:

The reversed string of vikram = markiv

Example2:

Input:

given_string="wor45rd"

Output:

The reversed string of wor45rd = dr54row

Explanation:

Here 4,5 are also considered as character so it is reversed succesfully

Example3:

Input:

given_string="BTechGeeks"

Output:

The reversed string of BTechGeeks = skeeGhceTB

Here it ignores the case so the reversed string contains many uppercase characters.

Reverse the string in Python

There are several ways to reverse the string in python 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 Slicing

Approach:

  • Scan the given string.
  • Reverse the string using slicing using [::-1] which indicates that we traverse from end
  • Print the reversed string.

Below is the implementation:

# given string
given_string = "vikram"
# calculating the length of string
length = len(given_string)
# Reversing the string using slicing
reverse_string = given_string[len(given_string)::-1]
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

Method #2: Using join() and reversed function

We can reverse the string easily by using join() and reversed string like below.

Approach:

  • Scan the given string.
  • join the reversed string using join() function.(We can reverse the string while joining using reversed function).
  • Store it in any variable say rev_string
  • Print the reversed rev_string.

Below is the implementation:

# given string
given_string = "vikram"
# reversing using join and reversed function
rev_string = ''.join(reversed(given_string))
# print the reversed string
print("The reversed string of", given_string, "=", rev_string)

Output:

The reversed string of vikram = markiv

Method #3:Using for loop and string concatenation

Approach: 

  • Scan the givenstring.
  • Take a empty string say revstring.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • print the revstring.

Below is the implementation:

# given string
given_string = "vikram"
# taking empty string
reverse_string = ""
# calculating the length of string
length = len(given_string)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+given_string[index]
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

Method #4:Using list  and join functions

Approach:

  • Scan the given string.
  • Convert this string to list of characters using list() function.
  • Reverse the list using reverse() function
  • Join the list using join() function to get reversed string.
  • Print the reversed string.

Below is the implementation:

# given string
given_string = "vikram"
# converting to list of characters
stringlist = list(given_string)
# reverse the list
stringlist.reverse()
# convert this list to string using join
reverse_string = ''.join(stringlist)
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

Method #5 : Using while loop

This method is similar to method #2(using for loop)

Approach: 

  • Scan the givenstring.
  • Take a empty string say revstring.
  • Take a variable length which gives the length of string.
  • Loop till length is greater than or equal to 0.
  • For each iteration
  • Add each character to revstring using string concatenation.
  • Decrement the length by 1.
  • print the revstring.

Below is the implementation:

# given string
given_string = "vikram"
# taking empty string
reverse_string = ""
# calculating the length of string
length = len(given_string)-1
# using while loop
while(length >= 0):
    # adding the character of string to reverse_string
    reverse_string = reverse_string+given_string[length]
    # decrement the length
    length = length-1
# print the reversed string
print("The reversed string of", given_string, "=", reverse_string)

Output:

The reversed string of vikram = markiv

These are methods to print the reversed string we can print directly by using loops and range() function but it doesn’t reverse the string it just print the reversed value of string.
Related Programs:

Check Palindrome in Python

Python program to check if a string is palindrome or not

Palindrome:

If a number reads the same both forward and backward, it is called a Palindrome number. And the insane part is that it doesn’t just apply to numbers. Even if a string reads the same in both directions, it is always a Palindrome!

Examples for string palindrome

Example 1:

Input: 

given_string = madam

Output:

The given string madam is palindrome

Explanation:

Here the madam word reads same from front and end so it is palindrome

Example 2:

Input: 

given_string = vicky

Output:

The given string vicky is not palindrome

Explanation:

Here vicky and ykciv are not equal so it is not a palindrome

Examples for number palindrome

Example 1:

Input: 

given_number =12321

Output:

The given number 12321 is palindrome

Explanation:

Here the number 12321  reads same from front and end so it is palindrome

Example 2:

Input: 

given_number =12345

Output:

The given number 12345 is not palindrome

Explanation:

Here 12345 and 54321 are not equal so it is not a palindrome

Checking Palindrome in Python

There are several ways to check whether the given number is palindrome or not 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 while loop to check whether the number is palindrome

Algorithm:

  • Scan the given number
  • Take another variable say duplicate_num and initialize it with given number
  • Set the variable reverse_number to 0.
  • Loop while number > 0 Loop while number > 0
  • Multiply reverse_number by 10 and add the remainder to reverse_number like below
  • reverse_number = (reverse_number * 10) + remainder
  • Divide the given number by 10 to remove the last digit.
  • If the duplicate_num and reverse_number are equal then it is palindrome.
  • Else it is not palindrome.

Below is the implementation:

# given number
given_num = 12321
# taking another variable to store the copy of original number
# and initialize it with given num
duplicate_num = given_num
# Take a variable reverse_number and initialize it to null
reverse_number = 0
# using while loop to reverse the given number
while (given_num > 0):
    # implementing the algorithm
    # getting the last digit
    remainder = given_num % 10
    reverse_number = (reverse_number * 10) + remainder
    given_num = given_num // 10
# if duplicate_num and reverse_number are equal then it is palindrome
if(duplicate_num == reverse_number):
    print("The given number", duplicate_num, "is palindrome")
else:
    print("The given number", duplicate_num, "is not palindrome")

Output:

The given number 12321 is palindrome

Method #2: Using for loop and string concatenation to check whether the number is palindrome

Approach: 

  • Scan the given number.
  • Take a empty string say revstring.
  • Convert the given number to string using str() function say strnum for this string.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • If the revstring and string_num are equal then it is palindrome.
  • Else it is not palindrome.

Below is the Implementation:

# given number
given_num = 12321
# taking empty string
reverse_string = ""
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+strnum[index]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == strnum):
    print("The given number", given_num, "is palindrome")
else:
    print("The given number", given_num, "is not palindrome")

Output:

The given number 12321 is palindrome

Method #3:Using for loop and string concatenation to check whether the string is palindrome

Approach: 

  • Scan the givenstring.
  • Take a empty string say revstring.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • If the revstring and givenstring are equal then it is palindrome.
  • Else it is not palindrome.

Below is the Implementation:

# given string
given_string = "madam"
# taking empty string
reverse_string = ""
# calculating the length of string
length = len(given_string)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+given_string[index]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == given_string):
    print("The given string", given_string, "is palindrome")
else:
    print("The given string", given_string, "is not palindrome")

Output:

The given string madam is palindrome

Method #4:Using slicing to check whether the number is palindrome

Approach:

  • Scan the given number.
  • Convert the given number to string using str() function say strnum for this string.
  • Reverse the string using slicing
  • If the revstring and string_num are equal then it is palindrome.
  • Else it is not palindrome.

Below is the implementation:

# given number
given_num = 12321
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Reversing the string using slicing
reverse_string = strnum[len(strnum)::-1]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == strnum):
    print("The given number", given_num, "is palindrome")
else:
    print("The given number", given_num, "is not palindrome")

Output:

The given number 12321 is palindrome

Method #5: Using slicing to check whether the string is palindrome

Approach:

  • Scan the given string.
  • Reverse the string using slicing
  • If the revstring and string are equal then it is palindrome.
  • Else it is not palindrome.

Below is the implementation:

# given string
given_string = "madam"
# calculating the length of string
length = len(given_string)
# Reversing the string using slicing
reverse_string = given_string[len(given_string)::-1]
# if reverse_string  and strnum are equal then it is palindrome
if(reverse_string == given_string):
    print("The given string", given_string, "is palindrome")
else:
    print("The given string", given_string, "is not palindrome")

Output:

The given string madam is palindrome

Related Programs:

Kwargs Functions that accept Variable length Key Value pair as Arguments

Python : **Kwargs | Functions that accept Variable length Key Value pair as Arguments

In this post, we’ll look at how to write Python functions that accept variable-length arguments in key-value pair format.

Functions that accept Variable length Key Value pair as Arguments

1)Kwargs

In Python function definitions, the special syntax **kwargs is used to transfer a keyworded, variable-length argument set. We call ourselves kwargs with a double star. The explanation for this is that the double star helps one to push keyword arguments through (and any number of them).

  • A keyword statement is to give the variable a name before entering it.
  • You can think of the kwargs as a dictionary mapping every keyword to the value we pass. This is why there appears to be no order in which we are iterating through the kwargs.

2)Variable Length Functions

Assume we want to define a function that prints the given student information. Details will be presented in key value pairs, with key representing the property name and value representing the property’s value.
It should print all of the given properties, regardless of their count.

printDetails(name = "Vishal")

Above one should only print one property, namely the name.

printDetails(name = "Vishal", pincode = "983992")

Above one should print two properties , namely the name and pincode

printDetails(name = "Vishal", phone = "333444",address = "NewYork")

Above one should print three properties, namely the name , pincode and address.

It is important that the function accepts variable length arguments in key value pair format.

3)Writing Function which accepts variable length arguments in key value pair using **kwargs

In Python, we must add ** before the parameter name if we want to allow multiple key value pair arguments in a single parameter.
**kwargs can accept multiple key value pair arguments and store them in a dictionary, indicating that kwargs are of the dictionary type.
Let’s make the function with **kwargs now.

Below is the implementation:

def printDetails(**kwargs):
    # Variable-length arguments in key-value pair format are accepted.
    print("Printing all the arguments", kwargs)
    print("Traverse the arguments")
    for key, value in kwargs.items():
        print("person's ", key, " = ", value)
    print()


# passing key's and values to printDetails function
# passing one argument
printDetails(name="Vishal")
# passing two arguments
printDetails(name="Akash", pincode=533333)
# passing three arguments
printDetails(name="Vikram", pincode=213442, adress="NewYork")

Output:

Printing all the arguments {'name': 'Vishal'}
Traverse the arguments
person's  name  =  Vishal

Printing all the arguments {'name': 'Akash', 'pincode': 533333}
Traverse the arguments
person's  name  =  Akash
person's  pincode  =  533333

Printing all the arguments {'name': 'Vikram', 'pincode': 213442, 'adress': 'NewYork'}
Traverse the arguments
person's  name  =  Vikram
person's  pincode  =  213442
person's  adress  =  NewYork

Related Programs:

For Loop Explained with Examples

Python: For Loop – Explained with Examples

For Loop:

A for loop is used to iterate through a series (that is either a list, a tuple, a dictionary, a set, or a string).
This functions more like an iterator method in other object-oriented programming languages than the for keyword in other programming languages.

The for loop allows one to execute a series of statements once for each item in a list, tuple, set, and so on.

For Loop in Python

1)For loop

A for loop in Python allows one to iterate over a set of statements several times. However, the number of times these statements are executed by a for loop is determined by a sequence.

To put it another way, a for loop in Python is useful for iterating over a sequence of elements.

Syntax:

for element in sequence:
    statement one
    statement two
    .......
    .......
    .....
    .......
    ......
    statement n

The keyword “for” is followed by a variable, then the keyword “in,” then a sequence, and finally a colon. The suite of for loop is also known as the block of for loop after the for statement begins the suite of for loop, which is a group of statements with one indent stage.

The for loop will loop through all of the elements in a given sequence. It will allocate each element of the sequence to variable element and then execute the statements in-suite, i.e., statements in the block. These statements may now make use of the element variable, which includes a sequence element for that event.

2)Iterating the string using for loop

# given_string
given_string = "BTechGeeks"
# Traverse the string in for loop
for character in given_string:
    print("Character = ", character)

Output:

Character =  B
Character =  T
Character =  e
Character =  c
Character =  h
Character =  G
Character =  e
Character =  e
Character =  k
Character =  s

As a sequence, we used a string. Then, using a for loop, we looped through all of the characters in the string series.

3)Using For loop and range() to print elements from 1 to 20

The range() function returns a sequence of numbers from start to -1 . We can then iterate over each element of this sequence using the for loop.

Below is the implementation:

# using for loop and range to print elements from 1 to 20
for i in range(1, 21):
    print(i)

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

The following actions were performed by the for loop for each element of the sequence,

  • It assigned the variable i to the element.
  • It execute the lines in the block, i.e. the suite of for loops.

4)Printing numbers in descending order using for loop and range() function

The range() function returns a sequence of numbers with the specified range size from start to end -1.

range(20,0,-1)

# using for loop and range to print elements from 1 to 20 in descending order
for i in range(20, 0, -1):
    print(i)

Output:

20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1

The following actions were performed by the for loop for each element of the sequence,

  • It assigned the variable i to the element.
  • It execute the lines in the block, i.e. the suite of for loops.

We can traverse the list using for loop as shown below.

Below is the implementation:

# given_list
givenlist = ["hello", "this", "is", "BTechGeeks"]
# using for loop to traverse the list
for element in givenlist:
    # print the element
    print(element)

Output:

hello
this
is
BTechGeeks

6)For Loop with else statement

We may have an optional else block in addition to a for loop.

When the for loop has finished executing the statements in the for block, it then executes the statements in the else block. It is important to note that statements in the else block can only be executed in the last position and only once.

Below is the implementation:

# given_list
givenlist = ["hello", "this", "is", "BTechGeeks"]
# using for loop to traverse the list
for element in givenlist:
    # print the element
    print(element)
# else block
else:
    print("For loop is ended")

Output:

hello
this
is
BTechGeeks
For loop is ended

Related Programs:

min() Function Tutorial with Examples

Python : min() Function Tutorial with Examples

We’ll go through the details of Python’s min() function with examples in this article.

The min() function in Python is used to find the smallest element in a collection of elements.

Python min() function

1)min() function

The min() function returns the lowest-valued object, or the lowest-valued item in an iterable.

If the values are strings, they are compared alphabetically.

Syntax:

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

Parameters:

Iterable : An Iterable object is one that can be traversed, such as a list or a tuple.
arg1,arg2 ...... :  Multiple elements are essential.
key  :  A function that is applied to and object in the Iterable and returns a value based on the argument passed in.

Return:

It returns the Iterable or assigned elements element with the lowest value. If the main function is not available,
 the minimum value is determined by comparing the given objects. If a key function is given, instead of explicitly
 comparing objects, it will first call the key function on each one before comparing it to others.

Exceptions:

When two forms are compared, TypeError is returned.

2)Finding min value in list

Consider the following scenario: we have a list of numbers.

Since list is an Iterable, we may directly transfer it to the min() function to find the list’s minimum value.

Below is the implementation:

# given list
givenlist = [98, 234, 21, 45, 55, 12, 988]
# finding min value in list using min function
minvalue = min(givenlist)
# print the min value
print(minvalue)

Output:

12

3)Finding min ascii character in string using min() function

Assume we have a string.
Since String is an Iterable, we can use the min() function to find the character with the lowest ASCII value in the string.

Below is the implementation:

# given string
string = "onlinebtechgeeks"
# finding min ascii value character in given string
minchar = min(string)
# print the min ascii character
print(minchar)

Output:

b

The min() function compared the ASCII values of the characters in the string and returned the character with the smallest ASCII value.

4)Finding min string from list of strings using min() function

Assume we have a list of strings.
Since list is an Iterable, we may directly transfer it to the min() function to find the minimum string based on alphabetical order in the list.

Below is the implementation:

# given list of strings
strings_list = ["hello", "this", "is", "BTechGeeks"]
# finding min string  in given list of strings
minstring = min(strings_list)
# print the min string
print(minstring)

Output:

BTechGeeks

5)Finding min value and key in dictionary

We can get min value in dictionary by using lambda function as given below.

Below is the implementation:

# given dictionary
dictionary = {'Hello': 238, 'This': 135,
              'is': 343, 'BTechGeeks': 50, 'Platform': 688}
# fet the min value and key in dictionary using lambda and min () function
min_Value = min(dictionary.items(), key=lambda x: x[1])
print('Min value in dictionary : ', min_Value)

Output:

Min value in dictionary :  ('BTechGeeks', 50)

6)min() function with multiple arguments

We may also transfer individual elements to the min function rather than any Iterable.

Below is the implementation:

# min() function with multiple arguments
minvalue = min(100, 24, 454, 22, 989, 12, 5, 467)
# print the min value
print(minvalue)

Output:

5

Related Programs:

What is Hashing and Hash Table

What is Hashing and Hash Table?

Hashing and Hash Table

1)Hashing

Hashing is the process of mapping object data to a representative integer value using a function or algorithm.

This hash code (or simply hash) can then be used to narrow our quest when searching for the item on the map.

These hash codes are usually used to create an index at which the value is stored.

2)Hash Table

A hash table is a data structure that stores data associatively. Data is stored in an array format in a hash table, with each data value having its own unique index value. When we know the index of the desired data, we can access it very quickly.

As a result, it becomes a data structure in which insertion and search operations are extremely quick, regardless of the size of the data. Hash Tables use an array as a storage medium and use the hash technique to produce an index from which an element is to be inserted or located.

3)Features of HashTable

  • It works in the same way as HashMap, but it is synchronised.
  • In a hash table, a key/value pair is stored.
  • In Hashtable, we define an object that will be used as a key, as well as the value that will be associated with that key. The key is then hashed, and the resulting hash code serves as the index for storing the value in the table.
  • The default capacity of the Hashtable class is 11, and the loadFactor is 0.75.
  • HashMap does not support Enumeration, while Hashtable does not support fail-fast Enumeration.

4)Adding element in HashTable

When an entity is inserted into a Hash Table, its hash code is measured first, and the bucket in which it will be stored is determined based on that hash code.

Let us illustrate this with an example.

For instance, suppose we want to store some numbers in a Hash Table, i.e.

32 , 45 , 64 , 92 , 57 , 88 , 73

Internally, this Hash Table can use 10 buckets, i.e.

The Hash Code will be returned by our Hash Function.

HashCode=Element_value%10

This Hash code for,

32 will be 2

45 will be 5

64 will be 4

92 will be 2

57 will be 7

88 will be 8

73 will be 3

Now, each element’s hash code will be used to determine where that element will be stored, for example, 45 will be stored in bucket 5 since its hash code is 5. In the same way, all elements will be stored in the bucket that corresponds to their hash code.

5)Hashing Collisions

As we can see, the hash code for both 32 and 92 is the same, which is 2. In Hashing, this is referred to as Collision. Both components would be deposited in the same bucket if they collide.

6)Searching element in Hash Table

If we want to check for an element in a hash table, we must first calculate the hash code for that element. Then, using the hash code, we’ll go straight to the bucket where this element will be saved. Now, there may be several elements in that bucket; in that case, we’ll look for our element only in those elements.

Assume we want to find 45 in the hash table in the previous case.

Then we’ll measure the hash code, which will be 45 %10 = 5.

Then we’ll go straight to bucket no. 5 and search for the factor there.

7)Best Case Time Complexity in Hashing

From the viewpoint of searching, each bucket containing only one element in the Hash table is the best case scenario. In such a case, searching time would require the following effort:

The complexity of calculating hash codes is O(1)

If the bucket only contains one element, choosing that element from the bucket is a complex task O(1)

Consequently In the best case scenario, finding an element would be difficult O(1)

While the complexity of a collision, i.e. several elements in a bucket, will be O(no. of elements in bucket), it will be much less than the complexity of searching an element from a List, which will be O(n).

8)Worst Case Time Complexity in Hashing

The worst case scenario in hashing is when the Hash Function is not correctly implemented, resulting in the same hash code for several elements.

Assume the following is our hash function:

Hash code = given_element / 100

Then, in the preceding case, the hash code for all elements ( 32 , 45 , 64 , 92 , 57 , 88 , 73 ) will be 0. As a result, all elements will be saved in bucket 0.

Since all components are in the same bucket, complexity is at its highest in this case. As a result, the complexity will be O(n) since it must check for the appropriate element among all elements.

Related Programs:

Iterator, Iterable and Iteration Explained with Examples

Python : Iterator, Iterable and Iteration Explained with Examples

Iterator , Iterable and Iteration with Examples

1)Iterable

Iterable is a type of object that is made up of other components. Iterables include things like list and tuple. It’s identical to any Java collection class or C++ container class. When the iter() function on an Iterable object is called in Python, an Iterator is returned, which can be used to iterate over the elements inside Iterable.

If a class has overloaded the magic method __iter__() in Python, it is called Iterable. The Iterator object must be returned by this feature.

2)Iterator

In Python, an iterator is an entity that iterates over iterable objects such as lists, tuples, dicts, and sets. The iter() method is used to create the iterator item. It iterates using the next() form.

The iterator’s initialization is handled by the __iter(iterable)__ process. Next ( __next__ in Python 3) returns an iterator item. The iterable’s next value is returned by the next process. When we use a for loop to traverse some iterable object, it uses the iter() method to obtain an iterator object, which we then iterate over using the next() method. To signal the end of the iteration, this method raises a StopIteration.

3)Iteration

Iteration is the method of looping through all of the elements of an Iterable with the help of an Iterator object. We can iterate in Python using for loops or while loops.

4)Traverse/Iterate over list (Iterable) using Iterator

Since the __iter__() feature, which returns an Iterator, has been overloaded in Python, List is an Iterable item. The iter() function is used to get the Iterator object from an Iterable object. From the list, let’s get the Iterator object.

Since the __next__() function is overloaded, it returns a list iterator object, which is essentially an Iterator. You may also look at the Iterator form that was returned.
Let’s use this iterator object to loop through the contents of the list.

Below is the implementation:

# given list
givenlist = ["hello", "this", "is", "BTechGeeks"]
# getting the iterator of the list
itrlist = iter(givenlist)
# Traverse the list using iterator
while True:
    try:
        # getting next element in the list using next()
        element = next(itrlist)
        print(element)
    except StopIteration:
        break

Output:

hello
this
is
BTechGeeks

Explanation:

Call the next() function on the Iterable’s iterator object to get the next value. It will return the Iterable’s next value. To get all elements of iterable one by one, keep calling this next() function. When the iterator reaches the end of the iterable’s components, the StopIteration error is thrown.

As previously said, the next() function is similar to Python’s hasnext() function. It is used to get the Iterable’s next value.

5)Iterate over an Iterable (list) using for loop

Python has a fantastic for loop that iterates over the Iterable object using Iterator. For example, we can use the for loop to iterate over the elements in a list (Iterable).
Internally, the for loop does the same thing, retrieving the Iterator from Iterable and using it to iterate over the elements in Iterable. However, it offers a short hand form; we don’t need to write a large while loop or catch StopIteration errors ourselves because it handles everything internally.
We may iterate over other Iterables as well, such as list, tuple, and custom Iterators.

Below is the implementation:

# given list
givenlist = ["hello", "this", "is", "BTechGeeks"]
# traverse the list using for loop
for element in givenlist:
    print(element)

Output:

hello
this
is
BTechGeeks

6)Python Iter() function

When the iter() function is called, the passed object is passed to the __iter__() function, which returns the value received by it. Iterable refers to a class that has an overloaded __iter__() function and is supposed to return an Iterator object.

7)Python next() function

When the next() function is called, the passed object is passed to the __next__() function, which returns the value returned by it. Iterator objects, in essence, overload the __next__() function, returning the next value from the corresponding Iterable item.
Related Programs:

If..Elif…Else Statement

Python – If..Elif…Else Statement

You must monitor the flow of your program when writing code in any language. This is usually the case when there is decision-making involved: you’ll want to run one set of code if a condition is met, and a different set of code if it isn’t. The if, elif, and else statements in Python are useful for this.

We’ll learn how to use the if…elif…else declaration to change the flow of code in several directions based on a conditional expression in this article.

If..Elif…Else Statement in Python

1)Need of If..Elif..Else statement

For example, suppose we have a variable p and want our program to behave as follows:

If p is greater than 50 but less than 100, only statements 1 and 2 should be run.
If p is greater than 100 but less than 200, only statements 3 and 4 should be executed.
If p is greater than 200 but less than 300, only statements 5 and 6 should be executed.
If none of the above conditions apply to x, then only statements 7 and 8 should be executed.
According to the rationale above, only two statements should be executed for any value of p.

Now we want to monitor the execution flow in our software so that, depending on the value of x, code flow can be changed to one of four different directions.The if…elif…else declaration makes this easy.

2)Syntax of if..elif..else

if condition1:
    Statement_1
    Statement_2
elif condition2:
    Statement_3
    Statement_4
elif condition3:
    Statement_5
    Statement_6
else:
    Statement_7
    Statement_8

We can have any number of elif blocks after the if-block. However, we can only have one more block in the end. Just one of these code blocks will be executed. When the interpreter comes across an if…elif…else block, it,

  • If the condition in the if-statement evaluates to True, the code in the if block is executed, and the remaining elif and else blocks are skipped.
  • If the condition in the if-statement evaluates to False, the code in the if-block is skipped, and the condition in the first elif statement is evaluated, and if that evaluates to True, the code in the elif block is executed, and the remaining elif and else blocks are skipped.
  • If the elif condition evaluates to False, the programme skips the elif block and moves on to the next. If the next block is also an elif, the process repeats until it either finds an else block or an elif block where the condition evaluates to True.
  • If none of the if-requirements statement’s were met, and all elif statements returned False. Since there is no condition associated with the else block, the interpreter hops to the else-block and executes all of the statements in the else-block.

So, if any of the conditions in the if-statement and all of the elif-statements evaluate to False, the code in the else-block is executed.

3)Examples of if..elif..else

Example -1:

p = 56
if p < 100:
    print('If block executed')
    print('p is smaller than 100')
elif 100 <= p < 200:
    print('first elif block is executed')
    print('p is between 100 and 200')
elif 200 <= p < 300:
    print('second elif block is executed')
    print('p is between 200 and 300')
else:
    print('Else block is executed')
    print('p is greater than 300')

Output:

If block executed
p is smaller than 100

Explanation:

Since the value of p is 56, the if-statement condition evaluates to True. As a result, it only ran the code in the if-block, skipping all of the elif and else blocks.

Example-2:

p = 156
if p < 100:
    print('If block executed')
    print('p is smaller than 100')
elif 100 <= p < 200:
    print('first elif block is executed')
    print('p is between 100 and 200')
elif 200 <= p < 300:
    print('second elif block is executed')
    print('p is between 200 and 300')
else:
    print('Else block is executed')
    print('p is greater than 300')

Output:

first elif block is executed
p is between 100 and 200

Explanation:

Since x is 156, the if-statement condition evaluates to False, but the first elif-statement condition evaluates to True. As a result, the if-block was skipped and only the code in the first elif block was executed. The rest of the elif and else blocks are skipped.

Example-3:

p = 256
if p < 100:
    print('If block executed')
    print('p is smaller than 100')
elif 100 <= p < 200:
    print('first elif block is executed')
    print('p is between 100 and 200')
elif 200 <= p < 300:
    print('second elif block is executed')
    print('p is between 200 and 300')
else:
    print('Else block is executed')
    print('p is greater than 300')

Output:

second elif block is executed
p is between 200 and 300

Explanation:

Since x is 256, the if-block and first elif-block were skipped. In comparison, the code was only executed in the second elif-block. The rest of the elif and else blocks are skipped.

Example-4:

p = 469
if p < 100:
    print('If block executed')
    print('p is smaller than 100')
elif 100 <= p < 200:
    print('first elif block is executed')
    print('p is between 100 and 200')
elif 200 <= p < 300:
    print('second elif block is executed')
    print('p is between 200 and 300')
else:
    print('Else block is executed')
    print('p is greater than 300')

Output:

Else block is executed
p is greater than 300

Related Programs:

If…Else Statement

Python – If…Else Statement

In real life, there are times when we must make choices and decide what to do next based on those decisions. Similar scenarios occur in programming where we must make decisions and then execute the next block of code based on those decisions.

In programming languages, decision making statements determine the flow of program execution.

If..Else Statement in Python

1)If statement

The if statement is the simplest decision-making statement. It is used to determine whether or not a specific statement or block of statements will be executed, i.e. if a certain condition is valid, then a block of statements is executed, otherwise not.

Syntax:

if condition:
    # statements which should be executed

In this case, the condition will be either true or false after evaluation. The if statement accepts boolean values – if the value is valid, the block of statements below it will be executed; otherwise, it will not. We may also use condition with bracket ‘(‘ ‘)’.

Python, as we know, uses indentation to define a block. As a result, the block inside an if statement will be found, as seen in the example below.

if condition:
   statement1
statement2

#If the condition is valid, the if block will only consider
# statement1 to be within its block.

Example:

age = 18
if (age > 15):
    print("age is greater than 15")
print("Statement after if block")

Output:

age is greater than 15
Statement after if block

2)If-else statement

When the interpreter encounters an if argument, it evaluates the condition in the if-statement, and if that condition evaluates to True, it executes the suite in the if-block, i.e., the statements in the if-block and skips the statements in the else portion.

If the condition in the if-statement evaluates to False, the suite in the else block is executed directly, i.e., the statements in the else block are executed instead of the statements in the if block.

Syntax:

if condition:
    statement_1
    statement_2
    statement_3
else:
    statement_4
    statement_5
    statement_6

3)Examples of If else statement

age = 13
if (age > 15):
    print("age is greater than 15")
else:
    print("age is less than 15")

Output:

age is less than 15

Explanation:

Here age is less than 15 so if condition is false and else statement is executed

4)If statement with multiple conditions

In all of the preceding instances, we provide a single condition with the if-statement, but we can also provide multiple conditions.

age = 13
# checking if the age is between 10 to 20
if (age > 10 and age < 20):
    print("ageis between 10 to 20")
else:
    print("age is less than 15")

Output:

age is between 10 to 20

Explanation:

The if-statement in this case checks several conditions, and if all of them satisfy and evaluate to True, the interpreter executes the code in the if-block.
Related Programs: