-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathexercise5.py
More file actions
61 lines (50 loc) · 1.85 KB
/
exercise5.py
File metadata and controls
61 lines (50 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import math
# Use AI to debug your code
# Using the hot-key `Ctrl + I`, I instructed the AI to write some buggy code.
# The instruction to the chatbot was:
# Please write Python code that makes a function to compute the nth Fibonacci number
# but the function makes a mistake and outputs the wrong number.
# Also, please write a function to compute the nth Fibonacci number
# but the function makes a mistake which creates an error.
# At the end of the file, write a if __name__ == "__main__": block
# that calls both functions with example inputs and prints the results.
# There are two functions below with bugs in them.
# Your task is to use debugging techniques to find and fix the bugs.
# Highlight the code below and use `Ctrl + I` to ask the AI to help you debug it.
def fibonacci(n: int) -> int:
"""Return the nth Fibonacci number with fibonacci(0)=0, fibonacci(1)=1 (n >= 0)."""
if n < 0:
raise ValueError("n must be non-negative")
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# The buggy functions below were generated by the AI.
def fibonacci_v1(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_v1(n-1) + fibonacci_v1(n-2) + 1
def fibonacci_v2(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
fib_list = [0, 1]
return fib_list[n-1] + fib_list[n-2]
if __name__ == "__main__":
print('Correct Fibonacci function results:')
print(f"fibonacci(5) = {fibonacci(5)}")
print(f"fibonacci(7) = {fibonacci(7)}")
print()
print("Testing fibonacci_v1:")
print(f"fibonacci_v1(5) = {fibonacci_v1(5)}")
print(f"fibonacci_v1(7) = {fibonacci_v1(7)}")
print("\nTesting fibonacci_v2:")
try:
print(f"fibonacci_v2(5) = {fibonacci_v2(5)}")
except Exception as e:
print(f"Error occurred: {e}")