python判断连续相同数值
以下是一个判断连续相同数值的Python代码示例:
def check_consecutive_values(seq):
count = 1
for i in range(1, len(seq)):
if seq[i-1] == seq[i]:
count += 1
if count >= 3:
return True
else:
count = 1
return False
numbers = [1, 2, 3, 3, 3, 4, 5]
if check_consecutive_values(numbers):
print("There are consecutive values in the list.")
else:
print("There are no consecutive values in the list.")
string = "pidancode.com"
if check_consecutive_values(string):
print("There are consecutive characters in the string.")
else:
print("There are no consecutive characters in the string.")
在这个示例中,check_consecutive_values函数接受一个序列参数,并返回一个布尔值,指示序列中是否存在三个或更多连续相等的值。它使用一个count变量来追踪连续相等值的数量,并在达到三个或更多时返回True。如果序列中没有三个或更多连续相等的值,则返回False。
此代码示例还展示了如何使用该函数来检查数字列表和字符串中是否存在连续值。在数字列表中,有三个3,所以函数返回True。在字符串“pidancode.com”中,没有三个或更多连续的相同字符,因此该函数返回False。
相关文章