content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
input()
l = [i for i,j in enumerate(input()) if j =='.']
ans = 11111111
for i in range(len(l)-1):
ans = min(ans, l[i+1] - l[i])
print(ans - 1) | input()
l = [i for (i, j) in enumerate(input()) if j == '.']
ans = 11111111
for i in range(len(l) - 1):
ans = min(ans, l[i + 1] - l[i])
print(ans - 1) |
coins = 0
price = round(float(input()), 2)
while price != 0:
if price >= 2:
price -= 2
coins += 1
elif price >= 1:
price -= 1
coins += 1
elif price >= 0.50:
price -= 0.50
coins += 1
elif price >= 0.20:
price -= 0.20
coins += 1
elif pric... | coins = 0
price = round(float(input()), 2)
while price != 0:
if price >= 2:
price -= 2
coins += 1
elif price >= 1:
price -= 1
coins += 1
elif price >= 0.5:
price -= 0.5
coins += 1
elif price >= 0.2:
price -= 0.2
coins += 1
elif price >=... |
{
"targets": [{
"target_name": "krb5",
"sources": [
"./src/module.cc",
"./src/krb5_bind.cc",
"./src/gss_bind.cc",
"./src/base64.cc"
],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exceptions'],
'include_dirs': ["... | {'targets': [{'target_name': 'krb5', 'sources': ['./src/module.cc', './src/krb5_bind.cc', './src/gss_bind.cc', './src/base64.cc'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'dependencies': ['<!(node -p "require(\'node-addon... |
class Solution:
def validPalindrome(self, s: str) -> bool:
left, right = self.twopointer(0, len(s) - 1, s)
if left >= right :
return True
return self.valid(left + 1, right, s) or self.valid(left, right - 1, s)
def valid(self, left, right, s) :
l, r = self.twopoin... | class Solution:
def valid_palindrome(self, s: str) -> bool:
(left, right) = self.twopointer(0, len(s) - 1, s)
if left >= right:
return True
return self.valid(left + 1, right, s) or self.valid(left, right - 1, s)
def valid(self, left, right, s):
(l, r) = self.twopoin... |
SQLALCHEMY_DATABASE_URI = "postgresql:///test_freight"
LOG_LEVEL = "INFO"
WORKSPACE_ROOT = "/tmp/freight-tests"
SSH_PRIVATE_KEY = "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEArvyc+vZVxUjC5ZcFg1VN3jQOCOjO94gwQKFxlz0zOCrCz+Sq\nnWk28YdUpOU016Zinlh4ZZk2136nCKKTMnNMjd6cTTCn5fWomjR+F2CSdaYYpYfO\nNtVnq0SIDUgGmjyPncOGr... | sqlalchemy_database_uri = 'postgresql:///test_freight'
log_level = 'INFO'
workspace_root = '/tmp/freight-tests'
ssh_private_key = '-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEArvyc+vZVxUjC5ZcFg1VN3jQOCOjO94gwQKFxlz0zOCrCz+Sq\nnWk28YdUpOU016Zinlh4ZZk2136nCKKTMnNMjd6cTTCn5fWomjR+F2CSdaYYpYfO\nNtVnq0SIDUgGmjyPncOGrxVT... |
#
# PySNMP MIB module SUPERMICRO-SMI (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUPERMICRO-SMI
# Produced by pysmi-0.3.4 at Mon Apr 29 21:04:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection) ... |
#
# PySNMP MIB module CISCO-WAN-ATM-CONN-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-ATM-CONN-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 18:03:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ... |
s = 0
for i in range(101):
s += i
print("Suma liczb od 1 do 100 to: ", s)
| s = 0
for i in range(101):
s += i
print('Suma liczb od 1 do 100 to: ', s) |
def BinarySearch(Array, LowerBound, UpperBound, What):
while LowerBound != UpperBound:
mid = (LowerBound + UpperBound) // 2
if Array[mid] < What:
LowerBound = mid
elif Array[mid] > What:
UpperBound = mid - 1
else:
return mid
re... | def binary_search(Array, LowerBound, UpperBound, What):
while LowerBound != UpperBound:
mid = (LowerBound + UpperBound) // 2
if Array[mid] < What:
lower_bound = mid
elif Array[mid] > What:
upper_bound = mid - 1
else:
return mid
return None |
'''
immutable
'''
letters = ("a", "b", "c", "d", "c")
print(letters.count("c"))
print(letters.index("d"))
coordinates = (94, 6, 7)
x, y, z = coordinates
print(x, y, z) | """
immutable
"""
letters = ('a', 'b', 'c', 'd', 'c')
print(letters.count('c'))
print(letters.index('d'))
coordinates = (94, 6, 7)
(x, y, z) = coordinates
print(x, y, z) |
responses = {
'https://example.com/api/v1/something/': {
'count': 5,
'next': 'https://example.com/api/v1/something/?limit=3&offset=3',
'previous': None,
'results': [
{'id': 1}, {'id': 2}, {'id': 3}
],
'collection_links': {}
},
'https://example.com/... | responses = {'https://example.com/api/v1/something/': {'count': 5, 'next': 'https://example.com/api/v1/something/?limit=3&offset=3', 'previous': None, 'results': [{'id': 1}, {'id': 2}, {'id': 3}], 'collection_links': {}}, 'https://example.com/api/v1/something/?limit=3&offset=3': {'count': 5, 'next': 'https://example.co... |
#!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: https://github.com/kazuto1011
# Created: 2016-06-07
config = {
'server_IP': '192.168.4.170',
'PORT': 49952,
'xml_file': 'C:/Users/nemuriscan/Desktop/NemuriScanLog/NemuriScanStateInfo.xml'
}
| config = {'server_IP': '192.168.4.170', 'PORT': 49952, 'xml_file': 'C:/Users/nemuriscan/Desktop/NemuriScanLog/NemuriScanStateInfo.xml'} |
# Replace the file path with an existing text file on your machine.
with open("/home/aditya/Desktop/sample.txt", "r") as file_:
lines = file_.readlines()
for line in lines:
print(lines)
| with open('/home/aditya/Desktop/sample.txt', 'r') as file_:
lines = file_.readlines()
for line in lines:
print(lines) |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: otp.uberdog.SpeedchatRelayGlobals
NORMAL = 0
CUSTOM = 1
EMOTE = 2
PIRATES_QUEST = 3
TOONTOWN_QUEST = 4 | normal = 0
custom = 1
emote = 2
pirates_quest = 3
toontown_quest = 4 |
#
# PySNMP MIB module JUNIPER-PFE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-PFE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:00:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) ... |
def implement_each(folder, each):
folder['tags'] = each['tags'] + folder['tags']
for key, tags in each['folders'].items():
folder['folders'][key] = {'tags': tags, 'folders': {}}
return folder
| def implement_each(folder, each):
folder['tags'] = each['tags'] + folder['tags']
for (key, tags) in each['folders'].items():
folder['folders'][key] = {'tags': tags, 'folders': {}}
return folder |
# Palindrome Permutation:
# Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
def palindromePerm... | def palindrome_permutation(string):
string = string.lower()
sort = sorted(string)
sorted_string = ''.join(sort)
is_perm = True
odd_counter = 0
char_count = len(sortedString)
if charCount % 2 == 0:
for char in range(0, charCount, 2):
if sortedString[char] == sortedString[c... |
# Default colors
STRONG = "5aa69d" # primary color (for highlighting etc)
NEUTRAL = "999999"
POSITIVE = "47b358"
NEGATIVE = "ec6b56"
FILL_BETWEEN = "F7F4F4"
WARM = "ff808f"
COLD = "4062bb"
BLACK = "0F1108"
DARK_GRAY = "42404F"
LIGHT_GRAY = "C8C7D1"
# For categorical coloring
# picked from color brewer, but without to... | strong = '5aa69d'
neutral = '999999'
positive = '47b358'
negative = 'ec6b56'
fill_between = 'F7F4F4'
warm = 'ff808f'
cold = '4062bb'
black = '0F1108'
dark_gray = '42404F'
light_gray = 'C8C7D1'
qualitative = ['66c2a5', 'fc8d62', '8da0cb', 'e78ac3', 'a6d854', 'ffd92f', 'e5c494', 'b3b3b3'] |
values = []
values.append(1)
values.append(3)
values.append(5)
print('first time:', values)
values = values[1:]
print('second time:', values) | values = []
values.append(1)
values.append(3)
values.append(5)
print('first time:', values)
values = values[1:]
print('second time:', values) |
s = list(map(int, input().split()))
for i in range(1, len(s), 2):
s[i - 1], s[i] = s[i], s[i - 1]
print(*s)
| s = list(map(int, input().split()))
for i in range(1, len(s), 2):
(s[i - 1], s[i]) = (s[i], s[i - 1])
print(*s) |
for i in range(100):
count=i+1
if count % 3==0 and count % 5==0:
a= 'fizzbuzz'
elif count % 3==0:
a= "fizz"
elif count % 5==0:
a="buzz"
else:
a=count
user=input("whats the next number in fizzbuzz?")
a= str(a)
if user==a:
print("goodjob")
else:
... | for i in range(100):
count = i + 1
if count % 3 == 0 and count % 5 == 0:
a = 'fizzbuzz'
elif count % 3 == 0:
a = 'fizz'
elif count % 5 == 0:
a = 'buzz'
else:
a = count
user = input('whats the next number in fizzbuzz?')
a = str(a)
if user == a:
prin... |
# .py file for python maths exercises
# convert degree to radian
# x * pi/180
# in = 15
# out = 0.2619047619047619
def deg2rad(degrees):
pi = 22/7
return degrees * pi / 180
# convert radian to degree
# in = .52
# out = 29.781818181818185
def rad2deg(rad):
pi = 22/7
return rad / pi * 180
# area of tra... | def deg2rad(degrees):
pi = 22 / 7
return degrees * pi / 180
def rad2deg(rad):
pi = 22 / 7
return rad / pi * 180
def area_of_trapezoid(a, b, h):
ab = a + b
return ab / 2 * h
def area_of_parallelogram(b, h):
return b * h
def get_volume_surface_of_cylinder(r, h):
pi = 22 / 7
a = 2 *... |
def add_class_name(attrs, class_name):
class_names = attrs.get('class')
if class_names:
class_names = [class_names]
else:
class_names = []
class_names.append(class_name)
attrs['class'] = ' '.join(class_names)
return attrs
class ReadonlyValue:
def __init__(self, value, huma... | def add_class_name(attrs, class_name):
class_names = attrs.get('class')
if class_names:
class_names = [class_names]
else:
class_names = []
class_names.append(class_name)
attrs['class'] = ' '.join(class_names)
return attrs
class Readonlyvalue:
def __init__(self, value, human... |
'''
Segments which start with six zero-bits after the header are
very often ascii files.
'''
class R1k6ZeroSegment():
''' Look for ascii files with six zero bits prefix '''
def __init__(self, this):
if not this.has_note('R1k_Segment'):
return
bits = bin(int.from_bytes(b'\xff' + this... | """
Segments which start with six zero-bits after the header are
very often ascii files.
"""
class R1K6Zerosegment:
""" Look for ascii files with six zero bits prefix """
def __init__(self, this):
if not this.has_note('R1k_Segment'):
return
bits = bin(int.from_bytes(b'\xff' + this[... |
c = c2 = c3 = 0
while True:
print('-' * 30)
print(' CADASTRE UMA PESSOA ')
print('-' * 30)
idade = int(input('Idade: '))
sexo = str(input('Sexo: [F/M] ')).strip().upper()[0]
while sexo not in 'FM':
sexo = str(input('Sexo: [F/M] ')).strip().upper()[0]
if idade < 18:
c... | c = c2 = c3 = 0
while True:
print('-' * 30)
print(' CADASTRE UMA PESSOA ')
print('-' * 30)
idade = int(input('Idade: '))
sexo = str(input('Sexo: [F/M] ')).strip().upper()[0]
while sexo not in 'FM':
sexo = str(input('Sexo: [F/M] ')).strip().upper()[0]
if idade < 18:
c ... |
#-*- coding:utf-8 -*-
AbsoluteFreqMap = {
'C': 261,
'#C': 276,
'bD': 276,
'D': 292,
'#D': 310,
'bE': 310,
'E': 328,
'F': 348,
'#F': 369,
'bG': 369,
'G': 391,
'#G': 414,
'bA': 414,
'A': 438,
'#A': 465,
'bB': 465,
'B': 492
}
RelativeFreqMap = {
'1'... | absolute_freq_map = {'C': 261, '#C': 276, 'bD': 276, 'D': 292, '#D': 310, 'bE': 310, 'E': 328, 'F': 348, '#F': 369, 'bG': 369, 'G': 391, '#G': 414, 'bA': 414, 'A': 438, '#A': 465, 'bB': 465, 'B': 492}
relative_freq_map = {'1': 0, '#1': 1 / 12, 'b2': 1 / 12, '2': 2 / 12, '#2': 3 / 12, 'b3': 3 / 12, '3': 4 / 12, '4': 5 /... |
def open_file():
file = input('Enter input file:')
if file=="measles.txt":
return file
else:
print("File should be \"measles.txt\"")
exit()
#Function compare income and the integers
def ref(income):
if income==1:
income="WB_LI"
return income
elif income==2:
... | def open_file():
file = input('Enter input file:')
if file == 'measles.txt':
return file
else:
print('File should be "measles.txt"')
exit()
def ref(income):
if income == 1:
income = 'WB_LI'
return income
elif income == 2:
income = 'WB_LMI'
ret... |
load(
"@build_bazel_rules_nodejs//:index.bzl",
"node_repositories",
"yarn_install",
)
PACKAGE_JSON = "@com_github_scionproto_scion//spec/tools:package.json"
def install_yarn_dependencies():
node_repositories(
package_json = [PACKAGE_JSON],
)
yarn_install(
name = "spec_npm",
... | load('@build_bazel_rules_nodejs//:index.bzl', 'node_repositories', 'yarn_install')
package_json = '@com_github_scionproto_scion//spec/tools:package.json'
def install_yarn_dependencies():
node_repositories(package_json=[PACKAGE_JSON])
yarn_install(name='spec_npm', exports_directories_only=False, package_json=PA... |
def test_del_first_group(app):
app.group.delete_first_group()
| def test_del_first_group(app):
app.group.delete_first_group() |
class HttpFetchError(BaseException):
pass
class MaxExceptionError(BaseException):
pass
class KnownError(BaseException):
pass
| class Httpfetcherror(BaseException):
pass
class Maxexceptionerror(BaseException):
pass
class Knownerror(BaseException):
pass |
print("Enter a number")
num = int(input())
print("Type 1 or 0")
num2 = int(input())
b = bool(num2)
if(b == True):
for i in range(1, num+1):
for j in range(1, i+1):
print("*", end=" ")
print()
elif (b == False):
for i in range(num, 0, -1):
for j in range(1, i+1):
p... | print('Enter a number')
num = int(input())
print('Type 1 or 0')
num2 = int(input())
b = bool(num2)
if b == True:
for i in range(1, num + 1):
for j in range(1, i + 1):
print('*', end=' ')
print()
elif b == False:
for i in range(num, 0, -1):
for j in range(1, i + 1):
... |
string = '012345678901234567890123456789012345678901234567890123456789'
n = 10
lista = [string[i:i+n] for i in range(0, len(string), n)]
listastring = '.'.join(lista)
print(listastring) | string = '012345678901234567890123456789012345678901234567890123456789'
n = 10
lista = [string[i:i + n] for i in range(0, len(string), n)]
listastring = '.'.join(lista)
print(listastring) |
# OpenWeatherMap API Key
weather_api_key = "4b6f407bc3690ac1562800a586bbda13"
# Google API Key
g_key = "AIzaSyBH17Xn87x8SM7waCAzHnS4gKMWRX96iDQ"
| weather_api_key = '4b6f407bc3690ac1562800a586bbda13'
g_key = 'AIzaSyBH17Xn87x8SM7waCAzHnS4gKMWRX96iDQ' |
t=int(input())
for i in range(t):
n=int(input())
h=0
for i in range(n+1):
if i%2==0:
h += 1
else:
h *= 2
print(h) | t = int(input())
for i in range(t):
n = int(input())
h = 0
for i in range(n + 1):
if i % 2 == 0:
h += 1
else:
h *= 2
print(h) |
# Same as sorted_list_permutation [3 (ii)], however we are counting the number of occurring *columns* in A instead of number of occurrences itself.
#
# Goal: *no runtime goal*
def custom_sort(A,B):
C=B
i=1
while i < len(B):
j=i
while j > 0 and (count_occurring_columns(B[j-1],A) > count_occu... | def custom_sort(A, B):
c = B
i = 1
while i < len(B):
j = i
while j > 0 and (count_occurring_columns(B[j - 1], A) > count_occurring_columns(B[j], A) or (count_occurring_columns(B[j - 1], A) == count_occurring_columns(B[j], A) and B[j - 1] < B[j])):
new_val = C[j]
C[j] ... |
hello = ''
with open('hello-world.txt', 'r') as f:
hello = f.read()
print(hello) | hello = ''
with open('hello-world.txt', 'r') as f:
hello = f.read()
print(hello) |
# This is just for socgen-k test, you make sure Socgen-k server is working well.
# https://socgen-k-api.openbankproject.com/
# API server URL
BASE_URL = "https://socgen-k-api.openbankproject.com"
API_VERSION = "v2.0.0"
API_VERSION_V210 = "v2.1.0"
# API server will redirect your browser to this URL, should be non-funct... | base_url = 'https://socgen-k-api.openbankproject.com'
api_version = 'v2.0.0'
api_version_v210 = 'v2.1.0'
callback_uri = 'http://127.0.0.1/cb'
username = '1000203893'
password = '123456'
consumer_key = '45wpocdzh2uwnorvrk2sfy1rnwyc0h2ff3kdkr2s'
from_bank_id = '00100'
from_account_id = '83b96bb4-ae2c-3e90-ad2c-8ce0b4b002... |
GOOD_HTTP_CODES = [200, 201, 202, 203]
USER_FIELD = 'username'
ACCESS_TOKEN_FIELD = 'access_token'
REFRESH_TOKEN_FIELD = 'refresh_token'
EXPIRE_TIME_TOKEN_FIELD = 'expires_in'
ERROR_CODE_FIELD = 'errcode'
MENSSAGE_FIELD = 'errmsg'
LIST_FIELD = 'list'
STATE_FIELD = 'state'
PAGES_FIELD = 'pages'
GATEWAY_MAC_FIELD = 'gat... | good_http_codes = [200, 201, 202, 203]
user_field = 'username'
access_token_field = 'access_token'
refresh_token_field = 'refresh_token'
expire_time_token_field = 'expires_in'
error_code_field = 'errcode'
menssage_field = 'errmsg'
list_field = 'list'
state_field = 'state'
pages_field = 'pages'
gateway_mac_field = 'gate... |
def insertionSort(alist):
for index in range(1, len(alist)):
currentvalue = alist[index]
position = index
while position > 0 and alist[position - 1] > currentvalue:
alist[position] = alist[position - 1]
position = position - 1
alist[position] = currentvalue... | def insertion_sort(alist):
for index in range(1, len(alist)):
currentvalue = alist[index]
position = index
while position > 0 and alist[position - 1] > currentvalue:
alist[position] = alist[position - 1]
position = position - 1
alist[position] = currentvalue
a... |
"Github API v2 library for Python"
VERSION = (0, 2, 0)
__author__ = "Ask Solem"
__contact__ = "askh@opera.com"
__homepage__ = "http://github.com/ask/python-github2"
__version__ = ".".join(map(str, VERSION))
| """Github API v2 library for Python"""
version = (0, 2, 0)
__author__ = 'Ask Solem'
__contact__ = 'askh@opera.com'
__homepage__ = 'http://github.com/ask/python-github2'
__version__ = '.'.join(map(str, VERSION)) |
N = 6
edge_list = [(0, 1, 30), (1, 0, 30), (0, 2, 25), (2, 0, 20), (1, 2, 40),
(2, 1, 35), (1, 3, 35), (2, 4, 15), (3, 1, 25), (3, 2, 20),
(3, 5, 45), (4, 3, 10), (4, 5, 40), (5, 3, 50), (5, 4, 50)]
dij = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(N):
dij[i][i] = 0... | n = 6
edge_list = [(0, 1, 30), (1, 0, 30), (0, 2, 25), (2, 0, 20), (1, 2, 40), (2, 1, 35), (1, 3, 35), (2, 4, 15), (3, 1, 25), (3, 2, 20), (3, 5, 45), (4, 3, 10), (4, 5, 40), (5, 3, 50), (5, 4, 50)]
dij = [[float('inf') for i in range(N)] for j in range(N)]
for i in range(N):
dij[i][i] = 0.0
for e in edge_list:
... |
#list
list = [1,2,3,4,8]
print(list)
list.append(6)
print(list)
list.pop(2)
print(list)
list.insert(1,7)
print(list)
list.extend([1,2,4,7])
print(list)
print(list.count(2))
print(1 in list)
list.sort()
print(list)
list.reverse()
print(list)
#dictionary
dict = {
1:'yasser',
'h':'honey',
... | list = [1, 2, 3, 4, 8]
print(list)
list.append(6)
print(list)
list.pop(2)
print(list)
list.insert(1, 7)
print(list)
list.extend([1, 2, 4, 7])
print(list)
print(list.count(2))
print(1 in list)
list.sort()
print(list)
list.reverse()
print(list)
dict = {1: 'yasser', 'h': 'honey', 'l': 3}
tuple = (1, 2, 4, 5, 8, 8)
set = {... |
class Card:
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
def __init__(self, value, suit):
self.set_value(value)
self.set_suit(suit)
def __repr__(self):
return f"{self.value} of {self.suit}"
... | class Card:
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
def __init__(self, value, suit):
self.set_value(value)
self.set_suit(suit)
def __repr__(self):
return f'{self.value} of {self.suit}'
de... |
def running_sum(numbers, start=0):
if len(numbers) == 0:
print()
return
total = numbers[0] + start
print(total,end="")
running_sum(numbers[1:],total)
| def running_sum(numbers, start=0):
if len(numbers) == 0:
print()
return
total = numbers[0] + start
print(total, end='')
running_sum(numbers[1:], total) |
class MyClass:
var = "hello"
def say(a,b):
print("hello"+a.var+b) | class Myclass:
var = 'hello'
def say(a, b):
print('hello' + a.var + b) |
def parse_iteration(s):
if s[-1] == 'k':
return int(s[:-1])*1000
elif s[-1] == 'm':
return int(s[:-1])*1000000
else:
return int(s)
| def parse_iteration(s):
if s[-1] == 'k':
return int(s[:-1]) * 1000
elif s[-1] == 'm':
return int(s[:-1]) * 1000000
else:
return int(s) |
#ALGORITHM USED FOR GENERATING A MAGIC SQUARE USING FORMULA IS AS FOLLOWS:
#Step 1: Start in the middle of the top row, and let n=1
#Step 2: Insert n into the current grid position;
#Step 3: If n=N2 the grid is complete so stop. Otherwise increment n
#Step 4: Move diagonally up and right, wrapping to the first colu... | def generate_square(n):
magic_square = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
i = n / 2
j = n - 1
temp = 1
while temp <= n * n:
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1... |
# this module is a place to store stuff that is used in multiple modules
# valorant client object
client = None
# websocket connections
sockets = []
# user configuration
config = None
# onboarding state
onboarding = False
# asyncio loop
loop = None | client = None
sockets = []
config = None
onboarding = False
loop = None |
def print_hello_world(n):
while n > 0:
print('Hello, world!')
n = n - 1
print_hello_world(3)
| def print_hello_world(n):
while n > 0:
print('Hello, world!')
n = n - 1
print_hello_world(3) |
our_set = set()
our_set2 = {0}
print(our_set, type(our_set))
print(our_set2, type(our_set2))
our_set.add('tomato')
our_set2.add("potato")
print(our_set)
print(our_set2)
x = "tomato"
print(x in our_set)
print(x in our_set2)
print(our_set.isdisjoint(our_set2))
our_set3 = our_set.union(our_set2)
print(our_set3)
our_set.up... | our_set = set()
our_set2 = {0}
print(our_set, type(our_set))
print(our_set2, type(our_set2))
our_set.add('tomato')
our_set2.add('potato')
print(our_set)
print(our_set2)
x = 'tomato'
print(x in our_set)
print(x in our_set2)
print(our_set.isdisjoint(our_set2))
our_set3 = our_set.union(our_set2)
print(our_set3)
our_set.up... |
#
# PySNMP MIB module CISCO-XGCP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-XGCP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:21:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ... |
#Given an array of integers, find the sum of its elements.
#Input Format
#The first line contains an integer, n, denoting the size of the array.
#The second line contains n space-separated integers representing the array's elements.
#Output Format
#Print the sum of the array's elements as a single integer.
#Sampl... | def simple_array_sum(ar):
n = len(ar)
i = 0
p = 0
while i < n:
p = p + ar[i]
i += 1
return p |
AUTH_LDAP_GLOBAL_OPTIONS = {
ldap.OPT_X_TLS_REQUIRE_CERT: True,
ldap.OPT_X_TLS_CACERTFILE: "/etc/certs/ldap.pem"
}
| auth_ldap_global_options = {ldap.OPT_X_TLS_REQUIRE_CERT: True, ldap.OPT_X_TLS_CACERTFILE: '/etc/certs/ldap.pem'} |
class Worker:
def __init__(self, number, name, age, salary):
self.number = number,
self.name = name,
self.age = age,
self.salary = salary
| class Worker:
def __init__(self, number, name, age, salary):
self.number = (number,)
self.name = (name,)
self.age = (age,)
self.salary = salary |
class SessionTimeOut(Exception):
pass
class InvalidFormat(Exception):
pass
class UserExists(Exception):
pass
class EmailAlreadyUsed(Exception):
pass
class SQLInjectionAlert(Exception):
pass
| class Sessiontimeout(Exception):
pass
class Invalidformat(Exception):
pass
class Userexists(Exception):
pass
class Emailalreadyused(Exception):
pass
class Sqlinjectionalert(Exception):
pass |
class Button:
def __init__(self, label, _x, _y, _w, _h):
self.label = label
self.position = PVector(_x, _y)
self.WIDTH = _w
self.HEIGHT = _h
def display(self):
fill(218)
stroke(0)
rect(self.position.x, self.position.y... | class Button:
def __init__(self, label, _x, _y, _w, _h):
self.label = label
self.position = p_vector(_x, _y)
self.WIDTH = _w
self.HEIGHT = _h
def display(self):
fill(218)
stroke(0)
rect(self.position.x, self.position.y, self.WIDTH, self.HEIGHT, 10)
... |
EXPECTED = {'X680': {'extensibility-implied': False,
'imports': {},
'object-classes': {'ATTRIBUTE-E-2-15': {'members': [{'name': '&AttributeType',
'type': 'OpenType'},
{'name'... | expected = {'X680': {'extensibility-implied': False, 'imports': {}, 'object-classes': {'ATTRIBUTE-E-2-15': {'members': [{'name': '&AttributeType', 'type': 'OpenType'}, {'name': '&attributeId', 'type': 'OBJECT IDENTIFIER'}]}}, 'object-sets': {}, 'tags': 'AUTOMATIC', 'types': {'A': {'type': 'NULL'}, 'A-19-5': {'type': 'E... |
output_name = "test"
config = {
"_description": "Test configuration",
"gpu": [0],
# data
"dataset": "Lsun_church",
"data_path": "/home/yct/data/church_outdoor_train_lmdb/Lsun_church_unlabeled_64",
"data_size": 2000,
"use_image_generator": False,
# model & training
"model": ... | output_name = 'test'
config = {'_description': 'Test configuration', 'gpu': [0], 'dataset': 'Lsun_church', 'data_path': '/home/yct/data/church_outdoor_train_lmdb/Lsun_church_unlabeled_64', 'data_size': 2000, 'use_image_generator': False, 'model': 'vanilla', 'z_dim': 128, 'gf_dim': 16, 'df_dim': 16, 'lr_g': 0.0002, 'lr_... |
#/usr/bin/python3
GPIO_NUM = 23
COLUMN_LEN = 16
COLUMN_GAP = 30
def read_file():
file = open("line")
count = 0
while 1:
for i in range(GPIO_NUM):
count = count + 1
if count > GPIO_NUM * COLUMN_LEN:
return
line = file.readline()
if not... | gpio_num = 23
column_len = 16
column_gap = 30
def read_file():
file = open('line')
count = 0
while 1:
for i in range(GPIO_NUM):
count = count + 1
if count > GPIO_NUM * COLUMN_LEN:
return
line = file.readline()
if not line:
... |
n, k = map(int, input().split())
a = list(sorted(map(int, input().split()), reverse=True))
s = set()
for i in range(len(a)):
if a[i] * k not in s:
s.add(a[i])
print(len(s)) | (n, k) = map(int, input().split())
a = list(sorted(map(int, input().split()), reverse=True))
s = set()
for i in range(len(a)):
if a[i] * k not in s:
s.add(a[i])
print(len(s)) |
def smile():
return ":)"
def frown():
return ":("
| def smile():
return ':)'
def frown():
return ':(' |
# coding=utf-8
DEBUG = True
SITE_ID = 1
SECRET_KEY = 'blabla'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite3',
}
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sites',
'south',
'contacts'... | debug = True
site_id = 1
secret_key = 'blabla'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3'}}
installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', 'south', 'contacts', 'contacts.tests']
use_i18_n = True
use_l10_n = True |
# pylint: disable=missing-docstring, invalid-name
MY_DICTIONARY = {"key_one": 1, "key_two": 2, "key_three": 3}
try: # [max-try-statements]
value = MY_DICTIONARY["key_one"]
value += 1
except KeyError:
pass
try:
value = MY_DICTIONARY["key_one"]
except KeyError:
value = 0
| my_dictionary = {'key_one': 1, 'key_two': 2, 'key_three': 3}
try:
value = MY_DICTIONARY['key_one']
value += 1
except KeyError:
pass
try:
value = MY_DICTIONARY['key_one']
except KeyError:
value = 0 |
# Jupyter Extension points
def _jupyter_nbextension_paths():
return [
dict(
section="notebook",
src="static",
# directory in the `nbextension/` namespace
dest="imjoy_jupyter_extension",
# _also_ in the `nbextension/` namespace
require="... | def _jupyter_nbextension_paths():
return [dict(section='notebook', src='static', dest='imjoy_jupyter_extension', require='imjoy_jupyter_extension/imjoy-rpc')] |
COLOR_CANVAS_DARK = 'rgb(33,33,33)'
COLOR_CANVAS_LIGHT = 'rgb(252, 252, 252)'
COLOR_PLOT_TEXT_LIGHT = 'rgb(52, 49, 49)'
COLOR_PLOT_TEXT_DARK = 'rgb(252, 252, 252)'
COLOR_ZERO_LINE_LIGHT = "green"
COLOR_ZERO_LINE_DARK = "limegreen"
COLOR_BEAM = "red"
COLOR_DETECTOR = "#D3D3D3"
COLOR_PAD = "slateblue"
COLOR_PATIENT = "#C... | color_canvas_dark = 'rgb(33,33,33)'
color_canvas_light = 'rgb(252, 252, 252)'
color_plot_text_light = 'rgb(52, 49, 49)'
color_plot_text_dark = 'rgb(252, 252, 252)'
color_zero_line_light = 'green'
color_zero_line_dark = 'limegreen'
color_beam = 'red'
color_detector = '#D3D3D3'
color_pad = 'slateblue'
color_patient = '#C... |
#3) Largest prime factor
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?
# Solution
def primes_naive(n):
if n < 2: return []
sieve = [True] * n
for i in range(3,int(n**0.5)+1,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i... | def primes_naive(n):
if n < 2:
return []
sieve = [True] * n
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i]:
sieve[i * i::2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [i for i in range(3, n, 2) if sieve[i]]
def primes(n):
sieve = [True] * (n // 2... |
f = open("twentyfive.txt", "r")
lines = [x.strip() for x in f.readlines()]
width = len(lines[0])
height = len(lines)
left = {}
down = {}
for y in range(len(lines)):
left[y] = []
down[y] = []
for x in range(len(lines[y])):
if lines[y][x] == ">":
left[y].append(x)
elif lines[y][... | f = open('twentyfive.txt', 'r')
lines = [x.strip() for x in f.readlines()]
width = len(lines[0])
height = len(lines)
left = {}
down = {}
for y in range(len(lines)):
left[y] = []
down[y] = []
for x in range(len(lines[y])):
if lines[y][x] == '>':
left[y].append(x)
elif lines[y][x] ... |
class dotPolymeshValidateInvalidInfo_t(object):
# no doc
ClientId=None
nInvalidFaces=None
| class Dotpolymeshvalidateinvalidinfo_T(object):
client_id = None
n_invalid_faces = None |
def parse_svg(txt):
txt = txt.split('<path d="')[-1]
txt = txt.split('z"/>')[0]
txt = txt.replace('\n', ' ')
txt = txt.split(' ')
# Take out the initial M x y instruction
txt = txt[2:]
# Take out the initial c instruction
txt[0] = txt[0][1:]
txt = [int(num) for num in txt]
curves = []
cur_pos = (0, 0)
... | def parse_svg(txt):
txt = txt.split('<path d="')[-1]
txt = txt.split('z"/>')[0]
txt = txt.replace('\n', ' ')
txt = txt.split(' ')
txt = txt[2:]
txt[0] = txt[0][1:]
txt = [int(num) for num in txt]
curves = []
cur_pos = (0, 0)
for i in range(0, len(txt) - 2, 6):
c = []
... |
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
seen = set() # visited cells here
res = 0
for r, row in enumerate(grid):
for c, val in enumerate(row): # val is basically grid[r, c]
if val and (r,c) not in seen: # if val is 1 and not visi... | class Solution:
def max_area_of_island(self, grid: List[List[int]]) -> int:
seen = set()
res = 0
for (r, row) in enumerate(grid):
for (c, val) in enumerate(row):
if val and (r, c) not in seen:
stack = [(r, c)]
curr_area = 0... |
# -*- coding: utf-8 -*-
'''
Generate baseline proxy minion grains
'''
__proxyenabled__ = ['rest_sample']
__virtualname__ = 'rest_sample'
def __virtual__():
if 'proxy' not in __opts__:
return False
else:
return __virtualname__
def kernel():
return {'kernel': 'proxy'}
def os():
retu... | """
Generate baseline proxy minion grains
"""
__proxyenabled__ = ['rest_sample']
__virtualname__ = 'rest_sample'
def __virtual__():
if 'proxy' not in __opts__:
return False
else:
return __virtualname__
def kernel():
return {'kernel': 'proxy'}
def os():
return {'os': 'proxy'}
def loca... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Tests that custom auth works & is not impaired by CORS',
'category': 'Hidden',
'data': [],
}
| {'name': 'Tests that custom auth works & is not impaired by CORS', 'category': 'Hidden', 'data': []} |
#String unpack example
testString = '0xL08$#$john18:jcTeam01_@#@_https://docs.google.com/spreadsheetExampleUrl'
commandData, data = testString.split('_@#@_')
print(commandData)
print(data)
command, cData = commandData.split('$#$')
print(command)
print(cData)
username, fileName = cData.split(':')
print(username)
print(... | test_string = '0xL08$#$john18:jcTeam01_@#@_https://docs.google.com/spreadsheetExampleUrl'
(command_data, data) = testString.split('_@#@_')
print(commandData)
print(data)
(command, c_data) = commandData.split('$#$')
print(command)
print(cData)
(username, file_name) = cData.split(':')
print(username)
print(fileName) |
def canConstruct(target, word_bank):
tab = [False for _ in range(len(target)+1)]
# seed
tab[0] = True # creating an empty string is always possible
for i in range(len(target)+1):
if tab[i] is True:
for word in word_bank:
# If the word matches the characters starting at position i
if target[i:].start... | def can_construct(target, word_bank):
tab = [False for _ in range(len(target) + 1)]
tab[0] = True
for i in range(len(target) + 1):
if tab[i] is True:
for word in word_bank:
if target[i:].startswith(word):
tab[i + len(word)] = True
return tab[-1]
pr... |
#The urllib module has a function called urljoin which might be able to improve how I put together these urls.
DefaultBaseUrl = "https://api.idfy.io"
DefaultOAuthBaseUrl = DefaultBaseUrl #Could this lead to problems where the DefaultOAuthBaseUrl resets unexpectedly?
TestBaseUrl = "http://localhost:5000" #testing on... | default_base_url = 'https://api.idfy.io'
default_o_auth_base_url = DefaultBaseUrl
test_base_url = 'http://localhost:5000'
o_auth_tokens = '/oauth/connect/token'
signature = '/signature'
signature_documents = Signature + '/documents'
notification = '/notification'
identification = '/identification'
identification_sessio... |
# APIs for Windows 32-bit user32 library.
# Format: retval, rettype, callconv, exactname, arglist(type, name)
# arglist type is one of ['int', 'void *']
# arglist name is one of [None, 'funcptr', 'obj', 'ptr']
api_defs = {
'user32.main_entry':( 'int', None, 'stdcall', 'user32.main_entry', (('int... | api_defs = {'user32.main_entry': ('int', None, 'stdcall', 'user32.main_entry', (('int', None), ('int', None), ('int', None))), 'user32.activatekeyboardlayout': ('int', None, 'stdcall', 'user32.ActivateKeyboardLayout', (('int', None), ('int', None))), 'user32.adjustwindowrect': ('int', None, 'stdcall', 'user32.AdjustWin... |
class Solution:
def minFallingPathSum(self, matrix: List[List[int]]) -> int:
# dp[i][j] means minimum falling path ended with matrix[i][j]
# dp[i][j] = min(dp[i-1][j],dp[i-1][j-1], dp[i-1][j+1])
dp = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
for i in range(le... | class Solution:
def min_falling_path_sum(self, matrix: List[List[int]]) -> int:
dp = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
for i in range(len(matrix[0])):
dp[0][i] = matrix[0][i]
for i in range(1, len(matrix)):
for j in range(len(matrix[0])... |
# A number of options exist when aiming to review how many components to include to reduce the dimensionality complexity
# Let PCA select 90% of the variance
pipe = Pipeline([('scaler', StandardScaler()),
('reducer', PCA(n_components=0.9))]) # By providing a percent ratio value this means the algorithm aims ... | pipe = pipeline([('scaler', standard_scaler()), ('reducer', pca(n_components=0.9))])
pipe.fit(ansur_df)
print('{} components selected'.format(len(pipe.steps[1][1].components_)))
pipe = pipeline([('scaler', standard_scaler()), ('reducer', pca(n_components=10))])
pipe.fit(ansur_df)
plt.plot(pipe.steps[1][1].explained_var... |
# ### Trees
# A tree is a widely used abstract data type that simulates a hierarchical tree structure, with a `root` value and subtrees of `children` with a `parent` node, represented as a set of linked nodes.
#
# A tree data structure can be defined recursively as a collection of nodes (starting at a root node), wher... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def preorder(self, root):
if root:
print(root.data, end=' ')
self.preorder(root.left)
sel... |
#Not finished yet
# intervals = [[1,3],[2,6],[8,10],[15,18]]
# intervals = [[1,4],[4,5]]
intervals = [[2,3],[4,5],[6,7],[8,9],[1,10]]
intervals.sort(key = lambda it : it[0])
myList = [intervals[0]]
for i in range(1,len(intervals)):
# print(myList)
comp1i, comp1j = myList.pop()
comp2i, comp2j = intervals[i... | intervals = [[2, 3], [4, 5], [6, 7], [8, 9], [1, 10]]
intervals.sort(key=lambda it: it[0])
my_list = [intervals[0]]
for i in range(1, len(intervals)):
(comp1i, comp1j) = myList.pop()
(comp2i, comp2j) = intervals[i]
if comp2i > comp1j:
myList.append([comp1i, comp1j])
myList.append(intervals[i... |
# -------------------------------------------------------
#
#
#
# -------------------------------------------------------
class ServiceCategory():
inpatient = 'inpatient'
other_services = 'other_services'
long_term = 'long_term'
prescription = 'prescription'
# -------------------------------------... | class Servicecategory:
inpatient = 'inpatient'
other_services = 'other_services'
long_term = 'long_term'
prescription = 'prescription' |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"make_session": "00_scrapers.ipynb",
"make_browser": "00_scrapers.ipynb",
"s": "00_scrapers.ipynb",
"browsers": "00_scrapers.ipynb",
"cache_db": "00_scrapers.ipynb",
... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'make_session': '00_scrapers.ipynb', 'make_browser': '00_scrapers.ipynb', 's': '00_scrapers.ipynb', 'browsers': '00_scrapers.ipynb', 'cache_db': '00_scrapers.ipynb', 'RS_URLS': '00_scrapers.ipynb', 'ITEM_FORM': '00_scrapers.ipynb', 'KW_OPTIONS': '00... |
'''HashMap class to keep track of key value pairs'''
class HashMap:
'''HashMap class to keep track of key value pairs'''
def __init__(self):
'''initializes key val pair'''
self.inner_size = 7
self.array = [None] * self.inner_size
self.count = 0
def get(self, key):
''... | """HashMap class to keep track of key value pairs"""
class Hashmap:
"""HashMap class to keep track of key value pairs"""
def __init__(self):
"""initializes key val pair"""
self.inner_size = 7
self.array = [None] * self.inner_size
self.count = 0
def get(self, key):
... |
def split_and_join(line):
# write your code here
line_splitted = line.split(' ')
return ('-').join(line_splitted)
# Or in one line:
# return ('-').join(line.split(' ')
| def split_and_join(line):
line_splitted = line.split(' ')
return '-'.join(line_splitted) |
def multiplication(a, b):
a = float(a)
b = float(b)
value = a * b
return value | def multiplication(a, b):
a = float(a)
b = float(b)
value = a * b
return value |
level = 3
name = 'Pamengpeuk'
capital = 'Sukasari'
area = 14.62
| level = 3
name = 'Pamengpeuk'
capital = 'Sukasari'
area = 14.62 |
def get_repo_path(path):
path = path.replace('\\\\', '/').replace('\\', '/')
url_array = path.split("/")
del url_array[len(url_array) - 1]
repo_path = ""
for word in url_array:
if word != url_array[len(url_array) - 1]:
repo_path += word + "/"
return repo_path + url_array[len(... | def get_repo_path(path):
path = path.replace('\\\\', '/').replace('\\', '/')
url_array = path.split('/')
del url_array[len(url_array) - 1]
repo_path = ''
for word in url_array:
if word != url_array[len(url_array) - 1]:
repo_path += word + '/'
return repo_path + url_array[len(... |
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0:
return []
def generateTrees(mini: int, maxi: int) -> List[Optional[int]]:
if mini > maxi:
return [None]
ans = []
for i in range(mini, maxi + 1):
for left in generateTrees(mini, i - 1):
... | class Solution:
def generate_trees(self, n: int) -> List[TreeNode]:
if n == 0:
return []
def generate_trees(mini: int, maxi: int) -> List[Optional[int]]:
if mini > maxi:
return [None]
ans = []
for i in range(mini, maxi + 1):
... |
def taskA(data):
difference = ord('a') - ord('A')
stack = []
for c in data:
if len(stack) == 0:
stack.append(c)
elif c != stack[-1] and (ord(c)+difference == ord(stack[-1]) or ord(c) == ord(stack[-1]) + difference):
stack.pop()
else:
stack.appen... | def task_a(data):
difference = ord('a') - ord('A')
stack = []
for c in data:
if len(stack) == 0:
stack.append(c)
elif c != stack[-1] and (ord(c) + difference == ord(stack[-1]) or ord(c) == ord(stack[-1]) + difference):
stack.pop()
else:
stack.appen... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
level... | class Solution:
def right_side_view(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
level_node = [root]
while levelNode:
res.append(levelNode[-1].val)
level_node_num = len(levelNode)
for i in range(levelNodeNum):
... |
print(True)
print(False, "\n\n") #booleans have to be capitalized or they return false
a =3
b =5
print(a==b) #a is equal to b equal False
print(a!=b) #a is not equal to b equal True
print(a<b) #less than
print(a>b, "\n") #greater than
print(bool(28))
print(bool(-2.1562))
print(bool(0), "\n")
#with strings, trivial ... | print(True)
print(False, '\n\n')
a = 3
b = 5
print(a == b)
print(a != b)
print(a < b)
print(a > b, '\n')
print(bool(28))
print(bool(-2.1562))
print(bool(0), '\n')
print(bool('turing'))
print(bool(' '))
print(bool(''), '\n')
print(str(True))
print(str(False), '\n')
print(int(True))
print(int(False))
print(10 * False) |
#!/usr/bin/env python3
# https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
class Terminal:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[... | class Terminal:
header = '\x1b[95m'
okblue = '\x1b[94m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
@staticmethod
def warning(message):
print(Terminal.WARNING + message + Terminal.ENDC)
@staticm... |
A = [[2, 5, 11],
[-9, 4, 6],
[4, 7, 12]]
soma=0
for linha in range(len(A)): # linhas
for coluna in range(len(A[0])): #colunas
#soma+=A[linha][coluna]
soma = soma + A[linha][coluna]
print ("Soma:", soma) | a = [[2, 5, 11], [-9, 4, 6], [4, 7, 12]]
soma = 0
for linha in range(len(A)):
for coluna in range(len(A[0])):
soma = soma + A[linha][coluna]
print('Soma:', soma) |
service_broadcast_settings_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Set a services broadcast settings",
"type": "object",
"title": "Set a services broadcast settings",
"properties": {
"broadcast_channel": {"enum": ["operator", "test", "severe", "govern... | service_broadcast_settings_schema = {'$schema': 'http://json-schema.org/draft-04/schema#', 'description': 'Set a services broadcast settings', 'type': 'object', 'title': 'Set a services broadcast settings', 'properties': {'broadcast_channel': {'enum': ['operator', 'test', 'severe', 'government']}, 'service_mode': {'enu... |
sims_pre = []
with open('lpips_sim_waymo.txt') as f:
data = f.read()
sims_pre = data.split('(')[1:]
sims_post = []
for sim in sims_pre:
sim = sim.split('): ')
img1 = sim[0].split(', ')[0]
img2 = sim[0].split(', ')[1]
val = sim[1]
sims_post.append(img1+','+img2+','+val)
with open('lpip... | sims_pre = []
with open('lpips_sim_waymo.txt') as f:
data = f.read()
sims_pre = data.split('(')[1:]
sims_post = []
for sim in sims_pre:
sim = sim.split('): ')
img1 = sim[0].split(', ')[0]
img2 = sim[0].split(', ')[1]
val = sim[1]
sims_post.append(img1 + ',' + img2 + ',' + val)
with open('lpi... |
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if head == None or head.next == None:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fa... | class Solution:
def has_cycle(self, head):
if head == None or head.next == None:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False |
LIGHT = "#"
DARK = "."
iterations = 50
padding = iterations * 2
with open('day20/input.txt') as f:
lines = f.readlines()
map = lines[0].strip()
lines.pop(0)
lines.pop(0)
image = []
h = len(lines)
w = len(lines[0].strip())
def blank():
q = []
for i in range(2 * padding + h):
qq = []
... | light = '#'
dark = '.'
iterations = 50
padding = iterations * 2
with open('day20/input.txt') as f:
lines = f.readlines()
map = lines[0].strip()
lines.pop(0)
lines.pop(0)
image = []
h = len(lines)
w = len(lines[0].strip())
def blank():
q = []
for i in range(2 * padding + h):
qq = []
... |
def proteins(strand):
seq = []
codon_map = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UAU": "Tyrosi... | def proteins(strand):
seq = []
codon_map = {'AUG': 'Methionine', 'UUU': 'Phenylalanine', 'UUC': 'Phenylalanine', 'UUA': 'Leucine', 'UUG': 'Leucine', 'UCU': 'Serine', 'UCC': 'Serine', 'UCA': 'Serine', 'UCG': 'Serine', 'UAU': 'Tyrosine', 'UAC': 'Tyrosine', 'UGU': 'Cysteine', 'UGC': 'Cysteine', 'UGG': 'Tryptophan'... |
s=input()
d={}
if s in d:
print(s+str(d[s]))
d[s] += 1 | s = input()
d = {}
if s in d:
print(s + str(d[s]))
d[s] += 1 |
# This problem was recently asked by Twitter:
# Given a Roman numeral, find the corresponding decimal value. Inputs will be between 1 and 3999.
# Numbers are strings of these symbols in descending order. In some cases, subtractive notation is used to avoid repeated characters.
# The rules are as follows:
# 1.) I place... | class Solution:
def value(self, r):
if r == 'I':
return 1
if r == 'V':
return 5
if r == 'X':
return 10
if r == 'L':
return 50
if r == 'C':
return 100
if r == 'D':
return 500
if r == 'M':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.