Сyclic shift of all array elements

Question:

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)
Asked By: obibe

||

Answers:

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)
Answered By: atxr
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.