loop 'for' for string of numbers - python

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

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)

How to count how many maximum numbers there are among inputted in one line values?

I've got 4 integer inputs in one line separated by a space, and I have to output the largest of them and how many largest integers there are, also in one line and separated by a space. The first request can be easily done with a max function, however I can't figure out how to do the second one. Example:
Input: 6 4 -3 6
Output: 6 2
And this is code I've written so far:
a, b, c, d = map(int, input().split())
max = max(a,b,c,d)
print(max, )
How can I count the amount of largest integers?
Here is a way to do it:
x = "6 4 -3 6"
l = list(map(int, x.split()))
print(max(l), l.count(max(l)))
Where x is the string that you got from the call to input().

Taking two inputs as initial and final value and printing range

This is my code:
a,b=input().split()
for x in range(a,b):
print(list(x))
Why is this not working?
It says can't interpret str as an int.
And when I put it under int(), it says int() argument must be a string.
I want this:
Input:
2 6
Output:
3
4
5
6
This does exactly what you expect:
a,b=input().split()
for x in range(int(a)+1,int(b)+1):
print(x)
input() returns a string, and split() returns a list of strings. You have to convert them to integers before feeding them to range. Also, in print(x) x is already a number and there is no reason to convert it into a list (and it would not work, either).
Simply replace print(list(x)) with print(x) . I don't see any reason to use list() . You can also use range(a,b+1) instead of range(a,b) if you want the last number printed to be the same as b.
By default, input() accepts values as string and split() returns a list of strings. You need to convert a and b to int after input. Also, you need to get rid of list(x) and just print(x) since int in Python is not iterable.
The correct code is:
a, b = map(int, input().split())
for x in range(a + 1, b + 1):
print(x)
OR
a, b = [int(i) for i in input().split()]
for x in range(a + 1, b + 1):
print(x)
In both cases, for input 2 6, the output is
3
4
5
6

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 read array elements from user in 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(" ")

Categories

Resources