【发布时间】:2019-06-24 14:30:46
【问题描述】:
我正在尝试解决这个问题:
一个列表初始化为
["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"],然后进行一系列操作。在每个操作中,列表的第一个元素被移动到列表的末尾并复制。例如,在第一个操作中,列表变为["Leonard", "Penny", "Rajesh", "Howard", "Sheldon", "Sheldon"]("Sheldon"被移动和复制);在第二次操作中,它变为["Penny", "Rajesh", "Howard", "Sheldon", "Sheldon", "Leonard", "Leonard"](“Leonard”被移动和复制);等等。给定一个正整数n,找出在第n次操作中被移动和复制的字符串。 [转述自https://codeforces.com/problemset/problem/82/A]
我已经写了一个可行的解决方案,但是当 n 很大时它太慢了:
l = ['Sheldon','Leonard','Penny','Rajesh','Howard']
n = int(input()) # taking input from user to print the name of the person
# standing at that position
for i in range(n):
t = l.pop(0)
l.append(t)
l.append(t)
#debug
# print(l)
print(t)
我怎样才能更快地做到这一点?
【问题讨论】:
-
您可以在不实际生成列表的情况下找出答案。将每个名称加倍一次将使列表的长度加倍。您可以计算出需要将列表翻倍的次数,然后推断此时列表的结构。
-
@khelwood 你能详细说明一下吗?
-
@Aman 你在找人帮你解决这个问题吗? khelwood 给了你一个巨大的提示,如果你想自己解决它,它应该会对你有所帮助。
-
@Code-Apprentice 从那时起我一直在关注 khelwoods 的提示并尝试解决。我只是一个初学者,这就是为什么我需要时间
-
@Aman 即使不是初学者,解决问题也需要时间
标签: python algorithm math implementation