Riešenie 17. cvičenia


  1. Napríklad:

    >>> zoz = [1, '2']
    >>> zoz[2]
    IndexError: list index out of range
    >>> zoz.pop(2)
    IndexError: pop index out of range
    >>> zoz.remove(2)
    ValueError: list.remove(x): x not in list
    >>> zoz[2] = 3
    IndexError: list assignment index out of range
    >>> zoz + 3
    TypeError: can only concatenate list (not "int") to list
    >>> zoz * zoz
    TypeError: can't multiply sequence by non-int of type 'list'
    >>> zoz / 2
    TypeError: unsupported operand type(s) for /: 'list' and 'int'
    >>> zoz()
    TypeError: 'list' object is not callable
    >>> zoz.index(3)
    ValueError: 3 is not in list
    >>> zoz[:0].pop()
    IndexError: pop from empty list
    >>> zoz += 1
    TypeError: 'int' object is not iterable
    >>> zoz[None]
    TypeError: list indices must be integers or slices, not NoneType
    >>> zoz[0]()
    TypeError: 'int' object is not callable
    >>> zoz.sort()
    TypeError: '<' not supported between instances of 'str' and 'int'
    

  1. Riešenie:

    def int2(hodnota, nahrada=None):
        try:
            return int(hodnota)
        except (ValueError, TypeError):
            return nahrada
    
    def float2(hodnota, nahrada=None):
        try:
            return float(hodnota)
        except (ValueError, TypeError):
            return nahrada
    

  1. Riešenie:

    def zoznam_cisel(retazec):
        vysl = []
        if isinstance(retazec, str):
          for prvok in retazec.split():
              try:
                  vysl.append(int(prvok))
              except (ValueError, TypeError):
                  pass
        return vysl
    

  1. Riešenie:

    def priemer(zoznam):
        try:
            sucet = sum(zoznam)
        except TypeError:
            return 0
        try:
            return sucet / len(zoznam)
        except ZeroDivisionError:
            return None
    

  1. Riešenie:

    def suma(postupnost):
        vysl = 0
        for prvok in postupnost:
            try:
                vysl += prvok
            except TypeError:
                pass
        return vysl
    

  1. Riešenie:

    def suma2(postupnost):
        vysl = 0
        for prvok in postupnost:
            try:
                vysl += prvok
            except TypeError:
                if not isinstance(prvok, str):
                    try:
                        vysl += suma2(prvok)
                    except TypeError:
                        pass
        return vysl
    

  1. Riešenie:

    def pocet_riadkov(meno_suboru):
        try:
            with open(meno_suboru) as subor:
                return subor.read().count('\n')  # alebo return len(subor.readlines())
        except FileNotFoundError:
            return -1
    

  1. Riešenie:

    def daj_cislo(meno_suboru, index, nahrada=0):
        try:
            with open(meno_suboru) as subor:
                while index > 0:
                    subor.readline()
                    index -= 1
                return int(subor.readline())
        except (FileNotFoundError, ValueError):
            return nahrada
    

  1. Riešenie:

    def sustavy(retazec):
        vysl = []
        for i in range(17):
            try:
                vysl.append(int(retazec, i))
            except ValueError:
                vysl.append(None)
        return vysl
    

  1. Riešenie:

    def ako(hodnota1, hodnota2):
        try:
            return type(hodnota1)(hodnota2)
        except TypeError:
            return None
    

  1. Riešenie:

    def sucet(zoznam):
        vysl = zoznam[0]
        for prvok in zoznam[1:]:
            try:
                vysl += type(vysl)(prvok)
            except TypeError:
                pass
        return vysl
    

  1. Riešenie:

    class TelefonnyZoznam:
        def __init__(self, meno_suboru=None):
            try:
                self.citaj(meno_suboru)
            except ValueError:
                pass
    
        def pridaj(self, meno, telefon):
            if not isinstance(meno, str):
                raise TypeError('meno musi byt retazec')
            if not isinstance(telefon, str):
                raise TypeError('telefon musi byt retazec')
            for i, (m, t) in enumerate(self.zoznam):
                if m == meno:
                    self.zoznam[i] = meno, telefon
                    return
            self.zoznam.append((meno, telefon))
    
        def zisti(self, meno):
            for m, t in self.zoznam:
                if m == meno:
                    return telefon
            raise KeyError(f'{meno!r} nie je v zozname')
    
        def citaj(self, meno_suboru):
            self.zoznam = []
            try:
                with open(meno_suboru) as subor:
                    for riadok in subor:
                        m, t = riadok.split()
                        self.pridaj(m, t)
            except (TypeError, ValueError, FileNotFoundError):
                raise ValueError(f'chybny subor {meno_suboru!r}')
    
        def zapis(self, meno_suboru):
            try:
                with open(meno_suboru, 'w') as subor:
                    for m, t in self.zoznam:
                        print(m, t, file=subor)
            except (TypeError, PermissionError):
                raise ValueError('chybny subor {meno_suboru!r}')
    
        def vypis(self):
            for m, t in self.zoznam:
                print(m, t)