0
Count number of even elements in a user given tuple in Python.
5 ответов
+ 3
Algorithm: Begin by setting a counter variable to zero. Then iterate over the elements of the tuple using a for loop. Check whether an element is even by testing its remainder module 2. If even, increase the counter by 1. The final value of the counter is your answer.
If you have difficulty implementing it, share your attempt, and we'll be happy to help you.
+ 1
Tried the same but shows error.
+ 1
Okay! Save your code in the code playground, and share a link to your code as a comment here. I'm sure someone will be able to figure out what's wrong.
+ 1
Oh, the algorithm is fine, the problem is with input processing. The user input is taken as a string, and not treated as a real tuple. Try this:
t=tuple(map(int, input().split()))
And don't use parentheses or commas in your input, just spaces.
OR, if you insist on taking input as a nice tuple with parentheses, commas, and spaces, you could do this:
t = input("Enter tuple with parenthesis: ")
for c in "(),":
t = t.replace(c, " ")
t = tuple(map(int, t.split()))