Weekly Challenge 311
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. It's a great way for us all to practice some coding.
Task 1: Upper Lower
Task
You are given a string consists of English letters only.
Write a script to convert lower case to upper and upper case to lower in the given string.
My solution
Well this will be one of the easiest challenges to complete. Python has a swapcase method that will swap the case of letters in the string.
def upper_lower(s: str) -> str:
return s.swapcase()
I didn't do a Perl solution, but if I did the line $str =~ tr/A-Za-z/a-zA-Z/
would do the trick.
Examples
$ ./ch-1.py PerL
pERl
$ ./ch-1.py rakU
RAKu
$ ./ch-1.py PyThOn
pYtHoN
Task 2: Group Digit Sum
Task
You are given a string, $str
, made up of digits, and an integer, $int
, which is less than the length of the given string.
Write a script to divide the given string into consecutive groups of size $int
(plus one for leftovers if any). Then sum the digits of each group, and concatenate all group sums to create a new string. If the length of the new string is less than or equal to the given integer then return the new string, otherwise continue the process.
My solution
As both str
and int
are reserved words in Python, I've called the variables s
and i
respectively. These are the steps that I take for this task.
- Create a list
groups
that splits the inputs
intoi
characters. - Create a variable
sums
which is an empty string. - For each group of
groups
, sum the individual digits and append that to thesums
variable. - If the length of
sums
string is greater thani
, call the function again. - Return the
sums
value as an integer.
def group_digit_sum(s: str, i: int) -> int:
groups = [s[x:x+i] for x in range(0, len(s), i)]
sums = ''
for group in groups:
sums += str(sum(int(d) for d in group))
if len(sums) > i:
return group_digit_sum(sums, i)
return int(sums)
Examples
$ ./ch-2.py 111122333 3
359
$ ./ch-2.py 1222312 2
76
$ ./ch-2.py 100012121001 4
162
Top comments (0)