Alright, it’s been awhile I haven’t gotten on coding challenges; been busy with school and such ( nah, still not an enough excuse =/ ). So, here are three easy challenges that I did from CodeEval today. They are Sum of Digits, Multiplication Tables, and Odd Numbers. These are easy ones but I tried using the list comprehension.

Sum of Digits

Summary :

Input : 2345

Output : 14

import sys test_cases = open(sys.argv[1], 'r').readlines() def sumofDigit(number): summation = 0 digits = list(number) for x in xrange(len(digits)): summation = summation + int(digits[x]) return summation if test_cases is not None: for test in test_cases: print sumofDigit(test.rstrip()) else: test_cases.close()

Stripping characters in Python

Three methods : strip(), lstrip() and rstrip()

Strip removes any trailing characters such as white space or new line by default. So, lstrip() and rstrip() represents left and right.

exampleStr = " welcome " print spacious.strip() Output : 'welcome' exampleStr = " welcome " print spacious.lstrip() Output : 'welcome ' exampleStr = " welcome " print spacious.rstrip() Output : ' welcome'

Odd Numbers

Summary: list all of odd numbers from 1 to 100

print "\n".join([str(i) for i in xrange(1,100,2)])

So, this is list comprehension. This line of code prints odd numbers per line till 99. First, it create a list from 1 to 99 with 2 increments. Then, I join the whole list using a new line “\n”.

Multiplication Tables

Summary: Draw a multiplication table from 1 to 12

Output:

1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36

Here is the attempt:

for x in xrange(1,13): print ''.join([(i*x >= 10 and i*x <= 99) * (" "+str(i*x)) \ or (i*x >= 100) * (" "+str(i*x)) \ or " "+str(i*x) \ for i in xrange(1,13)])

I used list comprehension in this piece of code. It checks the conditions which return either 1 or 0. So, we can multiply the number with characters to index how many times in the list; in this case, it’s either the number or none. Check out some of the other python usage at previous CodeEval challenge.