Python

Python Interview Questions on Python Conditionals

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Python Conditionals

Question 1.
What constitutes “True” in Python?
Answer:
A true expression is any expression that does not evaluate to 0, the empty list [ ], tuple ( ), dictionary { } or the objects None or False.

Question 2:
What are the three main conditional statements in Python?
Answer:
if, elif, and else

Question 3:
What are the comparison operators in Python?
Answer:
< Less than, > Greater than, <= Less than or equal to, >= Greater than or equal to, = Equal to, != not equal, o alternative not equal. Note a single = is NOT a Python comparison operator, it is an assignment operator only.

Question 4:
Illustrate a basic if, elif, else structure.
Answer:
if <condition>:
. . .
elif<another condition>:
. . .
else:
. . .
Question 5:
In Python 2.5+, the equivalent of a tertiary operator has been added to the language. Provide an example of its use.
Answer:
myValue = ‘Positive’ if myNumber > 0 else ‘Negative or Zero’

Question 6:
What does elif mean?
Answer:
It means else if. It is used after an if statement, to do another comparison.

Question 7.
What would the output be from the following code? a =4 If a = 5:
Print “True”
Else:
Print “False”
Answer:
This is a trick question. The a = 5 is not a comparison operator, but an assignment. It will yield “True”. The correct coding would be a == 5.

Question 8:
How are if, elif, and else blocks defined?
Answer:
All blocks in Python are defined by indenting. All lines of a particular code block must have the same level of indenting.

Question 9:
Illustrate a switch-case equivalent using if-elif-else.
Answer:
if item=valueA:
. . .
elif item == valueB:
. . .
elif item = =  valueC:
. . .
elifitem = valueN:
. . .
else:
… #default code

Question 10:
How is the Python switch statement used?
Answer:
This is a trick question, there is no built-in switch statement in Python, which is unusual. A switch statement can be easily created using if-elif using lambda or with Python dictionaries.

Question 11:
Using a dictionary, create an equivalent to a switch case statement.
Answer:
deffunc1( ):
. . .
deffunc2( ):
. . .
switch = {
‘Aardvark’: fund1,
‘Armadillo’: fund2,
}
mySwi tchKey= “Armadillo ”

switch[mySwitchKey]( ) #callsJunc2( )
switch[‘Aardvark’]( ) #calls func1( )

Question 12:
Illustrate comparing two strings for equality in a case insensitive manner.
Answer:
if stringl. lower ( ) = string2.lower ( ):
#Note: .upper( ) is equally valid.

Question 13:
Illustrate comparing two strings, printing if the first string is longer, equal, or shorter than the second string.
Answer:
if len(stringl) > len(string2):
print “Stringl is longer than string2.”
elif len(stringl) < len(string2):
print “String1 is shorter than string2.”
else:
print “String1 is the same length as string2.”

Question 14:
When comparing two d^tes, what method is used?
Answer:
Date.toordinal( ) Otherwise, Python would compare the dates by their object address.

Question 15:
In comparing dates and DateTime objects, what happens when one comparand is naive and the other aware?
Answer:
A TypeError is raised.

Question 16:
What happens when you try to compare a DateTime object with other classes of objects?
Answer:
A TypeError is raised.

Question 17:
When are dictionaries considered equal?
Answer:
If and only if their sorted lists compare equally.

Question 18:
How is collection membership determined?
Answer:
Using the in and not in operators.

Question 19:
Illustrate how collection membership determination would be written.
Answer:
if x in collection:
print “It is in the collection”
else:
print “Not in the collection.”

Question 20:
How is object identity tested? Illustrate with an example.
Answer:
Using the is and is not operators.
if x is objecttype:
print “x is the type you thought it was.
else:
print “x isn’t an objecttype.”

Python Interview Questions on Python Conditionals Read More »

Python Interview Questions on Searching and Sorting

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Searching and Sorting

Sequential Search

In the chapter based on Python operators, we have seen that we can make use of the membership operator ‘in’ to check if a value exists in a list or not.

    >>> list.1 = [1,2,3,4,5,6,71
    >>> 3 in list1
   True
    >>> 8 in list1
    False
    >>>

This is nothing but searching for an element in a list. We are going to look at how elements can be searched and how process efficiency can be improved. We start by learning about sequential search.

The simplest way of searching for an element in a sequence is to check every element one by one. If the element is found then the search ends and the element is returned or else the search continues till the end of the sequence. This method of searching is known as linear search or sequential search. It follows a simple approach but it is quite an inefficient way of searching for an element because we move from one element to the other right from the beginning to end and if the element is not present in the sequence we would not know about it till we reach the last element.

Time analysis for sequential search:

  • Best scenario is that the element that we are looking for is the very first element in the list. In this case, the time complexity will be 0(1).
  • The worst scenario would be if we traverse throughout the entire sequence and realize that the element that we are looking for, does not exist. In this case, the time complexity will be O(n).

Python Interview Questions on Searching and Sorting chapter 14 img 1

Question 1.
Sequential search is also known as _______
Answer:
Linear Search

Question 2.
How are the elements reviewed in sequential search?
Answer:
The elements are reviewed one at a time in sequential terms.

Question 3.
When does the sequential search end?
Answer:
The sequential search ends when an element is found or when the end of the sequence is reached.

Question 4.
Write code to implement sequential search.
Answer:
The sequential search can be implemented as follows:

  • The function takes two values: seq list which is the list and target_ num which is the number to search in the list.
  • We set search_flag = 0 if the target number is found in the list we will set the search_flag to 1 else we let it be 0.
  • We iterate through the list comparing each element in the list with the target_num.
  • If a match is found we print a message and update the search_flag to 1.
  • After the “for” loop if the search_flag is still 0 then it means that the number was not found.

Code

def sequential__search (seq_list, target_num) :
    search_flag = 0
    for i in range(len(seq_list)):
        if seq_list[i] == target_num:
           print("Found the target number ", target_num, " at index", i,".")
            search_flag = 1;
    if search_flag == 0:
       print("Target Number Does Not Exist.Search Unsuccessful.")

Execution

seq_list = [1,2,3,4,5,6,7,8,2,9,10,11,12,13,14,15, 16]
target__num = input ("Please enter the target number : ")
sequential_search(seq_list, int(target_num))

Output 1

Please enter the target number: 5
Found the target number 5 at index 4.

Output 2

Please enter the target number: 2
Found the target number 2 at index 1.
Found the target number 2 at index 8.

Output 3

Please enter the target number: 87
Target Number Does Not Exist. Search Unsuccessful.

Question 5.
How would you implement a sequential search for an ordered list?
Answer:
When elements in a list are sorted, then many times there may not be the need to scan the entire list. The moment we reach an element that has a value greater than the target number, we know that we need not go any further.

Step 1: We define a function sequential_search() that takes two arguments – a list (seq_list) and the number that we are looking for (target num).

def sequential_search(seq_list, target_num):

Step 2: The first thing we do is set define a flag (search_flag) and set it to “False’’ or “0” value. The flag is set to “True” or “1” if the element is found. So, after traversing through the list if the search_flag value is still “False” or “0”, we would know that the number that we are looking for does not exist in the list.

def sequential__search (seq_list, target_num) :
    search_flag = 0

Step 3: Now, it’s time to check the elements one by one so, we define the for loop:

def sequential_search(seq_list, target_num):
    search_flag = 0
    for i in range(len(seq_list)):

Step 4: We now define how the elements are compared. Since it is an ordered list for every “i” in seq_list we have to check if i > target_num. If yes, then it means that there is no point moving further as it is an ordered list and we have reached an element that is greater than the number that we are looking for. However, if seq_list[i] == target_num then, the search is successful and we can set the search_flag to 1.

def sequential_search(seq_list, target^num):
    search_flag = 0
    for i in range(len(seq_list)):
        if seq_list[i] > target_num:
           print("search no further.")
           break;
       elif seq_list[i] == target_num:
            print("Found the target number ", target_num, " at index", i,".")
            search_flag = 1;

Step 5: After the for loop has been executed if the value of search_flag is still 0 then a message stating that the target number was not found must be displayed.

Code

def sequential_search(seq_list, target_num):
      search_flag = 0
      for i in range(len(seq_list)):
          if seq_list[i] > target_num:
             print("search no further.")
             break;
         elif seq_list[i] == target_num:
              print("Found the target number ", target_num, " at index", i,".")
              search_flag = 1 ;

      if search_flag == 0 ;
      print ("Target Number Does Not Exist. search Unsuccessful.")

Execution

seq_list = [1,2,3,4,5,6,7,8,2,9,10,11,12,13,14,15, 16]
target_num = input ("Please enter the target number : ")
sequential_search(seq_list, int(target_num))

Output 1

Please enter the target number: 2
Found the target number 2 at index 1.
Found the target number 2 at index 2.
search no further.
>>>

Output 2

Please enter the target number: 8
Found the target number 8 at index 8.
Search no further.
>>>

Output 3

Please enter the target number: 89
Target Number Does Not Exist. Search Unsuccessful.
>>>

Binary Search

A binary search is used to locate a target value from a sorted list. The search begins from the center of the sequence. The element present at the center is not equal to the target number it is compared with the target number. If the target number is greater than the element at the center then it means that we need to search for the number in the right half of the list and the left half need not be touched. Similarly, if the target number is less than the element present in the center then we will have to direct our search efforts towards the left. This process is repeated till the search is completed. The beauty of binary search is that in every search operation the sequence is cut into half and focus is shifted to only that half that has chances of having the value.

Python Interview Questions on Searching and Sorting chapter 14 img 2

Question 6.
Write a code to implement the binary search function.
Answer:
The binary search can be implemented in the following manner:
Step 1: Define the binary_search function. It takes 4 parameters:

  • sorted list: the input list that is in sorted form
  • target_num: the number that we are looking for
  • starting_point: the place from where we want to start searching, default value = 0
  • end_point: The endpoint for search, default value = None

Note that the list will be split in half in every step so the starting and ending point may change in every search operation.

def binary_search(sorted_list, target_num, start_ point=0, end_point=None):

Step 2: Do the following:

  • Set the search_flag to “False”
  • If the end_point is not provided, it would have the default value of “None”, set it to the length of the input list.
def binary_search(sorted_list, target_num, 
start_point=0, end_point=None):
     search_flag = False
     if end_point == None:
        end_point = len(sorted_list)-1

Step 3: Check, the start_point should be less than the endpoint. If that is true, do the following:

  • Get midpoint index value: mid_point = (end_point+start_point)//2
  • Check the value of the element at mid_point. Is it equal to the target_ num?
  • If sorted_lLst[midjioint] == target num1
  • Set search flag to True
  • If not check if the value at mid_point is greater than target_num :
  • sorted_list[mid_point] > target num
  • If yes, then we can discard the right side of the list now we can repeat the search from beginning to mid_point-1 value. Set
    endpoint to mid_point – 1. The starting point can remain the same(0).
  • The function should now call itself with:
  • sorted_list: same as before
  • target_num: same as before
  • starting point: same as before
  • endpoint: mid_point – 1
  • If not check if the value at mid_point is lesser than target num :
  • sorted_list[mid_point] < target_num
  • If yes, then the left side of the list is not required. We can repeat the search from mid_point+1 to the end of the list. Set starting point to mid_point+1. The ending_point can remain the same.
  • The function should now call itself with:
  • sorted_list: same as before
  • target_num: same as before
  • starting point: mid_point+l
  • end_point: same as before
  • If at the end of this procedure the search_flag is still set to “False”, then it means that the value does not exist in the list.

Code

def binary_search(sorted_list, target_num, start_ point=0, end_point=None):
       search_flag = False
       if end_point == None:
          end_point = len(sorted_list)-1
       if start_point < end_point:
          mid_point = (end_point+start_point)//2
          if sorted_list[mid_point] == target_num:
             search_flag = True
             print(target_num," Exists in the list at ",sorted_list.index(target_num))
             elif sorted_list[mid_point] > target_num:
                  end_point = mid_point-l 
                  binary_search(sorted_list, target_ num,start_point, end_point)
            elif sorted_list[mid_point] < target_num:
            start_point = mid_point+l 
            binary_search(sorted_list, target_num, start_point, end_point)
       elif not search_flag:
             print(target_num," Value does not exist")

Execution

sorted_list=[ 1,2,3,4,5,6,7,8,9,10,11,12,13]
binary_search(sorted_list, 14)
binary_search(sorted_list,0)
binary_search(sorted_list,5)

Output

14 Value does not exist 
0 Value does not exist 
5 Exists in the list at 4

Hash Tables

Hash Tables are data structures where a hash function is used to generate the index or address value for a data element. It is used to implement an associative array that can map keys to values. The benefit of this is that it allows us to access data faster as the index value behaves as a key for data value. Hash tables store data in key-value pairs but the data is generated using the hash function. In Python, the Hash Tables are nothing but Dictionary data type. Keys in the dictionary are generated using a hash function and the order of data elements in Dictionary is not fixed. We have already learned about various functions that can be used to access a dictionary object but what we actually aim at learning here is how hash tables are actually implemented.

We know that by binary search trees we can achieve the time complexity of O(logn) for various operations. The question that arises here is that can search operations be made faster? Is it possible to reach a time complexity of 0(1)11 This is precisely why hash tables came into existence? Like in a list or an array if the index is known, the time complexity for search operation can become 0(1). Similarly, if data is stored in key-value pairs, the result can be retrieved faster. So, we have keys and we have slots available where the values can be placed. If we are able to establish a relationship between the slots and the key it would be easier to retrieve the value at a fast rate. Look at the following figure:

Python Interview Questions on Searching and Sorting chapter 14 img 3

The key value is not always a nonnegative integer, it can be a string also, whereas the array has an index starting from 0 to length_of_array -1. So there is a need to do prewashing in order to match the string keys to indexes. So, for every key, there is a need to find an index in an array where the corresponding value can be placed. In order to do this, we will have to create a hash( ) function that can map a key of any type to a random array index.

During this process, there are chances of collision. Collision is when we map two keys to the same index as shown in the following figure:

Python Interview Questions on Searching and Sorting chapter 14 img 4

To resolve collision we can use chaining. Chaining is when values are stored -in the same slot with the help of a linked list as shown in the following figure:

Python Interview Questions on Searching and Sorting chapter 14 img 5

However, there can be cases of more than one collision for the same spot, and considering the worst-case scenario where there is a need to insert all values as elements of a linked list, it can be a tough situation that will have a severe impact on the time complexity. Worst case scenario will be if we land up placing all values as linked list elements at the same index.

To avoid this scenario we can consider the process of open addressing. Open addressing is the process of creating a new address. Consider a case where if there is a collision we increment the index by 1 and place the value there as shown below, there is collision while placing val3, as val2 already exists at index 1. So, the index value is incremented by 1 (1+1 =2) and val3 is placed at the index

Python Interview Questions on Searching and Sorting chapter 14 img 6

Had there been any other value at index 2 then the index would have incremented again and val3 could be placed at index 3. This means that this process of incrementing the index is continued till an empty slot is spotted. This is called Linear probing. Quadratic probing on the other hand increments by two times the index value. So, the search for the empty slots is done at a distance of 1,2,4,8, and so on. Rehashing is the process of hashing the result obtained again to find an empty slot.

The purpose of the hash function is to calculate an index from which the right value can be found therefore its job would be:

  1. To distribute the keys uniformly in the array.
  2. If n is the number of keys and m is the size of an array, the hash( ) = n%m(modulo operator) in case we use integers as keys.
  3. Prefer to use prime numbers both for array and the hash function for uniform distribution
  4. For string keys, you can calculate the ASCII value of each character and add them up and make a modulo operator on them

In many scenarios, hash tables prove to be more efficient than the search trees and are often used in caches, databases, and sets.
Important points:

  1. You can avoid clustering by using prime numbers.
  2. The number of entries divided by the size of the array is called the load factor.
  3. If the load factor increases the number of collisions will increase. This will reduce the performance of the hash table.
  4. Resize the table when the load factor exceeds the given threshold. However, this would be an expensive option as the hashes of the values entered will change whenever resizing is done and this can take O(n) to complete. Hence dynamic size array may be inappropriate for real-time scenarios.

Question 7.
What does the hash function do?
Answer:
The purpose of a hash function is to map the values or entries into the slots that are available in a hash table. So, for every entry, the hash function will compute an integer value that would be in the range of 0 to m-1 where m is the length of the array.

Question 8.
What is a remainder hash function? What are the drawbacks? Write the code to implement the remainder hash function.
Answer:
The remainder hash function calculates the index value by taking one item at a time from the collection. It is then divided by the size of the array and the remainder is returned.
h(item) = item% m, where m = size of the array Let’s consider the following array:
[18, 12,45,34, 89, 4]
The above array is of size 8.

Python Interview Questions on Searching and Sorting chapter 14 img 7

Drawback: You can see here that 18 and 34 have the same hash value of 2 and 12 and 4 have the same hash value of 4. This is a case of collision as a result when you execute the program, values 18 and 12 are replaced by 34 and 4 and you will not find these values in the hash table.

Let’s have a look at the implementation:

Step1: Define the hash function that takes a list and size of the array as input.
def hash(list_items, size):

def hash(list items, size) :

Step2: Do the following:

  • Create an empty list.
  • Now populate this key ‘from the numbers 0 to size mention. This
    example takes a list of 8 elements so we are creating a list [0, 1, 2, 3, 4, 5,6, 7].
  • Convert this list to diet using from keys( ). We should get a dictionary object of form {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None}. This value is assigned to hash_table.
def hash(list_items, size):
temp_list =[ ]
for i in range(size):
      temp_list.append(i)
'hash_table = diet.fromkeys(temp_list)

Step3:

  • Now iterate through the list.
  • Calculate the index for every item by calculating item%size.
  • For the key value in the hash_table = index, insert the item.

Code

def hash(list_items, size):
     temp_list =[ ]
     for i in range(size):
          temp_list.append(i)
     hash_table = diet.fromkeys(temp_list)
     for item in list_items:
         i = item%size
         hash_table[i] = item
    print("value of hash table is : ",hash_table)

Execution

list_items = [18,12,45,34,89,4]
hash(list_items, 8)

Output

value of hash table is : {0: None, 1: 89, 2: 34,
3: None, 4: 4, 5: 45, 6: None, 7: None}
>>>

Question 9.
What is a folding hash function?
Answer:
The folding hash function is a technique used to avoid collisions while hashing. The items are divided into equal-size pieces, they are added together and then the slot value is calculated using the same hash function (item%size).

Suppose, we have a phone list as shown below:

phone_list= [4567774321, 4567775514, 9851742433, 4368884732]

We convert every number to a string, then each string is converted to a list, and then each list is appended to another list and we get the following result:
[[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7\ ‘4’, ‘3’, ‘2’, ‘1’], [‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘5’, ‘5’’, ‘1’, ‘4’], [‘9’, ‘8’, ‘5’, ‘1’, ‘7’, ‘4’, ‘2’, ‘4’, ‘3’, ‘3’], [‘4’, ‘3’, ‘6’, ‘8’, ‘8’, ‘8’, ‘4’, ‘7’, ‘3’, ‘2’]]

Now from this new list, we take one list item one by one, for every item we concatenate two characters convert them to integer, and then concatenate next to characters convert them to integer, and add the two values and continue this till we have added all elements. The calculation will be something like this:
[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘4’, ‘3’, ‘2’, ‘1’]

1. items =45
string val = 45
integer value = 45
hash value= 45

2. items =67
string val = 67
integer value = 67
hash value= 45+67 =112

3. items =77
string val = 77
integer value = 77
hash value= 112+77 =189

4. items =43
string val = 43
integer value = 43
hash value= 189+43 = 232

5. items =21
string val = 21 ,
integer value = 21
hash value= 232+21 = 253 Similarly,
[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘5’, ‘5’, ‘1’, ‘4’] will have a hash value of 511.
[‘9’, ‘8’, ‘5’, ‘1’, ‘7’, ‘4’, ‘2’, ‘4’, ‘3’, ‘3’] will have a hash value of 791.
[‘4’, ‘3’, ‘6\ ‘8’, ‘8’, ‘8’, ‘4’, ‘7’, ‘3’, ‘2’] will have a hash value of 1069.
We now call the hash function for [253, 531, 791, 1069] for size 11.
Python Interview Questions on Searching and Sorting chapter 14 img 8

So, the result we get is:
{0: 253, 1: None, 2: 1069, 3: None, 4: None, 5: 511, 6: None, 7: None, 8: None, 9: None, 10: 791}

Question 10.
Write the code to implement the coding hash function.
Answer:
Let’s look at the execution statements for this program:

phone_list = [4567774321, 4567775514, 9851742433, 4368884732]
str_phone_values = convert_to_string(phone_list)
folded_value = foldingjiash(str_phone_values)
folding_hash_table = hash(folded_value,11)
print(folding_hash_table)

1. A list of phone numbers is defined: phonejist = [4567774321, 4567775514, 9851742433, 4368884732]
2. The next statement “str_phonepy allies = convert_to_string(phone_ list)” calls a function convert to_string( ) and passes the phone_list as argument. The function in turn returns a list of lists. The function takes one phone number at a time converts it to a list and adds to new list. So, we get the output as: [[‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘4’, ‘3’, ‘2’, M’], [‘4’, ‘5’, ‘6’, ‘7’, ‘7’, ‘7’, ‘5’, ‘5’, ‘1’, ‘4’], [‘9’, ‘8’, ‘5’, ‘1’, ‘7’, ‘4’, ‘2’, ‘4’, ‘3’, ‘3’], [‘4’, ‘3’, ‘6’, ‘8’, ‘8’, ‘8’, ‘4’, ‘7’, ‘3’, ‘2’]]. The following steps are involved in this function:

a. Define two lists a phone_list[ ]
b. For elements in phone_list, take every element i.e. the phone number one by one and:
i. convert the phone number to string: temp_string = str(i)
ii. Convert each string to list: tempjist = list (temp_string)
iii. Append the list obtained to the phone_list defined in previous step.
iv. Return the phone_list and assign values to str_phone_ values

def convert_to_string(input_list):
phone_list=[ ]
for i in input_list:
temp_string = str(i)
temp_list = list(temp_string)
phone_list.append(temp_list)
return phone_list

3. The list str_phone_values is passed on to folding_hash( ). This method takes a list as input.
a. It will take each phone list element which is also a list.
b. Take one list item one by one.
c. For every item concatenate first two characters convert them to integer and then concatenate next to characters convert them to integer and add the two values.
d. Pop the first two elements from thr list.
e. Repeat c and d till we have added all elements.
f. The function returns a list of hash values.

def folding_hash(input_list):
    hash_final = [ ]
    while len(input_list) > 0:
         hash_val = 0
         for element in input_list:
             while len(element) > 1:
                 stringl = element[0]
                 string2 = element[1]
                 str_contbine = string1 + string2
                 int_combine = int(str_combine)
                 hash_val += int_combine
                 element.pop(0)
                 element.pop(0)
             if len(element) > 0:
                hash_val += element[0]
             else:
                pass
             hash_final. append (hash_val)
        return hash final

4. Call hash function for size 11. The code for the hash function is same.

def hash(list_items, size):
    temp_list =[ ]
    for i in range (size) :
        temp_list.append(i)
    hash_table = diet.fromkeys(temp_list)
    for item in list_items:
        i = item%size
        hash_table[i] = item
    return hash_table

Code

def hash(list_items, size):
    temp_list =[ ]
    for i in range(size):
        temp_list.append(i)
    hash_table = diet.fromkeys(temp_list)
    for item in list_items:
        i = item%size
        hash_table[i] = item
   return hash_table
def convert_to_string(input_list):
    phone_list=[ ]
    for i in input_list:
        temp_string = str(i)
        temp_list = list(temp_string)
        phone_list.append(temp_list)
   return phone_list
def folding_hash(input_list):
    hash_final = [ ]
    while len(input_list) > 0:
         hash_val = 0
         for element in input_list:
             while len(element) > 1:
                 string1 = element[0]
                 string2 = element[1]
                 str_combine = string1 + string2
                 int_combine = int(str_combine)
                 hash_val += int_combine
                 element.pop(0)
                 element.pop(0)
            if len(element) > 0:
                hash_val += element[0]
           else:
              pass
           hash_final. append (hash_val)
    return hash_final

Execution

phone_list = [4567774321, 4567775514, 9851742433, 4368884732]
str_phone_values = convert_to_string(phone_list)
folded_value = folding_hash (str_phone_valu.es)
folding_hash_table = hash(folded_value,11)
print(folding_hash_table)

Output

{0: 253, 1: None, 2: 1069, 3: None, 4: None, 5:
511, 6: None, 7: None, 8: None, 9: None, 10: 791}

In order to store phone numbers at the index, we slightly change the hash() function;

  1. The hash( ) function will take one more parameter : phone_list
  2. After calculating the index the corresponding element from the phone_list is saved instead of the folded_value.
def hash(list_items,phone_list, size):
    temp_list =[ ]
    for i in range(size):
        temp_list.append(i)
   hash_table = diet.fromkeys(temp_list)
   for i in range(len(list_items)):
       hash_index = list_items[i]%size
       hash_table[hash_index] = phone_list[i]
   return hash_table

Execution

phone_list = [4567774321, 4567775514, 9851742433, 4368884732]
str_phone_values = ‘convert_to_string(phone_list)
folded_value = folding_hash(str_phone_values)
folding_hash_table = hash (folded_value,phone_ list,11)
print(folding_hash_table)

Output

{0: 4567774321, 1: None, 2: 4368884732, 3: None,
4: None, 5: 4567775514, 6: None, 7: None, 8: None,
9: None, 10: 9851742433}

Bubble sort

Bubble sort is also known as sinking sort or comparison sort. In bubble sort, each element is compared with the adjacent element, and the elements are swapped if they are found in the wrong order. However, this is a time-consuming algorithm. It is simple but quite inefficient.

Python Interview Questions on Searching and Sorting chapter 14 img 9

Question 10.
How will you implement bubble sort in Python?
Answer:
The code for a bubble sort algorithm is very simple.
Step 1: Define the function for bubble sort. It would take the list that needs
to be sorted as input.

def bubble_sort(input_list):

Step 2:
1. Set a loop for i in range len(input_list)
a. Inside this for loop set another loop for j in range len(input_ list)-i-1).
b. For every i, in the nested loop value at index j, is compared with the value at index j+1. If the value at index j+1 is smaller than the value at index j then the values are swapped.
c. After the for loop is overprint the sorted list.

