📜  计算反向字符串对的Python程序

📅  最后修改于: 2022-05-13 01:55:26.311000             🧑  作者: Mango

计算反向字符串对的Python程序

给定字符串列表,编写一个Python程序来计算反向字符串对。

例子:

方法 #1:使用reversed() + 循环

在此,我们使用 reversed() 和条件语句执行将字符串与其反向版本进行比较的任务。在此,循环用于与每个字符串进行比较以进行配对的任务。

Python3
# Python3 code to demonstrate working of
# Reversed Pairs in Strings List
# Using reversed() + loop
  
# initializing Matrix
test_list = ["geeks", "best", "tseb", "for", "skeeg"]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = 0
for idx in range(0, len(test_list)):
  
    # nested loop to check with each element with possible reverse counterpart
    for idxn in range(idx, len(test_list)):
        if test_list[idxn] == str(''.join(list(reversed(test_list[idx])))):
            res += 1
  
# printing result
print("Reversed Pairs : " + str(res))


Python3
# Python3 code to demonstrate working of
# Reversed Pairs in Strings List
# Using list comprehension + sum()
  
# initializing Matrix
test_list = ["geeks", "best", "tseb", "for", "skeeg"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# list comprehension for nested loop
# sum increments counts
res = sum([1 for idx in range(0, len(test_list)) for idxn in range(idx, len(
    test_list)) if test_list[idxn] == str(''.join(list(reversed(test_list[idx]))))])
  
# printing result
print("Reversed Pairs : " + str(res))


输出:

方法 #2:使用列表理解 + sum()

在这种情况下,列表理解处理嵌套循环,而 sum() 处理计数对的增量计数器的一部分。

蟒蛇3

# Python3 code to demonstrate working of
# Reversed Pairs in Strings List
# Using list comprehension + sum()
  
# initializing Matrix
test_list = ["geeks", "best", "tseb", "for", "skeeg"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# list comprehension for nested loop
# sum increments counts
res = sum([1 for idx in range(0, len(test_list)) for idxn in range(idx, len(
    test_list)) if test_list[idxn] == str(''.join(list(reversed(test_list[idx]))))])
  
# printing result
print("Reversed Pairs : " + str(res))

输出: