@virnuls/

Years in Range

Python

One of the tasks from the OCR Coding Challenges booklet

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# input with validation as a function
def ask(question):
  answer = input(question)
  try:
    answer = int(answer)
    if answer < 0:
      print("Numbers entered must be positive.")
    return answer
  except:
    print("The input must be a valid number.")
    return -1

#Check for repeated digits
def repeated_digits(num_int):
  # put the digits from the number into a list
  num_list = list(str(num_int))
  # iterate through the list
  for digit in num_list:
    # count whether the digit appears more than once
    if num_list.count(digit) > 1:
      return True
  return False

start = finish = -1
# No negative numbers
while start < 0:
  start = ask("First year in range: ")
# The end of the range can't be before the start
while finish < start:
  # the end of the range can't be before the start
  finish = ask("Last year in range: ")
  if finish < start:
    print("The last year can't be earlier than the first one.")

# Loop through the range of years
repeated = 0
# loop through the years counting if digits repeated
for yr in range(start, finish+1):
  repeated += repeated_digits(yr)

# Display the results with correct grammar
verb = ("are","is")
print("There",verb[repeated == 1],repeated,"year"+"s"*(repeated != 1),"in the range",start,"-",finish,"that contain"+"s"*(repeated == 1),"repeated digits.")