这里有一个解决方案。唯一的“诀窍”是使用模运算符将座位限制在0…5。此外,该公式还增加了6,以避免产生负座位数。在def main():
array = ["susan", "mary", "david", "tom", "richard", "mark"]
places_moved = int(input("How many places would you like to move?\n" + \
"(positive is to the right) "))
new_list = []
for seat in range(6):
new_list.append(array[(seat + 6 - places_moved) % 6])
print new_list
return 0
if __name__ == '__main__':
main()
(只是一个观察:在本例中,array不是一个数组,而是一个列表)
如果你可以在这个数组之后分配新的数组
^{pr2}$
而且,对于那些不想使用额外变量(甚至是模!):)def main():
array = ["susan", "mary", "david", "tom", "richard", "mark"]
places_moved = int(input("How many places would you like to move?\n" + \
"(positive is to the right) "))
if places_moved >= 0:
for move in range(places_moved):
array = [array[-1]] + array[0:-1]
else:
for move in range(abs(places_moved)):
array = array[1:] + [array[0]]
print array
return 0
if __name__ == '__main__':
main()