List Number Limit Question

Asked 2 years ago, Updated 2 years ago, 11 views

N=int(input())

N_list=list(map(int,input().split()))

print(min(N_list),max(N_list))

I want to limit the number of N_list. For example, if the integer of N is 5, I want to try to fit up to five integers that can fit in the N_list..

if N_list[]<N:

I tried to do it in the way I thought about, such as the if statement, but I got an index error. Please help me with how to solve it.<

python

2022-09-20 22:25

2 Answers

>>> N = int(input())
5
>>> N_list = list(map(int, input().split()[:N]))
1 2 3 4 5 6 7 8 9
>>> N_list
[1, 2, 3, 4, 5]


2022-09-20 22:25

It is convenient to use deque for collections modules or inherit UserList.

from collections import deque, UserList
q = deque([], maxlen=5)
q.append(1)# Only up to 5 can be saved.

class MyList(UserList):
    def __init__(self, n):
        self.n = n
        self.data = [None] * n
    def append(self, n):
        raise Exception(f"exceed the limit.[{self.n}]")

my_list = MyList(5)
my_list
Out[45]: [None, None, None, None, None]

my_list.append(6)
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-47-c44ca8f1f6a6> in <module>
----> 1 my_list.append(6)

<ipython-input-43-b212c25e065a> in append(self, n)
      4         self.data = [None] * n
      5     def append(self, n):
----> 6         raise Exception(f"exceed the limit.[{self.n}]")
      7

Exception: exceed the limit.[5]


2022-09-20 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.