更多课程 选择中心


Python培训

400-111-8989

听说你python学的不错,那这几道python练习题敢挑战吗?

  • 发布:yang_bingo
  • 来源:博客
  • 时间:2018-07-19 12:02

有句俗语说的好:是驴子是马总得拉出来溜溜,今天的python培训课堂给出的是十二道python练习题,感觉自己python学的还不错的,那就赶紧来试试吧。

python练习题一

def accum(s):

#写你的代码,代码输出结果

#accum("abcd") # "A-Bb-Ccc-Dddd"

#accum("cwAt") # "C-Ww-Aaa-Tttt"

这到题用到了字符串的所有字母大写和所有字母小写和字符串拼接,复制,用到的函数有 json 将列表中的内容按照指定字符连接成一个字符串,upper() 所有字母变大写 和lower() 所有字母小写 含有内置函数enumerate 返回值是索引和对应得值。对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值,enumerate多用于在for循环中得到计数。

具体代码如下:

def asuum(s):

return '-'.join(y.upper() + y.lower()* x for x,y in enumerate(s))

a = asuum('abcd')

print(a)

python练习题二

def get_sum(a,b):

#写代码, 输出结果

# get_sum(1, 0) == 1 // 1 + 0 = 1

# get_sum(1, 2) == 3 // 1 + 2 = 3

# get_sum(0, 1) == 1 // 0 + 1 = 1

# get_sum(1, 1) == 1 // 1 Since both are same

# get_sum(-1, 0) == -1 // -1 + 0 = -1

# get_sum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2

这里面用到了最小值和最大值min(),max(),还有求和函数sum(),具体实现由以下代码:

def get_sum(a,b):

return sum(range(min(a,b),max(a,b)+1))

a = get_sum(2,-9)

python练习题三

def duplicate_count():

#写代码,要求实现以下功能给你一串字符串你要返回他的有重复的的字母个数包括大小

# test.assert_equals(duplicate_count("abcde"), 0)

# test.assert_equals(duplicate_count("abcdea"), 1)

# test.assert_equals(duplicate_count("indivisibility"), 1)

这里面用到了将所有字母都转成小写还有集合,和列表代码具体如下:

def duplicate_count(text):

# Your code goes here

text = text.lower()

texts = set(text)

lists = []

for i in texts:

umbers = text.count(i)

if numbers != 1:

lists.append(numbers)

return len(lists)

python练习题四

def likes():

# 输入代码实现以下的内容

#

# likes [] // must be "no one likes this"

# likes ["Peter"] // must be "Peter likes this"

# likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"

# likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"

# likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

这个方法有点鲁,主要运用的只是点就是列表和len()函数,具体代码如下:

def likes(names):

# your code here

if names:

if len(names) == 1:

return names[0] + ' likes this'

elif len(names) == 2:

return names[0] + ' and ' + names[1] + ' like this'

elif len(names) == 3:

return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this'

else:

return names[0] + ', ' + names[1] + ' and ' + str(len(names) - 2) + ' others like this'

else:

return 'no one likes this'

python练习题五

你的任务是创建一个函数,它可以将任何非负整数作为参数,并以降序的数字返回它。基本上,重新排列数字以创建尽可能高的数字。

例子:

输入:21445 输出:54421

输入:145263 输出:654321

输入:1254859723 输出:9875543221

里面用到列表的排序,从大到小,还有类型转换,大神代码:

def Descending_Order(num):

return int("".join(sorted(str(num), reverse=True)))

我的代码:

def Descending_Order(num):

#Bust a move right here

ums = list(str(num))

ums.sort(reverse=True)

return int(''.join(nums))

python练习题六

给定:一个包含名称散列的数组

返回:格式为由逗号分隔的名称列表的字符串,除了最后两个名称之外,应该用连字符分隔。例:

namelist([ {'name': 'Bart'}, {'name': 'Lisa'}, {'name': 'Maggie'} ])

# returns 'Bart, Lisa & Maggie'

amelist([ {'name': 'Bart'}, {'name': 'Lisa'} ])

# returns 'Bart & Lisa'

amelist([ {'name': 'Bart'} ])

# returns 'Bart'

amelist([])

# returns ''

这个主要用到列表和字符串的相关知识:

def namelist(names):

# your code here

if len(names) > 1:

return '{} & {}'.format(', '.join(i['name'] for i in names[:-1]), names[-1]['name'])

elif len(names) == 1:

return names[0]['name']

else:

return ''

python练习题七

In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m.

The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a...

Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm.

You have to write a function printer_error which given a string will output the error rate of the printer as a string representing a rational whose umerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.

The string has a length greater or equal to one and contains only letters from ato z.

#Examples:

s="aaabbbbhaijjjm"error_printer(s) => "0/14"s="aaaxbbbbyyhwawiwjjjwwm"error_printer(s) => "8/22"

简单的说也就是说你就是让你证明这些字符串在不在‘abcdefghijkml’里,我的代码如下:

def printer_error(s):

# your code

a = 0

for i in range(0,len(s)):

if s[i] not in 'abcdefghijklm':

a += 1

