From c29235c1008ec049c7b4f09bffbe95fadfc19de9 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 22:57:51 -0700 Subject: [PATCH 01/17] Update and rename README to README.md --- README | 0 README.md | 2375 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 2375 insertions(+) delete mode 100644 README create mode 100644 README.md diff --git a/README b/README deleted file mode 100644 index e69de29b..00000000 diff --git a/README.md b/README.md new file mode 100644 index 00000000..030db828 --- /dev/null +++ b/README.md @@ -0,0 +1,2375 @@ +100+ Python challenging programming exercises + +1. Level description +Level Description +Level 1 Beginner means someone who has just gone through an introductory Python course. He 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 means someone who has just learned Python, but already has a relatively strong programming background from before. He 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 should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques. + +2. Problem template + +#----------------------------------------# +Question +Hints +Solution + +3. Questions + +#----------------------------------------# +Question 1 +Level 1 + +Question: +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 + +Solution: +l=[] +for i in range(2000, 3201): + if (i%7==0) and (i%5!=0): + l.append(str(i)) + +print ','.join(l) +#----------------------------------------# + +#----------------------------------------# +Question 2 +Level 1 + +Question: +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +def fact(x): + if x == 0: + return 1 + return x * fact(x - 1) + +x=int(raw_input()) +print fact(x) +#----------------------------------------# + +#----------------------------------------# +Question 3 +Level 1 + +Question: +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() + +Solution: +n=int(raw_input()) +d=dict() +for i in range(1,n+1): + d[i]=i*i + +print d +#----------------------------------------# + +#----------------------------------------# +Question 4 +Level 1 + +Question: +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 + +Solution: +values=raw_input() +l=values.split(",") +t=tuple(l) +print l +print t +#----------------------------------------# + +#----------------------------------------# +Question 5 +Level 1 + +Question: +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. + +Hints: +Use __init__ method to construct some parameters + +Solution: +class InputOutString(object): + def __init__(self): + self.s = "" + + def getString(self): + self.s = raw_input() + + def printString(self): + print self.s.upper() + +strObj = InputOutString() +strObj.getString() +strObj.printString() +#----------------------------------------# + +#----------------------------------------# +Question 6 +Level 2 + +Question: +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 + +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. + +Solution: +#!/usr/bin/env python +import math +c=50 +h=30 +value = [] +items=[x for x in raw_input().split(',')] +for d in items: + value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) + +print ','.join(value) +#----------------------------------------# + +#----------------------------------------# +Question 7 +Level 2 + +Question: +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]] + +Hints: +Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. + +Solution: +input_str = raw_input() +dimensions=[int(x) for x in input_str.split(',')] +rowNum=dimensions[0] +colNum=dimensions[1] +multilist = [[0 for col in range(colNum)] for row in range(rowNum)] + +for row in range(rowNum): + for col in range(colNum): + multilist[row][col]= row*col + +print multilist +#----------------------------------------# + +#----------------------------------------# +Question 8 +Level 2 + +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +items=[x for x in raw_input().split(',')] +items.sort() +print ','.join(items) +#----------------------------------------# + +#----------------------------------------# +Question 9 +Level 2 + +Question�� +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +lines = [] +while True: + s = raw_input() + if s: + lines.append(s.upper()) + else: + break; + +for sentence in lines: + print sentence +#----------------------------------------# + +#----------------------------------------# +Question 10 +Level 2 + +Question: +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. + +Solution: +s = raw_input() +words = [word for word in s.split(" ")] +print " ".join(sorted(list(set(words)))) +#----------------------------------------# + +#----------------------------------------# +Question 11 +Level 2 + +Question: +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. + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +value = [] +items=[x for x in raw_input().split(',')] +for p in items: + intp = int(p, 2) + if not intp%5: + value.append(p) + +print ','.join(value) +#----------------------------------------# + +#----------------------------------------# +Question 12 +Level 2 + +Question: +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. + +Solution: +values = [] +for i in range(1000, 3001): + s = str(i) + if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): + values.append(s) +print ",".join(values) +#----------------------------------------# + +#----------------------------------------# +Question 13 +Level 2 + +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +s = raw_input() +d={"DIGITS":0, "LETTERS":0} +for c in s: + if c.isdigit(): + d["DIGITS"]+=1 + elif c.isalpha(): + d["LETTERS"]+=1 + else: + pass +print "LETTERS", d["LETTERS"] +print "DIGITS", d["DIGITS"] +#----------------------------------------# + +#----------------------------------------# +Question 14 +Level 2 + +Question: +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. + +Solution: +s = raw_input() +d={"UPPER CASE":0, "LOWER CASE":0} +for c in s: + if c.isupper(): + d["UPPER CASE"]+=1 + elif c.islower(): + d["LOWER CASE"]+=1 + else: + pass +print "UPPER CASE", d["UPPER CASE"] +print "LOWER CASE", d["LOWER CASE"] +#----------------------------------------# + +#----------------------------------------# +Question 15 +Level 2 + +Question: +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +a = raw_input() +n1 = int( "%s" % a ) +n2 = int( "%s%s" % (a,a) ) +n3 = int( "%s%s%s" % (a,a,a) ) +n4 = int( "%s%s%s%s" % (a,a,a,a) ) +print n1+n2+n3+n4 +#----------------------------------------# + +#----------------------------------------# +Question 16 +Level 2 + +Question: +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +values = raw_input() +numbers = [x for x in values.split(",") if int(x)%2!=0] +print ",".join(numbers) +#----------------------------------------# + +Question 17 +Level 2 + +Question: +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 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: +import sys +netAmount = 0 +while True: + s = raw_input() + if not s: + break + values = s.split(" ") + operation = values[0] + amount = int(values[1]) + if operation=="D": + netAmount+=amount + elif operation=="W": + netAmount-=amount + else: + pass +print netAmount +#----------------------------------------# + +#----------------------------------------# +Question 18 +Level 3 + +Question: +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: +ABd1234@1,a F1#,2w3E*,2We3345 +Then, the output of the program should be: +ABd1234@1 + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solutions: +import re +value = [] +items=[x for x in raw_input().split(',')] +for p in items: + if len(p)<6 or len(p)>12: + continue + else: + pass + if not re.search("[a-z]",p): + continue + elif not re.search("[0-9]",p): + continue + elif not re.search("[A-Z]",p): + continue + elif not re.search("[$#@]",p): + continue + elif re.search("\s",p): + continue + else: + pass + value.append(p) +print ",".join(value) +#----------------------------------------# + +#----------------------------------------# +Question 19 +Level 3 + +Question: +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')] + +Hints: +In case of input data being supplied to the question, it should be assumed to be a console input. +We use itemgetter to enable multiple sort keys. + +Solutions: +from operator import itemgetter, attrgetter + +l = [] +while True: + s = raw_input() + if not s: + break + l.append(tuple(s.split(","))) + +print sorted(l, key=itemgetter(0,1,2)) +#----------------------------------------# + +#----------------------------------------# +Question 20 +Level 3 + +Question: +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 + +Solution: +def putNumbers(n): + i = 0 + while ilen2: + print s1 + elif len2>len1: + print s2 + else: + print s1 + print s2 + + +printValue("one","three") + + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +def checkValue(n): + if n%2 == 0: + print "It is an even number" + else: + print "It is an odd number" + + +checkValue(7) + + +#----------------------------------------# +2.10 + +Question: +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. +Use ** operator to get power of a number. + +Solution +def printDict(): + d=dict() + d[1]=1 + d[2]=2**2 + d[3]=3**2 + print d + + +printDict() + + + + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +def printDict(): + d=dict() + for i in range(1,21): + d[i]=i**2 + print d + + +printDict() + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +def printDict(): + d=dict() + for i in range(1,21): + d[i]=i**2 + for (k,v) in d.items(): + print v + + +printDict() + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +def printDict(): + d=dict() + for i in range(1,21): + d[i]=i**2 + for k in d.keys(): + print k + + +printDict() + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +def printList(): + li=list() + for i in range(1,21): + li.append(i**2) + print li + + +printList() + +#----------------------------------------# +2.10 + +Question: +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 + +Solution +def printList(): + li=list() + for i in range(1,21): + li.append(i**2) + print li[:5] + + +printList() + + +#----------------------------------------# +2.10 + +Question: +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 + +Solution +def printList(): + li=list() + for i in range(1,21): + li.append(i**2) + print li[-5:] + + +printList() + + +#----------------------------------------# +2.10 + +Question: +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 + +Solution +def printList(): + li=list() + for i in range(1,21): + li.append(i**2) + print li[5:] + + +printList() + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +def printTuple(): + li=list() + for i in range(1,21): + li.append(i**2) + print tuple(li) + +printTuple() + + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +tp=(1,2,3,4,5,6,7,8,9,10) +tp1=tp[:5] +tp2=tp[5:] +print tp1 +print tp2 + + +#----------------------------------------# +2.10 + +Question: +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. + +Solution +tp=(1,2,3,4,5,6,7,8,9,10) +li=list() +for i in tp: + if tp[i]%2==0: + li.append(tp[i]) + +tp2=tuple(li) +print tp2 + + + +#----------------------------------------# +2.14 + +Question: +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. + +Solution +s= raw_input() +if s=="yes" or s=="YES" or s=="Yes": + print "Yes" +else: + print "No" + + + +#----------------------------------------# +3.4 + +Question: +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. + +Solution +li = [1,2,3,4,5,6,7,8,9,10] +evenNumbers = filter(lambda x: x%2==0, li) +print evenNumbers + + +#----------------------------------------# +3.4 + +Question: +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. + +Solution +li = [1,2,3,4,5,6,7,8,9,10] +squaredNumbers = map(lambda x: x**2, li) +print squaredNumbers + +#----------------------------------------# +3.5 + +Question: +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. + +Solution +li = [1,2,3,4,5,6,7,8,9,10] +evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) +print evenNumbers + + + + +#----------------------------------------# +3.5 + +Question: +Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). + +Hints: + +Use filter() to filter elements of a list. +Use lambda to define anonymous functions. + +Solution +evenNumbers = filter(lambda x: x%2==0, range(1,21)) +print evenNumbers + + +#----------------------------------------# +3.5 + +Question: +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. + +Solution +squaredNumbers = map(lambda x: x**2, range(1,21)) +print squaredNumbers + + + + +#----------------------------------------# +7.2 + +Question: +Define a class named American which has a static method called printNationality. + +Hints: + +Use @staticmethod decorator to define class static method. + +Solution +class American(object): + @staticmethod + def printNationality(): + print "America" + +anAmerican = American() +anAmerican.printNationality() +American.printNationality() + + + + +#----------------------------------------# + +7.2 + +Question: +Define a class named American and its subclass NewYorker. + +Hints: + +Use class Subclass(ParentClass) to define a subclass. + +Solution: + +class American(object): + pass + +class NewYorker(American): + pass + +anAmerican = American() +aNewYorker = NewYorker() +print anAmerican +print aNewYorker + + + + +#----------------------------------------# + + +7.2 + +Question: +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. + +Solution: + +class Circle(object): + def __init__(self, r): + self.radius = r + + def area(self): + return self.radius**2*3.14 + +aCircle = Circle(2) +print aCircle.area() + + + + + + +#----------------------------------------# + +7.2 + +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. + +Solution: + +class Rectangle(object): + def __init__(self, l, w): + self.length = l + self.width = w + + def area(self): + return self.length*self.width + +aRectangle = Rectangle(2,10) +print aRectangle.area() + + + + +#----------------------------------------# + +7.2 + +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. + +Solution: + +class Shape(object): + def __init__(self): + pass + + def area(self): + return 0 + +class Square(Shape): + def __init__(self, l): + Shape.__init__(self) + self.length = l + + def area(self): + return self.length*self.length + +aSquare= Square(3) +print aSquare.area() + + + + + + + + +#----------------------------------------# + + +Please raise a RuntimeError exception. + +Hints: + +Use raise() to raise an exception. + +Solution: + +raise RuntimeError('something wrong') + + + +#----------------------------------------# +Write a function to compute 5/0 and use try/except to catch the exceptions. + +Hints: + +Use try/except to catch exceptions. + +Solution: + +def throws(): + return 5/0 + +try: + throws() +except ZeroDivisionError: + print "division by zero!" +except Exception, err: + print 'Caught an exception' +finally: + print 'In finally block for cleanup' + + +#----------------------------------------# +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. + +Solution: + +class MyError(Exception): + """My own exception class + + Attributes: + msg -- explanation of the error + """ + + def __init__(self, msg): + self.msg = msg + +error = MyError("something wrong") + +#----------------------------------------# +Question: + +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. + +Hints: + +Use \w to match letters. + +Solution: +import re +emailAddress = raw_input() +pat2 = "(\w+)@((\w+\.)+(com))" +r2 = re.match(pat2,emailAddress) +print r2.group(1) + + +#----------------------------------------# +Question: + +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. + +Example: +If the following email address is given as input to the program: + +john@google.com + +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. + +Hints: + +Use \w to match letters. + +Solution: +import re +emailAddress = raw_input() +pat2 = "(\w+)@(\w+)\.(com)" +r2 = re.match(pat2,emailAddress) +print r2.group(2) + + + + +#----------------------------------------# +Question: + +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. + +Hints: + +Use re.findall() to find all substring using regex. + +Solution: +import re +s = raw_input() +print re.findall("\d+",s) + + +#----------------------------------------# +Question: + + +Print a unicode string "hello world". + +Hints: + +Use u'strings' format to define unicode string. + +Solution: + +unicodeString = u"hello world!" +print unicodeString + +#----------------------------------------# +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. + +Solution: + +s = raw_input() +u = unicode( s ,"utf-8") +print u + +#----------------------------------------# +Question: + +Write a special comment to indicate a Python source code file is in unicode. + +Hints: + +Solution: + +# -*- coding: utf-8 -*- + +#----------------------------------------# +Question: + +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. + +Hints: +Use float() to convert an integer to a float + +Solution: + +n=int(raw_input()) +sum=0.0 +for i in range(1,n+1): + sum += float(float(i)/(i+1)) +print sum + + +#----------------------------------------# +Question: + +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. + +Hints: +We can define recursive function in Python. + +Solution: + +def f(n): + if n==0: + return 0 + else: + return f(n-1)+100 + +n=int(raw_input()) +print f(n) + +#----------------------------------------# + +Question: + + +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. + +Hints: +We can define recursive function in Python. + + +Solution: + +def f(n): + if n == 0: return 0 + elif n == 1: return 1 + else: return f(n-1)+f(n-2) + +n=int(raw_input()) +print f(n) + + +#----------------------------------------# + +#----------------------------------------# + +Question: + +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 + + +Hints: +We can define recursive function in Python. +Use list comprehension to generate a list from an existing list. +Use string.join() to join a list of strings. + +In case of input data being supplied to the question, it should be assumed to be a console input. + +Solution: + +def f(n): + if n == 0: return 0 + elif n == 1: return 1 + else: return f(n-1)+f(n-2) + +n=int(raw_input()) +values = [str(f(x)) for x in range(0, n+1)] +print ",".join(values) + + +#----------------------------------------# + +Question: + +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. + +Solution: + +def EvenGenerator(n): + i=0 + while i<=n: + if i%2==0: + yield i + i+=1 + + +n=int(raw_input()) +values = [] +for i in EvenGenerator(n): + values.append(str(i)) + +print ",".join(values) + + +#----------------------------------------# + +Question: + +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 + +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. + +Solution: + +def NumGenerator(n): + for i in range(n+1): + if i%5==0 and i%7==0: + yield i + +n=int(raw_input()) +values = [] +for i in NumGenerator(n): + values.append(str(i)) + +print ",".join(values) + + +#----------------------------------------# + +Question: + + +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. + + +Solution: + +li = [2,4,6,8] +for i in li: + assert i%2==0 + + +#----------------------------------------# +Question: + +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 + +Hints: +Use eval() to evaluate an expression. + + +Solution: + +expression = raw_input() +print eval(expression) + + +#----------------------------------------# +Question: + +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. + + +Hints: +Use if/elif to deal with conditions. + + +Solution: + +import math +def bin_search(li, element): + bottom = 0 + top = len(li)-1 + index = -1 + while top>=bottom and index==-1: + mid = int(math.floor((top+bottom)/2.0)) + if li[mid]==element: + index = mid + elif li[mid]>element: + top = mid-1 + else: + bottom = mid+1 + + return index + +li=[2,5,7,9,11,17,222] +print bin_search(li,11) +print bin_search(li,12) + + + + +#----------------------------------------# +Question: + +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. + + +Hints: +Use if/elif to deal with conditions. + + +Solution: + +import math +def bin_search(li, element): + bottom = 0 + top = len(li)-1 + index = -1 + while top>=bottom and index==-1: + mid = int(math.floor((top+bottom)/2.0)) + if li[mid]==element: + index = mid + elif li[mid]>element: + top = mid-1 + else: + bottom = mid+1 + + return index + +li=[2,5,7,9,11,17,222] +print bin_search(li,11) +print bin_search(li,12) + + + + +#----------------------------------------# +Question: + +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]. + + +Solution: + +import random +print random.random()*100 + +#----------------------------------------# +Question: + +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]. + + +Solution: + +import random +print random.random()*100-5 + + +#----------------------------------------# +Question: + +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. + + +Solution: + +import random +print random.choice([i for i in range(11) if i%2==0]) + + +#----------------------------------------# +Question: + +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. + + +Solution: + +import random +print random.choice([i for i in range(201) if i%5==0 and i%7==0]) + + + +#----------------------------------------# + +Question: + +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. + + +Solution: + +import random +print random.sample(range(100), 5) + +#----------------------------------------# +Question: + +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. + + +Solution: + +import random +print random.sample([i for i in range(100,201) if i%2==0], 5) + + +#----------------------------------------# +Question: + +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. + + +Solution: + +import random +print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) + +#----------------------------------------# + +Question: + +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. + + +Solution: + +import random +print random.randrange(7,16) + +#----------------------------------------# + +Question: + +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. + + +Solution: + +import zlib +s = 'hello world!hello world!hello world!hello world!' +t = zlib.compress(s) +print t +print zlib.decompress(t) + +#----------------------------------------# +Question: + +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. + +Solution: + +from timeit import Timer +t = Timer("for i in range(100):1+1") +print t.timeit() + +#----------------------------------------# +Question: + +Please write a program to shuffle and print the list [3,6,7,8]. + + + +Hints: +Use shuffle() function to shuffle a list. + +Solution: + +from random import shuffle +li = [3,6,7,8] +shuffle(li) +print li + +#----------------------------------------# +Question: + +Please write a program to shuffle and print the list [3,6,7,8]. + + + +Hints: +Use shuffle() function to shuffle a list. + +Solution: + +from random import shuffle +li = [3,6,7,8] +shuffle(li) +print li + + + +#----------------------------------------# +Question: + +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. + +Solution: + +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)): + sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) + print sentence + + +#----------------------------------------# +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. + +Solution: + +li = [5,6,77,45,22,12,24] +li = [x for x in li if x%2!=0] +print li + +#----------------------------------------# +Question: + +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. + +Solution: + +li = [12,24,35,70,88,120,155] +li = [x for x in li if x%5!=0 and x%7!=0] +print li + + +#----------------------------------------# +Question: + +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. + +Solution: + +li = [12,24,35,70,88,120,155] +li = [x for (i,x) in enumerate(li) if i%2!=0] +print li + +#----------------------------------------# + +Question: + +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. + +Solution: + +array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] +print array + +#----------------------------------------# +Question: + +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. + +Solution: + +li = [12,24,35,70,88,120,155] +li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] +print li + + + +#----------------------------------------# + +Question: + +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. + +Solution: + +li = [12,24,35,24,88,120,155] +li = [x for x in li if x!=24] +print li + + +#----------------------------------------# +Question: + +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. + +Solution: + +set1=set([1,3,6,78,35,55]) +set2=set([12,24,35,24,88,120,155]) +set1 &= set2 +li=list(set1) +print li + +#----------------------------------------# + +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. + +Solution: + +def removeDuplicate( li ): + newli=[] + seen = set() + for item in li: + if item not in seen: + seen.add( item ) + newli.append(item) + + return newli + +li=[12,24,35,24,88,120,155,88,120,155] +print removeDuplicate(li) + + +#----------------------------------------# +Question: + +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. + +Solution: + +class Person(object): + def getGender( self ): + return "Unknown" + +class Male( Person ): + def getGender( self ): + return "Male" + +class Female( Person ): + def getGender( self ): + return "Female" + +aMale = Male() +aFemale= Female() +print aMale.getGender() +print aFemale.getGender() + + + +#----------------------------------------# +Question: + +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 + +Hints: +Use dict to store key/value pairs. +Use dict.get() method to lookup a key with default value. + +Solution: + +dic = {} +s=raw_input() +for s in s: + dic[s] = dic.get(s,0)+1 +print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) + +#----------------------------------------# + +Question: + +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 + +Hints: +Use list[::-1] to iterate a list in a reverse order. + +Solution: + +s=raw_input() +s = s[::-1] +print s + +#----------------------------------------# + +Question: + +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 + +Hints: +Use list[::2] to iterate a list by step 2. + +Solution: + +s=raw_input() +s = s[::2] +print s +#----------------------------------------# + + +Question: + +Please write a program which prints all permutations of [1,2,3] + + +Hints: +Use itertools.permutations() to get permutations of list. + +Solution: + +import itertools +print list(itertools.permutations([1,2,3])) + +#----------------------------------------# +Question: + +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? + +Hint: +Use for loop to iterate all possible solutions. + +Solution: + +def solve(numheads,numlegs): + ns='No solutions!' + for i in range(numheads+1): + j=numheads-i + if 2*i+4*j==numlegs: + return i,j + return ns,ns + +numheads=35 +numlegs=94 +solutions=solve(numheads,numlegs) +print solutions + +#----------------------------------------# + From a28cadbe6b5050ec0b4910eea1405aa2c2214712 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:02:17 -0700 Subject: [PATCH 02/17] Update README.md --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 030db828..51177293 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,12 @@ 100+ Python challenging programming exercises - +== 1. Level description -Level Description -Level 1 Beginner means someone who has just gone through an introductory Python course. He 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 means someone who has just learned Python, but already has a relatively strong programming background from before. He 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 should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques. + +| Level | Description | +|-------|-------------| +|Level 1| Beginner means someone who has just gone through an introductory Python course. He 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 means someone who has just learned Python, but already has a relatively strong programming background from before. He 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 should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques.| 2. Problem template From 73e069c3fa29ff1c6e77cb1f95428d88ea55b277 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:08:09 -0700 Subject: [PATCH 03/17] Update README.md --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 51177293..904c2f07 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ 100+ Python challenging programming exercises == -1. Level description +# Table of Contents +1. [Level description](# Level description) +2. [Problem template](# Problem template) +## Level description | Level | Description | |-------|-------------| @@ -8,7 +11,7 @@ |Level 2|Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He 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 should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques.| -2. Problem template +## Problem template #----------------------------------------# Question From 5b060b61b0bccd04d9af98c5ea6e6197fe0582d3 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:11:07 -0700 Subject: [PATCH 04/17] Update README.md --- README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 904c2f07..7a4c5360 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ -100+ Python challenging programming exercises -== -# Table of Contents -1. [Level description](# Level description) -2. [Problem template](# Problem template) -## Level description +# 100+ Python challenging programming exercises +* * * +## Table of Contents +1. [Level description](#Level description) +2. [Problem template](#Problem template) +3. [Questions](#Questions) + +### Level description | Level | Description | |-------|-------------| @@ -11,14 +13,12 @@ |Level 2|Intermediate means someone who has just learned Python, but already has a relatively strong programming background from before. He 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 should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques.| -## Problem template - -#----------------------------------------# -Question -Hints -Solution +### Problem template +* Question +* Hints +* Solution -3. Questions +### Questions #----------------------------------------# Question 1 From 2dd857f78d30b8f747eacf837b70e567759575ad Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:13:02 -0700 Subject: [PATCH 05/17] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7a4c5360..d71dbc68 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,9 @@ # 100+ Python challenging programming exercises * * * ## Table of Contents -1. [Level description](#Level description) -2. [Problem template](#Problem template) -3. [Questions](#Questions) +1. [Level description](#level-description) +2. [Problem template](#problem-template) +3. [Questions](#questions) ### Level description From c406d36cc821a460da7b5839c8e20081ea732e1a Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:25:40 -0700 Subject: [PATCH 06/17] Update README.md --- README.md | 843 +++++++++++++++++++++++++++--------------------------- 1 file changed, 419 insertions(+), 424 deletions(-) diff --git a/README.md b/README.md index d71dbc68..e148b921 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,9 @@ 1. [Level description](#level-description) 2. [Problem template](#problem-template) 3. [Questions](#questions) + 1. [Level 1](#level-1) + 2. [Level 2](#level-2) + 3. [Level 3](#level-3) ### Level description @@ -20,32 +23,33 @@ ### Questions -#----------------------------------------# -Question 1 -Level 1 +#### Level 1 +* * * + + -Question: +**Question:** 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: +**Hints:** Consider use range(#begin, #end) method -Solution: +**Solution:** l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): l.append(str(i)) print ','.join(l) -#----------------------------------------# +* * * + +* * * + -#----------------------------------------# -Question 2 -Level 1 -Question: +**Question:** 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: @@ -53,10 +57,10 @@ Suppose the following input is supplied to the program: Then, the output should be: 40320 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** def fact(x): if x == 0: return 1 @@ -64,37 +68,33 @@ def fact(x): x=int(raw_input()) print fact(x) -#----------------------------------------# +* * * -#----------------------------------------# -Question 3 -Level 1 +* * * -Question: +**Question:** 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: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() -Solution: +**Solution:** n=int(raw_input()) d=dict() for i in range(1,n+1): d[i]=i*i print d -#----------------------------------------# +* * * -#----------------------------------------# -Question 4 -Level 1 +* * * -Question: +**Question:** 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 @@ -102,32 +102,29 @@ Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98') -Hints: +**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 -Solution: +**Solution:** values=raw_input() l=values.split(",") t=tuple(l) print l print t -#----------------------------------------# - -#----------------------------------------# -Question 5 -Level 1 +* * * -Question: +* * * +**Question:** 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. -Hints: +**Hints:** Use __init__ method to construct some parameters -Solution: +**Solution:** class InputOutString(object): def __init__(self): self.s = "" @@ -141,13 +138,12 @@ class InputOutString(object): strObj = InputOutString() strObj.getString() strObj.printString() -#----------------------------------------# +* * * -#----------------------------------------# -Question 6 -Level 2 +#### Level 2 +* * * -Question: +**Question:** 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: @@ -159,11 +155,11 @@ Let us assume the following comma separated input sequence is given to the progr The output of the program should be: 18,22,24 -Hints: +**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. -Solution: +**Solution:** #!/usr/bin/env python import math c=50 @@ -174,13 +170,13 @@ for d in items: value.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print ','.join(value) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 7 Level 2 -Question: +**Question:** 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 @@ -189,10 +185,10 @@ Suppose the following inputs are given to the program: Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] -Hints: +**Hints:** Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. -Solution: +**Solution:** input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] @@ -204,30 +200,30 @@ for row in range(rowNum): multilist[row][col]= row*col print multilist -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 8 Level 2 -Question: +**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 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 9 Level 2 Question�� @@ -239,10 +235,10 @@ Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** lines = [] while True: s = raw_input() @@ -253,34 +249,34 @@ while True: for sentence in lines: print sentence -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 10 Level 2 -Question: +**Question:** 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: +**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. -Solution: +**Solution:** s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 11 Level 2 -Question: +**Question:** 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 @@ -288,10 +284,10 @@ Then the output should be: 1010 Notes: Assume the data is input by console. -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** value = [] items=[x for x in raw_input().split(',')] for p in items: @@ -300,33 +296,33 @@ for p in items: value.append(p) print ','.join(value) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 12 Level 2 -Question: +**Question:** 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: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print ",".join(values) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 13 Level 2 -Question: +**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 @@ -334,10 +330,10 @@ Then, the output should be: LETTERS 10 DIGITS 3 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: @@ -349,13 +345,13 @@ for c in s: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 14 Level 2 -Question: +**Question:** 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! @@ -363,10 +359,10 @@ Then, the output should be: UPPER CASE 1 LOWER CASE 9 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: @@ -378,55 +374,55 @@ for c in s: pass print "UPPER CASE", d["UPPER CASE"] print "LOWER CASE", d["LOWER CASE"] -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 15 Level 2 -Question: +**Question:** 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 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) n3 = int( "%s%s%s" % (a,a,a) ) n4 = int( "%s%s%s%s" % (a,a,a,a) ) print n1+n2+n3+n4 -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 16 Level 2 -Question: +**Question:** 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 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) -#----------------------------------------# +* * * + -Question 17 Level 2 -Question: +**Question:** 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 @@ -440,10 +436,10 @@ D 100 Then, the output should be: 500 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** import sys netAmount = 0 while True: @@ -460,13 +456,13 @@ while True: else: pass print netAmount -#----------------------------------------# +* * * -#----------------------------------------# -Question 18 -Level 3 +* * * -Question: +#### Level 3 + +**Question:** 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] @@ -482,7 +478,7 @@ ABd1234@1,a F1#,2w3E*,2We3345 Then, the output of the program should be: ABd1234@1 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. Solutions: @@ -508,13 +504,13 @@ for p in items: pass value.append(p) print ",".join(value) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 19 Level 3 -Question: +**Question:** 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; @@ -529,7 +525,7 @@ 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')] -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. We use itemgetter to enable multiple sort keys. @@ -544,19 +540,19 @@ while True: l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) -#----------------------------------------# +* * * + +* * * -#----------------------------------------# -Question 20 Level 3 -Question: +**Question:** Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. -Hints: +**Hints:** Consider use yield -Solution: +**Solution:** def putNumbers(n): i = 0 while i0). @@ -1555,10 +1551,10 @@ Then, the output of the program should be: In case of input data being supplied to the question, it should be assumed to be a console input. -Hints: +**Hints:** Use float() to convert an integer to a float -Solution: +**Solution:** n=int(raw_input()) sum=0.0 @@ -1567,8 +1563,8 @@ for i in range(1,n+1): print sum -#----------------------------------------# -Question: +* * * +**Question:** Write a program to compute: @@ -1588,10 +1584,10 @@ Then, the output of the program should be: In case of input data being supplied to the question, it should be assumed to be a console input. -Hints: +**Hints:** We can define recursive function in Python. -Solution: +**Solution:** def f(n): if n==0: @@ -1602,9 +1598,9 @@ def f(n): n=int(raw_input()) print f(n) -#----------------------------------------# +* * * -Question: +**Question:** The Fibonacci Sequence is computed based on the following formula: @@ -1627,11 +1623,11 @@ Then, the output of the program should be: In case of input data being supplied to the question, it should be assumed to be a console input. -Hints: +**Hints:** We can define recursive function in Python. -Solution: +**Solution:** def f(n): if n == 0: return 0 @@ -1642,11 +1638,11 @@ n=int(raw_input()) print f(n) -#----------------------------------------# +* * * -#----------------------------------------# +* * * -Question: +**Question:** The Fibonacci Sequence is computed based on the following formula: @@ -1667,14 +1663,14 @@ Then, the output of the program should be: 0,1,1,2,3,5,8,13 -Hints: +**Hints:** We can define recursive function in Python. Use list comprehension to generate a list from an existing list. Use string.join() to join a list of strings. In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** def f(n): if n == 0: return 0 @@ -1686,9 +1682,9 @@ values = [str(f(x)) for x in range(0, n+1)] print ",".join(values) -#----------------------------------------# +* * * -Question: +**Question:** 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. @@ -1701,12 +1697,12 @@ Then, the output of the program should be: 0,2,4,6,8,10 -Hints: +**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. -Solution: +**Solution:** def EvenGenerator(n): i=0 @@ -1724,9 +1720,9 @@ for i in EvenGenerator(n): print ",".join(values) -#----------------------------------------# +* * * -Question: +**Question:** 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. @@ -1739,12 +1735,12 @@ Then, the output of the program should be: 0,35,70 -Hints: +**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. -Solution: +**Solution:** def NumGenerator(n): for i in range(n+1): @@ -1759,28 +1755,28 @@ for i in NumGenerator(n): print ",".join(values) -#----------------------------------------# +* * * -Question: +**Question:** Please write assert statements to verify that every number in the list [2,4,6,8] is even. -Hints: +**Hints:** Use "assert expression" to make assertion. -Solution: +**Solution:** li = [2,4,6,8] for i in li: assert i%2==0 -#----------------------------------------# -Question: +* * * +**Question:** Please write a program which accepts basic mathematic expression from console and print the evaluation result. @@ -1793,27 +1789,27 @@ Then, the output of the program should be: 38 -Hints: +**Hints:** Use eval() to evaluate an expression. -Solution: +**Solution:** expression = raw_input() print eval(expression) -#----------------------------------------# -Question: +* * * +**Question:** 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. -Hints: +**Hints:** Use if/elif to deal with conditions. -Solution: +**Solution:** import math def bin_search(li, element): @@ -1838,17 +1834,17 @@ print bin_search(li,12) -#----------------------------------------# -Question: +* * * +**Question:** 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. -Hints: +**Hints:** Use if/elif to deal with conditions. -Solution: +**Solution:** import math def bin_search(li, element): @@ -1873,154 +1869,154 @@ print bin_search(li,12) -#----------------------------------------# -Question: +* * * +**Question:** Please generate a random float where the value is between 10 and 100 using Python math module. -Hints: +**Hints:** Use random.random() to generate a random float in [0,1]. -Solution: +**Solution:** import random print random.random()*100 -#----------------------------------------# -Question: +* * * +**Question:** Please generate a random float where the value is between 5 and 95 using Python math module. -Hints: +**Hints:** Use random.random() to generate a random float in [0,1]. -Solution: +**Solution:** import random print random.random()*100-5 -#----------------------------------------# -Question: +* * * +**Question:** Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. -Hints: +**Hints:** Use random.choice() to a random element from a list. -Solution: +**Solution:** import random print random.choice([i for i in range(11) if i%2==0]) -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use random.choice() to a random element from a list. -Solution: +**Solution:** import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) -#----------------------------------------# +* * * -Question: +**Question:** Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. -Hints: +**Hints:** Use random.sample() to generate a list of random values. -Solution: +**Solution:** import random print random.sample(range(100), 5) -#----------------------------------------# -Question: +* * * +**Question:** Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. -Hints: +**Hints:** Use random.sample() to generate a list of random values. -Solution: +**Solution:** import random print random.sample([i for i in range(100,201) if i%2==0], 5) -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use random.sample() to generate a list of random values. -Solution: +**Solution:** import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) -#----------------------------------------# +* * * -Question: +**Question:** Please write a program to randomly print a integer number between 7 and 15 inclusive. -Hints: +**Hints:** Use random.randrange() to a random integer in a given range. -Solution: +**Solution:** import random print random.randrange(7,16) -#----------------------------------------# +* * * -Question: +**Question:** Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". -Hints: +**Hints:** Use zlib.compress() and zlib.decompress() to compress and decompress a string. -Solution: +**Solution:** import zlib s = 'hello world!hello world!hello world!hello world!' @@ -2028,50 +2024,50 @@ t = zlib.compress(s) print t print zlib.decompress(t) -#----------------------------------------# -Question: +* * * +**Question:** Please write a program to print the running time of execution of "1+1" for 100 times. -Hints: +**Hints:** Use timeit() function to measure the running time. -Solution: +**Solution:** from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() -#----------------------------------------# -Question: +* * * +**Question:** Please write a program to shuffle and print the list [3,6,7,8]. -Hints: +**Hints:** Use shuffle() function to shuffle a list. -Solution: +**Solution:** from random import shuffle li = [3,6,7,8] shuffle(li) print li -#----------------------------------------# -Question: +* * * +**Question:** Please write a program to shuffle and print the list [3,6,7,8]. -Hints: +**Hints:** Use shuffle() function to shuffle a list. -Solution: +**Solution:** from random import shuffle li = [3,6,7,8] @@ -2080,15 +2076,15 @@ print li -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use list[index] notation to get a element from a list. -Solution: +**Solution:** subjects=["I", "You"] verbs=["Play", "Love"] @@ -2100,72 +2096,72 @@ for i in range(len(subjects)): print sentence -#----------------------------------------# +* * * Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. -Hints: +**Hints:** Use list comprehension to delete a bunch of element from a list. -Solution: +**Solution:** li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use list comprehension to delete a bunch of element from a list. -Solution: +**Solution:** li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print li -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. -Solution: +**Solution:** li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li -#----------------------------------------# +* * * -Question: +**Question:** By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0. -Hints: +**Hints:** Use list comprehension to make an array. -Solution: +**Solution:** array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. -Solution: +**Solution:** li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] @@ -2173,31 +2169,31 @@ print li -#----------------------------------------# +* * * -Question: +**Question:** 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: +**Hints:** Use list's remove method to delete a value. -Solution: +**Solution:** li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print li -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use set() and "&=" to do set intersection operation. -Solution: +**Solution:** set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) @@ -2205,14 +2201,14 @@ set1 &= set2 li=list(set1) print li -#----------------------------------------# +* * * 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: +**Hints:** Use set() to store a number of values without duplicate. -Solution: +**Solution:** def removeDuplicate( li ): newli=[] @@ -2228,15 +2224,15 @@ li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) -#----------------------------------------# -Question: +* * * +**Question:** 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: +**Hints:** Use Subclass(Parentclass) to define a child class. -Solution: +**Solution:** class Person(object): def getGender( self ): @@ -2257,8 +2253,8 @@ print aFemale.getGender() -#----------------------------------------# -Question: +* * * +**Question:** Please write a program which count and print the numbers of each character in a string input by console. @@ -2277,11 +2273,11 @@ d,1 g,1 f,1 -Hints: +**Hints:** Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value. -Solution: +**Solution:** dic = {} s=raw_input() @@ -2289,9 +2285,9 @@ for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) -#----------------------------------------# +* * * -Question: +**Question:** Please write a program which accepts a string from console and print it in reverse order. @@ -2304,18 +2300,18 @@ Then, the output of the program should be: ris etov ot esir -Hints: +**Hints:** Use list[::-1] to iterate a list in a reverse order. -Solution: +**Solution:** s=raw_input() s = s[::-1] print s -#----------------------------------------# +* * * -Question: +**Question:** Please write a program which accepts a string from console and print the characters that have even indexes. @@ -2328,32 +2324,32 @@ Then, the output of the program should be: Helloworld -Hints: +**Hints:** Use list[::2] to iterate a list by step 2. -Solution: +**Solution:** s=raw_input() s = s[::2] print s -#----------------------------------------# +* * * -Question: +**Question:** Please write a program which prints all permutations of [1,2,3] -Hints: +**Hints:** Use itertools.permutations() to get permutations of list. -Solution: +**Solution:** import itertools print list(itertools.permutations([1,2,3])) -#----------------------------------------# -Question: +* * * +**Question:** 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? @@ -2361,7 +2357,7 @@ We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many Hint: Use for loop to iterate all possible solutions. -Solution: +**Solution:** def solve(numheads,numlegs): ns='No solutions!' @@ -2376,5 +2372,4 @@ numlegs=94 solutions=solve(numheads,numlegs) print solutions -#----------------------------------------# - +* * * From 243150f3b13bddc788fd62e22fd86352ba064307 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:29:29 -0700 Subject: [PATCH 07/17] Update README.md --- README.md | 423 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 240 insertions(+), 183 deletions(-) diff --git a/README.md b/README.md index e148b921..1b6cd9dd 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,8 @@ The numbers obtained should be printed in a comma-separated sequence on a single **Hints:** Consider use range(#begin, #end) method -**Solution:** +**Solution:** + l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): @@ -60,7 +61,8 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + def fact(x): if x == 0: return 1 @@ -70,9 +72,8 @@ x=int(raw_input()) print fact(x) * * * -* * * - -**Question:** + + *** **Question:** 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 @@ -83,7 +84,8 @@ Then, the output should be: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() -**Solution:** +**Solution:** + n=int(raw_input()) d=dict() for i in range(1,n+1): @@ -92,9 +94,8 @@ for i in range(1,n+1): print d * * * -* * * - -**Question:** + + *** **Question:** 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 @@ -106,7 +107,8 @@ Then, the output should be: 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 -**Solution:** +**Solution:** + values=raw_input() l=values.split(",") t=tuple(l) @@ -114,8 +116,8 @@ print l print t * * * -* * * -**Question:** + + *** **Question:** 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. @@ -124,7 +126,8 @@ Also please include simple test function to test the class methods. **Hints:** Use __init__ method to construct some parameters -**Solution:** +**Solution:** + class InputOutString(object): def __init__(self): self.s = "" @@ -141,9 +144,8 @@ strObj.printString() * * * #### Level 2 -* * * - -**Question:** + + *** **Question:** 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: @@ -159,7 +161,8 @@ The output of the program should be: 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. -**Solution:** +**Solution:** + #!/usr/bin/env python import math c=50 @@ -188,7 +191,8 @@ Then, the output of the program should be: **Hints:** Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. -**Solution:** +**Solution:** + input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] @@ -216,7 +220,8 @@ bag,hello,without,world **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) @@ -238,7 +243,8 @@ PRACTICE MAKES PERFECT **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + lines = [] while True: s = raw_input() @@ -266,7 +272,8 @@ again and hello makes perfect practice world 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. -**Solution:** +**Solution:** + s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) @@ -287,7 +294,8 @@ 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. -**Solution:** +**Solution:** + value = [] items=[x for x in raw_input().split(',')] for p in items: @@ -309,7 +317,8 @@ The numbers obtained should be printed in a comma-separated sequence on a single **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + values = [] for i in range(1000, 3001): s = str(i) @@ -333,7 +342,8 @@ DIGITS 3 **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: @@ -362,7 +372,8 @@ LOWER CASE 9 **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: @@ -390,7 +401,8 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) @@ -413,7 +425,8 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) @@ -439,7 +452,8 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + import sys netAmount = 0 while True: @@ -552,7 +566,8 @@ Define a class with a generator which can iterate the numbers, which are divisib **Hints:** Consider use yield -**Solution:** +**Solution:** + def putNumbers(n): i = 0 while i import math pos = [0,0] while True: @@ -637,7 +653,8 @@ to:1 Hints In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + freq = {} # frequency of words in text line = raw_input() for word in line.split(): @@ -660,7 +677,8 @@ for w in words: **Hints:** Using the ** operator -**Solution:** +**Solution:** + def square(num): return num ** 2 @@ -680,7 +698,8 @@ print square(3) **Hints:** The built-in document method is __doc__ -**Solution:** +**Solution:** + print abs.__doc__ print int.__doc__ print raw_input.__doc__ @@ -707,7 +726,8 @@ print square.__doc__ Define a instance parameter, need add it in __init__ method You can init a object with construct parameter or set the value later -**Solution:** +**Solution:** + class Person: # Define the class parameter "name" name = "Person" @@ -724,8 +744,8 @@ nico.name = "Nico" print "%s name is %s" % (Person.name, nico.name) * * * -* * * -**Question:** + + *** **Question:** Define a function which can compute the sum of two numbers. **Hints:** @@ -737,8 +757,8 @@ def SumFunction(number1, number2): print SumFunction(1,2) -* * * -**Question:** + + *** **Question:** Define a function that can convert a integer into a string and print it in console. **Hints:** @@ -752,8 +772,8 @@ def printValue(n): printValue(3) -* * * -**Question:** + + *** **Question:** Define a function that can convert a integer into a string and print it in console. **Hints:** @@ -1246,7 +1266,8 @@ Define a class named American and its subclass NewYorker. Use class Subclass(ParentClass) to define a subclass. -**Solution:** +**Solution:** + class American(object): pass @@ -1274,7 +1295,8 @@ Define a class named Circle which can be constructed by a radius. The Circle cla Use def methodName(self) to define a method. -**Solution:** +**Solution:** + class Circle(object): def __init__(self, r): @@ -1301,7 +1323,8 @@ Define a class named Rectangle which can be constructed by a length and width. T Use def methodName(self) to define a method. -**Solution:** +**Solution:** + class Rectangle(object): def __init__(self, l, w): @@ -1327,7 +1350,8 @@ Define a class named Shape and its subclass Square. The Square class has an init To override a method in super class, we can define a method with the same name in the super class. -**Solution:** +**Solution:** + class Shape(object): def __init__(self): @@ -1363,7 +1387,8 @@ Please raise a RuntimeError exception. Use raise() to raise an exception. -**Solution:** +**Solution:** + raise RuntimeError('something wrong') @@ -1376,7 +1401,8 @@ Write a function to compute 5/0 and use try/except to catch the exceptions. Use try/except to catch exceptions. -**Solution:** +**Solution:** + def throws(): return 5/0 @@ -1398,7 +1424,8 @@ Define a custom exception class which takes a string message as attribute. To define a custom exception, we need to define a class inherited from Exception. -**Solution:** +**Solution:** + class MyError(Exception): """My own exception class @@ -1412,8 +1439,8 @@ class MyError(Exception): error = MyError("something wrong") -* * * -**Question:** + + *** **Question:** 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. @@ -1432,7 +1459,8 @@ In case of input data being supplied to the question, it should be assumed to be Use \w to match letters. -**Solution:** +**Solution:** + import re emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" @@ -1440,8 +1468,8 @@ r2 = re.match(pat2,emailAddress) print r2.group(1) -* * * -**Question:** + + *** **Question:** 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. @@ -1460,7 +1488,8 @@ In case of input data being supplied to the question, it should be assumed to be Use \w to match letters. -**Solution:** +**Solution:** + import re emailAddress = raw_input() pat2 = "(\w+)@(\w+)\.(com)" @@ -1470,8 +1499,8 @@ print r2.group(2) -* * * -**Question:** + + *** **Question:** Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. @@ -1490,14 +1519,15 @@ In case of input data being supplied to the question, it should be assumed to be Use re.findall() to find all substring using regex. -**Solution:** +**Solution:** + import re s = raw_input() print re.findall("\d+",s) -* * * -**Question:** + + *** **Question:** Print a unicode string "hello world". @@ -1506,7 +1536,8 @@ Print a unicode string "hello world". Use u'strings' format to define unicode string. -**Solution:** +**Solution:** + unicodeString = u"hello world!" print unicodeString @@ -1518,25 +1549,27 @@ Write a program to read an ASCII string and to convert it to a unicode string en Use unicode() function to convert. -**Solution:** +**Solution:** + s = raw_input() u = unicode( s ,"utf-8") print u -* * * -**Question:** + + *** **Question:** Write a special comment to indicate a Python source code file is in unicode. **Hints:** -**Solution:** +**Solution:** + # -*- coding: utf-8 -*- -* * * -**Question:** + + *** **Question:** Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). @@ -1554,7 +1587,8 @@ In case of input data being supplied to the question, it should be assumed to be **Hints:** Use float() to convert an integer to a float -**Solution:** +**Solution:** + n=int(raw_input()) sum=0.0 @@ -1563,8 +1597,8 @@ for i in range(1,n+1): print sum -* * * -**Question:** + + *** **Question:** Write a program to compute: @@ -1587,7 +1621,8 @@ In case of input data being supplied to the question, it should be assumed to be **Hints:** We can define recursive function in Python. -**Solution:** +**Solution:** + def f(n): if n==0: @@ -1598,9 +1633,8 @@ def f(n): n=int(raw_input()) print f(n) -* * * - -**Question:** + + *** **Question:** The Fibonacci Sequence is computed based on the following formula: @@ -1627,7 +1661,8 @@ In case of input data being supplied to the question, it should be assumed to be We can define recursive function in Python. -**Solution:** +**Solution:** + def f(n): if n == 0: return 0 @@ -1640,9 +1675,8 @@ print f(n) * * * -* * * - -**Question:** + + *** **Question:** The Fibonacci Sequence is computed based on the following formula: @@ -1670,7 +1704,8 @@ Use string.join() to join a list of strings. In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** +**Solution:** + def f(n): if n == 0: return 0 @@ -1682,9 +1717,8 @@ values = [str(f(x)) for x in range(0, n+1)] print ",".join(values) -* * * - -**Question:** + + *** **Question:** 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. @@ -1702,7 +1736,8 @@ 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. -**Solution:** +**Solution:** + def EvenGenerator(n): i=0 @@ -1720,9 +1755,8 @@ for i in EvenGenerator(n): print ",".join(values) -* * * - -**Question:** + + *** **Question:** 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. @@ -1740,7 +1774,8 @@ 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. -**Solution:** +**Solution:** + def NumGenerator(n): for i in range(n+1): @@ -1755,9 +1790,8 @@ for i in NumGenerator(n): print ",".join(values) -* * * - -**Question:** + + *** **Question:** Please write assert statements to verify that every number in the list [2,4,6,8] is even. @@ -1768,15 +1802,16 @@ Please write assert statements to verify that every number in the list [2,4,6,8] Use "assert expression" to make assertion. -**Solution:** +**Solution:** + li = [2,4,6,8] for i in li: assert i%2==0 -* * * -**Question:** + + *** **Question:** Please write a program which accepts basic mathematic expression from console and print the evaluation result. @@ -1793,14 +1828,15 @@ Then, the output of the program should be: Use eval() to evaluate an expression. -**Solution:** +**Solution:** + expression = raw_input() print eval(expression) -* * * -**Question:** + + *** **Question:** 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. @@ -1809,7 +1845,8 @@ Please write a binary search function which searches an item in a sorted list. T Use if/elif to deal with conditions. -**Solution:** +**Solution:** + import math def bin_search(li, element): @@ -1834,8 +1871,8 @@ print bin_search(li,12) -* * * -**Question:** + + *** **Question:** 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. @@ -1844,7 +1881,8 @@ Please write a binary search function which searches an item in a sorted list. T Use if/elif to deal with conditions. -**Solution:** +**Solution:** + import math def bin_search(li, element): @@ -1869,8 +1907,8 @@ print bin_search(li,12) -* * * -**Question:** + + *** **Question:** Please generate a random float where the value is between 10 and 100 using Python math module. @@ -1880,13 +1918,14 @@ Please generate a random float where the value is between 10 and 100 using Pytho Use random.random() to generate a random float in [0,1]. -**Solution:** +**Solution:** + import random print random.random()*100 -* * * -**Question:** + + *** **Question:** Please generate a random float where the value is between 5 and 95 using Python math module. @@ -1896,14 +1935,15 @@ Please generate a random float where the value is between 5 and 95 using Python Use random.random() to generate a random float in [0,1]. -**Solution:** +**Solution:** + import random print random.random()*100-5 -* * * -**Question:** + + *** **Question:** Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. @@ -1913,14 +1953,15 @@ Please write a program to output a random even number between 0 and 10 inclusive Use random.choice() to a random element from a list. -**Solution:** +**Solution:** + import random print random.choice([i for i in range(11) if i%2==0]) -* * * -**Question:** + + *** **Question:** 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. @@ -1930,16 +1971,16 @@ Please write a program to output a random number, which is divisible by 5 and 7, Use random.choice() to a random element from a list. -**Solution:** +**Solution:** + import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) -* * * - -**Question:** + + *** **Question:** Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. @@ -1949,13 +1990,14 @@ Please write a program to generate a list with 5 random numbers between 100 and Use random.sample() to generate a list of random values. -**Solution:** +**Solution:** + import random print random.sample(range(100), 5) -* * * -**Question:** + + *** **Question:** Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. @@ -1965,14 +2007,15 @@ Please write a program to randomly generate a list with 5 even numbers between 1 Use random.sample() to generate a list of random values. -**Solution:** +**Solution:** + import random print random.sample([i for i in range(100,201) if i%2==0], 5) -* * * -**Question:** + + *** **Question:** Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. @@ -1982,14 +2025,14 @@ Please write a program to randomly generate a list with 5 numbers, which are div Use random.sample() to generate a list of random values. -**Solution:** +**Solution:** + import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) -* * * - -**Question:** + + *** **Question:** Please write a program to randomly print a integer number between 7 and 15 inclusive. @@ -1999,14 +2042,14 @@ Please write a program to randomly print a integer number between 7 and 15 inclu Use random.randrange() to a random integer in a given range. -**Solution:** +**Solution:** + import random print random.randrange(7,16) -* * * - -**Question:** + + *** **Question:** Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". @@ -2016,7 +2059,8 @@ Please write a program to compress and decompress the string "hello world!hello Use zlib.compress() and zlib.decompress() to compress and decompress a string. -**Solution:** +**Solution:** + import zlib s = 'hello world!hello world!hello world!hello world!' @@ -2024,8 +2068,8 @@ t = zlib.compress(s) print t print zlib.decompress(t) -* * * -**Question:** + + *** **Question:** Please write a program to print the running time of execution of "1+1" for 100 times. @@ -2034,14 +2078,15 @@ Please write a program to print the running time of execution of "1+1" for 100 t **Hints:** Use timeit() function to measure the running time. -**Solution:** +**Solution:** + from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() -* * * -**Question:** + + *** **Question:** Please write a program to shuffle and print the list [3,6,7,8]. @@ -2050,15 +2095,16 @@ Please write a program to shuffle and print the list [3,6,7,8]. **Hints:** Use shuffle() function to shuffle a list. -**Solution:** +**Solution:** + from random import shuffle li = [3,6,7,8] shuffle(li) print li -* * * -**Question:** + + *** **Question:** Please write a program to shuffle and print the list [3,6,7,8]. @@ -2067,7 +2113,8 @@ Please write a program to shuffle and print the list [3,6,7,8]. **Hints:** Use shuffle() function to shuffle a list. -**Solution:** +**Solution:** + from random import shuffle li = [3,6,7,8] @@ -2076,15 +2123,16 @@ print li -* * * -**Question:** + + *** **Question:** 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. -**Solution:** +**Solution:** + subjects=["I", "You"] verbs=["Play", "Love"] @@ -2102,29 +2150,31 @@ Please write a program to print the list after removing delete even numbers in [ **Hints:** Use list comprehension to delete a bunch of element from a list. -**Solution:** +**Solution:** + li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li -* * * -**Question:** + + *** **Question:** 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. -**Solution:** +**Solution:** + li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print li -* * * -**Question:** + + *** **Question:** 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]. @@ -2132,28 +2182,29 @@ By using list comprehension, please write a program to print the list after remo Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. -**Solution:** +**Solution:** + li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li -* * * - -**Question:** + + *** **Question:** 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. -**Solution:** +**Solution:** + array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array -* * * -**Question:** + + *** **Question:** 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]. @@ -2161,7 +2212,8 @@ By using list comprehension, please write a program to print the list after remo Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. -**Solution:** +**Solution:** + li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] @@ -2169,31 +2221,32 @@ print li -* * * - -**Question:** + + *** **Question:** 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. -**Solution:** +**Solution:** + li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print li -* * * -**Question:** + + *** **Question:** 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. -**Solution:** +**Solution:** + set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) @@ -2208,7 +2261,8 @@ With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print **Hints:** Use set() to store a number of values without duplicate. -**Solution:** +**Solution:** + def removeDuplicate( li ): newli=[] @@ -2224,15 +2278,16 @@ li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) -* * * -**Question:** + + *** **Question:** 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. -**Solution:** +**Solution:** + class Person(object): def getGender( self ): @@ -2251,10 +2306,8 @@ aFemale= Female() print aMale.getGender() print aFemale.getGender() - - -* * * -**Question:** + + *** **Question:** Please write a program which count and print the numbers of each character in a string input by console. @@ -2277,7 +2330,8 @@ f,1 Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value. -**Solution:** +**Solution:** + dic = {} s=raw_input() @@ -2285,9 +2339,8 @@ for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) -* * * - -**Question:** + + *** **Question:** Please write a program which accepts a string from console and print it in reverse order. @@ -2303,15 +2356,15 @@ ris etov ot esir **Hints:** Use list[::-1] to iterate a list in a reverse order. -**Solution:** +**Solution:** + s=raw_input() s = s[::-1] print s -* * * - -**Question:** + + *** **Question:** Please write a program which accepts a string from console and print the characters that have even indexes. @@ -2327,7 +2380,8 @@ Helloworld **Hints:** Use list[::2] to iterate a list by step 2. -**Solution:** +**Solution:** + s=raw_input() s = s[::2] @@ -2343,13 +2397,15 @@ Please write a program which prints all permutations of [1,2,3] **Hints:** Use itertools.permutations() to get permutations of list. -**Solution:** +**Solution:** + import itertools print list(itertools.permutations([1,2,3])) -* * * -**Question:** + + *** + **Question:** 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? @@ -2357,7 +2413,8 @@ We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many Hint: Use for loop to iterate all possible solutions. -**Solution:** +**Solution:** + def solve(numheads,numlegs): ns='No solutions!' @@ -2371,5 +2428,5 @@ numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions - + * * * From e224e5fe0c7b33bbd83f576852ac14f32475fa90 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:33:00 -0700 Subject: [PATCH 08/17] Update README.md --- README.md | 444 +++++++++++++++++++++++------------------------------- 1 file changed, 185 insertions(+), 259 deletions(-) diff --git a/README.md b/README.md index 1b6cd9dd..f81ed58c 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,7 @@ The numbers obtained should be printed in a comma-separated sequence on a single **Hints:** Consider use range(#begin, #end) method -**Solution:** - +**Solution:** l=[] for i in range(2000, 3201): if (i%7==0) and (i%5!=0): @@ -61,8 +60,7 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** def fact(x): if x == 0: return 1 @@ -72,8 +70,9 @@ x=int(raw_input()) print fact(x) * * * - - *** **Question:** +* * * + +**Question:** 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 @@ -84,8 +83,7 @@ Then, the output should be: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() -**Solution:** - +**Solution:** n=int(raw_input()) d=dict() for i in range(1,n+1): @@ -94,8 +92,9 @@ for i in range(1,n+1): print d * * * - - *** **Question:** +* * * + +**Question:** 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 @@ -107,8 +106,7 @@ Then, the output should be: 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 -**Solution:** - +**Solution:** values=raw_input() l=values.split(",") t=tuple(l) @@ -116,8 +114,8 @@ print l print t * * * - - *** **Question:** +* * * +**Question:** 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. @@ -126,8 +124,7 @@ Also please include simple test function to test the class methods. **Hints:** Use __init__ method to construct some parameters -**Solution:** - +**Solution:** class InputOutString(object): def __init__(self): self.s = "" @@ -144,8 +141,9 @@ strObj.printString() * * * #### Level 2 - - *** **Question:** +* * * + +**Question:** 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: @@ -161,8 +159,7 @@ The output of the program should be: 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. -**Solution:** - +**Solution:** #!/usr/bin/env python import math c=50 @@ -191,8 +188,7 @@ Then, the output of the program should be: **Hints:** Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. -**Solution:** - +**Solution:** input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] @@ -220,8 +216,7 @@ bag,hello,without,world **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) @@ -243,8 +238,7 @@ PRACTICE MAKES PERFECT **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** lines = [] while True: s = raw_input() @@ -272,8 +266,7 @@ again and hello makes perfect practice world 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. -**Solution:** - +**Solution:** s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) @@ -294,8 +287,7 @@ 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. -**Solution:** - +**Solution:** value = [] items=[x for x in raw_input().split(',')] for p in items: @@ -317,8 +309,7 @@ The numbers obtained should be printed in a comma-separated sequence on a single **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** values = [] for i in range(1000, 3001): s = str(i) @@ -342,8 +333,7 @@ DIGITS 3 **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: @@ -372,8 +362,7 @@ LOWER CASE 9 **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: @@ -401,8 +390,7 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** a = raw_input() n1 = int( "%s" % a ) n2 = int( "%s%s" % (a,a) ) @@ -425,8 +413,7 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) @@ -452,8 +439,7 @@ Then, the output should be: **Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** import sys netAmount = 0 while True: @@ -566,8 +552,7 @@ Define a class with a generator which can iterate the numbers, which are divisib **Hints:** Consider use yield -**Solution:** - +**Solution:** def putNumbers(n): i = 0 while i +**Solution:** import math pos = [0,0] while True: @@ -653,8 +637,7 @@ to:1 Hints In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** freq = {} # frequency of words in text line = raw_input() for word in line.split(): @@ -677,8 +660,7 @@ for w in words: **Hints:** Using the ** operator -**Solution:** - +**Solution:** def square(num): return num ** 2 @@ -698,8 +680,7 @@ print square(3) **Hints:** The built-in document method is __doc__ -**Solution:** - +**Solution:** print abs.__doc__ print int.__doc__ print raw_input.__doc__ @@ -726,8 +707,7 @@ print square.__doc__ Define a instance parameter, need add it in __init__ method You can init a object with construct parameter or set the value later -**Solution:** - +**Solution:** class Person: # Define the class parameter "name" name = "Person" @@ -744,8 +724,8 @@ nico.name = "Nico" print "%s name is %s" % (Person.name, nico.name) * * * - - *** **Question:** +* * * +**Question:** Define a function which can compute the sum of two numbers. **Hints:** @@ -757,8 +737,8 @@ def SumFunction(number1, number2): print SumFunction(1,2) - - *** **Question:** +* * * +**Question:** Define a function that can convert a integer into a string and print it in console. **Hints:** @@ -772,8 +752,8 @@ def printValue(n): printValue(3) - - *** **Question:** +* * * +**Question:** Define a function that can convert a integer into a string and print it in console. **Hints:** @@ -1266,8 +1246,7 @@ Define a class named American and its subclass NewYorker. Use class Subclass(ParentClass) to define a subclass. -**Solution:** - +**Solution:** class American(object): pass @@ -1295,8 +1274,7 @@ Define a class named Circle which can be constructed by a radius. The Circle cla Use def methodName(self) to define a method. -**Solution:** - +**Solution:** class Circle(object): def __init__(self, r): @@ -1323,8 +1301,7 @@ Define a class named Rectangle which can be constructed by a length and width. T Use def methodName(self) to define a method. -**Solution:** - +**Solution:** class Rectangle(object): def __init__(self, l, w): @@ -1350,8 +1327,7 @@ Define a class named Shape and its subclass Square. The Square class has an init To override a method in super class, we can define a method with the same name in the super class. -**Solution:** - +**Solution:** class Shape(object): def __init__(self): @@ -1387,8 +1363,7 @@ Please raise a RuntimeError exception. Use raise() to raise an exception. -**Solution:** - +**Solution:** raise RuntimeError('something wrong') @@ -1401,8 +1376,7 @@ Write a function to compute 5/0 and use try/except to catch the exceptions. Use try/except to catch exceptions. -**Solution:** - +**Solution:** def throws(): return 5/0 @@ -1424,8 +1398,7 @@ Define a custom exception class which takes a string message as attribute. To define a custom exception, we need to define a class inherited from Exception. -**Solution:** - +**Solution:** class MyError(Exception): """My own exception class @@ -1439,8 +1412,8 @@ class MyError(Exception): error = MyError("something wrong") - - *** **Question:** +* * * +**Question:** 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. @@ -1459,8 +1432,7 @@ In case of input data being supplied to the question, it should be assumed to be Use \w to match letters. -**Solution:** - +**Solution:** import re emailAddress = raw_input() pat2 = "(\w+)@((\w+\.)+(com))" @@ -1468,8 +1440,8 @@ r2 = re.match(pat2,emailAddress) print r2.group(1) - - *** **Question:** +* * * +**Question:** 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. @@ -1488,8 +1460,7 @@ In case of input data being supplied to the question, it should be assumed to be Use \w to match letters. -**Solution:** - +**Solution:** import re emailAddress = raw_input() pat2 = "(\w+)@(\w+)\.(com)" @@ -1499,8 +1470,8 @@ print r2.group(2) - - *** **Question:** +* * * +**Question:** Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only. @@ -1519,15 +1490,14 @@ In case of input data being supplied to the question, it should be assumed to be Use re.findall() to find all substring using regex. -**Solution:** - +**Solution:** import re s = raw_input() print re.findall("\d+",s) - - *** **Question:** +* * * +**Question:** Print a unicode string "hello world". @@ -1536,8 +1506,7 @@ Print a unicode string "hello world". Use u'strings' format to define unicode string. -**Solution:** - +**Solution:** unicodeString = u"hello world!" print unicodeString @@ -1549,27 +1518,25 @@ Write a program to read an ASCII string and to convert it to a unicode string en Use unicode() function to convert. -**Solution:** - +**Solution:** s = raw_input() u = unicode( s ,"utf-8") print u - - *** **Question:** +* * * +**Question:** Write a special comment to indicate a Python source code file is in unicode. **Hints:** -**Solution:** - +**Solution:** # -*- coding: utf-8 -*- - - *** **Question:** +* * * +**Question:** Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). @@ -1587,8 +1554,7 @@ In case of input data being supplied to the question, it should be assumed to be **Hints:** Use float() to convert an integer to a float -**Solution:** - +**Solution:** n=int(raw_input()) sum=0.0 @@ -1597,8 +1563,8 @@ for i in range(1,n+1): print sum - - *** **Question:** +* * * +**Question:** Write a program to compute: @@ -1621,8 +1587,7 @@ In case of input data being supplied to the question, it should be assumed to be **Hints:** We can define recursive function in Python. -**Solution:** - +**Solution:** def f(n): if n==0: @@ -1633,8 +1598,9 @@ def f(n): n=int(raw_input()) print f(n) - - *** **Question:** +* * * + +**Question:** The Fibonacci Sequence is computed based on the following formula: @@ -1661,8 +1627,7 @@ In case of input data being supplied to the question, it should be assumed to be We can define recursive function in Python. -**Solution:** - +**Solution:** def f(n): if n == 0: return 0 @@ -1675,8 +1640,9 @@ print f(n) * * * - - *** **Question:** +* * * + +**Question:** The Fibonacci Sequence is computed based on the following formula: @@ -1704,8 +1670,7 @@ Use string.join() to join a list of strings. In case of input data being supplied to the question, it should be assumed to be a console input. -**Solution:** - +**Solution:** def f(n): if n == 0: return 0 @@ -1717,8 +1682,9 @@ values = [str(f(x)) for x in range(0, n+1)] print ",".join(values) - - *** **Question:** +* * * + +**Question:** 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. @@ -1736,8 +1702,7 @@ 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. -**Solution:** - +**Solution:** def EvenGenerator(n): i=0 @@ -1755,8 +1720,9 @@ for i in EvenGenerator(n): print ",".join(values) - - *** **Question:** +* * * + +**Question:** 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. @@ -1774,8 +1740,7 @@ 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. -**Solution:** - +**Solution:** def NumGenerator(n): for i in range(n+1): @@ -1788,31 +1753,19 @@ for i in NumGenerator(n): values.append(str(i)) print ",".join(values) +* * * - - - *** **Question:** - - +**Question:** 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. - - -**Solution:** - +**Solution:** li = [2,4,6,8] for i in li: assert i%2==0 - - - - *** **Question:** - +* * * +**Question:** Please write a program which accepts basic mathematic expression from console and print the evaluation result. Example: @@ -1828,15 +1781,14 @@ Then, the output of the program should be: Use eval() to evaluate an expression. -**Solution:** - +**Solution:** expression = raw_input() print eval(expression) - - *** **Question:** +* * * +**Question:** 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. @@ -1845,8 +1797,7 @@ Please write a binary search function which searches an item in a sorted list. T Use if/elif to deal with conditions. -**Solution:** - +**Solution:** import math def bin_search(li, element): @@ -1871,8 +1822,8 @@ print bin_search(li,12) - - *** **Question:** +* * * +**Question:** 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. @@ -1881,8 +1832,7 @@ Please write a binary search function which searches an item in a sorted list. T Use if/elif to deal with conditions. -**Solution:** - +**Solution:** import math def bin_search(li, element): @@ -1907,8 +1857,8 @@ print bin_search(li,12) - - *** **Question:** +* * * +**Question:** Please generate a random float where the value is between 10 and 100 using Python math module. @@ -1918,14 +1868,13 @@ Please generate a random float where the value is between 10 and 100 using Pytho Use random.random() to generate a random float in [0,1]. -**Solution:** - +**Solution:** import random print random.random()*100 - - *** **Question:** +* * * +**Question:** Please generate a random float where the value is between 5 and 95 using Python math module. @@ -1935,15 +1884,14 @@ Please generate a random float where the value is between 5 and 95 using Python Use random.random() to generate a random float in [0,1]. -**Solution:** - +**Solution:** import random print random.random()*100-5 - - *** **Question:** +* * * +**Question:** Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. @@ -1953,15 +1901,14 @@ Please write a program to output a random even number between 0 and 10 inclusive Use random.choice() to a random element from a list. -**Solution:** - +**Solution:** import random print random.choice([i for i in range(11) if i%2==0]) - - *** **Question:** +* * * +**Question:** 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. @@ -1971,16 +1918,16 @@ Please write a program to output a random number, which is divisible by 5 and 7, Use random.choice() to a random element from a list. -**Solution:** - +**Solution:** import random print random.choice([i for i in range(201) if i%5==0 and i%7==0]) - - *** **Question:** +* * * + +**Question:** Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive. @@ -1990,14 +1937,13 @@ Please write a program to generate a list with 5 random numbers between 100 and Use random.sample() to generate a list of random values. -**Solution:** - +**Solution:** import random print random.sample(range(100), 5) - - *** **Question:** +* * * +**Question:** Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. @@ -2007,15 +1953,14 @@ Please write a program to randomly generate a list with 5 even numbers between 1 Use random.sample() to generate a list of random values. -**Solution:** - +**Solution:** import random print random.sample([i for i in range(100,201) if i%2==0], 5) - - *** **Question:** +* * * +**Question:** Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. @@ -2025,14 +1970,14 @@ Please write a program to randomly generate a list with 5 numbers, which are div Use random.sample() to generate a list of random values. -**Solution:** - +**Solution:** import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) - - *** **Question:** +* * * + +**Question:** Please write a program to randomly print a integer number between 7 and 15 inclusive. @@ -2042,14 +1987,14 @@ Please write a program to randomly print a integer number between 7 and 15 inclu Use random.randrange() to a random integer in a given range. -**Solution:** - +**Solution:** import random print random.randrange(7,16) - - *** **Question:** +* * * + +**Question:** Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!". @@ -2059,8 +2004,7 @@ Please write a program to compress and decompress the string "hello world!hello Use zlib.compress() and zlib.decompress() to compress and decompress a string. -**Solution:** - +**Solution:** import zlib s = 'hello world!hello world!hello world!hello world!' @@ -2068,8 +2012,8 @@ t = zlib.compress(s) print t print zlib.decompress(t) - - *** **Question:** +* * * +**Question:** Please write a program to print the running time of execution of "1+1" for 100 times. @@ -2078,15 +2022,14 @@ Please write a program to print the running time of execution of "1+1" for 100 t **Hints:** Use timeit() function to measure the running time. -**Solution:** - +**Solution:** from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() - - *** **Question:** +* * * +**Question:** Please write a program to shuffle and print the list [3,6,7,8]. @@ -2095,16 +2038,15 @@ Please write a program to shuffle and print the list [3,6,7,8]. **Hints:** Use shuffle() function to shuffle a list. -**Solution:** - +**Solution:** from random import shuffle li = [3,6,7,8] shuffle(li) print li - - *** **Question:** +* * * +**Question:** Please write a program to shuffle and print the list [3,6,7,8]. @@ -2113,8 +2055,7 @@ Please write a program to shuffle and print the list [3,6,7,8]. **Hints:** Use shuffle() function to shuffle a list. -**Solution:** - +**Solution:** from random import shuffle li = [3,6,7,8] @@ -2123,16 +2064,15 @@ print li - - *** **Question:** +* * * +**Question:** 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. -**Solution:** - +**Solution:** subjects=["I", "You"] verbs=["Play", "Love"] @@ -2150,31 +2090,29 @@ Please write a program to print the list after removing delete even numbers in [ **Hints:** Use list comprehension to delete a bunch of element from a list. -**Solution:** - +**Solution:** li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li - - *** **Question:** +* * * +**Question:** 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. -**Solution:** - +**Solution:** li = [12,24,35,70,88,120,155] li = [x for x in li if x%5!=0 and x%7!=0] print li - - *** **Question:** +* * * +**Question:** 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]. @@ -2182,29 +2120,28 @@ By using list comprehension, please write a program to print the list after remo Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. -**Solution:** - +**Solution:** li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li - - *** **Question:** +* * * + +**Question:** 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. -**Solution:** - +**Solution:** array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array - - *** **Question:** +* * * +**Question:** 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]. @@ -2212,8 +2149,7 @@ By using list comprehension, please write a program to print the list after remo Use list comprehension to delete a bunch of element from a list. Use enumerate() to get (index, value) tuple. -**Solution:** - +**Solution:** li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i not in (0,4,5)] @@ -2221,32 +2157,31 @@ print li - - *** **Question:** +* * * + +**Question:** 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. -**Solution:** - +**Solution:** li = [12,24,35,24,88,120,155] li = [x for x in li if x!=24] print li - - *** **Question:** +* * * +**Question:** 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. -**Solution:** - +**Solution:** set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) @@ -2261,8 +2196,7 @@ With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print **Hints:** Use set() to store a number of values without duplicate. -**Solution:** - +**Solution:** def removeDuplicate( li ): newli=[] @@ -2278,16 +2212,15 @@ li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) - - *** **Question:** +* * * +**Question:** 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. -**Solution:** - +**Solution:** class Person(object): def getGender( self ): @@ -2306,8 +2239,10 @@ aFemale= Female() print aMale.getGender() print aFemale.getGender() - - *** **Question:** + + +* * * +**Question:** Please write a program which count and print the numbers of each character in a string input by console. @@ -2330,8 +2265,7 @@ f,1 Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value. -**Solution:** - +**Solution:** dic = {} s=raw_input() @@ -2339,8 +2273,9 @@ for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) - - *** **Question:** +* * * + +**Question:** Please write a program which accepts a string from console and print it in reverse order. @@ -2356,15 +2291,15 @@ ris etov ot esir **Hints:** Use list[::-1] to iterate a list in a reverse order. -**Solution:** - +**Solution:** s=raw_input() s = s[::-1] print s - - *** **Question:** +* * * + +**Question:** Please write a program which accepts a string from console and print the characters that have even indexes. @@ -2380,42 +2315,33 @@ Helloworld **Hints:** Use list[::2] to iterate a list by step 2. -**Solution:** - +**Solution:** s=raw_input() s = s[::2] print s * * * - - **Question:** - Please write a program which prints all permutations of [1,2,3] - **Hints:** Use itertools.permutations() to get permutations of list. -**Solution:** - - +**Solution:** + import itertools print list(itertools.permutations([1,2,3])) - - - *** - **Question:** - + +* * * +**Question:** 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? -Hint: +**Hint:** Use for loop to iterate all possible solutions. -**Solution:** - - +**Solution:** + def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): From ab90a85b3113a1b49dc95c28013de9a53d435f81 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:33:30 -0700 Subject: [PATCH 09/17] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f81ed58c..ebda85f2 100644 --- a/README.md +++ b/README.md @@ -2341,7 +2341,7 @@ We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many Use for loop to iterate all possible solutions. **Solution:** - +
 def solve(numheads,numlegs):
     ns='No solutions!'
     for i in range(numheads+1):
