Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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.
- # Hints: Consider use range(#begin, #end) method
- l=[]
- for i in range(2000,3200):
- if (i%7==0) &(i%5!=0):
- l.append(str(i))
- print ','.join(l)
- # In[ ]:
- # 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.
- #raw_input() function can be used for getting user(console) input
- #Suppose the input is supplied to the program: 8
- #Then, the output should be: 40320
- #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
- x = int(input("Enter number:"))
- def fact(x):
- if x==0:
- return 1
- return x * fact(x-1)
- print fact(x)
- # In[ ]:
- # 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}
- #Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict()
- n = int(input("Enter number:"))
- dict = {}
- for i in range(1,n+1):
- dict[i] = i*i
- print dict
- # In[ ]:
- # 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')
- #Hints: In case of input data being supplied to the question, it should be assumed to be a console input. tuple() method can convert list to tuple
- ## 4- Solution 1
- i = input("Input some comma seprated numbers : ")
- l = list(i)
- t = i
- print l
- print t
- # In[ ]:
- ## Solution 2
- values=raw_input("Input some comma seprated numbers : ")
- l=values.split(",")
- t=tuple(l)
- print l
- print t
- # In[ ]:
- # Define a class which has at least two methods: getString: to get a string from console input and
- #printString: to print the string in upper case. Also please include simple test function to test the class methods.
- #Hints: Use __init__ method to construct some parameters
- class iostring:
- def _init_(self):
- self.s=""
- def getString(self):
- self.s=raw_input()
- def printString(self):
- print self.s.upper()
- newobj = iostring()
- newobj.getString()
- newobj.printString()
- # In[4]:
- #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.
- 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
- Hints: If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
- In case of input data being supplied to the question, it should be assumed to be a console input."""
- import math as mt
- var = input("Enter comma seperated numbers:")
- C = 50
- H = 30
- for D in list(var):
- print mt.sqrt((2*C*D)/H)
- # In[ ]:
- #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.
- 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]]
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form."""
- x= int(input("insert row \n: "))
- y = int(input("insert col \n: "))
- def darray(r,c):
- array = [[i * j for j in range(c)] for i in range(r)]
- return array
- print (darray(x,y))
- # In[ ]:
- # 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
- #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
- l= raw_input("Enter:")
- words = list(l.split(","))
- words.sort()
- l=[]
- for word in words:
- l.append(word)
- print ', '.join(l)
- # In[ ]:
- # Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
- """AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
- Suppose the input is supplied to the program: Hello world
- Practice makes perfect
- Then, the output should be: HELLO WORLD
- PRACTICE MAKES PERFECT
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- l=[]
- while True:
- s = raw_input("Enter a sentence:")
- if s:
- l.append(s.upper())
- else:
- break;
- for sentence in l:
- print sentence
- # In[ ]:
- # 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
- #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
- #We use set container to remove duplicated data automatically and then use sorted() to sort the data.
- input_str = raw_input("Enter a string:")
- words = list(set(input_str.split()))
- words.sort()
- l=[]
- for word in words:
- l.append(word)
- print ' '.join(l)
- # In[ ]:
- # 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.
- """Suppose the input is supplied to the program: 0100,0011,1010,1001
- Then the output should be: 1010
- Notes: Assume the data is input by console.
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- binary = raw_input("Enter binary numbers:")
- listbin = var.split(",")
- for d in listbin:
- if int(d,2) % 5 == 0:
- print d
- # In[ ]:
- # 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.
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- l= []
- for i in range(1000,3001):
- if i % 2 ==0:
- l.append(str(i))
- print ','.join(l)
- # In[ ]:
- # Write a program that accepts a sentence and calculate the number of letters and digits.
- """Suppose the input is supplied to the program: hello world! 123
- Then, the output should be: LETTERS 10
- AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
- DIGITS 3
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- var = raw_input("Enter A Sentence:")
- print ("DIGITS " + str(sum(1 for l in var if l.isdigit()))) + (" LETTERS " + str(sum(1 for l in var if l.isalpha())))
- # In[ ]:
- # 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
- #Hints: In case of input data being supplied to the question, it should be assumed to be a console input.
- l = raw_input("Enter a sentence:")
- print ("UPPER CASE "+ str(sum(1 for word in l if word.isupper()))) + (" LOWER CASE "+ str(sum(1 for word in l if word.islower())))
- # In[ ]:
- # Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
- """Suppose the input is supplied to the program: 9
- Then, the output should be: 11106
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- a = raw_input("Enter a digit:")
- a1 = int("%s" % a)
- a2 = int("%s%s" % (a,a))
- a3 = int("%s%s%s" % (a,a,a))
- a4 = int("%s%s%s%s" % (a,a,a,a))
- print a1+a2+a3+a4
- # In[ ]:
- # 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 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
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- var = input("Enter Numbers:")
- l= list(var)
- for n in l:
- if n % 2 !=0:
- a= n*n
- print n,a
- # In[ ]:
- # Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
- #Hints: Consider use yield
- s= int(raw_input("Enter a number:"))
- def divi(s):
- for i in range(0,s):
- if i%7==0:
- print i
- print divi(s)
- # In[ ]:
- # Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
- """Suppose the 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
- Hints: In case of input data being supplied to the question, it should be assumed to be a console input."""
- var = raw_input("Enter a sentence:")
- word = var.split()
- word.sort()
- wordfreq = [word.count(x) for x in word]
- dict(zip(word,wordfreq))
- # In[ ]:
- # Write a method which can calculate square value of number
- #Hints: Using the ** operator
- def squa(x):
- return x**2
- # In[ ]:
- # 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
- #Hints: The built-in document method is __doc__
- def absoluteNumber(number):
- return abs(number)
- print absoluteNumber(int(raw_input('Enter Number :')))
- print abs.__doc__
- print int.__doc__
- print raw_input.__doc__
- # In[ ]:
- # Define a class, which have a class parameter and have a same instance parameter.
- """Hints: Define a instance parameter, need add it in __init__ method
- You can init a object with construct parameter or set the value later"""
- class Person:
- # Define the class parameter "name"
- name = "Person"
- def __init__(self, name = None):
- # self.name is the instance parameter
- self.name = name
- jeffrey = Person("Jeffrey")
- print "%s name is %s" % (Person.name, jeffrey.name)
- nico = Person()
- nico.name = "Nico"
- print "%s name is %s" % (Person.name, nico.name)
- # In[ ]:
- # Define a function which can compute the sum of two numbers.
- """Hints: Define a function with two numbers as arguments. You can compute the sum in the function and return the value."""
- def addition(x,y):
- z = x+y
- return z
- # In[ ]:
- # Define a function that can convert a integer into a string and print it in console.
- """Hints: Use str() to convert a number to string."""
- def inttostr(x):
- y = str(x)
- return y
- # In[ ]:
- # Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
- """Hints: Use int() to convert a string to integer."""
- def rec(x,y):
- print float(x)+float(y) #not working with int()
- # In[ ]:
- # Define a function that can accept two strings as input and concatenate them and then print it in console.
- """Hints: Use + to concatenate the strings"""
- def twostr(x,y):
- z= x + y
- return z
- # In[ ]:
- # 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 al l strings line by line.
- """Hints: Use len() function to get the length of a string"""
- def length(x,y):
- if len(x) > len(y):
- print x
- elif len(x) < len(y):
- print y
- else:
- print x,y
- # In[ ]:
- # 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".
- """Hints: Use % operator to check if a number is even or odd."""
- def eveorodd(x):
- if x % 2==0:
- print "It is an even number"
- else:
- print "It is an odd number"
- # In[ ]:
- # 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.
- """Hints: Use dict[key]=value pattern to put entry into a dictionary.
- AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
- Use ** operator to get power of a number."""
- def dic():
- d= {}
- for i in range(1,4):
- d[i]= i*i
- print d
- # In[ ]:
- # 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.
- """Hints: Use dict[key]=value pattern to put entry into a dictionary.
- Use ** operator to get power of a number. Use range() for loops."""
- def dicsqua():
- d = {}
- for i in range(1,21):
- d[i] = i**2
- print d
- # In[ ]:
- # 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.
- """Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs."""
- def dictval():
- d={}
- for i in range(1,21):
- d[i] = i **2
- print d.values()
- # In[ ]:
- # 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.
- """Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs."""
- def dictkey():
- d={}
- for i in range(1,21):
- d[i] = i **2
- print d.keys()
- # In[ ]:
- # Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).
- """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list."""
- def squa():
- l=[]
- for i in range(1,21):
- l.append(i ** 2)
- print l
- # In[ ]:
- # 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.
- """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list"""
- def listfirst():
- l= []
- for i in range(1,21):
- l.append(i**2)
- print l[:5]
- # In[ ]:
- # 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.
- """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list"""
- def listlast():
- l=[]
- for i in range(1,21):
- l.append(i**2)
- print l[-5:]
- # In[ ]:
- # 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.
- """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list"""
- def listsquare():
- l=[]
- for i in range(1,21):
- l.append(i**2)
- print l[5:]
- # In[ ]:
- # Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).
- """Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use tuple() to get a tuple from a list."""
- def tuplesquare():
- l = []
- for i in range(1,21):
- l.append(i**2)
- print tuple(l)
- # In[ ]:
- # 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.
- """Hints: Use [n1:n2] notation to get a slice from a tuple."""
- t= tuple(range(1,11))
- print t[:5]
- print t[5:]
- # In[ ]:
- # 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).
- """Hints: Use "for" to iterate the tuple. Use tuple() to generate a tuple from a list."""
- t = tuple(range(1,11))
- l= []
- for i in t:
- if i % 2 ==0:
- l.append(i)
- print tuple(l)
- # In[ ]:
- # Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".
- """Hints: Use if statement to judge condition."""
- x = raw_input("Enter a word:")
- if x == "yes" or x == "YES" or x == "Yes":
- print "Yes"
- else:
- print "No"
- # In[ ]:
- # 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].
- """Hints: use filter() to filter some elements in a list. Use lambda to define anonymous functions."""
- filter(lambda x: x % 2==0, range(1,21))
- # In[ ]:
- # 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].
- """Hints: Use map() to generate a list. Use lambda to define anonymous functions."""
- map(lambda x: x**2, range(1,21))
- # In[ ]:
- # 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].
- """Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions."""
- map(lambda y:y**2, filter(lambda x: x%2==0, range(1,21)))
- # In[ ]:
- # Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).
- """AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
- Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions."""
- filter(lambda x: x%2==0, range(1,21))
- # In[ ]:
- # Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
- """Hints: Use map() to generate a list. Use lambda to define anonymous functions."""
- map(lambda x:x**2, range(1,21))
- # In[ ]:
- # Define a class named American which has a static method called printNationality.
- """Hints: Use @staticmethod decorator to define class static method."""
- class American():
- @staticmethod #
- def printNationality():
- print "America"
- an = American()
- an.printNationality()
- American.printNationality()
- # In[ ]:
- # Define a class named American and its subclass NewYorker.
- """Hints: Use class Subclass(ParentClass) to define a subclass."""
- class American():
- pass
- class NewYorker(American):
- pass
- # In[ ]:
- #52.Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
- """Hints: Use def methodName(self) to define a method."""
- class circle():
- def __init__(self,r):
- self.r = r
- def area(self):
- return 3.14*self.r**2
- areacircle = circle(4)
- print areacircle.area()
- # In[ ]:
- # 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.
- """ Hints: Use def methodName(self) to define a method."""
- class rectangle():
- def __init__(self,l,w):
- self.l = l
- self.w = w
- def area(self):
- return self.l*self.w
- arearec = rectangle(2,3)
- print arearec.area()
- # In[ ]:
- # 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.
- """Hints: To override a method in super class, we can define a method with the same name in the super class."""
- class shape():
- def __init__(self):
- pass
- def area(self):
- return 0
- class square(shape):
- def __init__(self,l):
- shape.__init__(self)
- self.l = l
- def area(self):
- return self.l*self.l
- asquare= square(3)
- print asquare.area()
- # In[ ]:
- # Write a function to compute 5/0 and use try/except to catch the exceptions.
- """Hints: Use try/except to catch exceptions."""
- try:
- 5/0
- except Exception as e:
- print "Caught an error: " + str(e)
- # In[ ]:
- # Define a custom exception class which takes a string message as attribute.
- """Hints: To define a custom exception, we need to define a class inherited from Exception."""
- class MyError(Exception):
- """My own exception class
- Attributes:
- msg -- explanation of the error
- """
- def __init__(self, msg):
- self.msg = msg
- error = MyError("something wrong")
- # In[ ]:
- # 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.
- """If the following email address is given as input to the program: Chandra@analytixlabs.com
- Then, the output of the program should be: Chandra
- AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
- In case of input data being supplied to the question, it should be assumed to be a console input.
- Hints: Use \w to match letters."""
- import re
- import pandas as pd
- var = raw_input("Enter an email address:")
- re.match("(\w+)@((\w+\.)+(com))",var).group(1)
- # In[ ]:
- # Assuming that we have some email addresses in the "username@companyname.com" 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.
- """If the following email address is given as input to the program: Chandra@analytixlabs.com
- Then, the output of the program should be: analytixlabs
- In case of input data being supplied to the question, it should be assumed to be a console input.
- Hints: Use \w to match letters"""
- var = raw_input("Enter an email address:")
- re.match("(\w+)@(\w+)\.+(com)",var).group(2)
- # In[ ]:
- # Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
- """If the following words are 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.
- Hints: Use re.findall() to find all substring using regex."""
- inputstr = raw_input("Enter a string:")
- inputstr = [x for x in var if x.isdigit()]
- print inputstr
- # In[ ]:
- # Print a unicode string "hello world".
- """Hints: Use u'strings' format to define unicode string."""
- stringUni = u'hello world'
- print stringUni
- # In[ ]:
- # Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
- """Hints: Use unicode() function to convert."""
- s = raw_input()
- UnicodeString = unicode( s ,"utf-8")
- print UnicodeString
- # In[ ]:
- # Write a special comment to indicate a Python source code file is in unicode.
- # In[ ]:
- # 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
- Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input."""
- n= input("Enter a number")
- l = []
- for x in range(0,n):
- if x%2 ==0:
- l.append(str(x))
- print ','.join(l)
- # In[ ]:
- # 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.
- """If the following n is given as input to the program: 100
- Then, the output of the program should be: 0, 35, 70
- Hints: Use yield to produce the next value in generator. In case of input data being supplied to the question, it should be assumed to be a console input."""
- n= input("Enter a number")
- l = []
- for x in range(0,n):
- if (x%5 ==0) and (x%7 ==0):
- l.append(str(x))
- print ','.join(l)
- # In[ ]:
- # Please write assert statements to verify that every number in the list [2,4,6,8] is even.
- """Hints: Use "assert expression" to make assertion."""
- l = [2,4,6,8]
- for i in l:
- assert i% 2 ==0
- # In[ ]:
- # Please write a program which accepts basic mathematic expression from console and print the evaluation result.
- """If the following string is given as input to the program: 35+3
- Then, the output of the program should be: 38
- Hints: Use eval() to evaluate an expression."""
- maths = raw_input()
- print eval(maths)
- # In[ ]:
- # Please generate a random float where the value is between 10 and 100 using Python math module.
- """Hints: Use random.random() to generate a random float in [0,1]."""
- import math as mt
- import numpy as np
- import random
- random.random()*100
- # In[ ]:
- # Please generate a random float where the value is between 5 and 95 using Python math module.
- """Hints: Use random.random() to generate a random float in [0,1]."""
- random.random()*100-5
- # In[ ]:
- # Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
- """Hints: Use random.choice() to a random element from a list."""
- random.choice([i for i in range(11) if i%2==0])
- # In[ ]:
- # 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.
- """Hints: Use random.choice() to a random element from a list."""
- random.choice([i for i in range(100) if (i%5==0) and (i%7==0)])
- # In[ ]:
- # Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
- """Hints: Use random.sample() to generate a list of random values."""
- random.sample(range(100,201),5)
- # In[ ]:
- # Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
- """Hints: Use random.sample() to generate a list of random values."""
- random.sample([i for i in range(100,201) if i%2==0],5)
- # In[ ]:
- # Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.
- """Hints: Use random.sample() to generate a list of random values."""
- random.sample([i for i in range(1,1001) if (i%5==0) and (i%7==0)],5)
- # In[ ]:
- # Please write a program to randomly print a integer number between 7 and 15 inclusive.
- """Hints: Use random.randrange() to a random integer in a given range."""
- random.randrange(7,16)
- # In[ ]:
- # Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
- """Hints: Use zlib.compress() and zlib.decompress() to compress and decompress a string."""
- import zlib
- s = "hello world!hello world!hello world!hello world!"
- compress = zlib.compress(s)
- print compress
- print zlib.decompress(compress)
- # In[ ]:
- # Please write a program to print the running time of execution of "1+1" for 100 times.
- """Hints: Use timeit() function to measure the running time."""
- %%timeit
- "for i in range(101):1+1"
- # In[ ]:
- # Please write a program to shuffle and print the list [3,6,7,8].
- """Hints: Use shuffle() function to shuffle a list."""
- from random import shuffle
- l = [3,6,7,8]
- shuffle(l)
- print l
- # In[ ]:
- # 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"].
- """Hints: Use list[index] notation to get a element from a list."""
- subjects = ["I", "You"]
- verbs = ["Play", "Love"]
- objects =["Hockey","Football"]
- for i in range(len(subjects)):
- for j in range(len(verbs)):
- for k in range(len(objects)):
- print "%s%s%s." % (subjects[i],verbs[j],objects[k])
- # In[ ]:
- # Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].
- """Hints: Use list comprehension to delete a bunch of element from a list."""
- l = [5,6,77,45,22,12,24]
- l = [x for x in l if x % 2 !=0]
- print l
- # In[ ]:
- # 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].
- """Hints: Use list comprehension to delete a bunch of element from a list."""
- l = [12,24,35,70,88,120,155]
- l = [x for x in l if (x%5 !=0) and (x%7!=0)]
- print l
- # In[ ]:
- # 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].
- """Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple."""
- l = [12,24,35,70,88,120,155]
- l = [x for i,x in enumerate(l) if i not in (0,2,4,6)]
- print l
- # In[ ]:
- # By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
- """Hints: Use list comprehension to make an array."""
- import numpy as np
- np.zeros([3,5,8])
- # In[ ]:
- # 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].
- """Hints: Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple."""
- l = [12,24,35,70,88,120,155]
- l = [x for i,x in enumerate(l) if i not in (0,4,5)]
- print l
- # In[ ]:
- # 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].
- """Hints: Use list's remove method to delete a value."""
- l = [12,24,35,24,88,120,155]
- l = [x for x in l if x !=24]
- print l
- # In[ ]:
- # 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.
- """Hints: Use set() and "&=" to do set intersection operation."""
- a = set([1,3,6,78,35,55])
- b = a.intersection([12,24,35,24,88,120,155])
- b
- # In[ ]:
- # 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.
- """Hints: Use set() to store a number of values without duplicate."""
- l = [12, 24, 35, 24, 88, 120, 155, 88, 120, 155]
- order = list(set(l))
- order.reverse()
- order
- # In[ ]:
- # 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.
- """Hints: Use Subclass(Parentclass) to define a child class."""
- class Person():
- def getGender(self):
- print "Unknown"
- class Male(Person):
- def getGender(self):
- print "Male"
- class Female(Person):
- def getGender(self):
- print "Female"
- aMale = Male()
- aFemale= Female()
- print aMale.getGender()
- print aFemale.getGender()
- # In[ ]:
- # Please write a program which count and print the numbers of each character in a string input by console.
- """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
- Hints: Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value."""
- var = raw_input("Enter a string:")
- charfreq = [var.count(x) for x in var]
- d=dict(zip(var,charfreq))
- print d
- # In[ ]:
- # Please write a program which accepts a string from console and print it in reverse order.
- """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
- Hints: Use list[::-1] to iterate a list in a reverse order."""
- inputrev = raw_input("Enter a string:")
- inputrev[::-1]
- # In[ ]:
- # Please write a program which accepts a string from console and print the characters that have even indexes.
- """AnalytixLabs, Website: www.analytixlabs.co.in Email: info@analytixlabs.co.in phone: +91-88021-73069
- If the following string is given as input to the program: H1e2l3l4o5w6o7r8l9d
- Then, the output of the program should be: Helloworld
- Hints: Use list[::2] to iterate a list by step 2."""
- inputstr = raw_input("Enter a string:")
- inputstr[::2]
- # In[ ]:
- # Create a dictionary with phone numbers (phonebook = {“John”: 938477566, "Jack”: 938377264, "Jill”: 947662781}). Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.
- phonebook = {"John":938477566, "Jack":938377264, "Jill": 947662781}
- phonebook["Jake"] = 938273443
- del phonebook["Jill"]
Add Comment
Please, Sign In to add comment