И если вы действительно хотите свести этот тип решения к минимуму:
def is_prime(n):
factors = range(2, int(math.sqrt(n)) + 1)
return (n > 1 and all(n % f for f in factors))
Один неожиданный элемент пустяков, который я мог бы знать однажды и забыть.Почему функция возвращает True
для n = 2
?
factors # range(2, 1 + 1)
# range(2, 2)
# Which is an empty range.
# Or in more concrete form: an empty list.
n > 1 # True
all([]) # Hmmmmm?
#
# Are all of the items in an empty collection true?
#
# If every tree falls in the forest at once, but no one hears them,
# does it make a sonic boom?
#
# Contrary to Billy Preston -- and microeconomists world wide --
# can you really get something from nothing?
#
# Python says YES. I'm sure smart mathematics do too, but
# I would be curious to hear the reasoning.
Я думаю, у StackOverflow есть ответ на мой вопрос.И у логиков есть имя для этой ситуации: " пустая правда - это утверждение, которое утверждает, что все члены пустого набора имеют определенное свойство."