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

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

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):
s = ''
for i in range (1, n+1):
s = s + string
return s
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
if a == float("-inf"):
raise ValueError("max() arg is an empty sequence")
return a
print(max([-4,-6,-3]))
#-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 编写一个程序将一个单词列表映射到一个整数列表,代表单词的长度。
def list_num(list_str):
a =[]
for str in list_str:
a.append(len(str))
return a
print(list_num(['I\'m', 'a', 'pythoncoder']))
#[3, 1, 11]
# 扩展:把一个单词列表转换成单词个数列表。比如列表["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']))
#

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道题)的更多相关文章

  1. 46 Simple Python Exercises-Very simple exercises

    46 Simple Python Exercises-Very simple exercises 4.Write a function that takes a character (i.e. a s ...

  2. 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 nu ...

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

    当今时代,开源是创新和技术快速发展的核心.本文来自 KDnuggets 的年度盘点,介绍了 2016 年排名前 20 的 Python 机器学习开源项目,在介绍的同时也会做一些有趣的分析以及谈一谈它们 ...

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

    前言:python统计apache.nginx访问日志IP访问次数并且排序(显示前20条).其实用awk+sort等命令可以实现,用awk数组也可以实现,这里只是用python尝试下.   apach ...

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

    前三并没有什么悬念,依然是Java,C,Python.C与Java的差距正在缩小,不过我们不用担心,在大数据分析领域Java,Python依然都是不可或缺的. 基于图形的基于块的编程语言Scratch ...

  6. Python面试 【315+道题】

    Python面试 [315+道题] 第一部分 Python基础篇(80题) 为什么学习Python? 因为看到python的发展趋势,觉得需要与时俱进,第一点,python开发速度极快,能快速完成一个 ...

  7. Java例题_20 前20项之和!

    1 /*20 [程序 20 求前 20 项之和] 2 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前 20 项之和. 3 程序分析:请抓住分子与分母的变 ...

  8. 一个面试题的解答-----从500(Id不连续)道试题库里随机抽取20道题!

    做一个考试系统的项目,现在从试题库里面随机抽取20道题 比如我题库有500道题(ID不连续).题目出现了,如何解决呢,随机抽取! 1,我们先把500道题的id存进一个长度为500的数组. 2,实现代码 ...

  9. c - 2/1, 3/2, 5/3, 8/5, 13/8...前20项的和

    double pres(const int n) { ; //分子. ; //分母. ; double tmp; ; i <= n; i++) { sum += (numerator / den ...

随机推荐

  1. js事件、事件流以及target、currentTarget、this那些事

    你是如此简单我却将你给遗忘   前面面试被问到js的事件机制  target.currentTarget.碰巧今天有时间来拔一拔,顺便记下.

  2. c++学习过程

    作者本人也是一名初学者,我的QQ:2522929921,可以一起交流啊! 希望广大初学者能够一起进步: 1.掌握编程思维真的很重要!!!!***. 2.不能刻意记忆语法规则. 3.在循序渐进的项目实战 ...

  3. 集合和format

    昨天没来及整理博客,有点小累.休息了一下,今天的内容比较多 集合还是按照之前的方法,整理了一边所有的方法,其次在看了下format的方法 还有一些函数,暂时学了一点 还不知道怎么整理 s = {,,, ...

  4. 运维ldd语法--》ldconfig

    Linux:ldd命令详解   ldd 用于打印程序或者库文件所依赖的共享库列表. 语法 ldd(选项)(参数) 选项 --version:打印指令版本号: -v:详细信息模式,打印所有相关信息: - ...

  5. 服务器搭建lamp环境

    使用的例子:服务器版本内核centos 7.04     Xshell连接到您的服务器上,使系统处于最新状态执行以下命令, yum update -y     利用yum命令安装Apache执行命令, ...

  6. Linux 驱动——Button驱动1

    button_drv.c驱动文件: #include <linux/module.h>#include <linux/kernel.h>#include <linux/i ...

  7. 看到Console.WriteLine($"string")写法,一时间不理解$的用途

    参了网上资料,原来它是C# 6.0的语法糖. C# 6.0 新加上的功能:   Null-Conditional Operator 大概就是,简洁代码量,缩短一些关于为null的判断~ 旧写法: pu ...

  8. Python第十课学习

    Python第十课学习 www.cnblogs.com/yuanchenqi/articles/5828233.html 函数: 1 减少代码的重复 2 更易扩展,弹性更强:便于日后文件功能的修改 3 ...

  9. python库-Arrow处理时间

    Arrow是一个处理时间的python库,能一键转换dates/times/timestamps等时间格式而不需要大量导致各种时间模块和格式转换函数,十分快捷方便 使用Arrow需要两步转换操作: 1 ...

  10. two pointers

    two pointers是算法编程中一种非常重要的思想,但是很少会有教材单独拿出来将,其中一个原因是它更倾向于是一种编程技巧,而长得不太像是一个是“算法”的模样.two pointers的思想十分简介 ...