Resolution of the Challenges/Kata CODEWARS – Python

During my training of Python I also used Codewars Web and these are the blocks I solved:

 def multiply(a,b):
    return a * b

Correct this code, so that the greet function returns the expected value:

class Person:
    def __init__(self, name):
      self.name = name
    def greet(self,other_name):
      return "Hi {0}, my name is {1}".format(other_name,self.name)

Vampire Numbers

def vampire_test(x,y):
 prd = x * y
 num_prd= list(str(prd))
 num_xy = list(str(x))+list(str(y))
 if sorted(num_prd)==sorted(num_xy) and len(num_xy)==len(num_prd):
   return True
 else:
   return False

Making Copies

def copy_list(l):
  "Make a copy of a list of numbers"
   copy = []
   for i in l:
      copy.append(i)
   return copy

Ghostbusters (whitespace removal)

def ghost(phrase):
   for i in list(phrase):
      if i != " ":
             print i,

Character Counter

def validate_word(word):
 match = []
 word = word.upper()
 if " " not in word and len(word) in range(0,100):
    for i in word:
       match.append(word.count(i))
    if (match[1:] == match[:-1]):
      return True
    else:
      return False
 else:
    return False

UVB-76 Message Validator

def validate(message):
 l = message.split()
 if len(l) != 8:
   return False
 if l[0] != "MDZHB":
   return False
 if not (l[1].isdigit() and len(l[1]) == 2):
   return False
 if not (l[2].isdigit() and len(l[2]) == 3):
   return False
 if not (l[3].isalpha() and l[3].isupper):
   return False
 for i in l[-4:]:
   if not i.isdigit() or len(i)!=2:
     return False 
 return True

Length_of_Line

def length_of_line(array):
 from math import sqrt
 x1 = array[0][0] 
 y1 = array[0][1]
 x2 = array[1][0] 
 y2 = array[1][1]
 r = range( -20, 21 )
 if not( x1 in r and x2 in r and y1 in r and y1 in r ):
     return False
 return '{0:.{1}f}'.format( sqrt( ( x2 - x1 ) ** 2 + ( y2 - y1 ) ** 2 ), 2)

Alphabetize a list by the nth character

def sort_it(list_, n):
  def enesima(s):
    return s[n-1]
  lista = list_.split(', ')
  return ', '.join(sorted( lista, key=enesima))

 Checking Groups

def group_check(s): 
 if s == "":
   return True
 else:
   L = []
   L.append(s[0])
   for i in range(1,len(s)):
     L.append(s[i])
     if L[len(L)-2:len(L)] == ['{','}'] or L[len(L)-2:len(L)] == [    '(',')'] or L[len(L)-2:len(L)] == ['[',']']:
       L.pop()
       L.pop()
 
 if len(L) == 0:
 return True
 else:
 return False

Square(n) Sum

def square_sum(numbers):
 sum = 0
 for i in numbers:
     sum = sum + i * i
 return sum

 IPv4 to int32

def ip_to_int32(ip):
 ip = ip.split(".")
 bin_total = []
 for i in ip:
    bin_total.append(format(int(i), 'b').zfill(8))
 a = ''.join(bin_total)
 intIP = 0
 for i in range(32):
    if int(a[i]):
 intIP += 2 ** (31-i)
 return intIP

Bit Counting

def countBits(n):
 n = format(n,'b').zfill(8)
 count = 0
 for i in str(n):
    if int(i):
      count += 1
 return count

IQ Test

def iq_test(numbers):
  numbers = numbers.split(" ")
  odd = []
  even = []
  for i,v in enumerate(numbers):
    if int(v) % 2:
      odd.append([i,v])
    else:
      even.append([i,v])
  if len(even) == 1:
    return (even[0][0])+1
  if len(odd) == 1:
    return (odd[0][0])+1

Fibonacci, Tribonacci and friends

def Xbonacci(signature,n):
 for i in range(n-len(signature)):
    signature.append(sum(signature[i:]))
 return signature[:n]

