Why does my linear regression code print multiple times in one terminal?

0
4
Asked By PixelPioneer94 On

I've developed a linear regression program for an assignment, and it's mostly functioning as expected. However, when I execute the code, it outputs the result multiple times—specifically five times in my terminal, which corresponds to the length of my list. Interestingly, when I run the same code in a separate terminal session, it only prints the result once. Is this behavior typical? In my function, there's a for loop that processes a list of numbers to compute the necessary variables for the regression formula. Here's a snippet of my code:

```python
x = [1, 2, 3, 4, 5]
y = [2, 4, 5, 4, 5]

def fit(x, y):
# calculate xy, x^2, sum x and sum y
...
return m, b

m, b = fit(x, y)
def predict(x_value):
return (m * x_value) + b
print(f'y = {m}x + {b}')
print(predict(10))
```
Could anyone shed light on why this is happening and how to fix it?

2 Answers

Answered By CodeMaster23 On

It looks like you might be calling `fit(x, y)` twice—once when you set `m, b`, and again right before those print statements. That second call is likely causing the output to appear multiple times in your terminal. It’s puzzling why the dedicated terminal behaves differently, but try removing that extra `fit(x, y)` call and see if that resolves the issue!

DebugDiva88 -

Oh, good catch! I completely missed that duplicate call. If removing it fixes the prints, then you’re golden!

Answered By TechWhiz42 On

It seems like you're printing while inside the for loop, which can lead to multiple outputs. As for what a 'dedicated terminal' means, I'm not really sure, but consider running your code step-by-step to track the variable changes and the print outputs manually—it might help you pinpoint the issue!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.