

























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Scientific Computing
Typology: Exercises
1 / 33
This page cannot be seen from the preview
Don't miss anything!


























zhiwehu / Python-programming-exercises^50 213 Code Issues 2 Pull requests 5 Branch: master Find file Copy path 81b147a on Jun 20, 2012 1 contributor xinlincao added more questions 2377 lines (1585 sloc) 50.1 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 Raw Blame History 100+ Python challenging programming exercises
def fact(x): if x == 0: return 1 return x * fact(x - 1) x=int(raw_input()) print fact(x) #----------------------------------------# #----------------------------------------# Question 3 Level 1 Question: With a given integral number n, write a program to generate a dictionary that contains (i, ii) such that is an integral number between 1 and n ( Suppose the following input is supplied to the program: 8 Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Consider use dict() Solution: n=int(raw_input()) d=dict() for i in range(1,n+1): d[i]=ii print d #----------------------------------------# #----------------------------------------# Question 4 Level 1 Question: Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12, Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98') Hints: In case of input data being supplied to the question, it should be assumed to be a console input. tuple() method can convert list to tuple Solution: values=raw_input() l=values.split(",") t=tuple(l) print l print t #----------------------------------------# #----------------------------------------# Question 5 Level 1 Question: Define a class which has at least two methods: getString: to get a string from console input printString: to print the string in upper case. Also please include simple test function to test the class methods. Hints: Use init method to construct some parameters Solution: class InputOutString(object): def init(self): self.s = ""
Question 8 Level 2 Question: Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence after sorting them a Suppose the following input is supplied to the program: without,hello,bag,world Then, the output should be: bag,hello,without,world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: items=[x for x in raw_input().split(',')] items.sort() print ','.join(items) #----------------------------------------# #----------------------------------------# Question 9 Level 2 Question£º Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print sentence #----------------------------------------# #----------------------------------------# Question 10 Level 2 Question: Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sortin Suppose the following input is supplied to the program: hello world and practice makes perfect and hello world again Then, the output should be: again and hello makes perfect practice world Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use set container to remove duplicated data automatically and then use sorted() to sort the data. Solution: s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) #----------------------------------------# #----------------------------------------# Question 11 Level 2
Question: Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether they are divisible by 5 or Example: 0100,0011,1010, Then the output should be: 1010 Notes: Assume the data is input by console. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: value = [] items=[x for x in raw_input().split(',')] for p in items: intp = int(p, 2) if not intp%5: value.append(p) print ','.join(value) #----------------------------------------# #----------------------------------------# Question 12 Level 2 Question: Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: values = [] for i in range(1000, 3001): s = str(i) if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0) and (int(s[3])%2==0): values.append(s) print ",".join(values) #----------------------------------------# #----------------------------------------# Question 13 Level 2 Question: Write a program that accepts a sentence and calculate the number of letters and digits. Suppose the following input is supplied to the program: hello world! 123 Then, the output should be: LETTERS 10 DIGITS 3 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: s = raw_input() d={"DIGITS":0, "LETTERS":0} for c in s: if c.isdigit(): d["DIGITS"]+= elif c.isalpha(): d["LETTERS"]+= else: pass print "LETTERS", d["LETTERS"] print "DIGITS", d["DIGITS"] #----------------------------------------# #----------------------------------------# Question 14
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 D 100 W 200 ¡ D means deposit while W means withdrawal. Suppose the following input is supplied to the program: D 300 D 300 W 200 D 100 Then, the output should be: 500 Hints: In case of input data being supplied to the question, it should be assumed to be a console input. Solution: import sys netAmount = 0 while True: s = raw_input() if not s: break values = s.split(" ") operation = values[0] amount = int(values[1]) if operation=="D": netAmount+=amount elif operation=="W": netAmount-=amount else: pass print netAmount #----------------------------------------# #----------------------------------------# Question 18 Level 3 Question: A website requires the users to input username and password to register. Write a program to check the validity of password input by users. Following are the criteria for checking the password:
continue elif re.search("\s",p): continue else: pass value.append(p) print ",".join(value) #----------------------------------------# #----------------------------------------# Question 19 Level 3 Question: You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers. T 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score. The priority is that name > age > score. If the following tuples are given as input to the program: Tom,19, John,20, Jony,17, Jony,17, Json,21, Then, the output of the program should be: [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] Hints: In case of input data being supplied to the question, it should be assumed to be a console input. We use itemgetter to enable multiple sort keys. Solutions: from operator import itemgetter, attrgetter l = [] while True: s = raw_input() if not s: break l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) #----------------------------------------# #----------------------------------------# Question 20 Level 3 Question: Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n. Hints: Consider use yield Solution: def putNumbers(n): i = 0 while i
for w in words: print "%s:%d" % (w,freq[w]) #----------------------------------------# #----------------------------------------# Question 23 level 1 Question: Write a method which can calculate square value of number Hints: Using the ** operator Solution: def square(num): return num ** 2 print square(2) print square(3) #----------------------------------------# #----------------------------------------# Question 24 Level 1 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 b Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input() And add document for your own function Hints: The built-in document method is doc Solution: print abs.doc print int.doc print raw_input.doc def square(num): '''Return the square value of the input number. The input number must be integer. ''' return num ** 2 print square(2) print square.doc #----------------------------------------# #----------------------------------------# Question 25 Level 1 Question: Define a class, which have a class parameter and have a same instance parameter. Hints: Define a instance parameter, need add it in init method You can init a object with construct parameter or set the value later Solution: class Person:
name = "Person" def init(self, name = None):
self.name = name jeffrey = Person("Jeffrey") print "%s name is %s" % (Person.name, jeffrey.name)
nico = Person() nico.name = "Nico" print "%s name is %s" % (Person.name, nico.name) #----------------------------------------# #----------------------------------------# Question: Define a function which can compute the sum of two numbers. Hints: Define a function with two numbers as arguments. You can compute the sum in the function and return the value. Solution def SumFunction(number1, number2): return number1+number print SumFunction(1,2) #----------------------------------------# Question: Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. Solution def printValue(n): print str(n) printValue(3) #----------------------------------------# Question: Define a function that can convert a integer into a string and print it in console. Hints: Use str() to convert a number to string. Solution def printValue(n): print str(n) printValue(3) #----------------------------------------#
Question: Define a function that can receive two integral numbers in string form and compute their sum and then print it in console. Hints: Use int() to convert a string to integer. Solution def printValue(s1,s2): print int(s1)+int(s2) printValue("3","4") # #----------------------------------------#
Question: Define a function that can accept two strings as input and concatenate them and then print it in console. Hints: Use + to concatenate the strings
printDict() #----------------------------------------#
Question: Define a function which can print a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i** print d printDict() #----------------------------------------#
Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i** for (k,v) in d.items(): print v printDict() #----------------------------------------#
Question: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. Hints: Use dict[key]=value pattern to put entry into a dictionary. Use ** operator to get power of a number. Use range() for loops. Use keys() to iterate keys in the dictionary. Also we can use item() to get key/value pairs. Solution def printDict(): d=dict() for i in range(1,21): d[i]=i** for k in d.keys():
print k printDict() #----------------------------------------#
Question: Define a function which can generate and print a list where the values are square of numbers between 1 and 20 (both included). Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li printList() #----------------------------------------#
Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to p Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[:5] printList() #----------------------------------------#
Question: Define a function which can generate a list where the values are square of numbers between 1 and 20 (both included). Then the function needs to p Hints: Use ** operator to get power of a number. Use range() for loops. Use list.append() to add values into a list. Use [n1:n2] to slice a list Solution def printList(): li=list() for i in range(1,21): li.append(i**2) print li[-5:] printList()
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 tp #----------------------------------------#
Question: Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise print "No". Hints: Use if statement to judge condition. Solution s= raw_input() if s=="yes" or s=="YES" or s=="Yes": print "Yes" else: print "No" #----------------------------------------#
Question: Write a program which can filter even numbers in a list by using filter function. The list is: [1,2,3,4,5,6,7,8,9,10]. Hints: Use filter() to filter some elements in a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = filter(lambda x: x%2==0, li) print evenNumbers #----------------------------------------#
Question: Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10]. Hints: Use map() to generate a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] squaredNumbers = map(lambda x: x**2, li) print squaredNumbers #----------------------------------------#
Question: Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
Hints: Use map() to generate a list. Use filter() to filter elements of a list. Use lambda to define anonymous functions. Solution li = [1,2,3,4,5,6,7,8,9,10] evenNumbers = map(lambda x: x**2, filter(lambda x: x%2==0, li)) print evenNumbers #----------------------------------------#
Question: Write a program which can filter() to make a list whose elements are even number between 1 and 20 (both included). Hints: Use filter() to filter elements of a list. Use lambda to define anonymous functions. Solution evenNumbers = filter(lambda x: x%2==0, range(1,21)) print evenNumbers #----------------------------------------#
Question: Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included). Hints: Use map() to generate a list. Use lambda to define anonymous functions. Solution squaredNumbers = map(lambda x: x**2, range(1,21)) print squaredNumbers #----------------------------------------#
Question: Define a class named American which has a static method called printNationality. Hints: Use @staticmethod decorator to define class static method. Solution class American(object): @staticmethod def printNationality(): print "America" anAmerican = American() anAmerican.printNationality() American.printNationality() #----------------------------------------#
aRectangle = Rectangle(2,10) print aRectangle.area() #----------------------------------------#
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 a Hints: To override a method in super class, we can define a method with the same name in the super class. Solution: class Shape(object): def init(self): pass def area(self): return 0 class Square(Shape): def init(self, l): Shape.init(self) self.length = l def area(self): return self.length*self.length aSquare= Square(3) print aSquare.area() #----------------------------------------# Please raise a RuntimeError exception. Hints: Use raise() to raise an exception. Solution: raise RuntimeError('something wrong') #----------------------------------------# Write a function to compute 5/0 and use try/except to catch the exceptions. Hints: Use try/except to catch exceptions. Solution: def throws(): return 5/ try: throws() except ZeroDivisionError: print "division by zero!"
except Exception, err: print 'Caught an exception' finally: print 'In finally block for cleanup' #----------------------------------------# Define a custom exception class which takes a string message as attribute. Hints: To define a custom exception, we need to define a class inherited from Exception. Solution: class MyError(Exception): """My own exception class Attributes: msg -- explanation of the error """ def init(self, msg): self.msg = msg error = MyError("something wrong") #----------------------------------------# Question: Assuming that we have some email addresses in the "[email protected]" format, please write program to print the user name of a given email Example: If the following email address is given as input to the program: [email protected] Then, the output of the program should be: john In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. Solution: import re emailAddress = raw_input() pat2 = "(\w+)@((\w+.)+(com))" r2 = re.match(pat2,emailAddress) print r2.group(1) #----------------------------------------# Question: Assuming that we have some email addresses in the "[email protected]" format, please write program to print the company name of a given em Example: If the following email address is given as input to the program: [email protected] Then, the output of the program should be: google In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters.