0

My issue is as follows: I want to create a program which accepts strings divided from each other by one space. Then the program should prompt a number, which is going to be the amount of words it's going to shift forward. I also want to use lists for words as well as for the output, because of practice.

Input: one two three four five six seven 3

Output: ['four', 'five', 'six', 'seven', 'one', 'two', 'three']

This is what I've came up with. For the input I've used the same input as above. However, when I try increasing a prompt number by N, the amount of appended strings to list cuts by N. Same happens when I decrease the prompt number by N (the amount of appended strings increases by N). What can be an issue here?

l_words = list(input().split())
shift = int(input()) + 1 #shifting strings' number
l = [l_words[shift - 1]]
for k in range(len(l_words)):
    if (shift+k) < len(l_words):
      l.append(l_words[shift+k])
    else:
      if (k-shift)>=0:
        l.append(l_words[k-shift])
print(l)
10 Rep
  • 2,217
  • 7
  • 19
  • 33
JoshJohnson
  • 181
  • 3
  • 18
  • Does this answer your question? [Efficient way to rotate a list in python](https://stackoverflow.com/questions/2150108/efficient-way-to-rotate-a-list-in-python) – azro Oct 12 '20 at 19:04
  • Or https://stackoverflow.com/questions/9457832/python-list-rotation – azro Oct 12 '20 at 19:04

1 Answers1

2

You can use slicing by just joining the later sliced part to the initial sliced part given the rotation number.

inp = input().split()
shift_by = int(inp[-1])
li = inp[:-1]

print(li[shift_by:] + li[:shift_by]) # ['four', 'five', 'six', 'seven', 'one', 'two', 'three']
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36