return '{}/{}'.format(str(a),len(s)

大神解决方案:

from re import sub

def printer_error(s):

return "{}/{}".format(len(sub("[a-m]",'',s)),len(s))

#他这里用到了字符串的替换sub

我们讲一下sub 的用法:

re.sub的各个参数的详细解释

re.sub共有五个参数。

re.sub(pattern, repl, string, count=0, flags=0)

其中三个必选参数:pattern, repl, string

两个可选参数:count, flags

第一个参数:pattern

pattern,表示正则中的模式字符串,这个没太多要解释的。

第二个参数:repl

repl,就是replacement,被替换,的字符串的意思。

repl可以是字符串,也可以是函数。

repl是字符串

如果repl是字符串的话,其中的任何反斜杠转义字符,都会被处理的。

即:

:会被处理为对应的换行符;

:会被处理为回车符;

其他不能识别的转移字符,则只是被识别为普通的字符:

比如j,会被处理为j这个字母本身;

反斜杠加g以及中括号内一个名字,即:g,对应着命了名的组,named group

第三个参数:string

string,即表示要被处理,要被替换的那个string字符串。

没什么特殊要说明。

python练习题八

转为二进制:

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

要求输出结果:

Test.assert_equals(add_binary(1,1),"10")

Test.assert_equals(add_binary(0,1),"1")

Test.assert_equals(add_binary(1,0),"1")

Test.assert_equals(add_binary(2,2),"100")

Test.assert_equals(add_binary(51,12),"111111")

具体实现代码如下:

def add_binary(a,b):

return bin(a+b).lstrip('0b')

更加简单的:

def add_binary(a, b):

return format(a + b, 'b')

python练习题九

Write Number in Expanded Form

You will be given a number and you will need to return it as a string in Expanded Form. For example:

expanded_form(12) # Should return '10 + 2'

expanded_form(42) # Should return '40 + 2'

expanded_form(70304) # Should return '70000 + 300 + 4'

代码如下:

def expanded_form(num):

ums = str(num)

x = []

for i in range(0,len(nums)):

if int(nums[i]) != 0:

s = str(int(nums[i]) * (10 ** (len(nums) - i - 1)))

x.append(s)

return ' + '.join(x)

首先给数字转成字符串,然后建一个空列表,循环这个字符串的长度,然后进行判断判断他这个字符串有没有0。没有0,就进行计算让他的位数根据字符的长度进行想成:好比78,就要输出 7* 10**1 8*10**0,最后添加到列表中,然后进行字符串的拼接,要注意字符串的空格。

python练习题十

My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest.

I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to umbers. The weight of a number will be from now on the sum of its digits.

For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99. Given a string with the weights of FFC members in ormal order can you give this string ordered by "weights" of these numbers?

Example:

"56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes: "100 180 90 56 65 74 68 86 99"

When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string.

All numbers in the list are positive numbers and the list can be empty.

到题主要是说数字的重权,也就是说数字的累加和。

order_weight("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234000 44444444 9999")

好比2000 就是2 10003就是4 也就是这串数字的累加和

我的思路是用sorted()这个函数根据这组数的代码如下:

def order_weight(strng):

# your code

return ' '.join(sorted(sorted(strng.split(' ')),key = lambda x:sum(int(c) for c in x)))

首先把这个数进行切割,然后用lambda算出这个数的累加和,在根据累加和进行排序。

python练习题十一

Write a function that takes an (unsigned) integer as input, and returns the umber of bits that are equal to one in the binary representation of that umber.

Write a function that takes an (unsigned) integer as input, and returns the umber of bits that are equal to one in the binary representation of that umber.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case

#这道题是计算二进制数。1出现的次数

def countBits(n):

s = lambda x: sum(int(z) for z in x)

return s(format(n, 'b'))

我这里用的是累加和

还有一种更简单的方法

def countBits(n):

return format(n, 'b').count('1')

python练习题十二

Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.

Examples:

"()" => true

")(()))" => false

"(" => false

"(())((()())())" => true

#括号问题判断是否是有效空号

def valid_parentheses(string):

#your code here

cnt = 0

for i in string:

if i == "(":cnt+=1

if i == ")":cnt-=1

if cnt < 0: return False

return True if cnt == 0 else False

感谢您的阅读,这十二道python练习题你做完了吗?做的怎么样呢?有什么不理解不明白的地方吗?欢迎你来达内python培训机构寻求答案!

免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

预约申请免费试听课

填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!

上一篇:python面试题讲解:python中常用的5个运维脚本
下一篇:Python数据挖掘试题四十道,你敢来挑战吗?

怎样选择Python培训机构,才能让我的未来充满阳光?

考一考:python大数据与机器学习Matplotlib练习题十道

在Python面试中如何展现你的代码能力?

Python计算机二级考试,你能考过吗?

  • 扫码领取资料

    回复关键字:视频资料

    免费领取 达内课程视频学习资料

Copyright © 2023 Tedu.cn All Rights Reserved 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有

选择城市和中心
黑龙江省

吉林省

河北省

湖南省

贵州省

云南省

广西省

海南省