Created
June 19, 2016 05:45
-
-
Save hackerdem/28ed16a4e2f72af3544d46819bf3ed86 to your computer and use it in GitHub Desktop.
solutions for codewars challenges in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Product of consecutive Fib numbers in python | |
def productFib(n): | |
f=[1,1] | |
d1,d2,d3,pro=0,0,0,0 | |
while pro<=n: | |
if pro==n:return ([d1,d2,True]) | |
else:pro=0 | |
d1,d2=f[0],f[1] | |
d3=d1+d2 | |
pro=d1*d2 | |
f[0],f[1]=d2,d3 | |
return([d1,d2,False]) | |
#Perimeter of squares in a rectangle | |
def perimeter(n): | |
f=[1,1] | |
d1,d2,d3,sum,h=0,0,0,0,0 | |
while h<=n: | |
d1=f[0] | |
d2=f[1] | |
d3=d1+d2 | |
sum+=f[0] | |
f[0]=d2 | |
f[1]=d3 | |
h+=1 | |
return(4*sum) | |
#Roman Numerals Decoder | |
def solution(roman): | |
num_list=[1,4,5,9,10,40,50,90,100,400,500,900,1000] | |
rom_list=['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM','M'] | |
next_val= 0 | |
for i in range(len(roman)): | |
if i!=len(roman)-1: | |
if rom_list.index(roman[i])>=rom_list.index(roman[i+1]): | |
next_val+=num_list[rom_list.index(roman[i])] | |
else: | |
next_val-=num_list[rom_list.index(roman[i])] | |
else:next_val+=num_list[rom_list.index(roman[i])] | |
return next_val | |
#validDate Regex | |
import re | |
valid_date = re.compile("\[(0[13578]|1[02])-(0[1-9]|[1-2][0-9]|3[0,1])\]|\[(02)-(0[1-9]|1[0-9]|2[0-8])\]|\[(0[469]|11)-(0[1-9]|[1-2][0-9]|30)\]") | |
# Weight for weight | |
import operator | |
def order_weight(s): | |
aw=s.split() | |
a=[] | |
for i in aw: | |
top=0 | |
for j in i:top=top+int(j) | |
a.append((i,top)) | |
q=sorted(a,key=operator.itemgetter(1,0)) | |
z=[q[i][0] for i in range(len(q))] | |
return "{}".format((' '.join(z))) | |
#Excel's COUNTIF, SUMIF and AVERAGEIF functions | |
import re,operator | |
from decimal import Decimal | |
def provider(values,criteria): | |
d={'<>':operator.ne,'>=':operator.ge,'<=':operator.le,'<':operator.lt,'>':operator.gt,' ':operator.eq} | |
a=re.search(r'[a-zA-Z0-9\.\-]+',str(criteria)).group(0) | |
if re.search(r'[<>=]+',str(criteria)):b=re.search(r'[<>=]+',criteria).group(0) | |
else:b=' ' | |
if re.search(r'[0-9]+',a):a=float(a) | |
return a,d[b] | |
def count_if(values,criteria): | |
c=0 | |
s=provider(values, criteria) | |
for i in values: | |
if s[1](i,s[0]): | |
c+=1 | |
return c | |
def sum_if(values,criteria): | |
c=0 | |
s=provider(values, criteria) | |
for i in values: | |
if s[1](i,s[0]): | |
if s[0] is str:c+=1 | |
else:c+=i | |
return (c) | |
def average_if(values,criteria): | |
return(sum_if(values,criteria)/round(count_if(values,criteria),1)) | |
#Ninja vs Samurai: Attack + Block | |
Position = {'high': 'h','low': 'l'} | |
class Warrior(): | |
def __init__(self,name): | |
#each warrior should be created with a name and 100 health points | |
self.name=name | |
self.deceased=False | |
self.health=100 | |
self.zombie=False | |
#default guard is "", that is unguarded | |
self.block="" | |
def attack(self,enemy,position): | |
self.damage=0 | |
#attacking high deals 10 damage, low 5 | |
#0 damage if the enemy blocks in the same position | |
if enemy.block!=position: self.damage+=10 if position==Position['high'] else 5 | |
#and even more damage if the enemy is not blocking at all | |
if enemy.block=="": self.damage+=5 | |
enemy.set_health(enemy.health-self.damage) | |
def set_health(self,new_health): | |
#health cannot have negative values | |
self.health=max(0,new_health) | |
#if a warrior is set to 0 health he is dead | |
if self.health==0: | |
self.deceased=True | |
self.zombie=False | |
#he would be a zombie only if he was already dead | |
if self.deceased: self.zombie is True | |
#IP Validation | |
import re | |
def is_valid_IP(s): | |
if s=='':return False | |
d=s.split('.') | |
for i in range(len(d)): | |
if not re.match(r'(^[1-9]{1}[0-9]{0,2})\Z', d[i]) or int(d[i])>=256 or len(d)!=4:return False | |
return True | |
#Last digit of a large number | |
def last_digit(n1, n2): | |
if n2==0:return 1 | |
a=n2%4 | |
b=((n1**4)*(n1**a))%10 | |
return(b) | |
#Memoized Fibonacci | |
def fibonacci(n): | |
d=[0,1] | |
if n <len(d):return d[n-1] | |
while n>=len(d): | |
a=len(d) | |
d.append(d[a-1]+d[a-2]) | |
return d[-1] | |
#Josephus Survivor | |
def josephus_survivor(l, s): | |
e=[i for i in range(1,l+1)] | |
d=[] | |
x=0 | |
while e: | |
x+=s-1 | |
while x>=len(e): | |
x=x-len(e) | |
selected=e.pop(x) | |
d.append(selected) | |
return d[-1] | |
#Josephus Permutation | |
def josephus(n,s): | |
e=n | |
d=[] | |
x=0 | |
while e: | |
x+=s-1 | |
while x>=len(e): | |
x=x-len(e) | |
selected=e.pop(x) | |
d.append(selected) | |
return d | |
#Luck check | |
def luck_check(s): | |
v,t=0,0 | |
b=(len(s)-1)/2.0 | |
for i in range(len(s)): | |
if s[i].isdigit()==False:raise ValueError | |
if i<b:v+=int(s[i]) | |
elif i>b:t+=int(s[i]) | |
else:pass | |
if v==t:return True | |
else:return False | |
#Odd/Even number of divisors | |
from math import sqrt | |
def oddity(n): | |
factors=set() | |
for x in range(1,int(sqrt(n))+1): | |
if n%x==0: | |
factors.add(x) | |
factors.add(n//x) | |
if len(factors)%2==0:return 'even' | |
else:return 'odd' | |
#Number of permutations without repetitions | |
from math import factorial | |
from collections import Counter | |
def perms(it): | |
s=Counter(str(it)) | |
c=factorial(len(str(it))) | |
for i in set(str(it)): | |
if s[i]>1:c=int(c/factorial(s[i])) | |
return(c) | |
#import datetime | |
def make_readable(sec): | |
if sec==0:return('00:00:00') | |
else: | |
m,s=divmod(sec,60) | |
h,m=divmod(m,60) | |
return ('%02d:%02d:%02d'%(h, m, s)) | |
#Nested List Depth | |
def list_depth(l): | |
if isinstance(l, list): | |
if len(l)==0:return 1 | |
return 1 + max(list_depth(item) for item in l) | |
else: | |
return 0 | |
#A Crazy Robot? Who's is behind the scenes to make that? | |
import math | |
def finaldist_crazyrobot(moves, init_pos): | |
x,y=0,0 | |
for i in range(len(moves)): | |
p=moves[i][0] | |
d=moves[i][1] | |
if p=='R':x+=d | |
elif p=='L':x+=-d | |
elif p=='U':y+=d | |
else:y+=-d | |
return (math.sqrt(x**2+y**2)) | |
#DNA Sequence Tester | |
def check_DNA(seq1, seq2): | |
y={'A':'T','T':'A','C':'G','G':'C'} | |
t='' | |
if len(seq1)<len(seq2): | |
p=seq2 | |
seq2=seq1 | |
seq1=p | |
seq2=seq2[::-1] | |
for i in seq2: | |
t+=y['{}'.format(i)] | |
if t in seq1:return True | |
else:return False | |
#Reach Me and Sum my Digits | |
def sumDig_nthTerm(i, p, n): | |
b,t=1,0 | |
while True: | |
for j in p: | |
b+=1 | |
i+=j | |
if b==n: | |
for g in str(i): | |
t+=int(g) | |
return t | |
#Cumulative Triangle | |
def cumulative_triangle(n): | |
top,d=0,0 | |
for i in range(n-1): | |
top=top+(i+1) | |
for i in range(top+1,top+1+n): | |
d+=i | |
return d | |
#Base64 Numeric Translator | |
def base64_to_base10(st): | |
t=0 | |
s='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' | |
st=st[::-1] | |
for i in range(len(st)):t=t+(s.index(st[i]))*(64**(i)) | |
return(t) | |
#Caesar Cipher Helper | |
import string | |
class CaesarCipher(): | |
def __init__(self, sh): | |
self.shift=sh | |
self.alph=list(string.ascii_uppercase) | |
def encode(self, s): | |
self.s=s | |
self.ret='' | |
for char in self.s: | |
if char.upper() in self.alph: | |
a=(self.alph.index(char.upper())) | |
if a+self.shift>=len(self.alph):a=a-len(self.alph) | |
self.ret=self.ret+self.alph[a+self.shift] | |
else:self.ret=self.ret+char | |
return (self.ret) | |
def decode(self, p): | |
self.p=p | |
self.reret='' | |
for char in self.p: | |
if char.upper() in self.alph: | |
b=(self.alph.index(char.upper())) | |
if b-self.shift<0:b=b+len(self.alph) | |
self.reret=self.reret+self.alph[b-self.shift] | |
else:self.reret=self.reret+char | |
return (self.reret) | |
#Where my anagrams at? | |
from collections import Counter | |
def anagrams(word, words): | |
return ([i for i in words if Counter(i)==Counter(word)]) | |
#Find Fibonacci last digit | |
def get_last_digit(index): | |
fib=[0,1] | |
num=1 | |
while num<index: | |
fib.append(fib[0]+fib[1]) | |
fib.remove(fib[0]) | |
num+=1 | |
return (int(str(fib[1])[-1])) | |
#Printing Array elements with Comma delimiters | |
def print_array(arr): | |
s="" | |
for i in range(len(arr)):s+=str(arr[i])+',' | |
return (s[:-1]) | |
#Sum of many ints | |
def f(n,m): | |
return((m*(m-1)/2)*(n//m)+(((n%m)+1)*(n%m)/2)) | |
#Array.diff | |
def array_diff(a, b): | |
return ([i for i in a if not i in b ]) | |
#Valid Phone Number | |
import re | |
def validPhoneNumber(phoneNumber): | |
if re.match(r'(^\([0-9]{3}\)) ([0-9]{3})-([0-9]{4})$',phoneNumber): return True | |
else:return False | |
#What's a Perfect Power anyway? | |
import math | |
def isPP(n): | |
for k in range(2,4000): | |
if math.ceil(round(n**(1/k),7))**k==n:return [math.ceil(round(n**(1/k),7)),k] | |
return None | |
#Unique In Order | |
def unique_in_order(it): | |
a=[] | |
try: | |
for i in range(len(it)-1): | |
if it[i]!=it[i+1]:a.append(it[i]) | |
return a+[it[-1]] | |
except:return a | |
#Find the odd int | |
def find_it(seq): | |
for i in range(len(seq)): | |
if seq.count(seq[i])%2!=0:return seq[i] | |
#Lambdas as a mechanism for Open/Closed | |
spoken = lambda greeting: greeting+"." | |
shouted = lambda greeting: greeting.upper()+"!" | |
whispered = lambda greeting: greeting.lower()+"." | |
greet = lambda style,msg:style(msg) | |
#Replace With Alphabet Position | |
import string | |
def alphabet_position(text): | |
word='' | |
a=list(string.ascii_lowercase) | |
for i in range(len(text)): | |
if text[i].lower() in a:word+=str(a.index(text[i].lower())+1)+" " | |
else:pass | |
return(word.strip()) | |
#Dubstep | |
import re | |
def song_decoder(song): | |
return (re.sub(r'(WUB){1,}'," ",song)).lstrip(' ').rstrip(' ') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment