前端之家收集整理的这篇文章主要介绍了
python面试题简单罗列,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
感兴趣python面试题简单罗列的小伙伴,下面一起跟随编程之家 jb51.cc的小编来看看吧。
# 来自jb51.cc
一些初级python面试题,这里简单罗列一下
# 反转字符串, 这个是最常见的
# 比如给一个字符串hello,将其反转为olleh
def reverse(str):
alist = list(str)
alist.reverse()
new_str = ''.join(alist)
return new_str
# 写一个方法打印如下内容,每一行打印5个
# server1,server2,server3,server4,server5(换行)
# server6,server7,server8,server9,server10(换行)
# server11,server12,server13,server14,server15(换行)
# server16,server17,server18,server19,server20(换行)
# ...
# server996,server997,server998,server999,server1000
#正确写法1
for i in range(1,1000):
if (i % 5 == 1):
a = i + 1
b = i + 2
c = i + 3
d = i + 4
print('server' + str(i) + ',' + 'server' + str(a) + ',' + 'server' + str(b) + ',' + 'server' + str(c) + ',' 'server' + str(d))
#正确写法2
for i in range(1,1004):
if (i % 5 == 0):
a = i - 4
b = i - 3
c = i - 2
d = i - 1
print('server' + str(a) + ',' + 'server' + str(d) + ',' 'server' + str(i))
#注意难点
#print语句每运行一次,都是另起一行,因此完全不必要写一个\n
#以下是错误写法
for i in range(1,1000):
if (i % 5 == 0):
print('server' + str(i) + '\n')
else:
print('server' + str(a) + ',')
#这种写法的运行结果是
server1,
server2,
server3,
server4,
server5
server6,
server7,
server8,
server9,
server10
server11,
server12,
server13,
server14,
server15
server16,......
# 给一个dir,循环遍历该dir下面的所有文件(只列出文件,不要文件夹).
import os
def get_file_names(dir):
alist = os.listdir(dir)
path = os.path.realpath(dir)
result = []
for i in alist:
ipath = os.path.join(path,i)
if os.isdir(ipath):
#get_file_name(ipath)
result.extend(get_file_name(ipath))
else:
result.append(ipath)
return result
# Given an array of integers,return indices of the two numbers
# such that they add up to a specific target.
# You may assume that each input would have exactly one solution.
# 给了一个全是数字的列表,现在让列表中任意2个数字相加,得到一个指定target,# 然后返回这2个数字的index
# Example:
# Given nums = [2,7,11,15],target = 9,#
# Because nums[0] + nums[1] = 2 + 7 = 9,# return [0,1].
def two_sum(nums,target):
for a in (0,len(nums)):
b = a + 1
res1 = 0
res2 = 0
for i in (b,len(nums)):
if ( nums[a] + nums[i] == target ):
res1 = a
res2 = i
return [res1,res2]
原文链接:https://www.f2er.com/pythoninterview/527109.html