Implement the basic algorithm in Python to deepen your understanding of the algorithm. The year is treated as the seventh bullet.
This time, we made it possible to convert from Meiji to Reiwa. However, as will be described later, this time the program is versatile, so it can be expanded as much as possible by adding only the year standard and year name. However, the year of the same year (eg, 1988 and 1989) will be the new era.
The year boundary for the first year from the Meiji era to Reiwa, that is, the boundary of the era, is shown below.
Year | Year |
---|---|
First year of the Meiji era | 1868 |
Taisho era | 1912 |
Showa 1st year | 1926 |
1989 | 1989 |
First year of Reiwa | 2019 |
Based on the above, implement it in python. The code and output are shown below.
era_name.py
"""
2020/12/18
@Yuya Shimizu
Year conversion
"""
def trans2era_name(year):
year_dict = {2019:"Reiwa", 1989:"Heisei", 1926:"Showa", 1912:"Taisho", 1868:"Meiji"} #Year boundary
change = True #Variable for determining whether conversion was possible
#Year judgment
for Y in year_dict:
if year >= Y:
year -= Y
if year == 0:
print(year_dict[Y] + "First year")
else:
print(year_dict[Y] + str(year + 1) + "Year")
change = False
break
#Error message for not subject to year conversion
if change:
print("Conversion is possible only in the range from Meiji to Reiwa")
trans2era_name(1868)
Reiwa 2 years
First year of the Meiji era
Conversion is possible only in the range from Meiji to Reiwa
As I mentioned at the beginning, I think we have created something that is highly versatile. I will explain the code a little. The year_dict contains the year and the year set of the first year. In the defined function, the dictionary type array is rotated by for, so the target of year conversion can be expanded by simply adding the contents of ** year_dict **. However, it may be necessary to change the content of the error message that is output when the year cannot be converted.
The year conversion dealt with this time was given as a reference question, and I thought about it myself and created the program. As I mentioned earlier, I think it was well organized. Although I have just begun to learn algorithms, I felt that algorithms and ideas were important, and I became more motivated to learn algorithms.
Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha
Recommended Posts