Search code examples
pythoncpython-3.xcode-translation

Is there a way of processing list of number integers entered via terminal without saving them into list?


I am trying to write a similar code in Python, but I am new to it.

int counts[] = { 0, 0, 0, 0, 0 };
for (int i = 0; i < groups; i++) {
    int groups_size;
    scanf(" %d", &groups_size);

    counts[groups_size] += 1;
}

Please note that it does not save all the numbers into memory regardless of how large group_size is.

This is how I tried to do it in Python:

for group in range(groups):
    num = int(input().strip())
    counts[num] += 1

This does not work. When I enter 1 2 3 4 5 into terminal, I get ValueError: invalid literal for int() with base 10: '1 2 3 4 5'.

Is there a way of doing this in Python without using storing the entire string into the memory?


Solution

  • In python, it will not automatically take one number and then loop for the other. You input() command will read the whole line at once. So, what you can do is read the whole line in a string and then split it into a list as follows -

    str = input()
    num = list(map(int,str.split()))
    

    Now you have all the input given by user stored in the num variable. You can just iterate over it and complete your process as follows -

    counts = [0]*5       #assuming you want it to be of size 5 as in your question
    for inp in num :
        counts[inp] = counts[inp] + 1
    

    Hope this helps!