Code

def bubble_sort(input_list):
    for i in range(len(input_list)):
        for j in range(len(input_list)-i-1):
            if input_list[j]>input_list[j+1]:
               temp = input_list[j]
               input_list[j]=input_list[j+1]
               input_list[j+1]= temp
    print(input_list)

Execution

x = [7,1,3,6,2,4]
print("Executing Bubble sort for ",x)
bubble_sort(x)

y = [23,67,12,3,45,87,98,34]
print("Executing Bubble sort for ",y)
bubble_sort(y)

Output

Executing Bubble sort for [7, 1, 3, 6, 2, 4]
[1, 2, 3, 4, 6, 7] 
Executing 98, 34] Bubble sort for [23, 67, 12, 3, 45, 87,
[3, 12, 23 , 34, 45, 67, 87, 98]

Question 11.
Write code to implement selection sort.
Answer:
Step 1: Define the function for selection_sort. It would take the list that
needs to be sorted as input.

def selection_sort(input_list):

Step 2:
1. Set a loop for i in range len(input_list)
a. Inside this for loop set another loop for j in range (i+1, len(input_ list)-i-l))
b. For every i, in the nested loop value at index j is compared with the value at index i. If the value at index j is smaller than the value at index i then the values are swapped.
c. After the for loop is overprint the sorted list.

Code

def selection_sort(input_list):
    for i in range(len(input list)-1) :
        for j in range(i+1,len(input list)):
            if input_list[j] < input_list[i]:
               temp = input_list[j]
               input_list[j] = input_list[i]
               input list[i] = temp
  print(input list)

Execution

selection_sort([15,10,3,19,80,85])

Output

[3, 10, 15, 19, 80, 85]

Insertion Sort

In insertion sort, each element at position x is compared with elements located at position x-1 to position 0. If the element is found to be less than any of the values that it is compared to then the values are swapped. This process is repeated till the last element has been compared.

Python Interview Questions on Searching and Sorting chapter 14 img 10

Question 12.
Write code to implement insertion sort.
Answer:
It is very easy to implement insertion sort:
Consider a list [7,1,3,6,2,4]
Let indexi = i
indexj = indexi + 1

Python Interview Questions on Searching and Sorting chapter 14 img 11

Step 1: Define the insert_sort( ) function. It will take input ist as input.

def insertion_sort(input_list):

Step 2: for i in range(input_list)-1), set indexi =1, indexj = i+1

for i in range(len(input_list)-1):
indexi = i
indexj = i+1

Step 3: set while loop, condition inaexi>=0

  • if input_list[indexi]>input_list[indexj]
  • swap values of input list [indexi] and input_list[indexj]
  • set indexi = indexi -1
  • set indexj = indexj -1
  • else
  • set indexi = indexi -1
while indexi >= 0:
            if input list[indexi]>input
list[indexj]:
               print("swapping")
               temp = input list indexi]
               input list[indexi] = input
list[indexj]
               input list[indexj] = temp
               indexi = indexi - 1
               indexj = indexj - 1
         else:
               indexi = indexi - 1

Step 4: Print updated list

Code

def insertion_sort(input_list):
    for i in range(len(input_list)-1):
        indexi = i
        indexj = i+1
        print("indexi = ", indexi)
        print("indexj = ", indexj)
        while indexi >= 0:
              if input_list[indexi]>input_ list[indexj]:
                            print("swapping")
                            temp = input_list[indexi]
                            input_list[indexi] = input
list[indexj]
                            input_list[indexj] = temp
                            indexi = indexi - 1
                            indexj = indexj - 1
                      else :
                            indexi = indexi - 1
                 print("list update:",input_list)
        print ("final list = ", input_list)

Execution

insertion_sort([9,5,4,6,7,8,2])

Output

[7, 1, 3, 6, 2, 4 ]
indexi = 0
indexj = 1
swapping
list update: [1, 7, 3, 6, 2, 4 ]
indexi = 1
indexj = 2
swapping
list update: [1, 3, 7, 6, 2, 4 ]
indexi = 2
indexj = 3
swapping
list update: [1, 3, 6, 7, 2, 4 ]
indexi = 3
indexj = 4
swapping
swapping
swapping
list update: [ 1, 2, 3,6,7,4]
indexi = 4
indexj = 5
swapping
swapping
list update: [1, 2, 3, 4, 6, 7]
final list = [1, 2, 3, 4, 6, 7]
>>>

Shell Sort

  • Shell sort is a very efficient sorting algorithm.
  • Based on insertion sort.
  • Implements insertion sort on widely spread elements at first and then in each step space or interval is narrowed down.
  • Great for medium size data set.
  • Worst case time complexity: O(n)
  • Worst-case space complexity : 0(n)

I Consider a list: [10,30,11,4,36,31,15,1]
Size of the list, n = 8
Divide n/2 = 4, let this value be named k
Consider every kth(in this case 4th) element and sort them in the right order.

Python Interview Questions on Searching and Sorting chapter 14 img 12

II. do the following:
k = k/2 = 4/2 = 2
consider every kth element and sort the order.

Python Interview Questions on Searching and Sorting chapter 14 img 13

III. Do the following:
k = k/2 = 2/ 2 = 1
This is the last pass and will always be an insertion pass.

Python Interview Questions on Searching and Sorting chapter 14 img 14

Question 13.
Write code to implement the shell sort algorithm.
Answer:
The following steps will be involved:
Step1: Define the shell_sort( ) function to sort the list. It will take the list(input_list) that needs to be sorted as the input value.

def shell_sort(input_list):

Step2:
Calculate size, n = len(inputjist)
Number of steps for the while loop, k = n/2

def shell_sort(input_list):
n = len(input_list)
k = n//2

Step 3:

  • While k > 0:
  • for j in range 0, size of input list
  • for i in range (k, n)
  • if the value of element at i is less than the element located at index i-k, then swap the two values
  • set k = k//2
while k > 0:
     for j in range(n):
         for i in range(k,n):
             temp = input_list[i]
             if input_list[i] < input_list[i-k]:
                input_list[i] = input_list[i-k]
                input_list[i-k] = temp
    k = k//2

Step 4: Print the value of the sorted list.

Code

def shell_sort(input_list):
    n = len(input_list)
    k = n//2
    while k > 0:
         for j in range.(n) :
             for i in range(k,n):
                 temp = input_list[i]
                 if input_list[i] < input_list[i-k]:
                     input_list[i] = input_list[i-k]
                     input_list[i-k] = temp
        k = k//2
   print(input_list)

Execution

shell_sort ([10, 30, 11, 1,36, 31, 15, 4)]

Output

[1, 4, 10, 11, 15, 30, 31, 36]

Quick sort

  • In quicksort, we make use of a pivot to compare numbers.
  • All items smaller than the pivot are moved to its left side and all items larger than the pivot are moved to the right side.
  • This would provide a left partition that has all values less than the pivot and a right partition having all values greater than the pivot.
  • Let’s take a list of 9 numbers: [15, 39, 4, 20, 50, 6, 28, 2, 13].
  • The last element ‘ 13 ’ is taken as the pivot.
  • We take the first element ‘15’ as the left mark and the second last element ‘2’ as the right mark.
  • If left mark > pivot and Highmark <pivot then swap left a mark and right mark and increment left mark by 1 and decrement right make by 1.
  • If leftmark> pivot and rightmark> pivot then only decrement the right mark.
  • Same way if leftmark<pivot and rightmark< pivot then only increment the left mark.
  • If left mark <pivot and rightmark>pivot, increment leftmark by 1 and decrement right mark by 1.
  • When the left mark and right mark meet at one element, swap that element with the pivot.

I
The updated list is now [2, 6, 4, 13, 50, 39, 28, 15, 20]:

  • Take the elements to the left of 13, takin 4 as a pivot, and sort them in the same manner.
  • Once the left partition is sorted take the elements on the right and sort them taking 20 as a pivot.

Python Interview Questions on Searching and Sorting chapter 14 img 15

II.

Python Interview Questions on Searching and Sorting chapter 14 img 16

Question 14.
Write the code to implement the quicksort algorithm.
Answer:
Step: Decide upon the Pivot

  • This function takes three parameters, the list(input list), starting (fast) and ending (last) index for the list that has to be sorted.
  • Take the input_list. pivot = input_list[last]. We set the pivot to the last value of the list.
  • Set the left_pointer to first.
  • Set right_pointer to last -1, because the last element is the pivot.
  • Set pivot flag to True.
  • While pivot_flag is true:
  • If left mark > pivot and right mark <pivot then swap left mark and right mark and increment left mark by 1 and decrement right mark by 1.
  • If leftmark> pivot and rightmark> pivot then only decrement the rightmark.
  • Same way if leftmark<pivot and rightmark< pivot then only increment the leftmark.
  • If leftmark <pivot and rightmark>pivot, increment leftmark by 1 and decrement right mark by 1.
  • When left mark and rightmark meet at one element, swap that element with the pivot.
  • When, leftmark >= rightmark, swap the value of the pivot with the element at left pointer, set the pivot_flag to false.
def find_pivot (input_list, first, last):
    pivot = input_list[last]
    print("pivot =", pivot)
    left_pointer = first
    print("left pointer = ", left_pointer, " ",input_list[left_pointer])
    right_pointer = last-1
    print("right pointer = ", right_pointer, " ",input_list[right_pointer])
    pivot_flag = True

   while pivot_flag:
         if input_list[left_pointer]>pivot:
            if input_list[right_pointer]<pivot:
                temp = input_list[right_pointer]
                input_list[right_pointer]=input_ list[left_pointer]

                input_list[left_pointer]= temp
                right_pointer = right_pointer-1
                left_pointer = left_pointer+1

       else:
                right_pointer = right_pointer-1
  else:
        left_pointer = left_pointer+1
        right_pointer = right_pointer-1
  if left_pointer >= right_pointer:
        temp = input_list[last]
  input_list[last] = input_list[left_pointer]
  input_list[left_pointer] = temp
  pivot_flag = False
print(left_pointer)
return left_pointer

Step 2:
Define quicksort(input list) function.

  • This function will take a list as input.
  • Decides the starting point(O) and end point(length_of_the_list-1) for sorting.
  • Call the qsHelper( ) function.
def quicksort(input_list):
    first = 0
    last = len(input_list)-1
    qsHelper (input_list,first, last)

Step 3:
Define the qsHelper( ) function

This function checks the first index and last index value, it is a recursive function, it calls the find_pivot method where left mark is incremented by 1 and the right mark is decremented by 1. So, as long as the left mark(which is parameter first in this case) is less than the right mark(which is parameter last in this case) the while loop will be executed where qsHelper finds a new value of pivot, creates; eft and right partition and calls itself.

def qsHelper (input_list,first, last) :
    if first<last:
         partition = find_pivot (input_ list, first, last)
         qsHelper(input_list, first,partition-1)
         qsHelper(input_list,partition+l,last)

Code

def find_pivot (input_list, first, last):
    pivot = input_list[last]
    left_pointer = first
    right_pointer = last-1
    pivot_flag = True

    while pivot_flag:
          if input_list[left_pointer]>pivot:
             if input_list[right_pointer]<pivot:
                temp = input_list[right_pointer]
                input_list[right_pointer]=input_ list[left_pointer]
                input_list[left_pointer]= temp
                right_pointer = right_pointer-l left_pointer = left_pointer+l 
        else:
                right_pointer = right_pointer-l
        else:
               if input_list[right_pointer]<pivot:
                 left_pointer = left_pointer+l 
              else:
                 left_pointer = left_pointer+l 
                 right_pointer = right_pointer-1
            if left_pointer >= right_pointer: 
            temp = input_list[last]
            input_list[last] = input_list[left_pointer]

            input_list[left_pointer] = temp 
            pivot_flag = False 
            return left_pointer 
def quicksort(input_list): 
first = 0 
last = len(input_list)-1 
qsHelper (input_list, first, last)
def qsHelper (input_list,first, last) : 
if firstclast:
partition = find_pivot (input_list,first, last) 
qsHelper (input_list, first, partition-1) 
qsHelper(input_list,partition+1,last)

Execution

input_list=[15,39,4,20, 50, 6,28,2, 13]
quicksort(input_list)
print(input list)

Output

[2,4, 6, 13, 15, 20, 28, 39, 50]

Python Interview Questions on Searching and Sorting Read More »

Python Interview Questions on Trees

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Trees

There are several types of data structures that can be used to tackle application problems. We have seen how linked lists work in a sequential manner, we have also seen how stacks and queues can be used in programming applications but they are very restricted data structures. The biggest problem while dealing with linear data structure is that if we have to conduct a search, the time taken increases linearly with the size of the data. Whereas there are some cases where linear structures can be really helpful but the fact remains that they may not be a good choice for situations that require high speed.

So, now let’s move on from the concept of linear data structures to nonlinear data structures called trees. Every tree has a distinguished node called the root. Unlike the trees that we know in real life the tree data structure branches downwards from parent to child and every node except the root is connected by a direct edge from exactly one other node.

Python Interview Questions on Trees chapter 13 img 1

Look at the figure given above:
A is the root and it is parent to three nodes – B, C, and D.
Same way B is a parent to E and C is a parent to F and G.

Nodes like D, E, F, and G that have no children are called leaves or external nodes.
Nodes that have at least child such as B and C are called internal nodes.
The number of edges from the root to the node is called the depth or level of a
node. The depth of B is 1 whereas the depth of G is 2.
The height of a node is the number of edges from the node to the deepest leaf.
B, C, and D are siblings because they have the same parent A. Similarly, F and
G are also siblings because they have the same parent C.
Children of one node are independent of children of another node.
Every leaf node is unique.

  • The file system that we use on our computer machines is an example of the tree structure.
  • Additional information about the node is known as payload. Payload is not given much importance in algorithms but it plays a very important role in modem day computer applications.
  • An edge connects two nodes to show that there is a relationship between them.
  • There is only one incoming edge to every node (except the root). However, a node may have several outgoing edges.
  • The root of the tree is the only node of the tree that has no incoming edges as it marks the starting point for a tree.
  • Set of nodes having incoming edges from the same node are the children of that node.
  • A node is a parent of all the nodes that connect to it by the outgoing edges.
  • A set of nodes and edges that comprises a parent along with all its descendants are called subtrees.
  • A unique path traverses from the root to each node.
  • A tree that has a maximum of two children is called a binary tree.

Recursive definition of a tree

A tree can be empty, or it may have a root with zero or more subtree. The root of every subtree is connected to the root of a parent tree by an edge.

Simple Tree Representation

Have a look at the following tree. Here, we are considering the case of a binary tree.

Python Interview Questions on Trees chapter 13 img 2

In the case of a binary tree, a node cannot have more than two children. So, for ease of understanding, we can say that the above scenario is similar to something like this:

Python Interview Questions on Trees chapter 13 img 3

In this diagram, left and right are references to the instances of the node that are located on the left and right of this node respectively. As you can see, every node has three values:

  1. Data
  2. Reference to the child on left
  3. Reference to the child on the right

Python Interview Questions on Trees chapter 13 img 4

So, the constructor for the node class to create a Node object will be as follows:

class Node(object):
     def_init_(self, data_value):
         self.data_value = data_value
         self.left = None
         self.right = None

So, this is how a root node is created:

# Root_Node
print ("Create Root Node")
root = Node("Root_Node")
print("Value of Root = ",root.data_value," left =",root.left, " right = ", root.right)

When we execute this block of code, the output is as follows:
Create Root Node

Value of Root = Root_Node left = None right = None
Value of Node = Tree Left left = None right = None

Now, we write code for inserting values to the left or right. When a node is created, initially it’s left and right reference point to None. So, to add a child to left we just need to say:
self. left = child_node
and a child can be added to right in a similar way:
self.left = child_node
However, if the root node is already pointing to some existing child and we try to insert a child node then the existing child should be pushed down one level and the new object must take its place. So, the reference of the existing child stored in self.left is passed on to child.left and then self.help is assigned the reference to child. This can be achieved in the following manner:

def insert_left (self, child):
     if self.left is None :
        self.left = child
else:
     child.left = self.left
     self.left = child
def insert_right(self, child):
    if self.right is None:
       self.right = child
else :
    child.right = self.right
    self.right = child

Code

class Node(object):
     def_init_(self, data__value) :
        self . data_value = data_value
        self.left = None
        self.right = None

def insert_left(self, child):
     if self.left is None:
         self.left = child
else:
     child.left = self.left
     self.left = child
def insert_right(self, child):
    if self.right is None:
       self.right = child
else:
    child.right = self.right
    self.right = child

Execution

