##1. Level description Level 1 Beginner: Beginner means someone who has just gone through an introductory Python course. He/She can solve some problems with 1 or 2 Python classes or functions. Normally, the answers could directly be found in the textbooks.

Level 2 Intermediate: Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He/She should be able to solve problems which may involve 3 or 3 Python classes or functions. The answers cannot be directly be found in the textbooks.

Level 3 Advanced: He/She should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He/She is supposed to solve the problem using several Python standard packages and advanced techniques.

Question:1 Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.

value=[]
for i in range(2000, 3200):
    if (i%7==0) and (i%5!=0):
        value.append(str(i))

print(",".join(value))

Question2

Write a program which can compute the factorial of a given numbers. The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320

def fact(z):
    if z == 0:
        return 1
    else:
        return z * fact(z - 1)

z=int(input('ENTER INPUT: '))
print(fact(z))

Question 3

With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

n=int(input('enter input: ' ))
d=dict()
for i in range(1,n+1):
    d[i]=i*i

print(d)

Question 4

Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: [‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’] (‘34’, ‘67’, ‘55’, ‘33’, ‘12’, ‘98’)## Question 4

multiplevalues=input("enter values: ")
multiplevalues.split(",")
tup=tuple(multiplevalues.split(","))
print(tup)

Question 5

Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods.

getstrings=input()
printstings=getstrings.upper()
print(printstrings)

Question 6

Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Example Let us assume the following comma separated input sequence is given to the program: 100,150,180 The output of the program should be: 18,22,24

C=50
H=30
import numpy as np
D =input()
sq=(2*C*D)
np.sqrt(sq/H)

Question 7

Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Note: i=0,1.., X-1; j=0,1,¡­Y-1. Example Suppose the following inputs are given to the program: 3,5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]

userInput = input("Enter values for row and column number:\t").split(",")
rownumbers=dimensions[0]
colnumbers=dimensions[1]
list = [[0 for col in range(colnumbers)] for row in range(rownumbers)]

for row in range(rownumbers):
    for col in range(colnumbers):
        list[row][col]= row*col

print(list)

Question 8

Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically. Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world

phrase = input(("Input words: ").split(","))
phrase_list.sort()
print((', ').join(phrase_list))

Question 9

Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT

lines = []
while True:
    l = input()
    if l:
        lines.append(l.upper())
    else:
        break;

for l in lines:
    print(l)
 

Question 10

Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world

Mwords= input()
words = [word for word in Mwords.split(" ")]
print(" ".join(sorted(list(set(words)))))

Question 11

Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 Then the output should be: 1010 Notes: Assume the data is input by console.

items_list = []
num = [x for x in input().split(',')]
for p in num:
    x = int(p, 2)
    if not x%5:
        items_list.append(p)
print(','.join(items_list))

Question 12

`Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line.

numbers = []
for x in range (1001, 3001):
    num_Split = [int(d) for d in str(x)]
    odd = False
    for y in range (0, len(num_Split)):
        if num_Split[y] % 2 != 0:
            odd = True
    if (odd == False):
        numbers.append(x)
print (numbers)

Question 13

Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3

phrase = input("Type in: ")
phrase = list(phrase)

l, d = 0, 0
for i in phrase:
    if i.isalpha():
        l = l + 1
    if i.isdigit():
        d = d + 1
    else:
        pass

print("Letters:", l)
print("Digits:", d)

Question 14

Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. Suppose the following input is supplied to the program: Hello world! Then, the output should be: UPPER CASE 1 LOWER CASE 9

def up_low(s):      
    u = sum(1 for i in s if i.isupper())
    l = sum(1 for i in s if i.islower())
    print( "No. of Upper : %s,No. of Lower : %s" % (u,l))

up_low("Hello world!")

Question 15

Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106

a = input()
v1 = int( "%s" % a )
v2 = int( "%s%s" % (a,a) )
v3 = int( "%s%s%s" % (a,a,a) )
v4 = int( "%s%s%s%s" % (a,a,a,a) )
print(v1+v2+v3+v4)

Question 16

Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,3,5,7,9

nums = input()
numbers = [v for v in values.split(",") if int(v)%2!=0]
print(",".join(numbers))

Question 17

Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: D 100 W 200

D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output should be: 500

netbal = 0
while True:
    en= input()
    if not en:
        break
    values = en.split(" ")
    operation = values[0]
    amount = int(values[1])
    if operation=="D":
        netbal+=amount
    elif operation=="W":
        netbal-=amount
    else:
        pass
print(netbal)

Question 18

A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password: 1. At least 1 letter between [a-z] 2. At least 1 number between [0-9] 1. At least 1 letter between [A-Z] 3. At least 1 character from [$#@] 4. Minimum length of transaction password: 6 5. Maximum length of transaction password: 12 Your program should accept a sequence of comma separated passwords and will check them according to the above criteria. Passwords that match the criteria are to be printed, each separated by a comma. Example If the following passwords are given as input to the program: ,a F1#,2w3E*,2We3345 Then, the output of the program should be:

user_input = input()
passwords = user_input.split(",")
special_chars = ["$","#","@"]
valid = []

for x in passwords:
    #check length
    if(len(x) > 12 or len(x) < 6):
        continue

    #check if has both uppercase and lower
    if (x.isupper() or x.islower()): 
        continue
    
    #check numbers
    has_number = any(char.isdigit() for char in x)
    if(not has_number):
        continue
    
    #check if has special character
    has_char = any(char in special_chars for char in x)
    if(not has_char):
        continue

    #only reached if all checks are passed
    valid.append(x)
print(valid)

Question 19

You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. The tuples are input by console. The sort criteria is: 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score. The priority is that name > age > score. If the following tuples are given as input to the program: Tom,19,80 John,20,90 Jony,17,91 Jony,17,93 Json,21,85 Then, the output of the program should be: [(‘John’, ‘20’, ‘90’), (‘Jony’, ‘17’, ‘91’), (‘Jony’, ‘17’, ‘93’), (‘Json’, ‘21’, ‘85’), (‘Tom’, ‘19’, ‘80’)]

info = input()
info_list = [case.split(',') for case in info.split(' ')] 
print(sorted(info_list))

Question 20

Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.

def generator(n):
    list_of = range(1,n+1)
    for i in list_of:
        if i % 7 == 0:
             yield i
print (list(generator(150)))

Question 21

A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 ¡­ The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program: UP 5 DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2

import math
postions = [0,0]
while True:
    s = input()
    if not s:
        break
    movement = s.split(" ")
    direction = movement[0]
    steps = int(movement[1])
    if direction=="UP":
        postions[0]+=steps
    elif direction=="DOWN":
        positions[0]-=steps
    elif direction=="LEFT":
        positions[1]-=steps
    elif direction=="RIGHT":
        positions[1]+=steps
    else:
        pass

print(int(round(math.sqrt(positions[1]**2+pos[0]**2))))

Question 22

Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically. Suppose the following input is supplied to the program: New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3. Then, the output should be: 2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1

def frequency(input):
    freq = {}

    for word in input.split():
        freq[word] = freq.get(word, 0) + 1

    words = list(freq.keys())
    words.sort()

    for w in words:
        print(f'{w}:{freq[w]}')

Question 23

Write a method which can calculate square value of number

def square(number):
    return number ** 2

print(square(8))

Question 24

Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions.

Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()

And add document for your own function

print(abs.__doc__)
print(int.__doc__)
print(input.__doc__)

def square(num):
    '''Return the square value of the input number.
    
    The input number must be integer.
    '''
    return num ** 2

print(square(2))
print(square.__doc__)

Question 25

Define a class, which have a class parameter and have a same instance parameter.

class Robot:
    Three_Laws = (
"""A robot may not injure a human being.""",
"""A robot must obey the orders given to it by human beings,except if it conflicts with the first one""",
"""A robot must protect its own existence ."""
)
    def __init__(self, name, build_year):
        self.name = name
        self.build_year = build_year
from robot_asimov import Robot
for number, text in enumerate(Robot.Three_Laws):
    print(str(number+1) + ":\n" + text) 
    

Question 26:

Define a function with two numbers as arguments. You can compute the sum in the function and return the value.

def total(a,b):
   result=a+b
   print(" Sum of ",a,"and"," sun of ",b,result )  
a= int(input("Enter first number:"))
b= int(input("Enter second number:"))
total(a,b)#funtion call the 2 integer

Question 27

Define a function that can convert a integer into a string and print it in console.

 number = 9960
number_as_string = str(number)
number_as_string

Question 28

Define a function that can convert an integer into a string and print it in console.

 number = 9960
number_as_string = str(number)
number_as_string

Question 29

Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.

a, b = map(int, input('enter two numbers\n').split())
c = a + b
print('{0} + {1} = {2}'.format(a, b, c))

Question 30

Define a function that can accept two strings as input and concatenate them and then print it in console.

def printstr(s1,s2):
    print(s1+s2)

printstr("67","99")

Question 31

Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print all strings line by line.

def printVal(s1,s2):
    length1 = len(s1)
    length2 = len(s2)
    if length1>length2:
        print(s1)
    elif length2>length1:
        print(s2)
    else:
        print(s1)
        print(s2)
        
printVal("two","three")

Question 32

Define a function that can accept an integer number as input and print the “It is an even number” if the number is even, otherwise print “It is an odd number”.

print ("Enter an integer number to check:\n")

x = int (input ())

if (x % 2 == 0):
    print ("The number is even.\n")
else:
    print ("The number is odd.\n")

Question 33

Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys.

def generate_dict(number):
    return {i:i**2 for i in range(1,number+1)}

print(generate_dict(3))

Question 34

Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.

def generate_dict(number):
    return {i:i**2 for i in range(1,number+1)}

print(generate_dict(20))

Question 35

Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only.

def printdictionary():
    dicttionary=dict()
    for i in range(1,21):
        dictionary[i]=i**2
    for (x,y) in dictionary.items():    
        print(x,y)

printdictionary()

Question 36

Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.

sq = dict(enumerate([i ** 2 for i in range(1, 21)], 1)) 
for _, val in sq.items(): 
    print(val)

Question 37

Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).

def printValues():
    l = list()
    for i in range(1,21):
        l.append(i**2)
    print(l)

printValues()

Question 38

Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.

def printValues():
    l = list()
    for i in range(1,21):
        l.append(i**2)
    print(l[:5])

printValues()

Question 39

Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.

def printValues():
    l = list()
    for i in range(1,21):
        l.append(i**2)
    print(l[-5:])

printValues()

Question 40

Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.

def printValues():
    l = list()
    for i in range(1,21):
        l.append(i**2)
    print l[5:]

printValues()

Question 41

Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).

def printValues():
    l = list()
    for i in range(1,21):
        l.append(i**2)
    print(l)
        
printValues()

Question 42

With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.

tup=(1,2,3,4,5,6,7,8,9,10)

tup1=tup[:5]

tup2=tup[5:]

print(tup1)

print(tup2)

Question 43

Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).

evenTuple = (1,2,3,4,5,6,7,8,9,10)
print("Tuple Items = ", evenTuple)
for i in range(len(evenTuple)):
    if(evenTuple[i] % 2 == 0):
        print(evenTuple[i], end = "  ")

Question 44

Write a program which accepts a string as input to print “Yes” if the string is “yes” or “YES” or “Yes”, otherwise print “No”.

tup=(1,2,3,4,5,6,7,8,9,10)
l=list()
for l in tup:
    if tp[i]%2==0:
        l.append(tup[i])

tup2=tuple(l)
print(tup2)

Question 45

Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].

li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print(evenNumbers)

Question 46

Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].

def square(x):
        return x*x

numbers = [1,2,3,4,5,6]
squares = map(square, numbers)

print(str(squares)) 

Question 47

Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].

li = [1,2,3,4,5,6,7,8,9,10]
evennums = map(lambda x: x**2, filter(lambda x: x%2==0, li))
print(evennums)

Question 48

Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).

evennums = filter(lambda x: x%2==0, range(1,21))
print(evennums)

Question 49

Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).


squarednums = filter(lambda x: x**2, range(1,21))
print(squarednums)

Question 50

Define a class named American which has a static method called printNationality.

class American(object):
    @staticmethod
    def printNationality():
        print("America")

anAmerican = American()
anAmerican.printNationality()
American.printNationality()

Question 51

Define a class named American and its subclass NewYorker.

class American:
    pass

class NewYorker(American):
    pass

american = American()
newyorker = NewYorker()

print(american)
print(newyorker)

Question 52

Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.

class Circle:
    def __init__(self,radius):
        self.radius = radius
    def area(self):
        return (self.radius**2*3.14)
circle = Circle(5)
print(circle.area())

Question 53

Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.

class Rectangle():
    def __init__(self,l,w):
        self.length = l
        self.width = w

    def area(self):
        return self.length*self.width


rect = Rectangle(2,4)
print(rect.area())

Question 54

Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape’s area is 0 by default.

class Shape():
    def __init__(self):
        pass

    def area(self):
        return 0

class Square(Shape):
    def __init__(self,length = 0):
        Shape.__init__(self)
        self.length = length

    def area(self):
        return self.length*self.length
    
Asqr = Square(5)
print(Asqr.area())      

print(Square().area())

Question 55

Please raise a RuntimeError exception.

raise RuntimeError('something wrong')

Question 56

Write a function to compute 5/0 and use try/except to catch the exceptions.

def divide():
    return 5/0

try:
    divide()
except ZeroDivisionError as ze:
    print("Why are you dividing by ZERO!!")
except:
    print("Any other exceptions")

Question 57

Define a custom exception class which takes a string message as attribute.


class CustomException(Exception):
    """Exception raised for custom purpose

    Attributes:
        message -- explanation of the error
    """

    def __init__(self, message):
        self.message = message


num = int(input())

try:
    if num < 10:
        raise CustomException("Input is less than 10")
    elif num > 10:
        raise CustomException("Input is grater than 10")
except CustomException as ce:
    print("The error raised: " + ce.message)

``

### Question 58
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.

Example:
If the following email address is given as input to the program:

john@google.com

Then, the output of the program should be:

john

In case of input data being supplied to the question, it should be assumed to be a console input.
``
email = "john@google.com"
email = email.split('@')
print(email[0])

Question 59

Assuming that we have some email addresses in the “” format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only.

Example: If the following email address is given as input to the program:

Then, the output of the program should be:

google

In case of input data being supplied to the question, it should be assumed to be a console input.

import re

email = "john@google.com rilty@gmail.com"
pattern = "\w+@(\w+).com"
ans = re.findall(pattern,email)
print(ans)

Question 60

Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.

Example: If the following words is given as input to the program:

2 cats and 3 dogs.

Then, the output of the program should be:

[‘2’, ‘3’]

In case of input data being supplied to the question, it should be assumed to be a console input.

import re

email = input()
pattern = "\d+"
ans = re.findall(pattern,email)
print(ans)

Question 61

Print a unicode string “hello world”.

print(u'Hello world!')

Question 62

Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.

v = input()
f= v.encode('utf-8')
print(f)

Question 63

Write a special comment to indicate a Python source code file is in unicode.

# -*- coding: utf-8 -*-

Question 64

Write a program to compute 1/2+2/3+3/4+…+n/n+1 with a given n input by console (n>0).

Example: If the following n is given as input to the program:

5

Then, the output of the program should be:

3.55

In case of input data being supplied to the question, it should be assumed to be a console input.

n = int(input())
sum = 0
for i in range(1, n+1):
    sum+= i/(i+1)
print(round(sum, 2)) 

Question 65

Write a program to compute:

f(n)=f(n-1)+100 when n>0 and f(0)=1

with a given n input by console (n>0).

Example: If the following n is given as input to the program:

5

Then, the output of the program should be:

500

In case of input data being supplied to the question, it should be assumed to be a console input.

def f(n):
    if n == 0:
        return 0
    return f(n-1) + 100

n = int(input())
print(f(n))

Question 66

The Fibonacci Sequence is computed based on the following formula:

f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1

Please write a program to compute the value of f(n) with a given n input by console.

Example: If the following n is given as input to the program:

7

Then, the output of the program should be:

13

In case of input data being supplied to the question, it should be assumed to be a console input.

def f(n):
    if n < 2:
        return n
    return f(n-1) + f(n-2)

n = int(input())
print(f(n))

Question 67

The Fibonacci Sequence is computed based on the following formula:

f(n)=0 if n=0 f(n)=1 if n=1 f(n)=f(n-1)+f(n-2) if n>1

Please write a program using list comprehension to print the Fibonacci Sequence in comma separated form with a given n input by console.

Example: If the following n is given as input to the program:

7

Then, the output of the program should be:

0,1,1,2,3,5,8,13

n = int(input())
f = lambda x: 0 if x == 0 else 1 if x == 1 else f(x-1)+f(x-2)
print(','.join([str(f(x)) for x in range(0, n+1)]))

Question 68

Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.

Example: If the following n is given as input to the program:

10

Then, the output of the program should be:

0,2,4,6,8,10

n = int(input())

for i in range(0, n+1, 2):
  if i < n - 1:
    print(i, end = ',' )
  else:
    print(i)

Question 69

Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.

Example: If the following n is given as input to the program:

100

Then, the output of the program should be:

0,35,70

def generate(n):
    for i in range(n+1):
        if i % 35 == 0:    # 5*7 = 35, if a number is divisible by a & b then it is also divisible by a*b
            yield i

n = int(input())
resp = [str(i) for i in generate(n)]
print(",".join(resp))

Question 70

Please write assert statements to verify that every number in the list [2,4,6,8] is even.

nums = [2,4,6,8]
for i in nums:
    assert i%2 == 0

Question 71

Please write a program which accepts basic mathematic expression from console and print the evaluation result.

Example: If the following string is given as input to the program:

35+3

Then, the output of the program should be:

38

expression = input()
ans = eval(expression)
print(ans)

Question 72

Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.

def binary_search(lst, item):
    low = 0
    high = len(lst) - 1
    
    while low <= high:
        mid = round((low + high) / 2)
        
        if lst[mid] == item:
            return mid
        elif lst[mid] > item:
            high = mid - 1
        else:
            low = mid + 1
    return None
    
lst = [1,3,5,7,]
print(binary_search(lst, 9))   

Question 73

Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.

def binary_search(lst, item):
    low = 0
    high = len(lst) - 1
    
    while low <= high:
        mid = round((low + high) / 2)
        
        if lst[mid] == item:
            return mid
        elif lst[mid] > item:
            high = mid - 1
        else:
            low = mid + 1
    return None
    
lst = [1,3,5,7,]
print(binary_search(lst, 9))   

Question 74

Please generate a random float where the value is between 10 and 100 using Python math module.

import random
print(random.random()*100)

Question 75

Please generate a random float where the value is between 5 and 95 using Python math module.

import random
print (random.random()*100-5)

Question 76

Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.

import random
resp = [i for i in range(0,11,2)]
print(random.choice(resp))

Question 77

Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension.

import random
resp = [i for i in range(10,151) if i % 35 == 0 ]
print(random.choice(resp))

Question 78

Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.

import random
ran= random.sample(range(100,201),5)
print(ran)

Question 79

Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.

import random
ran = random.sample(range(100,201,2),5)
print(ran)

Question 80

Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.

import random
lst = [i for i in range(1,1001) if i%35 == 0]
ran = random.sample(lst,5)
print(ran)

Question 81

Please write a program to randomly print a integer number between 7 and 15 inclusive.

import random
print(random.randrange(7,16))

Question 82

Please write a program to compress and decompress the string “hello world!hello world!hello world!hello world!”.

s = 'hello world!hello world!hello world!hello world!'
y = bytes(s, 'utf-8')
x = zlib.compress(y)
print(x)      ##in python zlib() compresses accepyts only bytes data types
print(zlib.decompress(x))

Question 83

Please write a program to print the running time of execution of “1+1” for 100 times.

import time

before = time.time()
for i in range(100):
    x = 1 + 1
after = time.time()
execution_time = after - before
print(execution_time)

Question 84

Please write a program to shuffle and print the list [3,6,7,8].

from random import shuffle
nums = [3,6,7,8]
shuffle(nums)
print(nums)

Question 85

Please write a program to shuffle and print the list [3,6,7,8].

from random import shuffle
nums = [3,6,7,8]
shuffle(nums)
print(nums)

Question 86

Please write a program to generate all sentences where subject is in [“I”, “You”] and verb is in [“Play”, “Love”] and the object is in [“Hockey”,“Football”].

import itertools
subject = ["I", "You"]
verb = ["Play", "Love"]
objects = ["Hockey","Football"]

sentence = [subject, verb, objects]
n = list(itertools.product(*sentence))
for i in n: 
    print(i)

Question 87

Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].

nums = [5,6,77,45,22,12,24]
nums = list(filter(lambda n:n%2!=0,nums))
print(nums)

Question 88

By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].

lst = [12,24,35,70,88,120,155]
lst = [x for x in li if x % 35!=0]
print(lst)

Question 89

By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].

lst = [12,24,35,70,88,120,155]
lst = [lst[i] for i in range(len(lst)) if i%2 != 0 and i <= 6]
print(lst)

Question 90

By using list comprehension, please write a program generate a 358 3D array whose each element is 0.

lst = [12,24,35,70,88,120,155]
print([i for i in lst if lst.index(i) not in range(2,5)])

Question 91

By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155].

lst = [12, 24, 35, 70, 88, 120, 155]
print(list(j for i, j in enumerate(lst) if i != 0 and i != 4 and i != 5))

Question 92

By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].

lst = [12,24,35,24,88,120,155]
lst.remove(24)  # this will remove only the first occurrence of 24
print(lst)

Question 93

With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.

list1 = [1,3,6,78,35,55]
list2 = [12,24,35,24,88,120,155]
set1= set(list1)
set2= set(list2)
intersection = set.intersection(set1,set2)
print(intersection)

Question 94

With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.

lst= [12,24,35,24,88,120,155,88,120,155]
for i in lst:
    if lst.count(i) > 1:
        lst.remove(i)
print(lst)

Question 95

Define a class Person and its two child classes: Male and Female. All classes have a method “getGender” which can print “Male” for Male class and “Female” for Female class.

class Person(object):
    def __init__(self):
    self.gender = "unknown"

    def getGender(self):
    print(self.gender)

class Male(Person):
    def __init__(self):
    self.gender = "Male"

class Female(Person):
    def __init__(self):
    self.gender = "Female"

sharon = Female()
doug = Male()
sharon.getGender()
doug.getGender()

Question 96

Please write a program which count and print the numbers of each character in a string input by console.

Example: If the following string is given as input to the program:

abcdefgabc

Then, the output of the program should be:

a,2 c,2 b,2 e,1 d,1 g,1 f,1

s = 'abcdefgabc'
for i in sorted(set(s)):
    print(f'{i}, {s.count(i)}')

Question 97

Please write a program which accepts a string from console and print it in reverse order.

Example: If the following string is given as input to the program:

rise to vote sir

Then, the output of the program should be:

ris etov ot esir

s = input()
s = ''.join(reversed(s))
print(s)

Question 98

Please write a program which accepts a string from console and print the characters that have even indexes.

Example: If the following string is given as input to the program:

H1e2l3l4o5w6o7r8l9d

Then, the output of the program should be:

Helloworld

s = "H1e2l3l4o5w6o7r8l9d"
news =''
for i in range(len(s)):
    if i % 2 == 0:
        news+=s[i]
print(news)

Question 99

Please write a program which prints all permutations of [1,2,3]

from itertools import permutations

def permuation_generator(iterable):
    p = permutations(iterable)
    for i in p:
        print(i)


x = [1,2,3]
permuation_generator(x)

Question 100

Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?

def solve(heads,legs):
    sol='No solutions!'
    for i in range(heads+1):
        j=heads-i
        if 2*i+4*j==legs:
            return i,j
    return sol,sol

heads = 35
legs = 94
solutions=solve(heads,legs)
print (solutions)