【发布时间】:2021-06-04 06:16:59
【问题描述】:
在这个程序中,用户必须输入序列的长度,然后在以下每个序列中输入一个单词。 python程序需要输出以相同首字母开头的相邻单词对的数量。在您输入诸如此类的输入之前,我下面的代码可以很好地执行此操作
示例 1: 输入:
Length of sequence: 2
1st word: blue
2nd word: black
预期输出:
Pairs of adjacent words: 1
我的代码输出:
pairs of adjacent words: 0
示例 2: 输入:
Length of sequence: 3
1st word: what
2nd word: who
3rd word: when
预期输出:
Pairs of adjacent words: 2
我的代码输出:
pairs of adjacent words: 0
这是我的代码:
n= int(input("Enter the length of the sequence:\n"))
current_letter = 'a'
count = 0
pairs = 0
for i in range (0,n):
word = input('Enter word '+ str(i+1)+':\n')
first_letter = word[:1]
if current_letter == first_letter:
count = count + 1
else:
if count > 0:
pairs = pairs + 1
count = 0
current_letter = first_letter
print('Number of pairs of adjacent words with same first letter: '+ str(pairs))
正确输出示例:
Enter the length of the sequence:5
Enter word 1: how
Enter word 2: here
Enter word 3: who
Enter word 4: when
Enter word 5: you
Number of pairs of adjacent words with the same first letter: 2
【问题讨论】:
标签: python