46 Simple Python Exercises (前20道题)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了46 Simple Python Exercises (前20道题)相关的知识,希望对你有一定的参考价值。

46 Simple Python 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 ([email protected]). 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.)

#coding:utf-8
#exercises 1 定义一个函数max,两个数字比较大小
def max_of_two(a, b):
    if a > b:
        return a
    else:
        return b
result = max_of_two(5, 1)
print(result)
#5

 

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

#exercises 2 定义一个函数max_of_three,三个数字比较大小
def max_of_two(a, b):
    if a > b:
        return a
    else:
        return b
def max_of_three(a, b, c):
    max_ab = max_of_two(a, b)
    max_abc = max_of_two(max_ab, c)
    return max_abc
result = max_of_three(5, 1, 42.5)
print(result)
#42.5

 

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.)

#exercises 3 定义一个函数,计算给定列表(list)或字符串的长度
def length(a):
    n = 0
    for every_a in a:
        n = n + 1
    return n
result = length(Hello world)
result1 = length([a, b, c])
print(result, result1)
#11 3

 

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.

#exercises 4 写一个函数,接收只有一个字符的字符串,判断其是否为元音字母(即A、E、I、O、U)
def Vowel(letter):
    Vowel_letters = [A, E, I, O, U]
    if letter.upper() in Vowel_letters:
        return True
    else:
        return False
print(Vowel(a),Vowel(b))
#True False

 

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".

#exercises 5 写一个函数translate,把一个英文句子除元音外的字母复制自身且中间放一个字母O。
def translate(string_a):
    Vowel_letter = [A, E, I, O, U]
    b = []
    for a in string_a:
        if a.upper() in Vowel_letter:
            b.append(a)
        elif a.upper() ==  :
            b.append(a)
        else:
            b.append(a + o + a)
    c = "".join(b)
    return c
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.

#exercises 6 定义函数 sum 和 multiply ,参数为一个数字列表,分别返回数字的和\乘积
def sum(a):
    sum = 0
    for every_a in a:
        sum = sum + every_a
    return sum
def multiply(b):
    multiply = 1
    for every_b in b:
        multiply = multiply * every_b
    return multiply
print(sum([1, 2, 3, 4]),multiply([1, 2, 3, 4]))
#10 24

 

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".

#exercises 7 定义一个函数reverse,参数为一个字符串,反转该字符串并返回。
def reverse(a):
    b = []
    for i in range(1, len(a)+1):
        j = -1 * i
        b.append(a[j])
        c = "".join(b)
    return c
print(reverse("I am testing"))
#gnitset ma I

 

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.

#exercises 8 定义一个函数 is_palindrome,识别一个单词是否为回文,比如 is_palindrome("radar") 返回True
def reverse(a):
    b = []
    for i in range(1, len(a)+1):
        j = -1 * i
        b.append(a[j])
        c = "".join(b)
    return c
def is_palindrome(d):
    if d == reverse(d):
        return True
    else:
        return False
print(is_palindrome("radar"))
#True

 

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.)

#exercises 9 定义函数 is_member,其两个参数分别为x和列表,如果x在列表中则返回True,如果不在则返回False。
def is_member(x,list_x):
    if x in list_x:
        return True
    else:
        return False
print(is_member(apple,[pear,orange, apple]),is_member(apple,[pear,orange]) )
#True 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.

#exercises 10 定义函数 overlapping,两个列表作为参数,这两个列表中有一个相同的元素则返回True,否则返回False。
def overlapping(list_x,list_y):
    for x in list_x:
        for y in list_y:
            if x==y:
                return True
    else:
        return False
print(overlapping([pear,orange, apple] ,[apple,peach]))
print(overlapping([pear,orange] ,[apple,peach]))
#True
#False

 

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.)

#exercises 11 定义一个函数generate_n_chars,接收一个整数n和一个字符c,函数返回一个字符串其内容为n个c
def generate_n_chars(n,string):
    return string*n
print(generate_n_chars(5,x))
#xxxxx

 

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:

****

*********

*******

#exercises 12 定义一个函数histogram,参数为一个整数列表,函数在显示器上打印出直方图
def histogram(list_x):
    for x in list_x:
        print("*"*x)
histogram([4, 9 , 7])
#****
#*********
#*******

 

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.

