content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# https://leetcode.com/problems/remove-duplicate-letters/
# Given a string s, remove duplicate letters so that every letter appears once and
# only once. You must make sure your result is the smallest in lexicographical
# order among all possible results.
##############################################################... | class Solution:
def remove_duplicate_letters(self, s: str) -> str:
last_pos = {}
for (idx, char) in enumerate(s):
last_pos[char] = idx
stack = []
for (idx, char) in enumerate(s):
if char not in stack:
while stack and char < stack[-1] and (idx ... |
#%% Imports and function declaration
class Node:
def __init__(self, data):
self.data = data
self.next = None
# helper functions for testing purpose
def create_linked_list(arr):
if len(arr)==0:
return None
head = Node(arr[0])
tail = head
for data in arr[1:]:
tail.next... | class Node:
def __init__(self, data):
self.data = data
self.next = None
def create_linked_list(arr):
if len(arr) == 0:
return None
head = node(arr[0])
tail = head
for data in arr[1:]:
tail.next = node(data)
tail = tail.next
return head
def print_linked_... |
def random_gauss(mean, standard_deviation):
sum = 0
for _ in range(12):
sum = sum + random()
centered_around_zero = sum - 6
deviated = centered_around_zero * standard_deviation
gauss_value = deviated + mean
return gauss_value
# use the returned value as the next seed
# and use any numbe... | def random_gauss(mean, standard_deviation):
sum = 0
for _ in range(12):
sum = sum + random()
centered_around_zero = sum - 6
deviated = centered_around_zero * standard_deviation
gauss_value = deviated + mean
return gauss_value
def random(seed, a, b, c):
rand = (a * seed + b) % c
... |
class Point2D():
def __init__(self, x,y):
self.coord = [x,y]
def __str__(self):
return f'Point:({self.coord[0]},{self.coord[1]})'
def __eq__(self,other):
return (self.coord[0]==other.coord[0])&(self.coord[1]==other.coord[1])
def __ne__(self,other):
return (self.coord[0]... | class Point2D:
def __init__(self, x, y):
self.coord = [x, y]
def __str__(self):
return f'Point:({self.coord[0]},{self.coord[1]})'
def __eq__(self, other):
return (self.coord[0] == other.coord[0]) & (self.coord[1] == other.coord[1])
def __ne__(self, other):
return (sel... |
# Dictionary Carrent book with attributes
currentBook = {
"title": "Possibility of an Island",
"author": "Michel Houellebecq",
"price": 40
}
print(currentBook)
print(currentBook["author"])
currentBook["ISBN"] = "374795"
print("The Current book has these values:")
for value in currentBook.values():
p... | current_book = {'title': 'Possibility of an Island', 'author': 'Michel Houellebecq', 'price': 40}
print(currentBook)
print(currentBook['author'])
currentBook['ISBN'] = '374795'
print('The Current book has these values:')
for value in currentBook.values():
print(' => {}'.format(value)) |
# optimizes artifacts per roll, not exact values
# e.g. a +20 artifact has 5 rolls total
# rolls are averaged, with data from
# https://genshin-impact.fandom.com/wiki/Artifacts/Stats
# ===============================================
# how this works:
# ===============================================
# our damage equa... | max_rolls = 5
dp_stat_order = ['ATKb', 'ERb', 'CRCDb']
max_num_stats = len(dp_stat_order)
dp_statlv = [[(0, None) for i in range(max_num_stats + 1)] for j in range(MAX_ROLLS + 1)]
crcdlv = [(0, None) for j in range(MAX_ROLLS)]
def transformative_em_rolls_dmg(_rolls_em, _curr_stats):
return _rolls_em * 2 - 3
def a... |
def fo1():
print('1')
print('2')
print('3')
def main():
fo1()
print('a')
print('b')
print('c')
main() | def fo1():
print('1')
print('2')
print('3')
def main():
fo1()
print('a')
print('b')
print('c')
main() |
#!/usr/bin/python3
def solve(input_fname):
lines = []
pos = depth = aim = 0
with open(input_fname) as ifile:
for line in ifile:
lines.append(line.strip().split())
for cmd, unit in lines:
unit = int(unit)
if cmd == "forward":
pos += unit
depth ... | def solve(input_fname):
lines = []
pos = depth = aim = 0
with open(input_fname) as ifile:
for line in ifile:
lines.append(line.strip().split())
for (cmd, unit) in lines:
unit = int(unit)
if cmd == 'forward':
pos += unit
depth += aim * unit
... |
{
"files.associations": {
"**/*.html": "html",
"**/templates/**/*.html": "django-html",
"**/templates/**/*": "django-txt",
"**/requirements{/**,*}.{txt,in}": "pip-requirements"
},
"emmet.includeLanguages": {
"django-html": "html"
},
"python.pythonPath": "/usr/... | {'files.associations': {'**/*.html': 'html', '**/templates/**/*.html': 'django-html', '**/templates/**/*': 'django-txt', '**/requirements{/**,*}.{txt,in}': 'pip-requirements'}, 'emmet.includeLanguages': {'django-html': 'html'}, 'python.pythonPath': '/usr/local/bin/python3'} |
class DevConfig(object):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/octocd'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = 'DEV_KEY'
| class Devconfig(object):
debug = True
sqlalchemy_database_uri = 'sqlite:////tmp/octocd'
sqlalchemy_track_modifications = False
secret_key = 'DEV_KEY' |
#!/usr/bin/env python
""" Problem 61 daily-coding-problem.com """
def custom_pow(x: int, y: int) -> int:
if y == 0:
return 1
temp = custom_pow(x, int(y / 2))
if (y % 2 == 0):
return temp * temp
else:
if y > 0:
return x * temp * temp
else:
retur... | """ Problem 61 daily-coding-problem.com """
def custom_pow(x: int, y: int) -> int:
if y == 0:
return 1
temp = custom_pow(x, int(y / 2))
if y % 2 == 0:
return temp * temp
elif y > 0:
return x * temp * temp
else:
return temp * temp / x
if __name__ == '__main__':
as... |
class Education:
def __init__(self, school, time, title, desc):
self.school = school
self.time = time
self.title = title
self.desc = desc | class Education:
def __init__(self, school, time, title, desc):
self.school = school
self.time = time
self.title = title
self.desc = desc |
'''
## The PyLCONF
A LCONF parser and emitter for Python.
### Web Presence
* PyLCONF [web site](http://lconf-data-serialization-format.github.io/PyLCONF/)
* PyLCONF [github repository](https://github.com/LCONF-Data-Serialization-Format/PyLCONF/)
### Copyrights & Licenses
The *PyLCONF package* is licensed under ... | """
## The PyLCONF
A LCONF parser and emitter for Python.
### Web Presence
* PyLCONF [web site](http://lconf-data-serialization-format.github.io/PyLCONF/)
* PyLCONF [github repository](https://github.com/LCONF-Data-Serialization-Format/PyLCONF/)
### Copyrights & Licenses
The *PyLCONF package* is licensed under ... |
#!/usr/bin/env python3
class FilterMiddleware(object):
def __init__(self, wsgi_app):
self.wsgi_app = wsgi_app
self.blacklist = ["sqlmap", "dirbuster"]
def __call__(self, environ, start_response):
try:
if any((x for x in self.blacklist if x in environ["HTTP_USER_AGENT"].low... | class Filtermiddleware(object):
def __init__(self, wsgi_app):
self.wsgi_app = wsgi_app
self.blacklist = ['sqlmap', 'dirbuster']
def __call__(self, environ, start_response):
try:
if any((x for x in self.blacklist if x in environ['HTTP_USER_AGENT'].lower())):
... |
w, b = input().split()
w = int(w)
b = float(b)
if (w % 5 == 0 and b>(w+.5)):
b = b - w - 0.5
print('%.2f' % b)
else:
print('%.2f' % b) | (w, b) = input().split()
w = int(w)
b = float(b)
if w % 5 == 0 and b > w + 0.5:
b = b - w - 0.5
print('%.2f' % b)
else:
print('%.2f' % b) |
# ======================================================================= #
# Copyright (C) 2020 Hoverset Group. #
# ======================================================================= #
"""
A store and manager for all application functions and routines
"""
class Routine:
... | """
A store and manager for all application functions and routines
"""
class Routine:
"""
Representation of an action available throughout the lifetime
of a hoverset application
* **key**: A uniques string value used to access the action
* **desc**: Long description of what the action does
* *... |
def valid_card(card):
return (
not sum(
[
d if i & 1 else d % 5 * 2 + d / 5
for i, d in enumerate(map(int, card.replace(" ", "")))
]
)
% 10
)
| def valid_card(card):
return not sum([d if i & 1 else d % 5 * 2 + d / 5 for (i, d) in enumerate(map(int, card.replace(' ', '')))]) % 10 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# html_templates.py
"""
##############
HTML Templates
##############
*Created on Wed Jun 01 2015 by A. Pahl*
A simple and pythonic templating library where every HTML tag is a function.
"""
# import time
# import os.path as op
TABLE_OPTIONS = {"cellspacing": "1", "cell... | """
##############
HTML Templates
##############
*Created on Wed Jun 01 2015 by A. Pahl*
A simple and pythonic templating library where every HTML tag is a function.
"""
table_options = {'cellspacing': '1', 'cellpadding': '1', 'border': '1', 'align': '', 'height': '60px', 'summary': 'Table'}
page_options = {'icon': '... |
def XPLMFindCommand(command):
return 1
def XPLMCommandOnce(commandID):
pass
| def xplm_find_command(command):
return 1
def xplm_command_once(commandID):
pass |
# Copyright Least Authority Enterprises.
# See LICENSE for details.
"""
Tests for ``txkube.testing``.
"""
| """
Tests for ``txkube.testing``.
""" |
SERVICE_KPI_HOOK = (u"kpi_hook", u"KPI Hook POST")
SERVICE_CHOICES = (
SERVICE_KPI_HOOK,
)
default_app_config = "onadata.apps.restservice.app.RestServiceConfig"
| service_kpi_hook = (u'kpi_hook', u'KPI Hook POST')
service_choices = (SERVICE_KPI_HOOK,)
default_app_config = 'onadata.apps.restservice.app.RestServiceConfig' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2020
Day 22, Part 2
"""
def play_game(player1, player2):
seen = {1: [], 2: []}
while True:
if len(player1) == 0:
winner = 2
break
if len(player2) == 0:
winner = 1
break
if... | """
Advent of Code 2020
Day 22, Part 2
"""
def play_game(player1, player2):
seen = {1: [], 2: []}
while True:
if len(player1) == 0:
winner = 2
break
if len(player2) == 0:
winner = 1
break
if player1 in seen[1] or player2 in seen[2]:
... |
# ---- ratings ----
urlpatterns += patterns('',
(r'^ratings/', include('ratings.urls')),
) | urlpatterns += patterns('', ('^ratings/', include('ratings.urls'))) |
# Total Purchase
# Simple Regsiter Program
print("In the fields below, enter the prices of five items")
totalAmount = float(input("What is the price of the first item? "))
totalAmount += float(input("What is the price of the second item? "))
totalAmount += float(input("What is the price of the third item? "))
totalAmo... | print('In the fields below, enter the prices of five items')
total_amount = float(input('What is the price of the first item? '))
total_amount += float(input('What is the price of the second item? '))
total_amount += float(input('What is the price of the third item? '))
total_amount += float(input('What is the price of... |
n = int(input())
ans = n//4*"abcd"
if n%4==1:
ans += "a"
elif n%4==2:
ans += "ab"
elif n%4==3:
ans += "abc"
print(ans)
| n = int(input())
ans = n // 4 * 'abcd'
if n % 4 == 1:
ans += 'a'
elif n % 4 == 2:
ans += 'ab'
elif n % 4 == 3:
ans += 'abc'
print(ans) |
# Trigger: com.android.internal.telephony.gsm.GSMPhone.handleMessage(Landroid/os/Message;)V
# Callback: android.content.Context.sendOrderedBroadcast(Landroid/content/Intent;Ljava/lang/String;ILandroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V
IFAv0 = Int('IFAv0') # <Inpu... | if_av0 = int('IFAv0')
s.add(IFAv0 == 16) |
LOGFILE = '/tmp/robots.log'
def log(msg):
with open(LOGFILE, 'a') as f:
f.write(str(msg)+'\n')
| logfile = '/tmp/robots.log'
def log(msg):
with open(LOGFILE, 'a') as f:
f.write(str(msg) + '\n') |
# user defined-exceptions
# an exception class, that will serve as the base file for calculations
class CalculatorError(Exception):
""" Base class for my exception handlers for the calculator class\n
None value may be returned after a calculation, when an exception is
caught """
pass
| class Calculatorerror(Exception):
""" Base class for my exception handlers for the calculator class
None value may be returned after a calculation, when an exception is
caught """
pass |
## Beginner Series #2 Clock
## 8 kyu
## https://www.codewars.com/kata/55f9bca8ecaa9eac7100004a
def past(h, m, s):
hours = h * 60 * 60 * 1000
minutes = m * 60 * 1000
seconds = s * 1000
return hours + minutes + seconds
| def past(h, m, s):
hours = h * 60 * 60 * 1000
minutes = m * 60 * 1000
seconds = s * 1000
return hours + minutes + seconds |
class HashTable:
def __init__(self, size: int):
if size < 1:
raise IndexError('Size of hashtable should be minimum 1')
self.size = size
self.data = [None] * size
def _hash(self, key):
hash_data = 0
for i in range(len(key)):
hash_data = (hash_data ... | class Hashtable:
def __init__(self, size: int):
if size < 1:
raise index_error('Size of hashtable should be minimum 1')
self.size = size
self.data = [None] * size
def _hash(self, key):
hash_data = 0
for i in range(len(key)):
hash_data = (hash_dat... |
miles = 1000.0 # A floating point
name = "John" # A string
print(miles)
print(name)
| miles = 1000.0
name = 'John'
print(miles)
print(name) |
class ScriptPlatformScriptGen:
def __init__(self):
pass
def GenerateScriptStart(self):
Script = "var layers = null;\r\n"
Script += "var filePath = activeDocument.fullName.path;\r\n"
Script += "var newDoc = app.activeDocument.duplicate();\r\n"
Script += "... | class Scriptplatformscriptgen:
def __init__(self):
pass
def generate_script_start(self):
script = 'var layers = null;\r\n'
script += 'var filePath = activeDocument.fullName.path;\r\n'
script += 'var newDoc = app.activeDocument.duplicate();\r\n'
script += 'app.activeDocu... |
class MyClass:
pass
var: [MyClass] = MyClass() | class Myclass:
pass
var: [MyClass] = my_class() |
"""Re-export of some bazel rules with repository-wide defaults."""
load("@build_bazel_rules_typescript//:defs.bzl", _ts_library = "ts_library")
load("//packages/bazel:index.bzl", _ng_module = "ng_module")
DEFAULT_TSCONFIG = "//packages:tsconfig-build.json"
def ts_library(tsconfig = None, **kwargs):
if not tsconfig:... | """Re-export of some bazel rules with repository-wide defaults."""
load('@build_bazel_rules_typescript//:defs.bzl', _ts_library='ts_library')
load('//packages/bazel:index.bzl', _ng_module='ng_module')
default_tsconfig = '//packages:tsconfig-build.json'
def ts_library(tsconfig=None, **kwargs):
if not tsconfig:
... |
## Get the mean of an array
## 8 kyu
## https://www.codewars.com/kata/563e320cee5dddcf77000158
def get_average(marks):
return sum(marks) // len(marks)
| def get_average(marks):
return sum(marks) // len(marks) |
def main():
s=[]
minlen = 257
n=int(input())
for i in range(n):
s.append(list(input()))
s[i].reverse()
if len(s[i])<minlen: minlen = len(s[i])
kuchiguse = 0
nai = False
for i in range(minlen):
same = True
for j in range(1,n):
if s[j][i] !=... | def main():
s = []
minlen = 257
n = int(input())
for i in range(n):
s.append(list(input()))
s[i].reverse()
if len(s[i]) < minlen:
minlen = len(s[i])
kuchiguse = 0
nai = False
for i in range(minlen):
same = True
for j in range(1, n):
... |
lorem_file = open("lorem.txt")
for line in lorem_file:
print(line.rstrip())
lorem_file.close()
| lorem_file = open('lorem.txt')
for line in lorem_file:
print(line.rstrip())
lorem_file.close() |
class Articles:
'''
articles class to define article objects
'''
def __init__(self,id,author,description,url,urlToImage,publishedAt,content):
self.id = id
self.author = author
self.description = description
self.url = url
self.urlToImage = urlToImage
self.... | class Articles:
"""
articles class to define article objects
"""
def __init__(self, id, author, description, url, urlToImage, publishedAt, content):
self.id = id
self.author = author
self.description = description
self.url = url
self.urlToImage = urlToImage
... |
#Activity 9
def factorial(n):
f = 1
for i in range (1, n + 1):
f = f * i
return f
def pascal(n):
for i in range (n):
for j in range (1, n - i):
print(" ", end = '')
for k in range (0, i + 1):
c = int(factorial(i) / (factorial(k) * factorial(i-k)))
... | def factorial(n):
f = 1
for i in range(1, n + 1):
f = f * i
return f
def pascal(n):
for i in range(n):
for j in range(1, n - i):
print(' ', end='')
for k in range(0, i + 1):
c = int(factorial(i) / (factorial(k) * factorial(i - k)))
print(' ', ... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
for i in range(0, 6):
if i == 3:
print("skip 3")
continue
print(i)
# In[3]:
for i in range(0, 6):
if i == 3:
print("skip 3")
break
print(i)
| for i in range(0, 6):
if i == 3:
print('skip 3')
continue
print(i)
for i in range(0, 6):
if i == 3:
print('skip 3')
break
print(i) |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'conditions': [
['OS=="android"', {
'targets': [
{
'target_name': 'native_test_apk',
'message': 'building nativ... | {'conditions': [['OS=="android"', {'targets': [{'target_name': 'native_test_apk', 'message': 'building native test apk', 'type': 'none', 'dependencies': ['native_test_native_code'], 'actions': [{'action_name': 'native_test_apk', 'inputs': ['<(DEPTH)/testing/android/native_test_apk.xml', '<!@(find <(DEPTH)/testing/andro... |
def declarations(declaration):
if len(declaration[2][0]) > 1:
string = '%s _%s[%s];\n' %(
declaration[3][0],
declaration[0],
']['.join([
str(int(ranges[2]) - int(ranges[1]) + 1)
for ranges in declaration[2]
if len(ranges) > 1
])
)
string += '%s __%s(void) {\n' %(
declaration[3][0],
... | def declarations(declaration):
if len(declaration[2][0]) > 1:
string = '%s _%s[%s];\n' % (declaration[3][0], declaration[0], ']['.join([str(int(ranges[2]) - int(ranges[1]) + 1) for ranges in declaration[2] if len(ranges) > 1]))
string += '%s __%s(void) {\n' % (declaration[3][0], declaration[0])
... |
class RainyRoad:
def isReachable(self, road):
for i, j in zip(*road):
if i == j == 'W':
return 'NO'
return 'YES'
| class Rainyroad:
def is_reachable(self, road):
for (i, j) in zip(*road):
if i == j == 'W':
return 'NO'
return 'YES' |
data_path = '../data'
app_path = '../web-app'
naics_dict = {
'11': 'Agriculture, Forestry, Fishing, and Hunting',
'21': 'Mining, Quarrying, and Oil and Gas Extraction',
'22': 'Utilities',
'23': 'Construction',
'31': 'Manufacturing',
'32': 'Manufacturing',
'33': 'Manufacturing',
'42': '... | data_path = '../data'
app_path = '../web-app'
naics_dict = {'11': 'Agriculture, Forestry, Fishing, and Hunting', '21': 'Mining, Quarrying, and Oil and Gas Extraction', '22': 'Utilities', '23': 'Construction', '31': 'Manufacturing', '32': 'Manufacturing', '33': 'Manufacturing', '42': 'Wholesale Trade', '44': 'Retail Tra... |
sample_sizes = [100, 500, 1000, 5000, 10000, 15000, y.size]
scores_sample_sizes = {}
rng = np.random.RandomState(0)
for n_samples in sample_sizes:
sample_idx = rng.choice(
np.arange(y.size), size=n_samples, replace=False
)
X_sampled, y_sampled = X.iloc[sample_idx], y[sample_idx]
size, score = m... | sample_sizes = [100, 500, 1000, 5000, 10000, 15000, y.size]
scores_sample_sizes = {}
rng = np.random.RandomState(0)
for n_samples in sample_sizes:
sample_idx = rng.choice(np.arange(y.size), size=n_samples, replace=False)
(x_sampled, y_sampled) = (X.iloc[sample_idx], y[sample_idx])
(size, score) = make_cv_an... |
'''Given: A DNA string s
s
of length at most 1000 nt.
Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s
'''
s = 'AGACTCGCGCACTCACGATGAATCCCAAGACAGCCTGGCGGAGTATGGTACTACGGCCGTCCTCACCAAGGCATTTCGGTCCGAGTAGCGGATTGTGTGCCAGCCCTGAGGGCGAGTTA... | """Given: A DNA string s
s
of length at most 1000 nt.
Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s
"""
s = 'AGACTCGCGCACTCACGATGAATCCCAAGACAGCCTGGCGGAGTATGGTACTACGGCCGTCCTCACCAAGGCATTTCGGTCCGAGTAGCGGATTGTGTGCCAGCCCTGAGGGCGAGTTAT... |
# 200020001
if 2400 == chr.getJob():
sm.warp(915010000, 1)# should be instance ?
elif 2410 <= chr.getJob() <= 2411:
sm.warp(915020000, 2)
else:
sm.chat("Only Phantoms can enter.")
sm.dispose()
| if 2400 == chr.getJob():
sm.warp(915010000, 1)
elif 2410 <= chr.getJob() <= 2411:
sm.warp(915020000, 2)
else:
sm.chat('Only Phantoms can enter.')
sm.dispose() |
[
{'base_name': 'HEASARC_swiftmastr',
'service_type': 'tap',
'access_url': 'https://heasarc.gsfc.nasa.gov/xamin/vo/tap',
'adql':'''
SELECT
*
FROM swiftmastr
WHERE
1=CONTAINS(POINT('ICRS', ra, dec),
CIRCLE('ICRS', {}, {}, {}))
'''
}
]
| [{'base_name': 'HEASARC_swiftmastr', 'service_type': 'tap', 'access_url': 'https://heasarc.gsfc.nasa.gov/xamin/vo/tap', 'adql': "\nSELECT\n *\n FROM swiftmastr\n WHERE \n 1=CONTAINS(POINT('ICRS', ra, dec),\n CIRCLE('ICRS', {}, {}, {}))\n "}] |
#Los atributos describen las caracteristicas de los objetos, las clases es donde declaramos estos atributos,el atributo se utiliza segun las variables o tipos de datos que disponemos en python
# Metodos son acciones/funciones
# Constructor o inicializador para inicializar los objetos de una forma predeterminada que pod... | class Persona:
n_brazos = 0
n_piernas = 0
cabello = True
c_cabello = 'Defecto'
hambre = 0
def __init__(self):
self.nBrazos = 2
self.nPiernas = 2
def dormir():
pass
def comer(self):
self.hambre = 5
class Hombre(Persona):
nombre = 'Defecto'
sexo ... |
BATCH_SIZE = 16
PROPOSAL_NUM = 6
CAT_NUM = 4
INPUT_SIZE = (448, 448) # (w, h)
LR = 0.0001
WD = 1e-4
SAVE_FREQ = 1
resume = ''
test_model = './checkpoints/model.ckpt'
save_dir = './trainlog/'
| batch_size = 16
proposal_num = 6
cat_num = 4
input_size = (448, 448)
lr = 0.0001
wd = 0.0001
save_freq = 1
resume = ''
test_model = './checkpoints/model.ckpt'
save_dir = './trainlog/' |
# Problem: Group Anagrams
# Difficulty: Medium
# Category: String
# Leetcode 49: https://leetcode.com/problems/group-anagrams/description/
# Description:
"""
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","ta... | """
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
"""
class Solution(object):
def group_anagrams(self, strs):
if not strs:
... |
def _chomp_element(base, index, value):
"""Implementation of perl = and chomp on an array element"""
if value is None:
value = ''
base[index] = value.rstrip("\n")
return len(value) - len(base[index])
| def _chomp_element(base, index, value):
"""Implementation of perl = and chomp on an array element"""
if value is None:
value = ''
base[index] = value.rstrip('\n')
return len(value) - len(base[index]) |
class Credentials:
BASE_URL = "http://localhost:8080"
# Login Page
LOGIN_PAGE_TITLE = "OpenProject"
USERNAME = "admin"
PASSWORD = "qazwsxedcr"
# Home Page
HOME_PAGE_TITLE = "OpenProject"
HOME_PAGE_SELECTED_PROJECT = "TestProject1"
# New Project page
NEW_PROJECT_PAGE_TITLE = "N... | class Credentials:
base_url = 'http://localhost:8080'
login_page_title = 'OpenProject'
username = 'admin'
password = 'qazwsxedcr'
home_page_title = 'OpenProject'
home_page_selected_project = 'TestProject1'
new_project_page_title = 'New project | OpenProject'
new_project_name = 'Hello Wo... |
x1 = float(input("Enter x1: "))
y1 = float(input("Enter y1: "))
x2 = float(input("Enter x2: "))
y2 = float(input("Enter y2: "))
m = (y2 - y1) / (x2 - x1)
print("Gradient is {:g}".format(m))
c = y1 - (m * x1)
print("y-int is {:g}".format(c))
print("Equation: y = {:g}x + {:g}".format(m,c)) | x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
m = (y2 - y1) / (x2 - x1)
print('Gradient is {:g}'.format(m))
c = y1 - m * x1
print('y-int is {:g}'.format(c))
print('Equation: y = {:g}x + {:g}'.format(m, c)) |
# See https://developers.notion.com/reference/request-limits
RICH_TEXT_CONTENT_MAX_LENGTH = 2000
RICH_TEXT_LINK_MAX_LENGTH = 1000
EQUATION_EXPRESSION_MAX_LENGTH = 1000 | rich_text_content_max_length = 2000
rich_text_link_max_length = 1000
equation_expression_max_length = 1000 |
#---
def plotUAVcontrolSignals(df,plt):
## - Plot the Control Signals
fig, axs = plt.subplots(2,2, sharex=True)
fig.suptitle("Control Signals (Executed by the Drone)")
# ---------- u_\theta
axs[0,0].plot(df['time'], df['A.pSCU[0]'])
axs[0,0].set(ylabel=r'$u_{\theta}~$ [rad]')
axs[0,0].... | def plot_ua_vcontrol_signals(df, plt):
(fig, axs) = plt.subplots(2, 2, sharex=True)
fig.suptitle('Control Signals (Executed by the Drone)')
axs[0, 0].plot(df['time'], df['A.pSCU[0]'])
axs[0, 0].set(ylabel='$u_{\\theta}~$ [rad]')
axs[0, 0].grid(True)
axs[0, 0].set(xlim=(min(df['time']), max(df['t... |
def arr_pair_sum(arr, k):
# edge case
if len(arr) < 2:
return
# set for tracking
seen = set()
output = set()
for num in arr:
target = k - num
if target not in seen:
seen.add(num)
else:
output.add((min(num, target), max(num, target)))
... | def arr_pair_sum(arr, k):
if len(arr) < 2:
return
seen = set()
output = set()
for num in arr:
target = k - num
if target not in seen:
seen.add(num)
else:
output.add((min(num, target), max(num, target)))
return len(output)
print(arr_pair_sum([1,... |
def sanitize(time_string):
if "-" in time_string:
splitter = "-"
elif ":" in time_string:
splitter = ":"
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + "." + secs
with open("james.txt") as jaf:
data = jaf.readline()
james = sorted([sani... | def sanitize(time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return time_string
(mins, secs) = time_string.split(splitter)
return mins + '.' + secs
with open('james.txt') as jaf:
data = jaf.readline()
james = sorted([sanit... |
# Backport of str.removeprefix.
# TODO Remove when minimum python version is 3.9 or above
def removeprefix(string: str, prefix: str) -> str:
if string.startswith(prefix):
return string[len(prefix) :]
return string
| def removeprefix(string: str, prefix: str) -> str:
if string.startswith(prefix):
return string[len(prefix):]
return string |
# Some magic data values exist.
# They often represent missing data. More information can be found at the following link.
# https://www.census.gov/data/developers/data-sets/acs-1year/notes-on-acs-estimate-and-annotation-values.html
class Magic:
MISSING_VALUES = [
None,
-999999999,
-8888888... | class Magic:
missing_values = [None, -999999999, -888888888, -666666666, -555555555, -333333333, -222222222] |
"""
Author: Ioannis Paraskevakos
License: MIT
Copyright: 2018-2019
"""
# ------------------------------------------------------------------------------
# States
NEW = 0 # New campaign is submitted
PLANNING = 1 # Planning the exeuction of the campaign
EXECUTING = 2 # At least one workflow is executing
DONE = 3 #... | """
Author: Ioannis Paraskevakos
License: MIT
Copyright: 2018-2019
"""
new = 0
planning = 1
executing = 2
done = 3
failed = 4
canceled = 5
cfinal = [DONE, FAILED, CANCELED]
state_dict = {0: 'NEW', 1: 'PLANNING', 2: 'EXECUTING', 3: 'DONE', 4: 'FAILED', 5: 'CANCELED'} |
class Tile (object):
""" This is the abstract representation of Tiles, the building blocks of the world."""
def __init__ (self, stage, x, y):
self.stage = stage
self.x = x
self.y = y
"initializes the tile with a random type from the types list"
self.tile_type = self.st... | class Tile(object):
""" This is the abstract representation of Tiles, the building blocks of the world."""
def __init__(self, stage, x, y):
self.stage = stage
self.x = x
self.y = y
'initializes the tile with a random type from the types list'
self.tile_type = self.stage.... |
def sample(task):
if task is not logistic:
raise NotImplementedError
# Parametric Generator for Logistic Regression Task (TODO: Generalize for Task - Parameter Specification)
theta = [np.random.uniform( 1, 10),
np.random.uniform( 1, 10),
np.random.uniform(-1, 1)]
return task(samp... | def sample(task):
if task is not logistic:
raise NotImplementedError
theta = [np.random.uniform(1, 10), np.random.uniform(1, 10), np.random.uniform(-1, 1)]
return (task(sample_space, theta), theta)
def sample_points(task, batch_size):
idx = np.random.choice(np.arange(len(sample_space)), batch_s... |
def read_input():
joltages = []
with open('day10_input.txt') as input_file:
for line in input_file:
line = line.strip()
joltages.append( int(line) )
return joltages
# Find a chain that uses all of your adapters to connect the charging outlet
# to your device's built-in adap... | def read_input():
joltages = []
with open('day10_input.txt') as input_file:
for line in input_file:
line = line.strip()
joltages.append(int(line))
return joltages
def part1(joltages):
diffs = [0, 0, 0, 1]
for i in range(1, len(joltages)):
diff = joltages[i] -... |
class Solution:
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
last, n, y = chars[0], 1, 0
for x in range(1, len(chars)):
c = chars[x]
if c == last: n += 1
else:
for ch in last + str(n > 1 and ... | class Solution:
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
(last, n, y) = (chars[0], 1, 0)
for x in range(1, len(chars)):
c = chars[x]
if c == last:
n += 1
else:
for ch in ... |
def main(request, response):
response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin"))
token = request.GET[b"token"]
request.server.stash.put(token, b"")
response.content = b"PASS"
| def main(request, response):
response.headers.set(b'Access-Control-Allow-Origin', request.headers.get(b'origin'))
token = request.GET[b'token']
request.server.stash.put(token, b'')
response.content = b'PASS' |
def iterate_dictionary(d, path, squash_single=False):
"""
Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of objects found at all leaf nodes at all trajectories `dict[A][B][C][D]`. It does this using BFS not DFS.
The word "leaf" hereby refers to an item at the search path l... | def iterate_dictionary(d, path, squash_single=False):
"""
Takes a dict, and a path delimited with slashes like A/B/C/D, and returns a list of objects found at all leaf nodes at all trajectories `dict[A][B][C][D]`. It does this using BFS not DFS.
The word "leaf" hereby refers to an item at the search path l... |
class Address:
def __init__(self, street_address, city, country):
self.country = country
self.city = city
self.street_address = street_address
def __str__(self):
return f'{self.street_address}, {self.city}, {self.country}'
| class Address:
def __init__(self, street_address, city, country):
self.country = country
self.city = city
self.street_address = street_address
def __str__(self):
return f'{self.street_address}, {self.city}, {self.country}' |
def extractBetwixtedtranslationsBlogspotCom(item):
'''
Parser for 'betwixtedtranslations.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Transmigrated Senior Martial Brother', ... | def extract_betwixtedtranslations_blogspot_com(item):
"""
Parser for 'betwixtedtranslations.blogspot.com'
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [('Transmigrated Senior ... |
#
# This file contains the Python code from Program 16.20 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_20.txt
#
class Algorithms(... | class Algorithms(object):
class Earliesttimevisitor(Visitor):
def __init__(self, earliestTime):
super(Algorithms.EarliestTimeVisitor, self).__init__()
self._earliestTime = earliestTime
def visit(self, w):
t = self._earliestTime[0]
for e in w.inciden... |
day_num = 15
file_load = open("input/day15.txt", "r")
file_in = file_load.read()
file_load.close()
file_in = list(map(int, file_in.split(",")))
def run():
def game(input_in, round_hunt):
num_last = {}
for temp_pos, temp_num in enumerate(input_in, 1):
num_last[temp_num] = temp_pos
game_round ... | day_num = 15
file_load = open('input/day15.txt', 'r')
file_in = file_load.read()
file_load.close()
file_in = list(map(int, file_in.split(',')))
def run():
def game(input_in, round_hunt):
num_last = {}
for (temp_pos, temp_num) in enumerate(input_in, 1):
num_last[temp_num] = temp_pos
... |
def findDuplicatesSequence(sequence):
stringySequence = str(sequence)
while stringySequence[0] == stringySequence[-1]:
stringySequence = stringySequence[-1] + stringySequence[0:-1]
iterableSequenceDuplicates = (re.finditer(r"(\d)\1+", str(stringySequence)))
duplicatesList = [iterable[0] for iter... | def find_duplicates_sequence(sequence):
stringy_sequence = str(sequence)
while stringySequence[0] == stringySequence[-1]:
stringy_sequence = stringySequence[-1] + stringySequence[0:-1]
iterable_sequence_duplicates = re.finditer('(\\d)\\1+', str(stringySequence))
duplicates_list = [iterable[0] fo... |
"""
Given a list of words, find all pairs of unique indices such that the concatenation
of the two words is a palindrome.
For example, given the list ["code", "edoc", "da", "d"], return [(0, 1), (1, 0), (2, 3)].
"""
test = ['code', 'edoc', 'da', 'd']
palindrome_index = []
for i in range(len(test)):
for j in range... | """
Given a list of words, find all pairs of unique indices such that the concatenation
of the two words is a palindrome.
For example, given the list ["code", "edoc", "da", "d"], return [(0, 1), (1, 0), (2, 3)].
"""
test = ['code', 'edoc', 'da', 'd']
palindrome_index = []
for i in range(len(test)):
for j in range(... |
#
# PySNMP MIB module NNCBELLCOREGR820DS1STATISTICS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NNCBELLCOREGR820DS1STATISTICS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:13:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ... |
cities = [
{
"city": "New York",
"growth_from_2000_to_2013": "4.8%",
"latitude": 40.7127837,
"longitude": -74.0059413,
"population": "8405837",
"rank": "1",
"state": "New York",
},
{
"city": "Los Angeles",
"growth_from_2000_to_2013": "4... | cities = [{'city': 'New York', 'growth_from_2000_to_2013': '4.8%', 'latitude': 40.7127837, 'longitude': -74.0059413, 'population': '8405837', 'rank': '1', 'state': 'New York'}, {'city': 'Los Angeles', 'growth_from_2000_to_2013': '4.8%', 'latitude': 34.0522342, 'longitude': -118.2436849, 'population': '3884307', 'rank':... |
class QualifierClassifier:
def __init__(self):
pass
@staticmethod
def get_qualifiers(act_state):
return {}
| class Qualifierclassifier:
def __init__(self):
pass
@staticmethod
def get_qualifiers(act_state):
return {} |
#def createUnitDict(filename):
# unit_info = dict()
# with open(filename, 'r') as unit_file:
# all_units = unit_file.readlines()
# for unit in all_units:
# unit = unit.split(",")
# unit_info[unit[1].split("\n")[0]] = int(unit[0])
# return unit_info
NUM_PROTOSS_ACTIONS = 70;
def getUnitData(units, unit_info):
u... | num_protoss_actions = 70
def get_unit_data(units, unit_info):
unit_list = units.split(']')
unit_list = unit_list[:len(unit_list) - 1]
unit_types = [0 for i in range(NUM_PROTOSS_ACTIONS)]
units_free = [0 for i in range(NUM_PROTOSS_ACTIONS)]
units_being_built = [0 for i in range(NUM_PROTOSS_ACTIONS)]... |
a=int(input("enter the first number:"))
b=int(input("enter the second number:"))
s=(a&b) #sum
print(s)
u=(a/b) #or
print(u)
k=(~a) #not
print(k)
m=(a^b) #x-or
print(m)
o=(a<<b) #left shift
print(o)
t=(a>>b) #right shift
print(t)
| a = int(input('enter the first number:'))
b = int(input('enter the second number:'))
s = a & b
print(s)
u = a / b
print(u)
k = ~a
print(k)
m = a ^ b
print(m)
o = a << b
print(o)
t = a >> b
print(t) |
"""
A person has X amount of money and wants to buy ice-creams. The cost of each ice-cream is Y.
For every purchase of ice-creams he gets 1 unit of money which could be used to buy ice-creams.
Find the number of ice-creams he can buy.
"""
class Solution:
def approach2(self, money, cost_per_ice):
ans = 0
... | """
A person has X amount of money and wants to buy ice-creams. The cost of each ice-cream is Y.
For every purchase of ice-creams he gets 1 unit of money which could be used to buy ice-creams.
Find the number of ice-creams he can buy.
"""
class Solution:
def approach2(self, money, cost_per_ice):
ans = 0
... |
class solve_day(object):
with open('inputs/day07.txt', 'r') as f:
data = f.readlines()
# method for NOT operation
def n(self, value):
return 65535 + ~value + 1
def part1(self):
wires = {}
for d in self.data:
d = d.strip()
# print(f'input: \t\... | class Solve_Day(object):
with open('inputs/day07.txt', 'r') as f:
data = f.readlines()
def n(self, value):
return 65535 + ~value + 1
def part1(self):
wires = {}
for d in self.data:
d = d.strip()
try:
operator = [x for x in ['AND', 'OR... |
# Function which adds two numbers
def compute(num1, num2):
return (num1 + num2)
| def compute(num1, num2):
return num1 + num2 |
def majuscule(chaine):
whitelist = "abcdefghijklmnopqrstuvwxyz"
chrs = [chr(ord(c) - 32) if c in whitelist else c for c in chaine]
return "".join(chrs)
print(majuscule("axel coezard"))
def val2ascii(entier):
ch = ""
for i in range(entier):
ch = chr(ord(ch) + 1)
print(ch)
val2ascii(355... | def majuscule(chaine):
whitelist = 'abcdefghijklmnopqrstuvwxyz'
chrs = [chr(ord(c) - 32) if c in whitelist else c for c in chaine]
return ''.join(chrs)
print(majuscule('axel coezard'))
def val2ascii(entier):
ch = ''
for i in range(entier):
ch = chr(ord(ch) + 1)
print(ch)
val2ascii(355) |
class Node(object):
def __init__(self,data):
self.data = data
self.prev = None
self.next = None
class DoubleLinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def prepend(self,data):
node = Node(data)
if not self.head:
... | class Node(object):
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class Doublelinkedlist(object):
def __init__(self):
self.head = None
self.tail = None
def prepend(self, data):
node = node(data)
if not self.head:
... |
# Copyright [2019] [Christopher Syben, Markus Michen]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | learning_rate = 1e-05
batch_size_train = 50
num_training_samples = 800
max_train_steps = NUM_TRAINING_SAMPLES // BATCH_SIZE_TRAIN + 1
batch_size_validation = 50
num_validation_samples = 150
max_validation_steps = NUM_VALIDATION_SAMPLES // BATCH_SIZE_VALIDATION
num_test_samples = 1
max_test_steps = NUM_TEST_SAMPLES
max_... |
BOOLEAN_OPTION_TYPE = ['false', 'true']
# Extracted from the documentation of clang-format version 13
# https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormatStyleOptions.html
ALL_TUNEABLE_OPTIONS = {
'AccessModifierOffset': ['0', '-1', '-2', '-3', '-4'],
'AlignAfterOpenBracket': ['DontAlign', 'Align', ... | boolean_option_type = ['false', 'true']
all_tuneable_options = {'AccessModifierOffset': ['0', '-1', '-2', '-3', '-4'], 'AlignAfterOpenBracket': ['DontAlign', 'Align', 'AlwaysBreak'], 'AlignArrayOfStructures': ['None', 'Left', 'Right'], 'AlignConsecutiveAssignments': ['None', 'Consecutive', 'AcrossEmptyLines', 'AcrossCo... |
{
'variables': {
'node_shared_openssl%': 'true'
},
'targets': [
{
'target_name': 'ed25519',
'sources': [
'src/ed25519/keypair.c',
'src/ed25519/sign.c',
'src/ed25519/open.c',
'src/ed25519/crypto... | {'variables': {'node_shared_openssl%': 'true'}, 'targets': [{'target_name': 'ed25519', 'sources': ['src/ed25519/keypair.c', 'src/ed25519/sign.c', 'src/ed25519/open.c', 'src/ed25519/crypto_verify_32.c', 'src/ed25519/ge_double_scalarmult.c', 'src/ed25519/ge_frombytes.c', 'src/ed25519/ge_scalarmult_base.c', 'src/ed25519/g... |
def issorted(str1, str2):
if len(str1) != len(str2):
return False
bool_b1 = [0] * 256
bool_b2 = [0] * 256
for i in range(len(str1)):
bool_b1[ord(str1[i])] += 1
bool_b2[ord(str2[i])] += 1
if bool_b1 == bool_b2:
return True
else:
return False
#... | def issorted(str1, str2):
if len(str1) != len(str2):
return False
bool_b1 = [0] * 256
bool_b2 = [0] * 256
for i in range(len(str1)):
bool_b1[ord(str1[i])] += 1
bool_b2[ord(str2[i])] += 1
if bool_b1 == bool_b2:
return True
else:
return False
print(issorted(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 28 13:30:29 2021
@author: jr3
"""
"""
Write a Python program that takes as input a file containing DNA sequences in multi-FASTA format,
and computes the answers to the following questions.
You can choose to write one program with multiple func... | """
Created on Tue Sep 28 13:30:29 2021
@author: jr3
"""
"\nWrite a Python program that takes as input a file containing DNA sequences in multi-FASTA format, \nand computes the answers to the following questions. \n\nYou can choose to write one program with multiple functions to answer these questions, \nor you can ... |
class Event:
def __init__(self, name, payload):
self.name = name
self.payload = payload
| class Event:
def __init__(self, name, payload):
self.name = name
self.payload = payload |
alphabet = "abcdefghijklmnopqrstuvwxyz"
class Scrambler():
"""
Class to represent a rotor in the machine.
"""
def __init__(self, mapping, step_orientation=[0], orientation=0):
self.orientation = orientation # integer representing current orientation of scrambler
self.m = mapping # li... | alphabet = 'abcdefghijklmnopqrstuvwxyz'
class Scrambler:
"""
Class to represent a rotor in the machine.
"""
def __init__(self, mapping, step_orientation=[0], orientation=0):
self.orientation = orientation
self.m = mapping
self.inverse_m = self.calculate_inverse_m()
self... |
class Solution:
def numDecodings(self, s):
if not s:
return 0
second_last, last = 0, 1
for i, ch in enumerate(s):
ways = 0
curr = int(ch)
# current number is not 0
if curr:
# there is at least one way to decode
... | class Solution:
def num_decodings(self, s):
if not s:
return 0
(second_last, last) = (0, 1)
for (i, ch) in enumerate(s):
ways = 0
curr = int(ch)
if curr:
ways = last
if i:
prev = int(s[i - 1]... |
def Divide(a,b):
try:
return (a/b)
except ZeroDivisionError:
print("\nHey!Dont be insane!\n")
def Rem(a,b):
try:
return (a%b)
except ZeroDivisionError:
print("\nHey!Dont be insane!\n")
print("Enter Operand1:\n")
oper1=float(input())
print("Enter Operand2:\n")
oper2=float(input... | def divide(a, b):
try:
return a / b
except ZeroDivisionError:
print('\nHey!Dont be insane!\n')
def rem(a, b):
try:
return a % b
except ZeroDivisionError:
print('\nHey!Dont be insane!\n')
print('Enter Operand1:\n')
oper1 = float(input())
print('Enter Operand2:\n')
oper2 =... |
#global Variable
x = 100
def fun(x):
#local scope of variable
x = 3 + 2
return x
local = fun(x)
print(local)
print(x) | x = 100
def fun(x):
x = 3 + 2
return x
local = fun(x)
print(local)
print(x) |
sqrt = lambda n: n ** .5
sqrt_5 = sqrt(5)
phi = (1 + sqrt_5) / 2
psi = (1 - sqrt_5) / 2
fibonacci = lambda n: int(round((phi ** n - psi ** n) / sqrt_5))
for n in range(-12, 12):
print(fibonacci(n))
| sqrt = lambda n: n ** 0.5
sqrt_5 = sqrt(5)
phi = (1 + sqrt_5) / 2
psi = (1 - sqrt_5) / 2
fibonacci = lambda n: int(round((phi ** n - psi ** n) / sqrt_5))
for n in range(-12, 12):
print(fibonacci(n)) |
class Solution(object):
def calcEquation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
key_pairs = {}
value_pairs = {}
for i in xrange(le... | class Solution(object):
def calc_equation(self, equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
key_pairs = {}
value_pairs = {}
for i in xrange(... |
def originalSystemPrettyPrint():
var = "Original System \n\ny1' = 7 y3 + 4.5 y5 + -19.5 y1^2 -9.5 y1 y2 + -10 y1 y5 + -9.75 y1 y3 -9.75 y1 y4\n" + \
"y2' = 9 y4 + 4.5 y5 + -6 y2^2 -9.5 y1 y2 + -10 y3 y2 + -4 y5 y2 -1.75 y2 y4\n" + \
"y3' = 9.75 y1^2 -3.5 y3 + -9.75 y1 y3 + -19.5 y3^2 -10 y3 y2\n... | def original_system_pretty_print():
var = "Original System \n\ny1' = 7 y3 + 4.5 y5 + -19.5 y1^2 -9.5 y1 y2 + -10 y1 y5 + -9.75 y1 y3 -9.75 y1 y4\n" + "y2' = 9 y4 + 4.5 y5 + -6 y2^2 -9.5 y1 y2 + -10 y3 y2 + -4 y5 y2 -1.75 y2 y4\n" + "y3' = 9.75 y1^2 -3.5 y3 + -9.75 y1 y3 + -19.5 y3^2 -10 y3 y2\n" + "y4' = 8 y2^2 -4.... |
class DataQueue:
def __init__(self):
self.data = []
def Add(self, unitData):
self.Enqueue(unitData)
self.Dequeue()
def Enqueue(self, unitData):
self.data.append(unitData)
def Dequeue(self):
self.data.pop(0) | class Dataqueue:
def __init__(self):
self.data = []
def add(self, unitData):
self.Enqueue(unitData)
self.Dequeue()
def enqueue(self, unitData):
self.data.append(unitData)
def dequeue(self):
self.data.pop(0) |
QUIT_MSG = "go home, you're drunk"
class CreativeQuitPlugin(object):
name = "Creative quit plugin"
def __init__(self, bot_instance):
self.bot_instance = bot_instance
def leave(self, user, channel):
"""
Wrapper around bot quit, since we have extra args per
the plugin inter... | quit_msg = "go home, you're drunk"
class Creativequitplugin(object):
name = 'Creative quit plugin'
def __init__(self, bot_instance):
self.bot_instance = bot_instance
def leave(self, user, channel):
"""
Wrapper around bot quit, since we have extra args per
the plugin interf... |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
if not matrix:
print()
else:
for row in range(len(matrix)):
for item in range(len(matrix[row])):
if item != len(matrix[row]) - 1:
endspace = ' '
else:
end... | def print_matrix_integer(matrix=[[]]):
if not matrix:
print()
else:
for row in range(len(matrix)):
for item in range(len(matrix[row])):
if item != len(matrix[row]) - 1:
endspace = ' '
else:
endspace = ''
... |
value = int(input())
def dumb_fib(n):
if n < 3:
return 1
else:
return dumb_fib(n - 1) + dumb_fib(n - 2)
print(dumb_fib(value + 1))
| value = int(input())
def dumb_fib(n):
if n < 3:
return 1
else:
return dumb_fib(n - 1) + dumb_fib(n - 2)
print(dumb_fib(value + 1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.