Using a program language of your choice, write a simple program to exhaustively
ID: 3587401 • Letter: U
Question
Using a program language of your choice, write a simple program to exhaustively list (generate) all binary strings of length N. Your program should read N > 5 as input and then list all binary strings of length N. Use your program to answer the following questions by testing each of your generated binary strings.
(a) How many binary strings of length N contain the substring 1010 ? (b) How many binary strings of length N contain at least four 0s ? (c) How many 5-element subsets of {1,2,3,...,N} contain both 1 and 2?
Explanation / Answer
import itertools
def printBinaryStrng(n):
binaries = ["".join(seq) for seq in itertools.product("01", repeat=n)]
count_substr = 0
count_40 = 0
print("Binary strings are: ")
for b in binaries:
print(b)
if "1010" in b:
count_substr += 1
if b.count('0') >= 4:
count_40 += 1
print("Count of binary number with substring '1010' is " + str(count_substr))
print("Count of binary number with atleast 4 0's is " + str(count_40))
printBinaryStrng(7)
# link to code: https://paste.ee/p/mJTLk
Sampe run:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.