📜  计算元音周围字符的Python程序

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

计算元音周围字符的Python程序

给定一个字符串,任务是编写一个Python程序来计算那些具有元音作为其邻居的字符。

例子:

方法一:使用循环

在这种情况下,我们在使用循环检查元音的前一个和后继元素的同时增加计数器。

Python3
# initializing string
test_str = 'geeksforgeeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
res = 0
vow_list = ['a', 'e', 'i', 'o', 'u']
for idx in range(1, len(test_str) - 1):
  
    # checking for preceding and succeeding element to be vowel
    if test_str[idx] not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list):
        res += 1
  
# solving for 1st and last element
if test_str[0] not in vow_list and test_str[1] in vow_list:
    res += 1
  
if test_str[-1] not in vow_list and test_str[-2] in vow_list:
    res += 1
  
# printing result
print("Characters around vowels count : " + str(res))


Python3
# initializing string
test_str = 'geeksforgeeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
vow_list = ['a', 'e', 'i', 'o', 'u']
  
# sum() accumulates all vowels surround elements
res = sum([1 for idx in range(1, len(test_str) - 1) if test_str[idx]
           not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list)])
  
# solving for 1st and last element
if test_str[0] not in vow_list and test_str[1] in vow_list:
    res += 1
  
if test_str[-1] not in vow_list and test_str[-2] in vow_list:
    res += 1
  
# printing result
print("Characters around vowels count : " + str(res))


输出:

方法 2:使用sum()列表推导

在这里,我们使用 sum() 执行获取计数的任务,并使用列表理解完成迭代和过滤。

蟒蛇3

# initializing string
test_str = 'geeksforgeeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
vow_list = ['a', 'e', 'i', 'o', 'u']
  
# sum() accumulates all vowels surround elements
res = sum([1 for idx in range(1, len(test_str) - 1) if test_str[idx]
           not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list)])
  
# solving for 1st and last element
if test_str[0] not in vow_list and test_str[1] in vow_list:
    res += 1
  
if test_str[-1] not in vow_list and test_str[-2] in vow_list:
    res += 1
  
# printing result
print("Characters around vowels count : " + str(res))

输出: