Home > Back-end >  How to take a tuple as input, and return it as a new tuple, but only with odd numbers?
How to take a tuple as input, and return it as a new tuple, but only with odd numbers?

Time:10-20

Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). I got 0.6/1 with this code:

def oddTuple(tup):
    b = 1
    if b % 2 != 0:
        d.append(tup[b])
        b  = 1
    print (d)

CodePudding user response:

You can do this with basic slicing.

tup = ('I', 'am', 'a', 'test', 'tuple')
tup[::2]
# ('I', 'a', 'tuple')

The syntax for slicing is iterable[start:end:step]. If you leave any of those start, end, or step blank, they default to the beginning, the end, and 1 respectively. So the above is going through the whole thing (beginning to end) but only selecting every other element.

If you need it in a method:

def odd_tuple(tup):
    return tup[::2]  # or print(tup) if you prefer

CodePudding user response:

You can use enumerate and return odd elements as tuple like below:

>>> def oddTuple(tup):
...    return tuple(t for idx, t in enumerate(tup) if idx % 2==0)
        
>>> oddTuple(('I', 'am', 'a', 'test', 'tuple'))
('I', 'a', 'tuple')

CodePudding user response:

Try this:

def oddTuple(tup):
    return tuple(tup[i] for i in range(0, len(tup), 2))
  • Related