Python :: Aufgabe #318

3 Lösungen Lösungen öffentlich

Liste aller zukünftigen Palindromtage in diesem Jahrtausend

Anfänger - Python von hollst - 12.02.2021 um 18:29 Uhr
Ein Datum (z. B. 12. Februar 2021) nennt man Palindromdatum, wenn es als Zahl geschrieben ein Palindrom ist (12022021, vorwärts gelesen identisch mit rückwärts gelesen).

Man schreibe ein Programm, das alle zukünftige Palindromtage bis zum 31. Dezember 2999 ausgibt.

Viel Spaß

Lösungen:

vote_ok
von satn1241 (2900 Punkte) - 14.02.2021 um 16:09 Uhr
Quellcode ausblenden Python-Code
from datetime import date
from datetime import timedelta

liste = []
anfang = date(1999, 12, 31)
ende = date(3000, 1, 1)


# Palindrom_check
def palindrom(datum):
    for i in range(0, len(datum)):
        if datum[i] == datum[len(datum) - 1 - i]:
            continue
        return False
    else:
        return True


for i in range(0, (ende - anfang).days):
    anfang += timedelta(1)
    datum = str(anfang.strftime("%d.%m.%Y"))
    datum_zahl = ""
    for e in datum:
        if e != ".":
            datum_zahl += e
    if palindrom(datum_zahl):
        datum = datum_zahl[0:2] + "." + datum_zahl[2:4] + "." + datum_zahl[4:9]
        liste.append(datum)
print("Es gibt", len(liste), "Palindromdaten in diesem Jahrtausend.")
print(liste)
vote_ok
von eisheiliger (1980 Punkte) - 21.02.2021 um 17:39 Uhr
Quellcode ausblenden Python-Code
"""
#318: Liste aller zukünftigen Palindromtage in diesem Jahrtausend
Man schreibe ein Programm, das alle zukünftige Palindromtage bis zum 31. Dezember 2999 ausgibt.
"""

import datetime

beg = datetime.datetime.strptime("01012021", "%d%m%Y")
end = datetime.datetime.strptime("31122999", "%d%m%Y")
datum = (beg + datetime.timedelta(days=x) for x in range(0, (end - beg).days))

for zeitstrahl in datum:
    pal_in = (zeitstrahl.strftime("%d%m%Y"))
    pal_out = ""
    for nex in pal_in:
        pal_out = nex + pal_out
    if pal_in == pal_out:
        print(pal_in)

vote_ok
von bobTheCoder (40 Punkte) - 14.03.2021 um 17:17 Uhr
Im sorry for neglecting all styleguides, but im open for improvments
greetings Bob

Quellcode ausblenden Python-Code
def wrap(func):
    # a decorathor, which allows to read input and output of a function easly
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        msg = "{}(".format(func.__name__)
        if args:
            msg += "{}".format(args).replace("(", "").replace(")", "")
        if kwargs:
            msg += "{}".format(kwargs)
        msg += ") -> {} {}".format(result, type(result))
        msg = msg.replace("\n", "").replace("  ", "")
        print(msg)
        return result

    return wrapper


def is_palindrom(text):
    # returns true, if the text is mirrored
    # eg. "12321", "aba", "a"
    text = text
    if text == text[::-1]:
        return True
    return False


class Date:
    # constants
    DAYS = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]
    MONTHS = ["Jan", "Feb", "Mer", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"]
    DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    def __init__(self, day, month, year):
        self.day, self.month, self.year = day, month, year

    @property
    def is_valid(self):
        # if self is a valid date it will return true
        d, m = self.day, self.month
        if 0 <= m <= len(self.MONTHS) + 1:
            if 0 <= d <= self.DAYS_IN_MONTH[m - 1] + 1:
                return True
        return False

    def __gt__(self, other):
        # self > other
        if self is not other:
            d, m, y = self.day, self.month, self.year
            if y > other.year:
                return True
            if y is other.year and m > other.month:
                return True
            if y is other.year and m is other.month and d > other.day:
                return True
        return False

    def __lt__(self, other):
        # self < other
        return not self.__gt__(other)

    def __ge__(self, other):
        # self >= other
        if self is other or self > other:
            return True
        return False

    def __le__(self, other):
        # self <= other
        if self is other or self < other:
            return True
        return False

    def __eq__(self, other):
        # self == other
        if self.day is other.day:
            if self.month is other.month:
                if self.year is other.year:
                    return True
        return False

    def __repr__(self):
        # represents self
        return "Date({}/{}/{})".format(self.day, self.month, self.year)

    def __add__(self, other):
        # unused, but
        # it adds two dates to a single one
        # or a date and a number of days
        if type(other) is Date:
            days = date2days(self) + date2days(other)
            return days2date(days)
        elif type(other) in (int, float):
            days = date2days(self) + other
            return days2date(days)
        else:
            raise ValueError("{} is not supported".format(type(other)))

    def __sub__(self, other):
        # unused, but
        # it subs two dates to a single one
        # or a date and a number of days
        if type(other) is Date:
            days = date2days(self) - date2days(other)
            return days2date(days)
        elif type(other) in (int, float):
            days = date2days(self) - other
            return days2date(days)
        else:
            raise ValueError("{} is not supported".format(type(other)))


def days2date(n):
    # convert a number of dates to a valid date
    year = n // 365
    n = n % 365
    month = 0
    for days in Date.DAYS_IN_MONTH:
        n -= days
        if n > 0:
            month += 1
        else:
            n += days
            break
    day = n
    return Date(day, month, year)


def date2days(date):
    # convert a date to a number of days
    if not date.is_valid:
        raise ValueError("Date isn't a valid date object!")
    days = date.day + date.year * 365 + sum(date.DAYS_IN_MONTH[:date.month])
    return days


@wrap
def palindromes_from_dates(start_date, end_date):
    # this function will return palindromes from a range between two dates
    assert start_date < end_date
    palis = []
    for days in range(date2days(start_date), date2days(end_date)):
        date = days2date(days)
        if is_palindrom("{}{}{}".format(date.day, date.month, date.year)):
            palis.append(date)
    return palis


print(palindromes_from_dates(Date(0, 0, 2000), Date(0, 0, 2999)))
# output = [Date(10/0/2001), Date(20/0/2002), ... usw ..., Date(19/9/2991), Date(29/9/2992)]