46 Simple Python Exercises-Very simple exercises

This is version 0.45 of a collection of simple Python exercises constructed (but in many cases only found and collected) by Torbj�rn Lager (torbjorn.lager@ling.gu.se). Most of them involve characters, words and phrases, rather than numbers, and are therefore suitable for students interested in language rather than math.

Very simple exercises

1、Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.)

1 def max(num1, num2):
2     if num1 > num2:
3         return num1
4     else:
5         return num2
6 
7 print(max(1,3)) #3
8 print(max(5,5)) #5

 

2、Define a function max_of_three() that takes three numbers as arguments and returns the largest of them.

 1 def max(num1, num2):
 2     if num1 > num2:
 3         return num1
 4     else:
 5         return num2
 6 
 7 def max_of_three(num1, num2, num3):
 8     _max = max(num1, num2)
 9     _max = max(_max, num3)
10     return _max
11 
12 
13 print(max_of_three(5, 1, 42.5)) #42.5

【june】找最大值的一般思想:每次只比较两个数,拿到最大值后,再把最大值和下一个数比较,然后得出最大值,以此类推,最后留下的那个数字一定是最大值。

 

3、Define a function that computes the length of a given list or string. (It is true that Python has the len() function built in, but writing it yourself is nevertheless a good exercise.)

1 def calc_length(a_list):
2     count = 0
3     for ele in a_list:
4         count += 1
5     return count
6 
7 print(calc_length("learn python")) #12

【june】整数递增,用 += 操作符

 

4、Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.

 1 def is_vowel(letter):
 2     _letter = letter.lower() 
 3     if _letter == "a"\
 4         or _letter == "e"\
 5         or _letter == "i"\
 6         or _letter == "o"\
 7         or _letter == "u":
 8         return True
 9     else:
10         return False
11 print(is_vowel("a"),is_vowel("b")) #True False

【june】使用逻辑运算符 or

 

5、Write a function translate() that will translate a text into "r�varspr�ket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".

 

 1 def is_vowel(letter):
 2      _letter = letter.lower() 
 3      if _letter == "a"\
 4          or _letter == "e"\
 5          or _letter == "i"\
 6          or _letter == "o"\
 7          or _letter == "u":
 8          return True
 9      else:
10        return False
11 
12 def translate(string):
13     char_list = []
14     for char in string:
15         if is_vowel(char) or char == " ":
16             char_list.append(char)
17         else:
18             char_list.append(char + "o" + char)
19     return "".join(char_list)
20     
21 print(translate("this is fun")) #tothohisos isos fofunon

 

6、Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.

 1 def sum(numbers):
 2     result = 0
 3     for num in numbers:
 4         result += num
 5     return result 
 6 
 7 print(sum([1,2,3,4])) #10
 8 
 9 def multiply(numbers):
10     result = 1
11     for num in numbers:
12         result *= num
13     return result
14 print(multiply([1, 2, 3, 4])) #24
15 
16 #更加高级的实现(利用python的传参特点)
17 def adv_sum(*numbers):
18     result = 0
19     for num in numbers:
20         result += num
21     return result
22 
23 print(adv_sum(1,2,3,4)) #10

 

7、Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".

 

 1 #方法1
 2 def reverse(string):
 3     if len(string) <= 1:
 4         return string
 5     chars = []
 6     for char in string:
 7         chars.insert(0, char)
 8     return "".join(chars)
 9 
10 print(reverse("I am testing"))        
11 
12 #方法2
13 def reverse_v2(string):
14     return string[::-1]
15 
16 print(reverse_v2("I am testing"))
17 
18 #方法3
19 def reverse_v3(string):
20     return "".join(reversed(string))
21 
22 print(reverse_v3("I am testing")) 
23 
24 #方法4
25 def reverse_v4(string):
26     to_list = list(string)
27     to_list.reverse()
28     return "".join(to_list)
29 
30 print(reverse_v4("I am testing"))

【june】

