Sunday 8 November 2020

Class 12th sumita arora solutions || Chapter 1- Python Revision tour - 1 || Important Question

Q. Why is Python interpreted?

Answer =

Python is interpreted because the program is processed at runtime by the interpreter and we do not need to compile the program before executing it.

Q. Who developed Python?

Answer =

Python was developed by Guido van Rossum in the early nineties at the National Research Institute for Mathematics in the Netherlands.

Q. Is Python a compiler language or an interpreter language?

Answer =

The normal execution of Python program is interpreted. However, subsets of the language can be compiled.

Q. What is the difference between interactive mode and script mode in Python?

Answer =

The normal execution of Python program is interpreted. However, subsets of the language can be compiled.

Q. How are keywords different from identifiers?

Answer =

keywords have special meaning in python while identifier are define by user.

Q. Differentiate between mutable and immutable objects in Python language with example.

Answer =

Every variable in Python holds an instance of an object. There are two types of objects in Python, i.e.,
Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can't be changed afterwards.

However, its state can be changed if it is a mutable object.

For example, int, float, bool, string, unicode, tuple are immutable objects in Python. In simple words, an immutable object can't be changed after it is created. Lists, dictionaries and sets are mutable types.

Q. What are literals in Python? How many types of literals are allowed in Python?

Answer =

Literals mean constants i.e., the data items that never change their value during a program run. Python allows five types of literals:

(i) String literals
(ii) Numeric literals

(iii) Boolean literals
(iv) Special Literal None
(v) Literal Collections like tuples, lists etc.

Q. How many ways are there in Python to represent an integer literal?

Answer =

Python allows three types of integer literals:

(a) Decimal (base 10) integer literals

(b) Octal (base 8) integer literals
(c) Hexadecimal (base 16) integer literals

(a) Decimal Integer Literals:- An integer literal consisting of a sequence of digits is taken to be decimal integer literal unless it begins with 0 (digit zero).

For instance, 1234, 41, +97, -17 are decimal integer literals.

(b) Octal Integer Literals:- A sequence of digits starting with 0 (digit zero) is taken to be an octal integer.

For instance, decimal integer 8 will be written as 010 is octal integer. (810 = 108,) and decimal integer 12 will be written as 014 as octal integer (1210 = 148).

(c) Hexadecimal Integer Literals:- A sequence of digits preceded by 0x or 0X is taken to be an hexadecimal integer.

For instance, decimal 12 will be written as 0XC as hexadecimal integer.
Thus number 12 will be written either as 12 (as decimal), 014 (as octal) and 0XC (as hexadecimal).

Q. What are data types? What are Python's built-in core data types?

Answer =

The real life data is of many types. So to represent various types of real-life data, programming languages provide ways and facilities to handle these, which are known as data types.

Python's built-in core data types belong To:

(i) Numbers (integer, floating-point, complex numbers, Booleans)
(ii) String
(iii) List
(iv) Tuple
(v) Dictionary

Q. What is a statement ? What is the significance of an empty statement?

Answer =

A statement is an instruction given to the computer to perform any kind of action.

An empty statement is useful in situations where the code requires a statement but logic does not. To fill these two requirements simultaneously, empty statement is used.

Python offers pass statement as an empty statement.

Q. If you are asked to label the Python loops as determinable or non-determinable, which label would you give to which loop? Justify your answer.

Answer =

The 'for loop' can be labelled as determinable loop as number of its iterations can be determined beforehand as the size of the sequence, it is operating upon.

The 'while loop' can be labelled as non-determinable loop, as its number of iterations cannot be determined beforehand. Its iterations depend upon the result of a test-condition, which cannot be determined beforehand.

Q. There are two types of else clauses in Python. What are these two types of else clauses?

Answer =

The two types of Python else clauses are:

(a) else in an if statement :- The else clause of an if statement is executed when the condition of the if statement results into false.

(b) else in a loop statement :- The else clause of a loop is executed when the loop is terminating normally i.e., when its test-condition has gone false for a while loop or when the for loop has executed for the last value in sequence.

Q. What do you understand by the term Iteration?

Answer =

Iteration refers to repetition of a set of statements for a sequence of values or as long as a condition is true.

Q. What is indexing in context to Python strings? Why is it also called two-way indexing?

Answer =

In Python strings, each individual character is given a location number, called index and this process is called indexing. Python allocates indices in two directions:

* in forward direction, the indexes are numbered as 0, 1, 2 ... length-1.

* in backward direction, the indexes are numbered as -1, -2, -3.... length.

This is known as two-way indexing.

Q. What is a string slice? How is it useful?

Answer =

A sub-part or a slice of a string, say s, can be obtained using s [n : m] where n and m are integers.

Python returns all the characters at indices, n, n + 1, n + 2, n + 3 ….. m - 1 e.g.,

Well done' [1 : 4] will give ‘ell’

Q. Write a program that reads a string and checks whether it is a palindrome string or not.

Answer =

string = input("Enter a string :")
length = len(string)
mid = int(length / 2)
rev = -1
for a in range (mid) :
    if string[a] == string[rev] :
        a += 1
        rev -= 1
    else :
        print(string, "is not a palindrome")
else :
    print(string, "is a palindrome")

Q. How are lists different from strings when both are sequences?

Answer =

The lists and strings are different in following ways:

(i) The lists are mutable sequences while strings are immutable.
(ii) In consecutive locations, a string stores the individual characters while a list stores the references of its elements.
(iii) Strings store single type of elements - all characters while lists can store elements belonging to different types.

Q. Write the most appropriate list method to perform the following tasks.

(a) Delete a given element from the list.

(b) Delete 3rd element from the list.

(c)Add an element in the end of the list.

(d) Add an element in the beginning of the list.

(e) Add elements of a list in the end of a list.

Answer =

(a) remove

(b) pop()

(c) append()

(d) insert()

(e) extend()

Q. How are tuples different from lists when both are sequences?

Answer =

The tuples and lists are different in following ways:

* The tuples are immutable sequences while lists are mutable.
* Lists can grow or shrink while tuples cannot.

Q. When are dictionaries more useful than lists?

Answer =

Dictionaries can be much more useful than lists. For example, suppose we wanted to store all our friends' cell-phone numbers. We could create a list of pairs (name of friend, phone number), but once this list becomes long enough searching this list for a specific phone number will get time-consuming. Better would be if we could index the list by our friend's name. This is precisely what a dictionary does.

Q. Can sequence operations such as slicing and concatenation be applied to dictionaries? Why?

Answer =

No, sequence operations like slicing and concatenation cannot be applied on dictionaries. The reason being, a dictionary is not a sequence. Because it is not maintained in any specific order, operations that depend on a specific order cannot be used.

Q. Why can't Lists be used as keys?

Answer =

Lists cannot be used as keys in a dictionary because they are mutable. And a Python dictionary can have only keys of immutable types.

Q. How many types of strings are supported in Python?

Answer =

Python allows two string types:

1. Single line Strings: - Strings that are terminated in a single line.
2. Multi-line Strings: - Strings storing multiple lines of text.

Q. What is a tuple?

Answer = 

A tuple is an immutable sequence of values which can be of any type and are indexed by an integer.

Q. Differentiate between lists and tuples.

Answer =

Tuples cannot be changed unlike lists; tuples use parentheses, whereas lists use square brackets.

Q. What is a dictionary?

Answer =

A Python dictionary is a mapping of unique keys to values. It is a collection of key-value pairs. Dictionaries are mutable which means that they can be changed.

Q. Find errors, underline them and rewrite the same after correcting the following code:-

d1 = dict[]

i = 1

n = input ("Enter number of entries : ")

while i <= n :

    a = input ("Enter name:")

    b = input ("Enter age:")

    d1 (a) = b

    i = i + 1

l = d1.key []

for i in l :

    print (i, '\t', 'd1[ i ]')

Answer =

d1 = dict ()

i = 1

n = int (input ("Enter number of entries:"))

while i <= n :

    a = input ("Enter name:")

    b = int (input ("Enter age:"))

    d1[ a ] = b

    i = i + 1

l = d1.keys ()

for i in l :

    print(i, '\t', d1[i])

Q. Write a program to accept values from a user in a tuple. Add a tuple to it and display its elements one by one. Also display its maximum and minimum value.

Answer =

tup = eval(input("Enter a tuple :-"))

min = tup[0]
max = tup[0]
for i in range(len(tup)) :
    if max < tup[i] :
        max = tup[i]
    if min > tup[i]:
        min = tup[i]


Q. Write a Python program to count the number of characters (character frequency) in a string.

Sample String : “”

