3114 - abq

From Bitnami MediaWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Cerință

Alexandru a învățat azi despre numerele romane și cum se scriu acestea. Fiind distras de ce spuneau colegii a ajuns acasă și a realizat că nu știe cum să transforme un număr din cifre arabe în cifre romane. Deoarece a doua zi are un test numai din acest capitol, vă roagă să îl ajutați la transformarea unui număr N dat, scris cu cifre arabe în cifre romane.

Date de intrare

Fișierul cifre_romane.in conține un număr natural N scris cu cifre arabe.

Date de ieșire

Fișierul cifre_romane.out va conține scrierea cu cifre romane a lui N.

Restricții

  • 1≤N≤3999
  • cifrele romane sunt:
    • I=1
    • V=5
    • X=10
    • L=50
    • C=100
    • D=500
    • M=1000

Exemplu

cifre_romane.in

4

cifre_romane.out

IV

Rezolvare

<syntaxhighlight lang="python3"> import sys

def convert_to_roman(num):

   """Converts a given number from Arabic numerals to Roman numerals."""
   roman_numerals = {
       1: "I",
       5: "V",
       10: "X",
       50: "L",
       100: "C",
       500: "D",
       1000: "M"
   }
   result = ""
   while num > 0:
       # Find the largest Roman numeral that is less than or equal to the current number
       for key in sorted(roman_numerals.keys(), reverse=True):
           if num >= key:
               result += roman_numerals[key]
               num -= key
               break
   return result

def main():

   """Reads input and converts numbers to Roman numerals."""
   num = int(input())
   # Check if the number is within the valid range
   if 1 <= num <= 3999:
       roman_numeral = convert_to_roman(num)
       print(roman_numeral)
   else:
       print("Numarul nu este in intervalul valid (1 ≤ N ≤ 3999).")

if __name__ == "__main__":

   sys.stdin = open("cifre_romane.in")
   sys.stdout = open("cifre_romane.out", "w")
   main()
   sys.stdin.close()
   sys.stdout.close()

</syntaxhighlight>