Higher – SDD – Reading a file into an array

The code below allows us to read a file into an array then process the data. In this case the processing is just to see how many of each of the numbers (1-6) there were in the file.

def getData(array):
    txtFile=open("diceRolls.txt","r")
    for x in range(len(array)):
        array[x]=int(txtFile.readline().strip())
    
    txtFile.close()
    return array

def countOcc(array,target):
    total=0
    for number in array:
        if number==target:
            total=total+1
            
    return total

def main():
    dice=[0 for x in range(1000)]
    dice=getData(dice)
    for x in range(1,7):
        print("Number of",x,"'s=",countOcc(dice,x))
        
main()

The text file is the result of 1000 D6 rolls.
Can you modify the program to work out which number has the largest number of occurrences?

Leave a Reply

Your email address will not be published. Required fields are marked *