题1:求m以内的素数(m>2)

def find_all_primes_in(m):
    def prime(num):
        for i in range(2, num):
            if divmod(num, i)[1] == 0:
                return False
        return True

    print([i for i in range(2, m + 1) if prime(i)])


if __name__ == '__main__':
    find_all_primes_in(100)

我还有一种效率不是最高,但是写法最短的一行版求2到100以内的素数的写法:

print(list(filter(lambda num: False not in set([False if divmod(num, i)[1] == 0 else True for i in range(2, num)]), [i for i in range(2, 101)])))

这种方法的优点是只有一行,缺点是判断素数的方法不好,把之前所有的数都遍历了一遍并判断是否能够整除,最后才得出是否是素数的结论。正确的方法是遍历之前的数,如果出现了能整除的直接就返回False不再继续判断。 

 

题2:求m个数中最小的n个数(m>n)

def get_max(data):
    max, index = data[0], 0
    for i in range(1, len(data)):
        if data[i] > max:
            max, index = data[i], i

    return max, index


def get_min(data, n, min=[]):
    for dt in data:
        if len(min) < n:
            min.append(dt)
        else:
            max, index = get_max(min)
            if dt < max:
                min[index] = dt

    print(sorted(min))


if __name__ == '__main__':
    data = [2, 55, 41, 2, 56, 89, 85, 45, 15, 3, 6, 4, 89, 75, 21, 10, 20, 31, 226, 10, 225, 456, 895, 42, 14, 547, 61,
            45, 95, 84, 81]
    get_min(data, 5)