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 (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道题)的更多相关文章
- 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 ...
- 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 ...
- 2016年GitHub排名前20的Python机器学习开源项目(转)
当今时代,开源是创新和技术快速发展的核心.本文来自 KDnuggets 的年度盘点,介绍了 2016 年排名前 20 的 Python 机器学习开源项目,在介绍的同时也会做一些有趣的分析以及谈一谈它们 ...
- python统计apache、nginx访问日志IP访问次数并且排序(显示前20条)【转】
前言:python统计apache.nginx访问日志IP访问次数并且排序(显示前20条).其实用awk+sort等命令可以实现,用awk数组也可以实现,这里只是用python尝试下. apach ...
- 少儿编程崛起?2020年4月编程语言排名发布——Java,C,Python分列前三,Scratch挤进前20
前三并没有什么悬念,依然是Java,C,Python.C与Java的差距正在缩小,不过我们不用担心,在大数据分析领域Java,Python依然都是不可或缺的. 基于图形的基于块的编程语言Scratch ...
- Python面试 【315+道题】
Python面试 [315+道题] 第一部分 Python基础篇(80题) 为什么学习Python? 因为看到python的发展趋势,觉得需要与时俱进,第一点,python开发速度极快,能快速完成一个 ...
- Java例题_20 前20项之和!
1 /*20 [程序 20 求前 20 项之和] 2 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前 20 项之和. 3 程序分析:请抓住分子与分母的变 ...
- 一个面试题的解答-----从500(Id不连续)道试题库里随机抽取20道题!
做一个考试系统的项目,现在从试题库里面随机抽取20道题 比如我题库有500道题(ID不连续).题目出现了,如何解决呢,随机抽取! 1,我们先把500道题的id存进一个长度为500的数组. 2,实现代码 ...
- 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 ...
随机推荐
- Vue源码之----为什么Vue中Array的pop,push等方法可以reactive,而Array[0]='a'这样的方法不会reactive?
这就要从reactive开始讲起了,粗略的说,js的操作能引起页面上显示的改变,是因为该操作引起了组件的重新渲染,渲染会生成新的虚拟节点,新节点和旧节点会对比,操作浏览器的node进行改变. vue实 ...
- Introduction to Unity UI
https://www.raywenderlich.com/795-introduction-to-unity-ui-part-1 https://www.raywenderlich.com/794- ...
- tomcat文件下目录介绍
主目录下有bin ,conf ,lib ,logs ,temp ,webapps ,work 7个文件夹,下面对它们分别进行介绍: 1.bin目录主要是用来存放tomcat的命令,主要有两大类,一类是 ...
- 爬取QQ音乐歌手的歌单
import requests# 引用requests库res_music = requests.get('https://c.y.qq.com/soso/fcgi-bin/client_search ...
- vsftpd 的端口模式以及端口映射问题
开个blog ,写一下关于vsftp 端口映射的一些坑 内容繁多,改日再更.
- PC能替代服务器吗?
PC能替代服务器吗?全方位解析二者区别_华为服务器_服务器x86服务器-中关村在线http://server.zol.com.cn/536/5366835_all.html
- PXE自动装机
PXE自动装机 一.搭建PXE远程安装服务器 PXE自动装机需要桌面模式 假如不是桌面模式安装的PXE需要安装桌面模式软件包 yum groupinstall "Desktop" ...
- Python学习第七课
Python学习第七课 'Alex' "Alex"print('hello'*5) #重复输出字符串 print('hellowold'[2:]) #类似于切片操作:会取出 llo ...
- mysql新增用户并开启远程连接
之前使用mysql一直使用root来连接登录数据库,现在想使用新的用户名来连接数据库,碰到数据连接不上的情况. 把这些记录下来,以备后用 1.首先,创建用户 CREATE USER 'xiazhenx ...
- AutomaticReferenceCounting.html#runtime-support
https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support Runtime support This sec ...