常见的python算法题_90% 人会做错常见的10道Python面试题

用三种方法写出次方计算

第一种方法是用运算符 **

>>> 2**5

32

第二种方法用内置的 pow方法

>>> pow(2, 5)

32

第三种方法用 math 模块里的 pow 方法

>>> import math

>>> math.pow(2,5)

32.0

怎么让字符串居中

用字符串中的 center 方法,他会在两边自动填充字符(默认为空格),让字符串居中

>>> k = '更多精彩,请关注公众号「Python知识圈」'

>>> k.center(50)

' 更多精彩,请关注公众号「Python知识圈」 '

>>> k.center(50, '*')

'**************更多精彩,请关注公众号「Python知识圈」**************'

用两种方法让字符的首字母大写,其他字母小写

解法1:用 title 方法。

>>> ss = 'welcome to pay attention to my weChat official accounts: PythonCircle'

>>> ss.title()

'Welcome To Pay Attention To My Wechat Official Accounts: Pythoncircle'

解法2:用 string 模块里的 capwords 方法,记得先 import string

>>> ss = 'welcome to pay attention to my weChat official accounts: PythonCircle'

>>> string.capwords(ss)

'Welcome To Pay Attention To My Wechat Official Accounts: Pythoncircle'

一个序列中随机返回 n 个不同值的元素

用 random 中的 sample 方法

>>> import random

>>> t = (2020, 7, 3, 21, 48, 56, 4, 21, 0)

>>> random.sample(t, 2)

[56, 0]

一行代码在等差数列中随机选择一个数

用 random 中的 randrange 方法

>>> random.randrange(0, 100, 10)

70

快速随机打乱列表的顺序

用 random 模块里的 shuffle 方法

>>> import random

>>> t = list(range(20))

>>> t

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> random.shuffle(t)

>>> t

[16, 3, 13, 7, 6, 12, 17, 4, 15, 2, 5, 8, 18, 10, 9, 19, 14, 0, 1, 11]

创建一个空集合a={},这样对吗?

不对,这样创建的是空字典

>>> a = {}

>>> type(a)

用 set 关键字创建空集合

>>> a = set()

>>> type(a)

怎么打印出数字中分数格式

用 fractions 中的 Fraction 方法

>>> from fractions import Fraction

>>> print(Fraction(1, 3))

1/3

列出一个目录下所有的文件名和子文件名

用 os.walk 生成器函数,我用 site-packages 目录举例。

>>> import os

>>> dirs = os.walk('C:\Program Files\Python36\Lib\site-packages')

>>> for dir in dirs:

print(dir)

('C:\\Program Files\\Python36\\Lib\\site-packages', ['ad3', 'ad3-2.2.1.dist-info', 'adodbapi', 'aip', 'appium', 'AppiumLibrary', 'Appium_Python_Client-0.46-py3.6.egg-info', 'apscheduler', 'APScheduler-3.6.0.dist-info', 'atomicwrites', 'atomicwrites-1.3.0.dist-info', ...)

一行代码拼接字符串和序列形成新的列表

用 itertools 里的 chain 方法可以一行代码搞定。

>>> import itertools

>>> list(itertools.chain('ABC', range(5)))

['A', 'B', 'C', 0, 1, 2, 3, 4]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值