Python Code Question (File I/O problem, count = [0] * 10 I don't know what it means.)

Asked 1 years ago, Updated 1 years ago, 437 views

The problem is a random 30 count between 1 and 10.Create an in file using a random module. Then read this file and print out the number of occurrences of integers from 1 to 10 in the count.out file.

//count.in

import random

fout = open('count.in', 'w')

for _ in range(30):
    num = random.randint(1, 10)
    fout.write('{:3d} '.format(num))

fout.close()

//count.out

fin = open('count.in', 'r')
fout = open('count.out', 'w')

N = fin.readline().rstrip().split()

for idx, value in enumerate(N):
    N[idx] = int(N[idx])

count = [0] * 10
for value in N:
    count[value - 1] += 1

for idx, value in enumerate(count):
    fout.write('{:3d}: {:4d}\n'.format(idx + 1, value))

fin.close()
fout.close()

I made the chords while googling.

But my question is, I don't know what count = [0] * 10 means in count.out code. I would appreciate it if you could explain the process of calculating the count.out code as well

python

2023-05-30 07:40

1 Answers

Quite simply, we're going to initialize the counter to zero to count.

We need a "counter" for each of the 10 numbers from 1 to 10, so we're going to make it into an array of 10.

It's usually dangerous to make 10 in a Python array with *10 but because it's a basic numeric array, you can make 10 copies and write it like that.


2023-06-02 02:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.