I'm obtaining input values in a list using the following statement:
ar = map(int, raw_input().split())
However, I would want to limit the number of inputs a user can give at a time. For instance, if the limit is specified by a number n, the array should only capture the first n values entered during the program.
e.g: if n = 6, Input:
1 2 3 4 5 6 7 8 9 10
On performing 'print ar', it should display the following without any error messages:
[1, 2, 3, 4, 5, 6]
Limiting input number between minimum and maximum values range in Python. Raw. limit-number.py. def limit ( num, minimum=1, maximum=255 ): """Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""". return max ( min ( num, maximum ), minimum)
"""Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.""" Sign up for free to join this conversation on GitHub .
Write a Python Program to Find Minimum and Maximum Value in an Array. The numpy module has min and max functions to return the minimum and maximum values in a numpy array. We use these numpy min and max functions to return the minimum and maximum values in the number and string array.
Example 1: Get a list of numbers as input from a user and calculate the sum of it Note: Python input () function always converts the user input into a string then returns it to the calling program. With those in mind, we converted each element into a number using an int () function.
If you want to ignore the rest of the input, then you can use slicing to take only the first n
input. Example -
n = 6
ar = map(int, raw_input().split(None, n)[:n])
We are also using the maxsplit
option for str.split
so that it only splits 6 times , and then takes the first 6 elements and converts them to int.
This is for a bit more performance. We can also do the simple - ar = map(int, raw_input().split())[:n]
but it would be less performant than the above solution.
Demo -
>>> n = 6
>>> ar = map(int, raw_input().split(None, n)[:n])
1 2 3 4 5 6 7 8 9 0 1 2 3 4 6
>>> print ar
[1, 2, 3, 4, 5, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With