Add tasks

This commit is contained in:
Oystein Kristoffer Tveit 2020-09-14 14:34:03 +02:00
parent d472539f38
commit fed17cb0a5
4 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,26 @@
def numberPyramid(length):
for i in range(length):
row = ''
for k in range(i+1):
row += f'{k+1} '
print(row)
def numberPyramidGenerator():
currentList = ['1']
while True:
yield ' '.join(currentList)
currentList.append(str(int(currentList[-1]) + 1))
def solutionWithForLoops(n):
return numberPyramid(n)
def solutionWithGenerator(n):
myGenerator = numberPyramidGenerator()
for i in range(n):
print(next(myGenerator))
if __name__ == "__main__":
n = int(input('n: '))
print(solutionWithForLoops(n))

18
Exercise 3/8.py Normal file
View File

@ -0,0 +1,18 @@
def fibonacciIterative(n):
k1 = 0
k2 = 1
for i in range(n-1):
previousK2 = k2
k2 = k1 + k2
k1 = previousK2
return k1
fibonacciSum = lambda n: sum([fibonacciIterative(i) for i in range(1, n+1)])
fibonacciList = lambda n: [fibonacciIterative(i) for i in range(1, n+1)]
if __name__ == "__main__":
n = int(input('n: '))
print(f'a) Fibonacci({n})', fibonacciIterative(n))
print(f'b) Sum av Fibonacci(1..{n})', fibonacciSum(n))
print(f'c) Sum av Fibonacci(1..{n})', fibonacciList(n))

View File

@ -0,0 +1,9 @@
def alternateSum(n):
positiveNumbers = [num**2 for num in [i for i in range(1,n+1) if i % 2 != 0]]
negativeNumbers = [-num**2 for num in [i for i in range(1,n+1) if i % 2 == 0]]
return sum(positiveNumbers + negativeNumbers)
if __name__ == "__main__":
n = int(input('n: '))
print(alternateSum(n))

View File

@ -0,0 +1,24 @@
def AlternateNumberGenerator():
isEven = lambda n: n % 2 == 0
n = 1
counter = 2
while True:
yield n
n = n + (-counter**2 if isEven(counter) else counter**2)
counter+=1
def alternateSumStopAt(k):
numGen = AlternateNumberGenerator()
previousN = None
n = next(numGen)
iterations = 0
while n<k:
previousN = n
n = next(numGen)
iterations += 1
print(f'Summen av tallene før summen blir større enn k er {previousN}. Antall iterasjoner: {iterations}')
if __name__ == "__main__":
k = int(input('k: '))
alternateSumStopAt(k)