how to read array elements from user in python - python

I am trying to read array elements as
4 #no. of elements to be read in array
1 2 3 4
what i have tried by referring other answers
def main():
n=int(input("how many number you want to enter:"))
l=[]
for i in range(n):
l.append(int(input()))
this works fine if i give input as
4 #no. of elements to be read
1
2
3
4
but if i try to give like
4 #no. of element to be read
1 2 3 4
I get error as:
ValueError: invalid literal for int() with base 10: '1 2 3 4'
Please help me with this

Since there's no input delimiters in Python, you should use split and split the input that you've received from the user:
lst = your_input.split()

Your first approach is OK, for the second way use this:
n=int(input("how many number you want to enter:"))
l=map(int, input().split())[:n] # l is now a list of at most n integers
This will map the function int on the split parts (what split gives) of the user input (which are 1, 2, 3 and 4 in your example.
It also uses slicing (the [:n] after map) to slice in case the user put more integers in.

The input() function returns a string that the user enters. The int() function expects to convert a number as a string to the corresponding number value. So int('3') will return 3. But when you type in a string like 1 2 3 4 the function int() does not know how to convert that.
You can either follow your first example:
n = int(input('How many do you want to read?'))
alist = []
for i in range(n):
x = int(input('-->'))
alist.append(x)
The above requires you to only enter a number at a time.
Another way of doing it is just to split the string.
x = input('Enter a bunch of numbers separated by a space:')
alist = [int(i) for i in x.split()]
The split() method returns a list of numbers as strings excluding the spaces

n = input("how many number you want to enter :")
l=readerinput.split(" ")

Related

Сyclic shift of all array elements

A list of integers is entered from the keyboard. Write a program that will cycle through all the elements of an array one position to the right (the last element is moved to the beginning of the list).
Input data
The first line contains the number of elements in the list. After that, the list elements themselves are entered - one per line.
Output
Output the list resulting from the shift.
Example
Input data
6
8
12
3
4
5
1
Output
1 8 12 3 4 5
I don't understand what's wrong with this code. It works, but the teacher said that the task was not solved correctly.
h = []
k = int(input())
for i in range(k):
o = int(input())
h.append(o)
h = h[len(h) - 1:] + h[:len(h)-1]
print(h)
I think there is a typo in the example, the 1 is missing. Did you mean:
Input 6 8 12 3 4 5 1
Output 1 6 8 12 3 4 5
EDIT: There is no typo here, the 6 represents how many numbers the user will input, and they are typed line by line. So the following doesn't make sense :)
Did you actually try to run your code with the example? Because it doesn't work :)
First, line 2:
You cannot convert a string like "6 8 12 3 4 5 1" directly to an integer because the int() function doesn't know how to deal with the spaces.
Then, line 3:
for i in range(k) doesn't make sense for python, because k is a list.
The range function takes (at least) an integer and returns a "list" with all the numbers between 0 and this number (excluded). With a quick google search you can find some examples like this one.
The correct way to loop over a string, by character would be:
s = "hello"
for letter in s:
print(s)
or
s = "hello"
for i in range(len(s)):
print(s[i])
Both will output:
h
e
l
l
o
Finally, line 4:
You try to convert the character (I assume) to an integer.
But what if the character is a space? (it will crash)
And what about a number like 12? You will then add 1 and 2 but not 12 to your final list.
To summarize, you need a function that split the string on spaces. The split function does exactly this! It takes a character and splits a string regarding this character, returning a list of substrings.
Again, you can google it to find examples
Here is a solution for you problem, I tried to comment it to make it easier to understand:
inp = input("Please enter several numbers: ") # read the numbers
inp = inp.split(" ") # split the input on spaces
h = []
for element in inp:
h.append(int(element)) # Convert each element to int
# rotate the list
# you don't need the len(h) here, python handles negative indices
rot = h[-1:] + h[:-1]
print(rot)

loop 'for' for string of numbers

Note: you have input where have 5 numbers:
Sample Input: 12 21 15 19 8
Sample Output: 12 8
x = input()
for i in x:
print(i)
need to use input() in program but loop takes the number 12 as 1 and 2. how to avoid this
input: 12
output: 1 2
In case you also want to turn the numbers into integers to use in your code, you can do:
x = list(map(int, input().split()))
which just casts each of the numeric strings created by split() to int types and puts them back into a list.
Calling the split() method separates a sentence into a list of words.
x = input().split()
for i in x:
print(i)
Python String split() Method

Generate list of 5 non-repeating integers

I'm new to Python and I am trying to generate a list of 4 random numbers with integers between 1 and 9. The list must contain no repeating integers.
The issue I am having is that the program doesn't output exactly 4 numbers everytime. Sometimes it generates 3 numbers or 2 numbers and I can't figure out how to fix it.
My code:
import random
lst = []
for i in range(5):
r = random.randint(1,9)
if r not in lst: lst.append(r)
print(lst)
Is there a way to do it without the random.sample? This code is part of a larger assignment for school and my teacher doesn't want us using the random.sample or random.shuffle functions.
Your code generates 5 random numbers, but they are not necessarily unique. If a 2 is generated and you already have 2 in list you don't append it, while you should really be generating an alternative digit that hasn't been used yet.
You could use a while loop to test if you already have enough numbers:
result = [] # best not to use list as a variable name!
while len(result) < 5:
digit = random.randint(1, 9)
if digit not in result:
result.append(digit)
but that's all more work than really needed, and could in theory take forever (as millions of repeats of the same 4 initial numbers is still considered random). The standard library has a better method for just this task.
Instead, you can use random.sample() to take 5 unique numbers from a range() object:
result = random.sample(range(1, 10), 5)
This is guaranteed to produce 5 values taken from the range, without duplicate digits, and it does so in 5 steps.
Use random.sample:
import random
random.sample(range(1, 10), 4)
This generates a list of four random values between 1 to 9 with no duplicates.
Your issue is, you're iterating 5 times, with a random range of 1-9. That means you have somewhere in the neighborhood of a 50/50 chance of getting a repeat integer, which your conditional prevents from being appended to your list.
This will serve you better:
def newRunLst():
lst = []
while len(lst) < 4:
r = random.randint(1,9)
if r not in lst: lst.append(r)
print lst
if random list needed is not too small (compared to the total list) then can
generate an indexed DataFrame of random numbers
sort it and
select from the top ... like
(pd.DataFrame([(i,np.random.rand()) for i in range(10)]).sort_values(by=1))[0][:5].sort_index()

How can take input of n number of lists in python?

How can we take input of n number of lists in python
for example
2
1 2 3
4 5 6 7
here 2 is specifying number of lists that are going to input
1 2 3 is one list
4 5 6 7 is second list
another example
3
1 2 3
4 5 6 8
2 3 5 7
3 indicates 3 lists are going to input
1 2 3 is list one
4 5 6 8 is list two
2 3 5 7 id list three
i have done this code
n=input()
for i in range(n):
b=map(int,raw_input().split())
i am struck with this how can i take input for n number of lists i able to take only one list into one variable i want take to different different variables
i want take to different different variables
You can not assign the input to "different" variables in the loop, particularly if you do not know how large n will be. Instead, you should append the different values of b to a list of lists, e.g. bs.
n = input()
bs = []
for i in range(n):
bs.append(map(int, raw_input().split()))
Or use a list comprehension:
bs = [map(int, raw_input().split()) for _ in range(n)]
do you want to read from file or cli?
If you read from file, you can iterate over its content line by line and work only in the specific lines.
The lines input you can split to get the single numbers into a list.
nums=[]
with open(infile.txt) as f:
n=0
for i, line in enumerate(f):
if i==1:
n == 1
elif i <= n
nums[i] = line.split()
There are a few things to fix:
You need to convert your input 'n' to an integer.
Your 'b' gets overwritten with every iteration of the loop.
Why are you using 'raw_input' in the second case? 'input' will give you a sanitized version of the input which is preferable in this case (so that a malicious user cannot inject code).
Keep it simple and use lists instead of a map.
n = int(input())
rows = [] # will contain the input as a list of integers
for i in range(n):
row_string = input()
row = [int(num) for num in row_string.split()]
rows.append(row)

How to input n values in one line in python Provided n is decided by the user

Suppose the user decides he wants to input n integers.
How do we write code to accept n integers in the same line given n is decided by the user?
I know we can use a, b = map(int,input().split()) but in this case I know 2 integers have to be inputted.
You could just use an array:
numbers = map(int, input().split(' ')) #=> suppose input is '12 43 7'
print(list(numbers)) #=> [12, 43, 7]
You can use a list comprehension to create a list of provided numbers:
numbers = [int(num) for num in input().split()]
How it works: the input string is split on whitespace, then the list comprehension creates a list of numbers by applying int() to each item.

Categories

Resources