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)
Related
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().
as you see i am stuck in the below python code to find the desired output. I got the the output but it is not 2(Which is right output.)
Anyone got some ropes. he want to make each of the rope as small as possible. The sequence of ropes has got some special property. Each rope has a unique length. The ropes are numbered 1 to N.
We can choose M sized subsegment of the sequence and cut all the ropes present in the subsegment to the length of the minimum length rope present in that subsegment.
The first line of input contains a single integer M denoting the size of the subarray we can pick in any operation. the next line contains a single integer N denoting the number of ropes. Then N lines follow where each line contains a single integer denoting the length of the rope
import collections
>>> class Solution:
'''Defining function for min operation'''
def minOperations(self, sizeOfSubarray, lengthsOfRopes):
#write code here
///writing code
def main():
R = input()
R = int(R)
k = input()
k = int(k)
res = []
'''Using loop for input'''
for i in range(k):
res.append(int(input().strip()))
ret = Solution().minOperations(R,res)
print(ret)
if __name__=='__main__':
main()
'''//input
4
5
2
1
3
4
5
//output
2
This is a repl.it problem I have been working on for the past 6 hours and as far as I can tell my code works properly from the output point of view. for example if I input 56789 my program outputs 5 7 9. Repl.it tests fail every time and tell me my output is 56789 when theirs is 5 7 9. If I define the input as a specified list instead of a user input then repl.it passes the first test and fails the second....because it indicates that the program fails with a new set of numbers. So I know stack overflow is not repl.it but not finding any help there. note...I am sure my code is clunky and inefficient but I am still learning how to walk here
def picky():
position = 0
a = input("") #input asking for a number
b = list(a) #converts my input into a list
c = [] #list for storing even index values
d = [] #list for converting c to string
while position <= len(b):
if position % 2 == 0:
c += b[position]
position += 1
for x in c:
d += str(x)
preOutput = str(d).strip('[]').replace('\'','').replace(',','')
# removes brackets, commas, and quotes from output.
print(preOutput)
picky()
using 3.6.4
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)
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(" ")