Python计算有序元音字符串数量的程序
假设有一个数字n,我们需要找到大小为n的元音字符串(a,e,i,o,u)的数量,并且它们是按字典顺序排序的。我们可以说,当对于所有有效的索引i,s[i]与字母表中的s[i+1]相同或在其之前时,字符串s是按字典顺序排序的。
因此,如果输入为n = 2,则输出将为15,因为有许多字符串,例如[“aa”, “ae”, “ai”, “ao”, “au”, “ee”, “ei”, “eo”, “eu”, “ii”, “io”, “iu”, “oo”, “ou”, “uu”]。
要解决此问题,我们将按照以下步骤进行 –
- 如果n与1相同,则
- 返回5
- count:大小为6的数组,最初填充为1
- 对于i在3到n之间的范围,执行以下操作 –
- count [1]: = count [1] + count [2] + count [3] + count [4] + count [5]
- count [2]: = count [2] + count [3] + count [4] + count [5]
- count [3]: = count [3] + count [4] + count [5]
- count [4]: = count [4] + count [5]
- total: = 0
- 对于i在1到5之间的范围,执行以下操作 –
- total: = total + i * count [i]
- 返回总计
示例
让我们看一下以下实现以更好地理解 –
def solve(n):
if n==1:
return 5
count = [1 for i in range(6)]
for i in range(3,n+1):
count[1] = count[1]+count[2]+count[3]+count[4]+count[5]
count[2] = count[2]+count[3]+count[4]+count[5]
count[3] = count[3]+count[4]+count[5]
count[4] = count[4]+count[5]
total = 0
for i in range(1,6):
total += i*count[i]
return total
n = 2
print(solve(n))
输入
2
输出
15