I found Codewars while searching for suitable coding websites to practice daily, this website is really great with its diversity of challenges, ranking system and opportunites to gain "honor", which helped with the motivation. I find the greatest perk Codewars has over other sites is the ability to compare solutions with others after solving challenges. This really helped me learn alot from the other users with different ways to solve a single problem.
Grade 8 Kyu
Counting true or false in an array
defcount_sheeps(sheep):# Given an array of true and false, count number of trues count =0for i in sheep:if i isTrue:# you can even put "if i:" count+=1else:passreturn count### solution 2 - .countdefcount_sheeps(arrayOfSheeps):return arrayOfSheeps.count(True)### solution 3 - list comprehension lendefcount_sheeps(sheep):returnlen([x for x in sheep if x isTrue])
Grade 7 Kyu
Reverse given int string from largest to smallest
etc. 67590 to 97650
defdescending_order(num):# Bust a move right here s=str(num)#int cannot be manipulated or sorted, sonvert to string s=list(s)#only list can sort or reversed s=sorted(s)#sort by numerical value s=reversed(s)# have to list to see the actualy values, reverse makes it named as the memroy location s=list(s)#list to see actual values of reversed s=''.join(s)returnint(s)#question asked for int, use return to end code block if not it continues###SOLUTION 2defDescending_Order(num):returnint("".join(sorted(str(num), reverse=True)))###SOLUTION 3defDescending_Order(num):returnint(''.join(sorted(str(num))[::-1]))### Manual method >>> digits = [0,1,2,3,4,5,6,7,8,9]>>>for i inrange(len(digits) //2):... digits[i], digits[-1- i]= digits[-1- i], digits[i]...>>> digits[9,8,7,6,5,4,3,2,1,0]
# Guide : Manipulator Tips:
Familiar examples of iterables include lists, tuples, and strings
sorted(list) can only work on lists, it returns a list back from smallest to largest
reversed() can work on strings, tuples, list / list.reversed()
reversed() changes underlying argument given, returns a new reversed one
reverse() executes INPLACE - do not assign variable, just call <digits.reverse> instead of digit = digit.reverse(), digit> THIS WILL RETURN NONE
>>> digits = [0,1,2,3,4,5,6,7,8,9]>>> reversed_digits =reversed(digits)>>> reversed_digits<list_reverseiterator object at 0x7fca9999e790>>>>list(reversed_digits)[9,8,7,6,5,4,3,2,1,0]
''.join(iterable) only works on strings, list, tuple, dictionary
# for stringseq_string ='Python'print(list(reversed(seq_string)))# for tupleseq_tuple = ('P','y','t','h','o','n')print(list(reversed(seq_tuple)))# for rangeseq_range =range(5, 9)print(list(reversed(seq_range)))# for listseq_list = [1,2,4,3,5]print(list(reversed(seq_list)))
Filter integer from List
deffilter_list(l): new_list=[]for i in l:#print(i)iftype(i)==int: new_list.append(i)else:passreturn new_list### Solution 2deffilter_list(l):return [i for i in l ifnotisinstance(i,str)]# iterate i in l for NOT str instances###solution 3deffilter_list(l):return [i for i in l iftype(i)isint]
Disemvowel (Filter vowels)
defdisemvowel(string):for i in"AEIOUaeiou":# this iterates every letter in string string = string.replace(i, '')#replace i with nothingreturn string### Solution 2 - translate replaces (Python 2+ versions)defdisemvowel(string):return string.translate(None, "AEIOUaeiou")
Printing Complementary DNA given DNA Strand
Always remember you can't join a list! Use .join (element for element in list)
defDNA_strand(dna):list=[]for i in dna:if i =="A":list.append("T")elif i =="T":list.append("A")elif i =="C":list.append("G")else:list.append("C")return''.join(e for e inlist)### solution 2 - using dictionary key value map ATCG to TAGCpairs ={'A':'T','T':'A','C':'G','G':'C'}defDNA_strand(dna):return''.join(pairs[keys] for keys in dna)# pairs[keys] will give the value
Manipulating Lists, Iterating Lists
There is a bus moving in the city, and it takes and drop some people in each bus stop.
You are provided with a list (or array) of integer pairs. Elements of each pair represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.
Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there. Test case: [ [10,0],[3,5],[5,8]] Ans: 5
defnumber(bus_stops):# take index 0 of all elemts subtract index 1 plus=0 minus=0for i in bus_stops: plus+=i[0] minus+=i[1] x = plus-minusreturn x### solution 2 - list comprehensiondefnumer(bus_stops):returnsum([stop[0] - stop[1] for stop in bus_stops])
Determine if an integer n, given, is a square (can be square root to a whole number)
# used the math library with sqrt function#tested whether we get a whole number by modulo 1#whole numbers return zero remainders when divideed by 1 import mathdefis_square(n): if n==0:returnTrueelif n<0:returnFalseelif math.sqrt(n)%1==0:#this is a whole number if it remainder is zeroreturnTrueelse:returnFalse#not whole number implies not a square as there is decimal number#to check if its whole number divide by 1, every whole number has zero remainders, decimals will give awayprint(math.sqrt(4))# should return true### SOLUTION 2 - Return conditionsimport mathdefis_square(n):return n>-1and math.sqrt(n)% ! ==0; # so that we accept n==0 too###SOLUTION 3 - Using is_integer, math libaryimport mathdefis_square(n):if n<0:returnFalse sqrt=math.sqrt(n)return sqrt.is_integer()### SOLUTION 4 - Run the sqrt function thru and back to see whether is equal to n defis_square(n):if n>=0:ifint(n**0.5)**2== n:#main - sqrt n then square is it int?returnTruereturnFalse
Return Sum of 1 to n given integer
### SOLUTION 2deff(n):returnsum(range(1,n+1))iftype(n)isintand n >0elseNone### SOLUTION 3deff(n):try:if n<=0:returnNoneelse:returnsum(range(1,n+1))except:returnNone### deff(n):try: x =int(n)ifint(n)<=0:returnNoneelifint(n)>0:returnsum([i for i inrange(0, n+1)])except:None
Given average of array, find new value to add to hit target newaverage
import mathdefnew_avg(arr,newavg):# take newavg * (n+1) = total# total - sum(arr) = anstry:if newavg <=0:returnNoneelse: n =len(arr)+1 total = newavg * nreturn math.ceil(total -sum(arr))except:returnNone
Grade 6 Kyu
List Comprehension
Remove things in list b from list a
defarray_diff(a,b):return [x for x in a if x notin b]# Solution 2: while loop & .removedefarray_diff(a,b):for i inrange(len(b)):while b[i]in a: a.remove(b[i])return a