Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active May 7, 2020 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/3072a69a69395df1764d9cbb69877cab to your computer and use it in GitHub Desktop.
Save lbvf50mobile/3072a69a69395df1764d9cbb69877cab to your computer and use it in GitHub Desktop.
Python Arcade
import json
def buildCommand(jsonFile):
object = json.loads(jsonFile)
answer = rec(object)
return json.dumps(answer)
def rec(object):
for key in object:
if str == type(object[key]): object[key] = ''
if int == type(object[key]): object[key] = 0
if float == type(object[key]): object[key] = 0
if list == type(object[key]): object[key] = []
if dict == type(object[key]): object[key] = rec(object[key])
return object
def calcBonuses(bonuses, n):
it = iter(bonuses[:n])
res = 0
try:
for _ in range(n):
res += next(it)
except StopIteration:
res = 0
return res
def calcFinalScore(scores, n):
gen = iter(map(lambda x: x**2,sorted(scores,reverse = True))[:n])
res = 0
try:
for _ in range(n):
res += next(gen)
except StopIteration:
res /= 5
return res
def calkinWilfSequence(number):
def fractions():
q = [[1,1]]
while True:
a,b = q[0]
q = q[1:]
yield [a,b]
q.append([a,a+b])
q.append([a+b,b])
gen = fractions()
res = 0
while next(gen) != number:
res += 1
return res
def calkinWilfSequence(number):
def fractions():
a,b = 1,1
while True:
yield [a,b]
a,b = b, 2 *(a- a%b) + b - a
gen = fractions()
res = 0
while next(gen) != number:
res += 1
return res
def checkParticipants(participants):
return [ i for i,x in enumerate(participants) if i > x]
def chessTeams(smarties, cleveries):
return zip(smarties, cleveries)
def collegeCourses(x, courses):
def shouldConsider(course):
return len(course) != x
return list(filter(shouldConsider, courses))
def competitiveEating(t, width, precision):
return format(t,"."+str(precision)+"f").center(width)
def constructShell(n):
return [ [0]*(i+1) if i < n else [0]*(2*n - 1 - i) for i in range(2*n-1)]
def coolPairs(a, b):
uniqueSums = {x+y for x in a for y in b if 0 == (x*y)%(x+y)}
return len(uniqueSums)
def correctLineup(athletes):
return [j for i in zip(athletes[1::2],athletes[0::2]) for j in i]
def correctScholarships(bestStudents, scholarships, allStudents):
return set(bestStudents).issubset(set(scholarships)) and set(scholarships).issubset(allStudents) and len(scholarships)<len(allStudents)
class Counter(object):
def __init__(self,beta):
self.value = beta
def inc(self):
self.value += 1
def get(self):
return self.value
def countVisitors(beta, k, visitors):
counter = Counter(beta)
for visitor in visitors:
if visitor >= k:
counter.inc()
return counter.get()
from itertools import product
def crackingPassword(digits, k, d):
def createNumber(digs):
return "".join(map(str, digs))
return list(filter(lambda x: 0 == int(x)%d,map(lambda x: createNumber(list(x)),product(sorted(digits),repeat = k))))
from itertools import combinations
def crazyball(players, k):
return list(combinations(sorted(players),k))
import random
def createDie(seed, n):
class Die(object):
def __init__(self, s, n):
self.s = s
self.n = n
def __new__(cls,s,n):
random.seed( s )
return int(random.random()*n)+1
class Game(object):
die = Die(seed, n)
return Game.die
def createHistogram(ch, assignments):
return list(map(lambda x: ch * x, assignments))
def createSpiralMatrix(n):
dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
curDir = 0
curPos = (n - 1, n - 1)
res = [[0]*n for i in range(0,n)]
for i in range(1, n * n + 1):
res[curPos[0]][curPos[1]] = i
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
if not (0 <= nextPos[0] < n and
0 <= nextPos[1] < n and
res[nextPos[0]][nextPos[1]] == 0):
curDir = (curDir + 1) % 4
nextPos = curPos[0] + dirs[curDir][0], curPos[1] + dirs[curDir][1]
curPos = nextPos
return res
from itertools import cycle
def cyclicName(name, n):
gen = cycle(name)
res = [next(gen) for _ in range(n)]
return ''.join(res)
from collections import deque
def doodledPassword(digits):
n = len(digits)
res = [deque(digits) for _ in range(n)]
deque(map(lambda x: res[x[0]].rotate(-x[0]),[(x,y) for x,y in enumerate(res)]), 0)
return [list(d) for d in res]
def fibonacciList(n):
return [[0] * x for x in functools.reduce(lambda acc,i: acc + [acc[-1]+acc[-2]] if i > 2 else [0] if 0 == i else acc + [1], range(n),[])]
def fibonacciGenerator(n):
def fib():
last = (0, 1)
while True:
yield last[0]
last = last[0] + last[1], last[0]
gen = fib()
return [next(gen) for _ in range(n)]
def fixResult(result):
def fix(x):
return x // 10
return list(map(fix, result))
def fixTree(tree):
return list(map(lambda x: x.strip().center(len(x)),tree))
from itertools import count, takewhile
def floatRange(start, stop, step):
gen = takewhile(lambda x: x < stop,count(start,step))
return list(gen)
from collections import Counter
def frequencyAnalysis(encryptedText):
return Counter(encryptedText).most_common(1)[0][0]
def compose(functions):
return functools.reduce(lambda acc, func: (lambda x: func(acc(x))), list(functions)[::-1],lambda x: x)
def functionsComposition(functions, x):
return compose(map(eval, functions))(x)
# https://app.codesignal.com/profile/mcg1969
def compose(functions):
return reduce(lambda f,g: lambda x:f(g(x)), functions)
def functionsComposition(functions, x):
return compose(map(eval, functions))(x)
def getPoints(answers, p):
questionPoints = lambda number, ans: (number+1) if ans else -p
res = 0
for i, ans in enumerate(answers):
res += questionPoints(i, ans)
return res
def getCommit(commit):
return re.sub(r"[0\?\+\!]+","",commit,1)
class Greeter(object):
def __init__(self, names):
self.cnt = 0
self.names = names
def __iter__(self):
return self
def __next__(self):
if self.cnt < len(self.names):
self.cnt += 1
return 'Hello, {}!'.format(self.names[self.cnt - 1])
else:
raise StopIteration()
def greetingsGenerator(team):
return list(Greeter(team))
def groupDating(male, female):
return [[x for i,x in enumerate(male) if male[i] != female[i]],[y for i,y in enumerate(female) if male[i]!=female[i]]]
class Team(object):
def __init__(self, names):
self.names = names
def __bool__(self):
# 1. Make all chars upcase. Because names are dublicated need to add index.
self.names = [ (x+str(i)).upper() for i,x in enumerate(self.names)]
# 2. Make Dictionary of first_letter will be used as adjacency list
self.first = { x[0]:[] for x in self.names}
for x in self.names: self.first[x[0]].append(x)
print (self.first)
# 3. Add used list for DFS markin
self.used = {}
# 4. max_depth
self.max_depth = len(self.names)
# 5. Add dictionary for DP that as key going to store chain of words.
self.dp = {}
for x in self.names:
self.used = {}
self.used[x] = True
print ("start", x)
answer = self.dfs(x,1,x)
print(x, answer)
if answer: return True
return False
def dfs(self,name,depth,chain):
if chain in self.dp: return self.dp(chain)
if depth == self.max_depth: return True
print(depth, name, chain, [x for x in self.names])
adjacency_list = self.first.get(name[-2])
if adjacency_list:
for x in adjacency_list:
if not self.used.get(x):
self.used[x] = True
if self.dfs(x,depth+1,chain+"->"+x):
self.dp[chain] = True
return True
self.used[x] = False
self.dp[chain] = False
return False
def isCoolTeam(team):
return bool(Team(team))
#### kien_the_sun https://app.codesignal.com/profile/kien_the_sun
class Team(object):
def __init__(self, names):
self.names = names
def __bool__(self):
from collections import defaultdict as ddict, Counter
IN, OUT = Counter(), Counter()
g = ddict(set)
for name in self.names:
i, j = name[0].lower(), name[-1].lower()
g[i].add(j)
g[j].add(i)
IN[j] += 1
OUT[i] += 1
d = [IN[c] - OUT[c]for c in IN+OUT if IN[c] != OUT[c]]
s = {i}
path = [i]
while path:
node = path.pop()
for i in g[node]:
if i not in s:
s.add(i)
path.append(i)
return (not d or d[0] * d[1] == -1) and len(s) == len(g)
def isCoolTeam(team):
return bool(Team(team))
def isTestSolvable(ids, k):
digitSum = lambda x: sum([int(num) for num in str(x)])
sm = 0
for questionId in ids:
sm += digitSum(questionId)
return sm % k == 0
from itertools import permutations, islice
def kthPermutation(numbers, k):
return list(islice(permutations(sorted(numbers)),k-1,k))[0]
from fractions import gcd
def leastCommonDenominator(denominators):
return functools.reduce(lambda x,y: (x*y)/gcd(x,y), denominators)
def listsConcatenation(lst1, lst2):
res = lst1
res.extend(lst2)
return res
from datetime import datetime, timedelta
from calendar import monthrange
def maliciousProgram(curDate, changes):
datetime_object = datetime.strptime(curDate, '%d %b %Y %X')
print("Input data:", datetime_object)
datetime_array = createDateArray(datetime_object)
print("Input array:", datetime_array)
raw_array = addDiff(datetime_array, changes)
x = raw_array
try:
answer = datetime(x[2],x[1],x[0],x[3],x[4],x[5]).strftime('%d %b %Y %X')
print("Output:", answer)
return answer
except (ValueError):
return curDate
def createDateArray(datetime_object):
x = datetime_object
return [x.day,x.month,x.year,x.hour,x.minute,x.second]
def addDiff(datetime_array, changes):
return list(map(lambda a: sum(a),zip(datetime_array,changes)))
def mathPractice(numbers):
return functools.reduce(lambda acc,y: acc + y[0] if 1 == y[1]%2 else acc * y[0] ,zip(numbers,range(len(numbers))),1)
from itertools import dropwhile
def memoryPills(pills):
gen = dropwhile(lambda x: 0 != len(x)%2, pills + [""]*10)
next(gen)
return [next(gen) for _ in range(3)]
def mergingVines(vines, n):
def nTimes(n):
def decorator(func):
return lambda vines: functools.reduce(lambda x,_: func(x), range(n),vines)
return decorator
@nTimes(n)
def sumOnce(vines):
res = [vines[i] + vines[i + 1] for i in range(0, len(vines) - 1, 2)]
if len(vines) % 2 == 1:
res.append(vines[-1])
return res
return sumOnce(vines)
def multiplicationTable(n):
return [ [i*x for x in range(1,n+1)] for i in range(1,n+1)]
def newStyleFormatting(s):
tmp = "123!_tmp_!321"
s = s.replace("%%",tmp)
s = re.sub(r"%[a-z]","{}",s)
return s.replace(tmp,"%")
def newStyleFormatting(s)
temp = "123_temp_321"
s.gsub!('%%',temp)
s.gsub!(/%[a-z]/,'{}')
s.gsub(temp,"%")
end
from html.parser import HTMLParser
class PageParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.depth = 0
self.array = []
self.max_depth = 1
def handle_starttag(self, tag, attrs):
self.depth += 1
self.array.append((self.depth,tag))
print('Encountered %s at depth %d.' % (tag, self.depth))
if self.max_depth < self.depth: self.max_depth = self.depth
def handle_endtag(self, tag):
self.depth -= 1
def max_depth_items(self):
answer = [x[1] for x in self.array if x[0] == self.max_depth ]
return sorted(set(answer))
def pageComplexity(document):
x = PageParser()
x.feed(document)
print("Max depth:", x.max_depth)
answer = x.max_depth_items()
return answer
def prefSum(a):
return functools.reduce(lambda x,y: x + [x[-1]+y],a,[0])[1::]
def pressureGauges(morning, evening):
return [[min(morning[i],evening[i]) for i in range(len(evening))],[max(morning[i],evening[i]) for i in range(len(evening))]]
def pressureGauges(morning, evening):
return list(zip(*map(sorted,zip(morning,evening))))
class Rectangle(object):
def __init__(self, height, width):
self.height = height
self.width = width
def __str__(self):
return '{} x {} = {}'.format(self.height, self.width, self.area)
@property
def area(self):
return self.height * self.width
def primarySchool(height, width):
return str(Rectangle(height, width))
def primesSum(a, b):
return sum(filter(lambda x: a<=x<=b,functools.reduce(lambda acc,v: acc + [v] if v > acc[-1] and all([0!=v%x for x in acc]) else acc ,range(1,b+1),[2])))
def primesSum(a, b):
return sum(filter(lambda x: all(x % i for i in range(2, int(x**0.5) + 1)), range(max(2, a), b+1)))
# https://app.codesignal.com/profile/yasu
def printList(lst):
return "This is your list: " + str(lst)
class FRange(object):
def __init__(self, start, stop=None, step=None):
if stop is None:
self.i = 0
self.stop = start
self.step = 1
elif step is None:
self.i = start
self.stop = stop
self.step = 1
else:
self.i = start
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
if (self.step > 0 and self.i >= self.stop) or (self.step < 0 and self.i <= self.stop): raise StopIteration
ans = self.i
self.i += self.step
return ans
def rangeFloat(args):
return list(FRange(*args))
def removeTasks(k, toDo):
del toDo[k-1::k]
return toDo
repeatChar = lambda ch,n: ch*n
from itertools import permutations
def rockPaperScissors(players):
return list(permutations(sorted(players),2))
class Functions(object):
@staticmethod
def sign(x):
if x > 0: return 1
if x < 0: return -1
return 0
def sign(x):
return Functions.sign(x)
def compose(f, g):
return lambda x: f(g(x))
def simpleComposition(f, g, x):
return compose(eval(f), eval(g))(x)
def sortCodesignalUsers(users):
res = [CodeSignalUser(*user) for user in users]
res.sort(reverse=True)
return list(map(str, res))
class CodeSignalUser(object):
def __init__(self,n,i,s):
self.n = n
self.i = int(i)
self.s = int(s)
def __str__(self):
return self.n
def __lt__(self, other):
if self.s < other.s: return True
if self.s == other.s and self.i > other.i: return True
return False
def sortStudents(students):
students.sort(key=lambda x: x.split()[-1])
return students
def startupName(companies):
cmp1 = set(companies[0])
cmp2 = set(companies[1])
cmp3 = set(companies[2])
res = (cmp1|cmp2|cmp3) - (cmp1 & cmp2 & cmp3) - (cmp1 -(cmp2|cmp3)) -(cmp2 -(cmp1|cmp3)) - (cmp3 -(cmp2|cmp1))
return list(sorted(list(res)))
class Prizes(object):
def __init__(self,pur,n,d):
self.a = (i+1 for i,v in enumerate(pur) if 0 == v%d and 0 == (i+1)%n )
def __iter__(self):
return self.a
def superPrize(purchases, n, d):
return list(Prizes(purchases, n, d))
class Mammal(object):
def __init__(self, age):
self.age = age
print(self.age)
def __str__(self):
age = 0
if "Human" in str(type(self)):
print(self.age)
age = self.age
else:
print(self.toHuman())
age = self.toHuman()
return "{} y.o. in human age".format(age)
class Cat(Mammal):
def toHuman(self):
if self.age == 0:
return 0
elif self.age < 3:
return 25 // (3 - self.age)
else:
return 25 + 4 * (self.age - 2)
class Dog(Mammal):
def toHuman(self):
if self.age == 0:
return 0
elif self.age == 1:
return 15
elif self.age == 2:
return 24
else:
return 24 + (self.age - 2) * 4
class Human(Mammal):
pass
def toHumanAge(members):
species = {
'cat': Cat,
'dog': Dog,
'human': Human
}
res = []
for spec, age in members:
res.append(str(species[spec](int(age))))
return res
def transposeDictionary(scriptByExtension):
return sorted([[scriptByExtension[k],k] for k in scriptByExtension])
def tryFunctions(x, functions):
return [ eval(f)(x) for f in functions]
def twinsScore(b, m):
return map(lambda x: x[0]+x[1],zip(b,m))
from functools import partial
def line_y(m, b, x):
return m * x + b
def twoLines(line1, line2, l, r):
line1_y = partial(line_y, line1[0], line1[1])
line2_y = partial(line_y, line2[0], line2[1])
balance = 0
for x in range(l, r + 1):
y1 = line1_y(x)
y2 = line2_y(x)
if y1 > y2:
balance += 1
elif y1 < y2:
balance -= 1
if balance > 0:
return "first"
if balance < 0:
return "second"
return "any"
def twoTeams(students):
return sum(students[0::2]) - sum(students[1::2])
def uniqueCharacters(document):
return sorted(list(set(document)))
from urllib import parse
def urlSimilarity(url1, url2):
total = 0
a = parse.urlsplit(url1)
b = parse.urlsplit(url2)
if a.scheme == b.scheme:
print(a.scheme,"+5")
total += 5
if a.netloc == b.netloc:
print(a.netloc, "+10");
total += 10
a_path = a.path.strip("?/").split('/')
b_path = b.path.strip("?/").split('/')
for i in range(0, min(len(a_path),len(b_path))):
if a_path[i] and a_path[i] == b_path[i]:
print(a_path[i], "+1")
total += 1
else: break
a_query = dict(parse.parse_qs(a.query))
b_query = dict(parse.parse_qs(b.query))
for k in a_query:
if k in b_query:
if a_query[k][0] == b_query[k][0]:
print(k, a_query[k][0], "+2")
total += 2
else:
print(k, "+1")
total += 1
return total
class User(object):
def __init__(self, username, _id, xp, name):
self.username = username
self._id = _id
self.xp = xp
self.name = name
def __getattr__(self, name):
if name in ['username','_id','xp', 'name']: return getattr(self, name)
else: return "{} attribute is not defined".format(name)
def userAttribute(attribute):
user = User("annymaster", "1234567", "1500", "anny")
return getattr(user, attribute)
# Codesignal: Website Celandar.
# Thanks for: @danolition, @dmireles, @henry_r7.
import calendar
def websiteCalendar(month, year):
x = calendar.HTMLCalendar().formatmonth(theyear=year, themonth=month, withyear=True)
x = x.replace('\n','')
return x
import base64
def weirdEncoding(encoding, message):
x = base64.b64decode(message,encoding)
return x.decode()
def wordPower(word):
num = { chr(i):i-96 for i in range(97,123)}
return sum([num[ch] for ch in word])
def wordsRecognition(word1, word2):
def getIdentifier(w1, w2):
return "".join(sorted(list(set(w1) - set(w2))))
return [getIdentifier(word1, word2), getIdentifier(word2, word1)]
import xml.etree.ElementTree as ET
def xmlTags(xml):
root = ET.fromstring(xml)
dictionary = dict()
answer = rec(root,0,[], dictionary)
print(dictionary)
return ["{}({})".format(x,", ".join(dictionary[x])) for x in answer]
def rec(root, deep, arr, dictionary):
tag = root.tag
prefix = "--" * deep
attribs = sorted(root.attrib)
line = prefix + tag
if line not in dictionary:
dictionary[line] = attribs
arr.append(line)
else:
x = dictionary[line]
dictionary[line] = sorted(list(set(attribs+x)))
for x in root:
rec(x, deep+1, arr, dictionary)
return arr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment