Oppgave 1 - Opprette dictionaries
Code Block | ||
---|---|---|
| ||
kokebok = {'pasta carbonara':['fløte','pasta','bacon'], 'sopp risotto':['sopp','ris','fløte'], 'pasta bolognese':['pasta','kjøttdeig','tomatsaus']} |
Oppgave 2 - Hente, slette og legge til verdier fra en dictionary
Code Block | ||
---|---|---|
| ||
#a print(kokebok.get('pasta carbonara')) #b kokebok['kyllingsalat'] = ['kylling','tomat','agurk','salat'] #c if 'sopp risotto' in kokebok: print 'sopp risotto finnes i kokeboken' else: print 'beklager, opp risotto finnes ikke i kokeboken' #d del kokebok['pasta bolognese'] |
Oppgave 3 - Iterere over elementer i en dictionary
Code Block | ||
---|---|---|
| ||
for rett in kokebok: print rett + ' inneholder ' + str(kokebok.get(rett)) |
Oppgave 4 - Endre verdier i en dictionary
Code Block | ||
---|---|---|
| ||
for rett in kokebok: kokebok[rett].append('salt') kokebok[rett].append('pepper') |
Oppgave 5 - Nyttige dictionaries metoder
Code Block | ||
---|---|---|
| ||
print(kokebok.keys()) print(kokebok.values()) kokebok.clear() |
Oppgave 6 - Enkle sett-operasjoner
Code Block | ||
---|---|---|
| ||
#a primtall = set([2,3,5,7]) #b print(len(primtall)) #c primtall.add(11) primtall.add(13) #d primtall.discard(min(primtall)) #e for tall in primtall: print(tall) |
Oppgave 7 - Union og snitt av sett
Code Block | ||
---|---|---|
| ||
#a oddetall = set([1,3,5,7,9,11,13]) #b print(oddetall.intersection(primtall)) #c print(oddetall.union(primtall)) #d print(oddetall.difference(primtall)) #e print(primtall.issubset(primtall)) |
Oppgave 8 - Fakultet
Code Block | ||
---|---|---|
| ||
def fakultet(n):
if n == 0:
return 1
else:
return n * fakultet(n - 1) |
Oppgave 9 - Fibonacci
Code Block | ||
---|---|---|
| ||
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2) |
Oppgave 10 - Pascals trekant
Code Block | ||
---|---|---|
| ||
def pascal(n):
if n == 1:
return [1]
else:
linje = [1]
forrige_linje = pascal(n-1)
for i in range(len(forrige_linje)-1):
line.append(forrige_linje[i] + forrige_linje[i+1])
linje += [1]
return linje |
Oppgave 11 - Palindrom
Code Block | ||
---|---|---|
| ||
def palindromTest(S):
if len(N) == 1 or len(N) == 0:
return True
else:
if N[0] == N[-1] and palindromTest(N[1:-1]):
return True
else:
return False |
Oppgave 12 - Minste element
Code Block | ||
---|---|---|
| ||
def minElement(L,n):
if n == 1:
return L[0]
else:
min = minElement(L[1:],n-1)
if L[0] < min:
return L[0]
else
return min |
Oppgave 13 - Største element
Code Block | ||
---|---|---|
| ||
def maxElement(L):
if len(L) == 1:
return L[0]
else:
max = maxElement(L[1:])
if L[0] > max:
return L[0]
else
return max |
Oppgave 14 - Exponent
Code Block | ||
---|---|---|
| ||
def power(x, n):
if n < 1:
return 1
return power(x, n-1) |