Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. """
  2. Given a list of N numbers, write a function to shift the numbers circularly by some integer k (where k < N).
  3. The function should take a list and k as a arguments and return the shifted list.
  4. """
  5. RIGHT = 1
  6. LEFT = 0
  7.  
  8.  
  9. def main():
  10. print("THe shifter function. Shits all elements in a array given a shift point and a direction")
  11. print("Populate the array!")
  12. print()
  13.  
  14. numbers_list = []
  15. while True:
  16. number = int(input("Give a number: "))
  17. numbers_list.append(number)
  18. another = input("Another? ['y'/'n']: ")
  19. if another.lower() == 'n':
  20. break
  21.  
  22. print("The array is: ", numbers_list)
  23.  
  24. direction = input("Give the direction to switch the numbers: ")
  25. if direction.lower() == 'right':
  26. direction = RIGHT
  27. elif direction.lower() == 'left':
  28. direction = LEFT
  29.  
  30. shifter_int = int(input("The shifter element: "))
  31.  
  32. print(shifter(numbers_list, shifter_int, direction))
  33.  
  34.  
  35. def shifter(numbers, shift_integer, shift_direction):
  36. """
  37.  
  38. :param numbers: it is the list of numbers generated by the user in the main function
  39. :param shift_integer: the integer to shift from - the index to be hold on place
  40. :param shift_direction: the direction to shift the number
  41. :return: the shifter list
  42. """
  43.  
  44. # the complicate way - shifting to the right without list slicing
  45. # using a while loop and a container to hold the data - remove it and then append it at the end of the list
  46. # one could use slicing - easies way
  47. if shift_direction:
  48. while shift_integer >= 0:
  49. holder = numbers[shift_integer-1]
  50. numbers.remove(holder)
  51. numbers.append(holder)
  52. shift_integer -= 1
  53.  
  54. return numbers
  55.  
  56. # the easiest way - using the integer as a cut element and split the initial list accordingly
  57. else:
  58. numbers = numbers[shift_integer:][::-1] + numbers[:shift_integer]
  59. return numbers
  60.  
  61.  
  62. if __name__ == '__main__':
  63. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement