Reputation: 11
I have an assignment that's asking me to get count without a for loop and the test environment keeps returning: Expected count to be 0, but got Params(tuple=(1, 'a', True), expected=0).
Assume tpl to be a tuple containing elements of different types (int, string, float and bool). Write some code that counts how many elements have the same type as the first element. Store the result in a variable called count. Do not use a for loop.
# Get the type of the first element
first_type = type(tpl[0])
# Use list comprehension and the sum function to count matching types
count = sum(1 for elem in tpl if type(elem) == first_type)
# Output the count
print(count)
Upvotes: -2
Views: 162
Reputation: 11
Well, I finally figured out the answer to this. I had to use a while loop and not count the first iteration of the first type. I did that by setting the index to 1.
typeFirst = type(tpl[0])
index = 1
count = 0
while index < len(tpl):
if type(tpl[index]) == typeFirst:
count += 1
index += 1
print(count)
Upvotes: 0
Reputation: 27629
Two more ways:
tpl = 3, 'one', 4, True, 5, 9.
a, *b = map(type, tpl)
count = b.count(a)
print(count)
count = 0
ts = map(type, tpl)
t = next(ts)
while t in ts:
count += 1
print(count)
Upvotes: 1
Reputation: 24593
Assuming tpl
a tuple of mixed types, you could write a recursive method as shown below.
def loop(tpl, target=None):
if not tpl:
return 0
if target is None:
target=type(tpl[0])
return int(type(tpl[0]) == target) + loop(tpl[1:], target)
Subtract 1
from the answer if you want to exclude the first element.
Another way to do it without slicing is to pass an index i
indicating the element to test against the target
. I’ll leave that as an exercise for you.
Upvotes: 0