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
时间: 2024-08-21 01:11:28

46 Simple Python Exercises (前20道题)的相关文章

46 Simple Python Exercises 16-22题

会贴出原题和答案,答案不是最优的,也反映了我的学习过程,如果有时间会更新优化的代码. 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. #Write a function filter_long_words() that takes a list of words # and a

46 Simple Python Exercises-Very simple exercises

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. def if_vowel(a): a=a.lower() if a in('a','e','i','o','u'): return True else: return Falseprint(if_vowel('A')) 原文地址:https://www.c

46 Simple Python Exercises-Higher order functions and list comprehensions

26. Using the higher order function reduce(), write a function max_in_list() that takes a list of numbers and returns the largest one. Then ask yourself: why define and call a new function, when I can just as well call the reduce() function directly?

2016年GitHub排名前20的Python机器学习开源项目(转)

当今时代,开源是创新和技术快速发展的核心.本文来自 KDnuggets 的年度盘点,介绍了 2016 年排名前 20 的 Python 机器学习开源项目,在介绍的同时也会做一些有趣的分析以及谈一谈它们的发展趋势.和去年一样,KDnuggets 介绍了 GitHub 上最新的并且排名前 20 的 Python 机器学习开源项目.令人吃惊的是,去年一些最活跃的项目已经停滞不前了,也有一些项目跌出了前 20 名(在 contribution 和 commit 方面),当然,也有 13 个新项目进入了前

python统计apache、nginx访问日志IP访问次数并且排序(显示前20条)

前言:python统计apache.nginx访问日志IP访问次数并且排序(显示前20条).其实用awk+sort等命令可以实现,用awk数组也可以实现,这里只是用python尝试下. apache脚本: ips = {} with open("/root/mail_access_log-20180629") as fh:     for line in fh:         ip = line.split(" ")[0]         if 6 < le

少儿编程崛起?2020年4月编程语言排名发布——Java,C,Python分列前三,Scratch挤进前20

前三并没有什么悬念,依然是Java,C,Python.C与Java的差距正在缩小,不过我们不用担心,在大数据分析领域Java,Python依然都是不可或缺的. 基于图形的基于块的编程语言Scratch已进入前20名.乍一看,对于旨在教孩子如何编程的编程语言来说,这似乎有些奇怪.但是,如果考虑到Scratch开发完成总数超过5,000万个项目,并且每月增加100万个新的Scratch项目,那么不能否认Scratch受欢迎.由于计算机越来越成为生活中不可或缺的一部分,因此教孩子编程的语言越来越受欢迎

RedMonk热门程序语言排行:Kotlin首次进入前20名

锁定软件开发领域的分析业者RedMonk根据GitHub项目所使用的程序语言及Stack Overflow社群的讨论程度,公布了今年的热门程序语言排行榜,显示出Android平台上的开发语言Kotlin依旧快速成长,从2017年的第65名.2018年的第28名,到今年首度挤进前20名.由JetBrains在2011年打造的Kotlin是个跨平台且静态的通用型程序语言,它能与Java互动,其标准函式库的JVM版本亦仰赖Java Class Library,且在2017年5月正式被网络大厂纳入And

2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。

package com.hanqi; public class Qiuhe { public static void main(String[] args) { // TODO 自动生成的方法存根 double sum=0,fenshu=0,a=1,b=2,c=0; for (int i = 0; i < 20; i++) { fenshu=b/a; c=a; a=b; b=a+c; sum+=fenshu; //System.out.println(fenshu); } System.out.

跟我一起学extjs5(20--模块Grid的其他功能的设想,前20节源码)

跟我一起学extjs5(20--模块Grid的其他功能的设想,前20节源码) 经过对自定义模块和Grid的设计和编码,现在已经能对一个有配置信息的模块来生成界面并进行一些简单的CURD操作.由于这是一个全解释性的前台的架构,因此你想到的任何新主意都可以放到所有的模块中. 比如对于"Grid列宽的自动适应"这个功能,我们可以在系统设置项里加入"列宽自适应模式",下面有三个选项:1.不自动适应:2.首次加载数据时自动适应:3?每次加载数据都自动适应.因为列宽自动适应需要