Expected Result: {'g': 2, 'o': 3, 1': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}

Answer =


def char_frequency (str1):
    dict = {}
    for n in str1 :
        keys = dict.keys ()
        if n in keys :
            dict[n] += 1
        else :
            dict[n] = 1
    return dict

print (char_frequency('Pathwala'))

Q. Write a program that reads a date as an integers in the format MMDDYYYY. The program will call a function that prints print out the date in the format <month name > <day>, <year>.

Answer = 


mon = ["january", "february","march" , "april", "may" , "june" , "july" , "august ", "september ", "october ", "november" , 'december '] 
a = int (input("enter the date  = " ))
month = a // 1000000
date = (a % 1000000) // 10000
year = a % 10000
print ( mon [ month - 1 ] , date ," , ", year )

Q. Write a program that reads two times in military format and prints the number of hours and minutes between the two times .

Answer =


first = int (input("please enter the first time = "))
sec = int (input ("please enter the second time  = " ))
a =  sec - first  
print (a // 100, "hours " , a % 100, "min")

Q. Write a Python program to capitalize first and last letters of each word of a given string.

Answer =


string = input("Enter a string :-")
new_str = string[0].upper()+string[1:-1]+string[-1].upper()

Q. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.

Sample String : 'restart'

Expected Result : 'resta$t'

Answer =

def change_char (str1) :
    char = str1[0]
    str1 = str1.replace (char, '$')
    str1 = char + str1 [1 : ]
    return str1

print (change_char ('restart'))

Q. Write a Python program to print the following floating numbers with no decimal places.

Answer =


x = 3.1415926
y = -12.9999
print ("\nOriginal Number : ", x)
print("Formatted Number with no decimal places : " + "{:.0f}".format (x));
print ("Original Number: ", y)
print("Formatted Number with no decimal places : " + "{:.0f}".format (y));
print ()

Q. Write a Python program to count and display the vowels of a given text.

Answer =


def vowel (text):
    vowels = "aeiouAEIOU"
    print (len ([letter for letter in text if letter in vowels]))
    print ([letter for letter in text if letter in vowels])

vowel ('Welcome')

Q. Write a Python program to find the second most repeated word in a given string.

Answer = 


string = input("Enter a string :-")
lst = string.split()
max = 0
for i in lst:
    if lst.count(i) > max :
        max = lst.count(i)
        maxvalue = i


Q. Write a Python program to remove duplicates from a list.

a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40]

Answer =


a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40]
dup_items = set ()
uniq_items = []
for x in a :
    if x not in dup_items :
        uniq_items.append (x)
        dup_items.add (x)
print (dup_items)

Q. Write a Python function that takes two lists and returns True if they have at least one common member.

Answer = 

def common_data (list1, list2) :
    result = False
    for x in list1 :
        for y in list2 :
            if x == y :
                result = True
    return result

print (common_data ([1, 2, 3, 4, 5], [5, 6, 7, 8, 9]))
print (common_data ([1, 2, 3, 4, 5], [6, 7, 8, 9]))

Q. Write a Python program to sort a dictionary by key.

Answer =

dic = eval(input("Enter dictionary :- "))
newdic = {}
lst = list(dic.keys())
for i in lst :
    newdic [ i ] = dic[ i ]


Q. Write a Python program to create a dictionary from two lists without losing duplicate values.

Sample data ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII'], [1, 2, 2, 3]

Expected Output: defaultdict(<class 'set'>, {'Class-V': {1}, 'Class-VI': {2}, 'Class-VII': {2}, 'Class-VIII': {3}})

Answer =


from collections import defaultdict
class_list = ['Class-V', 'Class-VI', 'Class-VII', 'Class-VIII']
id_list = [1, 2, 2, 3]
temp = defaultdict (set)
for c, i in zip(class_list, id_list) :
    temp[ c ].add ( i )

print (temp)

Q. Which of the following is valid arithmetic operator in Python:

(a) //

(b) ?

(c) <

(d) and

Answer =

(a) //

Q. What is an expression and a statement?

Answer =


Expression is a legal combination of symbol that represent a value.

Statement is an instruction that does something.

Q. Write a program to calculate the mean of a given list of numbers.

Answer =


lst = eval (input ("Enter the list of number : - "))
a = 0
b = 0
for i in lst :
    a = a + i
    b = b + 1
print ("Mean of the list is ", a / b)

Q. Write a program to sort a dictionary’s keys using bubble sort and produce the sorted keys as a list.

Answer =


dic = eval (input("Enter a dictionary : "))
key = list(dic.keys())

for i in range ( len ( key ) - 1 ) :
    if  key [ i ] > key [ i + 1 ] :
        key [ i ] , key [ i + 1 ] =  key [ i + 1 ] , key [ i ]

Q. Write a program to perform sorting on a given list of strings, on the basis of just the first letter of the strings. Ignore all other letters for sorting purposes.

Choose sorting algorithm of yourself.

Answer =


lst = eval(input("Enter a String list = "))
length = len(lst)
for i in range(1,length):
    temp = lst[i]
    j = i-1
    while j>=0 and temp[0] < lst[ j ][ 0 ]:
        lst[ j+1] = lst[j]
        j = j -1
    else :
        lst[ j+1] = temp


Q. Write a program that sort a list of tuple – elements in descending order of points using bubble sort. The tuple – element of the list contain following information about different players:

(player number , player name , points )

Answer =


lst = [(103 , 'ritika' , 3001),(104 ,'john',2819),(101,'razia',3451),(105,'tarandeep',2971)]
for i in range( len( lst ) - 1 ):
    for j in range( len ( lst ) - 1 ):
        if lst [ j ] [ 2 ] < lst [ j + 1 ] [ 2 ] :
            lst [ j ] , lst [ j + 1 ] = lst [ j + 1 ] , lst [ j ]

Credits to PATH WALA 

No comments:

Post a Comment