@@ -2354,5 +2354,5 @@ numheads=35
 numlegs=94
 solutions=solve(numheads,numlegs)
 print solutions
-
+
* * * From c4447ab96d98e92076e3b0236861ef1bf7827574 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:42:24 -0700 Subject: [PATCH 10/17] Create test.md --- test.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 test.md diff --git a/test.md b/test.md new file mode 100644 index 00000000..836df5d9 --- /dev/null +++ b/test.md @@ -0,0 +1,38 @@ +* * * +**Question:** +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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+def fact(x):
+    if x == 0:
+        return 1
+    return x * fact(x - 1)
+
+*** +**Question:** +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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+def fact(x):
+    if x == 0:
+        return 1
+    return x * fact(x - 1)
+
From 0dcd4122153fba166df59da9d1c00ecbaedff831 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:42:41 -0700 Subject: [PATCH 11/17] Update test.md --- test.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/test.md b/test.md index 836df5d9..398ac3c8 100644 --- a/test.md +++ b/test.md @@ -6,10 +6,8 @@ Suppose the following 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. - **Solution:**
 def fact(x):

From ec6644d8ec08b4cf504fa9a00b3758cfa5bae345 Mon Sep 17 00:00:00 2001
From: Om Prakash Manivannan 
Date: Tue, 4 Jul 2017 23:54:36 -0700
Subject: [PATCH 12/17] Update test.md