Find the Mine!

def mineLocation(field):
 result = []
 for i,v in enumerate(field):
   if 1 in v:
     result.append(i)
   for j in v:
     if j == 1:
       result.append(v.index(j))
 return result

Valid Phone Number

import re
def validPhoneNumber(phoneNumber):
 m = re.search('^\(\d{3}\)\s\d{3}-\d{4}$',phoneNumber)
 if m is None:
    return False
 elif m.group(0):
    return True
 else:
    return False

Sum of Digits / Digital Root

def digital_root(n):
 if len(str(n)) == 1:
 return n
 else:
 sum = 0
 for i in str(n):
 sum += int(i)
 return digital_root(sum)

Format a string of names like ‘Bart, Lisa & Maggie’.

def namelist(names):
 if names == []:
    return ''
 elif len(names) == 1:
    return names[0]['name']
 elif len(names) > 1:
    a = []
    for i in names:
      a.append(i['name'])
    return ', '.join(a[:-1])+" & "+''.join(a[-1])

Evil Autocorrect Prank

import re
def autocorrect(input):
 return re.sub(r"\b(\W*)((Yo|yo)u+|u)(\W*)\b", r"\1your sister\4",input)

Unique in order

def unique_in_order(iterable):
 if len(iterable) == 0:
     return []
 else:
     result = [iterable[0]]
     for i in range(1,len(iterable)):
        if iterable[i] != iterable[i-1]:
          result.append(iterable[i])
     return result

primeFactors

from math import ceil, sqrt 
def primeFactors(n):     
p = [i for i in range (2,int(ceil(sqrt(n))))]     
f = []     
i = 0     
while n > 1 and i != len(p):         
  if n % p[i] == 0:             
    f.append(p[i])             
    n = n/p[i]         
  else:             
    i = i + 1     
    if n!=1:         
f.append(n)     
return "".join(["({0}**{1})".format(i,k) if k > 1 else "({0})".format(i) for i,k in zip(sorted(set(f)),[f.count(i) for i in sorted(set(f))])])

Maximun Sequence

def maxSequence(arr):
    s = 0
    s_max = 0
    sl = []
    for i in range(1,len(arr)):
        for j in range(0,len(arr)-i+1):
            s = sum(arr[j:j+i])
            if s > s_max:
                s_max = s
                sl = arr[j:j+i]
    return s_max

Find the missing term in an Arithmetic Progression

def find_missing(sequence):
    l_r = []
    for i in range(1,len(sequence)):
        r = sequence[i] - sequence[i-1]
        l_r.append(r)
    l_ratio = [abs(r) for r in l_r]
    r_max = max(l_ratio)
    i_max = l_ratio.index(r_max)
    ratio = l_r[i_max]/2
    
    return int(sequence[i_max]+ratio)

Mod4 Regex

import re

class Mod:
    mod4 = re.compile(r".*\[[+-]?(\d*([02468][048]|[13579][26])|[048])\].*")
                      
        
    def match(self,test):
        return self.mod4.match(test)

Number of trailing zeros of N!

from itertools import groupby
def zeros(n):
 def factorial(n):
    if n == 0:
       return 1
    else:
       return n * factorial(n-1)

 m = str(factorial(n)) 

 p = [list(g) for k,g in groupby(m)] 

 if '0' in p[-1]:
     return len(p[-1])
 
 return 0

About Julita Inca

Ingeniero de Sistemas UNAC, Magíster en Ciencias de la Computación PUCP, OPW GNOME 2011, Miembro de la GNOME Foundation desde el 2012, Embajadora Fedora Perú desde el 2012, ganadora del scholarship of the Linux Foundation 2012, experiencia como Admin Linux en GMD y Especialista IT en IBM, con certificaciones RHCE, RHCSA, AIX 6.1, AIX 7 Administrator e ITILv3. Experiencia académica en universidades como PUCP, USIL y UNI. HPC researcher, a simple mortal, like you!
This entry was posted in τεχνολογια :: Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s