content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... | class Pointdataview:
def __init__(self, javaPointDataView):
self.__javaPdv = javaPointDataView
self.__keys = []
keyset = self.__javaPdv.getContainer().getParameters()
itr = keyset.iterator()
while itr.hasNext():
self.__keys.append(str(itr.next()))
def __geti... |
def hypotenuse_triangle(side1, side2):
hypotenuse = side1 ** 2 + side2 ** 2
return hypotenuse
print(hypotenuse_triangle(2, 4))
| def hypotenuse_triangle(side1, side2):
hypotenuse = side1 ** 2 + side2 ** 2
return hypotenuse
print(hypotenuse_triangle(2, 4)) |
# Tuplas sao imutaveis, nao se pode substituir um valor enquanto o programa estiver rodando
# oq foi definido no inicio permanece ate o final
lanche = ('hamburguer', 'pizza', 'suco', 'refri')
print(lanche[1])
print(lanche[-1]) #-1 mostra o ultimo elemento
print(sorted(lanche)) #para organizar a lista em ordem alfa... | lanche = ('hamburguer', 'pizza', 'suco', 'refri')
print(lanche[1])
print(lanche[-1])
print(sorted(lanche))
for comida in lanche:
print(f'comi bastante {comida}')
print('estou gordo')
for cont in range(0, len(lanche)):
print(cont)
print('fim')
for food in range(0, len(lanche)):
print(lanche[food], f'na posic... |
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
zeroindex = -1
for i in range(n):
if nums[i] == 0 and zeroindex == -1:
zeroi... | class Solution:
def move_zeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
zeroindex = -1
for i in range(n):
if nums[i] == 0 and zeroindex == -1:
zero... |
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def shiftGrid(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def rotate(grids, k):
def reverse(grid, start, end):
while start < end:
... | class Solution(object):
def shift_grid(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def rotate(grids, k):
def reverse(grid, start, end):
while start < end:
(start_r, start_c... |
FULL_ACCESS_GMAIL_SCOPE = "https://mail.google.com/"
LABELS_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.labels"
SEND_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
READ_ONLY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"
COMPOSE_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.c... | full_access_gmail_scope = 'https://mail.google.com/'
labels_gmail_scope = 'https://www.googleapis.com/auth/gmail.labels'
send_gmail_scope = 'https://www.googleapis.com/auth/gmail.send'
read_only_gmail_scope = 'https://www.googleapis.com/auth/gmail.readonly'
compose_gmail_scope = 'https://www.googleapis.com/auth/gmail.c... |
def read():
x = int(input())
return x
a = read()
b = read()
c = read()
d = read()
if b == c and b + c == d and b + c + d == a:
print("S")
else:
print("N")
| def read():
x = int(input())
return x
a = read()
b = read()
c = read()
d = read()
if b == c and b + c == d and (b + c + d == a):
print('S')
else:
print('N') |
def test_home(client):
response = client.get('/')
#import pdb;pdb.set_trace()
assert response.status_code == 200
assert response.template_name == ['home.html']
| def test_home(client):
response = client.get('/')
assert response.status_code == 200
assert response.template_name == ['home.html'] |
# MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
HACKAGE_URL = 'https://hackage.haskell.org/package/%s/preferred.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('hackage', name)
data = await cache.get_json(HACKAGE_URL % key)
return data['normal-version']... | hackage_url = 'https://hackage.haskell.org/package/%s/preferred.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('hackage', name)
data = await cache.get_json(HACKAGE_URL % key)
return data['normal-version'][0] |
load(
"//scala:advanced_usage/providers.bzl",
_ScalaRulePhase = "ScalaRulePhase",
)
load(
"//scala/private:phases/phases.bzl",
_phase_bloop = "phase_bloop",
)
ext_add_phase_bloop = {
"attrs": {
# "bloopDir": attr.label(
# allow_single_file = True,
# doc = "Bloop output ... | load('//scala:advanced_usage/providers.bzl', _ScalaRulePhase='ScalaRulePhase')
load('//scala/private:phases/phases.bzl', _phase_bloop='phase_bloop')
ext_add_phase_bloop = {'attrs': {'_bloop': attr.label(cfg='host', default='//scala/bloop', executable=True)}, 'phase_providers': ['//scala/bloop:add_phase_bloop']}
def _a... |
angka = {
0: 'tepat',
1: 'satu',
2: 'dua',
3: 'tiga',
4: 'empat',
5: 'lima',
6: 'enam',
7: 'tujuh',
8: 'delapan',
9: 'sembilan',
10: 'sepuluh',
11: 'sebelas',
12: 'dua belas',
}
def eja(n):
lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat',
... | angka = {0: 'tepat', 1: 'satu', 2: 'dua', 3: 'tiga', 4: 'empat', 5: 'lima', 6: 'enam', 7: 'tujuh', 8: 'delapan', 9: 'sembilan', 10: 'sepuluh', 11: 'sebelas', 12: 'dua belas'}
def eja(n):
lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat', 'lima', 'enam', 'tujuh', 'delapan', 'sembilan', 'sepuluh', 'sebelas', 'dua belas'... |
"""
Expert list created from Kompetenzpool data.
List contains Microsoft Academic Graph Ids
"""
kompetenzpool_expert_list = {
"Internet of Things": [
2241467651,
673846798,
2236413454
],
"blockchain": {
1245553041,
2021103267,
},
"natural language proc... | """
Expert list created from Kompetenzpool data.
List contains Microsoft Academic Graph Ids
"""
kompetenzpool_expert_list = {'Internet of Things': [2241467651, 673846798, 2236413454], 'blockchain': {1245553041, 2021103267}, 'natural language processing': {2794237920, 2578689274}, 'autonomous driving': {2490080048, 2156... |
#!/usr/bin/env python
# coding: utf-8
# In[99]:
class TreeNode:
def __init__(self, val = None, par = None):
self.left = None
self.right = None
self.value = val
self.parent = par
def left_child(self):
return self.left
def right_child(self):
return self... | class Treenode:
def __init__(self, val=None, par=None):
self.left = None
self.right = None
self.value = val
self.parent = par
def left_child(self):
return self.left
def right_child(self):
return self.right
def set_value(self, val):
self.value =... |
ColorNames = \
{ u'aliceblue': (240, 248, 255),
u'antiquewhite': (250, 235, 215),
u'aqua': (0, 255, 255),
u'aquamarine': (127, 255, 212),
u'azure': (240, 255, 255),
u'beige': (245, 245, 220),
u'bisque': (255, 228, 196),
u'black': (0, 0, 0),
u'blanchedalmond': (255, 235, 205),
u'blu... | color_names = {u'aliceblue': (240, 248, 255), u'antiquewhite': (250, 235, 215), u'aqua': (0, 255, 255), u'aquamarine': (127, 255, 212), u'azure': (240, 255, 255), u'beige': (245, 245, 220), u'bisque': (255, 228, 196), u'black': (0, 0, 0), u'blanchedalmond': (255, 235, 205), u'blue': (0, 0, 255), u'blueviolet': (138, 43... |
# https://stackoverflow.com/questions/63626389/how-to-sort-points-along-a-hilbert-curve-without-using-hilbert-indices
N=9 # 9 points
n=2 # 2 dimension
m=3 # order of Hilbert curve
def BitTest(x,od):
result = x & (1 << od)
return int(bool(result))
def BitFlip(b,pos):
b ^= 1 << pos
return b
def partiti... | n = 9
n = 2
m = 3
def bit_test(x, od):
result = x & 1 << od
return int(bool(result))
def bit_flip(b, pos):
b ^= 1 << pos
return b
def partition(idx, A, st, en, od, ax, di):
i = st
j = en
while True:
while i < j and bit_test(A[i][ax], od) == di:
i = i + 1
while ... |
# Authorization data
host = '*****'
user = '*****'
passwd = '*****'
db = 'hr'
| host = '*****'
user = '*****'
passwd = '*****'
db = 'hr' |
#
# PySNMP MIB module ENTERASYS-VLAN-AUTHORIZATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-VLAN-AUTHORIZATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ... |
#!/usr/bin/env python
"""
_Step.Templates_
Package for containing Step Template implementations
"""
__all__ = []
| """
_Step.Templates_
Package for containing Step Template implementations
"""
__all__ = [] |
class BookStore:
def __init__(self, book):
self.booklst = book
class Book:
def __init__(self, title, author, chapter, price):
self.title = title
self.author = author
self.chapter = list(chapter)
self.price = int(price)
book1 = Book("han kubrat", "Tangra", ['1', '3', '... | class Bookstore:
def __init__(self, book):
self.booklst = book
class Book:
def __init__(self, title, author, chapter, price):
self.title = title
self.author = author
self.chapter = list(chapter)
self.price = int(price)
book1 = book('han kubrat', 'Tangra', ['1', '3', '4... |
"""submodopt - A package for maximizing submodular functions"""
__version__ = '0.1.0'
__author__ = 'Satwik Bhattamishra <satwik55@gmail.com>'
__all__ = []
| """submodopt - A package for maximizing submodular functions"""
__version__ = '0.1.0'
__author__ = 'Satwik Bhattamishra <satwik55@gmail.com>'
__all__ = [] |
# Contains the objects found on our user greetings page.
# Imports --------------------------------------------------------------------------------
# Page Objects ---------------------------------------------------------------------------
class PatientGreetingPageObject(object):
bio = 'This is a test bio.'
... | class Patientgreetingpageobject(object):
bio = 'This is a test bio.'
def get_current_feeling_buttons(self):
feeling1element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-0"]')
feeling2element = self.client.find_element_by_xpath('// *[ @ id = "current_feeling-1"]')
f... |
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
studentX=Boys.copy()
studentY=Girls.copy()
print(studentX)
print(studentY)
students = list(Dict.keys())
students.sort()
for s in students:
print(":".join((s,str(Dict[s]))))
| dict = {'Tim': 18, 'Charlie': 12, 'Tiffany': 22, 'Robert': 25}
boys = {'Tim': 18, 'Charlie': 12, 'Robert': 25}
girls = {'Tiffany': 22}
student_x = Boys.copy()
student_y = Girls.copy()
print(studentX)
print(studentY)
students = list(Dict.keys())
students.sort()
for s in students:
print(':'.join((s, str(Dict[s])))) |
"""Utilities for interacting with databases"""
def generate_connect_string(
host: str,
port: int,
db: str,
user: str,
password: str,
) -> str:
conn_string = f"postgresql://{user}:{password}@"
if not host.startswith('/'):
conn_string += f"{host}:{port}"
conn_string += f"/{db}"
... | """Utilities for interacting with databases"""
def generate_connect_string(host: str, port: int, db: str, user: str, password: str) -> str:
conn_string = f'postgresql://{user}:{password}@'
if not host.startswith('/'):
conn_string += f'{host}:{port}'
conn_string += f'/{db}'
if host.startswith('/... |
class RaiseException:
def __init__(self, exception: Exception):
self.exception = exception
| class Raiseexception:
def __init__(self, exception: Exception):
self.exception = exception |
EVENT_ALGO_LOG = "eAlgoLog"
EVENT_ALGO_SETTING = "eAlgoSetting"
EVENT_ALGO_VARIABLES = "eAlgoVariables"
EVENT_ALGO_PARAMETERS = "eAlgoParameters"
APP_NAME = "AlgoTrading"
| event_algo_log = 'eAlgoLog'
event_algo_setting = 'eAlgoSetting'
event_algo_variables = 'eAlgoVariables'
event_algo_parameters = 'eAlgoParameters'
app_name = 'AlgoTrading' |
class AminoAcid:
def __init__(self,name='AA'):
self.name = name
self.name3L = ''
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # ... | class Aminoacid:
def __init__(self, name='AA'):
self.name = name
self.name3L = ''
self.Hydrophobic = 0
self.charge = 0
self.polar = 0
self.corner = 0
self.loop = 0
self.size = 0
self.SpecialRes = {0: 0}
self.ResWeight = 0
self.... |
initialized = True
class TestFrozenUtf8_1:
"""\u00b6"""
class TestFrozenUtf8_2:
"""\u03c0"""
class TestFrozenUtf8_4:
"""\U0001f600"""
def main():
print("Hello world!")
if __name__ == '__main__':
main()
| initialized = True
class Testfrozenutf8_1:
"""¶"""
class Testfrozenutf8_2:
"""π"""
class Testfrozenutf8_4:
"""😀"""
def main():
print('Hello world!')
if __name__ == '__main__':
main() |
'''
A collection of classes corresponding to fixed-income securities, to be fed into (and used with)
other classes and methods available in this repository (eg trees.py, Monte Carlo, etc)
'''
class SelfAmortizingMortgage:
def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100):
''' Inputs... | """
A collection of classes corresponding to fixed-income securities, to be fed into (and used with)
other classes and methods available in this repository (eg trees.py, Monte Carlo, etc)
"""
class Selfamortizingmortgage:
def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100):
""" Inputs... |
AVG = 70
FUNCTIONS = [
lambda geslacht: 0 if geslacht == 'man' else 4,
lambda rookt: -5 if rookt else 5,
lambda sport: -3 if not sport else sport,
lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0,
lambda f... | avg = 70
functions = [lambda geslacht: 0 if geslacht == 'man' else 4, lambda rookt: -5 if rookt else 5, lambda sport: -3 if not sport else sport, lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0, lambda fastfood: 3 if not fastfood else 0]
def levensverwachting(geslacht, roker, sport, ... |
class CommentHandlers(object):
def __init__(self):
self.handlers = []
self.comments = {}
def handler(self):
def wrapped(func):
self.register(func)
return func
return wrapped
def register_handler(self, func):
for handler in self.handlers:
... | class Commenthandlers(object):
def __init__(self):
self.handlers = []
self.comments = {}
def handler(self):
def wrapped(func):
self.register(func)
return func
return wrapped
def register_handler(self, func):
for handler in self.handlers:
... |
def incrementing_time(start=2000, increment=1):
while True:
yield start
start += increment
def monotonic_time(start=2000):
return incrementing_time(start, increment=0.000001)
def static_time(value):
while True:
yield value
| def incrementing_time(start=2000, increment=1):
while True:
yield start
start += increment
def monotonic_time(start=2000):
return incrementing_time(start, increment=1e-06)
def static_time(value):
while True:
yield value |
"""
Common constants and functions
Markus Konrad <markus.konrad@wzb.eu>
"""
DEFAULT_TOPIC_NAME_FMT = 'topic_{i1}'
DEFAULT_RANK_NAME_FMT = 'rank_{i1}'
| """
Common constants and functions
Markus Konrad <markus.konrad@wzb.eu>
"""
default_topic_name_fmt = 'topic_{i1}'
default_rank_name_fmt = 'rank_{i1}' |
class Solution:
def reverseBits(self, n: int) -> int:
val = 0
for i in range(32):
val <<= 1
val += n & 1
n >>= 1
return val
| class Solution:
def reverse_bits(self, n: int) -> int:
val = 0
for i in range(32):
val <<= 1
val += n & 1
n >>= 1
return val |
stages = iter(['alpha','beta','gamma'])
try:
next(stages)
next(stages)
next(stages)
next(stages)
except StopIteration as ex:
err_msg = 'Ran out of iterations'
| stages = iter(['alpha', 'beta', 'gamma'])
try:
next(stages)
next(stages)
next(stages)
next(stages)
except StopIteration as ex:
err_msg = 'Ran out of iterations' |
class Payment:
def __init__(self):
pass
def setPayment(self, payment):
Payment.payment = payment
def getPayment(self):
print("Total yang harus dibayarkan Rp. ", Payment.payment)
| class Payment:
def __init__(self):
pass
def set_payment(self, payment):
Payment.payment = payment
def get_payment(self):
print('Total yang harus dibayarkan Rp. ', Payment.payment) |
#from pageParser
'''
lines = []
with open('output111.txt', 'rt') as in_file:
for line in in_file:
lines.append(line.rstrip('\n'))
counter = (len(lines))
holder = 0
for element in range(0, counter):
if(lines[holder].find('a') == -1):
... | """
lines = []
with open('output111.txt', 'rt') as in_file:
for line in in_file:
lines.append(line.rstrip('
'))
counter = (len(lines))
holder = 0
for element in range(0, counter):
if(lines[holder].find('a') == -1):
print("No A is fo... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
c = x^y
r = 0
while c != 0:
r += (c & 1)
c = c>>1
return r
| class Solution:
def hamming_distance(self, x: int, y: int) -> int:
c = x ^ y
r = 0
while c != 0:
r += c & 1
c = c >> 1
return r |
v = "vvv"
a = [f"aaa{vvv}"
"bbb"]
print(a)
| v = 'vvv'
a = [f'aaa{vvv}bbb']
print(a) |
# worst case O(n^2)
# good case O(n)
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i -1
while (j>=0 and array[j]>key):
# scoot
array[j+1] = array[j]
j-=1
array[j+1] = key
return array
arr = [3,-9,5, 100,-2, 294,... | def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
array[j + 1] = array[j]
j -= 1
array[j + 1] = key
return array
arr = [3, -9, 5, 100, -2, 294, 5, 56]
sarr = insertion_sort(arr)
print(sarr, ... |
x=int(input("Enter first number:\n"))
y=int(input("Enter second number:\n"))
print("Before swapping:\n",x,"\n",y,"\n")
#Inputting two numbers from user
x,y=y,x
#Swapping two variables
print("After swapping:\n",x,"\n",y,"\n") | x = int(input('Enter first number:\n'))
y = int(input('Enter second number:\n'))
print('Before swapping:\n', x, '\n', y, '\n')
(x, y) = (y, x)
print('After swapping:\n', x, '\n', y, '\n') |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2016 Dean Jackson <deanishe@deanishe.net>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2016-12-17
#
"""CLI program sub-commands."""
| """CLI program sub-commands.""" |
n = int(input())
for i in range(1, 10):
if n % i != 0:
continue
for j in range(1, 10):
if n % j != 0:
continue
for k in range(1, 10):
if n % k != 0:
continue
for m in range(1, 10):
if n % m != 0:
con... | n = int(input())
for i in range(1, 10):
if n % i != 0:
continue
for j in range(1, 10):
if n % j != 0:
continue
for k in range(1, 10):
if n % k != 0:
continue
for m in range(1, 10):
if n % m != 0:
cont... |
def clean_path(path):
"""
Removes illegal characters from path (Windows only)
"""
return ''.join(i for i in path if i not in '<>:"/\|?*')
| def clean_path(path):
"""
Removes illegal characters from path (Windows only)
"""
return ''.join((i for i in path if i not in '<>:"/\\|?*')) |
reserv_list = set()
party_list = set()
command = input()
while command != 'PARTY':
reserv_list.add(command)
command = input()
if command == 'PARTY':
command = input()
while command != 'END':
party_list.add(command)
command = input()
diff = abs(len(reserv_list) - len(party_... | reserv_list = set()
party_list = set()
command = input()
while command != 'PARTY':
reserv_list.add(command)
command = input()
if command == 'PARTY':
command = input()
while command != 'END':
party_list.add(command)
command = input()
diff = abs(len(reserv_list) - len(party_list))
print(di... |
class Player(object):
TEAM_GREEN = 0
TEAM_RED = 1
TEAM_BLUE = 2
def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue):
self.id = id
self.front_grey = front_grey
self.front_red = front_red
self.front_blue = front_blue
self.deck... | class Player(object):
team_green = 0
team_red = 1
team_blue = 2
def __init__(self, id, front_grey, front_red, front_blue, deck_grey, deck_red, deck_blue):
self.id = id
self.front_grey = front_grey
self.front_red = front_red
self.front_blue = front_blue
self.deck_... |
# Advent of code 2021 : Day 1 | Part 2
# Source : https://adventofcode.com/2020/day/1
infile = "aoc/2020/Day 1/input.txt"
inputs = list(map(int, open(infile).read().splitlines()))
print([i*j*_ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0])
# Answer : 165080960
| infile = 'aoc/2020/Day 1/input.txt'
inputs = list(map(int, open(infile).read().splitlines()))
print([i * j * _ for i in inputs for j in inputs for _ in inputs if i + j + _ == 2020][0]) |
#!/usr/bin/python
class JustCounter:
__secret_count = 0
def count(self):
self.__secret_count += 1
print(self.__secret_count)
counter = JustCounter()
counter.count()
counter.count()
# can't access
print(counter.__secret_count) | class Justcounter:
__secret_count = 0
def count(self):
self.__secret_count += 1
print(self.__secret_count)
counter = just_counter()
counter.count()
counter.count()
print(counter.__secret_count) |
N = int(input())
A = [int(n) for n in input().split()]
ans = [0] + [0]*N
for i in range(N-1):
ans[A[i]] += 1
for i in range(1, N+1):
print(ans[i])
| n = int(input())
a = [int(n) for n in input().split()]
ans = [0] + [0] * N
for i in range(N - 1):
ans[A[i]] += 1
for i in range(1, N + 1):
print(ans[i]) |
def solve_part1(numbers, boards):
marked = {}.fromkeys(list(boards.keys()))
for key in marked:
# idx // 5 idx % 5
# row column
marked[key] = ([0,0,0,0,0],[0,0,0,0,0])
for number in numbers:
for board_idx in boards:
... | def solve_part1(numbers, boards):
marked = {}.fromkeys(list(boards.keys()))
for key in marked:
marked[key] = ([0, 0, 0, 0, 0], [0, 0, 0, 0, 0])
for number in numbers:
for board_idx in boards:
try:
idx = boards[board_idx].index(number)
marked[board_... |
def count(start, end=None, step=None):
if step == 0:
raise IndexError
if hasattr(step, "__iter__"):
raise TypeError
if (hasattr(start, "__iter__")
or hasattr(end, "__iter__")):
return __iter_count(start, end, step)
else:
return __num_count(start, end, step)
... | def count(start, end=None, step=None):
if step == 0:
raise IndexError
if hasattr(step, '__iter__'):
raise TypeError
if hasattr(start, '__iter__') or hasattr(end, '__iter__'):
return __iter_count(start, end, step)
else:
return __num_count(start, end, step)
def __iter_coun... |
#!python2.7
# -*- coding: utf-8 -*-
"""
Created by kun on 2016/10/10.
"""
__author__ = 'kun'
| """
Created by kun on 2016/10/10.
"""
__author__ = 'kun' |
def prime(n):
i=2
while i<=n//2:
if n%i==0:
return 0
i=i+1
return 1
n=2
sum=0
while n<=2000000:
if prime(n):
sum=sum+n
n=n+1
| def prime(n):
i = 2
while i <= n // 2:
if n % i == 0:
return 0
i = i + 1
return 1
n = 2
sum = 0
while n <= 2000000:
if prime(n):
sum = sum + n
n = n + 1 |
# Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
# For example,
# Given n = 3,
# You should return the following matrix:
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]
class Solution:
# @param {integer} n
# @return {integer[][]}
def generateMatri... | class Solution:
def generate_matrix(self, n):
matrix = [[0 for x in range(n)] for x in range(n)]
boundaries = [n - 1, n - 1, 0, 1]
bi = 0
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
di = 0
e = [0, 0]
ei = 1
for i in xrange(n * n):
matr... |
#
# This file contains the Python code from Program 4.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/pgm04_20.txt
#
class LinkedList(o... | class Linkedlist(object):
class Element(object):
def insert_after(self, item):
self._next = LinkedList.Element(self._list, item, self._next)
if self._list._tail is self:
self._list._tail = self._next
def insert_before(self, item):
tmp = LinkedLi... |
#file = open("data.csv", "r")
#for line in file:
# print(line)
with open("output.csv", "a") as fileout:
fileout.write("Hello World")
fileout.close() | with open('output.csv', 'a') as fileout:
fileout.write('Hello World')
fileout.close() |
# -*- coding: utf-8 -*-
__title__ = 'atomos'
__version_info__ = ('0', '3', '1')
__version__ = '.'.join(__version_info__)
__author__ = 'Max Countryman'
__license__ = 'BSD'
__copyright__ = 'Copyright 2014 Max Countryman'
| __title__ = 'atomos'
__version_info__ = ('0', '3', '1')
__version__ = '.'.join(__version_info__)
__author__ = 'Max Countryman'
__license__ = 'BSD'
__copyright__ = 'Copyright 2014 Max Countryman' |
# Copyright (C) 2019 Intel Corporation
#
# SPDX-License-Identifier: MIT
class Converter:
def __init__(self, cmdline_args=None):
pass
def __call__(self, extractor, save_dir):
raise NotImplementedError()
def _parse_cmdline(self, cmdline):
parser = self.build_cmdline_parser()
... | class Converter:
def __init__(self, cmdline_args=None):
pass
def __call__(self, extractor, save_dir):
raise not_implemented_error()
def _parse_cmdline(self, cmdline):
parser = self.build_cmdline_parser()
if len(cmdline) != 0 and cmdline[0] == '--':
cmdline = cm... |
class Credential :
"""
Class that generates new instances of credentials
"""
credential_list = []
def __init__ (self,account_name,email,password):
"""
__init__ method that helps us define properties for our objects.
"""
"""
Args:
accountname : New nam... | class Credential:
"""
Class that generates new instances of credentials
"""
credential_list = []
def __init__(self, account_name, email, password):
"""
__init__ method that helps us define properties for our objects.
"""
'\n Args:\n accountname : New na... |
primes = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
239, 241, 251
]
# len(primes) = 54
# symbol_size = 3
# for prime i... | primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251]
divisions = (17, 32, 41)
symbol_size = 3
target_size = 1048576
for d ... |
# -*- coding: utf-8 -*-
RADIX = 3
BYTE_RADIX = 256
MAX_TRIT_VALUE = (RADIX - 1) // 2
MIN_TRIT_VALUE = -MAX_TRIT_VALUE
NUMBER_OF_TRITS_IN_A_BYTE = 5
NUMBER_OF_TRITS_IN_A_TRYTE = 3
HASH_LENGTH = 243
BYTE_TO_TRITS_MAPPINGS = [[]] * HASH_LENGTH
TRYTE_TO_TRITS_MAPPINGS = [[]] * 27
HIGH_INTEGER_BITS = 0xFFFFFFFF
HIGH_LON... | radix = 3
byte_radix = 256
max_trit_value = (RADIX - 1) // 2
min_trit_value = -MAX_TRIT_VALUE
number_of_trits_in_a_byte = 5
number_of_trits_in_a_tryte = 3
hash_length = 243
byte_to_trits_mappings = [[]] * HASH_LENGTH
tryte_to_trits_mappings = [[]] * 27
high_integer_bits = 4294967295
high_long_bits = 1844674407370955161... |
"""
`adafruit_hid`
====================================================
This driver simulates USB HID devices. Currently keyboard and mouse are implemented.
* Author(s): Scott Shawcroft, Dan Halbert
"""
| """
`adafruit_hid`
====================================================
This driver simulates USB HID devices. Currently keyboard and mouse are implemented.
* Author(s): Scott Shawcroft, Dan Halbert
""" |
class AttributeDict(dict):
__slots__ = ()
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def __init__(self, dictionary: dict = {}):
super().__init__()
self.update(dictionary)
_defaults = AttributeDict({
"master": "master",
"develop": "develop",
"... | class Attributedict(dict):
__slots__ = ()
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def __init__(self, dictionary: dict={}):
super().__init__()
self.update(dictionary)
_defaults = attribute_dict({'master': 'master', 'develop': 'develop', 'features': 'feature', 'fixes... |
#encoding:utf-8
subreddit = 'HQDesi'
t_channel = '@r_HqDesi'
def send_post(submission, r2t):
return r2t.send_simple(submission)
| subreddit = 'HQDesi'
t_channel = '@r_HqDesi'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
class OrderElement:
def __init__(self, product, quantity):
self.product = product
self.quantity = quantity
def calculate_price(self):
return self.product.unit_price * self.quantity
def __str__(self):
return f"{self.product} x {self.quantity}"
| class Orderelement:
def __init__(self, product, quantity):
self.product = product
self.quantity = quantity
def calculate_price(self):
return self.product.unit_price * self.quantity
def __str__(self):
return f'{self.product} x {self.quantity}' |
#!/usr/bin/env python3
class Parser:
def __init__(self):
self.token = None
self.remained_token = None
'''from regex string to NFA class'''
def parse(self, regex_str):
if len(regex_str) == 0:
print("The compiled content is empty. Stop parsing.")
return None
... | class Parser:
def __init__(self):
self.token = None
self.remained_token = None
'from regex string to NFA class'
def parse(self, regex_str):
if len(regex_str) == 0:
print('The compiled content is empty. Stop parsing.')
return None
regex_str_list = [i ... |
def isgreaterthan20(number1,number2):
print(number1)
print(number2)
num=20
num1=10
isgreaterthan20(num,num1) | def isgreaterthan20(number1, number2):
print(number1)
print(number2)
num = 20
num1 = 10
isgreaterthan20(num, num1) |
class Solution:
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
memo={}
for i,v in enumerate(nums):
if memo.get(v) is None:
memo[v]=1
else:
memo[v]+=1
result=[]
for... | class Solution:
def find_duplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
memo = {}
for (i, v) in enumerate(nums):
if memo.get(v) is None:
memo[v] = 1
else:
memo[v] += 1
result = [... |
# -*- coding:utf-8 -*-
"""
Description:
Transaction Type in AntShares
Usage:
from AntShares.Core.TransactionType import TransactionType
"""
class TransactionType(object):
MinerTransaction = 0x00
IssueTransaction = 0x01
ClaimTransaction = 0x02
EnrollmentTransaction = 0x20
VotingTransaction =... | """
Description:
Transaction Type in AntShares
Usage:
from AntShares.Core.TransactionType import TransactionType
"""
class Transactiontype(object):
miner_transaction = 0
issue_transaction = 1
claim_transaction = 2
enrollment_transaction = 32
voting_transaction = 36
register_transaction ... |
class InvalidIdError(RuntimeError):
def __init__(self, id_value):
super(InvalidIdError, self).__init__()
self.id = id_value
| class Invalididerror(RuntimeError):
def __init__(self, id_value):
super(InvalidIdError, self).__init__()
self.id = id_value |
sku = [{"name": "id",
"type": "varchar(256)"},
{"name": "object",
"type": "varchar(256)"},
{"name": "active",
"type": "boolean"},
{"name": "attributes",
"type": "varchar(max)"},
{"name": "created",
"type": "timestamp"},
{"name": "currency",
... | sku = [{'name': 'id', 'type': 'varchar(256)'}, {'name': 'object', 'type': 'varchar(256)'}, {'name': 'active', 'type': 'boolean'}, {'name': 'attributes', 'type': 'varchar(max)'}, {'name': 'created', 'type': 'timestamp'}, {'name': 'currency', 'type': 'varchar(256)'}, {'name': 'image', 'type': 'varchar(256)'}, {'name': 'i... |
def import_code_query(path, project_name=None, language=None):
if not path:
raise Exception('An importCode query requires a project path')
if project_name and language:
fmt_str = u"""importCode(inputPath=\"%s\", projectName=\"%s\",
language=\"%s\")"""
return fmt_str % (path, project_nam... | def import_code_query(path, project_name=None, language=None):
if not path:
raise exception('An importCode query requires a project path')
if project_name and language:
fmt_str = u'importCode(inputPath="%s", projectName="%s",\nlanguage="%s")'
return fmt_str % (path, project_name, languag... |
#no refactoring
class hash_test:
participant = ["leo","kiki","eden"]
completion = ["leo","kiki"]
p = 31
m = 0xfffff
x = 0
hash_table = list([0 for i in range(m)])
unfinished = list()
# polynomial rolling hash function.
for i in participant:
print(i)
mo... | class Hash_Test:
participant = ['leo', 'kiki', 'eden']
completion = ['leo', 'kiki']
p = 31
m = 1048575
x = 0
hash_table = list([0 for i in range(m)])
unfinished = list()
for i in participant:
print(i)
mod_value = 0
for j in i:
mod_value = mod_value + o... |
# -*- coding: utf-8 -
#
# This file is part of tproxy released under the MIT license.
# See the NOTICE for more information.
version_info = (0, 5, 4)
__version__ = ".".join(map(str, version_info))
| version_info = (0, 5, 4)
__version__ = '.'.join(map(str, version_info)) |
"""Errors raised by mailmerge."""
class MailmergeError(Exception):
"""Top level exception raised by mailmerge functions."""
| """Errors raised by mailmerge."""
class Mailmergeerror(Exception):
"""Top level exception raised by mailmerge functions.""" |
def eh_primo(x):
if (x==3) or (x==2):
return True
if (x<2) or (x%2==0):
return False
for i in range(3, int(x**0.5)+1, 2):
if x%i==0:
return False
return True
def sup_primo(num):
while num >= 10:
sup = num % 10
num = int(num / 10)
if no... | def eh_primo(x):
if x == 3 or x == 2:
return True
if x < 2 or x % 2 == 0:
return False
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True
def sup_primo(num):
while num >= 10:
sup = num % 10
num = int(num / 10)
... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - Widget base class
@copyright: 2002 Juergen Hermann <jh@web.de>
@license: GNU GPL, see COPYING for details.
"""
class Widget:
def __init__(self, request, **kw):
self.request = request
def render(self):
raise NotImplementedError
| """
MoinMoin - Widget base class
@copyright: 2002 Juergen Hermann <jh@web.de>
@license: GNU GPL, see COPYING for details.
"""
class Widget:
def __init__(self, request, **kw):
self.request = request
def render(self):
raise NotImplementedError |
#listing
#representacion de grafos
a,b,c,d,e,f,g,h = range(8)
N = [{b:2,c:1,d:3,e:9,f:4}, #a
{c:4,e:3}, #b
{d:8}, #c
{e:7}, #d
{f:5}, #e
{c:2,g:2,h:2}, #f
{f:1,h:6}... | (a, b, c, d, e, f, g, h) = range(8)
n = [{b: 2, c: 1, d: 3, e: 9, f: 4}, {c: 4, e: 3}, {d: 8}, {e: 7}, {f: 5}, {c: 2, g: 2, h: 2}, {f: 1, h: 6}, {f: 9, g: 8}]
print(b in N[a])
print(len(N[f]))
print(N[a][b])
input()
m = [[0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0,... |
class Config(object):
_instance = None
def __new__(self):
if not self._instance:
self._instance = super(Config, self).__new__(self)
return self._instance
def setConfig(self, config):
self.config = config
def get(self, key):
return self.config[key]
def ... | class Config(object):
_instance = None
def __new__(self):
if not self._instance:
self._instance = super(Config, self).__new__(self)
return self._instance
def set_config(self, config):
self.config = config
def get(self, key):
return self.config[key]
def... |
# Faca um programa que tenha uma funcao
# chamada area(),
# que receba as dimensoes de um terreno
# retangular(largura e comprimento) e mostre a
# area do terreno
def area(larg, comp):
a = larg * comp
print(f'A area de um terreno {larg} x {comp} eh de {a}m2.')
print(' Controle de Terrenos')
print('-' * 20)
... | def area(larg, comp):
a = larg * comp
print(f'A area de um terreno {larg} x {comp} eh de {a}m2.')
print(' Controle de Terrenos')
print('-' * 20)
l = float(input('Largura (m): '))
c = float(input('Comprimento (m): '))
area(l, c) |
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fib = []
fib.extend([1, 1])
j = 1
i = 2
# calculate fibonacci number greater than k
while j < k:
x = fib[i - 1] + fib[i - 2]
fib.append(x)
i += 1
j = x
... | class Solution:
def find_min_fibonacci_numbers(self, k: int) -> int:
fib = []
fib.extend([1, 1])
j = 1
i = 2
while j < k:
x = fib[i - 1] + fib[i - 2]
fib.append(x)
i += 1
j = x
count = 0
for i in range(len(fib) ... |
input()
groups = sorted([ int(i) for i in input().split() ], reverse=True)
cars = 0
i = 0
j = len(groups) - 1
while i <= j:
g = groups[i]
if g == 4:
i += 1
cars += 1
continue
cur_car = g
while groups[j] <= 4 - cur_car and i < j:
cur_car += groups[j]
j -= 1
... | input()
groups = sorted([int(i) for i in input().split()], reverse=True)
cars = 0
i = 0
j = len(groups) - 1
while i <= j:
g = groups[i]
if g == 4:
i += 1
cars += 1
continue
cur_car = g
while groups[j] <= 4 - cur_car and i < j:
cur_car += groups[j]
j -= 1
i += ... |
def auto_newline(text: str, max_line_length: int):
def wrap_line_helper(line: str):
words = line.split(" ")
wrapped_line = []
current_line = ""
for word in words:
current_line += word
if len(current_line) > max_line_length:
current_line = " ".j... | def auto_newline(text: str, max_line_length: int):
def wrap_line_helper(line: str):
words = line.split(' ')
wrapped_line = []
current_line = ''
for word in words:
current_line += word
if len(current_line) > max_line_length:
current_line = ' '.... |
def explore(lines):
y = 0
x = lines[0].index('|')
dx = 0
dy = 1
answer = ''
steps = 0
while True:
x += dx
y += dy
if lines[y][x] == '+':
if x < (len(lines[y]) - 1) and lines[y][x+1].strip() and dx != -1:
dx = 1
dy = 0
... | def explore(lines):
y = 0
x = lines[0].index('|')
dx = 0
dy = 1
answer = ''
steps = 0
while True:
x += dx
y += dy
if lines[y][x] == '+':
if x < len(lines[y]) - 1 and lines[y][x + 1].strip() and (dx != -1):
dx = 1
dy = 0
... |
# Search in Rotated Sorted Array: https://leetcode.com/problems/search-in-rotated-sorted-array/
# There is an integer array nums sorted in ascending order (with distinct values).
# Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array i... | class Solution:
def search(self, nums, target: int) -> int:
(lo, hi) = (0, len(nums) - 1)
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return mid
elif nums[mid] >= nums[lo]:
if target >= nums[lo] and target <= ... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
k %= len(nums)
if k > 0:
for i, v in enumerate(nums[-k:] + nums[0:-k]):
nums[i] = v
| class Solution:
def rotate(self, nums: List[int], k: int) -> None:
k %= len(nums)
if k > 0:
for (i, v) in enumerate(nums[-k:] + nums[0:-k]):
nums[i] = v |
# sort given sequence given that the numbers go from 1 to n
def cyclic_sort(seq):
for i in range(len(seq)):
num = seq[i]
if num != seq[num-1]:
# swap
seq[num-1], seq[i] = seq[i], seq[num-1]
def main():
seq = [5,4,1,2,3]
cyclic_sort(seq)
print(f'seq = {seq}')
... | def cyclic_sort(seq):
for i in range(len(seq)):
num = seq[i]
if num != seq[num - 1]:
(seq[num - 1], seq[i]) = (seq[i], seq[num - 1])
def main():
seq = [5, 4, 1, 2, 3]
cyclic_sort(seq)
print(f'seq = {seq}')
if __name__ == '__main__':
main() |
class Student:
# Using a global base for all the available courses
numReg = []
# We will initalise the student class
def __init__(self, number, name, family, courses=None):
if courses is None:
courses = []
self.number = number
self.numReg.append(self)
... | class Student:
num_reg = []
def __init__(self, number, name, family, courses=None):
if courses is None:
courses = []
self.number = number
self.numReg.append(self)
self.name = name
self.family = family
self.courses = courses
def display_student(se... |
class Task:
"""
Abstract class defining a task. A task is an atomic action (i.e: switch on/off light, play music, etc ...)
It can take arguments which will be defined by the user (i.e: turn off light between 9 am and 1 pm. 9 and 1
can be defined as parameters given by user).
"""
def __init__(se... | class Task:
"""
Abstract class defining a task. A task is an atomic action (i.e: switch on/off light, play music, etc ...)
It can take arguments which will be defined by the user (i.e: turn off light between 9 am and 1 pm. 9 and 1
can be defined as parameters given by user).
"""
def __init__(se... |
###############################################################################
###############################################################################
#Copyright (c) 2016, Andy Schroder
#See the file README.md for licensing information.
##########################################################################... | CycleInputParameters['MaximumTemperature'] = 650.0 + 273.0
CycleInputParameters['StartingProperties']['Temperature'] = 273.0 + 47
CycleInputParameters['FluidType'] = 'Carbon Dioxide'
CycleInputParameters['PowerOutput'] = 1.0 * 10 ** 6
delta_p_per_delta_t = 0
CycleInputParameters['Piston']['MassFraction'] = 1.0
CycleInp... |
#D
def fibonacci(N :int) -> int:
if N == 1:
return 1
elif N == 2:
return 1
else:
return fibonacci(N-2)+fibonacci(N-1)
def main():
# input
N = int(input())
# compute
# output
print(fibonacci(N))
if __name__ == '__main__':
main()
| def fibonacci(N: int) -> int:
if N == 1:
return 1
elif N == 2:
return 1
else:
return fibonacci(N - 2) + fibonacci(N - 1)
def main():
n = int(input())
print(fibonacci(N))
if __name__ == '__main__':
main() |
class Solution:
def countVowelStrings(self, n: int) -> int:
d = ['a', 'e', 'i', 'o', 'u']
path = []
count = 0
def backtracking(n, start):
nonlocal count
if n == 0:
count += 1
return
for i in range(start, 5):... | class Solution:
def count_vowel_strings(self, n: int) -> int:
d = ['a', 'e', 'i', 'o', 'u']
path = []
count = 0
def backtracking(n, start):
nonlocal count
if n == 0:
count += 1
return
for i in range(start, 5):
... |
class _EventTarget:
'''https://developer.mozilla.org/en-US/docs/Web/API/EventTarget'''
NotImplemented
class _Node(_EventTarget):
'''https://developer.mozilla.org/en-US/docs/Web/API/Node'''
NotImplemented
class _Element(_Node):
'''ref of https://developer.mozilla.org/en-US/docs/Web/API/Element'''... | class _Eventtarget:
"""https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"""
NotImplemented
class _Node(_EventTarget):
"""https://developer.mozilla.org/en-US/docs/Web/API/Node"""
NotImplemented
class _Element(_Node):
"""ref of https://developer.mozilla.org/en-US/docs/Web/API/Element"""
... |
# This is function for sorting the array using bubble sort
def bubble_sort(length, array): # It takes two arguments -> Length of the array and the array itself.
for i in range(length):
j = 0
for j in range(0, length-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = a... | def bubble_sort(length, array):
for i in range(length):
j = 0
for j in range(0, length - i - 1):
if array[j] > array[j + 1]:
(array[j], array[j + 1]) = (array[j + 1], array[j])
return array
def main():
length = int(input('Enter the length of the array to be enter... |
print(type(1))
print(type('runnob'))
print(type([2]))
print(type({0:'zero'}))
| print(type(1))
print(type('runnob'))
print(type([2]))
print(type({0: 'zero'})) |
"""
Primality testing
"""
_tiny_primes = [2, 3, 5, 7, 11, 13, 17, 19]
_max_tiny_prime = 19
_tiny_primes_set = set(_tiny_primes)
def _is_tiny_prime(n):
return n <= _max_tiny_prime and n in _tiny_primes_set
def _has_tiny_factor(n):
for p in _tiny_primes:
if n % p == 0:
return True
retu... | """
Primality testing
"""
_tiny_primes = [2, 3, 5, 7, 11, 13, 17, 19]
_max_tiny_prime = 19
_tiny_primes_set = set(_tiny_primes)
def _is_tiny_prime(n):
return n <= _max_tiny_prime and n in _tiny_primes_set
def _has_tiny_factor(n):
for p in _tiny_primes:
if n % p == 0:
return True
retur... |
class Solution:
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
result = ''
for i in range(0, len(s), 2*k):
result += s[i:i+k][::-1] + s[i+k:i+2*k]
return result
| class Solution:
def reverse_str(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
result = ''
for i in range(0, len(s), 2 * k):
result += s[i:i + k][::-1] + s[i + k:i + 2 * k]
return result |
# author: Fei Gao
#
# Count And Say
#
# The count-and-say sequence is the sequence of integers beginning as follows:
# 1, 11, 21, 1211, 111221, ...
# 1 is read off as "one 1" or 11.
# 11 is read off as "two 1s" or 21.
# 21 is read off as "one 2, then one 1" or 1211.
# Given an integer n, generate the nth sequence.
# No... | class Solution:
def count_and_say(self, n):
def process(s):
l = []
start = 0
for end in range(1, len(s)):
if s[end] != s[end - 1]:
l.append(s[start:end])
start = end
l.append(s[start:])
res ... |
file = open('file.txt', 'r')
f = file.readlines()
readingList = []
for line in f:
readingList.append(line.strip())
print(readingList)
file.close()
| file = open('file.txt', 'r')
f = file.readlines()
reading_list = []
for line in f:
readingList.append(line.strip())
print(readingList)
file.close() |
"""
Write a Python program to get a single string from two given strings, separated by a space and swap the fisrt two characters
of each string
sample string: 'abc', 'xyz'
expected result: 'xyc abz'
"""
def swap_char(str1, str2):
char1 = str1[0:2]
char2 = str2[0:2]
str1 = str1.replace(char1, char2)
str2... | """
Write a Python program to get a single string from two given strings, separated by a space and swap the fisrt two characters
of each string
sample string: 'abc', 'xyz'
expected result: 'xyc abz'
"""
def swap_char(str1, str2):
char1 = str1[0:2]
char2 = str2[0:2]
str1 = str1.replace(char1, char2)
str... |
#right rotation of array
#it avoids unnecessary no. of recursions for large no. of rotations.
def right_rot(arr,s):# s is the no. of times to rotate
n=len(arr)
s=s%n
#print(s)
for a in range(s):
store=arr[n-1]
for i in range(n-2,-1,-1):
arr[i+1]=arr[i]
arr[0]=store
... | def right_rot(arr, s):
n = len(arr)
s = s % n
for a in range(s):
store = arr[n - 1]
for i in range(n - 2, -1, -1):
arr[i + 1] = arr[i]
arr[0] = store
return arr
arr = [11, 1, 2, 3, 4]
s = 1
print(right_rot(arr, s)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.