diff --git a/100+ Python challenging programming exercises.txt b/100+ Python challenging programming exercises.md similarity index 79% rename from 100+ Python challenging programming exercises.txt rename to 100+ Python challenging programming exercises.md index 97af5aaf..a08e260c 100644 --- a/100+ Python challenging programming exercises.txt +++ b/100+ Python challenging programming exercises.md @@ -1,46 +1,42 @@ -100+ Python challenging programming exercises +# 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 -2. Problem template +| Level | Description | +| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Level1](#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.| +| [Level2](#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. | +| [Level3](#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. | -#----------------------------------------# -Question -Hints -Solution +## Problem template -3. Questions +1. Question +2. Hints +3. Solution -#----------------------------------------# -Question 1 -Level 1 +## Questions: -Question: +### Level_1 + + #### Question 1 Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. -Hints: -Consider use range(#begin, #end) method +**Hints:** +Consider use `range(#begin, #end)` method -Solution: +**Solution:** +``` python l=[] for i in range(2000, 3201): - if (i%7==0) and (i%5!=0): + if (i%7 == 0) and (i%5 != 0): l.append(str(i)) print ','.join(l) -#----------------------------------------# - -#----------------------------------------# -Question 2 -Level 1 +``` -Question: + #### Question 2 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: @@ -48,10 +44,11 @@ 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:** +``` python def fact(x): if x == 0: return 1 @@ -59,37 +56,30 @@ def fact(x): x=int(raw_input()) print fact(x) -#----------------------------------------# +``` -#----------------------------------------# -Question 3 -Level 1 - -Question: +#### Question 3 With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary. Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Consider use dict() +Consider use `dict()` -Solution: -n=int(raw_input()) -d=dict() +**Solution:** +``` python +n = int(raw_input()) +d = dict() for i in range(1,n+1): - d[i]=i*i - -print d -#----------------------------------------# + d[i] = i*i -#----------------------------------------# -Question 4 -Level 1 +print(d) +``` -Question: + #### Question 4 Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 @@ -97,32 +87,30 @@ 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: -values=raw_input() -l=values.split(",") -t=tuple(l) -print l -print t -#----------------------------------------# - -#----------------------------------------# -Question 5 -Level 1 +**Solution:** ``` python +``` python +values = raw_input() +l = values.split(",") +t = tuple(l) +print(l) +print(t) +``` -Question: + #### Question 5 Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. -Hints: -Use __init__ method to construct some parameters +**Hints:** +Use `__init__` method to construct some parameters -Solution: +**Solution:** +``` python class InputOutString(object): def __init__(self): self.s = "" @@ -136,13 +124,80 @@ class InputOutString(object): strObj = InputOutString() strObj.getString() strObj.printString() -#----------------------------------------# +``` -#----------------------------------------# -Question 6 -Level 2 + #### Question 23 Question: + Write a method which can calculate square value of number + +**Hints:** + Using the ** operator + +**Solution:** +``` python +def square(num): + return num ** 2 + +print square(2) +print square(3) +``` + #### Question 24 + +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:** +``` python +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 25 +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:** +``` python +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) + +``` + +### Level_2 + + #### Question 6 Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: @@ -158,24 +213,20 @@ 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:** +``` python #!/usr/bin/env python import math -c=50 -h=30 +c = 50 +h = 30 value = [] -items=[x for x in raw_input().split(',')] +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: +``` + #### Question 7 Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Note: i=0,1.., X-1; j=0,1,¡­Y-1. Example @@ -184,10 +235,11 @@ 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:** +``` python input_str = raw_input() dimensions=[int(x) for x in input_str.split(',')] rowNum=dimensions[0] @@ -199,33 +251,24 @@ for row in range(rowNum): multilist[row][col]= row*col print multilist -#----------------------------------------# - -#----------------------------------------# -Question 8 -Level 2 - -Question: +``` + #### Question 8 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:** +``` python items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) -#----------------------------------------# - -#----------------------------------------# -Question 9 -Level 2 - -Question£º +``` + #### Question 9 Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world @@ -234,10 +277,11 @@ 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:** +``` python lines = [] while True: s = raw_input() @@ -248,34 +292,28 @@ while True: for sentence in lines: print sentence -#----------------------------------------# - -#----------------------------------------# -Question 10 -Level 2 +``` -Question: +#### Question 10 Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically. Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world -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:** +``` python s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) -#----------------------------------------# +``` -#----------------------------------------# -Question 11 -Level 2 -Question: +#### Question 11 Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence. Example: 0100,0011,1010,1001 @@ -283,10 +321,11 @@ 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:** ``` python +``` python value = [] items=[x for x in raw_input().split(',')] for p in items: @@ -295,33 +334,27 @@ for p in items: value.append(p) print ','.join(value) -#----------------------------------------# - -#----------------------------------------# -Question 12 -Level 2 +``` -Question: +#### Question 12 Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** +``` python 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 13 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 @@ -329,10 +362,11 @@ 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:** +``` python s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: @@ -344,13 +378,9 @@ for c in s: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] -#----------------------------------------# +``` -#----------------------------------------# -Question 14 -Level 2 - -Question: +#### Question 14 Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters. Suppose the following input is supplied to the program: Hello world! @@ -358,10 +388,11 @@ 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:** +``` python s = raw_input() d={"UPPER CASE":0, "LOWER CASE":0} for c in s: @@ -373,55 +404,50 @@ for c in s: pass print "UPPER CASE", d["UPPER CASE"] print "LOWER CASE", d["LOWER CASE"] -#----------------------------------------# - -#----------------------------------------# -Question 15 -Level 2 +``` -Question: +#### Question 15 Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a. Suppose the following input is supplied to the program: 9 Then, the output should be: 11106 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** +``` python 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 16 + Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1,2,3,4,5,6,7,8,9 Then, the output should be: 1,3,5,7,9 -Hints: +**Hints:** In case of input data being supplied to the question, it should be assumed to be a console input. -Solution: +**Solution:** +``` python values = raw_input() numbers = [x for x in values.split(",") if int(x)%2!=0] print ",".join(numbers) -#----------------------------------------# +``` + +#### Question 17 -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 @@ -435,10 +461,11 @@ 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:** +``` python netAmount = 0 while True: s = raw_input() @@ -454,21 +481,21 @@ while True: else: pass print netAmount -#----------------------------------------# +``` + +### Level_3 +#### Question 18 -#----------------------------------------# -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 +3. At least 1 letter between [A-Z] +4. At least 1 character from [$#@] +5. Minimum length of transaction password: 6 +6. 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: @@ -476,10 +503,11 @@ 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: +**Solution:** ``` python +``` python import re value = [] items=[x for x in raw_input().split(',')] @@ -502,13 +530,10 @@ for p in items: pass value.append(p) print ",".join(value) -#----------------------------------------# +``` -#----------------------------------------# -Question 19 -Level 3 +#### Question 19 -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; @@ -523,11 +548,12 @@ 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. -Solutions: +**Solution:** +``` python from operator import itemgetter, attrgetter l = [] @@ -538,19 +564,17 @@ while True: l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) -#----------------------------------------# -#----------------------------------------# -Question 20 -Level 3 +``` -Question: + #### Question 20 Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. -Hints: +**Hints:** Consider use yield -Solution: +**Solution:** +``` python def putNumbers(n): i = 0 while i0). @@ -1549,20 +1397,20 @@ 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:** +``` python n=int(raw_input()) sum=0.0 for i in range(1,n+1): sum += float(float(i)/(i+1)) print sum +``` - -#----------------------------------------# -Question: +#### Question: Write a program to compute: @@ -1582,11 +1430,12 @@ 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:** +``` python def f(n): if n==0: return 0 @@ -1595,11 +1444,9 @@ def f(n): n=int(raw_input()) print f(n) +``` -#----------------------------------------# - -Question: - +#### Question: The Fibonacci Sequence is computed based on the following formula: @@ -1621,12 +1468,13 @@ 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:** +``` python def f(n): if n == 0: return 0 elif n == 1: return 1 @@ -1634,13 +1482,8 @@ def f(n): n=int(raw_input()) print f(n) - - -#----------------------------------------# - -#----------------------------------------# - -Question: +``` +#### Question: The Fibonacci Sequence is computed based on the following formula: @@ -1661,15 +1504,16 @@ 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:** +``` python def f(n): if n == 0: return 0 elif n == 1: return 1 @@ -1678,11 +1522,8 @@ def f(n): n=int(raw_input()) 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. @@ -1695,13 +1536,13 @@ 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:** +``` python def EvenGenerator(n): i=0 while i<=n: @@ -1716,11 +1557,8 @@ for i in EvenGenerator(n): values.append(str(i)) 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. @@ -1733,13 +1571,13 @@ 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:** +``` python def NumGenerator(n): for i in range(n+1): if i%5==0 and i%7==0: @@ -1751,31 +1589,25 @@ 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: +**Hints:** Use "assert expression" to make assertion. -Solution: - +**Solution:** +``` python 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: @@ -1787,28 +1619,26 @@ Then, the output of the program should be: 38 -Hints: +**Hints:** Use eval() to evaluate an expression. -Solution: - +**Solution:** +``` python 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:** +``` python import math def bin_search(li, element): bottom = 0 @@ -1828,22 +1658,18 @@ def bin_search(li, element): li=[2,5,7,9,11,17,222] print bin_search(li,11) 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:** +``` python import math def bin_search(li, element): bottom = 0 @@ -1863,226 +1689,199 @@ def bin_search(li, element): li=[2,5,7,9,11,17,222] print bin_search(li,11) 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python import zlib s = 'hello world!hello world!hello world!hello world!' 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:** +``` python 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:** +``` python 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:** +``` python from random import shuffle li = [3,6,7,8] shuffle(li) 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:** +``` python subjects=["I", "You"] verbs=["Play", "Love"] @@ -2092,122 +1891,112 @@ for i in range(len(subjects)): for k in range(len(objects)): sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k]) print sentence +``` +#### Question: +Please write a program to print the list after removing delete even numbers in `[5, 6, 77, 45, 22, 12, 24]`. -#----------------------------------------# -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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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:** +``` python 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: +``` +#### 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:** +``` python 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:** +``` python set1=set([1,3,6,78,35,55]) set2=set([12,24,35,24,88,120,155]) set1 &= set2 li=list(set1) print li +``` -#----------------------------------------# +#### Question: 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:** +``` python def removeDuplicate( li ): newli=[] seen = set() @@ -2220,18 +2009,16 @@ def removeDuplicate( li ): 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:** +``` python class Person(object): def getGender( self ): return "Unknown" @@ -2248,11 +2035,8 @@ aMale = Male() 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. @@ -2271,22 +2055,19 @@ 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:** +``` python 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: - +``` + #### Question: Please write a program which accepts a string from console and print it in reverse order. Example: @@ -2298,18 +2079,16 @@ 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:** +``` python 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. @@ -2322,32 +2101,29 @@ Then, the output of the program should be: Helloworld -Hints: +**Hints:** Use list[::2] to iterate a list by step 2. -Solution: - +**Solution:** +``` python 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:** +``` python 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? @@ -2355,8 +2131,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:** +``` python def solve(numheads,numlegs): ns='No solutions!' for i in range(numheads+1): @@ -2369,7 +2145,6 @@ numheads=35 numlegs=94 solutions=solve(numheads,numlegs) print solutions - -#----------------------------------------# +```