Reputation: 128
I'm kind of stuck on an Edabit Challenge (Link: https://edabit.com/challenge/S9KCN5kqoDbhNdKh5 ), and the objective is to basically find the total amount of characters in a list (all of the values are strings) and return that value.
Some examples are provided:
count_characters([
"###",
"###",
"###"
]) ➞ 9
count_characters([
"22222222",
"22222222",
]) ➞ 16
count_characters([
"------------------"
]) ➞ 18
count_characters([]) ➞ 0
count_characters(["", ""]) ➞ 0
My current code to achieve the goal is:
def count_characters(lst):
print(lst) #I print the list
count = 0 #Setting my count var to 0
for item in lst: #Using a for loop to iterate through the list's values
count += len(lst) #Getting the length of each value and adding it to the variable 'count'
print(len(lst)) #I also print the length of each value
print(count) #Outside the for loop, I print the count variable
return count #Then I return it
(There are multiple tests to check if the entire function works btw)
When I ran the code, this is what the console outputs:
['###', '###', '###']
3
3
3
9
Test Passed
['22222222', '22222222']
2
2
4
FAILED: 4 should equal 16
ERROR: Traceback:
in <module>
File "./frameworks/python/cw-2.py", line 28, in assert_equals
expect(actual == expected, message, allow_raise)
File "./frameworks/python/cw-2.py", line 18, in expect
raise AssertException(message)
cw-2.AssertException: 4 should equal 16
I don't understand why the code did not find the length of the 2nd test, but worked for the 1st test.
Thank you
Upvotes: 0
Views: 73
Reputation: 1939
A very minor mistake...in the loop
for item in lst:
count+=len(item)
You are doing
for item in lst:
count+=len(lst)
As in the 1st case, both length of list & length of each element is 3, the code gave the desired output but not for the 2nd case
Upvotes: 3