---
 test.md | 2275 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 2267 insertions(+), 8 deletions(-)

diff --git a/test.md b/test.md
index 398ac3c8..004a3a95 100644
--- a/test.md
+++ b/test.md
@@ -1,3 +1,47 @@
+# 100+ Python challenging programming exercises
+* * *
+## Table of Contents
+1. [Level description](#level-description)
+2. [Problem template](#problem-template)
+3. [Questions](#questions)
+	1. [Level 1](#level-1)
+	2. [Level 2](#level-2)
+	3. [Level 3](#level-3)
+
+### Level description
+
+| Level	| Description |
+|-------|-------------|
+|Level 1| Beginner means someone who has just gone through an introductory Python course. He 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 means someone who has just learned Python, but already has a relatively strong programming background from before. He 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 should use Python to solve more complex problem using more rich libraries functions and data structures and algorithms. He is supposed to solve the problem using several Python standard packages and advanced techniques.|
+
+### Problem template
+* Question
+* Hints
+* Solution
+
+### Questions
+
+#### Level 1
+* * *
+**Question:**
+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
+
+**Solution:** 
+ 
+
 l=[]
+for i in range(2000, 3201):
+    if (i%7==0) and (i%5!=0):
+        l.append(str(i))
+
+print ','.join(l)
+
* * * **Question:** Write a program which can compute the factorial of a given numbers. @@ -6,31 +50,2246 @@ Suppose the following 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. + **Solution:**
 def fact(x):
     if x == 0:
         return 1
     return x * fact(x - 1)
+
+x=int(raw_input())
+print fact(x)
 
-*** +* * * **Question:** -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. +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: -40320 +{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() + +**Solution:** +
+n=int(raw_input())
+d=dict()
+for i in range(1,n+1):
+    d[i]=i*i
+print d
+
+* * * +**Question:** +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 + +**Solution:** +
+values=raw_input()
+l=values.split(",")
+t=tuple(l)
+print l
+print t
+
+* * * +**Question:** +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. + +**Hints:** +Use __init__ method to construct some parameters + +**Solution:** +
+class InputOutString(object):
+    def __init__(self):
+        self.s = ""
+
+    def getString(self):
+        self.s = raw_input()
+
+    def printString(self):
+        print self.s.upper()
+
+strObj = InputOutString()
+strObj.getString()
+strObj.printString()
+
+* * * + +#### Level 2 +* * * +**Question:** +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 + +**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. **Solution:**
-def fact(x):
-    if x == 0:
-        return 1
-    return x * fact(x - 1)
+#!/usr/bin/env python
+import math
+c=50
+h=30
+value = []
+items=[x for x in raw_input().split(',')]
+for d in items:
+    value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
+
+print ','.join(value)
+
+* * * +**Question:** +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]] + +**Hints:** +Note: In case of input data being supplied to the question, it should be assumed to be a console input in a comma-separated form. + +**Solution:** +
+input_str = raw_input()
+dimensions=[int(x) for x in input_str.split(',')]
+rowNum=dimensions[0]
+colNum=dimensions[1]
+multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
+
+for row in range(rowNum):
+    for col in range(colNum):
+        multilist[row][col]= row*col
+
+print multilist
+
+* * * +**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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+items=[x for x in raw_input().split(',')]
+items.sort()
+print ','.join(items)
+
+* * * +Question: +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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+lines = []
+while True:
+    s = raw_input()
+    if s:
+        lines.append(s.upper())
+    else:
+        break;
+
+for sentence in lines:
+    print sentence
+
+ +* * * +**Question:** +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. + +**Solution:** +
+s = raw_input()
+words = [word for word in s.split(" ")]
+print " ".join(sorted(list(set(words))))
+
+* * * +**Question:** +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. + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+value = []
+items=[x for x in raw_input().split(',')]
+for p in items:
+    intp = int(p, 2)
+    if not intp%5:
+        value.append(p)
+
+print ','.join(value)
+
+* * * +**Question:** +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. + +**Solution:** +
+values = []
+for i in range(1000, 3001):
+    s = str(i)
+    if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0):
+        values.append(s)
+print ",".join(values)
+
+* * * +**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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+s = raw_input()
+d={"DIGITS":0, "LETTERS":0}
+for c in s:
+    if c.isdigit():
+        d["DIGITS"]+=1
+    elif c.isalpha():
+        d["LETTERS"]+=1
+    else:
+        pass
+print "LETTERS", d["LETTERS"]
+print "DIGITS", d["DIGITS"]
+
+ +* * * +**Question:** +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. + +**Solution:** +
+s = raw_input()
+d={"UPPER CASE":0, "LOWER CASE":0}
+for c in s:
+    if c.isupper():
+        d["UPPER CASE"]+=1
+    elif c.islower():
+        d["LOWER CASE"]+=1
+    else:
+        pass
+print "UPPER CASE", d["UPPER CASE"]
+print "LOWER CASE", d["LOWER CASE"]
+
+* * * +**Question:** +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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+a = raw_input()
+n1 = int( "%s" % a )
+n2 = int( "%s%s" % (a,a) )
+n3 = int( "%s%s%s" % (a,a,a) )
+n4 = int( "%s%s%s%s" % (a,a,a,a) )
+print n1+n2+n3+n4
+
+* * * +**Question:** +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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+values = raw_input()
+numbers = [x for x in values.split(",") if int(x)%2!=0]
+print ",".join(numbers)
+
+* * * +**Question:** +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 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+import sys
+netAmount = 0
+while True:
+    s = raw_input()
+    if not s:
+        break
+    values = s.split(" ")
+    operation = values[0]
+    amount = int(values[1])
+    if operation=="D":
+        netAmount+=amount
+    elif operation=="W":
+        netAmount-=amount
+    else:
+        pass
+print netAmount
+
+ +* * * + +#### Level 3 + +**Question:** +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: +ABd1234@1,a F1#,2w3E*,2We3345 +Then, the output of the program should be: +ABd1234@1 + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
:
+import re
+value = []
+items=[x for x in raw_input().split(',')]
+for p in items:
+    if len(p)<6 or len(p)>12:
+        continue
+    else:
+        pass
+    if not re.search("[a-z]",p):
+        continue
+    elif not re.search("[0-9]",p):
+        continue
+    elif not re.search("[A-Z]",p):
+        continue
+    elif not re.search("[$#@]",p):
+        continue
+    elif re.search("\s",p):
+        continue
+    else:
+        pass
+    value.append(p)
+print ",".join(value)
+
+ +* * * + +Level 3 + +**Question:** +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')] + +**Hints:** +In case of input data being supplied to the question, it should be assumed to be a console input. +We use itemgetter to enable multiple sort keys. + +**Solution:** +
:
+from operator import itemgetter, attrgetter
+
+l = []
+while True:
+    s = raw_input()
+    if not s:
+        break
+    l.append(tuple(s.split(",")))
+
+print sorted(l, key=itemgetter(0,1,2))
+
+ +* * * + +Level 3 + +**Question:** +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 + +**Solution:** +
+def putNumbers(n):
+    i = 0
+    while i
+
+* * *
+
+Level 3
+
+Question:
+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
+
+**Hints:**
+In case of input data being supplied to the question, it should be assumed to be a console input.
+
+**Solution:** 
+ 
+import math
+pos = [0,0]
+while True:
+    s = raw_input()
+    if not s:
+        break
+    movement = s.split(" ")
+    direction = movement[0]
+    steps = int(movement[1])
+    if direction=="UP":
+        pos[0]+=steps
+    elif direction=="DOWN":
+        pos[0]-=steps
+    elif direction=="LEFT":
+        pos[1]-=steps
+    elif direction=="RIGHT":
+        pos[1]+=steps
+    else:
+        pass
+
+print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
+
+ +* * * + +Level 3 + +**Question:** +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 + +Hints +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+freq = {}   # frequency of words in text
+line = raw_input()
+for word in line.split():
+    freq[word] = freq.get(word,0)+1
+
+words = freq.keys()
+words.sort()
+
+for w in words:
+    print "%s:%d" % (w,freq[w])
+
+ +* * * + + + +**Question:** + Write a method which can calculate square value of number + +**Hints:** + Using the ** operator + +**Solution:** +
+def square(num):
+    return num ** 2
+
+print square(2)
+print square(3)
+
+ +* * * + +**Question:** + 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__ + +**Solution:** +
+print abs.__doc__
+print int.__doc__
+print raw_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:** + 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 + +**Solution:** +
+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)
 
+* * * +**Question:** +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. + +**Solution:** +
+def SumFunction(number1, number2):
+	return number1+number2
+
+print SumFunction(1,2)
+
+* * * +**Question:** +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. + +Solution +def printValue(n): + print str(n) + +printValue(3) +
+* * * +**Question:** +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. + +**Solution:** +
+def printValue(n):
+	print str(n)
+
+printValue(3)
+
+* * * +**Question:** +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. + +**Solution:** +
+def printValue(s1,s2):
+	print int(s1)+int(s2)
+
+printValue("3","4") #7
+
+* * * + +**Question:** +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 + +**Solution:** +
+def printValue(s1,s2):
+	print s1+s2
+
+printValue("3","4") #34
+
+* * * +**Question:** +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 + +**Solution:** +
+def printValue(s1,s2):
+	len1 = len(s1)
+	len2 = len(s2)
+	if len1>len2:
+		print s1
+	elif len2>len1:
+		print s2
+	else:
+		print s1
+		print s2
+		
+
+printValue("one","three")
+
+* * * + + +**Question:** +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. + +**Solution:** +
+def checkValue(n):
+	if n%2 == 0:
+		print "It is an even number"
+	else:
+		print "It is an odd number"
+		
+
+checkValue(7)
+
+* * * + + +**Question:** +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. +Use ** operator to get power of a number. + +**Solution:** +
+def printDict():
+	d=dict()
+	d[1]=1
+	d[2]=2**2
+	d[3]=3**2
+	print d
+		
+
+printDict()
+
+* * * + + +**Question:** +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. + +**Solution:** +
+def printDict():
+	d=dict()
+	for i in range(1,21):
+		d[i]=i**2
+	print d
+		
+
+printDict()
+
+* * * + + +**Question:** +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. + +**Solution:** +
+def printDict():
+	d=dict()
+	for i in range(1,21):
+		d[i]=i**2
+	for (k,v) in d.items():	
+		print v
+		
+
+printDict()
+
+* * * + + +**Question:** +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. + +**Solution:** +
+def printDict():
+	d=dict()
+	for i in range(1,21):
+		d[i]=i**2
+	for k in d.keys():	
+		print k
+		
+
+printDict()
+
+* * * + + +**Question:** +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. + +**Solution:** +
+def printList():
+	li=list()
+	for i in range(1,21):
+		li.append(i**2)
+	print li
+		
+
+printList()
+
+* * * + + +**Question:** +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 + +**Solution:** +
+def printList():
+	li=list()
+	for i in range(1,21):
+		li.append(i**2)
+	print li[:5]
+		
+
+printList()
+
+* * * + + +**Question:** +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 + +**Solution:** +
+def printList():
+	li=list()
+	for i in range(1,21):
+		li.append(i**2)
+	print li[-5:]
+		
+
+printList()
+
+* * * + + +**Question:** +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 + +**Solution:** +
+def printList():
+	li=list()
+	for i in range(1,21):
+		li.append(i**2)
+	print li[5:]
+		
+
+printList()
+
+* * * + + +**Question:** +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. + +**Solution:** +
+def printTuple():
+	li=list()
+	for i in range(1,21):
+		li.append(i**2)
+	print tuple(li)
+		
+printTuple()
+
+* * * + + +**Question:** +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. + +**Solution:** +
+tp=(1,2,3,4,5,6,7,8,9,10)
+tp1=tp[:5]
+tp2=tp[5:]
+print tp1
+print tp2
+
+* * * + +**Question:** +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. + +**Solution:** +
+tp=(1,2,3,4,5,6,7,8,9,10)
+li=list()
+for i in tp:
+	if tp[i]%2==0:
+		li.append(tp[i])
+
+tp2=tuple(li)
+print tp2
+
+* * * +**Question:** +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. + +**Solution:** +
+s= raw_input()
+if s=="yes" or s=="YES" or s=="Yes":
+    print "Yes"
+else:
+    print "No"
+
+* * * +**Question:** +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. + +**Solution:** +
+li = [1,2,3,4,5,6,7,8,9,10]
+evenNumbers = filter(lambda x: x%2==0, li)
+print evenNumbers
+
+* * * +**Question:** +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. + +**Solution:** +
+li = [1,2,3,4,5,6,7,8,9,10]
+squaredNumbers = map(lambda x: x**2, li)
+print squaredNumbers
+
+* * * +**Question:** +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. + +**Solution:** +
+li = [1,2,3,4,5,6,7,8,9,10]
+evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li))
+print evenNumbers
+
+* * * + +**Question:** +Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). + +**Hints:** + +Use filter() to filter elements of a list. +Use lambda to define anonymous functions. + +**Solution:** +
+evenNumbers = filter(lambda x: x%2==0, range(1,21))
+print evenNumbers
+
+* * * +**Question:** +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. + +**Solution:** +
+squaredNumbers = map(lambda x: x**2, range(1,21))
+print squaredNumbers
+
+* * * +**Question:** +Define a class named American which has a static method called printNationality. + +**Hints:** + +Use @staticmethod decorator to define class static method. + +**Solution:** +
+class American(object):
+    @staticmethod
+    def printNationality():
+        print "America"
+
+anAmerican = American()
+anAmerican.printNationality()
+American.printNationality()
+
+* * * +**Question:** +Define a class named American and its subclass NewYorker. + +**Hints:** + +Use class Subclass(ParentClass) to define a subclass. + +**Solution:** +
+class American(object):
+    pass
+
+class NewYorker(American):
+    pass
+
+anAmerican = American()
+aNewYorker = NewYorker()
+print anAmerican
+print aNewYorker
+
+* * * +**Question:** +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. + +**Solution:** +
+
+class Circle(object):
+    def __init__(self, r):
+        self.radius = r
+
+    def area(self):
+        return self.radius**2*3.14
+
+aCircle = Circle(2)
+print aCircle.area()
+
+* * * +**Question:** +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. + +**Solution:** +
+
+class Rectangle(object):
+    def __init__(self, l, w):
+        self.length = l
+        self.width  = w
+
+    def area(self):
+        return self.length*self.width
+
+aRectangle = Rectangle(2,10)
+print aRectangle.area()
+
+* * * +**Question:** +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. + +**Solution:** +
+
+class Shape(object):
+    def __init__(self):
+        pass
+
+    def area(self):
+        return 0
+
+class Square(Shape):
+    def __init__(self, l):
+        Shape.__init__(self)
+        self.length = l
+
+    def area(self):
+        return self.length*self.length
+
+aSquare= Square(3)
+print aSquare.area()
+
+* * * +**Question:** +Please raise a RuntimeError exception. + +**Hints:** + +Use raise() to raise an exception. + +**Solution:** +
+raise RuntimeError('something wrong')
+
+* * * +**Question:** +Write a function to compute 5/0 and use try/except to catch the exceptions. + +**Hints:** + +Use try/except to catch exceptions. + +**Solution:** +
+def throws():
+    return 5/0
+
+try:
+    throws()
+except ZeroDivisionError:
+    print "division by zero!"
+except Exception, err:
+    print 'Caught an exception'
+finally:
+    print 'In finally block for cleanup'
+
+* * * +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. + +**Solution:** +
+class MyError(Exception):
+    """My own exception class
+
+    Attributes:
+        msg  -- explanation of the error
+    """
+
+    def __init__(self, msg):
+        self.msg = msg
+
+error = MyError("something wrong")
+
+* * * +**Question:** +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. + +**Hints:** + +Use \w to match letters. + +**Solution:** +
+import re
+emailAddress = raw_input()
+pat2 = "(\w+)@((\w+\.)+(com))"
+r2 = re.match(pat2,emailAddress)
+print r2.group(1)
+
+
+
* * * +**Question:** + +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. + +Example: +If the following email address is given as input to the program: + +john@google.com + +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. + +**Hints:** + +Use \w to match letters. + +**Solution:** +
+import re
+emailAddress = raw_input()
+pat2 = "(\w+)@(\w+)\.(com)"
+r2 = re.match(pat2,emailAddress)
+print r2.group(2)
+
+* * * +**Question:** + +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. + +**Hints:** + +Use re.findall() to find all substring using regex. + +**Solution:** +
+import re
+s = raw_input()
+print re.findall("\d+",s)
+
+* * * +**Question:** + + +Print a unicode string "hello world". + +**Hints:** + +Use u'strings' format to define unicode string. + +**Solution:** +
+
+unicodeString = u"hello world!"
+print unicodeString
+
+
* * * +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. + +**Solution:** +
+
+s = raw_input()
+u = unicode( s ,"utf-8")
+print u
+
+
* * * +**Question:** + +Write a special comment to indicate a Python source code file is in unicode. + +**Hints:** + +**Solution:** +
+
+# -*- coding: utf-8 -*-
+
+
* * * +**Question:** + +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. + +**Hints:** +Use float() to convert an integer to a float + +**Solution:** +
+
+n=int(raw_input())
+sum=0.0
+for i in range(1,n+1):
+    sum += float(float(i)/(i+1))
+print sum
+
+
+
* * * +**Question:** + +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. + +**Hints:** +We can define recursive function in Python. + +**Solution:** +
+
+def f(n):
+    if n==0:
+        return 0
+    else:
+        return f(n-1)+100
+
+n=int(raw_input())
+print f(n)
+
+
* * * + +**Question:** + + +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. + +**Hints:** +We can define recursive function in Python. + + +**Solution:** +
+
+def f(n):
+    if n == 0: return 0
+    elif n == 1: return 1
+    else: return f(n-1)+f(n-2)
+
+n=int(raw_input())
+print f(n)
+
+* * * + +**Question:** + +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 + + +**Hints:** +We can define recursive function in Python. +Use list comprehension to generate a list from an existing list. +Use string.join() to join a list of strings. + +In case of input data being supplied to the question, it should be assumed to be a console input. + +**Solution:** +
+
+def f(n):
+    if n == 0: return 0
+    elif n == 1: return 1
+    else: return f(n-1)+f(n-2)
+
+n=int(raw_input())
+values = [str(f(x)) for x in range(0, n+1)]
+print ",".join(values)
+
+* * * + +**Question:** + +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. + +**Solution:** +
+
+def EvenGenerator(n):
+    i=0
+    while i<=n:
+        if i%2==0:
+            yield i
+        i+=1
+
+
+n=int(raw_input())
+values = []
+for i in EvenGenerator(n):
+    values.append(str(i))
+
+print ",".join(values)
+
* * * + +**Question:** + +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 + +**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. + +**Solution:** +
+
+def NumGenerator(n):
+    for i in range(n+1):
+        if i%5==0 and i%7==0:
+            yield i
+
+n=int(raw_input())
+values = []
+for i in NumGenerator(n):
+    values.append(str(i))
+
+print ",".join(values)
+
* * * + +**Question:** +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. +**Solution:** +
+
+li = [2,4,6,8]
+for i in li:
+    assert i%2==0
+
* * * +**Question:** +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 + +**Hints:** +Use eval() to evaluate an expression. + + +**Solution:** +
+
+expression = raw_input()
+print eval(expression)
+
+
+
* * * +**Question:** + +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. + + +**Hints:** +Use if/elif to deal with conditions. + + +**Solution:** +
+
+import math
+def bin_search(li, element):
+    bottom = 0
+    top = len(li)-1
+    index = -1
+    while top>=bottom and index==-1:
+        mid = int(math.floor((top+bottom)/2.0))
+        if li[mid]==element:
+            index = mid
+        elif li[mid]>element:
+            top = mid-1
+        else:
+            bottom = mid+1
+
+    return index
+
+li=[2,5,7,9,11,17,222]
+print bin_search(li,11)
+print bin_search(li,12)
+
+
+
+
+
* * * +**Question:** + +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. + + +**Hints:** +Use if/elif to deal with conditions. + + +**Solution:** +
+
+import math
+def bin_search(li, element):
+    bottom = 0
+    top = len(li)-1
+    index = -1
+    while top>=bottom and index==-1:
+        mid = int(math.floor((top+bottom)/2.0))
+        if li[mid]==element:
+            index = mid
+        elif li[mid]>element:
+            top = mid-1
+        else:
+            bottom = mid+1
+
+    return index
+
+li=[2,5,7,9,11,17,222]
+print bin_search(li,11)
+print bin_search(li,12)
+
+
+
+
+
* * * +**Question:** + +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]. + + +**Solution:** +
+
+import random
+print random.random()*100
+
+
* * * +**Question:** + +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]. + + +**Solution:** +
+
+import random
+print random.random()*100-5
+
+
+
* * * +**Question:** + +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. + + +**Solution:** +
+
+import random
+print random.choice([i for i in range(11) if i%2==0])
+
+
+
* * * +**Question:** + +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. + + +**Solution:** +
+
+import random
+print random.choice([i for i in range(201) if i%5==0 and i%7==0])
+
+
+
+
* * * + +**Question:** + +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. + + +**Solution:** +
+
+import random
+print random.sample(range(100), 5)
+
+
* * * +**Question:** + +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. + + +**Solution:** +
+
+import random
+print random.sample([i for i in range(100,201) if i%2==0], 5)
+
+
+
* * * +**Question:** + +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. + + +**Solution:** +
+
+import random
+print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5)
+
+
* * * + +**Question:** + +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. + + +**Solution:** +
+
+import random
+print random.randrange(7,16)
+
+
* * * + +**Question:** + +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. + + +**Solution:** +
+
+import zlib
+s = 'hello world!hello world!hello world!hello world!'
+t = zlib.compress(s)
+print t
+print zlib.decompress(t)
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+from timeit import Timer
+t = Timer("for i in range(100):1+1")
+print t.timeit()
+
+
* * * +**Question:** + +Please write a program to shuffle and print the list [3,6,7,8]. + + + +**Hints:** +Use shuffle() function to shuffle a list. + +**Solution:** +
+
+from random import shuffle
+li = [3,6,7,8]
+shuffle(li)
+print li
+
+
* * * +**Question:** + +Please write a program to shuffle and print the list [3,6,7,8]. + + + +**Hints:** +Use shuffle() function to shuffle a list. + +**Solution:** +
+
+from random import shuffle
+li = [3,6,7,8]
+shuffle(li)
+print li
+
+
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+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)):
+            sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
+            print sentence
+
+
+
* * * +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. + +**Solution:** +
+
+li = [5,6,77,45,22,12,24]
+li = [x for x in li if x%2!=0]
+print li
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+li = [12,24,35,70,88,120,155]
+li = [x for x in li if x%5!=0 and x%7!=0]
+print li
+
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+li = [12,24,35,70,88,120,155]
+li = [x for (i,x) in enumerate(li) if i%2!=0]
+print li
+
+
* * * + +**Question:** + +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. + +**Solution:** +
+
+array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
+print array
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+li = [12,24,35,70,88,120,155]
+li = [x for (i,x) in enumerate(li) if i not in (0,4,5)]
+print li
+
+
+
+
* * * + +**Question:** + +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. + +**Solution:** +
+
+li = [12,24,35,24,88,120,155]
+li = [x for x in li if x!=24]
+print li
+
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+set1=set([1,3,6,78,35,55])
+set2=set([12,24,35,24,88,120,155])
+set1 &= set2
+li=list(set1)
+print li
+
+
* * * + +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. + +**Solution:** +
+
+def removeDuplicate( li ):
+    newli=[]
+    seen = set()
+    for item in li:
+        if item not in seen:
+            seen.add( item )
+            newli.append(item)
+
+    return newli
+
+li=[12,24,35,24,88,120,155,88,120,155]
+print removeDuplicate(li)
+
+
+
* * * +**Question:** + +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. + +**Solution:** +
+
+class Person(object):
+    def getGender( self ):
+        return "Unknown"
+
+class Male( Person ):
+    def getGender( self ):
+        return "Male"
+
+class Female( Person ):
+    def getGender( self ):
+        return "Female"
+
+aMale = Male()
+aFemale= Female()
+print aMale.getGender()
+print aFemale.getGender()
+
+
+
+
* * * +**Question:** + +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 + +**Hints:** +Use dict to store key/value pairs. +Use dict.get() method to lookup a key with default value. + +**Solution:** +
+
+dic = {}
+s=raw_input()
+for s in s:
+    dic[s] = dic.get(s,0)+1
+print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])
+
+
* * * + +**Question:** + +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 + +**Hints:** +Use list[::-1] to iterate a list in a reverse order. + +**Solution:** +
+
+s=raw_input()
+s = s[::-1]
+print s
+
+
* * * + +**Question:** + +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 + +**Hints:** +Use list[::2] to iterate a list by step 2. + +**Solution:** +
+
+s=raw_input()
+s = s[::2]
+print s
+
* * * +**Question:** +Please write a program which prints all permutations of [1,2,3] + +**Hints:** +Use itertools.permutations() to get permutations of list. + +**Solution:** +
+
+import itertools
+print list(itertools.permutations([1,2,3]))
+
+
* * * +**Question:** +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? + +**Hint:** +Use for loop to iterate all possible solutions. + +**Solution:** +
+def solve(numheads,numlegs):
+    ns='No solutions!'
+    for i in range(numheads+1):
+        j=numheads-i
+        if 2*i+4*j==numlegs:
+            return i,j
+    return ns,ns
+
+numheads=35
+numlegs=94
+solutions=solve(numheads,numlegs)
+print solutions
+
* * * From d18016ccbf13c4c522b3e5af10f1a66df2a495ca Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Tue, 4 Jul 2017 23:55:30 -0700 Subject: [PATCH 13/17] Update test.md --- test.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test.md b/test.md index 004a3a95..6d7760d5 100644 --- a/test.md +++ b/test.md @@ -34,7 +34,6 @@ The numbers obtained should be printed in a comma-separated sequence on a single Consider use range(#begin, #end) method **Solution:** -
 
 l=[]
 for i in range(2000, 3201):
     if (i%7==0) and (i%5!=0):
@@ -42,6 +41,7 @@ for i in range(2000, 3201):
 
 print ','.join(l)
 
+ * * * **Question:** Write a program which can compute the factorial of a given numbers. @@ -64,6 +64,7 @@ def fact(x): x=int(raw_input()) print fact(x)
+ * * * **Question:** 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. From 2fc0821a7b5922e4c2d10185501ebfeb1b2a6a9a Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Wed, 5 Jul 2017 00:00:58 -0700 Subject: [PATCH 14/17] Update test.md --- test.md | 127 +++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 79 insertions(+), 48 deletions(-) diff --git a/test.md b/test.md index 6d7760d5..e51e4047 100644 --- a/test.md +++ b/test.md @@ -473,8 +473,6 @@ print ",".join(value) * * * -Level 3 - **Question:** 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; @@ -510,8 +508,6 @@ print sorted(l, key=itemgetter(0,1,2)) * * * -Level 3 - **Question:** Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. @@ -534,8 +530,6 @@ for i in reverse(100): * * * -Level 3 - Question: 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 @@ -583,8 +577,6 @@ print int(round(math.sqrt(pos[1]**2+pos[0]**2))) * * * -Level 3 - **Question:** 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: @@ -1349,7 +1341,8 @@ r2 = re.match(pat2,emailAddress) print r2.group(1) -
* * * +
+* * * **Question:** 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. @@ -1370,7 +1363,7 @@ In case of input data being supplied to the question, it should be assumed to be Use \w to match letters. **Solution:** -
+
 import re
 emailAddress = raw_input()
 pat2 = "(\w+)@(\w+)\.(com)"
@@ -1419,7 +1412,8 @@ Use u'strings' format to define unicode string.
 unicodeString = u"hello world!"
 print unicodeString
 
-
* * * +
+* * * Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8. **Hints:** @@ -1433,7 +1427,8 @@ s = raw_input() u = unicode( s ,"utf-8") print u - * * * + +* * * **Question:** Write a special comment to indicate a Python source code file is in unicode. @@ -1445,7 +1440,8 @@ Write a special comment to indicate a Python source code file is in unicode. # -*- coding: utf-8 -*- - * * * + +* * * **Question:** Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0). @@ -1474,7 +1470,8 @@ for i in range(1,n+1): print sum - * * * + +* * * **Question:** Write a program to compute: @@ -1510,7 +1507,8 @@ def f(n): n=int(raw_input()) print f(n) - * * * + +* * * **Question:** @@ -1628,7 +1626,8 @@ for i in EvenGenerator(n): values.append(str(i)) print ",".join(values) - * * * + +* * * **Question:** @@ -1662,7 +1661,8 @@ for i in NumGenerator(n): values.append(str(i)) print ",".join(values) - * * * + +* * * **Question:** Please write assert statements to verify that every number in the list [2,4,6,8] is even. @@ -1674,7 +1674,8 @@ Use "assert expression" to make assertion. li = [2,4,6,8] for i in li: assert i%2==0 - * * * + +* * * **Question:** Please write a program which accepts basic mathematic expression from console and print the evaluation result. @@ -1698,7 +1699,8 @@ expression = raw_input() print eval(expression) - * * * + +* * * **Question:** 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. @@ -1734,7 +1736,8 @@ print bin_search(li,12) - * * * + +* * * **Question:** 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. @@ -1770,7 +1773,8 @@ print bin_search(li,12) - * * * + +* * * **Question:** Please generate a random float where the value is between 10 and 100 using Python math module. @@ -1787,7 +1791,8 @@ Use random.random() to generate a random float in [0,1]. import random print random.random()*100 - * * * + +* * * **Question:** Please generate a random float where the value is between 5 and 95 using Python math module. @@ -1805,7 +1810,8 @@ import random print random.random()*100-5 - * * * + +* * * **Question:** Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension. @@ -1823,7 +1829,8 @@ import random print random.choice([i for i in range(11) if i%2==0]) - * * * + +* * * **Question:** 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. @@ -1842,7 +1849,8 @@ print random.choice([i for i in range(201) if i%5==0 and i%7==0]) - * * * + +* * * **Question:** @@ -1860,7 +1868,8 @@ Use random.sample() to generate a list of random values. import random print random.sample(range(100), 5) - * * * + +* * * **Question:** Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive. @@ -1878,7 +1887,8 @@ import random print random.sample([i for i in range(100,201) if i%2==0], 5) - * * * + +* * * **Question:** Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive. @@ -1895,7 +1905,8 @@ Use random.sample() to generate a list of random values. import random print random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5) - * * * + +* * * **Question:** @@ -1913,7 +1924,8 @@ Use random.randrange() to a random integer in a given range. import random print random.randrange(7,16) - * * * + +* * * **Question:** @@ -1934,7 +1946,8 @@ t = zlib.compress(s) print t print zlib.decompress(t) - * * * + +* * * **Question:** Please write a program to print the running time of execution of "1+1" for 100 times. @@ -1951,7 +1964,8 @@ from timeit import Timer t = Timer("for i in range(100):1+1") print t.timeit() - * * * + +* * * **Question:** Please write a program to shuffle and print the list [3,6,7,8]. @@ -1969,7 +1983,8 @@ li = [3,6,7,8] shuffle(li) print li - * * * + +* * * **Question:** Please write a program to shuffle and print the list [3,6,7,8]. @@ -1989,7 +2004,8 @@ print li - * * * + +* * * **Question:** 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"]. @@ -2010,7 +2026,8 @@ for i in range(len(subjects)): print sentence - * * * + +* * * Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24]. **Hints:** @@ -2023,7 +2040,8 @@ li = [5,6,77,45,22,12,24] li = [x for x in li if x%2!=0] print li - * * * + +* * * **Question:** 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]. @@ -2039,7 +2057,8 @@ li = [x for x in li if x%5!=0 and x%7!=0] print li - * * * + +* * * **Question:** 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]. @@ -2055,7 +2074,8 @@ li = [12,24,35,70,88,120,155] li = [x for (i,x) in enumerate(li) if i%2!=0] print li - * * * + +* * * **Question:** @@ -2070,7 +2090,8 @@ Use list comprehension to make an array. array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)] print array - * * * + +* * * **Question:** 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]. @@ -2088,7 +2109,8 @@ print li - * * * + +* * * **Question:** @@ -2105,7 +2127,8 @@ li = [x for x in li if x!=24] print li - * * * + +* * * **Question:** 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. @@ -2122,7 +2145,8 @@ set1 &= set2 li=list(set1) print li - * * * + +* * * 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. @@ -2146,7 +2170,8 @@ li=[12,24,35,24,88,120,155,88,120,155] print removeDuplicate(li) - * * * + +* * * **Question:** 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. @@ -2176,7 +2201,8 @@ print aFemale.getGender() - * * * + +* * * **Question:** Please write a program which count and print the numbers of each character in a string input by console. @@ -2209,7 +2235,8 @@ for s in s: dic[s] = dic.get(s,0)+1 print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]) - * * * + +* * * **Question:** @@ -2234,7 +2261,8 @@ s=raw_input() s = s[::-1] print s - * * * + +* * * **Question:** @@ -2258,7 +2286,8 @@ Use list[::2] to iterate a list by step 2. s=raw_input() s = s[::2] print s - * * * + +* * * **Question:** Please write a program which prints all permutations of [1,2,3] @@ -2271,7 +2300,8 @@ Use itertools.permutations() to get permutations of list. import itertools print list(itertools.permutations([1,2,3])) - * * * + +* * * **Question:** 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? @@ -2293,4 +2323,5 @@ numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions - * * * + +* * * From 26927103cbedd9252c4285126b3efb931e48d0e5 Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Wed, 5 Jul 2017 00:05:26 -0700 Subject: [PATCH 15/17] Update test.md --- test.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test.md b/test.md index e51e4047..42caef59 100644 --- a/test.md +++ b/test.md @@ -446,7 +446,7 @@ ABd1234@1 In case of input data being supplied to the question, it should be assumed to be a console input. **Solution:** -
:
+ 
 import re
 value = []
 items=[x for x in raw_input().split(',')]
@@ -493,7 +493,7 @@ In case of input data being supplied to the question, it should be assumed to be
 We use itemgetter to enable multiple sort keys.
 
 **Solution:** 
- 
:
+
 from operator import itemgetter, attrgetter
 
 l = []
@@ -515,7 +515,7 @@ Define a class with a generator which can iterate the numbers, which are divisib
 Consider use yield
 
 **Solution:** 
- 
+
 def putNumbers(n):
     i = 0
     while i
@@ -551,7 +550,7 @@ Then, the output of the program should be:
 In case of input data being supplied to the question, it should be assumed to be a console input.
 
 **Solution:** 
- 
+
 import math
 pos = [0,0]
 while True:

From 4bc7d57fa1b7543f371efdb6d9ce97300ff1ad09 Mon Sep 17 00:00:00 2001
From: Om Prakash Manivannan 
Date: Wed, 5 Jul 2017 00:08:17 -0700
Subject: [PATCH 16/17] Update test.md

---
 test.md | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)

