[WikiItic] [TitleIndex] [WordIndex

1. Exercicis Resolts Tema 9

Exercici 9.1

def suma_enters(m):
    """
    Suma els enters entre 1 i m.
    """
    if m==2:
        return 0
    else:
        return suma_enters(m-1) + (m-1)


Exercici 9.2

    def longitud(cadena):
    """
    Retorna la longitud duna cadena de caracters
    """
    if not len(cadena):
        return 0
    else:
        return 1 + longitud(cadena[1:])
    


Exercici 9.3

>>>def compta_a(cadena):
    """ 
    Compta les as que hi ha en una cadena de paraules
    """
    if not cadena:
        return 0
    elif cadena[0] != "a":
        return compta_a(cadena[1:])
    else:
        return 1 + compta_a(cadena[1:])


Exercici 9.4

def posicio(l,e):
    #l:llista ordenada d'enters
    #e:enter contingut a l
    if l[0]== e:
        return 0
    else:
       return 1 + posicio(l[1:],e)


Exercici 9.5

def palindroma(a):
    if len(a)==1:
        return True
    if len(a)==2:
        return a[0]==a[1]
    else:
        if a[0]==a[-1]:
            return True and palindroma(a[1:len(a)-1])
        else:
            return False


_Exercici 9.6

def inversa(l):
    if len(l)==0:
        pass
    elif len(l)==1:
        return l
    elif len(l)==2:
        return [l[1]]+[l[0]]
    else:
        return [l[-1]]+inversa(l[1:len(l)-1])+[l[0]]

_Exercici 9.6_ (senzill)

def inversa(l):

    if len(l)==0:
        return  []
    else:
        return inversa(l[1:])+[l[0]]

_Exercici 9.7

def fib(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

_Exercici 9.8 (lent)

def eleva(x,y):
    if y==0:
        return 1
    elif y==1:
        return x
    else:
        return eleva(x,y-1)*eleva(x,1)


_Exercici 9.8 (rĂ pid)

def eleva2(x,y):
    if y==0:
        return 1
    elif y%2==0:
        return eleva2(x*x,y/2)
    else:
        return x*eleva2(x,y-1)

_Exercici 9.8_ (senzill)

def potencia(x,y):
    if y == 1:
        return x
    else : 
        return potencia(x,y-1) * x

CategoryApunts


2023-07-03 11:46