Python Tutorial

Week - 4:

  1. Write a function called is sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise.

 

Answer:

Method:-1

numbers=[1,3,4,2]                       # Sorting list of Integers in ascending                                                       print(numbers.sort())                #None

print(numbers)                             # [1, 2, 3, 4]

print(sorted(numbers))            #[1, 2,3,4]

print(numbers)                             # [1, 2,3,4]

Output:

None

[1, 2, 3, 4]

[1, 2, 3, 4]

[1, 2, 3, 4]

 

Explanation:

 

  1. Numbers is the variable which contains the values that are to be sorted.
  2. sort() method is used to sort the list elements in ascending order, but it won’t display the elements in the list . So none is the output that will be displayed.
  3. Sorted function is used to sort the numbers in ascending order. Numbers is the parameter that is passed to the function.
  4. So the numbers will be sorted and displayed.

 

Method:-2

t = [1, 11, 2, 20,3 ,40]                  #assigning the values

list= sorted(t)                                #sorting the values

print(list)                                        #displaying sorted elements

Output:

[1, 2,3,11,20,40]

 

Explanation:

 

  1. t is the list variable to which values are assigned.
  2. Sorted() is the method used to sort the elements in ascending order. t is passed as a parameter to the function.
  3. Sorted elements are placed in list variable.
  4. Sorted elements are displayed by using print(list).

Method:-3

a = ["k", "b", "a", "j", "f", "d", "h", "g"]              #assigning values

list= sorted(a)                                                        #sorting the elements

print(list)                                                                #displaying the values

Output:

['a', 'b', 'd', 'f', 'g', 'h', 'j', 'k']

 

Explanation:

 

  1. a is the list variable to which values are assigned.
  2. Sorted() is the method used to sort the elements in ascending order. a is parameter that is passed to the function.
  3. Sorted elements are placed in list variable.
  4. Sorted elements are displayed by using print(list).

 

 

Method:-4

a = ("k", "b", "a", "c", "f", "d", "h", "g")             #assigning values

list = sorted(a, reverse=True)    #sorting elements in descending order

print(list)                                           displaying the elements

Output:

['k', 'h', 'g', 'f', 'd', 'c', 'b', 'a']

 

Explanation:

 

  1. a is the list variable to which values are assigned.
  2. Sorted() is the method used to sort the elements in ascending order.
  3. Reverse=true implies that the elements are displayed in descending order.
  4. Sorted elements are placed in list variable.
  5. Sorted elements are displayed by using print(list).

 

 

Method:-5

set_var= {8, 9, 4, 6, 7}                  #assigning the values

list = sorted(set_var)                   #sorting the elements

print(list)                                        #displaying the elements

 

Output:

[4, 6, 7, 8, 9]

 

Explanation:

 

  1. Set_var is the variable which contains the list elements that are to be sorted.
  2. Sorted() is the method used to sort the elements in ascending order. set_var is parameter that is passed to the function.
  3. Sorted elements are placed in list variable.
  4. Sorted elements are displayed by using print(list).

 

Method:-6

dict_var= {'a': 2, 'b': 1, 'c': 3}

print("Original Dictionary: ", dict_var)

print("List returned from Sorted Method: ", sorted(dict_var))

Output:

