CBSE · 083Class XII · 2024Section B2 marks

Question 21(or)

2 April 2024 · Computer Science (083)

Write a user defined function in Python named Puzzle(W,N) which takes the argument W as an English word and N as an integer and returns the string where every Nth alphabet of the word W is replaced with an underscore ("_").

For example : if W contains the word "TELEVISION" and N is 3, then the function should return the string "TE_EV_SI_N". Likewise for the word "TELEVISION" if N is 4, then the function should return "TEL_VIS_ON".

Answer

python
def Puzzle(W, N):
    NewW = ""
    for i in range(len(W)):
        if (i + 1) % N == 0:
            NewW += "_"
        else:
            NewW += W[i]
    return NewW

print(Puzzle("TELEVISION", 3))

Explanation

Iterates through the characters of W. If the 1-based index is a multiple of N, append '_'; otherwise append the original character.