方法1:利用列表的 insert 方法

方法2:利用列表的分片操作(步长为负,代表从后往前的方向)

方法3:利用python内置函数 reversed,反转后返回列表的副本

方法4:利用列表的reverse方法,此方法时在位反转

 

8、Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.

 1 def reverse(string):
 2     if len(string) <= 1:
 3         return string
 4     chars = []
 5     for char in string:
 6         chars.insert(0, char)
 7     return "".join(chars)
 8 
 9 def is_palindrome(string):
10     return reverse(string) == string
11 
12 print(is_palindrome("radar")) #True
13 print(is_palindrome("abc")) #False
14 
15 #更加高效的方法
16 def is_palindrome_fastway(string):
17     if len(string) <= 1:
18         return True
19     m = 0
20     n = len(string) - 1
21     while m < n:
22         if string[m] != string[n]:
23             return False
24         m += 1
25         n -= 1
26     return True
27 
28 print(is_palindrome_fastway("radar")) #True
29 print(is_palindrome_fastway("abc")) #False

【june】高效的方法:从字符串的两端挨个字符比较,只要碰到不同的就立即返回False

 

9、Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)

1 def is_member(x, a_list):
2     for ele in a_list:
3         if ele == x:
4             return True
5     return False
6 
7 print(is_member("apple",["pear","orange", "apple"])) #True 
8 print(is_member("apple",["pear","orange"])) #False

 

10、Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.

1 def overlapping(list_a,list_b):
2     for a in list_a:
3         for b in list_b:
4             if a == b:
5                 return True
6     return False
7 print(overlapping(["pear","orange", "apple"] ,["apple","peach"])) #True
8 print(overlapping(["pear","orange"] ,["apple","peach"])) #False

【june】嵌套循环

 

11、Define a function generate_n_chars() that takes an integer n and a character c and returns a string, n characters long, consisting only of c:s. For example, generate_n_chars(5,"x") should return the string "xxxxx". (Python is unusual in that you can actually write an expression 5 * "x" that will evaluate to "xxxxx". For the sake of the exercise you should ignore that the problem can be solved in this manner.)

1 def generate_n_chars(n, char):
2     string = ""
3     for i in range(n):
4         string += char 
5     return string
6 print(generate_n_chars(5,"X")) #XXXXX

【june】字符串相加操作,concat

 

12、Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example, histogram([4, 9, 7]) should print the following:

****

*********

*******

 1 def generate_n_chars(n, char):
 2     string = ""
 3     for i in range(n):
 4         string += char 
 5     return string
 6 
 7 def histogram(count_list):
 8     for n in count_list:
 9         print(generate_n_chars(n, "*"))
10 histogram([4, 9 , 7])
11 #****
12 #*********
13 #*******

 

13、The function max() from exercise 1) and the function max_of_three() from exercise 2) will only work for two and three numbers, respectively. But suppose we have a much larger number of numbers, or suppose we cannot tell in advance how many they are? Write a function max_in_list() that takes a list of numbers and returns the largest one.

1 def max(num_list):
2     a = float("-inf")
3     for num in num_list:
4         if num >= a:
5             a = num
6     if a == float("-inf"):
7         raise ValueError("max() arg is empty sequence")
8     return a
9 print(max([-3, -4, -9, -8])) #-3

 

14、Write a program that maps a list of words into a list of integers representing the lengths of the correponding words.

1 def make_count_list(word_list):
2     return [len(word) for word in word_list]
3     
4 print(make_count_list(["I am", "a", "python coder"])) #[4, 1, 12]

 

15、Write a function find_longest_word() that takes a list of words and returns the length of the longest one.

 1 def max(num_list):
 2     a = float("-inf")
 3     for num in num_list:
 4         if num >= a:
 5             a = num
 6     if a == float("-inf"):
 7         raise ValueError("max() arg is empty sequence")
 8     return a
 9 
