Series39. An integer K and K sets of nonzero integers are given. Each set contains at least three elements, the sign of its completion is the number 0. Find the number of sawtooth sets (the definition of the sawtooth set is given in the task of Series23).

Solution in Python 3:

import random

K = random.randrange(1,9)
print("K = ",K)

count_saw = 0
for i in range(0,K):
x_prev = random.randrange(1,10)
x_curr = random.randrange(x_prev+1,x_prev+11)
print(x_prev,end="; ")
print(x_curr,end="; ")
k = -1
saw = 0
i = 2
while True:
if k == 1:
y = list(range(x_curr-1,x_curr+11))
y.append(0)
#x_next = random.randrange(x_curr-1,x_curr+11)
x_next = random.choice(y)
else:
#x_next = random.randrange(x_curr-10,x_curr+1)
y = list(range(x_curr-10,x_curr+1))
y.append(0)
x_next = random.choice(y)
k *= -1
print(x_next,end="; ")
if x_next == 0:
break

if saw == 0:
if not ((x_prev < x_curr and x_curr > x_next) \
or (x_prev > x_curr and x_curr < x_next)):
saw = i
x_prev = x_curr
x_curr = x_next
i += 1

print()
if saw == 0:
print("saw: ", saw)
count_saw += 1
else:
print("not saw: ", saw)
print()
print("Number of saws: ", count_saw)