Python 中的索引映射密码


索引映射密码是通过传递整数字符串来获取特定字符串来定义的。在 Python 中,我们有一些内置函数,例如 str()、len()、join() 和 int(),将用于根据索引映射密码解决问题。

让我们举个例子来理解这一点

给定的字符串为:

my_str = “Hyderabad”

给定的索引为:

idx = 101456

最终结果为 yHyrab

语法

以下语法在示例中使用:

str()

这是 Python 中的一个内置函数,它接受任何值将其转换为字符串。

len()

这是 Python 中的一个内置方法,它返回对象的长度。

join()

join() 是 Python 中的一个内置函数,用于连接可迭代元素。它还按顺序组合每个元素。

int()

内置函数 int 将数字或字符串转换为整数形式。

使用 for 循环

程序使用 for 循环迭代原始字符串的长度,并将索引值初始化为打印特定字符串。

示例

在以下示例中,我们将从定义一个名为 idx_map_cypher() 的函数开始程序,该函数接受两个参数:r_str 和 index。这两个参数在函数调用期间接收值,它被称为递归函数。变量 result 通过一个空字符串初始化值,该字符串将根据条件和给定的索引值存储新的特定字符串。接下来,使用 for 循环,其中变量 i 迭代 str(index)。然后应用 if 语句来设置比较 idxr_str 的条件,借助于 < 运算符,并使用 += 运算符,它将形成新字符串并返回结果。现在开始在变量 my_str 中创建原始字符串,并将值设置为存储在变量 idx 中。然后使用函数调用并将其存储在变量 res 中。最后,我们借助一些变量(例如:my_str、index 和 res)打印格式化输出。

def idx_map_cypher(r_str, index):
    result = ""
    for i in str(index):
        index = int(i)
        if index < len(r_str):
            result += r_str[index]
    return result
# Create the string
my_str = "Tutorialspoint"
# Set the index value
index = 6875
res = idx_map_cypher(my_str, index)
print("The original string:", my_str, "\nThe index value:", index, "\nString printing based on the index:", res)

输出

The original string: Tutorialspoint
The index value: 6875 
String printing based on the index: asli

使用列表推导式

该程序使用列表推导式,其中将使用一个名为 join 的方法来根据给定的索引值组合特定的字符串,这有助于构建索引映射密码。

示例

在以下示例中,从在变量 my_str 中创建输入字符串并显示变量开始程序。接下来,初始化名为 index 的变量以存储随机整数的值,该值根据索引值指定原始字符串。现在它将创建 列表推导式,其中使用索引通过 for 循环中的值对 my_str 中的字符进行索引,并将这些过程存储在变量 res 中。继续使用变量 indexstr(res) 显示结果。

# Create the string
my_str = "BROWSER"
print("Original string: " + my_str)
# Create the index
index = "4154"
# list comprehension
res = ''.join([my_str[int(i)] for i in index])
# Display the result
print("The index value:", index, "\nstring is", str(res))

输出

Original string: BROWSER
The index value: 4154 
string is SRES

使用反向索引映射密码

该程序使用反向索引,这意味着如果变量 index 指定任何整数值,它将以反向顺序返回结果。例如:

输入

my_str = “PLOT”
index = 12

输出

OL

解释

输入字符串初始化在变量 my_str 中,而 index 变量将值设置为 12。为了反转索引,它将使用一些条件并且可以以反向形式打印索引字符串。

示例

在以下示例中,我们将从使用一个名为 rev_index_map_cypher 的递归函数开始程序,该函数接受两个参数:r_str 和 index,它们将在函数调用期间获取值。然后将空字符串存储在变量 result 中,该变量将根据反向索引存储特定字符串。现在使用 for 循环迭代字符串索引值及其切片。继续在变量 my_str 中创建原始字符串,并初始化名为 index 的变量以设置整数值。然后使用函数调用并将其存储在变量 res 中并打印结果。

def rev_index_map_cypher(r_str, index):
    result = ""
    for i in str(index)[::-1]:
        idx = int(i)
        if idx < len(r_str):
            result += r_str[idx]
    return result
# Create the string 
my_str = "INTERSTELLAR"
# Set the index value
index = 7455
res = rev_index_map_cypher(my_str, index)
print("The original string:", my_str, "\nThe index value:", index, "\nString printing based on index:", res)

输出

The original string: INTERSTELLAR 
The index value: 7455 
String printing based on the index: SSRE

结论

我们讨论了解决问题陈述的各种方法。索引映射密码通常用于密码学和计算机科学领域。术语“密码”将值定义为索引以查找特定字符串。

更新于: 2023年8月14日

262 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.