---
description: Practice makes perfect, and here is the dojo
---

# Codewars

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

```python
def count_sheeps(sheep):
  # Given an array of true and false, count number of trues
    count = 0
    for i in sheep:
        if i is True: # you can even put "if i:"
            count+=1
        else:
            pass
    return count
    
### solution 2 - .count
def count_sheeps(arrayOfSheeps):
    return arrayOfSheeps.count(True)
### solution 3 - list comprehension len
def count_sheeps(sheep):
    return len([x for x in sheep if x is True])
```

## Grade 7 Kyu&#x20;

### Reverse given int string from largest to smallest

etc. 67590 to 97650

```python
def descending_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)
    return int(s) #question asked for int, use return to end code block if not it continues
    
###SOLUTION 2
def Descending_Order(num):
    return int("".join(sorted(str(num), reverse=True)))
    
###SOLUTION 3
def Descending_Order(num):
    return int(''.join(sorted(str(num))[::-1]))
 
 ### Manual method 
 >>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> for i in range(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:&#x20;

* 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

```python
>>> 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

```python
# for string
seq_string = 'Python'
print(list(reversed(seq_string)))

# for tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seq_tuple)))

# for range
seq_range = range(5, 9)
print(list(reversed(seq_range)))

# for list
seq_list = [1, 2, 4, 3, 5]
print(list(reversed(seq_list)))
```

### Filter integer from List

```python
def filter_list(l):
    new_list=[]

    for i in l:
        #print(i)
        if type(i)==int:
            new_list.append(i)
        else:
            pass
    return new_list
    
### Solution 2
def filter_list(l):
    return [i for i in l if not isinstance(i,str)]
# iterate i in l for NOT str instances

###solution 3
def filter_list(l):
    return [i for i in l if type(i) is int]
    
```

### Disemvowel (Filter vowels)

```python
def disemvowel(string):
    for i in "AEIOUaeiou":
# this iterates every letter in string
        string = string.replace(i, '')
#replace i with nothing
    return string
    
### Solution 2 - translate replaces (Python 2+ versions)
def disemvowel(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)

```python
def DNA_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 in list)
    
### solution 2 - using dictionary key value map ATCG to TAGC
pairs = {'A' : 'T', 'T':'A', 'C':'G', 'G':'C'}
def DNA_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

```python
def number(bus_stops):
    # take index 0 of all elemts subtract index 1 
    plus=0
    minus=0
    for i in bus_stops:
        plus+=i[0]
        minus+=i[1]
        x = plus-minus
    return x
### solution 2 - list comprehension
def numer(bus_stops):
    return sum([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)

```python
# 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 math
def is_square(n):    
    if n==0:
        return True
    elif n<0:
        return False
    elif math.sqrt(n)%1==0:   #this is a whole number if it remainder is zero
        return True
    else:
        return False #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 away
    
print(math.sqrt(4)) # should return true

### SOLUTION 2 - Return conditions
import math
def is_square(n):
    return n>-1 and math.sqrt(n) % ! ==0;      
    # so that we accept n==0 too
    
    ###SOLUTION 3 - Using is_integer, math libary
import math
def is_square(n):
    if n<0:
        return False
    sqrt=math.sqrt(n)
    return sqrt.is_integer()
### SOLUTION 4 - Run the sqrt function thru and back to see whether is equal to n    
def is_square(n):
    if n>=0:
        if int(n**0.5)**2 == n: #main - sqrt n then square is it int?
            return True
        return False
            
```

### Return Sum of 1 to n given integer

```python
### SOLUTION 2
def f(n):
    return sum(range(1,n+1)) if type(n) is int and n >0 else None      

### SOLUTION 3
def f(n):
    try:
        if n<=0:
            return None
        else:
            return sum(range(1,n+1))
    except:
        return None
### 
def f(n):
    try:
        x = int(n)
        if int(n) <= 0:
            return None
        elif int(n) > 0:
            return sum([i for i in range(0, n+1)])
    except:
        None
```

### Given average of array, find new value to add to hit target newaverage

```python
import math

def new_avg(arr, newavg):
	# take newavg * (n+1) = total
    # total - sum(arr) = ans
    try:
        if newavg <=0:
            return None
        else:
            n = len(arr) + 1
            total = newavg * n
            return math.ceil(total - sum(arr))
    except:
        return None
```

## Grade 6 Kyu

### List Comprehension&#x20;

Remove things in list b from list a

```python
def array_diff(a,b):
    return [x for x in a if x not in b]

# Solution 2: while loop & .remove
def array_diff(a,b):
    for i in range(len(b)):
        while b[i] in a:
            a.remove(b[i])
    return a
```