10 def make_count_list(word_list):
11     return [len(word) for word in word_list]
12 
13 def find_longest_word(word_list):
14     return max(make_count_list(word_list))
15 
16 print(find_longest_word(["I am", "a", "python coder"])) #12

 

16、Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.

 1 def filter_long_words(word_list, n):
 2     result = []
 3     for word in word_list:
 4         if len(word) > n:
 5             result.append(word)
 6     return result
 7 
 8 print(filter_long_words(["I am", "a", "python coder"], 2))
 9 
10 #列表推导
11 def filter_long_words_v2(word_list, n):
12     return [word for word in word_list if len(word)>n]
13 
14 print(filter_long_words_v2(["I am", "a", "python coder"], 2))

 

17. Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'm mad!". Note that punctuation, capitalization, and spacing are usually ignored.

1 def recognize_palindrome(string):
2     new_string = "".join([char for char in string if char.isalnum()])
3     return new_string.lower() == new_string[::-1].lower()
4 
5 print(recognize_palindrome("Was it a rat I saw-?")) #True

 【june】使用字符串的 isalnum 方法来验证每个字符是否为字母或者数字

 

18. A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.

1 def is_pangram(string):
2     only_alpha = [char.lower() for char in string if char.isalpha()]
3     return len(set(only_alpha)) == 26
4 
5 print(is_pangram("The quick brown fox jumps ove the lazy dog")) #True

【june】先用字符串的 isalpha 把非字母的字符全部去掉,然后都变成小写,再用 set 数据类型把重复的字母去掉,如果剩余的字母数量是26则说明 传进来的字符串一定是包含26个字母

 

19. "99 Bottles of Beer" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows:

99 bottles of beer on the wall, 99 bottles of beer.
Take one down, pass it around, 98 bottles of beer on the wall.

The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero.

Your task here is write a Python program capable of generating all the verses of the song.

 1 def generate_song():
 2     n = 99
 3     song = []
 4     while n > 0:
 5         song.append("{} bottles of beer on the wall, {} bottles of beer.".format(n, n))
 6         n -= 1
 7         song.append("Take one down, pass it around, {} bottles of beer on the wall.".format(n))
 8     return "\n".join(song)
 9 
10 print(generate_song())
11 
12 #利用python的生成器实现,更加节省内存
13 def generate_song_v2():
14     n = 99
15     while n > 0:
16         yield "{} bottles of beer on the wall, {} bottles of beer.".format(n, n)
17         n -= 1
18         yield "Take one down, pass it around, {} bottles of beer on the wall.".format(n)
19 
20 for line in generate_song_v2():
21     print(line)

【june】主要考察循环,列表操作,字符串格式化。

生成器generator是python特色之处,对于内存计算来说,尤其适合,较少内存占用。

 

20. Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"�r"} and use it to translate your Christmas cards from English into Swedish. That is, write a function translate() that takes a list of English words and returns a list of Swedish words.

 1 def translate_into_swedish(english, dictionary):
 2     swedish_words = []
 3     for word in english.split():
 4         swedish_words.append(dictionary[word.lower()])
 5     return " ".join(swedish_words)
 6 
 7 dictionary = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"�r"}
 8 translated = translate_into_swedish("merry christmas and happy new year", dictionary)
 9 print(translated)
10 
11 #利用列表推导语法
12 def translate_into_swedish_v2(english, dictionary):
13     return " ".join([dictionary[word.lower()] for word in english.split()])
14 
15 dictionary = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"�r"}
16 print(translate_into_swedish_v2("merry christmas and happy new year", dictionary))

【june】考察字典的用法

 

21. Write a function char_freq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Python dictionary. Try it with something like char_freq("abbabcbdbabdbdbabababcbcbab").

 1 def char_freq(string):
 2     char_freq_dic = {}
 3     for char in string:
 4         if char in char_freq_dic:
 5             char_freq_dic[char] = char_freq_dic[char] + 1
 6         else:
 7             char_freq_dic[char] = 1
 8     return char_freq_dic
 9 