# Root_Node
print ("Create Root Node")
root = Node("Root_Node")
print("Value of Root = ",root.data_value," left = ",root.left, " right = ", root.right)
#Tree_Left
print("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
print ("Value of Node = ", tree__left. data_value, " left =",tree_left.left, " right = ",tree_left. right)
print("Value of Root = ", root,data_value," left = ",root.left, " right = ", root.right)
#Tree_Right
print("Create Tree_Right")
tree__right = Node ("Tree_Right")
root.insert_right(tree_right)
print("Value of Node = ",tree_right.data_value, " left =",tree_right.left, " right = ",tree_right. right)
print("Value of Root = " , root. data__value, " left = ",root.left, " right = ", root.right)
#TreeLL
print("Create TreeLL") tree11 = Node("TreeLL")
tree_left.insert_left(tree11)
print("Value of Node = ",tree11.data_value," left =",tree11.left, " right = ",tree11.right)
print("Value of Node = ",tree_left.data_value," left =",tree_left.left, " right = ",tree_left. right)
print("Value of Root = ", root.data_value," left =",root.left, " right = ", root.right)

Output

Create Root Node
Value of Root = Root_Node left = None right = None
Create Tree_Left
Value of Node = Tree_Left left = None right = None
Value of Root = Root_Node left = < main .Node
object at 0x000000479EC84F60> right = None Create Tree_Right
Value of Node = Tree_Right left = None right = None
Value of Root = Root_Node left = < main .Node
object at 0x000000479EC84F60> right = < main
Node object at 0x000000479ED05E80>
Create TreeLL
Value of Node = TreeLL left = None right =
None
Value of Node = Tree_Left left = < main .Node
object at 0x000000479ED0F160> right = None
Value of Root = Root_Node left = < main .Node
object at 0x000000479EC84F60> right = < main .
Node object at 0x000000479ED05E80>

Question 1.
What is the definition of a tree?
Answer.
A tree is a set of nodes that store elements. The nodes have a parent-child relationship such that:

  • If the tree is not empty, it has a special node called the root of the tree. The root has no parents.
  • Every node of the tree different from the root has a unique parent node.

Question 2.
Write a code to represent a tree through lists or a list of lists.
Answer:
In the list of lists, we shall store the value of the node as the first element. The second element will be the list that represents the left subtree and the third element represents the right subtree. The following figure shows a tree with just the root node.

Python Interview Questions on Trees chapter 13 img 5
Now, suppose we add a node to the left.
Python Interview Questions on Trees chapter 13 img 6
Now, adding another subtree to the right would be equal to:
Python Interview Questions on Trees chapter 13 img 7
Same way adding a node to the left of Tree Left would mean:

Implement Trees with Lists

Python Interview Questions on Trees chapter 13 img 8

Here you can see that the tree can be defined as follows:
binary_tree = [ ‘Root_Node’ , [ ‘Tree_Left’ ,[ ‘TreeLL’,[ ],[ ] ],[ ] ], [ ‘Tree_Right’,[ ],[ ] ] ]

Here, the root is Root_Node which is located at binary_tree[0].
Left subtree is at binary_tree[1].
The right subtree is at binary_tree[2].
Now let’s write the code for this.

Step 1:

Define Class

class Tree:

Step 2:

Create Constructor

Now let’s write the code for the constructor. Here, when we create an object we pass a value. The constructor creates a list where the value is placed at index 0 and at index 1 and 2 we have two empty lists. If we have to add subtree at the left side we will do so at index 1 and for the right subtree, we will insert values in the list at index 2.

def_init_(self, data):
self.tree = [data, [ ],[ ] ]

Step 3:

Define a function to insert left and right subtree

If you have to insert a value in the left subtree then pop the element at index 1 and insert the new list at that place. Similarly, if you have to insert a child on the right-hand side, pop the value at index 2 and insert the new list.

def left_subtree(self,branch):
        left_list = self . tree.pop(1)
        self.tree.insert(1,branch.tree)

def right_subtree(self,branch):
    right_list = self.tree.pop(2)
    self.tree.insert(2,branch.tree)

Now, let’s execute the code:

Code

class Tree:
     def_init_(self,data):
         self.tree = [data, [ ],[ ] ]

def left_subtree(self,branch):
    left_list = self.tree.pop(1)
    self.tree.insert(1,branch.tree)

def right_subtree(self,branch):
    right_list = self.tree.pop(2)
     self.tree.insert(2,branch.tree)

Execution

print("Create Root Node")
root = Tree("Root_node")
print("Value of Root = ", root.tree)
print("Create Left Tree")
tree_left = Tree("Tree_Left")
root.left_subtree(tree_left)
print("Value of Tree_Left = ", root.tree)
print("Create Right Tree")
tree_right = Tree("Tree_Right")
root.right_subtree(tree_right)
print("Value of Tree_Right = ", root.tree)
Create Root Node
Value of Root = ['Root_node', [ ], [ ] ]
Create Left Tree
Value of Tree_Left = ['Root_node', ['Tree_Left', [ ] ]/ [ ] ]
Create Right Tree
Value of Tree_Right = ['Root_node', [ 'Tree_Left', [ ], [ ] ], ['Tree_Right', [ ], [ ] ] ]
Create Terrell
Value of Tree_Left = ['Root_node', ['Tree_Left', [ 'TreeLL', [ ], [ ] ], [ ] ], ['Tree_Right', [ ], [ ] ] ]
>>>

There is however one thing ignored in this code. What if we want to insert a child somewhere in between? Here, in this case the child will be inserted at the given location and the subtree existing at that place will be pushed down.

For this we make changes in the insert functions.

def left_subtree(self,branch):
    left_list = self.tree.pop(1)
    if len(left_list) > 1:
        branch.tree[1]=left_list
        self.tree.insert (1,branch.tree)
  else:
        self.tree.insert(1,branch.tree)

If we have to insert a child in the left then first we pop the element at index 1. If the length of element at index 1 is 0 then, we simply insert the list. However, if the length is not zero then we push the element to the left of the new child. The same happens in case of right subtree.

def right_subtree(self,branch):
       right_list = self.tree.pop (2)
       if len(right_list) > 1:
          branch.tree[2]=right_list
          self.tree.insert(2,branch.tree)
    else:
         self.tree.insert(2,branch.tree)
print ("Create TreeLL")
tree11 = Tree("TreeLL")
tree_left.left_subtree(tree11)
print("Value of Tree_Left = ", root.tree)

Code

class Tree:
   def_init_(self,data) :
      self.tree = [data, [ ], [ ] ]

def left_subtree(self,branch):
    left_list = self.tree.pop(1)
    if len(left_list) > 1:
       branch.tree[1]=left_list
       self.tree.insert (1,branch.tree)
  else:
       self.tree.insert(1,branch.tree)

def right_subtree(self,branch):
    right_list = self.tree.pop(2)
    if len(right_list) > 1:
        branch.tree[2]=right_list
        self.tree.insert(2,branch.tree)
   else:
      self.tree.insert(2,branch.tree)

Execution

print ("Create Root Node")
root = Tree("Root_node")
print("Value of Root = ", root.tree)
print("Create Left Tree")
tree_left = Tree("Tree_Left")
root.left_subtree(tree_left)
print("Value of Tree_Left = ", root.tree)
print("Create Right Tree")
tree_right = Tree("Tree_Right")
root.right_subtree(tree_right)
print("Value of Tree_Right = ", root.tree)
print("Create Left Inbetween")
tree_inbtw = Tree("Tree left in between")
root.left_subtree(tree_inbtw)
print("Value of Tree_Left = ", root.tree)
print("Create TreeLL")
treell = Tree("TreeLL")
tree_left.left_subtree(tree11)
print("Value of TREE = ", root.tree)

Output

Create Root Node
Value of Root = ['Root node', [ ], [ ] ]
Create Left Tree
Value of Tree Left = [ 'Root node', [ 'Tree Left', [ ], [ ] ], [ ] ]
Create Right Tree
Value of Tree Right = [ 'Root node' , [ 'Tree Left', [ ] , [lie 1 'Tree Right', [], [ ] ] ]
Create Left Inbetween
Value of Tree Left = [ 'Root node' , [ 'Tree left in between' , [ 'Tree Left', [ ] , [ ] ] , [ ] ] ,
['Tree_Right', [ ], [ ] ] ]
Create TreeLL
Value of TREE = [ 'Root node', [ 'Tree left in between' , ['Tree Left' , [ 'TreeLL', [ ], [ ] ], [ ]], ['Tree_Right', [ ], [ ] ] ]
>>>

Question 3.
What is a binary tree? What are the properties of a binary tree?
Answer:
A data structure is said to be a binary tree if each of its nodes can have at most two children. The children of the binary tree are referred to as the left child and the right child.

Question 4.
What are tree traversal methods?
Answer:
Traversals
Preorder Traversal: First visit the root node, then visit all nodes on the left followed by all nodes on the right.

Code

class Node(object) :
     def_init_(self, data_value):
         self.data_value = data_value
         self.left = None
         self.right = None
def insert_left(self, child):
     if self.left is None:
        self.left = child
else:
      child.left = self.left
      self.left = child
def insert_right(self, child):
      if self.right is None:
         self.right = child
else:
     child.right = self.right
     self.right = child
def preorder(self, node):

res= [ ]
if node:
      res.append(node.data_value)
      res = res + self.preorder(node.left)
      res = res + self.preorder(node.right) 
   return res

Execution

# Root_Node
print("Create Root Node")
root = Node("Root_Node")
#Tree_Left
print ("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
#Tree_Right
print("Create Tree_Right")
tree_right = Node("Tree_Right")
root.insert_right(tree_right)
#TreeLL
print ("Create TreeLL")
treell = Node("TreeLL")
tree_left.insert_left(treell)
print("*****Preorder Traversal*****")
print(root.preorder(root))

Output

Create Root Node
Create Tree_Left
Create Tree_Right
Create TreeLL
*****Preorder Traversal*****
['Root_Node', 'Tree_Left', 'TreeLL', 'Tree_ Right']
>>>

In Order Traversal :First visit all nodes on the left then the root node and then all nodes on the right..

class Node(object):
     def_init_(self, data_value):
          self.data_value = data_value
          self.left = None
          self.right = None
   def insert_left(self, child):
       if self.left is None:
          self.left = child
   else:
      child.left = self.left
       self.left = child
def insert_right(self, child):
    if self.right is None:
       self.right = child
else:
     child.right = self.right
     self.right = child
def inorder(self, node):
  res=[ ]
  if node:
       res = self.inorder(node.left)
       res.append(node.data_value)
        res = res + self.inorder(node.right)
  return res
# Root_Node
print("Create Root Node")
root = Node("Root_Node")
#Tree_Left
print ("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
#Tree_Right
print("Create Tree_Right")
tree_right = Node("Tree_Right")
root.insert_right(tree_right)
#TreeLL
print("Create TreeLL")
treell = Node ("TreeLL")
tree_left.insert_left (treell)
print("*****Inorder Traversal*****)
print(root.inorder(root))

Output

Create Root Node
Create Tree_Left
Create Tree_Right
Create TreeLL
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
*****Inorder Traversal*****
["TreeLL' , 'Tree_Left' , 'Root_Node' , 'Tree_Right']
>>>

Post order Traversal: Visit all nodes on the left, then visit all nodes on the right , then visit the root node.

code

class Node(object):
     def_init_(self, data_value):
        self.data_value = data_value
        self.left = None
        self.right = None
    def insert_left (self, child):
        if self.left is None:
           self.left = child
else:
     child.right = self.right
     self.right = child
def postorder (self, node):
res = [ ]
if node:
    res = self.postorder (node.left)
    res = res + self.postorder (node.right)
    res.append (node.data_value)

   return res

Execution

#Root_Node
print("Create Root Node")
root = Node ("Root_Node")
#Tree_Left
print("Create Tree_Left")
tree_left = Node("Tree_Left")
root.insert_left(tree_left)
#Tree_Right
print("Create Tree_Right")
tree_right = Node("Tree_Right")

root . insert_right(tree_right)
#TreeLL
print ("Create TreeLL")
tree11 = Node ("TreeLL")
tree_left . insert_left(tree11)
print("*****postorder Traversal *****")
print (root.postorder (root))
OUTPUT
Create Root Node
Create Tree_Left
Create Tree_Right
Create TreeLL
*****Postorder Traversal*****
['TreeLL' , 'Tree_Left' , 'Tree_Right' , "Root_Node']

A binary heap is a binary tree. It is a complete tree, which means that all levels are completely filled except possibly the last level. It also means that the tree is balanced
As every new item is inserted next to the available space. A Binary heap can be stored in an array.

A binary heap can be of two types: Min Heap or Max Heap. In case of Min Heap binary heap, the root node is the minimum of all the nodes in the binary heap,all parent nodes are smaller than their children. On the other hand in case of Max Heap the root is the maximum among all the keys present in the heap and and all nodes are bigger than their children.

 

Python Interview Questions on Trees chapter 13 img 9

Heap has two important properties:
1. It is complete and is constructed from left to right across each row and the last row may not be completely full. Each row should be filled
up sequentially. So, the order of inserting values should be from left to right, row by row sequentially as shown in the following figure:

 

Python Interview Questions on Trees chapter 13 img 10

2. The parent must be larger (Max Heap)/smaller(Min Heap) than the children.

 

Python Interview Questions on Trees chapter 13 img 11

Look at the figure shown above, it is a case of Maximum heap because all parents are greater than their children.
The binary heap can be represented in an array as follows:
0 1 2 3 4 5

 

Python Interview Questions on Trees chapter 13 img 12

If you look at the array carefully you will realize that if a parent exists at location n then the left child is at 2n+l and the right child is at 2n + 2. ”
n= 0

 

Python Interview Questions on Trees chapter 13 img 13

So, if we know the location of the parent child we can easily find out the location of the left and right child.
Now suppose we have to build up a Max Heap using following values: 20,4, 90, 1, 125

Step 1:
Insert 20

 

Python Interview Questions on Trees chapter 13 img 14

Step 2:
Insert 4 -> Left to Right-> First element in second row

 

Python Interview Questions on Trees chapter 13 img 15

Since the parent is greater than the child, this is fine.

Step 3:
Insert 90 -> Left to Right -> Second element in second row
However when we insert 90 as the right child, it violates the rule of the max heap because the parent has a key value of 20. So, in order to resolve this problem it is better to swap places as shown in the following figure:

 

Python Interview Questions on Trees chapter 13 img 16

After swapping, the heap would look something like this:

 

Python Interview Questions on Trees chapter 13 img 17

Step 4:
Insert 1 -> left to right -> first element third row

 

Python Interview Questions on Trees chapter 13 img 18

Since 1 is smaller than the parent node, this is fine.
Step 5:
Insert 125

 

Python Interview Questions on Trees chapter 13 img 19

This violated the rule of Max Heap Swap 4 and 125

 

Python Interview Questions on Trees chapter 13 img 20

Not a heap still Swap 125 and 90

 

Python Interview Questions on Trees chapter 13 img 21

We now have a Max Heap.

Question 5.
Write python code to implement Max Heap. How would you insert a value so that the root node has the maximum value and all parents are greater than their children.
Answer:
Here we will write The code to implement Maxheap class. The class will have two functions:
Push( ) : To insert value.
FIoat_up( ): To place the value where it belongs.

Step 1

Define the class

class MaxHeap:

Step 2

Define The Constructor

def init (self):
self.heap = [ ]

Step 3

Define the push( ) function

The push function does two jobs:

  1. Appends the value at the end of the list. (We have seen earlier that the value has to be inserted first at the available location)
  2. After appending the value, the push() function will call the float_ up(index) function. The pushQ function passes the index of the last element to the float_up() function so that the float_up() function can analyse the values and do the needful as described in the next step.
def push(self,value):
                 self.heap.append(value)
                 self .floatj_up (len (self . heap) -1)

Step 4
Define the float_up function
1. The float_up( )function takes index value as parameter.

def float_up (self, index) :

2. The push( ) function passes the index value of the last element in the heap. The first thing that the float function does is that it checks if the element is at index 0 or not. If yes, then it is the root node. Root node has no parents and since it’s the last element of the heap it has no children either. So, we can return the value.

if index==0:
return

3. If the index is greater than 0 then we can proceed further. Look the following figure once again:

 

Python Interview Questions on Trees chapter 13 img 22

For programming, you need to understand few things:

The index 0 has two children at position 1 and 2. If I have an element at 1 then I can find the parent by calculating value of (1//2). Similarly for element at index 2, the parent’s index value can be found out by calculating value of (2//2 -1). So, we can say that if an element has an index value index and it is odd then it’s parent’s index value, parent_ ofindex = index//2. However, if index is even parentofindex will be (index//2)-1. This becomes the outer frame for the float_up function. The right child has an even number as index and the left child has an odd number as index.

if index==0:
         return
   else:
      if index%2==0:
         parent_of_index = (index//2)-l
         ----------write code----------
  else:
         parent_of_index = index//2
         ----------write code--------

4. Now, we compare the values of the child and the parent. If the child is greater than the parent, swap the elements.

def float_up (self, index) :
        if index==0:
              return
      else:
        if index%2==0:
           parent_of_index = (index//2)-1
           if self.heap[index]> self, heap[parent_of_index]:
          self.swap(index, parent_of_index)
     else:
          parent_of_index = index//2
          if self.heap[index]> self, heap[parent_of_index]:
         self.swap(index, parent_of_index)
         self.float_up (parent_of_index)

Step 5

Define the swap function

The swap( ) function helps in swapping the values of the parent and the child, the code for this is given as follows:

def swap(self,indexl, index2):
      temp = self.heap[index1]
      self.heap[index1] = self.heap[index2]
      self.heap[index2] = temp

Code

class MaxHeap:
      def_init_(self):
          self.heap = [ ]
     def push(self,value):
          self.heap.append(value)
          self .float_up (len (self .heap) -1)
    def float_up (self, index) :
         if index==0:
 return
    else:
            if index%2==0:
             parent_of_index = (index//2)-1
             if self.heap[index]> self, heap[parent_of_index]:
          self.swap(index, parent_of_ index)
  else:
            parent_of_index = index//2
            if self.heap[index]> self, heap[parent_of_index]:
            self.swap(index, parent_of_index)
           self .float_up (parent_of_index)
def peek(self):
      print(self.heap[0])
def pop(self):
        if len(self.heap)>=2:
           temp = self.heap[0]
             self.heap[0]=self.heap[len(self.heap)-1]
              self.heap[len(self.heap)-1]
             self.heap.pop( )
             self.down_adj( )
      elif len(self.heap)==1:
            self.heap.pop( )
  else:
            print("Nothing to pop")
 def swap(self,indexl, index2):
            temp = self.heap[index1]
            self.heap[indexl] = self.heap[index2]
            self.heap[index2] = temp

Execution

H = MaxHeap( )
print("*****pushing values***********")
print("pushing 165")
H.push(165)
print(H.heap)
print("pushing 60")
H.push (60)
print(H.heap)
print("pushing 179")
H.push(179)
print(H.heap)
print("pushing 400")
H.push(400)
print(H.heap)
print("pushing 6")
H.push(6)
print(H.heap)
print("pushing 275")
H.push(275)
print(H.heap)

Output

*****pushing values***********
pushing 165
[165]
pushing 60
[165, 60]
pushing 179
[179, 60, 165]
pushing 400
[400, 179, 165, 60]
pushing 6
[400, 179, 165, 60, 6]
pushing 275
[400, 179, 275, 60, 6, 165]
>>>

Question 6.
Write code to find out the maximum value in the Max heap.
Answer:
It is easy to find the max value in the max heap as the maximum value is available at the root node which is index 0 of the heap.

def peek(self):
print(self.heap[0])

Question 7.
Write the code to pop the maximum value from Max Heap.
Answer:
There are two steps involved:

  1. Swap the root with the last element in the array and pop the value.
  2. The root node now does have the maximum value. So, now we need to move downwards, comparing the parent with their left and right child to ensure that the children are smaller than the parent. If not we will have to swap places again.

Step 1

Define pop( ) function.

The pop( ) function which swaps the values of the root node with the last element in the list and pops the value. The function then calls the down_ adj( ) function which moves downwards and adjusts the values. The pop() function first checks the size of the heap. If the length of the heap is 1 then that means that it only contains one element that’s the root and there is no need to swap further.

def pop(self):
          if len(self.heap)>2:
              temp = self.heap[0]
              self.heap[0]=self.heap[len(self.heap)—1]
              self.heap[len(self.heap)-1]
              self.heap.pop ( )
              print("heap after popping largest value =", self.heap)
             self.down_adj( )
        elif len(self.heap)==1:
            self.heap.pop( )
     else:
          print("Nothing to pop")

Step 2:

Define downadj( ) function

Set Index Value To 0.
Index of left child = left_child = index*2+1 Index of right child = right child = index*2+2
Then we go through loop where we check the value of the parent with both left and right child. If the parent is smaller than the left child then we swap the value. We then compare the parent value with the right child, if it is less then we swap again.
This can be done as follows:

  • Check if parent is less than left child:
  • If yes, check if left child is less than the right child
  • if yes, then swap the parent with the right child
  • Change the value of index to value of right_child for further assessment
  • If no the just swap the parent with the left child
  • Set the value of index to value of left_child for further assessment
  • If the parent is not less than left child but only less than the right child then swap values with the right child
  • Change the value of index to right_child
def down_adj(self):
index = 0
for i in range(len(self.heap)//2):
left_child = index*2+1 .
if left_child > len (self.heap) :
return
print("left child = ", left_child)
right_child = index*2+2
if right_child > len (self.heap) :
return
print("right child = ", right_child)
if self.heap[index]<self.heap[left_child]:
temp = self.heap[index]
self.heap[index] = self.heap[left_child]
self.heap[left_child] = temp
index = left_child
if self.heap[index]<self.heap[right_child]:
temp = self.heap[index]
self.heap[index] = self.heap[right_child]
self.heap[right_child] = temp
index = right_child

Code

class MaxHeap:
      def_init_(self):
         self.heap = [ ]
    def push(self,value):
         self.heap.append(value)
         self .float_up (len (self, heap) -1)
def float_up (self, index) :
     if index==0:
           return
    else:
         if index%2==0:
               parent_of_index = (index//2)-1
               if self.heap[index]> self, heap[parent_of_index]:
                            temp = self.heap[parent_of_index]
                           self.heap[parent_of_index] =self.heap[index]
                              self.heap[index] = temp
         else:
               parent_of_index = index//2
               if self.heap[index]> self, heap[parent_of_index]:
                           temp = self.heap[parent_of_index]
                           self.heap[parent_of_index] = self.heap[index]
                           self.heap[index] = temp self.float_up (parent_of_index)
     def peek(self):
              print(self.heap [0])
     def pop(self):
           if len(self.heap)>=2:
                    temp = self.heap[0]
                    self.heap[0]=self.heap[len(self.heap)-1]
                    self.heap[len(self.heap)-1]
                    self.heap.pop( )
                    self.down_adj( )
                elif len(self.heap)==1:
                    self.heap.pop ( )
        else:
                 print ("Nothing to pop")
def swap(self,indexl, index2):
                temp = self.heap[index1]
                self.heap[indexl] = self.heap[index2]
                self.heap[index2] = temp

def down_adj(self):
       index = 0
       for i in range(len(self.heap)//2):
            left_child = index*2+1
            if left_child > len(self.heap)-1:
                 print(self.heap)
                 print("End Point")
                 print("Heap value after pop( ) =",self.heap)
     return
            right_child = index*2+2
            if right_child > len(self.heap)-1:
                   print ("right child does not exist")
                     if self.heap[index]<self.heap[left_child]:
                 self.swap(index,left_child)
                     index = left_child
                print("Heap value after pop( ) =", self.heap)
   return
                 if self.heap[index]<self.heap[left_child]:
                if self.heap[left_child]<self. heap[right_child]:
               self.swap(index,right_child) index = right_child 
      else:
                 self.swap(index,left_child) index = left_child
                  elif self.heap[index]<self.heap[right_child]:
           self.swap(index,right_child) index = right_child
   else:
           print("No change required" )
          print("Heap value after pop() = ", self.heap)

 

Execution

H = MaxHeap( )
print("*****pushing values***********")
H.push (165)
print(H.heap)
H.push(60)
print(H.heap)
H.push(179)
print(H.heap)
H.push(400)
print(H.heap)
H.push(6)
print(H.heap)
H.push(275)
print(H.heap)
print("*********popping values*******")
H.pop ( )
H.pop( )
H.pop ( )
H.pop ( )
H.pop ( )
H.pop ( )
H.pop ( )

Output

pushing values
[165]
[165, 60]
[179, 60, 165]
[400, 179, 165, 60]
[400, 179, 165, 60, 6]
[400, 179, 275, 60, 6, 165]
*********popping values*******
[275, 179, 165, 60, 6]
End Point
Heap value after pop( ) = [275, 179, 165, 60, 6]
right child does not'exist
Heap value after pop() = [179, 60, 165, 6]
Heap value after pop() = [165, 60, 6]
right child does not exist
Heap value after pop() = [60, 6]
Heap value after pop () = [6]
Nothing to pop
>>>

Question 8.
Time complexity for max heap:
Answer:

  • Insert: 0(log n)
  • Get Max: 0(1) because the maximum value is always the root at ‘ index( )
  • Remove Max: 0(log n)

The implementation of Min Heap is similar to Max Heap just that in this case the root has the lowest value and the value of parent is less than the left and right child.

Code

class MinHeap:
def_init_(self):
     self.heap = [ ]
def push(self,value):
      self.heap.append(value)
      self .float_up (len (self .heap) -1)
def float_up (self, index) :
   if index==0:
        return
else:
   if index%2==0:
        parent_of_index = (index//2)-1
        if self.heap[index]< self, heap[parent_of_index]:
        self.swap(index, parent_of_index)
else:
       parent_of_index = index//2
      if self.heap[index]< self, heap[parent_of_index]:
     self.swap(index, parent_of_index)
     self .floatyup (parent_of_index)
def peek(self) :
      print(self.heap [0])
def pop (self) :
     if len(self.heap)>=2:
     temp = self.heap[0]
     self.heap[0]=seIf.heap[len(self.heap)-1]
     self.heap[len(self.heap)-1]
     self.heap.pop ( )
     self.down_adj( )
  elif len(self.heap)==1:
     self.heap.pop()
else:
     print("Nothing to pop")
def swap(self,indexl, index2):
     temp = self.heap[index1]
     self.heap[indexl] = self.heap[index2]
     self.heap[index2] = temp

Execution

H = MinHeap( )
print("*****pushing values***********")
print("pushing 165")
H.push (165)
print(H.heap)
print("pushing 60")
H.push(60)
print(H.heap)
print("pushing 179")
H.push(179)
print(H.heap)
print("pushing 400")
H.push(400)
print(H.heap)
print("pushing 6")
H.push (6)
print(H.heap)
print("pushing 275")
H.push(275) '
print(H.heap)

Output

*****pushing values***********
pushing 165 [165]
pushing 60
[60, 165]
pushing 179
[60, 165, 179]
pushing 400
[60, 165, 179, 400]
pushing 6
[6, 60, 179, 400, 165]
pushing 275
[6, 60, 179, 400, 165, 275]
>>>

Question 9.
What are the applications of binary heap?
Answer:

  • Dijkstra Algorithm
  • Prims Algorithm
  • Priority Queue
  • Can be used to solve problems such as:
  • K’th Largest Element in an array
  • Sort an almost sorted array
  • Merge K Sorted Array

Question 10.
What is a priority queue and how can it be implemented?
Answer:
Priority queue is like a queue but it is more advanced. It has methods same as a queue. However, the main difference is that it keeps the value of higher priority at front and the value of lowest priority at the back. Items are added from the rear and removed from the front. In priority queue elements are added in order. So, basically there is a priority associated with every element. Element of highest priority is removed first. Elements of equal priority are treated ass per their order in queue.

Binary heap is the most preferred way of implementing priority queue as they can retrieve the element of highest priority in 0(1) time. Insert and delete can take O(logn) time. Besides that since, the binary heap use lists or arrays, it is easy to locate elements and the processes involved are definitely quite cache friendly. Binary heaps do not demand extra space for pointers and are much easier to insert.

Python Interview Questions on Trees Read More »

Python Interview Questions on Recursion

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Recursion

When a function makes a call to itself it is called recursion. The same sets of instructions are repeated again and again for new values and it is important to decide when the recursive call must end. For Example: Let’s look at the code to find the factorial of a number.
If we use a loop then a factorial function would look something like this:

Code

def factorial(number):
     j = 1
     if number==0|number==1:
        print(j)
     else:
           for i in range (1, number+1):
              print(j," * ",i," = ",j*i)
           j = j*i
    print(j)

Execution

factorial(5)

Output

1 * 1 = 1
1 * 2 = 2
2 * 3 = 6 
6 * 4 = 24
24 * 5 = 120
120 
>>>

Now, let’s have a look at how we can solve the same problem using a recursive algorithm.

Code

def factorial(number):
    j = 1
    if number==0 | number==1:
        return j
    else:
     return number*factorial(number-1)

Execution

print(factorial(4))

Output
24

Pros and Cons

Recursive functions make the code look neat, it helps in breaking a complex task into simpler sub-problems. It can be easier than implementing iterations. However, it can be a little difficult to understand the logic behind recursion. Recursion can consume more memory and time and can be hard to debug.

Question 1.
Write code to find the sum of natural numbers from 0 to the given number using recursion.
Answer:

IResult
00
11+0=i(1)+i(0)=1
22+1=i+i(1)=3
33+3=i+i(2)=6
44+6=i+i(3)=10
55+10=i+i(4)=15

Observe for i = 0, the result is 0, thereafter result = i(n)+i(n-l)

Code

def natural sum(num):
     if num == 0
          return 0
     else:
         return (num + natural sum(num-1) )

Execution

print (natural_sum(10))

Output

55

Question 2.
What would be the output for the following code?

def funny (x,y):
       if y == 1:
          return x [0]
      else:
           a = funny (x, y-1)
           if a>x [y-1]
            return a
     else:
         return x[y-1]
x = [1,5,3,6,7]
y = 3
print (funny (x,y) )

Answer:
If we insert a print statement in the code and execute the code again we can see the actual sequence in which it executes:

def funny(x,y):
   print("calling funny , y = ",y)
   if y == 1:
      return x[0]
else:

   print("inside else loop because y = ", y)
   a = funny(x, y-1)
   print("a = ", a)
   if a > x[y-1]:
       print("a = ",a, " Therefore a > ",x[y-1])
       return a
   else:
       print("a = ",a, " Therefore a < ",x[y-1])
return x[y-1]
x = [1,5,3,6,7]
y = 3
print(funny(x,y))

Output

calling funny , y = 3
inside else loop because y = 3
calling funny , y = 2
inside else loop because y = 2
calling funny , y = 1
a = 1
a = 1 Therefore a < 5
a = 5
a = 5 Therefore a > 3
5
The answer is 5

Question 3.
What would be the output of the following code?

def funny(x):
      if (x%2 == 1) :
         return x+1
     else:
        return funny(x-1)
print(funny(7))
print(funny(6))

Answer:
For x =7
1. x = 7
2. x % 2 is 1
return 7 + 1
For x = 6
1. x =6
2. x%2 = 0
3. Return funny(5)
4. x = 5 .
5. x%2 =1
6. Return x+1 = 6

Question 4.
Write Fibonacci sequence using recursion. Answer:
The Fibonacci sequence = 0, 1, 2, 3, 5, 8, 13 ……….

IResult
00
11
21+0=i(0)+i(1)=1
31+1=i(2)+i(1)=2
42+1=i(3)+i(2)=3
53+2=i(4)+i(3)=5

Observe for i = 0, the result is 0 and for i = 1, the result is 1. Thereafter, the value of i(n) = i(n-1) + i(n-2). We implement the same, when we try to find Fibonacci code using recursion.

  • The fibonacci_seq(num), takes a number as argument.
  • If num = 0, result is 0
  • If num = 1, result is 1
  • Else result is fibonacci_seq(num-l) + Fibonacci_seq(num-2)
  • If you want to find Fibonacci Sequence for 10 then:
  • For elements 0 to 10 o Call the fibonacci_seq( ) function
  • fibonacci_seq(0) = 0
  • fibonacciseq(l) = 1
  • fibonacci_seq(2) = fibonacci_seq(l)+ fibonacci_seq(0)
  • fibonacci_seq(3) = fibonacci_seq(2)+ fibonacci_seq(3)

Code

def fibonacci_seq (num) :
     if num <0:
          print("Please provide a positive integer value")
    if num == 0:
           return 0
    elif num == 1:
          return 1
   else:
        return (fibonacci_seq (num-1) +fibonacci_ seq(num-2))

Execution

for i in range(10):
     print (fibonacci_seq(i))

Output

0
1
1
2
3
5
8
13
21
34

Question 5.
What is memoization?
Answer:
Basically, in memoization, we maintain a look-up table where solutions are stored so that we don’t have to solve the same sub-problem again and again. Instead, we solve it once and store the values so that they can be reused.

We know that Fibonacci sequence is:
F(n) = F(n-1)+F(n-2) if n>1 = n if n =0,1
So,
F(n):
if n<1:
return n
else :
return F(n-1)+F(n-2)
Here, we are making two recursive calls and adding them up and the value is returned.
Look at the following diagram:

Python Interview Questions on Recursion chapter 12 img 1

Just to find Fibonacci(5), Fibonacci(2) is computed three times and Fibonacci (3) is computed two times. So, as n increases Fibonacci function’s performance will go down. The consumption of time and space would increase exponentially with an increase in n. In order to save time what we can do is save a value when it is computed for the first time. So, we can save F(2) when it is computed for the first time, the same way with F(3), F(4)… so on. So, we can say that:

F(n):
if n=<1:
return n
elif f(n) exist:
return F(n-1)
else:
F(n) = F(n-1) + F(n-2)
save F(n).
Return F(n).

In the code below:

  1. The function Fibonacci( ) takes a number and creates a list, fib_num of size num+1. This is because the Fibonacci series starts from 0.
  2. It calls the function fib_calculate( )which takes the number num and lists fib_num as a parameter.
  3. We have saved-I at all index in the list:

a. If fib_num[num] is>0, that means Fibonacci for this number already exists and we need not compute it again and the number can be returned.
b. If num <= 1 then return num.
c. Else if num >=2, calculate fib_calculate(num – 1, fib num) + fib_calculate(num – 2, fib_num). The value calculated must be stored in list fib_num at index num so that there is no need to calculate it again.

Code

def fibonacci (num) :

   fib_num = [-1] * (num + 1)
   return fib_calculate (num, fib_num)
def fib_calculate (num, fib_num) :
   if fib_num [num] >= 0:
        return fib_num[num]

if (num <= 1):
    fnum = num
else:
     fnum = fib_calculate (num - 1, fib_num) + fib_ calculate (num - 2, fib_num)
fib_num [num] = fnum

return fnum

Execution

num = int(input('Enter the number: '))
print ("Answer = ", fibonacci (num) )

Output

Enter the number: 15 
Answer = 610
>>>

Question 6.
What would be the output of the following program?

def test_function(i, j) :
      if i == 0:
          return j;
      else:
           return test_function(i-1, j+1)
    print (test_function(6,7) )

Answer:

IJI==0?Return
67NoTest_function(5,8)
58NoTest_function(4,9)
49NoTest_function(3,10)
310NoTest_function(2,11)
211NoTest_function(1,12)
112NoTest_function(0,13)
013Yes13

The output will be 13.

Question 7.
What will be the output for the following code:

def even(k):
    if k <= 0:
        print("please enter a positive value")
    elif k == 1:
           return 0
   else:
       return even(k-1) + 2
print(even(6))

Answer:

KK<=0K ==1Result
6noNoEven(5)+2
5NoNoEven(4)+2+2
4NoNoEven(3)+2+2+2
3NoNoEven(2)+2+2+2+2
2NoNoEven(1)+2+2+2+2+2
1Noyes0)+2+2+2+2+2

Question 8.
Write a code to find the n_power(n), of 3 using recursion. Answer:
1. Define function n_power(n), it takes the value of power and parameter(n).
2. If n = 0 then return 1 because any number raised to power 0 is 1.
3. Else return (n_power(n-1)).

NN<0N ==0Result
4NoNon_power(3)*3
3NoNon_power(2)*3*3
2NoNon_power(1)*3*3*3
1NoNon_power(0)*3*3*3*3
0NoYes1*3*3*3*3

Code

def n_power(n):
    if n < 0:
       print ("please enter a positive value")
   elif n == 0:
        return 1
   else:
       return n_power(n-1)*3

Execution

print(n_power(4))

Output

81

Python Interview Questions on Recursion Read More »

Program to Calculate the Length of a String Without Using a Library Function

Python Program to Calculate the Length of a String Without Using a Library Function

Strings in Python:

A string is one of the most frequent data types in any computer language. A string is a collection of characters that can be used to represent usernames, blog posts, tweets, or any other text content in your code. You can make a string and assign it to a variable by doing something like this.

sample_string='BTechGeeks'

Strings are considered immutable in Python, once created, they cannot be modified. You may, however, construct new strings from existing strings using a variety of approaches. This form of programming effort is known as string manipulation.

Examples:

Example1:

Input:

given string = hello this is btechgeeks online

Output:

The length of given string { hello this is btechgeeks online } = 31

Example2:

Input:

given string = for file operations upload files using 23199 -@33hello

Output:

The length of given string { for file operations upload files using 23199 -@33hello } = 54

Program to Calculate the Length of a String Without Using a Library Function in Python

Below is the full approach to calculate the length of the given string without using built-in library len() in Python.

1)Using Count variable(Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable to say stringLength that stores the length of the given string.
  • Initialize the stringLength to 0.
  • To traverse the characters in the string, use a For loop.
  • Increment the stringLength (Count Variable) by 1.
  • Print the stringLength.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
given_string = 'HelloThisisBTechGeeks'
# Take a variable to say stringLength that stores the length of the given string.
# Initialize the stringLength to 0.
stringLength = 0
# To traverse the characters in the string, use a For loop.
for charact in given_string:
    # Increment the stringLength (Count Variable) by 1.
    stringLength = stringLength+1
# Print the stringLength.
print('The length of given string {', given_string, '} =', stringLength)

Output:

The length of given string { HelloThisisBTechGeeks } = 21

Explanation:

  • A string must be entered by the user as static input and saved in a variable.
  • The count variable is set to zero.
  • The for loop is used to go over the characters in a string.
  • When a character is encountered, the count is increased.
  • The total number of characters in the string, which is the string’s length, is printed.

2)Using Count variable(User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say stringLength that stores the length of the given string.
  • Initialize the stringLength to 0.
  • To traverse the characters in the string, use a For loop.
  • Increment the stringLength (Count Variable) by 1.
  • Print the stringLength.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using input() function and store it in a variable.
given_string = input('Enter some random string = ')
# Take a variable to say stringLength that stores the length of the given string.
# Initialize the stringLength to 0.
stringLength = 0
# To traverse the characters in the string, use a For loop.
for charact in given_string:
    # Increment the stringLength (Count Variable) by 1.
    stringLength = stringLength+1
# Print the stringLength.
print('The length of given string {', given_string, '} =', stringLength)

Output:

Enter some random string = btechgeeksonlineplatformforgeeks and coding platform
The length of given string { btechgeeksonlineplatformforgeeksa nd coding platform } = 52

The total number of characters in the string, which is the string’s length, is printed.
Related Programs:

Python Program to Calculate the Length of a String Without Using a Library Function Read More »

Create an empty NumPy Array of given length or shape and data type in Python

In this article, we will be exploring different ways to create an empty 1D,2D, and 3D NumPy array of different data types like int, string, etc.

We have a Python module in NumPy that provides a function to create an empty() array.

numpy.empty(shape, dtype=float, order='C')
  • The arguments are shape and data type.
  • It returns the new array of the shape and data type we have given without initialising entries which means the array which is returned contain garbage values.
  • If the data type argument is not provided then the array will take float as a default argument.

Now, we will use this empty() function to create an empty array of different data types and shape.

You can also delete column using numpy delete column tutorial.

Create an empty 1D Numpy array of a given length

To create a 1D NumPy array of a given length, we have to insert an integer in the shape argument.

For example, we will insert 5 in the shape argument to the empty() function.

Create an empty 1D Numpy array of given length

Code:

import numpy as np
# Create an empty 1D Numpy array of length 5
empty_array = np.empty(5)
print(empty_array)

Create an empty Numpy array of given shape using numpy.empty()

In the above code, we saw how to create a 1D empty array. Now in this example, we will see how to create a 2D and 3D NumPy array numpy.empty() method.

Create an empty 2D Numpy array using numpy.empty()

To create the 2D NumPy array, we will pass the shape of the 2D array that is rows and columns as a tuple to the numpy.empty() function.

For instance, here we will create a 2D NumPy array with 5 rows and 3 columns.

Create an empty 2D Numpy array using numpy.empty()

Code:

empty_array = np.empty((5, 3))
print(empty_array)

It returned an empty numpy array of 3 rows and 5 columns. Since we did not provide any data type so the function has taken a default value as a float.

Create an empty 3D Numpy array using numpy.empty()

As we have seen with the 2D array, we will be doing the same thing to create an empty 3D NumPy array. We will create a 3D NumPy array with 2 matrix of 3 rows and 3 columns.

Create an empty 3D Numpy array using numpy.empty()

Code:

empty_array = np.empty((2, 3, 3))
print(empty_array)

The above code creates a 3D NumPy array with 2 matrix of 3 rows and 3 columns without initialising values.

In all the above examples, we have not provided any data type argument. Therefore, by default, all the values which were returned were in the float data type.

Now in the next section, we customize the data type. Let’s see how to do that.

Create an empty Numpy array with custom data type

To create an empty NumPy array with different data types, all we have to do is initialise the data type in type argument in the numpy.empty() function.

Let’s see different data types examples.

Create an empty Numpy array of 5 Integers

To create a NumPy array of integer 5, we have to initialise int in the type argument in the numpy.empty() function.

Create an empty Numpy array of 5 Integers

Code:

# Create an empty Numpy array of 5 integers
empty_array = np.empty(5, dtype=int)
print(empty_array)

Create an empty Numpy array of 5 Complex Numbers

Now, to create the empty NumPy array of 5 complex numbers, all we have to do is write the data type complex in the dtype argument in numpy.empty() function.

Create an empty Numpy array of 5 Complex Numbers

Code:

empty_array = np.empty(5, dtype=complex)
print(empty_array)

Create an empty Numpy array of 5 strings

In this, we will write the dtype argument as a string in the numpy.empty() function.

Create an empty Numpy array of 5 strings

Code:

empty_array = np.empty(5, dtype='S3')
print(empty_array)

The complete code:

import numpy as np
def main():
print('*** Create an empty Numpy array of given length ***')
# Create an empty 1D Numpy array of length 5
empty_array = np.empty(5)
print(empty_array)
print('*** Create an empty Numpy array of given shape ***')
# Create an empty 2D Numpy array or matrix with 5 rows and 3 columns
empty_array = np.empty((5, 3))
print(empty_array)
# Create an empty 3D Numpy array
empty_array = np.empty((2, 3, 3))
print(empty_array)
print('*** Create an empty Numpy array with custom data type ***')
# Create an empty Numpy array of 5 integers
empty_array = np.empty(5, dtype=int)
print(empty_array)
# Create an empty Numpy array of 5 Complex Numbers
empty_array = np.empty(5, dtype=complex)
print(empty_array)
# Create an empty Numpy array of 5 strings of length 3, You also get an array with binary strings
empty_array = np.empty(5, dtype='S3')
print(empty_array)
if __name__ == '__main__':
main()

I hope this article was useful for you and you enjoyed reading it!

Happy learning guys!

Create an empty NumPy Array of given length or shape and data type in Python Read More »

Delete elements from a Numpy Array by value or conditions in Python

Deleting elements from a NumPy Array by value or conditions in Python.

In this article we will discuss about how to delete elements from a NumPy Array by based on matching values or multiple conditions.

Remove all occurrences of an element with given value from numpy array :

Suppose we have a NumPy array and we want to delete all the occurrences of that particular element from that Numpy array.

#Program :

import numpy as np
# numpy array created from a list
arr = np.array([40,50,60,70,80,90,40,10,20,40])
print('Numpy Array before deleting all occurrences of 40 :')
print(arr)

# Removing all occurrences of elements with value 40 from numpy array
arr = arr[arr != 40]
print('Modified Numpy Array after deleting all occurrences of 40 :')
print(arr)
Output :
Numpy Array before deleting all occurrences of 40 :
[40 50 60 70 80 90 40 10 20 40]
Modified Numpy Array after deleting all occurrences of 40 :
[50 60 70 80 90 10 20]

The condition arr != 40 returns a bool array of same size as arr with value True at places where value is not equal to 40 and returns False at other places. Like this

[ False True True True True True False True True False]

When we will pass it to [] of numpy array arr then it will select the elemnts whose value is True. Means it will return the elements from arr which are not  equal to 40.

You can also delete column using numpy delete column tutorial.

Delete elements in Numpy Array based on multiple conditions :

Like above example, it will create a bool array using multiple conditions on numpy array and when it will be passed to [] operator of numpy array to select the elements then it will return a copy of the numpy array satisfying the condition suppose (arr > 40) & (arr < 80) means elements greater than 40 and less than 80 will be returned.

#Program : 

import numpy as np 
# numpy array created from a list 
arr = np.array([40,50,60,70,80,90,40,10,20,40]) 
print('Numpy Array before deleting any element :') 
print(arr) 

# Remove all occurrences of elements below 40 & greater than 80 
# Means keeping elements greater than 40 and less than 80
arr = arr[ (arr > 40) & (arr < 80) ]
print('Modified Numpy Array after deleting elements :') 
print(arr)
Output :
Numpy Array before deleting any element :
[40 50 60 70 80 90 40 10 20 40]
Modified Numpy Array after deleting elements :
[50 60 70]

Delete elements by value or condition using np.argwhere() & np.delete() :

By using np.argwhere() & np.delete()  we can also delete any elements.

#Program : 

import numpy as np 
# numpy array created from a list 
arr = np.array([40,50,60,70,80,90,40,10,20,40]) 
print('Numpy Array before deleting any element :') 
print(arr) 

# deleting all occurrences of element with value 40
arr = np.delete(arr, np.argwhere(arr == 40))
print('Modified Numpy Array after deleting all occurrences of 40') 
print(arr)
Output : 
Numpy Array before deleting all occurrences of 40 : 
[40 50 60 70 80 90 40 10 20 40] 
Modified Numpy Array after deleting all occurrences of 40 : 
[50 60 70 80 90 10 20]

In the above example np.delete() function will delete the element and np.argwhere() function will detect the index.
Means the condition arr == 40 will return a bool array like

[True False False False False False True False False True]

Where the condition arr == 40 matches it returns True and if condition fails it returns False. And when the bool array will be passed inside the function np.argwhere() then it will return the index positions where the values are True.

i.e

[ [0]
  [6]
  [9]]

These are the indices which represents the value 40.

When this index positions will be passed inside np.delete() function then the element present at those index positions will be deleted.

Delete elements by multiple conditions using np.argwhere() & np.delete() :

The concept is same like above only the difference is the elements will be deleted based on multiple conditions.

So, let’s see the implementation of it.

#Program : 

import numpy as np 
# numpy array created from a list 
arr = np.array([40,50,60,70,80,90,40,10,20,40]) 
print('Numpy Array before deleting any element :') 
print(arr) 

#It will delete all the elements which are greater than 40 and less than 80
arr = np.delete(arr, np.argwhere( (arr >= 40) & (arr <= 80) ))
print('Modified Numpy Array after deleting :') 
print(arr)
Output : 
Numpy Array before deleting any element : 
[40 50 60 70 80 90 40 10 20 40] 
Modified Numpy Array after deleting elements : 
[90 10 20]

Delete elements from a Numpy Array by value or conditions in Python Read More »

Python Interview Questions on Operators in Python

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Operators in Python

What are operators?
Operators are required to perform various operations on data. They are special symbols that are required to carry out arithmetic and logical operations. The values on which the operator operates are called operands.
So, if we say 10/5=2
Here 7’ is the operator that performs division and 10 and 5 are the operands. Python has the following operators defined for various operations:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical/Boolean Operators
  4. Assignment Operators
  5. Bitwise Operators
  6. Membership Operators
  7. Identity Operators

Question 1.
What are Arithmetic Operators? What are various types of arithmetic operators that we can use in Python?
Answer:
Arithmetic operators are used to performing mathematical functions such as addition, subtraction, division, and multiplication. Various types of Arithmetic operators that we can use in Python are as follows:

‘+’for Addition

>>> a = 9
>>> b = 10
>>> a + b
19
>>>

‘-’ for Subtraction

>>> a = 9
>>>b = 10
>>> a - b
-1
>>>

‘*’ for Multiplication

>>> a = 9
>>> b = 10
>>> a * b
90
>>>

‘/’ for division

>>> a = 9
>>> b = 10
>>> a/b
0.9
>>>

“%’ for Modulus – provides the value of the remainder

>>> a = 9
>>> b = 10
>>> a % b
9
>>> a = 11
>>> b = 2
>>> a % b
1
>>>

‘//’ for Floor division – a division of operands, provides integer value of quotient. The value after decimal points is removed.

>>> a = 9
>>> b = 10
>>> a // b
0
>>> a = 11
>>> b = 2
>>> a // b
5
>>>

‘**’ for finding Exponential value

>>> a = 2
>>> b = 3
>>> a**b
8
>>>b**a
9
>>>

Question 2.
What is the Arithmetic operator’s precedence in Python?
Answer:
When more than one arithmetic operator appears in an expression the operations will execute in a specific order. In Python, the operation precedence follows as per the acronym PEMDAS.
Parenthesis
Exponent
Multiplication
Division
Addition
Subtraction
(2+2)/2-2*2/(2/2)*2
= 4/2 -4/1*2
= 2-8
= -6
>>> (2+2)/2-2*2/(2/2)*2
-6.0

Question 3.
a = 2, b =4, c = 5, d = 4 Evaluate the following keeping Python’s precedence of operators:

  1. a+b+c+d
  2. a+b*c+d 4
  3. a/b+c/d
  4. a+b*c+a/b+d

Answer:

>>> a=2
>>> b=4
>>> c=5
>>> d=4
>>> a+b+c+d
15
>>> a+b*c+d
26
>>> a/b+c/d
1.75
>>> a+b*c+a/b+d
26.5
>>>

Question 4.
What are relational operators?
Answer:
Relational operators are also known as conditional or comparison operators. Relational operators in Python are defined as follows:

  1. ==: returns true if two operands are equal
  2. !=: returns true if two operands are not equal
  3. >: returns true if the left operand is greater than the right operand
  4. <: returns true if the left operand is smaller than the right operand
  5. >=: returns true if the left operand is greater than or equal to the right operand
  6. <=: returns true if the left operand is smaller or equal to the right operand
>>> a = 5
>>> b = 6
>>> c = 7
>>> d = 7
>>> a == b
False
>>> c == d
True
>>> a ! = b
True
>>> c ! = d
False
>>>
>>> a > b
False
>>> a < b
True
>>> a>=b
False
>>> c>=d
True
>>> a<=b
True
>>> c<=d
True

Question 5.
a = 5, b = 6, c =7, d=7 What will be the outcome for the following:

  1. a<=b>=c
  2. -a+b==c>d
  3. b+c==6+d>=13

Answer:

>>> a<=b>=c
False
>>> -a+b==c>d
False
>>> b+c==6+d>=13
True
>>>

Question 6.
What are assignment operators?
Answer:
Assignment operators are used for assigning values to variables. Various types of assignment operators are as follows:

  1. =: a = 5 means that a is assigned value of 5
  2. += a += 5 is same as a = a+5
  3. -=: a -= 5 is same as a = a – 5
  4. *=. a *= 5 js same as a = a * 5
  5. /=: a /= 5 is same as a = a/5
  6. %=: a %=5 is same as a = a%5
  7. //=: x //= 5 is same as x= x//5
  8. **=• x **=5 js same as x = x**5
  9. &=: x &= 5 is same as x = x&5
  10. |=: x |= 5 is same as x = x|5
  11. A=: x A= 5 is same as x = xA5
  12. >>=: x >>= 5 is same as x = x>>5
  13. <<=: x <<= 5 is same as x = x<<5

Question 7.
Is a = a*2+6 same as a *= 2 + 6?
Answer:
No, a = a*2+6 is not same as a *= 2 + 6 this is because assign operator have lower precedence than the addition operator. So, if a = 5 then,
a = a *2+6 => a = 16
a *= 2 + 6 => a = 40

>>> a = 5
>>> a = a *2+6
>>> a
16
>>> a = 5
>>> a*= 2+6
>>> a
40
>>>

Question 8.
What are logical operators?
Answer:
Logical operators are generally used in control statements like if and while. They are used to control program flow. The logical operator evaluates a condition and returns “True” or “False” depending on whether the condition evaluates to True or False. Three logical operators in Python are as follows:

  • ‘and’
  • ‘or’ and
  • ‘not’
>>> a = True
>>> b = False
>>> a and b
False
>>> a or b
True
>>> not a
False
>>> not b
True
>>>

Question  9.
What are membership operators?
Answer:
The membership operators are used to check if a value exists in a sequence or not.
Two types of membership operators are as follows:

  1. in: returns true if a value is found in a sequence
  2. not in: returns true if a value is not found in a sequence
>>> a = "Hello World"
>>> "h" in a
False
>>> "h" not in a
True
>>> "H" not in a
False
>>>

Question 10.
What are bitwise operators?
Answer:
Bitwise operators work on bits and perform bit-by-bit operations. In Python, the following bit-wise operations are defined:
1. AND – &
2 & 3
2
2. OR-|
2|3
3
3. One’s complement – ~
>>> ~2
-3
4. XOR -∧
2∧3
1
5. Right shift ->>
2>>2
0
6. Left shift -<<
2<<2
8

Question 11.
What are identity operators?
Answer:
Identity operators are used to verifying whether two values are on the same part of the memory or not. There are two types of identity operators:

  1. is: return true if two operands are identical
  2. is not: returns true if two operands are not identical
>>> a = 3
>>> id(a)
140721094570896
>>> b = 3
>>> id (b)
140721094570896
>>> a is b
True
>>> a = 3
>>> b = 6
>>> c = b - a
>>> id(c)
140721094570896
>>> a is c
True
>>> a = 4
>>> b = 8
>>> a is b
False
>>> a is not b
True
>>>

Question 12.
What is the difference between a = 10 and a= = 10?
Answer:
The expression a = 10 assigns the value 10 to variable a, whereas a == 10 checks if the value of a is equal to 10 or not. If yes then it returns ‘Ti^te’ else it will return ‘False’.

Question 13.
What is an expression?
Answer:
A logical line of code that we write while programing, is called expressions. An expression can be broken into operator and operands. It is therefore said that an expression is a combination of one or more operands and zero or more operators that are together used to compute a value.
For example:
a = 6
a + b = 9
8/7

Question 14.
What are the basic rules of operator precedence in Python?
Answer:
The basic rule of operator precedence in Python is as follows:

  1. Expressions must be evaluated from left to right.
  2. Expressions of parenthesis are performed first.
  3. In Python the operation precedence follows as per the acronym PEMDAS:
  • Parenthesis
  • Exponent
  • Multiplication
  • Division
  • Addition
  • Subtraction

4. Mathematical operators are of higher precedence and the Boolean operators are of lower precedence. Hence, mathematical operations are performed before Boolean operations.

Question 15.
Arrange the following operators from high to low precedence:

  1. Assignment
  2. Exponent
  3. Addition and Subtraction
  4. Relational operators
  5. Equality operators
  6. Logical operators
  7. Multiplication, division, floor division, and modulus

Answer:
The precedence of operators from high to low is as follows:

  1. Exponent
  2. Multiplication, division, floor division, and modulus
  3. Addition and subtraction operators
  4. Relational operators
  5. Equality operators
  6. Assignment operators
  7. Logical Operators

Question 16.
Is it possible to change the order of evaluation in an expression?
Answer:
Yes, it is possible to change the order of evaluation of an expression. Suppose you want to perform addition before multiplication in an expression, then you can simply put the addition expression in parenthesis.
(2+4)*4

Question 17.
What is the difference between implicit expression and explicit expression?
Answer:
Conversion is the process of converting one data type into another. Two types of conversion in Python are as follows:

  1. Implicit type conversion
  2. Explicit type conversion

When Python automatically converts one data type to another it is called implicit conversion.

>>> a = 7
>>> type(a)
Cclass 'int'>
>>> b = 8.7
>>> type(b)
<class 'float'>
>>> type(a+b)
<class 'float' >
>>>

Explicit conversion is when the developer has to explicitly convert datatype of an object to carry out an operation.

>>> c = "12"
>>> type(c)
<class 'str'>
>>> d = 12
# addition of string and integer will generate error
>>> c+d
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module> c+d
TypeError: can only concatenate str (not "int") to str
# convert string to integer and then add
>>> int (c) +d 24
# convert integer to string and then perform concatenation
>>> c+str(d)
'1212'
>>>

Question 18.
What is a statement?
Answer:
A complete unit of code that a Python interpreter can execute is called a statement.

Question 19.
What is an input statement?
Answer:
The input statement is used to get user input from the keyboard. The syntax for input() function is as follows:
input(prompt)
The prompt is a strong message for the user.

>>> a = input ("Please enter your message here :")
Please enter your message here: It is a beautiful
day
>>> a
' It is a beautiful day'
>>>

Whenever an input function is called, the program comes on hold till an input is provided by the user. The input( ) function converts the user input to a string and then returns it to the calling program.

Question 20.
Look at the following code:

num1 = input ("Enter the first number: ")
num2 = input("Enter the second number: ")
print(num1 + num2)

When the code is executed the user provides the following values:
Enter the first number: 67 Enter the second number: 78 What would be the output?
Answer:
The output will be 6778. This is because the input() function converts the user input into a string and then returns it to the calling program. So, even though the users have entered integer values, the input() function has returned string values ‘67’ and ‘78’ and the ‘+’ operator concatenates the two strings giving ‘6778’ as the answer. To add the two numbers they must be first converted to an integer value. Hence, the code requires slight modification:

num1 = input ("Enter the first number: ")
num2 = input("Enter the second number: ")
print(int(num1) + int(num2))

Output:

Enter the first number: 67
Enter the second number: 78
145
>>>

Question 21.
What is the Associativity of Python Operators? What are non-associative operators?
Answer:
Associativity defines the order in which an expression will be evaluated if it has more than one operator having the same precedence. In such a case generally left to right associativity is followed.
Operators like assignment or comparison operators have no associativity and are known as Nonassociative operators.

Python Interview Questions on Operators in Python Read More »

Python Interview Questions on Data Types and Their in-built Functions

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Data Types and Their in-built Functions

Data types in Python

Numbers: int, float, and complex
List: Ordered sequence of items
tuple: Ordered sequence of items similar to list but is immutable
Strings: Sequence of characters
Set: an unordered collection of unique items
Dictionary: an unordered collection of key-value pair

Question 1.
Differentiate between mutable and immutable objects?
Answer:

Mutable ObjectsImmutable Objects
Can change their state or contentsCannot change their state or contents
Type: list, diet, setInbuilt types: int, float, bool, string, Unicode, tuple
Easy to changeQuick to access but making changes require the creation of a copy
Customized container like types are mostly mutablePrimitive like data types are immutable
  • Mutable objects are recommended when one has the requirement to change the size or content of the object
  • The exception to immutability: tup1es are immutable but may contain elements that are mutable

Question 2.
What is Variable in Python?
Answer:
Variables in Python are reserved memory locations that store values. Whenever a variable is created, some space is reserved in the memory. Based on the data type of a variable, the interpreter will allocate memory and decide what should be stored in the memory.

>>> a = 9 #assign value to a
>>> type(a) #check type of variable a
<class 'int'>
>>>

Question 3.
How can we assign the same value to multiple variables in one single go?
Answer:
The same value can be assigned to multiple variables in one single go as shown in the following code:

>>> a = b = c = "Hello World ! ! ! "
>>> a
' Hello World ! ! ! '
>>> b
' Hello World ! ! ! '
>>> c
' Hello World ! ! ! '
>>>

Numbers
Types of numbers supported are as follows:

  1. Signed integers int: these can be +ve or -ve and do not have any decimal point
  2. Long integers long: these are integers of unlimited size followed by capital or lowercase ‘L’
  3. Float: are real numbers with decimal points
  4. Complex numbers: have real and imaginary parts

Question 4.
What are the methods available for the conversion of numbers from one type to another?
Answer:
The following functions are available to convert numbers from one form to another.

# convert to integer
a = 87.8
print("a = ", a)
print ("****************")
#After conversion to integer
print("After conversion to integer value of a will be a = ", int(a))
print("*****************")
# convert to float
a = 87
print("a = ", a)
print("*****************")
#After conversion to float
print ("After conversion to float value of a will
be a = ", float (a) )
print("*****************")
# convert to complex
a = 87
print("a = ",a)
#After conversion to complex
print("After conversion to complex value of a will be = ", complex(a))
print("*****************")

Output

a = 87.8
*****************
After conversion to integer, the value of a will be a = 87
*****************
a = 87
*****************
After conversion to float value of a will be a = 87.0
a = 87
After conversion to complex value of a will be =
(87 + 0j)
*****************
>>>

Question 5.
What are the mathematical functions defined in Python to work with numbers?
Answer:
Mathematical functions are defined in the

import math
#ceiling value
a = -52.3
print ("math ceil for ",a, " is : " ceil(a))
print ("********************")
#exponential value
a = 2
print("exponential value for ", a , exp(2))
print ("********************")
#absolute value of x
a = -98.4
print ("absolute value of ",a," is: ", abs(a) )
print("********************")
#floor values
a = -98.4
print ("floor value for ",a," is: " print )
# log(x)
a = 10
print ("log value for ",a," is : ", math . floor (a))
print ("********************")
# log10(x)
a = 56
print ("log to the base 10 for ",a," is : ", math . log10(a))
print ("********************")
# to the power of
a = 2
b = 3
print (a," to the power of ",b," is : " , pow(2,3))
print ("********************")
# square root
a = 2
print("sqaure root")
print ("Square root of ",a," is : " , math . sqrt(25))
print("********************")

math module. You will have to import this module in order to work with these functions.

Output

math ceil for -52.3 is: -52
********************
exponential value for 2 is: 7.38905609893065
********************
the absolute value of -98.4 is: 98.4
********************
floor value for -98.4 is: -99
********************
log value for 10 is: 2.302585092994046
********************
log to the base 10 for 56 is :
1.7481880270062005
********************
2 to the power of 3 is: 8.0
********************
square root
The square root of 2 is: 5.0
********************

Question 6.
What are the functions available to work with random numbers?
Answer:
To work with random numbers you will have to import a random module. The following functions can be used:

import random
#Random choice
print (" Working with Random Choice")
seq=[8,3,5,2,1,90,45,23,12,54]
print ("select randomly from ", seq," : ", random, choice(seq))
print("*******************")
#randomly select f?om a range
print ("randomly generate a number between 1 and 10 : ", random.randrange(1, 10))
print("*******************")
#random( )
print ("randomly display a float value between 0 and 1 : ",random.random())
print("* * * * * *")
#shuffle elements of a list or a tup1e
seq= [1,32,14,65,6,75]
print ("shuffle ",seq,"to produce ", random,
shuffle (seq) )
#uniform function to generate a random float number between two numbers
print ("randomly display a float value between 65 and 71 : ", random.uniform(65,71))

Output

Working with Random Choice
select randomly from [8, 3, 5, 2, 1, 90, 45, 23, 12, 54] : 2
*******************
randomly generate a number between 1 and 10: 8
*******************
randomly display a float value between 0 and 1: 0.3339711273144338
* * * * * *
shuffle [1, 32, 14, 75, 65, 6] to produce: None
randomly display a float value between 65 and 71 :
65.9247420528493

Question 7.
What are the trigonometric functions defined in the math module?
Answer:
Some of the trigonometric functions defined in the

import math
# calculate arc tangent in radians
print ("atan(0) : ",math.atan(0))
print ("**************")
# cosine of x
print ("cos (90) : ", math.cos(0))
print("**************")
# calculate hypotenuse
print ("hypot(3,6) : ",math.hypot(3,6))
print ("**************")
# calculates sine of x
print ("sin(O) : ", math.sin(0))
print ("**************")
# calculates tangent of x
print ("tan(0) : ", math.tan(0))
print("**************")
# converts radians to degree
print ("degrees(0.45) : ", math.degrees(0.45))
print("**************")
# converts degrees to radians
print ("radians(0) : ", math.radians(0))

math module is as follows:

Question 8.
What are number data types in Python?
Answer:
Number data types are the one which is used to store numeric values such as:

  1. integer
  2. long
  3. float
  4. complex

Whenever you assign a number to a variable it becomes a numeric data type.

>>> a = 1
>>> b = -1
>>> c = 1 . 1
>>> type (a)
<class 'int'>
>>> type (b)
<class 'int'>
>>> type (c)
<class 'float'>

Question 9.
How will you convert float value 12.6 to integer value?
Answer:
Float value can be converted to an integer value by calling int() function.

>>> a = 12.6
>>> type(a)
<class 'float' >
>>> int(a)
12
>>>

Question 10.
How can we delete a reference to a variable?
Answer:
You can delete a reference to an object using the del keyword.

>>> a=5
>>> a 5
>>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a
NameError: name 'a' is not defined
>>>

Question 11.
How will you convert real numbers to complex numbers?
Answer:
Real numbers can be converted to complex numbers as shown in the following code:

>>> a = 7
>>> b = -8
>>> x = complex(a,b)

>>> x.real
7.0
>>> x.imag
-8.0
>>>

Keywords, Identifiers, and Variables

Keywords

  • Keywords are also known as reserved words.
  • These words cannot be used as a name for any variable, class, or function.
  • Keywords are all in lower case letters.
  • Keywords form vocabulary in Python.
  • The total number of keywords in Python is 33.
  • Type help() in Python shell, a help> prompt will appear. Type keywords. This would display all the keywords for you. The list of keywords is highlighted for you.

Welcome to Python 3.7’s help utility?

If this is your first time using Python, you should definitely check: cut the tutorial on the Internet at https://docs.python.orgy 3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type “quit”.

To get a list of available modules, keywords, symbols, or topics, type “modules”, “keywords”, “symbols”, or “topics”. Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such 33 “spam”, type “modules spam”.

help> keywords

Here is a list of the python keywords, Enter any keyword to get more help.

Python Interview Questions on Data Types and Their in-built Functions chapter 2 img 1

help

Identifiers

  • Python Identifier is a name given to a variable, function, or class.
  • As the name suggests identifiers provide an identity to a variable, function, or class.
  • An identifier name can start with upper or lower case letters or an underscore followed by letters and digits.
  • An identifier name cannot start with a digit.
  • An identifier name can only contain letters, digits, and an underscore.
  • special characters such as @,%,! , #,$,’.’ cannot be a part of the identifier name.
  • As per naming convention, generally, the class name starts with a capital letter, and the rest of the identifiers in a program should start with lower case letters.
  • If an identifier starts with a single underscore then it is private and two leading underscores in front of an identifier’s name indicate that it is strongly private.
  • Avoid using an underscore as a leading or trailing character in an identifier because this notation is being followed for Python built-in types.
  • If an identifier also has two trailing underscores then it is a language-defined special name.
  • Though it is said that a Python identifier can be of unlimited length but having a name of more than 79 characters is a violation of the PEP-8 standard which asks to limit all lines to a maximum of 79 characters.
    You can check if an identifier is valid or not by calling iskeywords( ) function as shown in the following code:
>>> import keyword
>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("only")
False

Variables

  • Variables are nothing but a label to a memory location that holds a value.
  • As the name suggests, the value of a variable can change.
  • You need not declare a variable in Python but they must be initialized before use E.g, counter =0.
  • When we pass an instruction counter=0, it creates an object and a value 0 is assigned to it. If the counter variable already exists then it will be assigned a new value 0 and if it does not exist then it will get created.
  • By assigning a value we establish an association between a variable and an object.
  • counter=0 means that the variable counter refers to a value of ‘0’ in memory. If a new value is assigned to the counter then that means the

variable now refers to a new memory chunk and the old value was garbage collected.

>>> counter = 0
>>> id(counter)
140720960549680
>>> counter =10
>>> id(counter)
140720960550000
>>>

Question 12.
What are tokens?
Answer:
Tokens are the smallest units of the program in Python. There are four types of tokens in Python:

  • Keywords
  • Identifiers
  • Literals
  • Operators

Question 13.
What are constants?
Answer:
Constants (literals) are values that do not change while executing a program.

Question 14.
What would be the output for 2*4**2? Explain.
Answer:
The precedence of** is higher than the precedence of*. Thus, 4**2 will be computed first. The output value is 32 because 4**2 = 16 and 2*16 = 32.

Question 15.
What would be the output for the following expression:

print('{0:.4}'.format(7.0 / 3))

Answer:
2.333

Question 16.
What would be the output for the following expression?

print('(0:.4%}'.format(1 / 3))

Answer:
33.3333%

Question 17.
What would be the value of the following expressions?

  1. ~5
  2. ~~5
  3. ~~~5

Answer:
~x = -(x+1). Therefore the output for the given expressions would be as follows:

  1. -6
  2. 5
  3. -6

We will now have a look at the three most important sequence types in Python. All three represent a collection of values that are placed in order. These three types are as follows:

  1. String: immutable sequence of text characters. There is no special class for a single character in Python. A character can be considered as a String of text having a length of 1.
  2. List: Lists are very widely used in Python programming and a list represents a sequence of arbitrary objects. The list is mutable.
  3. tuple: tup1e is more or less like a list but it is immutable.

Strings

  • The sequence of characters.
  • Once defined cannot be changed or updated hence strings are immutable.
  • Methods such as replace( ), join( ), etc. can be used to modify a string variable. However, when we use these methods, the original string is not modified instead Python creates a copy of the string which is modified and returned.

Question 18.
How can String literals be defined?
Answer:
Strings can be created with single/double/triple quotes.

>>> a = "Hello World"
>>> b = 'Hi'
>>> type(a)
<class 'str'>
>>> type(b)
<class 'str' >
>>>
>>> c = """Once upon a time in a land far far away there lived a king"""
>>> type(c)
<class 'str'>
>>>

Question 19.
How can we perform concatenation of Strings?
Answer:
Concatenation of Strings can be performed using the following techniques:

1. + operator

>>> string1 = "Welcome"
>>> string2 = " to the world of Python!!!"
>>> string3 = string1 + string2
>>> string3
'Welcome to the world of Python!!!'
>>>

2. Join ( ) function

The join( ) function is used to return a string that has string elements joined by a separator. The syntax for using join( ) function, string_name.j oin(sequence)

>>> string1 = "-"
>>> sequence = ( "1","2","3","4")
>>> print(string1.joint(sequence))
1-2-3-4
>>>

3. % operator

>>> string1 = "HI"
>>> string2 = "THERE"
>>> string3 = "%s %s" %(string1, string2)
>>> string3 ,
'HI THERE'
>>>

4. format( ) function

>>> string1 = "HI"
>>> string2 ="THERE"
>>> string3 = "{ } { }" . format (string1, string2)
>>> string3
'HI THERE'
>>>

5. f-string

>>> string1 ="HI"
>>> string2 = "THREE"
>>> string3 = f ' { string1} {string2} '
>>> string3
'HI THERE'
>>>

Question 20.
How can you repeat strings in Python?
Answer:
Strings can be repeated either using the multiplication sign or by using for loop.

  • operator for repeating strings
>>> string1 = "Happy Birthday!!!"
>>> string1*3
'Happy Birthday!!!Happy Birthday!!!Happy Birthday!!!' *
>>>
  • for loop for string repetition
for x in range (0,3)

>>> for x in range(0,3):
print("HAPPY BIRTHDAY! ! !")

Question 21.
What would be the output for the following lines of code?

>>> string1 = "HAPPY "
>>> string2 = "BIRTHDAY!!!"
>>> (string1 + string2)*3

Answer:

'HAPPY BIRTHDAY!!!HAPPY BIRTHDAY!!!HAPPY BIRTHDAY!!!'

Question 22.
What is the simplest way of unpacking single characters from string “HAPPY”?
Answer:
This can be done as shown in the following code:

>>> string1 = "HAPPY"
>>> a,b,c,d,e = string1
>>> a
'H'
>>> b
'A'
>>> c
'P'
>>> d
'P'
>>> e
'Y'
>>>

Question 23.
Look at the following piece of code:

>>> string1 = "HAPPY"
>>> a,b = string1

What would be the outcome for this?
Answer:
This code will generate an error stating too many values to unpack because the number of variables does not match the number of characters in the strings.

Question 24.
How can you access the fourth character of the string “HAPPY”?
Answer:
You can access any character of a string by using Python’s array-like indexing syntax. The first item has an index of 0. Therefore, the index of the fourth item will be 3.

>>> string1 = "HAPPY"
>>> string1[3]
'P'

Question 25.
If you want to start counting the characters of the string from the rightmost end, what index value will you use (assuming that you don’t know the length of the string)?
Answer:
If the length of the string is not known we can still access the rightmost character of the string using the index of -1.

>>> string1 = "Hello World!!!"
>>> string1[-1]
' ! '
>>>

Question 26.
By mistake, the programmer has created string string1 having the value “HAPPU”. He wants to change the value of the last character. How can that be done?
Answer:
Strings are immutable which means that once they are created they cannot be modified. If you try to modify the string it will generate an error.

>>> string1 = "HAPPU"
>>> string1 [-1] = "Y"
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
string1[-1] = "Y”
TypeError: fstr* object does not support item assignment

However, there is a way out for this problem. We can use the replace( ) function.

>>> string1 = "HAPPU"
>>> string1.replace('U'Y')
'HAPPY'

Here, in the case of replace ( ) function, a new string is created and the value is reassigned to string1. So, string1 is not modified but is actually replaced.

Question 27.
Which character of the string will exist at index -2?
Answer:
Index of -2 will provide second last character of the string:

>>> string1 = "HAPPY"
>>> string1 [-1]
' Y'
>>> string1[-2]
'P'
>>>

Question 28.
>>> str1 = “\t\tHi\n”
>>> print(str1 .strip ( ))
What will be the output?
Answer:
Hi

Question 29.
Explain slicing in strings.
Answer:
Python allows you to extract a chunk of characters from a string if you know the position and size. All we need to do is to specify the start and endpoint. The following example shows how this can be done. In this case, we try to retrieve a chunk of the string starting at index 4 and ending at index 7. The character at index 7 is not included.

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1 [4:7]
'Y-B'
>>>

If in the above example you omit the first index, then the default value of 0 is considered and the slicing of text chunks starts from the beginning of the string.

>>> String1 = "HAPPY-BIRTHDAY! ! ! "
>>> string1 [:7]
'HAPPY-B'
>>>

Same way if you don’t mention the second index then the chunk will be taken from the starting position till the end of the string.

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1 [4:]
'Y-BIRTHDAY!!!'

Value of string1 [:n]+string1[n:] will always be the same string.

>>> string1 [:4]+ string1 [4:]
'HAPPY-BIRTHDAY!!!'

The negative index can also be used with slicing but in that case, the counting would begin from the end.

>>>string1 = "HAPPY-BIRTHDAY ! ! !"
>>> string1[-5:-1]
'AY!!' ! ”
>>>

You can also provide three index values:

>>> string1 [1:7:2]
'AP- '
>>> string1 [1: 9 : 3]
'AYI'
>>>

Here, the first index is the starting point, the second index is the ending point and the character is not included and the third index is the stride or how many characters you would skip before retrieving the next character.

Question 30.
What would be the output for the following code?

>>> string1 = "HAPPY-BIRTHDAY!!!"
>>> string1[-1:-9:-2]
Answer:
‘!!AH’

Question 31.
How does the split( ) function work with strings?
Answer:
We can retrieve a chunk of string based on the delimiters that we provide. The split( ) operation returns the substrings without the delimiters.

Example

>>> string1 = "Happy Birthday"
>>> string1.split ( )
['Happy', 'Birthday' ]

Example

>>> time_string = "17:06:56"
>>> hr_str,min_str,sec_str = time_string. split (":")
>>> hr_str
'17'
>>> min_str
'06'
>>> sec_str
'56'
>>>

You can also specify, how many times you want to split the string.

>>> date_string = "MM-DD-YYYY"
>>> date_string.split("-" , 1)
['MM', 'DD-YYYY']
>>>

In case you want Python to look for delimiters from the end and then split the string then you can use the rsplit( ) method.

>>> date_string = "MM-DD-YYYY"
>>> date_string.split("-" , 1)
['MM-DD', 'YYYY']
>>>

Question 32.
What is the difference between the splif() and partltion( ) function?
Answer:
The result of a partition function is a tup1e and it retains the delimiter.

>>> date_string = "MM-DD-YYYY"
>>> date_string.partition("-" , 1)
('MM', ' - ' , 'DD-YYYY')

The partition ( ) function on the other hand looks for the delimiter from the other end.

>>> date_string = "MM-DD-YYYY"
>>> date_string.rpartition("-")
('MM-DD', '-', 'YYYY')
>>>

Question 33.
Name the important escape sequence in Python.
Answer:
Some of the important escape sequences in Python are as follows:

  • \\: Backslash
  • \’: Single quote
  • \”: Double quote •
  • \f: ASCII form feed
  • \n: ASCII linefeed
  • \t: ASCII tab
  • \v: Vertical tab

String Methods

capitalize ( )
Will return a string that has first alphabet capital and the rest are in lower case, ‘

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.capitalize ( )
'Happy birthday'
>>>

casefold( )

Removes case distinction in string. Often used for caseless matching. ‘

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.casefold()
'happy birthday'
>>>

centre( )

The function takes two arguments: (1) length of the string with padded characters (2) padding character (this parameter is optional)

>>> string1 = "HAPPY BIRTHDAY"
>>> new_string = string1.center(24)
>>> print("Centered String: ", new_string)
Centered String: HAPPY BIRTHDAY
> >>

count( )

Counts the number of times a substring repeats itself in the string.
>>> string1 = "HAPPY BIRTHDAY"
>>> string1.count("P")
2
>>>

You can also provide the start index and ending index within the string where the search ends.

encode( )

Allows you to encode Unicode strings to encodings supported by python.

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.encode( )
b'HAPPY BIRTHDAY'

By default, python uses utf-8 encoding.
It can take two parameters:
encoding – type a string has to be encoded to and
error- response when encoding fails

>>> string1 = "HAPPY BIRTHDAY"
>>> string1.endswith('Y')
True
>>> string1.endswith('i')
False

endswith( )

It returns true if a string ends with the substring provided else it will return false.

>>> string1 = "to be or not to be"
>>> string1.endswith("not to be")
True
>>>

find( )

Get the index of the first occurrence of a substring in the given string.

>>> string1 = "to be or not to be"
>>> string1 .find ('be' )
3
>>>

format( )

The format function allows you to substitute multiple values in a string. With the help of positional formatting, we can insert values within a string. The string must contain {} braces, these braces work as a placeholder. This is where the values will be inserted. The format) the function will insert the values.

Example

 >>> print("Happy Birthday { }".format("Alex"))
Happy Birthday Alex

Example

>>> print("Happy Birthday { }, have a { } day!!", format("Alex","Great"))
Happy Birthday Alex, have a Great day ! !
>>>

 

Values that exist in the format( ) are tup1e data types. A value can be called by referring to its index value.

Example

>>> print("Happy Birthday {0}, have a {l} day!!", format("Alex","Great"))
Happy Birthday Alex, have a Great day!!
>>>

 

More types of data can be added to the code using {index: conversion} format where the index is the index number of the argument and conversion is the conversion code of data type.

s- string
d- decimal
f- float
c- character
b- binary
o- octal
x- hexadecimal with lower case letters after 9
X-hexadecimal with upper case letters after 9
e-exponent

Example

>>> print("I scored {0:.2f}% in my exams" . format(86))
I scored 86.00% in my exams,

index( )
It provides the position of the first occurrence of the substring in the given string.

>>> string1 = "to be or not to be"
>>> string1.index('not')
9
>>>

isalnum( )

It returns true if a string is alphanumeric else it returns false.

>>> string1 = "12321$%%^&*"
>>> string1.isalnum( )
False
>>> string1 = "string1"
>>> string1.isalnum()
True
>>>

isalpha( )

It returns true if the whole string has characters or returns false.

>>> string1.isalpha( )
False
>>> string1 = "tobeornottobe"
>>> string1.isalpha( )
True
>>>

isdeimal( )

Returns true if the string has all decimal characters.

>>> string1 = "874873"
>>> string1.isdecimal()
True

isdigit( )

Returns true if all the characters of a string are digits:

>>> string1 = "874a873"
>>> string1.isdigit()
False
>>>

islower( )

>>> string1 = "tIger"
>>> string1.islower()
False
>>>

isnumeric( )

Returns true if the string is not empty characters of a string are numeric.

>>> string1 = "45.6"
>>> string1.isnumeric()
False
>>>

isspace( )

Returns true if the string only has space.

>>> string1 =" "
>>> string1.isspace()
True
>>>

lower( )

Converts upper case letters to lower case.

>>> string1 ="TIGER"
>>> string1.lower()
'tiger'
>>>

swapcase( )

Changes lower case letters in a string to upper case and vice-versa.

>>> string1 = "tiger"
>>> string1 = "tiger".swapcase()
>>> string1
'TiGER'
>>>

Question 34.
What are execution or escape sequence characters?
Answer:
Characters such as alphabets, numbers, or special characters can be printed easily. However, whitespaces such as line feed, tab, etc. cannot be displayed like other characters. In order to embed these characters, we have used execution characters. These characters start with a backslash character (\) followed by a character as shown in the following code:

1. \n stands for the end of the line.
>>> print(“Happy \nBirthday”)
Happy
Birthday
2. \\ prints backslash – ‘V
. >>> print(‘\\’)
\
3. \t prints a tab
>>> print(“Happy\tBirthday”)
Happy Birthday

Lists

  • • Lists are ordered and changeable collections of elements.
  • • Can be created by placing all elements inside a square bracket.
  • • All elements inside the list must be separated by a comma
  • • It can have any number of elements and the elements need not be of the same type.
  • • If a list is a referential structure which means that it actually stores references to the elements.
  • Lists are zero-indexed so if the length of a string is “n” then the first element will have an index of 0 and the last element will have an index of n-1.
  • Lists are widely used in Python programming.
  • Lists are mutable therefore they can be modified after creation.

Question 35.
What is a list?
Answer:
A list is an in-built Python data structure that can be changed. It is an ordered sequence of elements and every element inside the list may also be called an item. By ordered sequence, it is meant that every element of the list can be called individually by its index number. The elements of a list are enclosed in square brackets[ ].

>>> # Create empty list
>>> list1 = [ ] 
>>> # create a list with few elements
>>> list 2 = [12, "apple" , 90.6,]
>>> list1
[ ] 
>>>list2
[12 , 'apple' , 90.6]
>>>

Question 36.
How would you access the 3rd element of the following list?

list1= ["h","e","1","p"]

What would happen when you try to access list1 [4]?
Answer:
The third element of list1 will have an index of 2. Therefore, we can access it in the following manner:

>>> list1 = ["h","e","1","p"]
>>> list1 [2]
'1'
>>>

There are four elements in the list. Therefore, the last element has an index of 3. There is no element at index 4. On trying to access list1 [4] you will get an “IndexError: list index out of range”

Question 37.
list1 = [”h”,”e”,”I”,”p”]. What would be the output for list1 [-2] and list1 [-5]?
Answer:
list1 [-2] = T
list1 [-5] will generate IndexError: list index out of range
Similar to Strings, the slice operator can also be used on the list. So, if the range given is [a:b]. It would mean that all elements from index a to index b will be returned. [a:b:c] would mean all the elements from index a to index b, with stride c.

Question 38.
list1 = [“l”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
What would be the value for the following?

  1. list1 [5]
  2. list1 [-5]
  3. list1 [3:6]
  4. list1 [:-3]
  5. list1[-3:]
  6. list1 [:]
  7. list1 [1:8:2]
  8. list1 [::2]
  9. list1[4::3]

Answer:

>>> list1 = ["I","L","O","V","E","p","Y","T","H","O","N"]
>>> list1 [5]
'p'
>>> list1 [-5]
'Y'
>>> list1 [3:6]
['V' , 'E' , 'P']
>>> list1 [:-3]
['I' , 'L' , 'O' ,'V' , 'E' , 'P' , 'Y' , 'T']
>>> list1 [-3:]
['H' , 'O' , 'N']
>>> list1 [:]
['I' , 'L' , 'O' ,'V' , 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' ]
>>> list1 [1:8:2]
['L' ,'V' , 'P' , 'T' ,]
>>> list1[: :2]
['I' , 'O' , 'E' , 'Y' , 'H' , 'N']
>>> list1 [4 : :3]
['E' , 'T' , 'N']
>>>

Question 39.
list1 = [“I”,”L”,”O”,”V”,”E”,”p”,”Y”,”T”,”H”,”O”,”N”]
list2 = [‘O’,’N’,’L’ , ‘Y’]
Concatenate the two strings.
Answer:

>>> list1 = list1+list2
>>> list1
['I' list1 , 'L' 'O' 'V' 'E' , 'P' , 'Y' , 'T' , 'H' , 'O' , 'N' , 'O' , 'N' , 'L' , 'Y' ]
>>>

Question 40.
How can you change or update the value of the element in a list?
Answer:
You can change the value of an element with the help of the assignment operator (=).

>>> list1 = [1,2,78,45,93,56,34,23,12,98,70]
>>> list1 = [1,2,78,45,93,56,34,23,12,98,70]
>>> list1 [3]
45
>>> list1[3]=67
>>> list1 [3]
67
>>> list1
[1,2,78,45,93,56,34,23,12,98,70]
>>>

Question 41.
list1 =[1,2,78,45,93,56,34,23,12,98,70]
list1[6:9]=[2,2,2]
What is the new value of list1?
Answer:
[1,2, 78, 45, 93, 56, 2, 2, 2, 98, 70]

Question 42.
What is the difference between append( ) and extend( ) function for lists?
Answer:
The append( ) function allows you to add one element to a list whereas extending ( ) allows you to add more than one element to the list.

>>> list1 = [1,2, 78,45,93,56,34,23,12,98,70]
>>> list1.append(65)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]

>>> list1.extend([-3,- 5, - 7 , -5] )
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, -3, -5, -7, -5]
>>>

Question 43.
list1 = [“h”,”e”,”l”,”p”]
What would be the value of list1 *2?
Answer:
[‘h’, ‘e’, T, ‘p’, ‘h’, ‘e’, ‘l’ , ‘p’]

Question 44.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 +=[87]
What is the value of list1?
Answer:
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65, 87]

Question 45.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
list1 -=[65]
What will be the output?
Answer:
The output will be TypeError: unsupported operand type(s) for -=: ‘list’ and ‘list’

Question 46.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
How will you delete second element from the list?
Answer:
An element can be deleted from a list using the ‘del’ keyword.

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> del(list1 [1])
>>> list1
[1, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 47.
list1 = [[1,4,5,9],[2,4,7,8,1]]
list1 has two elements, both are lists.
How will you delete the first element of the second list contained in the list1?
Answer:

>>> list1 = [ [1,4,5,9] , [2,4,7,8, 1] ]
>>> del(list1[1][0])
>>> list1
[[1, 4, 5, 9] , [4, 7, 8, 1] ]
>>>

Question 48.
How would you find the length of o list?
Answer:
The len( ) function is used to find the length of a string.

>>> list1 = [1, 2, ‘78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> len(list1)
12
>>>

Question 49.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Insert a value 86 at 5th position.
Answer:

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>list1 . insert (4, 86)
>>> list1
[1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 50.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Remove the value 78 from list1.
Answer:
A specific element can be removed from a list by providing the value to remove( ) function.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . remove (78)
>>> list1
[1,2,45, 93, 56, 34, 23, 12, 98, 70, 65]
>>>

Question 51.
What does the pop( ) function do?
Answer:
The pop( ) function can be used to remove an element from a particular index and if no index value is provided, it will remove the last element. The function returns the value of the element removed.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . pop(3)
45
>>> list1
[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . pop( )
65
>>> list1
[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70]
>>>

Question 52.
Is there a method to clear the contents of a list?
Answer:
Contents of a list can be cleared using the clear( ) function.

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . clear ( )
>>> list1
[ ]
>>>

Question 53.
list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
Find the index of element having value 93.
Answer:
We can find the index of a value using the index( ) function.

>>> list1 = [1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1.index(93)
4
>>>

Question 54.
Write code to sort list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65].
Answer:
We can sort a list using sort( ) function.

>>> list1 = [1,2,78,45,93,56,34,23,12,98,70,65]
>>> list1 . sort ( )
>>> list1
[1,2,12,23,34,45,56,65,70,78,93,98]
>>>

Question 55.
Reverse elements of list1 =[1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65].
Answer:

>>> list1 = [1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65]
>>> list1 . reverse ( )
>>> list1
[65,70,98,12,23,34,56,93,45,78,2,1]
>>>

Question 56.
How can we check if an element exists in a list or not?
Answer:
We can check if an element exists in a list or not by using ‘in’ keyword:

>>> list1 = [(1,2,4) , [18,5,4,6,2] , [4,6,5,7], 9, 23, [98, 56] ]
>>> 6 in list1
False
>>> member = [4,6,5,7]
>>> member in list1
True
>>>

tuples

  • tuples are sequences just like lists but are immutable.
  • Cannot be modified.
  • tuples may or may not be delimited by parenthesis ( ).
  • Elements in a tup1e are separated by a comma. If a tuple has only one element then a comma must be placed after that element. Without a trailing comma, a single value in simple parenthesis would not be considered as a tuple.
  • Both tup1es and lists can be used under the same situations.

Question 57.
When would you prefer to use a tup1e or a list?
Answer:
tup1es and lists can be used for similar situations but tup1es are generally preferred for the collection of heterogeneous data types whereas lists are considered for homogeneous data types. Iterating through a tup1e is faster than iterating through a list. tup1es are ideal for storing values that you don’t want to change. Since tup1es are immutable, the values within are write-protected.

Question 58.
How can you create a tup1e?
Answer:
A tup1e can be created in any of the following ways:

>>> tup1 =( )
>>> tup2=(4 , )
>>> tup3 = 9,8,6,5
>>> tup4= (7,9,5,4,3).
>>> type(tup1)
<class ' tup1e' >
>>> type(tup2)
<class 'tup1e'>
>>> type(tup3)
<class ' tup1e' >
>>> type(tup4)
<class 'tup1e'>

However, as mentioned before, the following is not a case of a tup1e:

>>> tup5 = (0)
>>> type(tup5)
1cclass 'int'>
>>>

Question 59.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
How would you retrieve the 7th element of this tup1e?
Answer:
Accessing an element of a tup1e is the same as accessing an element of a list.

>>> tup1 = (1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
>>> tup1 [6]
34
>>>

Question 60.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would happen when we pass an instruction tup1[6]=6?
Answer:
A tup1e is immutable hence tup1 [6]=6 would generate an error.

Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
tup1[6]=6
TypeError: 'tup1e' object does not support item
assignment
>>>

Question 61.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would happen if we try to access the 6th element using tup1 [5.0]?
Answer:
The index value should always be an integer value and not afloat. This would generate a type error. TypeError: ‘tup1e’ object does not support item assignment.

Question 62.
tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
What would be the value of tup1 [1 ][0]?
Answer:
8

Question 63.
tup1 =(1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What is the value of tup1 [-7] and tup1 [-15]?
Answer:

>>> tup1[-7]
56
>>> tup1[-15]
Traceback (most recent call last) :
File "<pyshell#2>", line 1, in <module> tup1 [-15]
IndexError: tup1e index out of range
>>>

Question 64.
tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
tup2 = (1,2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
Find the value of:

  1. tup1[2:9]
  2. tup2[:-l]
  3. tup2[-l:]
  4. tup1[3:9:2]
  5. tup2[3:9:2]

Answer:
1. tup1 [2:9]
((4, 6, 5, 7), 9, 23, [98, 56])
2. tup2[:-l]
(1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70)
3. tup2[-l:]
(65,)
4. tup1[3:9:2]
(9, [98, 56])
5. tup2[3:9:2]
(45, 56, 23)

Question 65.
tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
What will happen if tup1[l][0]=18 instruction is passed? What would happen if we pass an instruction tup1 [l].append(2)?
Answer:
tup 1 [ 1 ] is a list object and the list is mutable.
a tuple is immutable but if an element of a tup1e is mutable then its nested elements can be changed.

>>> tup1 = (1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
>>> tup1 [1] [0] = 18
>>> tup1 [1]
[18 , 5, 4, 6 ]
>>> tup1 [1] . append (2)
>>> tup1
((1,2,4) , [8,5,4,6],(4,6,5,7),9,23,[98,56] , 1,2,78,45, 93,56,34,23,12,98,70,65)
>>>

Question 66.
tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
tup2 =(1, 2, 78, 45, 93, 56, 34, 23, 12, 98, 70, 65)
What would be the output for tup1+tup2?
Answer:

>>> tup1 =(1,2,4), [8,5,4,6],(4,6,5,7),9,23,[98,56]
>>> tup2 = (1,2,78,45,93,56,34,23,12,98,70,65)
>>> tup1+tup2
>>> tup1
( (1,2,4) , [18,5,4,6,2] , (4,6,57), 9,23,[98,56], 1,2,78,45, 93, 56, 34,23,12,98,70,65)
>>>

Question 67.
How can we delete a tup1e?
Answer:
A tup1e can be deleted using del command.

>>> tup1 = (1,2,4), [8,5,4,61 , (4,6,5,7) ,9,23, [98,56]
>>> del tup1
>>> tup1
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
tup1
NameError: name 'tup1' is not defined
>>>

Question 68.
tup1 = ((1, 2, 4), [18, 5, 4, 6, 2], (4, 6, 5, 7), 9, 23, [98, 56])
tup2 = 1,6,5,3,6,4,8,30,3,5,6,45,98
What is the value of:

  1. tup1.count(6)
  2. tup2.count(6)
  3. tup1.index(6)
  4. tup2.index(6)?

Answer:
1. tup1.count(6)
0
2. tup2.count(6)
3
3. tup1.index(6)
0
4. tup2.index(6)
1

Question 69.
How can we test if an element exists in a tup1e or not?
Answer:
We can check if an element exists in a tup1e or not by using in a keyword:

>>> tup1 = ((1, 2, 4), [18, 5, 4, 6, 2], (4, 6, 5, 7) , 9, 23, [98, 56] )
>>> 6 in tup1
False
>>> member = [4,6,5,7]
>>> member in tup1
False
>>> member2 = (4, 6, 5, 7)
>>> member2 in tup1
True
>>>

Question 70.
How can we get the largest and the smallest value in tup1e?
Answer:
We can use max( ) function to get the largest value and min() function to get the smallest value.

>>> tup1 = (4, 6, 5, 7)
>>> max(tup1)
7
>>> min(tup1)
1 4
>> >

Question 71.
How to sort all the elements of a tup1e?
Answer:

>>> tup1 =(1,5,3,7,2,6,8,9,5,0,3,4,6,8)
>>> sorted(tup1)
[0, 1, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9]

Question 72.
How can we find the sum of all the elements in a tup1e?
Answer:
We can find some of all elements by using the sum( ) function.

>>> tup1 =(1,5,3,7,2,6,8,9,5,0,3,4,6,8)
>>> sum(tup1)
67

Enumerate function for tup1e and list in for loop section mentioned.

Dictionary

  • Unordered sets of objects.
  • Also known as maps, hashmaps, lookup tables, or associative array.
  • Data exists in key-value pair. Elements in a dictionary have a key and a corresponding value. The key and the value are separated from each other with a colon’: ’ and all elements are separated by a comma.
  • Elements of a dictionary are accessed by the “key” and not by index. Hence it is more or less like an associative array where every key is associated with a value .and elements exist in an unordered fashion as key-value pair.
  • Dictionary literals use curly brackets ‘ { } ’.

Question 73.
How can we create a dictionary object?
Answer:
A dictionary object can be created in any of the following ways:

>>> dictl = { }
>>> type(dict1)
<class 'dict'>

>>> dict2 = {'key1' :'value1', 'key2': 'value2', 'key3': 'value3', ' key4': ' value4'}
>>> dict2
{'key1': 'value1', 'key2': 'value2', 'key3' : 'value3', 'key4': 'value4' }
>>> type(dict2)
<class 'diet'>

>>> dict3 = diet({'key1': 'value1', 'key2':' value2', 'key3': 'value3', ' key4 ':' value4' })
>>> dict3
{'key1': 'value1', 'key2' : 'value2', 'key3': 'value3', 'key4':'value4'}
>>> type(dict3)
<class 'diet'>

>>> dict4 = diet(f('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3 ' ), ('key4','value4')])
>>> dict4 {'key1': 'value1' 'key2' : 'value2', 'key3': 'value3', 'key4':' value4'}
>>> type(dict4)
<class 'diet'>

Question 74.
How can you access the values of a dictionary?
Answer:
Values of a dictionary can be accessed by the help of the keys as shown in the following code:

>>> student_dict = {'name':'Mimoy', 'Age':12, 'Grade' :7, 'id' :'7102' }
>>> student_dict['name']
'Mimoy'

Keys are case-sensitive. If you give student diet [‘age’] instruction a key Error will be generated because the key actually has capital A in Age. The actual key is Age and not age.

>>> student_dict['age' ]
Traceback (most recent call last) -.
File "<pyshell#20>", line 1, in <module>
student_dict['age']
KeyError: 'age'
>>> student_dict['Age']
12
>>>

Question 75.
Can we change the value of an element of a dictionary?
Answer:
Yes, we can change the value of an element of a dictionary because dictionaries are mutable.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'} .
>>> dict1['English literature'] = '78%'
>>> dict1
{'English literature': '78%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' }
>>>

Question 76.
Can a dictionary have a list as a key or a value?
Answer:
A dictionary can have a list as a value but not as a key.

>>> dict1 = {'English literature':'67%','Maths':'78% ','Social Science':'87%','Environmental Studies': 97%' }
>>> dictl['English literature' >>> dict1] = ['67% ,'78%']
{'English literature': ['67%', '78%'], Maths': '78%', 'Social Science': '87%' , 'Environmental Studies' : '97%' }
>>>

If you try to have a list as a key then an error will be generated:

>>> dict1 = {['67%', '78%']:'English literature', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%'}
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
dict1 = {['67%', '78%']:'English literature',
'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%'}
TypeError: unhashable type: 'list'
>>>

Question 77.
How are elements deleted or removed from a dictionary?
Answer:
Elements can be deleted or removed from a dictionary in any of the following ways:

>>> dict1 = {‘English literature’:’67%YMaths’:’78%’, ’Social Science’: ’ 87%’, ’Environmental Studies ’: ’ 97% ’}

I. The pop( ) can be used to remove a particular value from a dictionary. pop( ) requires a valid key-value as an argument or you will receive a key error. If you don’t pass any argument then you will receive a type error: “TypeError: descriptor ‘pop’ of ‘diet’ object needs an argument”

>>> dict1.pop('Maths' )
'78%'
>>> dict1
{'English literature' '67%', 'Social Science': '87%', 'Environmental Studies' : '97%'}

II. The pop item( ) can be used to remove any arbitrary item.

>>> dict1.popitem( )
('Environmental Studies', '97%')
>>> dict1
{'English literature': '67%', 'Social Science': '87%' }

III. Yod can delete a particular value from a dictionary using the ‘del’ keyword.

>>> del dict1['Social Science']
>>> dict1
{'English literature': '67%'}

IV. clear( ) function can be used to clear the contents of a dictionary.

>>> dict1.clear( )
>>> dict1
{ }

V. The del( ) function can also be used to delete the whole dictionary after which if you try to access the dictionary object, a Name Error will be generated as shown in the following code:

>>> del dict1
>>> dict1
Traceback (most recent call last):
File "<pyshell#ll>" , line 1, in <module>
dict1
NameError: name 'dict1' is not defined
>>>

Question 78.
What is the copy( ) method used for?
Answer:
A copy method creates a shallow copy of a dictionary and it does not modify the original dictionary object in any way.

>>> dict2 = dict1.copy()
>>> dict2
{'English literature': '67%', 'Maths': ' 78%', 'Social Science': '87%','Environmental Studies': ' 97%'}
>>>

Question 79.
Explain from Keys( ) method.
Answer:
The from keys( ) method returns a new dictionary that will have the same keys as the dictionary object passed as the argument. If you provide a value then all keys will be set to that value or else all keys will be set to ‘None.

I. Providing no value
>>> dict2 = diet.fromkeys(dict1)
>>> dict2
{‘English literature’: None, ‘Maths’: None, ‘Social Science’ : None, ‘Environmental Studies’ : None}
>>>

II. Providing a value
>>> dict3 = diet.fromkeys(dictl,’90%’)
>>> dict3
{‘English literature’: ‘90%’, ‘Maths’: ‘90%’,
‘Social Science’: ‘90%’, ‘Environmental Studies’: ‘90%’ }
>>>

Question 80.
What is the purpose of items( ) function?
Answer:
The items( ) function does not take any parameters. It returns a view object that shows the given dictionary’s key-value pairs.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'}
>>> dictl.items()
dict_items([('English literature', '67%'),
('Maths', '78%'), ('Social Science', '87%'), ('Environmental Studies', '97%')])
>>>

Question 81.
dict1 = {(1,2,3):[‘1’,’2’,’3’]}
Is the instruction provided above, a valid command?
Answer:
dict1 = {(l,2,3):[‘r,’2’,’3’]} is a valid command. This instruction will create a dictionary object. In a dictionary, the key must always have an immutable value. Since the key is a tup1e which is immutable, this instruction is valid.

Question 82.
dict_items([(‘English literature’, ‘67%’), (‘Maths’, ‘78%’), (‘Social Science’, ‘87%’), (‘Environmental Studies’, ‘97%’)]).
Which function can be used to find the total number of key-value pairs in dict1?
Answer:
The len( ) function can be used to find the total number of key-value pairs.

>>> dictl = {'English literature' :' 67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'}
>>> len(dict1)
4
>>>

Question 83.
dict1 = {‘English literature’:’67%’,’ Maths’:’78%’,’ Social Science’:’87%’,’ Environmental Studies’:’97%’}
dict1 .keys( )
What would be the output?
Answer:
The keys( ) function is used to display a list of keys present in the given dictionary object.

>>> dict1 = {'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dictl.keys( )
dict_keys(['English literature', 'Maths', 'Social Science', 'Environmental Studies'])
>>>

Question 84.
dict1 = {‘English literature’:’67%’,’ Maths’:’78%’,’ Social Science’:’87%’,’ Environmental Studies’:’97%’}
‘Maths’ in dict1
What would be the output?
Answer:
True

The ‘in’ operator is used to check if a particular key exists in the diet or not. If the key exists then it returns ‘True’ else it will return ‘False’.

Question 85.
dict1 = {‘English literature’:’67%’,’Maths’:’78%’,’Social Science’:’87%’,’Environmental Studies’:’97%’}
dict2 = {(1,2,3):[‘1’,’2’,’3’]}
dict3 = {‘Maths’: ‘78%’}
dict4= {‘Maths’: ‘98%’,’Biology’:’56%’}
What would be the output of the following:

  1. dict1.update(dict2)
  2. dict2={(l,2,3):[‘l\’2Y3’]}
  3. dict3 ,update(dict3)
  4. dict1.update(dict4)

Answer:
The update( ) method takes a dictionary object as an argument. If the keys already exist in the dictionary then the values are updated and if the key does not exist then the key-value pair is added to the dictionary.

>>> dict1 = { 'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dict2 = { (1,2,3) : [ '1' , ' 2' , ' 3' ] }
>>> dict1.update(dict2)
>>> dict1
{'English literature': '67%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' , (1, 2, 3) : ['1' , '2' , '3' ] }
dict1 = {'English literature':'67%','Maths':'78%','Social Science' :'87%','Environmental Studies' :'97%'}
>>> dict3 = { 'Maths' : '78%' }
>>> dict1 .update (dict3)
>>> dict1
{'English literature': '67%', 'Maths': '78%', 'Social Science': '87%', 'Environmental Studies': '97%' }
dict3 = {'Maths' : '78%' }
>>> dict3.update(dict3)
>>> dict3 {'Maths' : '78%' }
dict1 = {'English
literature':'67%','Maths':'78%','Social Science':'87%','Environmental Studies':'97%'} dict4 = {'Maths': '98%','Biology':'56%'}
dictl.update(dict4) dictl
{'English literature' '67%', 'Maths': '98%',
'Social Science': '87%', 'Environmental Studies':
'97%.', 'Biology': '56%'}

Question 86.
dictl = {‘English literature’:’67%\’Maths’:78%\’Social Science’:’87%’,‘Environmental Studies’:’97%’}
dictl.values( )
What will be the output?
Answer:

>>> dictl.values( )
diet values (['67%', ' 78%' ' 87%' '97%'])
>>>

Sets

  • An unordered collection of items
  • Every element is unique and immutable
  • Set itself is mutable
  • Used for performing set operations in Math
  • Can be created by placing all the items in curly brackets {}, separated by ‘ , ‘
  • Set can also be created using the inbuilt set() function
>>> set1 ={8,9,10}
>>> set1
{8, 9, 10}
>>>
  • Since sets are unordered, indexing does not work for it

Question 87.
How can we create an empty set?
Answer:
The inbuilt function set( ) is used to create an empty set. Empty curly braces cannot be used for this task as it will create an empty dictionary object.

Question 88.
How can we add a single element to a set?
Answer:
We can add a single element with the help of add() function.

>>> set1 ={12,34,43,2}
>>> set1 . add(32)
>>> set1
(32, 2, 34, 43, 12}
>>>

Question 89.
How can we add multiple values to a set?
Answer:
Multiple values can be added using update( ) function.

>>> set1 ={12,34,43,2}
>>> set1.update( [76,84,14,56])
>>> set1
{2, 34, 43, 12, 76, 14, 84, 56}
>>>

Question 90.
What methods are used to remove value from sets?
Answer:
(1) discard( )
(2) remove ( )

Question 91.
What is the purpose of pop() method?
Answer:
The pop( ) function randomly removes an element from a set.

Question 92.
How can we remove all elements from a set?
Answer:
All elements from a set can be removed using the

>>> set1 = {2, 34, 43, 12, 76, 14, 84, 56}
>>> set1.clear( )
>>> set1
set ( )

Question 93.
What are various set operations?
Answer:

>>> #Union of two sets
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl | set2
{1, 3, 4, 5, 6, 7, 10, 12, 15}
>>> #Intersection of two sets
>>> set1 = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl & set2 {10, 3, 7}
>>> #Set difference
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> setl - set2
{1, 4, 5, 6} .
>>> #Set symmetric difference
>>> setl = {1,5,4,3,6,7,10}
>>> set2 = {10,3,7,12,15}
>>> set1∧set2
{1, 4, 5, 6, 12, 15}
>>>

Python Data Types

Question 94.
What are some of the built-in data types available in Python?
Answer:

  • Integer,
  • float,
  • long integer,
  • octal integer,
  • hexadecimal integer,
  • complex,
  • string,
  • list,
  • dictionary,
  • tuple,
  • file.

Question 95.
What is the difference between a tuple and a list?
Answer:
A tuple is immutable, it cannot be added to, rearranged, nor have items removed. It is faster to access and use than a list but it cannot be manipulated.

Question 96.
What are some of the specialized container types that are new in Python since 2.4?
Answer:
Namedtuple( ), deque, Counter, OrderedDict and defaultdict.

Question 97.
Illustrate defining a list.
Answer:
myList = [1, 2, “three”, 4] or myList = [ “I”, “Love”, “Python”] etc.

Question 98.
Write a code fragment that illustrates accessing a list by index.
Answer:
mylndex = 0
while mylndex < len(myList): print mylndex, ‘, myListlmylndex] mylndex++

Question 99.
What exception is raised when a negative index is used to access a list?
Answer:
Tricky question: Negative indexes are allowed in Python, it accesses the list from the bottom rather than the top. An index of -1 accesses the last item in the list, -2 the second to last, and so on.

Question 100.
Can a list contain other lists?
Answer:
Yes. A list can contain objects of any type.

Question 101.
How is a sublist accessed?
Answer:
The form is listname[listindex][sublistindex]. For example, myList[0][5] would retrieve the fifth item from the first sublist in myList.

Question 102.
How is a list sliced? Provide an example.
Answer:
By using the start, colon, end syntax. myList[5:10] This would return a list containing the 6th through 11th items in my list.

Question 103.
How would you add an item to an unsorted list?
Answer:
Using the append method. myList.append(theNexuItem)

Question 104.
How would you add an item to a sorted list in a specific position?
Answer:
Using the list insert method. myList.insert(index, theNewItem)

Question 105.
How would you remove an item from the list, if you know its index?
Answer:
Using the .pop list method. myList.pop(2) would remove the third item in my list.

Question 106.
How would you combine one list with another?
Answer:
Using the extend list method. myList.extend(theOtherList)

question 107.
How would you alphabetize a simple list of strings?
Answer:
Using the built-in sort method. myList.sort( )

Question 108.
How is a tuple created?
Answer:
myTuple = (“First item”, “Second Item”)

Question 109.
How is a tuple converted to a list, and a list to a tuple?
Answer:
Using the built-in functions list and tuple. myTuple = tuple(myList) and myList = list(myTuple) a

Question 110.
What is a dictionary and how is it constructed?
Answer:
A dictionary is a list containing name / value pairs.
myDict = {firstKey: firstValue, secondKey : secondValue } a

Question 111.
How is dictionary value retrieved?
Answer:
The usual method is to specify the key value in brackets. myDict[myKey] will return the value associated with myKey in the dictionary.

Question 112.
How are values added to a dictionary? Illustrate with an example.
Answer:
By creating a new key, and assigning a value to it.
myDict[myNewKey] = myNewValue

Question 113.
Can a dictionary contain lists or other dictionaries?
Answer:
Yes. The values assigned in a dictionary can be any valid Python object.

Python Interview Questions on Data Types and Their in-built Functions Read More »

Python Interview Questions on Introduction to Python

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Introduction to Python

Python

  • Python is a very popular programming language. It is known for being an interactive and object-oriented programming language.
  • Free software, an open-source language with a huge number of volunteers who are working hard to improve it. This is the main reason why the language is current with the newest trends.
  • It has several libraries which help build powerful code in a short span of time.
  • It is a very simple, powerful, and general-purpose computer programming language.
  • Python is easy to leam and easy to implement.
  • Well-known corporations are using Python to build their site. Some of the wells know websites built-in Python are as follows:
  1. Google
  2. Quora
  3. Yahoo!
  4. Instagram
  5. Survey Monkey
  6. You Tube
  7. Dropbox
  8. Reddit
  9. Spotify
  10. Bitly
  • The main reason for the popularity of the Python programming language is the simplicity of the code.
  • You require no skills to leam Python.

Question 1.
What can you do with python?
Answer:
There is no limit to what can be achieved with the help of Python Programming:

  • Python can be used for small or large, online or offline applications.
  • Developers can code using fewer lines of code compared to other languages.
  • Python is widely used for developing web applications as it has a dynamic system and automatic memory management is one of its strongest points.
  • Some of the very well-known Python frameworks are Pyramid, Django, and Flask.
  • Python is also used for a simple scripting and scientific modeling and big data applications:
  • It is the number one choice for several data scientists.
  • Its libraries such as NumPy, Pandas data visualization libraries such as Matplotlib and Seaborn have made Python very popular in this field.
  • Python also has some interesting libraries such as Scikit-Leam, NLTK, and TensorFlow that implement Machine learning Algorithms.
  • Video Games can be created using the PyGame module. Such applications can run on Android devices.
  • Python can be used for web scrapping.
  • Selenium with Python can be used for things like opening a browser or posting a status on Facebook.
  • Modules such a Tkinter and PyQt allow you to build a GUI desktop application.

Question 2.
Why is Python considered to be a highly versatile programming language?
Answer:
Python is considered to be a highly versatile programming language because it supports multiple models of programming such as:

  • OOP
  • Functional
  • Imperative
  • Procedural

Question 3.
What are the advantages of choosing Python over any other programming language?
Answer:
The advantages of selecting Python over other programming languages are as follows:

  • Extensible in C and C++.
  • It is dynamic in nature.
  • Easy to learn and easy to implement.
  • Third-party operating modules are present: As the name suggests a third party module is written by a third party which means neither you nor the python writers have developed it. However, you can make use of these modules to add functionality to your code.

Question 4.
What do you mean when you say that Python is an interpreted language?
Answer:
When we say that Python is an interpreted language it means that python code is not compiled before execution. Code written in compiled languages such as Java can be executed directly on the processor because it is compiled before runtime and at the time of execution it is available in the form of machine language that the computer can understand. This is not the case with Python. It does not provide code in machine language before runtime. The translation of code to machine language occurs while the program is being executed.

Question 5.
Are there any other interpreted languages that you have heard of?
Answer:
Some frequently used interpreted programming languages are as follows:

  • Python
  • Pearl
  • JavaScript
  • PostScript
  • PHP
  • PowerShell

Question 6.
Is Python dynamically typed?
Answer:
Yes, Python is dynamically typed because in a code we need not specify the type of variables while declaring them. The type of a variable is not known until the code is ‘executed.

Question 7.
Python is a high-level programming language? What is a need for high-level programming languages?
Answer:
High-level programming languages act as a bridge between the machine and humans. Coding directly in machine language can be a very time-consuming and cumbersome process and it would definitely restrict coders from achieving their goals. High-level programming languages like Python, JAVA, C++, etc are easy to understand. They are tools that programmers can use for advanced-level programming. High-level languages allow developers to code complex code that is then translated to machine language so that the computer can understand what needs to be done.

Question 8.
Is it true that Python can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java?
Answer:
Yes

Question 9.
What are the different modes of programming in Python?
Answer:
There are two modes of programming in Python:
1. Interactive Mode Programming:
In this, we invoke the interpreter without passing any script or python file. We can start the Python command-line interpreter or the Python shell in IDLE and start passing instructions and get instant results.
2. Script Mode of Programming:
Saving code in a Python file. When the script is executed the interpreter is invoked and it is active as long as the script is running. Once all the instructions of the script are executed the interpreter is no longer active.

Question 10.
Draw a comparison between Java and Python.
Answer:

1. Java is compiled and Python is interpreted:
Both Java and Python are compiled down to the byte code on the virtual machine. However, in the case of Python, this happens automatically during runtime whereas Java has a separate program – javac to accomplish this task. This also means that if speed is the major concern in your project then Java may have an edge over Python but you cannot deny that Python allows faster development (as you will leam in the next point).

2. Java is Statistically typed and Python is dynamically typed:
While coding in Python, it is not required to declare the type of the variable. This makes Python easy to write and read but it can be difficult to analyze. The developer is able to code faster and the task can be accomplished in fewer lines of code. Developing applications in Python can be much faster Python than Java. However, Java’s static type system makes it less prone to bugs.

3. Writing style:
Both Java and Python follow different writing styles. Java encloses everything in braces whereas Python follows indentation that makes the code neat and readable. Indentation also determines the code execution.

4. Both Java and Python are efficient languages:
Both Java and Python are being widely used for web development frameworks. Developers are able to create complex applications that can handle high traffic.

5. Both Java and Python have a strong community and library support:
Both are open source languages having communities that are offering support and contribution to the language. You can easily find a library for almost anything.

6. Python can be more budget-friendly:
Since Python is dynamically typed, it makes development a fast process as a result of which developers can expect to develop an application in a record time thereby lowering down the cost of development.

7. Java is the more preferred language in mobile development:
Android app development is mostly done using Java and XML. However, there are libraries like Kivy which can be used along with Python code in order to make it compatible with android development.

8. Python is preferred for Machine learning, the Internet of things, ethical hacking, data analysis, and artificial intelligence:
Python has very specialized libraries and general flexibility and hence it has become the number one choice for projects that have a bias towards deep learning, machine learning, and image recognition.

9. Java and Python both support OOP:

10. LOC in Java is more than in Python: Let’s have a look at how we would go about printing simple Hello World in Java:

public class HelloWorld 
{ 
  public static void main(String [ ] args) 
{ 
  System.out.println("Hello World"); 
} 
  } 
Whereas in python we just write one line of code: print("Hello World")

11. Java is more difficult to learn as compared to Python:
Python was developed with the main focus on making it easy to learn.

12. Java is stronger when it comes to connectivity with database:
The database access layer of Java is very strong and is compatible with almost any database. Python database connectivity is not as strong as Java.

13. Security:
Java gives high priority to security which is why it is a preferred language for applications that require security but a good developer can code a secure application in Python also.

Question 11.
Once Python is installed, how can we start working on code?
Answer:
After Python is installed there are three ways to start working on code:

1. You can start an interactive interpreter from the command line and start writing the instructions after the »> prompt.

2. If you intend to write a code of several lines then it would be a wise decision to save your file or script with the .py extension and you can execute these files from the command line. Multiline programs can be executed on an interactive interpreter, also but it does not save the work.

3. Python also has its own GUI environment known as Integrated Development Environment (IDLE). IDLE helps programmers write code faster as it helps with automatic indenting and highlights different keywords in different colors. It also provides an interactive environment. It has two windows: the shell provides an interactive environment whereas the editor allows you to save your scripts before executing the code written in it.

Question 12.
What is the function of the interactive shell?
Answer:
The interactive shell stands between the commands given by the user and the execution done by the operating system. It allows users to use easy shell commands and the user need not be bothered about the complicated basic functions of the Operating System. This also protects the operating system from incorrect usage of system functions.

Question 13.
How to exit interactive mode?
Answer:
Ctrl+D or exit( ) can be used to quit interactive mode.

Question 14.
Which character set does Python use?
Answer:
Python uses a traditional ASCII character set.

Question 15.
What is the purpose of indentation in Python?
Answer:
Indentation is one of the most distinctive features of Python. While in other programming languages, developers use indentation to keep their code neat but in the case of Python, indentation is required to mark the beginning of a block or to understand which block the code belongs to. No braces are used to mark blocks of code in Python. Blocks in code are required to define functions, conditional statements, or loops. These blocks are created simply by the correct usage of spaces. All statements that are the same distance from the right belong to the same block.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 1

Remember:

  • The first line of the block always ends with a semicolon (:).
  • Code under the first line of the block is indented. The preceding diagram depicts a scenario of indented blocks.
  • Developers generally use four spaces for the first level and eight spaces for a nested block, and so on.

Question 16.
Explain Memory Management in Python.
Answer:
Memory management is required so that a partial or complete section of the computer’s memory can be reserved for executing programs and processes. This method of providing memory is called memory allocation. Also, when data is no longer required, it must be removed. Knowledge of memory management helps developers develop efficient code.

Python makes use of its private heap space for memory management. All object structures in Python are located in this private heap (which is not accessible by the programmer). Python’s memory manager ensures that this heap space is allocated judiciously to the objects and data structures. An in-built garbage collector in Python recycles the unused memory so that it is available in heap space.

Everything in Python is an object. Python has different types of objects, such as simple objects which consist of numbers and strings, and container objects such as diet, list, and user-defined classes. These objects can be accessed by an identifier- name. Now, let’s have a look at how things work.
Suppose, we assign the value of 5 to a variable a:
a = 5
Here, ‘5’ is an integer object in memory, and ‘a’ has reference to this integer object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 2

In the above illustration, the id( ) function provides a unique identification number of an object. This unique identification number is an integer value that will remain unique and constant for the object during its lifetime. Two objects with non-overlapping lifetimes can have the same id( ) value.

The id for integer object 5 is 140718128935888. Now we assign the same value 5 to variable b. You can see in the following diagram that both a and b have to refer to the same object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 3

Now, let us say:
c = b.
This means, c too will have reference to the same object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 4

Now, suppose we perform the following operation: a =a+1

This means that a is now equal to 6 and now refers to a different object.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 5

Some amount of memory organization is done for every instruction. The underlying operating system allocates some amount of memory for every operation. The Python interpreter gets its share of memory depending on various factors such as version, platform, and environment.

The memory assigned to the interpreter is divided into the following:

1. Stack:
a. Here all methods are executed.
b. References to objects in the heap memory are created in stack memory.
2. Heap:
a. The objects are created in Heap memory.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 6

Now let’s have a look at how things work with the help of an example. Look at the following piece of the code:

def function1(x): 
    value1 = (x + 5)* 2 
    value2 = function2(value1) 
      return value2 
def function2(x): 
   x = (x*10)+5 
   return x 
   x = 5 
final_value = function1 (x) 
print ("Final value = ", final_value)

Now, let’s see how this works. The program’s execution starts from the main which in this case is:

x = 5 
final_value = function1 (x) 
print ("Final value = ", final_value)

Step 1: execute x =5
This creates integer object 5 in the heap and reference to this object i.e. x is created in the main stack memory.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 7

Step 2: is to execute final_value = function1(x)
This statement calls function1( ).

def function1 (x):
value1 = (x + 5)* 2
value2 = function2(value1)
return value2

In order to execute function1 ( ) a new stack frame is added to the memory. Till the time function1( ) is being executed the lower stack frame of x referencing to 5 is put on hold. The integer value 5 is passed as a parameter to this function.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 8

Now, value1 = (x+5)* 2 = (5+5)*2 = 10*2 = 20

Python Interview Questions and Answers on Introduction to Python chapter 1 img 9

function1( ) assigns the value of 50 to value1.
The next step is: value2 = function2(value1)

Here function2( ) is called to evaluate a value that needs to be passed on to value2. In order to accomplish this, another memory stack is created. The integer object value1 having a value of 20 is passed as a reference to function2.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 10

def function2 (x) : 
x = (x*10)+5 
return x

The function function2( ) evaluates the following expression and returns the value:

x = (x*10)+5
x = (20*10)+5 = (200)+5 = 205

 

Python Interview Questions and Answers on Introduction to Python chapter 1 img 11

The function function2( ) is fully executed and value 205 is assigned to value2 in function 1. So, now the stack for function(2) is removed.

 

Python Interview Questions and Answers on Introduction to Python chapter 1 img 12

Now, function1( ) will return the value 205 and it will be assigned to the final_value in the main stack.

Python Interview Questions and Answers on Introduction to Python chapter 1 img 13

Here it is important to note that you would see that x exists in the main as well as in different functions but the values don’t interfere with each other as each x is in a different memory stick.

Question 17.
Explain Reference counting and Garbage collection in Python.
Answer:
Unlike languages like C/ C++, the process of allocation and deallocation of memory in Python is automatic. This is achieved with the help of reference counting and garbage collection.

As the name suggests, reference counting counts the number of times an object is referred to by other objects in a program. Every time a reference to an object is eliminated, the reference count decreases by 1. As soon as the reference count becomes zero, the object is deallocated. An object’s reference count decreases when an object is deleted, the reference is reassigned or the object goes out of scope. The reference count increases when an object is assigned a name or placed in a container.

Garbage collection on the other hand allows Python to free and reclaim blocks of memory that are no longer of any use. This process is carried out periodically. The garbage collector runs while the program is being executed and the moment the reference count of an object reaches zero, the garbage collector is triggered.

Question 18.
What are multi-line statements?
Answer:
All the statements in Python end with a newline. If there is a long statement, then it is a good idea to extend it over multiple lines. This can be achieved using the continuation character (\).

Explicit line continuation is when we try to split a statement into multiple lines whereas in the case of implicit line continuation we try to split parentheses, brackets, and braces into multiple lines.
Example for multiple line statements:

Explicit:

>>> first_num = 54
>>> second_num = 879
>>> third__num = 8 76
>>> total = first_num +\
               second_num+\
               third_num
>>> total
1809
>>>
Implicit:
>>> weeks=['Sunday' ,
                      'Monday',
                      'Tuesday',
                      'Wednesday',
                      'Thursday' ,
                      'Friday',
                      'Saturday']
>>> weeks
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdy', 'Friday', 'Saturday']
>>>

Question 19.
What are the types of error messages in Python?
Answer:
While working with Python you can come across:

1. Syntax-error
2. Run-time errors

Syntax errors are static errors that are encountered when the interpreter is reading the program. If there is any mistake in the code then the interpreter will display a syntax error message and the program will not be executed.
Run time errors as the name suggests are dynamic errors. They are detected while the program is executing. Such errors are bugs in the program that may require design change such as running out of memory, dividing a number by zero, and so on.

Question 20.
What are the advantages of Python’s IDLE environment?
Answer:
The Python IDLE environment has the following:

  • Python’s interactive mode
  • Tools for writing and running programs
  • It comes along with the text editors which can be used for working on scripts

Question 21.
What is a comment?
Answer:
A comment is one or more statements used to provide documentation or information about a piece of code in a program. In Python one-line comments start with ‘#’.

Question 22.
Is Python a case-sensitive programming language?
Answer:
Yes

General Python Concepts

Question 23.
How is Python executed?
Answer:
Python files are compiled to bytecode, which is then executed by the host.
Alternate Answer: Type python <sourcefile>.py at the command line.

Question 24.
What is the difference between .py and .pyc files?
Answer:
.py files are Python source files, .pyc files are the compiled bytecode files that are generated by the Python compiler

Question 25.
How do you invoke the Python interpreter for interactive use?
Answer:
python or pythonx.y where x.y is the version of the Python interpreter desired.

Question 26.
How are Python blocks defined?
Answer:
By indents or tabs. This is different from most other languages which use symbols to define blocks. Indents in Python are significant.

Question 27.
What is the Python interpreter prompt?
Answer:
Three greater-than signsQuestion>>> Also, when the interpreter is waiting for more input the prompt changes to three periods …

Question 28.
How do you execute a Python Script?
Answer:
From the command line, type python <scriptname>.py or pythonx.y <scriptname>.py where the x.y is the version of the Python interpreter desired.

Question 29.
Explain the use of tryQuestionexceptQuestionraise, and finally:
Answer:
Try, except and finally blocks are used in Python error handling. Code is executed in the try block until an error occurs. One can use a generic except block, which will receive control after all errors, or one can use specific exception handling blocks for various error types. Control is transferred to the appropriate except block. In all cases, the final block is executed. Raise may be used to raise your own exceptions.

Question 30.
Illustrate the proper use of Python error handling.
Answer:
Code Example
try:
… # This can he any code
except:
… # error handling code goes here
finally:
… # code that will be executed regardless of exception handling goes here.

Question 31.
What happens if an error occurs that is not handled in the except block?
Answer:
The program terminates, and an execution trace is sent to sys. stderr.

Question 32.
How are modules used in a Python program?
Answer:
Modules are brought in via the import statement.

Question 33.
How do you create a Python function?
Answer:
Functions are defined using the def statement. An example might be deffoo(bar):

Question 34.
How is a Python class created?
Answer:
Classes are created using the class statement. An example might be class aardvark(foobar):

Question 35.
How is a Python class instantiated?
Answer:
The class is instantiated by calling it directly. An example might be myclass=aardvark(5)

Question 36.
In a class definition, what do the init ( ) functions do?
Answer:
It overrides any initialization from an inherited class and is called when the class is instantiated.

Question 37.
How does a function return values?
Answer:
Functions return values using the return statement.

Question 38.
What happens when a function doesn’t have a return statement? Is this valid?
Answer:
Yes, this is valid. The function will then return a None object. The end of a function is defined by the block of code is executed (i.e., the indenting) not by any explicit keyword.

Question 39.
What is the lambda operator?
Answer:
The lambda operator is used to create anonymous functions. It is mostly used in cases where one wishes to pass functions as parameters or assign them to variable names.

Question 40.
Explain the difference between local and global namespaces.
Answer:
Local namespaces are created within a function when that function is called. Global namespaces are created when the program starts.

Question 41.
Name the four main types of namespaces in Python? Answer:

  • Global,
  • Local,
  • Module and
  • Class namespaces.

Question 42.
When would you use triple quotes as a delimiter? Answer:
Triple quotes ” ” ” or are string delimiters that can span multiple lines in Python. Triple quotes are usually used when spanning multiple lines, or enclosing a string that has a mix of single and double quotes contained therein.

Python Interview Questions on Introduction to Python Read More »