#exercises 13 编写一个函数max,接收一个数字列表作为参数,返回该整数列表中的最大值。
#无穷大:float("inf"),无穷小:-float("inf")或float("-inf")
def max(list_num):
    a = float("-inf")
    for num in list_num:
        if num >= a:
            a = num
    return a
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.

#exercises 14 把一个单词列表转换成单词个数列表。比如列表["I am", "a", "python coder"],其单词数列表为[2, 1, 2])
def list_num(list_str):
    a =[]
    for str in list_str:
        str = str.split()
        a.append(len(str))
    return a
print(list_num([I am, a, python coder]))
#[2, 1, 2]

 

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

#exercises 15 编写函数find_longest_word(),参数为单词列表,返回the length of the longest one.
def find_longest_word(list_str):
    a = 0
    for str in list_str:
        if len(str) > a:
            a = len(str)
    return a
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.

#exercises 16 编写函数filter_long_words(),参数为单词列表和整数n,返回比n大the list of words.
def filter_long_words(list_str, n):
    a = []
    for str in list_str:
        if len(str) > n:
            a.append(str)
    return a
print(filter_long_words([I am, a, python coder], 2))
#[‘I am‘, ‘python coder‘]

 

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.

#去掉标点符号
import re
s ="Go hang a salami I‘m a lasagna hog."
s = re.sub(r[^\w\s],‘‘,s)
#exercises 17 编写回文识别器。注意,标点、大小写和间距通常被忽略。
def reverse(a):
    b = []
    for i in range(1, len(a)+1):
        j = -1 * i
        b.append(a[j])
        c = "".join(b)
    return c
def is_palindrome(a):
    import re
    a = re.sub(r[^\w\s], ‘‘, a)
    a = "".join(a.split())
    a = a.upper()
    print(a == reverse(a))
is_palindrome("Go hang a salami I‘m a lasagna hog.")
is_palindrome("Was it a rat I saw?")
is_palindrome("Step on no pets")
is_palindrome("Sit on a potato pan, Otis")
is_palindrome("Lisa Bonet ate no basil")
is_palindrome("Satan, oscillate my metallic sonatas")
is_palindrome("I roamed under it as a tired nude Maori")
is_palindrome("Rise to vote sir")
is_palindrome("Dammit, I‘m mad!")
#True

 

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. 

#exercises 18 写一个函数来检查一个句子是否包含所有英语字母表中所有字母。
def pangram_check(a):
    alphabets = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,
                 o,p,q,r,s,t,u,v,w,x,y,z]
    import re
    words = re.sub([^a-zA-Z], ‘‘,a).lower()
    i = 0
    for alphabet in alphabets:
        if alphabet in words:
            i = i + 1
    if i == 26:
        return True
    else:
        return False
print(pangram_check("The quick brown fox jumps over the lazy dog."))
#True

 

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.

#exercises 19 写一个Python程序,能够产生"99 Bottles of Beer" 歌曲的所有诗句。
def song(n):
    for i in range (0,n):
        print("{} bottles of beer on the wall, {} bottles of beer.".format(n - i, n - i))
        i = i + 1
        print("Take one down, pass it around, {} bottles of beer on the wall.".format(n - i))
song(99)
#99 bottles of beer on the wall, 99 bottles of beer.
#Take one down, pass it around, 98 bottles of beer on the wall.
#...
#1 bottles of beer on the wall, 1 bottles of beer.
#Take one down, pass it around, 0 bottles of beer on the wall.

 

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.

#exercises 20 写一个函数translate()将英语单词表,返回一个列表,瑞典语。
import re
def translate(a):
    dict = {"merry":"god", "christmas":"jul", "and":"och", "happy":"gott", "new":"nytt", "year":"?r"}
    a = re.sub(r[^\w\s], ‘‘, a)
    a = a.lower().split()
    b = []
    for every_a in a:
        if every_a in ("merry", "christmas", "and", "happy", "new", "year"):
            b.append(dict[every_a])
        else:
            b.append(every_a)
    return " ".join(b)
print(translate("Merry christmas and happy 2017 new year!"))
# god jul och gott 2017 nytt ?r

 


以上是关于46 Simple Python Exercises (前20道题)的主要内容,如果未能解决你的问题,请参考以下文章

46 Simple Python Exercises (前20道题)

46 Simple Python Exercises-Higher order functions and list comprehensions

markdown python,exercise,iterator

Python基础lpthw - Exercise 40 模块类和对象

Data Analysis with Python : Exercise- Titantic Survivor Analysis | packtpub.com

文件操作&函数 exercise