10 print(char_freq("abbabcbdbabdbdbabababcbcbab")) #{'a': 7, 'b': 14, 'c': 3, 'd': 3}
11 
12 #写法2,更加简短的代码,无需判断
13 def char_freq_v2(string):
14     char_freq_dic = {}
15     for char in string:
16         char_freq_dic.setdefault(char, 0)
17         char_freq_dic[char] = char_freq_dic[char] + 1
18     return char_freq_dic
19 
20 print(char_freq("abbabcbdbabdbdbabababcbcbab"))
21 
22 #写法3
23 def char_freq_v3(string):
24     import collections
25     return collections.Counter(string)
26 
27 print(char_freq_v3("abbabcbdbabdbdbabababcbcbab"))

【june】写法1,中规中矩,使用字典的 in 操作符

写法2,利用字典的 setdefault 方法,消除判断语句

写法3,利用python内置的库

 

22. 

In cryptography, a Caesar cipher is a very simple encryption techniques in which each letter in the plain text is replaced by a letter some fixed number of positions down the alphabet. For example, with a shift of 3, A would be replaced by D, B would become E, and so on. The method is named after Julius Caesar, who used it to communicate with his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesar cipher where the shift is 13. In Python, the key for ROT-13 may be represented by means of the following dictionary:

key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 
       'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 
       'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
       'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 
       'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 
       'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 
       'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}

Your task in this exercise is to implement an encoder/decoder of ROT-13. Once you're done, you will be able to read the following secret message:

   Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!

Note that since English has 26 characters, your ROT-13 program will be able to both encode and decode texts written in English.

 1 key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 
 2        'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 
 3        'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
 4        'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 
 5        'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 
 6        'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 
 7        'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
 8     
 9 def encode(sentence):
10     chars = list(sentence)
11     for i,char in enumerate(chars):
12         if char in key:
13             chars[i] = key[char]
14 
15     return "".join(chars)
16 
17 def decode(sentence):
18     chars = list(sentence)
19     for i, char in enumerate(chars):
20         for k,v in key.items():
21             if v == char:
22                 chars[i] = k
23     
24     return "".join(chars)
25 
26 print(encode("Hello World")) #Uryyb Jbeyq
27 print(decode("Uryyb Jbeyq")) #Hello World
28 print(decode("Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!")) #Caesar cipher? I much prefer Caesar salad!

【june】考察字典操作,in 操作符

更加简洁的实现:

 1 key = {'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u', 
 2        'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c', 
 3        'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
 4        'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S', 
 5        'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A', 
 6        'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I', 
 7        'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
 8 
 9 #写法2,利用列表推导(list comprehension),更加简洁
10 def encode(sentence):
11     #利用字典的get方法,如果找不到key,则返回默认值
12     return "".join([key.get(char, char) for char in sentence])
13 
14 #将字典翻转,来完成decode操作
15 reverse_key = dict(((v,k) for k,v in key.items()))
16 def decode(sentence):
17     return "".join([reverse_key.get(char, char) for char in sentence])
18     
19 print(encode("Hello World")) #Uryyb Jbeyq
20 print(decode("Uryyb Jbeyq")) #Hello World
21 print(decode("Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!")) #Caesar cipher? I much prefer Caesar salad!

 

 23. Define a simple "spelling correction" function correct() that takes a string and sees to it that 1) two or more occurrences of the space character is compressed into one, and 2) inserts an extra space after a period if the period is directly followed by a letter. E.g. correct("This   is  very funny  and    cool.Indeed!") should return "This is very funny and cool. Indeed!" Tip: Use regular expressions!

1 import re
2 def correct(string):
3     tmp = re.sub(r"\s{2,}", " ", string)
4     def create_space_after_period(matchobj):
5         print(matchobj.group(1))
6         return ". " + matchobj.group(1)
7     return re.sub(r"\.(\S)", create_space_after_period, tmp)
8 
9 print(correct("This   is  very funny  and    cool.Indeed!")) #This is very funny and cool. Indeed!

