## DEV Community is a community of 846,721 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Chapter 1 - Programming for the Puzzled

Programming for the Puzzled

I could not find the answer of Q4. Is it somewhere?

``````# Q1

caps = caps + ['END']
start = forward = backward = 0
intervals = []
for i in range(1, len(caps)):
if caps[start] != caps[i]:
intervals.append((start, i - 1, caps[start]))
if caps[start] == 'F':
forward += 1
else:
backward += 1
start = i

if forward < backward:
flip = 'F'
else:
flip = 'B'
for t in intervals:
if t == flip:
if t != t:
print('People in positions', t, 'through', t, 'flip your caps!')
else:
print('People in positions', t, 'flip your caps!')

caps1 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F'];
caps2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F'];

print('next')
``````
``````# Q2

caps = caps + [caps]
start = 0
for i in range(1, len(caps)):
if caps[i] != caps[i - 1]:
if caps[i] != caps:
print('People in positions', i, end = " ")
start = i
else:
if start == i - 1:
else:
print('through', i - 1, 'flip your caps!')

caps1 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F'];
caps2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F'];

print('next')
``````
``````# Q3

caps = caps + ['END']
start = forward = backward = 0
intervals = []
for i in range(1, len(caps)):
if caps[i - 1] == 'H':
start = i

if caps[start] != caps[i]:
intervals.append((start, i - 1, caps[start]))
if caps[start] == 'F':
forward += 1
else:
backward += 1
if caps[i] != 'H':
start = i

if forward < backward:
flip = 'F'
else:
flip = 'B'
for t in intervals:
if t == flip:
if t != t:
print('People in positions', t, 'through', t, 'flip your caps!')
else:
print('People in positions', t, 'flip your caps!')

caps = ['F', 'F', 'B', 'H', 'B', 'F', 'B', 'B', 'B', 'F', 'H', 'F', 'F'];
``````
``````# Q4

def encrypt(s):
s += '0'
start = 0
encrypted = ''
for i in range(1, len(s)):
if s[start] != s[i]:
encrypted += s[start] + str(i - start)
start = i
return encrypted

def decrypt(s):
character = ''
decrypted = ''
for i in range(len(s)):
if not s[i].isalpha():
decrypted += s[i - 1] * int(s[i])
return decrypted

s = 'BWWWWWBWWWW'
enc = encrypt(s)
dec = decrypt(enc)
print('encrypted=', enc, ', decrypted=', dec)
``````