diff --git a/test.md b/test.md
index 42caef59..1b194321 100644
--- a/test.md
+++ b/test.md
@@ -528,14 +528,12 @@ for i in reverse(100):
 
* * * - -Question: +**Question:** 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: @@ -575,7 +573,6 @@ print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
* * * - **Question:** 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: @@ -593,7 +590,7 @@ choosing:1 or:2 to:1 -Hints +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. **Solution:** @@ -682,6 +679,7 @@ nico = Person() nico.name = "Nico" print "%s name is %s" % (Person.name, nico.name)
+ * * * **Question:** Define a function which can compute the sum of two numbers. @@ -696,6 +694,7 @@ def SumFunction(number1, number2): print SumFunction(1,2)
+ * * * **Question:** Define a function that can convert a integer into a string and print it in console. @@ -704,12 +703,14 @@ Define a function that can convert a integer into a string and print it in conso Use str() to convert a number to string. -Solution +**Solution:** +
 def printValue(n):
 	print str(n)
 
 printValue(3)
 
+ * * * **Question:** Define a function that can convert a integer into a string and print it in console. From ce738dc0ca1a452f67ed8aff5d115eecf39b4a2a Mon Sep 17 00:00:00 2001 From: Om Prakash Manivannan Date: Thu, 25 Jul 2019 23:58:49 -0400 Subject: [PATCH 17/17] Create Q1.py --- answers/level1/Q1.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 answers/level1/Q1.py diff --git a/answers/level1/Q1.py b/answers/level1/Q1.py new file mode 100644 index 00000000..6e666721 --- /dev/null +++ b/answers/level1/Q1.py @@ -0,0 +1,10 @@ +# 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. + +start = 2000 +end = 3201 +result=[] +for i in range(start, end): + if (i%7 ==0 and i%5 != 0): + result.append(str(i)) + +print(','.join(result))