Original Dictionary: {'a': 2, ‘b': 1, 'c': 3}

List returned from Sorted Method: ['a', 'b', 'c']

 

Explanation:

 

  1. dict_var is the variable which contains the dictionary elements that are to be sorted.
  2. ‘a’:2 denotes that ‘a’ is the key whose value is 2.
  3. Sorted() is the method used to sort the elements in ascending order. dict_var is parameter that is passed to the function.
  4. The sorting is done based on the values and the key values are displayed.

 

Method:-7

def is_sorted(my_list):                                        #defining the function

#checking whether my_list elements are same as sorted elements or not

   return my_list == sorted(my_list)              

my_list=input("Enter the list: ")                      #enter the integer values

#separate the elements by using separators

my_list = my_list.split()                         

print(is_sorted(my_list))

print("our list: ", my_list)

Output:

Enter the list: 10 20 30 40 50

True

our list:  ['10', '20', '30', '40', '50']

 

Enter the list: 10 20 30 50 60 40

False

our list:  ['10', '20', '30', '50', '60', '40']

 

Explanation:

 

  1. Is_sorted is the function used to determine whether elements given are in sorted list or not.
  2. If the elements are in sorted order then function would return true.
  3. Else function returns false.
  4. The list elements are stored in my_list
  5. Split() function is used to separate the elements of the list by using separators.
  6. The elements sorted in ascending order are displayed using print function.

 

Method:-8

string_var = "Maneesh"

print("Original String: ", string_var)

print("List returned from Sorted Method: ", sorted(string_var))

Output:

Original String:  Maneesh

List returned from Sorted Method:  ['M', 'a', 'e', 'e', 'h', 'n', 's']

 

Explanation:

 

  1. The string is stored in the variable string_var
  2. Sorted() is the method used to sort the elements in ascending order. string_var is parameter that is passed to the function.
  3. The sorted elements are displayed using print function.

 

Method:-9

list_var = [5, 4, 2, 1, 3]

print("Original list: ", list_var)

list_var.sort(reverse=False)

print("Sorted list in ascending order: ", list_var)

 

Output:

Original list:  [5, 4, 2, 1, 3]

Sorted list in ascending order:  [1, 2, 3, 4, 5]

 

Explanation:

 

  1. The elements of the list are stored in list_var
  2. Sort() is the method used to sort the elements in ascending order.
  3. As reverse=false the elements will be arranged in ascending order.
  4. If reverse=true the elements will be arranged in descending order.
  5. The sorted elements are displayed using print function.

 

  1. Write a function called has a duplicate that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.

Answer:

Method 1: Using set() function

 

class Solution:                                            #define class

    def duplicate(self, list1):                    #define the function

        new_value = set(list1)                     #eliminate duplicate values

#check the length of the new_value list with length of list1

        if len(new_value) == len(list1):  

            return 'false'  

        else:  

            return 'true'  

nums = [1, 2, 3, 1]                         #assign values to nums

obj = Solution()                             #create object of the class

#call the function and display the output

print(obj.duplicate(nums))     

Output:

True

 

Explanation:

 

  1. To create class we use class keyword.
  2. Solution is the class name.
  3. The duplicate() function is used to indicate duplicate Series values.
  4. Self contains same elements of list1.
  5. Set(list1) is used to eliminate duplicate values in list.
  6. Len() function is used to determine the length of the list that is passed as a argument.
  7. Nums is a variable name in which the values of the list are stored.
  8. Obj is the object of class solution.
  9. By comparing the lengths of the lists in which the duplicate values are eliminated (new_value) and list1 which may contain duplicate values we can determine whether duplicate values exist in the list.

 

 

Method 2: Check Duplicate Element after Sorting

class Solution:                    #creating the class solution

    def solution1(self, list1):  #defining the function solution1

        list1.sort()                          #sorting elements of list1

        for i in range(1, len(list1)):  #outer loop i

            for j in range(0, i):                #inner loop j

#comparing the elements with other elements in list1

                if list1[i] == list1[i-1]:    

                    return 'true'               

            return 'false'  

obj = Solution()     #object creation            

list1 = [1, 2, 3]        #assigning elements to the list

print(obj.solution1(list1)) #display the returned value from the function

Output:

False

 

Explanation:

 

  1. To create class we use class keyword.
  2. Solution is the class name.
  3. Solution1 is a function defined by using def keyword.
  4. Self is the keyword used to access the instance of the class. It is used to access variables, member functions of the class.
  5. sort() is used to arrange the elements of list in ascending order.
  6. Len() function is used to determine the length of the list that is passed as a argument.
  7. i and j are inner and outer loop variables through which we check for duplicate elements.
  8. Obj is the object of class solution.
  9. Through obj we access the solution1 method to sort the elements and check for duplicates.

 

 

Approach -3: Using Brute-force Method

class Solution:                                #declare the class

    def solution1(self, list1):        #define the method

        for i in range(len(list1)):    #outer loop

            for j in range(0, i):            #inner loop

                if list1[i] == list1[j]:      #check the elements

                    return 'true'  

        return 'false'  

obj = Solution()                             #create object for class           

list1 = [1, 2, 3, 4, 8, 2,8,7]           #create list

#access member function through  object of class  

print(obj.solution1(list1)) 

Output:

True

 

Explanation:

 

  1. This program generates same output as above by using brute-force technique.
  2. Solution is a class name.
  3. solution1 is a function used to detect the existence of duplicate elements.
  4. list1 is a variable used to assign list elements statically.
  5. obj is an object of Solution class through which the variables and member functions can be accessed.
  6. By using obj we access member function solution1().
  7. i and j are variables used for inner and outer loops.
  8. The value of the list is compared with other elements in the same list.
  9. If there are duplicates true value will be displayed or else false will be displayed.

 

  1. Write a function called remove duplicates that takes a list and returns a new list with only the unique elements from the original. Hint: they don’t have to be in the same order.

Answer:

 Method:-1

def Remove(duplicate):

    my_list = []                                  #creating empty list variable

    for num in duplicate:               #loop to check duplicate values

        if num not in my_list:           #condition check

           my_list.append(num)       #adding elements to my_list

    return my_list                            #returning the values of my_list

    

# Driver Code

duplicate = [2, 4, 10, 20, 5, 2, 20, 4]   #assigning static values

print(Remove(duplicate))                     #calling the function

Output:

[2,4,10,20,5]

 

Explanation:

 

  1. This is a program used to remove duplicate elements from the list.
  2. Here the elements are assigned statically to duplicate list variable.
  3. Remove(duplicate) is a method with list variable as a parameter.
  4. My_list is a list variable which contains elements after removing duplicate values.
  5. For each value we check the elements in my_list with the duplicate list values.
  6. If they are same then the value is not placed in the my_list variable.
  7. If they are not identical then the value will be moved to the my_list variable.
  8. Then the my_list elements will be displayed.

 

 

Method:-2 Using Counter () function

from collections import Counter                     #import libraries

# Driver Code

duplicate = [2, 4, 10, 20, 5, 2, 20, 4]               #declare list variable

unique = Counter(duplicate)                            #check for duplicates

print(list(unique.keys()))                                 #display the keys

Output:

[2,4,10,20,5]

 

Explanation:

 

  1. This program performs the same operation as above but it uses counter library.
  2. Counter is an unordered collection where elements are stored as dict

keys and their count as dict value.  

  1. duplicate is a list variable which is assigned with values statically.
  2. Unique is a dictionary variable which contains the key and the value.
  3. Value will determine the number of occurrences of the key.
  4. The keys are displayed by using print function.                                                                                             

 

Method:-3 Using operator.countOf() method

import operator as op

# Python code to remove duplicate elements

 

def Remove(duplicate):              #define the method remove

    final_list = []                                #create empty list

    for num in duplicate:               #outer loop

        if op.countOf(final_list, num) == 0:         #compare the elements

            final_list.append(num)               #add the elements to final_list

    return final_list

 

# Driver Code

duplicate = [2, 4, 10, 20, 5, 2, 20, 4]   #assign the values to list

#call the function and display the value

print(Remove(duplicate))        

Output:

[2,4,10,20,5]

 

Explanation:

 

  1. This is a program used to remove duplicate elements from the list.
  2. Here the elements are assigned statically to duplicate list variable.
  3. Remove(duplicate) is a method with list variable as a parameter.
  4. final_list is a list variable which contains elements after removing duplicate values.
  5. The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python.
  6. By using operator module we can perform mathematical, logical, arithmetic operations.
  7. op is an object of operator library through which we can access functions of operator.
  8. By using op we use Countof() method to determine the number of occurrences of each element.
  9. For each value we check the elements in final_list with the duplicate list values.
  10. If they are same then the value is not placed in the final_list variable.
  11. If they are not identical then the value will be moved to the final_list variable.
  12. Then the final_list elements will be displayed.

 

 

Method:-4 Using dict.fromkeys()

 

input_list = {1, 2, 3, 2, 6, 3, 5, 3, 7, 8}

mylist = list(dict.fromkeys(input_list))

print(mylist)

def unique_list(l):

  x = []

  for a in l:

    if a not in x:

      x.append(a)

  return x

print(unique_list({1,2,3,3,3,3,4,5}))

Output:

[1, 2, 3, 5, 6, 7, 8]

[1, 2, 3, 4, 5]

 

 

 

Explanation:

 

  1. This program provide same output as above by using dict.fromkeys() method.
  2. input_list is a list variable to which values are assigned statically.
  3. fromkeys() is a method which gives dictionary values with keys and its values.
  4. Non duplicate elements will be displayed through mylist variable.
  5. unique_list is a function with list variable as a parameter.
  6. x is a list variable.
  7. For each element a in list l we check whether the element is present in x.
  8. If the element exists it is not appended to x else the element is appended to list x.
  9. The values are finally displayed by using return statement.

 

  1. Write a python code to read dictionary values from the user. Construct a function to invert its content. i.e., keys should be values and values should be keys.

Answer:

Method:-1

dict = {'a': 1, 'b': 2, 'c': 3}             #declare the dictionary values

print(dict['b'])

#exchange the dictionary values keys to values and values to keys

dict = {value:key for key, value in dict.items()}

#dict = {'a': 1, 'b': 2, 'c': 3}

print(dict)

#exchange the dictionary values keys to values and values to keys

dict = {value:key for key, value in dict.items()}

print(dict)

 Output:

2

{1: 'a', 2: 'b', 3: 'c'}

{'a': 1, 'b': 2, 'c': 3}

 

Explanation:

 

  1. This program will display the dictionary elements in reverse order

which means that the keys should be values and values should be keys.

  1. dict is a dictionary variable which contains the key and its values.
  2. {value:key for key, value in dict.items()} will interchange the values and keys in dictionary.

Method:-2

# swap of key and value

# initializing dictionary

old_dict = {'Joe': 67, 'Bee': 23, 'Jhon': 45, 'Don': 56, 'Eich': 12,    

'Rohan': 69, 'Mana': 67, 'Hunter': 23}

new_dict = dict([(value, key) for key, value in old_dict.items()])

# Printing original dictionary

print ("Original dictionary is : ")

print(old_dict)

print()

 # Printing new dictionary after swapping keys and values

print ("Dictionary after swapping is :  ")

print("keys: values")

for i in new_dict:

    print(i, " :  ", new_dict[i])

Output:

Original dictionary is :

{'Joe': 67, 'Bee': 23, 'Jhon': 45, 'Don': 56, 'Eich': 12, 'Rohan': 69,

'Mana': 67, 'Hunter': 23}

Dictionary after swapping is : 

keys: values

67  :   Mana

23  :   Hunter

45  :   Jhon

56  :   Don

12  :   Eich

69  :   Rohan

 

Explanation:

 

  1. This program is used to interchange the keys to values and values to key.
  2. old_dict is a dictionary variable.
  3. new_dict is a dictionary variable which contains the values after exchanging the key and values.
  4. i is a looping variable.
  5. For each i value the value and the key of the value will be displayed.

 

  1. Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e'

Answer:

Split function

my_string = “Welcome to Python”

my_string.split()

Method:-1

myStr="Apple"                              #mystr is a string variable.

print("The input string is:",myStr)

#convert string to characters

Str=character for character in myStr

print("The output is:",Str)

Output:

 The input string is: Apple

The output is: ['A', 'p', 'p', 'l', 'e']

 

Explanation:

 

  1. myStr is a variable which is assigned with string.
  2. Str is a variable which contains characters of myStr.
  3. The characters are displayed using print statement.

 

 

 

Method:-2

 

myStr="Apple"                              #assign value to string variable

print("The input string is:",myStr)

str=list(myStr)                              #convert string to list

print("The output is:",str)

Output:

 The input string is: Apple

The output is: ['A', 'p', 'p', 'l', 'e']

 

Explanation:

 

  1. myStr is a variable which is assigned with string.
  2. str is a list variable.
  3. list(myStr) will convert the string into list elements.
  4. The characters are displayed using print statement.

 

  1. Remove the given word in all the places in a string?

Answer:

print("Enter the String: ")

text = input()                      #assign string  dynamically to text

print("Enter a Word to Delete: ")

word = input()                   #assigning word to delete from string

text = text.replace(word, "")     #replacing word with “ “

print()

print(text)                           #display text after removing word

 

Output:

Enter the String:

hi to cse-B welcome to mrit and happy to here

Enter a Word to Delete:

here

hi to cse-B welcome to mrit and happy to

 

Explanation:

 

  1. This is a program used to remove a word from the given string.
  2. Text is the variable used to assign string .
  3. To assign the string dynamically to the variable text we use input() function.
  4. The word to be deleted is assigned to variable word.
  5. Replace() method is used to replace one word with another.
  6. replace(word, "") this statement is used to replace the word with an empty space .
  7. the modified string is stored in text variable.
  8. The modified string is then displayed as output.

 

  1. Write a function that takes a sentence as an input parameter and replaces the first letter of every word with the corresponding upper case letter and the rest of the letters in the word by corresponding letters in lower case without using a built-in function?

Answer:

def convert_first_char_to_uppercase(sentence):

    return ' '.join(word.capitalize() for word in sentence.split())

 

# Testing the function

sentences = ['hello world', 'good morning', 'how are you']

for sentence in sentences:

    print(f"Original: {sentence}")

    print(f"Converted: {convert_first_char_to_uppercase(sentence)}")

Output:

Original: hello world

Converted: Hello World

Original: good morning

Converted: Good Morning

Original: how are you

Converted: How Are You

 

Explanation:

 

  1. This is a program to convert starting letter of each word from lower case to upper case.
  2. convert_first_char_to_uppercase() is a method used to convert the starting letter of each word from lower case to upper case.
  3. split() is used to split the sentence into words.
  4. capitalize() is used to convert the starting character of word into upper case character.
  5. join is used to join the words into sentence.
  6. For each sentence given in sentences it will display original string as well as converted string.

 

 

  1. Writes a recursive function that generates all binary strings of n-bit length

Answer:

 

Method-1 

def printTheArray(arr, n):

    for i in range(0, n):

        print(arr[i], end = " ")

    print()

 

# Function to generate all binary strings

def generateAllBinaryStrings(n, arr, i):

 

    if i == n:

        printTheArray(arr, n)

        return

    

    # First assign "0" at ith position

    # and try for all other permutations

    # for remaining positions

    arr[i] = 0

    generateAllBinaryStrings(n, arr, i + 1)

 

    # And then assign "1" at ith position

    # and try for all other permutations

    # for remaining positions

    arr[i] = 1

    generateAllBinaryStrings(n, arr, i + 1)

 

# Driver Code

if __name__ == "__main__":

 

    n = 3

    arr = [None] * n

 

    # Print all binary strings

    generateAllBinaryStrings(n, arr, 0)

Output:

0 0 0

0 0 1

0 1 0

0 1 1

1 0 0

1 0 1

1 1 0

1 1 1

 

 

 

 

Explanation:

 

  1. printTheArray(arr,n) is a function that is used to display binary values.
  2. i is a variable used to run the loop.
  3. generateAllBinaryStrings() is a method used to generate all binary numbers of length n.
  4. n is a variable used to determine the binary length.
  5. Initially ith position is assigned with 0 and all the remaining permutations are assigned to it.
  6. Later ith position is assigned with 1 and all the remaining permutations are assigned to it.