Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Sean Connery, who played James Bond, 007, died on 31-10-20
- # The sum of the digits of that date is 007
- # How many dates are there in 2020 that total 007 in this way?
- # Mike Kerry - 15-April-2021
- mm, dd, ctr = 1, 1, 0
- while mm < 13:
- tot = 2 # Start a total containing 2 (as we are only dealing with year "02"
- # combine month and day into one integer e.g. month 12 day 15 becomes 1215
- x = mm * 100 + dd
- # Write a loop which continues until x becomes zero, processing 1 digit at a time
- while x:
- tot += x % 10 # get remainder of x divided by 10 and add it to tot.
- # This will be the junior digit (5, then 1, then 2, then 1)
- x //= 10 # Floor-Divide x by 10. This drops the junior digit
- # so, in our example, 1215 becomes 121
- if tot == 7: # If the total of all digits is 7 ...
- ctr += 1 # ... add 1 to our counter of matching dates
- # and print the counter and the date. I use zfill to get leading zeroes
- print(ctr, str(dd).zfill(2) + "-" + str(mm).zfill(2) + "-20")
- # Line 44 below is an algorithm I developed a few years ago for getting
- # the number of days per month. I think it's quite fun
- # I had noticed that odd numbered months from Jan to Jly have 31 days
- # But even numbered months from Aug to Dec have 31 days
- # Explanation: Start with (mm > 7) This is an expression that is either True or False
- # So if mm is August thru December, the expression evaluates to 1 (True)
- # and for months Jan thru July, it evaluates to zero (False)
- # Then the 1 or zero is added to mm so Jan to Jly stay as 1 to 7
- # and Aug to Dec become 9 to 13. Now it's all the odd numbers that have 31 days.
- # Then we use a bitwise AND (&) to determine if the number from above is odd or even
- # This gives 1 for odd numbers, zero for even
- # So Jan, Mar, May, Jly, Aug, Oct, Dec give a 1, the other months give zero
- # The resultant 1 or zero is added to 30, giving us the correct number of days per month
- # (Apart from Feb which is then handled discretely)
- n = 30 + (mm + (mm > 7) & 1)
- if mm == 2: # Special case for February
- n = 29 # We are only dealing with 2020, which is a leap year
- dd += 1 # Bump day by 1
- if dd > n: # If beyond month end ...
- mm += 1 # ... go to next month
- dd = 1 # ... and day 1
- # Output:-
- # 1 04-01-20
- # 2 13-01-20
- # 3 22-01-20
- # 4 31-01-20
- # 5 03-02-20
- # 6 12-02-20
- # 7 21-02-20
- # 8 02-03-20
- # 9 11-03-20
- # 10 20-03-20
- # 11 01-04-20
- # 12 10-04-20
- # 13 04-10-20
- # 14 13-10-20
- # 15 22-10-20
- # 16 31-10-20
- # 17 03-11-20
- # 18 12-11-20
- # 19 21-11-20
- # 20 30-11-20
- # 21 02-12-20
- # 22 11-12-20
- # 23 20-12-20
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement