-
Description Use a Functional Programming approach. Though this may look somewhat awkward (
map
instead of a generator expression), this is easier to parse and optimize. In the long run, it becomes easier to read, too.Code def getIDS(s): return sum(map(ord, s)) - 48 * len(s)
Test Cases from random import randint test.describe("Basic Test") Test.assert_equals(getIDS('1345'), 13) Test.assert_equals(getIDS('1'), 1) Test.assert_equals(getIDS('12'), 3) Test.assert_equals(getIDS('110'), 2) Test.assert_equals(getIDS('011'), 2) test.describe("Complex Test") Test.assert_equals(getIDS('134124325'), 25) Test.assert_equals(getIDS('13245675'), 33) Test.assert_equals(getIDS('1908765112'), 40) Test.assert_equals(getIDS('110000'), 2) Test.assert_equals(getIDS('04720011'), 15) test.describe("Random Test") for x in range(0, 100): string = "".join([str(randint(0, 9)) for x in range(randint(25, 50))]) Test.assert_equals(getIDS(string), sum([int(x) for x in string]))
Output:
-
Code - def getIDS(s):
return sum(ord(x) for x in s) - 48 * len(s)- return sum(map(ord, s)) - 48 * len(s)
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}