【june】利用 re 模块的 sub 方法

 

思路2:先把句号后面加上一个空格,然后统一把多个空格替换成一个空格。如果句号是最后一个字符,则需要用 strip 函数把字符串末尾的空格去掉

1 import re
2 def correct(string):
3     string = string.replace(".", ". ")
4     return re.sub("\s{2,}", " ", string).rstrip()
5 
6 corrected_string = correct("This   is  very funny  and    cool.Indeed!  ")
7 print(corrected_string) # This is very funny and cool. Indeed!

 

 24. 

The third person singular verb form in English is distinguished by the suffix -s, which is added to the stem of the infinitive form: run -> runs. A simple set of rules can be given as follows:

  1. If the verb ends in y, remove it and add ies
  2. If the verb ends in ochsshx or z, add es
  3. By default just add s

Your task in this exercise is to define a function make_3sg_form() which given a verb in infinitive form returns its third person singular form. Test your function with words like trybrushrun and fix. Note however that the rules must be regarded as heuristic, in the sense that you must not expect them to work for all cases. Tip: Check out the string method endswith().

 1 def make_3sg_form(verb):
 2     pattern_es =  ["o", "ch", "s", "sh", "x", "z"]
 3     if verb.endswith("y"):
 4         sg_verb = verb.rstrip("y") + "ies"
 5     elif any((verb.endswith(p) for p in pattern_es)):
 6         sg_verb = verb + "es"
 7     else:
 8         sg_verb = verb + "s"
 9     return sg_verb
10 
11 print(make_3sg_form("try")) #tries
12 print(make_3sg_form("brush")) #brushes
13 print(make_3sg_form("run")) #runs
14 print(make_3sg_form("fix")) #fixes

【june】使用内置方法 any (seq),只要序列中有一个为True,则表达式返回 True。再利用生成器语法 (ele for ele in sql)

25. In English, the present participle is formed by adding the suffix -ing to the infinite form: go -> going. A simple set of heuristic rules can be given as follows:

  1. If the verb ends in e, drop the e and add ing (if not exception: beseefleeknee, etc.)
  2. If the verb ends in ie, change ie to y and add ing
  3. For words consisting of consonant-vowel-consonant, double the final letter before adding ing
  4. By default just add ing

Your task in this exercise is to define a function make_ing_form() which given a verb in infinitive form returns its present participle form. Test your function with words such as lieseemove and hug. However, you must not expect such simple rules to work for all cases.

 1 def is_vowel(letter):
 2     """判断一个字母是否为元音"""
 3     _letter = letter.lower() 
 4     if _letter == "a"\
 5     or _letter == "e"\
 6     or _letter == "i"\
 7     or _letter == "o"\
 8     or _letter == "u":
 9         return True
10     else:
11         return False
12 
13 def is_consonant(letter):
14     """判断一个字母是否为辅音"""
15     return not is_vowel(letter)
16 
17 def make_ing_form(verb):
18     if verb.endswith("ie"):
19         ing_verb = verb.rstrip("ie") + "ying"
20     elif verb.endswith("e") and verb not in ["be", "see", "flee", "knee"]:
21         ing_verb = verb.rstrip("e") + "ing"
22     elif len(verb) == 3 and is_vowel(verb[1]) and is_consonant(verb[0]) and is_consonant(verb[2]):
23         ing_verb = verb + verb[2] + "ing"
24     else:
25         ing_verb = verb + "ing"
26     
27     return ing_verb
28     
29 print(make_ing_form("lie")) #lying
30 print(make_ing_form("see")) #seeing
31 print(make_ing_form("move")) #moving
32 print(make_ing_form("hug")) #hugging
33 print(make_ing_form("laugh")) #laughing

 

 

 

 

 

posted @ 2017-03-31 17:42  june.js  阅读(571)  评论(0编辑  收藏  举报