Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
(off) and (on) sequence
#6
This will create an iterator that always starts with 1, it will then randomly choose if it's a 0 or 1, once it is a 0 it will always be 0 until a new version is called.
import random


def on_till_randomly_off(count):
    if not count:
        return
    current_count = 0
    while True:
        if current_count == count:
            return
        yield 1
        current_count += 1
        if random.randint(0, 1):
            break
    while True:
        if current_count == count:
            return
        yield 0
        current_count += 1


print("-".join(str(state) for state in on_till_randomly_off(5)))
print("-".join(str(state) for state in on_till_randomly_off(5)))
print("-".join(str(state) for state in on_till_randomly_off(5)))
print("-".join(str(state) for state in on_till_randomly_off(5)))
print("-".join(str(state) for state in on_till_randomly_off(5)))
Output:
1-0-0-0-0 1-1-1-0-0 1-0-0-0-0 1-1-1-1-1 1-0-0-0-0

Shortened version
def on_till_randomly_off2(count):
    state = 1
    for _ in range(count):
        yield state
        if state:
            state = random.randint(0, 1)
AlexPython likes this post
Reply


Messages In This Thread
(off) and (on) sequence - by AlexPython - Dec-05-2022, 01:48 AM
RE: (off) and (on) sequence - by deanhystad - Dec-05-2022, 02:21 AM
RE: (off) and (on) sequence - by AlexPython - Dec-05-2022, 05:54 AM
RE: (off) and (on) sequence - by perfringo - Dec-05-2022, 07:57 AM
RE: (off) and (on) sequence - by AlexPython - Dec-05-2022, 03:56 PM
RE: (off) and (on) sequence - by Yoriz - Dec-05-2022, 04:59 PM
RE: (off) and (on) sequence - by AlexPython - Dec-05-2022, 07:25 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020