Python 根据用户输入旋转给定列表中的索引,而旋转顺序是从另一个列表中的索引派生出来的
此问题来自ACM ICPC 2014年年中问题集。具体来说,这是问题G,反向 我必须编写一个程序,它接受用户输入的字符串,将其反转,然后根据包含大写字母从a到Z、下划线和句点的列表将其旋转。到目前为止,我已经能够做的一切,但旋转它正确。这是我迄今为止的代码:Python 根据用户输入旋转给定列表中的索引,而旋转顺序是从另一个列表中的索引派生出来的,python,Python,此问题来自ACM ICPC 2014年年中问题集。具体来说,这是问题G,反向 我必须编写一个程序,它接受用户输入的字符串,将其反转,然后根据包含大写字母从a到Z、下划线和句点的列表将其旋转。到目前为止,我已经能够做的一切,但旋转它正确。这是我迄今为止的代码: #character list which is referenced during the rotation rotationList = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"
#character list which is referenced during the rotation
rotationList = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "_", "."]
reverseRotList = [] #list which stores the completed rotation, later to be joined into a string
def reverse(string) : #reverses the string and stores each character in indexes within a list
string = string[::-1]
string = list(string)
return string
string = input("What is the string? ").upper()
print(reverse(string)) #to show string was reversed and converted into a list correctly
rotAmount = int(input("Amount to be rotated? ")) #user decides how much rotation there will be
for i in string:
根据旋转列表旋转时,如何根据用户输入旋转字符串列表?构建旋转列表
方法一
假设您有一系列数字,例如:
[0, 1, 2, 3, 4, 5, 6, 7]
您要将它们向左旋转3
,如下所示:
[3, 4, 5, 6, 7, 0, 1, 2]
请注意,前三个数字从原始数字移动了+3
,而其余两个数字从原始数字移动了-5
。你注意到这里有一种模式吗
需要注意的关键是-5
只是+3-8
,其中8
是列表的长度。换句话说,数字经过加法移位,然后进行模运算:
现在,您拥有的不是一个数字列表,而是一个字符列表,但区别很肤浅:对字符串的索引应用相同的转换会产生相同的旋转效果:
new_list[old_i] = old_list[new_i]
然后,只需对列表中的每个元素重复此操作
(关于shift
的符号有一点微妙之处;在这里,我使用的惯例是,正移位相当于将值向右旋转。)
方法二
另一种方法是将列表旋转视为两步操作:
左半部分
和右半部分
右半+左半
break_index = shift % length
需要模,因为按长度的整数倍旋转对列表没有实际影响
翻译字符
要使用旋转列表翻译字符(或字符串),您需要找到字符在原始顺序中的位置:
index = old_list.index(character)
然后在旋转列表中找到相应的字符:
translated_character = new_list[index]
优化
构建包含旋转字母表的新列表
,对于执行翻译实际上是不必要的。通过执行一些代数变换,可以看到可以直接从原始字母表计算翻译后的字符:
translated_character = old_list[(index - shift) % length]
此外,使用index
方法效率低下:最好构造一个字典来加快查找速度。但是如何根据主列表(例如:[“R”、“U”、“O”])旋转用户输入的列表,旋转1。根据主列表,它应该变成[“Q”、“V”、“P”]。添加了关于翻译的解释。嗯
translated_character = old_list[(index - shift) % length]