I have a bit of code, that creates an initial array and reads data into the array until the array is full, and resizes the array
, increasing its size. Then it calculates the sum of all the integers and calculates the average of all the integers. (keep reading for my question on this)
import random
dataSize = random.randint(1,200)
# Create a random array with data
data = []
for i in range(dataSize):
randomNum = random.randint(1, 100);
data.insert(i, randomNum)
#--------------------------------------------------------------------
# Our solution:
constant_size = 100
size = 100
accumulator = 0
pos = 0
# Fill up our array with 0s, 100 items.
newArr = [0] * size
def insert(value):
global size, pos, accumulator
if pos >= size:
size += constant_size
newArr.insert(pos, value)
pos = pos + 1
accumulator = accumulator + value
# Main method to load data
for i in data:
insert(i)
print(newArr)
print('Total items position:', pos)
print('Total items size:', size)
print('Sum:', accumulator)
print('Average:', accumulator/pos)
#----------------------------------------------------------------------
What I would like to know is how to make the program read a sequence of integers from stdin and store them in the array. Essentially what this means is it reads a file I give it that contains integers, and then stores them in an array, takes those integers from the file to calculate the sum of the elements in the array, and calculate the average of the elements in the array.
So far what I've come up with is to replace the whole first part that defines what the data equals, and write data = sys.stdin.read() so that it can take a file and read it.