لتحقيق هذا، يمكنك استخدام حل بسيط يستخدم حلقة for
لتفقد العناصر في القائمة وفحص كل مجموعة من ثلاثة عناصر للتحقق مما إذا كانت مساوية للقيمة 1 أم لا. إليك كيف يمكن تنفيذ ذلك:
مقالات ذات صلة
pythona = [1,1,1,0,0,1,0,1,1,0,1,1,1]
# Initialize a counter for the number of occurrences
count = 0
# Iterate through the list, but only up to the third-to-last element
for i in range(len(a) - 2):
# Check if the current element and the next two elements are all equal to 1
if a[i] == a[i + 1] == a[i + 2] == 1:
# If they are, increment the counter
count += 1
# Print the number of occurrences found
print("Number of groups of three identical numbers:", count)
هذا الحل يتحقق من كل مجموعة متتالية من ثلاثة أعداد متساوية للقيمة 1 في القائمة ويزيد من العداد إذا تم العثور على مثل هذه المجموعات.
المزيد من المعلومات
بالطبع! يمكن تحسين الكود لجعله أكثر فعالية وفعالية. يمكننا استخدام تقنية تسمى “الانزلاق” (sliding) حيث نقوم بالتحقق من ثلاثة عناصر في كل تحرك بدلاً من فحص كل مجموعة ممكنة من ثلاثة عناصر. هذا يساعد على تقليل عدد العمليات ويجعل الكود أكثر فعالية. إليك كيف يمكن تحقيق ذلك:
pythona = [1,1,1,0,0,1,0,1,1,0,1,1,1]
# Initialize a counter for the number of occurrences
count = 0
# Iterate through the list, but only up to the third-to-last element
for i in range(len(a) - 2):
# Check if the current element and the next two elements are all equal to 1
if all(a[i+j] == 1 for j in range(3)):
# If they are, increment the counter
count += 1
# Print the number of occurrences found
print("Number of groups of three identical numbers:", count)
هذا الكود يستخدم الدالة all()
لفحص ما إذا كانت جميع العناصر في مجموعة الثلاثة تساوي 1. إذا كانت تساوي، يتم زيادة العداد.