In: Computer Science
Write a function COTtupleRange(xstart,xend,xstep) that returns a tuple that has:
- as index 0 item, the value of xstart
- as index 1 item, the value xstart+xstep
- as index 2 item, the value (xstart+xstep)+xstep,
and so on as long as the value does equal or pass the value of xend.
However, the function should return an empty string if for positive xstep, xstart>xend or if for negative xstep, xstart < xend. Here are three examples:
a = (2, 2.5, 3., 3.5)
a = (2, 1.5, 1., 0.5)
a = ()
Your code should also have a function mainProg() for testing the COTtupleRange(xstart,xend,xstep) function and the associated if __name__ == statement. Write the mainProg() code so that it does the three examples shown above.
Hi,
Hope you are doing fine. I have coded the question in python keeping all the requirements in mind. The code has been clearly explained using comments ehich have been highlighted in bold. Have a look at the snippets of the code for correct indentation.
Program:
#function COTtupleRange
def COTtupleRange(xstart,xend,xstep):
#result is an empty string
result=()
#if for positive xstep, xstart>xend or if for negative
xstep, xstart < xend the function returns an empty string.
#if you need an empty tuple simply return result
if (xstep>0 and xstart>xend) or (xstep<0 and
xstart<xend):
return ""
else:
#let s be the first term
s=xstart
#when xstep is positive, the loop must go on till s is
greater than xend
#when xstep is negative, the loop must on of till s is lesser than
xend
while((s<=xend and xstep>0) or (s>=xend and
xstep<0)):
#tuples are immutable, so append() cannot be used.
#instead we use concatenate and add another tuple (s,) in each
iteration
result=result+(s,)
#updating the value of s in each iteration
s=s+xstep
#return result
return result
def mainProg():
#testing the output using three tuples:
a,b,c
print("Testing COTtupleRange")
a = COTtupleRange(2, 3.51, 0.5)
b = COTtupleRange(2, 0.01, -0.5)
c = COTtupleRange(2, 1.51, 0.5)
#print results
print("a = COTtupleRange(2, 3.51, 0.5) : ",a)
print("b = COTtupleRange(2, 0.01, -0.5) : ",b)
#if you need the result of third tuple as '()' as shown in
the question, then instead of returning empty string in
COTtupleRange(), return an empty tuple (return
result)
print("c = COTtupleRange(2, 1.51, 0.5) : ",c)
#calling mainProg() is name is main:
if __name__ == "__main__":
mainProg()
Executable code snippet:
Output: Note that, for c, we return an empty string, hence nothing is visible. If you want '()' to be printed then replace the line return "" with return result in COTtupleRange function