-2

I have a bunch of loops for calculations that I want to perform. I am calculating the average value of 4 lines in a file. However, I want to loop this calculation of an entire file with hundreds of numbers.

i.e.

2
5
3
7
3
1
4
6
2
4
3
2
...

would give

4.25 
3.5
2.75 
...

Can someone recommend a solution?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
msicam
  • 41
  • 4
  • 1
    I suspect [What is the most “pythonic” way to iterate over a list in chunks?](https://stackoverflow.com/q/434287/364696) or [How do you split a list into evenly sized chunks?](https://stackoverflow.com/q/312443/364696) would solve 99% of your problem (just use one of the generator-friendly solutions that doesn't assume a slicable input). – ShadowRanger Feb 25 '20 at 21:37
  • 4
    Please supply what you have tried so far. – eddyizm Feb 25 '20 at 21:42
  • what is your input format? – Ratnesh Feb 25 '20 at 21:47

1 Answers1

4

Your problem appears to be a general programming problem, not really a Python problem. You have a problem, you understand what needs to happen, but are having trouble coming up with a program.

Think about it in small steps. What do you really want to happen?

  1. you want to open a (text) file for reading
  2. you want to take the next four values from the file
  3. you want to compute their average
  4. you want to write that average to the screen
  5. if there's more left in the file, you want to get back to 2.
  6. otherwise, you're done

You assume the file is all single numbers on a line, that's ok. You assume the file will have a multiple of 4 lines, also ok. But you should probably also think about what happens if that's not true.

Which part is giving you trouble? Which one of these steps cannot be easily found in the Python documentation or other StackOverflow questions?

Just remember to break down a task in small, simple steps that together solve the problem. Understand the problem before you start writing code.

Grismar
  • 27,561
  • 4
  • 31
  • 54