知乎5题测试

https://www.zhihu.com/question/40581047/answer/225775958

在知乎上面看到这样五道题。
作者说:如果上面的题目不会写出代码,说明只学了一些语法皮毛!
我就体验了一把,感觉题还是很不错的。
第四题强调用递归实现,我比较笨,只会用for循环。大神们快来看看有没有更好的解决办法。

1、只用循环输出这样的样式:1,2,3,4,5,6,7,8,9,10

print((",").join([str(i) for i in range(1,11)]))

2、请问一个日志文本文件有2000行,我要提取其中的100行到200行,怎么做?(限定只能用循环)

file2 = open('out.txt',"w")
def outLine(filepath):
    file1 = open(filepath,"r")
    while True:
        line = file1.readline()
        yield line
        if not line:
            break
    file1.close()
list1 = list(outLine("test.txt"))
file2.writelines(list1[100:201])
file2.close()

#方法2:
i = 0
file1 = open("test.txt","r")
file2 = open("out.txt","w")
while True:
    line = file1.readline()
    i += 1
    if 100<=i and i<=200:
        file2.write(line)
    if i>200:
        break
    if not line:
        break
file1.close()
file2.close()

3、全部用递归求第N个质数,不能用循环。

def prime(N):
    mylist = []
    for i in range(2, 1000000000):
        a = primes(i)
        if a is not 0:
            mylist.append(a)
            if len(mylist) == N:
                yield a
                break
    return mylist


def primes(n):
    a = True
    if n < 2:
        a = False
    elif n == 2 or n == 3:
        a = True
    else:
        for i in range(2, n // 2+1):
            if n % i == 0:
                a = False
                break
            else:
                continue
    if a is True:
        return n
    else:
        return 0


for i in prime(3):
    print(i,end=" ")

4、从终端读入一个整数n,随机一个输入一个0 或1
判断连续是0 或1 的最大次数。如:
输入
0
0
0
1
1
1
1
0
1
0
1在连续输入中,出现4次

from random import randint
number = eval(input("请输入一个数"))
# a=[1,0,0,1,1,1,0,0,0,0]
a = [randint(0, 1) for i in range(number)]
num = 1
counterd = 0
max = 1
Themax = 1
for i in range(len(a)):
    print(a[i])
    if a[i] == a[i - 1]:
        max += 1
        num += 1
    else:
        if Themax <= max:
            Themax = max
            counterd = a[i - 1]
        max = 1
        num = 1
else:
    if Themax <= max:
        Themax = max

print("%s在连续输出中输出了%s次" % (counterd, Themax))

5、用python写一个程序,找出数组中差值为K的数共有几对。

from random import randint
from collections import Counter
am = Counter()
k =eval(input("please input a number"))
a = [randint(1,10) for i in range(10)]
print(a)
for i in range(len(a)):
    for j in range(i+1,len(a),1):
        m = abs(a[i]-a[j])
        if k==m:
            print(a[i],a[j])
            am[m]+=1
        else:
            pass
print(am[k])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值