Issue
I want to be able to write a size for a input and after that enter each number seperated by space which is less or equal than the size.
Like this:
First input (length): 3
inputs: 1 2 3
This should also be converted as an integer and stored in a list
I have tried this:
import sys
inputs = sys.stdin.readline()
print(len(inputs))
mynumbers = inputs.strip().split(' ')
newlist = [int(x) for x in mynumbers]
print(newlist)
#print(input.rstrip(''))
Solution
Without using of stdin
A first possible answer (without use of stdin
but using input
) could be:
size = int(input("First input (length): "))
print(size)
input_value = input("inputs (length): ")
mynumbers = input_value.strip().split(' ')
newlist = [int(x) for x in mynumbers[:size]]
print(newlist)
Using stdin
print("First input (length): ")
inputs = sys.stdin.readline()
print("inputs: ")
input_value = sys.stdin.readline()
mynumbers = input_value.strip().split(' ')
# in new_list are inserted elements up to inputs value
newlist = [int(x) for x in mynumbers[0:(int)(inputs)]]
print(newlist)
In this case the output is:
First input (length):
3
inputs:
1 2 3 4
[1, 2, 3]
As you can see in the example I have selected 3 as length of the list, but I have inserted 4 elements.
In the list newlist
there are only 3 elements because length==3.
Answered By - frankfalse
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.