diff --git a/100+ Python challenging programming exercises.txt b/100+ Python challenging programming exercises.txt index 66c00215..eb01b1d5 100644 --- a/100+ Python challenging programming exercises.txt +++ b/100+ Python challenging programming exercises.txt @@ -27,14 +27,7 @@ The numbers obtained should be printed in a comma-separated sequence on a single 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 @@ -51,15 +44,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: -def fact(x): - if x == 0: - return 1 - return x * fact(x - 1) -x=int(raw_input()) -print fact(x) -#----------------------------------------# #----------------------------------------# Question 3 @@ -76,14 +61,7 @@ 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 @@ -101,13 +79,6 @@ 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 @@ -122,21 +93,7 @@ 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 @@ -158,18 +115,7 @@ 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 @@ -187,19 +133,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: -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 @@ -215,11 +149,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: -items=[x for x in raw_input().split(',')] -items.sort() -print ','.join(items) -#----------------------------------------# + #----------------------------------------# Question 9 @@ -237,18 +167,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: -lines = [] -while True: - s = raw_input() - if s: - lines.append(s.upper()) - else: - break; -for sentence in lines: - print sentence -#----------------------------------------# #----------------------------------------# Question 10 @@ -265,11 +184,7 @@ 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 @@ -286,16 +201,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: -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 @@ -308,14 +214,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: -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 @@ -332,19 +231,7 @@ 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 @@ -361,19 +248,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: -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 @@ -389,14 +264,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: -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 @@ -412,10 +280,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: -values = raw_input() -numbers = [x for x in values.split(",") if int(x)%2!=0] -print ",".join(numbers) + #----------------------------------------# Question 17 @@ -438,24 +303,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: -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 @@ -480,30 +328,7 @@ 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 @@ -531,15 +356,7 @@ 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 @@ -551,18 +368,7 @@ Define a class with a generator which can iterate the numbers, which are divisib 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") @@ -837,15 +545,7 @@ 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) #----------------------------------------# @@ -859,16 +559,7 @@ 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() @@ -886,15 +577,7 @@ 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() #----------------------------------------# @@ -910,16 +593,7 @@ 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 @@ -934,16 +608,6 @@ 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() #----------------------------------------# @@ -958,15 +622,7 @@ 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 @@ -981,15 +637,7 @@ 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() #----------------------------------------# @@ -1005,15 +653,7 @@ 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() #----------------------------------------# @@ -1029,15 +669,7 @@ 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() #----------------------------------------# @@ -1053,14 +685,7 @@ 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() + @@ -1074,12 +699,7 @@ 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 + #----------------------------------------# @@ -1093,15 +713,7 @@ 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 @@ -1115,12 +727,6 @@ 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" @@ -1135,10 +741,7 @@ 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 + #----------------------------------------# @@ -1152,10 +755,7 @@ 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 @@ -1169,11 +769,6 @@ 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 - @@ -1188,10 +783,6 @@ 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 @@ -1204,10 +795,6 @@ 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 - @@ -1221,16 +808,6 @@ Hints: Use @staticmethod decorator to define class static method. -Solution -class American(object): - @staticmethod - def printNationality(): - print "America" - -anAmerican = American() -anAmerican.printNationality() -American.printNationality() - @@ -1245,19 +822,6 @@ 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 - @@ -1273,18 +837,6 @@ 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() - @@ -1300,19 +852,6 @@ 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() - @@ -1326,29 +865,6 @@ 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() - - - - @@ -1362,10 +878,6 @@ Hints: Use raise() to raise an exception. -Solution: - -raise RuntimeError('something wrong') - #----------------------------------------# @@ -1375,20 +887,6 @@ 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. @@ -1397,20 +895,6 @@ 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: @@ -1431,13 +915,6 @@ 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: @@ -1459,13 +936,6 @@ 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) - @@ -1489,11 +959,6 @@ Hints: Use re.findall() to find all substring using regex. -Solution: -import re -s = raw_input() -print re.findall("\d+",s) - #----------------------------------------# Question: @@ -1505,10 +970,6 @@ 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. @@ -1517,11 +978,6 @@ Hints: Use unicode() function to convert. -Solution: - -s = raw_input() -u = unicode( s ,"utf-8") -print u #----------------------------------------# Question: @@ -1530,10 +986,6 @@ Write a special comment to indicate a Python source code file is in unicode. Hints: -Solution: - -# -*- coding: utf-8 -*- - #----------------------------------------# Question: @@ -1553,14 +1005,6 @@ 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: - -n=int(raw_input()) -sum=0.0 -for i in range(1,n+1): - sum += float(float(i)/(i+1)) -print sum - #----------------------------------------# Question: @@ -1586,16 +1030,6 @@ 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: - -def f(n): - if n==0: - return 0 - else: - return f(n-1)+100 - -n=int(raw_input()) -print f(n) #----------------------------------------# @@ -1626,18 +1060,6 @@ 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) - - -#----------------------------------------# #----------------------------------------# @@ -1669,16 +1091,6 @@ 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) #----------------------------------------# @@ -1701,22 +1113,6 @@ 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) #----------------------------------------# @@ -1739,19 +1135,6 @@ 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) #----------------------------------------# @@ -1767,12 +1150,6 @@ Hints: Use "assert expression" to make assertion. -Solution: - -li = [2,4,6,8] -for i in li: - assert i%2==0 - #----------------------------------------# Question: @@ -1792,12 +1169,6 @@ Hints: Use eval() to evaluate an expression. -Solution: - -expression = raw_input() -print eval(expression) - - #----------------------------------------# Question: @@ -1808,30 +1179,6 @@ 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: @@ -1879,10 +1226,6 @@ Hints: Use random.random() to generate a random float in [0,1]. -Solution: - -import random -print random.random()*100 #----------------------------------------# Question: @@ -1895,11 +1238,6 @@ Hints: Use random.random() to generate a random float in [0,1]. -Solution: - -import random -print random.random()*100-5 - #----------------------------------------# Question: @@ -1912,11 +1250,6 @@ 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: @@ -1929,11 +1262,6 @@ 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]) - #----------------------------------------# @@ -1948,10 +1276,6 @@ Hints: Use random.sample() to generate a list of random values. -Solution: - -import random -print random.sample(range(100), 5) #----------------------------------------# Question: @@ -1964,11 +1288,6 @@ 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: @@ -1981,11 +1300,6 @@ 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: @@ -1998,11 +1312,6 @@ Hints: Use random.randrange() to a random integer in a given range. -Solution: - -import random -print random.randrange(7,16) - #----------------------------------------# Question: @@ -2015,14 +1324,6 @@ 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: @@ -2033,11 +1334,6 @@ 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: - -from timeit import Timer -t = Timer("for i in range(100):1+1") -print t.timeit() #----------------------------------------# Question: @@ -2049,12 +1345,6 @@ 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: @@ -2066,13 +1356,6 @@ 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 - #----------------------------------------# @@ -2083,17 +1366,6 @@ Please write a program to generate all sentences where subject is in ["I", "You" 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]. @@ -2101,11 +1373,6 @@ 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: - -li = [5,6,77,45,22,12,24] -li = [x for x in li if x%2!=0] -print li #----------------------------------------# Question: @@ -2115,12 +1382,6 @@ By using list comprehension, please write a program to print the list after remo 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: @@ -2131,11 +1392,6 @@ 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 #----------------------------------------# @@ -2146,10 +1402,6 @@ By using list comprehension, please write a program generate a 3*5*8 3D array wh 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: @@ -2160,12 +1412,6 @@ 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 - #----------------------------------------# @@ -2177,11 +1423,6 @@ By using list comprehension, please write a program to print the list after remo 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 #----------------------------------------# @@ -2192,13 +1433,6 @@ With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a prog 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 #----------------------------------------# @@ -2207,20 +1441,6 @@ 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: - -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) #----------------------------------------# @@ -2231,25 +1451,6 @@ Define a class Person and its two child classes: Male and Female. All classes ha 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() - #----------------------------------------# @@ -2276,13 +1477,6 @@ 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()]) #----------------------------------------# @@ -2302,11 +1496,6 @@ 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 #----------------------------------------# @@ -2326,11 +1515,7 @@ Helloworld Hints: Use list[::2] to iterate a list by step 2. -Solution: -s=raw_input() -s = s[::2] -print s #----------------------------------------# @@ -2342,10 +1527,6 @@ 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: @@ -2356,20 +1537,6 @@ 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: - -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 #----------------------------------------#