Computer Science, asked by som239727, 5 days ago

Write a function that takes 2 inputs A string and an integer flag (Value can be 0 or 1)

• If the flag value is '0' the function should return all

the characters at even place in the input string If the flag value is '1' the function should return all the characters at odd place in the input string

• Function1(TRACKIN",0)="RCN™

• Function1"TRACKIN". 1] = "TAX

Answers

Answered by Equestriadash
8

The following co‎des have been written using Python.

\tt d ef\ str\_return(s,\ i):\\{\ \ \ \ \ }if\ i\ ==\ 0:\\{\ \ \ \ \ }{\ \ \ \ \ }ns\ =\ ""\\{\ \ \ \ \ }{\ \ \ \ \ }for\ i\ in\ s:\\{\ \ \ \ \ }{\ \ \ \ \ }{\ \ \ \ \ }if\ s.index(i)\%2\ !=\ 0:\\{\ \ \ \ \ }{\ \ \ \ \ }{\ \ \ \ \ }ns\ =\ ns\ +\ i\\{\ \ \ \ \ }elif\ i\ ==\ 1:\\{\ \ \ \ \ }{\ \ \ \ \ }ns\ =\ ""\\{\ \ \ \ \ }{\ \ \ \ \ }for\ i\ in\ s:\\{\ \ \ \ \ }{\ \ \ \ \ }{\ \ \ \ \ }if\ s.index(i)\%2\ ==\ 0:\\{\ \ \ \ \ }{\ \ \ \ \ }{\ \ \ \ \ }ns\ =\ ns\ +\ i\\{\ \ \ \ \ }print(ns)

Once the arguments (s = the string, i = the flag value) have been pas‎sed, we use a conditional statement to test the flag value. If the flag value is 0, as mentioned in the question, the characters at the even positions need to be printed.

In Python, when a string is stored, the positioning usually starts from 0, i.e., the first character's position = 0, the second character's position = 1, the third character's position = 2 ... and it goes on. However, in the example given, the position is assumed to start from 1, i.e., the first character's position = 1, the second character's position = 2, the third character's position = 3 ... and it goes on. Therefore, we need to reverse the logic to get our desired output. We use the \tt index() function to retrieve the index position [positioning as per Python] of the character. When the flag value is 0, all the odd number positionings as per Python will be printed. And when the flag value is 1, all the even number positionings as per Python will be printed.

A table to show the representation has been given below:

\begin{array}{|c|c|c|}\cline{1-3}\bf Character & \bf Python/Index\ Positioning & \bf Actual\ Positioning\\\cline{1-3} \sf T & 0 & 1\\\cline{1-3}\sf R & 1 & 2\\\cline{1-3}\sf A & 2 & 3\\\cline{1-3}\sf C & 3 & 4\\\cline{1-3}\sf K & 4 & 5\\\cline{1-3}\sf I & 5 & 6\\\cline{1-3}\sf N & 6 & 7\\\cline{1-3}\sf G & 7 & 8\\\cline{1-3}\end{array}

Once the index retrieval is done, after testing if it's even or odd, it is stored into a new variable and the final output is printed.

Similar questions