diff --git a/100+ Python challenging programming exercises for Python 3.md b/100+ Python challenging programming exercises for Python 3.md
index c4ba62c4..8ed71127 100644
--- a/100+ Python challenging programming exercises for Python 3.md
+++ b/100+ Python challenging programming exercises for Python 3.md
@@ -32,7 +32,9 @@ The numbers obtained should be printed in a comma-separated sequence on a single
Hints:
Consider use range(#begin, #end) method
-Solution:
+
+Show Solution
+
```python
l=[]
for i in range(2000, 3201):
@@ -41,6 +43,7 @@ for i in range(2000, 3201):
print(','.join(l))
```
+
### Question 2
Level 1
@@ -56,7 +59,9 @@ 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:
+
+Show Solution
+
```python
def fact(x):
if x == 0:
@@ -66,6 +71,7 @@ def fact(x):
x=int(input())
print(fact(x))
```
+
### Question 3
Level 1
@@ -81,7 +87,9 @@ Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
Consider use dict()
-Solution:
+
+Show Solution
+
```python
n=int(input())
d=dict()
@@ -90,6 +98,7 @@ for i in range(1,n+1):
print(d)
```
+
### Question 4
Level 1
@@ -106,7 +115,9 @@ 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:
+
+Show Solution
+
```python
values=input()
l=values.split(",")
@@ -114,6 +125,7 @@ t=tuple(l)
print(l)
print(t)
```
+
### Question 5
Level 1
@@ -127,7 +139,9 @@ Also please include simple test function to test the class methods.
Hints:
Use __init__ method to construct some parameters
-Solution:
+
+Show Solution
+
```python
class InputOutString(object):
def __init__(self):
@@ -143,6 +157,7 @@ strObj = InputOutString()
strObj.getString()
strObj.printString()
```
+
### Question 6
Level 2
@@ -163,7 +178,9 @@ 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:
+
+Show Solution
+
```python
import math
c=50
@@ -175,6 +192,7 @@ for d in items:
print(','.join(value))
```
+
### Question 7
Level 2
@@ -191,7 +209,9 @@ 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:
+
+Show Solution
+
```python
input_str = input()
dimensions=[int(x) for x in input_str.split(',')]
@@ -205,6 +225,7 @@ for row in range(rowNum):
print(multilist)
```
+
### Question 8
Level 2
@@ -219,12 +240,15 @@ 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:
+
+Show Solution
+
```python
items=[x for x in input().split(',')]
items.sort()
print(','.join(items))
```
+
### Question 9
Level 2
@@ -241,7 +265,9 @@ PRACTICE MAKES PERFECT
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
-Solution:
+
+Show Solution
+
```python
lines = []
while True:
@@ -254,6 +280,7 @@ while True:
for sentence in lines:
print(sentence)
```
+
### Question 10
Level 2
@@ -269,12 +296,15 @@ 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:
+
+Show Solution
+
```python
s = input()
words = [word for word in s.split(" ")]
print(" ".join(sorted(list(set(words)))))
```
+
### Question 11
Level 2
@@ -290,7 +320,9 @@ 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:
+
+Show Solution
+
```python
value = []
items=[x for x in input().split(',')]
@@ -301,6 +333,7 @@ for p in items:
print(','.join(value))
```
+
### Question 12
Level 2
@@ -312,7 +345,9 @@ 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:
+
+Show Solution
+
```python
values = []
for i in range(1000, 3001):
@@ -321,6 +356,7 @@ for i in range(1000, 3001):
values.append(s)
print(",".join(values))
```
+
### Question 13
Level 2
@@ -336,7 +372,9 @@ DIGITS 3
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
-Solution:
+
+Show Solution
+
```python
s = input()
d={"DIGITS":0, "LETTERS":0}
@@ -350,6 +388,7 @@ for c in s:
print("LETTERS", d["LETTERS"])
print("DIGITS", d["DIGITS"])
```
+
### Question 14
Level 2
@@ -365,7 +404,9 @@ LOWER CASE 9
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
-Solution:
+
+Show Solution
+
```python
s = input()
d={"UPPER CASE":0, "LOWER CASE":0}
@@ -379,6 +420,7 @@ for c in s:
print("UPPER CASE", d["UPPER CASE"])
print("LOWER CASE", d["LOWER CASE"])
```
+
### Question 15
Level 2
@@ -393,7 +435,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:
+
+Show Solution
```python
a = input()
@@ -403,6 +446,7 @@ 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
@@ -417,13 +461,15 @@ 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:
+
+Show Solution
```python
values = input()
numbers = [x for x in values.split(",") if int(x)%2!=0]
print(",".join(numbers))
```
+
### Question 17
Level 2
@@ -445,7 +491,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:
+
+Show Solution
```python
netAmount = 0
@@ -464,6 +511,7 @@ while True:
pass
print(netAmount)
```
+
### Question 18
Level 3
@@ -487,7 +535,8 @@ ABd1234@1
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
-Solutions:
+
+Show Solution
```python
import re
@@ -513,6 +562,7 @@ for p in items:
value.append(p)
print(",".join(value))
```
+
### Question 19
Level 3
@@ -536,10 +586,12 @@ 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
+
+Show Solution
```python
+from operator import itemgetter, attrgetter
+
l = []
while True:
s = input()
@@ -549,6 +601,7 @@ while True:
print(sorted(l, key=itemgetter(0,1,2)))
```
+
### Question 20
Level 3
@@ -559,7 +612,8 @@ Define a class with a generator which can iterate the numbers, which are divisib
Hints:
Consider use yield
-Solution:
+
+Show Solution
```python
def putNumbers(n):
@@ -573,6 +627,7 @@ def putNumbers(n):
for i in reverse(100):
print(i)
```
+
### Question 21
Level 3
@@ -597,7 +652,8 @@ Then, the output of the program should be:
Hints:
In case of input data being supplied to the question, it should be assumed to be a console input.
-Solution:
+
+Show Solution
```python
import math
@@ -622,6 +678,7 @@ while True:
print(int(round(math.sqrt(pos[1]**2+pos[0]**2))))
```
+
### Question 22
Level 3
@@ -646,7 +703,8 @@ to:1
Hints
In case of input data being supplied to the question, it should be assumed to be a console input.
-Solution:
+
+Show Solution
```python
freq = {} # frequency of words in text
@@ -660,6 +718,7 @@ words.sort()
for w in words:
print("%s:%d" % (w,freq[w]))
```
+
### Question 23
level 1
@@ -670,7 +729,8 @@ Write a method which can calculate square value of number
Hints:
Using the ** operator
-Solution:
+
+Show Solution
```python
def square(num):
@@ -679,6 +739,7 @@ def square(num):
print(square(2))
print(square(3))
```
+
### Question 24
Level 1
@@ -693,7 +754,9 @@ And add document for your own function
Hints:
The built-in document method is __doc__
-Solution:
+
+Show Solution
+
```python
print(abs.__doc__)
print(int.__doc__)
@@ -709,6 +772,7 @@ def square(num):
print(square(2))
print(square.__doc__)
```
+
### Question 25
Level 1
@@ -719,7 +783,9 @@ 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:
+
+Show Solution
+
```python
class Person:
# Define the class parameter "name"
@@ -736,6 +802,7 @@ nico = Person()
nico.name = "Nico"
print("%s name is %s" % (Person.name, nico.name))
```
+
### Question 26:
Define a function which can compute the sum of two numbers.
@@ -743,7 +810,8 @@ 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
+
+Show Solution
```python
def SumFunction(number1, number2):
@@ -751,6 +819,7 @@ def SumFunction(number1, number2):
print(SumFunction(1,2))
```
+
### Question 27
Define a function that can convert a integer into a string and print it in console.
@@ -759,13 +828,16 @@ Hints:
Use str() to convert a number to string.
-Solution
+
+Show Solution
+
```python
def printValue(n):
print(str(n))
printValue(3)
```
+
### Question 28
Define a function that can convert a integer into a string and print it in console.
@@ -774,13 +846,16 @@ Hints:
Use str() to convert a number to string.
-Solution
+
+Show Solution
+
```python
def printValue(n):
print(str(n))
printValue(3)
```
+
### Question 29
Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
@@ -789,13 +864,16 @@ Hints:
Use int() to convert a string to integer.
-Solution
+
+Show Solution
+
```python
def printValue(s1,s2):
print(int(s1)+int(s2))
printValue("3","4")
```
+
### Question 30
Define a function that can accept two strings as input and concatenate them and then print it in console.
@@ -804,13 +882,16 @@ Hints:
Use + to concatenate the strings
-Solution
+
+Show Solution
+
```python
def printValue(s1,s2):
print(s1+s2)
printValue("3","4") #34
```
+
### Question 31
Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line.
@@ -819,7 +900,9 @@ Hints:
Use len() function to get the length of a string
-Solution
+
+Show Solution
+
```python
def printValue(s1,s2):
len1 = len(s1)
@@ -835,6 +918,8 @@ def printValue(s1,s2):
printValue("one","three")
```
+
+
### Question 32
Define a function that can accept an integer number as input and print the "It is an even number" if the number is even, otherwise print "It is an odd number".
@@ -842,7 +927,9 @@ Hints:
Use % operator to check if a number is even or odd.
-Solution
+
+Show Solution
+
```python
def checkValue(n):
if n%2 == 0:
@@ -851,16 +938,20 @@ def checkValue(n):
print("It is an odd number")
checkValue(7)
+```
+
### Question 33
Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included) and the values are square of keys.
Hints:
-Use dict[key]=value pattern to put entry into a dictionary.
+Use `dict[key]=value` pattern to put entry into a dictionary.
Use ** operator to get power of a number.
-Solution
+
+Show Solution
+
```python
def printDict():
d=dict()
@@ -871,6 +962,9 @@ def printDict():
printDict()
```
+
+
+
### Question 34
Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys.
@@ -880,7 +974,8 @@ Use dict[key]=value pattern to put entry into a dictionary.
Use ** operator to get power of a number.
Use range() for loops.
-Solution
+
+Show Solution
```python
def printDict():
d=dict()
@@ -890,6 +985,7 @@ def printDict():
printDict()
```
+
### Question 35
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only.
@@ -901,7 +997,9 @@ 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
+
+Show Solution
+
```python
def printDict():
d=dict()
@@ -912,6 +1010,7 @@ def printDict():
printDict()
```
+
### Question 36
Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the keys only.
@@ -923,7 +1022,9 @@ 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
+
+Show Solution
+
```python
def printDict():
d=dict()
@@ -934,6 +1035,7 @@ def printDict():
printDict()
```
+
### Question 37
Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included).
@@ -944,7 +1046,9 @@ Use ** operator to get power of a number.
Use range() for loops.
Use list.append() to add values into a list.
-Solution
+
+Show Solution
+
```python
def printList():
li=list()
@@ -954,6 +1058,7 @@ def printList():
printList()
```
+
### Question 38
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the first 5 elements in the list.
@@ -964,7 +1069,9 @@ Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
-Solution
+
+Show Solution
+
```python
def printList():
li=list()
@@ -974,6 +1081,7 @@ def printList():
printList()
```
+
### Question 39
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print the last 5 elements in the list.
@@ -985,7 +1093,9 @@ Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
-Solution
+
+Show Solution
+
```python
def printList():
li=list()
@@ -995,6 +1105,7 @@ def printList():
printList()
```
+
### Question 40
Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to print all values except the first 5 elements in the list.
@@ -1005,7 +1116,9 @@ Use range() for loops.
Use list.append() to add values into a list.
Use [n1:n2] to slice a list
-Solution
+
+Show Solution
+
```python
def printList():
li=list()
@@ -1015,6 +1128,7 @@ def printList():
printList()
```
+
### Question 41
Define a function which can generate and print a tuple where the value are square of numbers between 1 and 20 (both included).
@@ -1026,7 +1140,9 @@ Use range() for loops.
Use list.append() to add values into a list.
Use tuple() to get a tuple from a list.
-Solution
+
+Show Solution
+
```python
def printTuple():
li=list()
@@ -1036,6 +1152,7 @@ def printTuple():
printTuple()
```
+
### Question 42
With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and the last half values in one line.
@@ -1043,7 +1160,9 @@ Hints:
Use [n1:n2] notation to get a slice from a tuple.
-Solution
+
+Show Solution
+
```python
tp=(1,2,3,4,5,6,7,8,9,10)
tp1=tp[:5]
@@ -1051,6 +1170,7 @@ tp2=tp[5:]
print(tp1)
print(tp2)
```
+
### Question 43
Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
@@ -1060,7 +1180,9 @@ Hints:
Use "for" to iterate the tuple
Use tuple() to generate a tuple from a list.
-Solution
+
+Show Solution
+
```python
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
@@ -1071,6 +1193,8 @@ for i in tp:
tp2=tuple(li)
print(tp2)
```
+
+
### Question 44
Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No".
@@ -1078,7 +1202,9 @@ Hints:
Use if statement to judge condition.
-Solution
+
+Show Solution
+
```python
s= raw_input()
if s=="yes" or s=="YES" or s=="Yes":
@@ -1086,6 +1212,8 @@ if s=="yes" or s=="YES" or s=="Yes":
else:
print "No"
```
+
+
### Question 45
Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10].
@@ -1094,12 +1222,15 @@ Hints:
Use filter() to filter some elements in a list.
Use lambda to define anonymous functions.
-Solution
+
+Show Solution
+
```python
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print(evenNumbers)
```
+
### Question 46
Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
@@ -1108,12 +1239,15 @@ Hints
Use map() to generate a list.
Use lambda to define anonymous functions.
-Solution
+
+Show Solution
+
```python
li = [1,2,3,4,5,6,7,8,9,10]
squaredNumbers = map(lambda x: x**2, li)
print(squaredNumbers)
```
+
### Question 47
Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
@@ -1123,12 +1257,16 @@ Use map() to generate a list.
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
-Solution
+
+Show Solution
+
```python
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 48
Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included).
@@ -1137,11 +1275,14 @@ Hints:
Use filter() to filter elements of a list.
Use lambda to define anonymous functions.
-Solution
+
+Show Solution
+
```python
evenNumbers = filter(lambda x: x%2==0, range(1,21))
print(evenNumbers)
```
+
### Question 49
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
@@ -1150,11 +1291,14 @@ Hints
Use map() to generate a list.
Use lambda to define anonymous functions.
-Solution
+
+Show Solution
+
```python
squaredNumbers = map(lambda x: x**2, range(1,21))
print(squaredNumbers)
```
+
### Question 50
Define a class named American which has a static method called printNationality.
@@ -1162,7 +1306,9 @@ Define a class named American which has a static method called printNationality.
Hints:
Use @staticmethod decorator to define class static method.
-Solution
+
+Show Solution
+
```python
class American(object):
@staticmethod
@@ -1173,6 +1319,7 @@ anAmerican = American()
anAmerican.printNationality()
American.printNationality()
```
+
### Question 51
Define a class named American and its subclass NewYorker.
@@ -1181,7 +1328,9 @@ Hints:
Use class Subclass(ParentClass) to define a subclass.
-Solution:
+
+Show Solution
+
```python
class American(object):
pass
@@ -1194,6 +1343,7 @@ aNewYorker = NewYorker()
print(anAmerican)
print(aNewYorker)
```
+
### Question 52
Define a class named Circle which can be constructed by a radius. The Circle class has a method which can compute the area.
@@ -1202,7 +1352,9 @@ Hints:
Use def methodName(self) to define a method.
-Solution:
+
+Show Solution
+
```python
class Circle(object):
def __init__(self, r):
@@ -1214,6 +1366,7 @@ class Circle(object):
aCircle = Circle(2)
print aCircle.area()
```
+
### Question 53
Define a class named Rectangle which can be constructed by a length and width. The Rectangle class has a method which can compute the area.
@@ -1222,7 +1375,9 @@ Hints:
Use def methodName(self) to define a method.
-Solution:
+
+Show Solution
+
```python
class Rectangle(object):
def __init__(self, l, w):
@@ -1235,6 +1390,7 @@ class Rectangle(object):
aRectangle = Rectangle(2,10)
print(aRectangle.area())
```
+
### Question 54
Define a class named Shape and its subclass Square. The Square class has an init function which takes a length as argument. Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
@@ -1243,7 +1399,9 @@ Hints:
To override a method in super class, we can define a method with the same name in the super class.
-Solution:
+
+Show Solution
+
```python
class Shape(object):
def __init__(self):
@@ -1263,6 +1421,7 @@ class Square(Shape):
aSquare= Square(3)
print(aSquare.area())
```
+
### Question 55
Please raise a RuntimeError exception.
@@ -1271,11 +1430,13 @@ Hints:
Use raise() to raise an exception.
-Solution:
+
+Show Solution
```python
raise RuntimeError('something wrong')
```
+
### Question 56
Write a function to compute 5/0 and use try/except to catch the exceptions.
@@ -1284,7 +1445,9 @@ Hints:
Use try/except to catch exceptions.
-Solution:
+
+Show Solution
+
```python
def throws():
return 5/0
@@ -1298,6 +1461,7 @@ except Exception, err:
finally:
print('In finally block for cleanup')
```
+
### Question 57
Define a custom exception class which takes a string message as attribute.
@@ -1306,7 +1470,9 @@ Hints:
To define a custom exception, we need to define a class inherited from Exception.
-Solution:
+
+Show Solution
+
```python
class MyError(Exception):
"""My own exception class
@@ -1320,6 +1486,7 @@ class MyError(Exception):
error = MyError("something wrong")
```
+
### Question 58
Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
@@ -1339,7 +1506,9 @@ Hints:
Use \w to match letters.
-Solution:
+
+Show Solution
+
```python
import re
emailAddress = raw_input()
@@ -1347,6 +1516,7 @@ pat2 = "(\w+)@((\w+\.)+(com))"
r2 = re.match(pat2,emailAddress)
print(r2.group(1))
```
+
### Question 59
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.
@@ -1366,7 +1536,9 @@ Hints:
Use \w to match letters.
-Solution:
+
+Show Solution
+
```python
import re
emailAddress = raw_input()
@@ -1374,6 +1546,7 @@ pat2 = "(\w+)@(\w+)\.(com)"
r2 = re.match(pat2,emailAddress)
print(r2.group(2))
```
+
### Question 60
Write a program which accepts a sequence of words separated by whitespace as input to print the words composed of digits only.
@@ -1393,12 +1566,15 @@ Hints:
Use re.findall() to find all substring using regex.
-Solution:
+
+Show Solution
+
```python
import re
s = raw_input()
print(re.findall("\d+",s))
```
+
### Question 61
Print a unicode string "hello world".
@@ -1407,11 +1583,14 @@ Hints:
Use u'strings' format to define unicode string.
-Solution:
+
+Show Solution
+
```python
unicodeString = u"hello world!"
print(unicodeString)
```
+
### Question 62
Write a program to read an ASCII string and to convert it to a unicode string encoded by utf-8.
@@ -1420,12 +1599,15 @@ Hints:
Use unicode() function to convert.
-Solution:
+
+Show Solution
+
```python
s = input()
u = unicode( s ,"utf-8")
print(u)
```
+
### Question 63
@@ -1433,13 +1615,16 @@ Write a special comment to indicate a Python source code file is in unicode.
Hints:
-Solution:
+
+Show Solution
+
```python
# -*- coding: utf-8 -*-
#----------------------------------------#
```
+
### Question 64
@@ -1459,7 +1644,9 @@ 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:
+
+Show Solution
+
```python
n=int(input())
sum=0.0
@@ -1467,6 +1654,7 @@ for i in range(1,n+1):
sum += float(float(i)/(i+1))
print(sum)
```
+
### Question 65
@@ -1491,7 +1679,9 @@ 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:
+
+Show Solution
+
```python
def f(n):
if n==0:
@@ -1502,6 +1692,7 @@ def f(n):
n=int(input())
print(f(n))
```
+
### Question 66
The Fibonacci Sequence is computed based on the following formula:
@@ -1527,7 +1718,9 @@ Hints:
We can define recursive function in Python.
-Solution:
+
+Show Solution
+
```python
def f(n):
if n == 0: return 0
@@ -1537,6 +1730,7 @@ def f(n):
n=int(input())
print(f(n))
```
+
### Question 67
The Fibonacci Sequence is computed based on the following formula:
@@ -1564,7 +1758,9 @@ 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:
+
+Show Solution
+
```python
def f(n):
if n == 0: return 0
@@ -1575,6 +1771,7 @@ n=int(input())
values = [str(f(x)) for x in range(0, n+1)]
print(",".join(values))
```
+
### Question 68
@@ -1594,7 +1791,9 @@ 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:
+
+Show Solution
+
```python
def EvenGenerator(n):
i=0
@@ -1611,6 +1810,7 @@ for i in EvenGenerator(n):
print(",".join(values))
```
+
### Question 69
Please write a program using generator to print the numbers which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
@@ -1629,7 +1829,9 @@ 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:
+
+Show Solution
+
```python
def NumGenerator(n):
for i in range(n+1):
@@ -1643,6 +1845,7 @@ for i in NumGenerator(n):
print(",".join(values))
```
+
### Question 70
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
@@ -1650,12 +1853,15 @@ Please write assert statements to verify that every number in the list [2,4,6,8]
Hints:
Use "assert expression" to make assertion.
-Solution:
+
+Show Solution
+
```python
li = [2,4,6,8]
for i in li:
assert i%2==0
```
+
### Question 71
Please write a program which accepts basic mathematic expression from console and print the evaluation result.
@@ -1673,11 +1879,14 @@ Hints:
Use eval() to evaluate an expression.
-Solution:
+
+Show Solution
+
```python
expression = raw_input()
print(eval(expression))
```
+
### Question 72
Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
@@ -1685,7 +1894,9 @@ Please write a binary search function which searches an item in a sorted list. T
Hints:
Use if/elif to deal with conditions.
-Solution:
+
+Show Solution
+
```python
import math
def bin_search(li, element):
@@ -1707,6 +1918,7 @@ li=[2,5,7,9,11,17,222]
print(bin_search(li,11))
print(bin_search(li,12))
```
+
### Question 73
Please write a binary search function which searches an item in a sorted list. The function should return the index of element to be searched in the list.
@@ -1714,7 +1926,9 @@ Please write a binary search function which searches an item in a sorted list. T
Hints:
Use if/elif to deal with conditions.
-Solution:
+
+Show Solution
+
```python
import math
def bin_search(li, element):
@@ -1736,6 +1950,7 @@ li=[2,5,7,9,11,17,222]
print(bin_search(li,11))
print(bin_search(li,12))
```
+
### Question 74
Please generate a random float where the value is between 10 and 100 using Python math module.
@@ -1743,11 +1958,14 @@ Please generate a random float where the value is between 10 and 100 using Pytho
Hints:
Use random.random() to generate a random float in [0,1].
-Solution:
+
+Show Solution
+
```python
import random
print(random.random()*100)
```
+
### Question 75
Please generate a random float where the value is between 5 and 95 using Python math module.
@@ -1755,11 +1973,14 @@ Please generate a random float where the value is between 5 and 95 using Python
Hints:
Use random.random() to generate a random float in [0,1].
-Solution:
+
+Show Solution
+
```python
import random
print(random.random()*100-5)
```
+
### Question 76
Please write a program to output a random even number between 0 and 10 inclusive using random module and list comprehension.
@@ -1767,11 +1988,14 @@ Please write a program to output a random even number between 0 and 10 inclusive
Hints:
Use random.choice() to a random element from a list.
-Solution:
+
+Show Solution
+
```python
import random
print(random.choice([i for i in range(11) if i%2==0]))
```
+
### Question 77
Please write a program to output a random number, which is divisible by 5 and 7, between 0 and 10 inclusive using random module and list comprehension.
@@ -1779,11 +2003,14 @@ Please write a program to output a random number, which is divisible by 5 and 7,
Hints:
Use random.choice() to a random element from a list.
-Solution:
+
+Show Solution
+
```python
import random
print(random.choice([i for i in range(201) if i%5==0 and i%7==0]))
```
+
### Question 78
Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
@@ -1791,11 +2018,14 @@ Please write a program to generate a list with 5 random numbers between 100 and
Hints:
Use random.sample() to generate a list of random values.
-Solution:
+
+Show Solution
+
```python
import random
print(random.sample(range(100), 5))
```
+
### Question 79
Please write a program to randomly generate a list with 5 even numbers between 100 and 200 inclusive.
@@ -1803,11 +2033,14 @@ Please write a program to randomly generate a list with 5 even numbers between 1
Hints:
Use random.sample() to generate a list of random values.
-Solution:
+
+Show Solution
+
```python
import random
print(random.sample([i for i in range(100,201) if i%2==0], 5))
```
+
### Question 80
Please write a program to randomly generate a list with 5 numbers, which are divisible by 5 and 7 , between 1 and 1000 inclusive.
@@ -1815,11 +2048,14 @@ Please write a program to randomly generate a list with 5 numbers, which are div
Hints:
Use random.sample() to generate a list of random values.
-Solution:
+
+Show Solution
+
```python
import random
print(random.sample([i for i in range(1,1001) if i%5==0 and i%7==0], 5))
```
+
### Question 81
Please write a program to randomly print a integer number between 7 and 15 inclusive.
@@ -1827,11 +2063,14 @@ Please write a program to randomly print a integer number between 7 and 15 inclu
Hints:
Use random.randrange() to a random integer in a given range.
-Solution:
+
+Show Solution
+
```python
import random
print(random.randrange(7,16))
```
+
### Question 82
Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
@@ -1839,7 +2078,9 @@ Please write a program to compress and decompress the string "hello world!hello
Hints:
Use zlib.compress() and zlib.decompress() to compress and decompress a string.
-Solution:
+
+Show Solution
+
```python
import zlib
s = b'hello world!hello world!hello world!hello world!'
@@ -1847,6 +2088,7 @@ t = zlib.compress(s)
print(t)
print(zlib.decompress(t))
```
+
### Question 83
Please write a program to print the running time of execution of "1+1" for 100 times.
@@ -1854,12 +2096,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:
+
+Show Solution
+
```python
from timeit import Timer
t = Timer("for i in range(100):1+1")
print(t.timeit())
```
+
### Question 84
Please write a program to shuffle and print the list [3,6,7,8].
@@ -1867,13 +2112,16 @@ Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
-Solution:
+
+Show Solution
+
```python
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print(li)
```
+
### Question 85
Please write a program to shuffle and print the list [3,6,7,8].
@@ -1881,13 +2129,16 @@ Please write a program to shuffle and print the list [3,6,7,8].
Hints:
Use shuffle() function to shuffle a list.
-Solution:
+
+Show Solution
+
```python
from random import shuffle
li = [3,6,7,8]
shuffle(li)
print(li)
```
+
### Question 86
Please write a program to generate all sentences where subject is in ["I", "You"] and verb is in ["Play", "Love"] and the object is in ["Hockey","Football"].
@@ -1895,7 +2146,9 @@ 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:
+
+Show Solution
+
```python
subjects=["I", "You"]
verbs=["Play", "Love"]
@@ -1906,6 +2159,7 @@ for i in range(len(subjects)):
sentence = "%s %s %s." % (subjects[i], verbs[j], objects[k])
print(sentence)
```
+
### Question 87
Please write a program to print the list after removing delete even numbers in [5,6,77,45,22,12,24].
@@ -1913,25 +2167,30 @@ 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:
-```
+
+Show Solution
+
+```python
li = [5,6,77,45,22,12,24]
li = [x for x in li if x%2!=0]
print(li)
```
+
### Question 88
By using list comprehension, please write a program to print the list after removing delete numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].
Hints:
Use list comprehension to delete a bunch of element from a list.
+
+Show 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 89
By using list comprehension, please write a program to print the list after removing the 0th, 2nd, 4th,6th numbers in [12,24,35,70,88,120,155].
@@ -1940,12 +2199,15 @@ Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
-Solution:
+
+Show 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 90
By using list comprehension, please write a program generate a 3*5*8 3D array whose each element is 0.
@@ -1953,11 +2215,14 @@ 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:
-```
+
+Show Solution
+
+```python
array = [[ [0 for col in range(8)] for col in range(5)] for row in range(3)]
print(array)
```
+
### Question 91
By using list comprehension, please write a program to print the list after removing the 0th,4th,5th numbers in [12,24,35,70,88,120,155].
@@ -1966,12 +2231,15 @@ Hints:
Use list comprehension to delete a bunch of element from a list.
Use enumerate() to get (index, value) tuple.
-Solution:
+
+Show 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 92
By using list comprehension, please write a program to print the list after removing the value 24 in [12,24,35,24,88,120,155].
@@ -1979,12 +2247,15 @@ 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:
+
+Show Solution
+
```python
li = [12,24,35,24,88,120,155]
li = [x for x in li if x!=24]
print(li)
```
+
### Question 93
With two given lists [1,3,6,78,35,55] and [12,24,35,24,88,120,155], write a program to make a list whose elements are intersection of the above given lists.
@@ -1992,7 +2263,9 @@ 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:
+
+Show Solution
+
```python
set1=set([1,3,6,78,35,55])
set2=set([12,24,35,24,88,120,155])
@@ -2000,6 +2273,7 @@ set1 &= set2
li=list(set1)
print(li)
```
+
### Question 94
With a given list [12,24,35,24,88,120,155,88,120,155], write a program to print this list after removing all duplicate values with original order reserved.
@@ -2007,7 +2281,9 @@ 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:
+
+Show Solution
+
```python
def removeDuplicate( li ):
newli=[]
@@ -2022,6 +2298,7 @@ def removeDuplicate( li ):
li=[12,24,35,24,88,120,155,88,120,155]
print(removeDuplicate(li))
```
+
### Question 95
Define a class Person and its two child classes: Male and Female. All classes have a method "getGender" which can print "Male" for Male class and "Female" for Female class.
@@ -2029,7 +2306,9 @@ 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:
+
+Show Solution
+
```python
class Person(object):
def getGender( self ):
@@ -2048,6 +2327,7 @@ aFemale= Female()
print(aMale.getGender())
print(aFemale.getGender())
```
+
### Question 96
Please write a program which count and print the numbers of each character in a string input by console.
@@ -2071,7 +2351,9 @@ Hints:
Use dict to store key/value pairs.
Use dict.get() method to lookup a key with default value.
-Solution:
+
+Show Solution
+
```python
dic = {}
s=raw_input()
@@ -2079,6 +2361,7 @@ 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 97
Please write a program which accepts a string from console and print it in reverse order.
@@ -2095,12 +2378,15 @@ ris etov ot esir
Hints:
Use list[::-1] to iterate a list in a reverse order.
-Solution:
+
+Show Solution
+
```python
s=raw_input()
s = s[::-1]
print(s)
```
+
### Question 98
Please write a program which accepts a string from console and print the characters that have even indexes.
@@ -2117,12 +2403,15 @@ Helloworld
Hints:
Use list[::2] to iterate a list by step 2.
-Solution:
+
+Show Solution
+
```python
s=raw_input()
s = s[::2]
print(s)
```
+
### Question 99
Please write a program which prints all permutations of [1,2,3]
@@ -2130,11 +2419,14 @@ Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
-Solution:
+
+Show Solution
+
```python
import itertools
print(list(itertools.permutations([1,2,3])))
```
+
### Question 100
Write a program to solve a classic ancient Chinese puzzle:
@@ -2143,7 +2435,9 @@ 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:
+
+Show Solution
+
```python
def solve(numheads,numlegs):
ns='No solutions!'
@@ -2158,4 +2452,5 @@ numlegs=94
solutions=solve(numheads,numlegs)
print(solutions)
```
+