Hello stackoverflowbros
I came up with a fun problem to find all the years (in the recent future, before I day basically) for which all of the following are true:
1) the day is prime (eg the 5th or the 17th of the month)
2) the month is prime (eg May is the 5th month 5 is prime)
3) the year is prime (eg the year 2027 is prime)
4) the numbers concatenated in DDMMYYYY format is prime (eg 3022027 is prime)
My code works which is nice. I get the following answers:
3-02-2027
13-02-2027
31-02-2027 ## February has 31 days now ok
31-05-2027
29-07-2027
But I also get told that the line if isPrime(year) and isPrime(month) and isPrime(day) and isPrime(int(str(day) + datefix(month) + str(year))):
Is TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
I have two questions: 1) what have I done wrong? 2) why do i only get answers in 2027 (kind of related, why do i get any answers at all if there's an error)
def isPrime(n) :
# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def datefix(y):
if y <= 9:
y = str(str(0) + str(y))
return y
print(type(datefix(5)))
years = range(2019, 2054) ## 2053 is a good year to stop - and it's prime
days = range(2, 32)
months = range(2,13)
for year in years:
for month in months:
for day in days:
if isPrime(year) and isPrime(month) and isPrime(day) and isPrime(int(str(day) + datefix(month) + str(year))):
print(str(day) + '-' + datefix(month) + '-' + str(year))
Well because datefix
only returns y
if y <= 9
, then if it's not,
It returns None
, the default return type of a function in Python.
So in your example Month is bigger than 9.
The function datefix
needs to handle that case.