content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def garterKnit(k,beg,end,length,c,side='l', knitsettings=[4,400,400], xfersettings=[2,0,300]):
if side == 'l':
start=1
else:
start=2
length=length+1
for b in range(start,length+1):
if b%2==1:
k.stitchNumber(xfersettings[0])
k.rollerAdvance(xfersetti... | def garter_knit(k, beg, end, length, c, side='l', knitsettings=[4, 400, 400], xfersettings=[2, 0, 300]):
if side == 'l':
start = 1
else:
start = 2
length = length + 1
for b in range(start, length + 1):
if b % 2 == 1:
k.stitchNumber(xfersettings[0])
k.r... |
# Disable while we have Python 2.x compatability
# pylint: disable=useless-object-inheritance
"""This module contains classes and functionality relating to Sonos Groups."""
class ZoneGroup:
"""
A class representing a Sonos Group. It looks like this::
ZoneGroup(
uid='RINCON_000FD584236D0... | """This module contains classes and functionality relating to Sonos Groups."""
class Zonegroup:
"""
A class representing a Sonos Group. It looks like this::
ZoneGroup(
uid='RINCON_000FD584236D01400:58',
coordinator=SoCo("192.168.1.101"),
members={SoCo("192.168.1.101... |
def resolve():
'''
code here
'''
N, M, Q = [int(item) for item in input().split()]
a_list = [[int(item) for item in input().split()] for _ in range(Q)]
res = 0
for item in comb:
temp_res = 0
print(item)
for j in a_list:
a = j[0]-1
b = ... | def resolve():
"""
code here
"""
(n, m, q) = [int(item) for item in input().split()]
a_list = [[int(item) for item in input().split()] for _ in range(Q)]
res = 0
for item in comb:
temp_res = 0
print(item)
for j in a_list:
a = j[0] - 1
b = j[1] ... |
## @file GenXmlFile.py
#
# This file contained the logical of generate XML files.
#
# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
'''
GenXmlFile
'''
| """
GenXmlFile
""" |
#
# PySNMP MIB module RBTWS-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:53:51 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, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
"""433. Number of Islands"""
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
## Practice:
if not grid:
return 0
self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
m =... | """433. Number of Islands"""
class Solution:
"""
@param grid: a boolean 2D matrix
@return: an integer
"""
def num_islands(self, grid):
if not grid:
return 0
self.directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
m = len(grid)
n = len(grid[0])
visit... |
"""
Code that changes input files and writes them back out. Useful for parameter sweeps.
See Also
--------
armi.reactor.converters
Code that changes reactor objects at runtime. These often take longer to run than
these but can be used in the middle of ARMI analyses.
"""
| """
Code that changes input files and writes them back out. Useful for parameter sweeps.
See Also
--------
armi.reactor.converters
Code that changes reactor objects at runtime. These often take longer to run than
these but can be used in the middle of ARMI analyses.
""" |
class MwClientError(RuntimeError):
pass
class MediaWikiVersionError(MwClientError):
pass
class APIDisabledError(MwClientError):
pass
class MaximumRetriesExceeded(MwClientError):
pass
class APIError(MwClientError):
def __init__(self, code, info, kwargs):
self.code = code
self... | class Mwclienterror(RuntimeError):
pass
class Mediawikiversionerror(MwClientError):
pass
class Apidisablederror(MwClientError):
pass
class Maximumretriesexceeded(MwClientError):
pass
class Apierror(MwClientError):
def __init__(self, code, info, kwargs):
self.code = code
self.inf... |
def plot_table(data):
fig = plt.figure()
ax = fig.add_subplot(111)
col_labels = list(range(0,10))
row_labels = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
# Draw table
value_table = plt.table(cellText=data, colWidths=[0.05] * 10,
rowLabels... | def plot_table(data):
fig = plt.figure()
ax = fig.add_subplot(111)
col_labels = list(range(0, 10))
row_labels = [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
value_table = plt.table(cellText=data, colWidths=[0.05] * 10, rowLabels=row_labels, colLabels=col_labels, loc='center... |
"""Qiskit-Braket exception."""
class QiskitBraketException(Exception):
"""Qiskit-Braket exception."""
| """Qiskit-Braket exception."""
class Qiskitbraketexception(Exception):
"""Qiskit-Braket exception.""" |
class Settings:
def __init__(self):
self.screen_width = 800
self.screen_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.red = (255, 0, 0)
self.green = (0, 255, 0)
self.blue = (0, 0, 255)
self.FPS = 90
| class Settings:
def __init__(self):
self.screen_width = 800
self.screen_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.red = (255, 0, 0)
self.green = (0, 255, 0)
self.blue = (0, 0, 255)
self.FPS = 90 |
N = 2
for i in range(1,N):
for j in range(1,N):
for k in range(1,N):
for l in range(1,N):
if i**3+j**3==k**3+l**3:
print(i,j,k,l) | n = 2
for i in range(1, N):
for j in range(1, N):
for k in range(1, N):
for l in range(1, N):
if i ** 3 + j ** 3 == k ** 3 + l ** 3:
print(i, j, k, l) |
# Given a linked list, rotate the list to the right by k places, where k is non-negative.
# Example 1:
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
# Example 2:
# Input: 0->1->2->... | class Solution:
def rotate_right(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
n = 1
point = head
while point.next:
point = point.next
n... |
def rainWaterTrapping(arr: list) -> int:
n = len(arr)
maxL = [1] * n
maxR = [1] * n
maxL[0] = arr[0]
for i in range(1, n):
maxL[i] = max(maxL[i - 1], arr[i])
maxR[n - 1] = arr[n - 1]
for i in range(n - 2, -1, -1):
maxR[i] = max(maxR[i + 1], arr[i])
total_water = 0
... | def rain_water_trapping(arr: list) -> int:
n = len(arr)
max_l = [1] * n
max_r = [1] * n
maxL[0] = arr[0]
for i in range(1, n):
maxL[i] = max(maxL[i - 1], arr[i])
maxR[n - 1] = arr[n - 1]
for i in range(n - 2, -1, -1):
maxR[i] = max(maxR[i + 1], arr[i])
total_water = 0
... |
n=int(input())
x=hex(n)[-1]
if x.isalpha():
x=ord(x)-87
print(bin(int(x))[-1]) | n = int(input())
x = hex(n)[-1]
if x.isalpha():
x = ord(x) - 87
print(bin(int(x))[-1]) |
BLACK = [0x00, 0x00, 0x00] # Floor
WHITE = [0xFF, 0xFF, 0xFF] # Wall
GOLD = [0xFF, 0xD7, 0x00] # Gold
BLUE = [0x00, 0x00, 0xFF] # Player
GRAY = [0x55, 0x55, 0x55] # Box
GREEN = [0x00, 0xAA, 0x00] # Key
PURPLE = [0xC4, 0x00, 0xC4] # Door
RED = [0xFF, 0x00, 0x00] # Teleport 1
BROWN = [0xA0, 0x50, 0x00] # Teleport 2 | black = [0, 0, 0]
white = [255, 255, 255]
gold = [255, 215, 0]
blue = [0, 0, 255]
gray = [85, 85, 85]
green = [0, 170, 0]
purple = [196, 0, 196]
red = [255, 0, 0]
brown = [160, 80, 0] |
# -*- coding: utf-8 -*-
# Authors: Y. Jia <ytjia.zju@gmail.com>
"""
Find the contiguous subarray within an array (containing at least one number) which has the
largest sum.
https://leetcode.com/problems/maximum-subarray/description/
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:... | """
Find the contiguous subarray within an array (containing at least one number) which has the
largest sum.
https://leetcode.com/problems/maximum-subarray/description/
"""
class Solution(object):
def max_sub_array(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if ... |
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum / count)
| count = 0
sum = 0
print('Before', count, sum)
for value in [9, 41, 12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After', count, sum, sum / count) |
"""
module-wide / shared constants
***
attributes
***
*LOGGING_CFG*: logging configuration dictionary
***
"""
LOGGING_DICT = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"verbose": {
"format": "[%(asctime)s] - [%(name)s] - [%(levelname)s]... | """
module-wide / shared constants
***
attributes
***
*LOGGING_CFG*: logging configuration dictionary
***
"""
logging_dict = {'version': 1, 'disable_existing_loggers': True, 'formatters': {'verbose': {'format': '[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(funcName)s:%(lineno)s] - [%(m... |
#!/usr/bin/env python3
class InputComponent:
def __init__(self):
"""
Constructor in Python is always called `__init__`
You should initialize all object-level variables in the constructor
"""
self._observers = []
def register_observer(self, observer):
self._observ... | class Inputcomponent:
def __init__(self):
"""
Constructor in Python is always called `__init__`
You should initialize all object-level variables in the constructor
"""
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
... |
def pattern_thirty_seven():
'''Pattern thirty_seven
1 2 3 4 5
2 5
3 5
4 5
5
'''
num = '12345'
for i in range(1, 6):
if i == 1:
print(' '.join(num))
elif i in range(2, 5):
space = -2 * i + 9 # using -2*n + 9 for ge... | def pattern_thirty_seven():
"""Pattern thirty_seven
1 2 3 4 5
2 5
3 5
4 5
5
"""
num = '12345'
for i in range(1, 6):
if i == 1:
print(' '.join(num))
elif i in range(2, 5):
space = -2 * i + 9
output = num[i ... |
def listening_algorithm(to,from_):
counts = []
to = to.split(' ')
for i in range(len(from_)):
count = 0
var = from_[i].split(' ')
n = min(len(to),len(var))
for j in range(n):
if var[j] in to[j]:
count += 1
counts.append(count)
... | def listening_algorithm(to, from_):
counts = []
to = to.split(' ')
for i in range(len(from_)):
count = 0
var = from_[i].split(' ')
n = min(len(to), len(var))
for j in range(n):
if var[j] in to[j]:
count += 1
counts.append(count)
maxm_ =... |
'''
06 - Combining groupby() and resample()
A very powerful method in Pandas is .groupby(). Whereas .resample()
groups rows by some time or date information, .groupby() groups rows
based on the values in one or more columns.
For example, rides.groupby('Member type').size() would tell us how many
rides there were... | """
06 - Combining groupby() and resample()
A very powerful method in Pandas is .groupby(). Whereas .resample()
groups rows by some time or date information, .groupby() groups rows
based on the values in one or more columns.
For example, rides.groupby('Member type').size() would tell us how many
rides there were... |
# model settings
weight_root = '/home/datasets/mix_data/iMIX/data/models/detectron.vmb_weights/'
model = dict(
type='M4C',
hidden_dim=768,
dropout_prob=0.1,
ocr_in_dim=3002,
encoder=[
dict(
type='TextBertBase', text_bert_init_from_bert_base=True, hidden_size=768, params=dict(num_... | weight_root = '/home/datasets/mix_data/iMIX/data/models/detectron.vmb_weights/'
model = dict(type='M4C', hidden_dim=768, dropout_prob=0.1, ocr_in_dim=3002, encoder=[dict(type='TextBertBase', text_bert_init_from_bert_base=True, hidden_size=768, params=dict(num_hidden_layers=3)), dict(type='ImageFeatureEncoder', encoder_... |
def rpc_gas_price_strategy(webu, transaction_params=None):
"""
A simple gas price strategy deriving it's value from the eth_gasPrice JSON-RPC call.
"""
return webu.manager.request_blocking("eth_gasPrice", [])
| def rpc_gas_price_strategy(webu, transaction_params=None):
"""
A simple gas price strategy deriving it's value from the eth_gasPrice JSON-RPC call.
"""
return webu.manager.request_blocking('eth_gasPrice', []) |
bot_token = "" # Bot token stored as string
bot_prefix = "" # bot prefix stored as string
log_level = "INFO" # log level stored as string
jellyfin_url = "" # jellyfin base url stored as string
jellyfin_api_key = "" # jellyfin API key stored as string
plex_url = "" # plex base url, stored as string
plex_api_key = "" #... | bot_token = ''
bot_prefix = ''
log_level = 'INFO'
jellyfin_url = ''
jellyfin_api_key = ''
plex_url = ''
plex_api_key = ''
plex_access_role = 0
guild_id = 0
plex_admin_role = 0 |
class backupsolution:
"""Virtual Parent for all Backups
Highlevel-API:
@list_backups( cluster_identifier=None, backup_identifier=None)
@take_backup(kind,cluster_identifier=None)
@remove_backup(kind,backup_identifier=None)
@check(cluster_identifier=None)
@add_cluster(c... | class Backupsolution:
"""Virtual Parent for all Backups
Highlevel-API:
@list_backups( cluster_identifier=None, backup_identifier=None)
@take_backup(kind,cluster_identifier=None)
@remove_backup(kind,backup_identifier=None)
@check(cluster_identifier=None)
@add_cluster(cl... |
def run_diagnostic_program(program):
instruction_lengths = [0, 4, 4, 2, 2, 3, 3, 4, 4]
i = 0
while i < len(program):
opcode = program[i] % 100
modes = [(program[i] // 10**j) % 10 for j in range(2, 5)]
if opcode == 99:
break
instruction_length = instruction_lengths... | def run_diagnostic_program(program):
instruction_lengths = [0, 4, 4, 2, 2, 3, 3, 4, 4]
i = 0
while i < len(program):
opcode = program[i] % 100
modes = [program[i] // 10 ** j % 10 for j in range(2, 5)]
if opcode == 99:
break
instruction_length = instruction_lengths... |
# In python lambda stands for an anonymous function.
# A lambda function can only perform one lines worth of operations on a given input.
greeting = lambda name: 'Hello ' + name
print(greeting('Viewers'))
# You can also use lambda with map(...) and filter(...) functions
names = ['Sherry', 'Jeniffer', 'Ron', 'Sam', '... | greeting = lambda name: 'Hello ' + name
print(greeting('Viewers'))
names = ['Sherry', 'Jeniffer', 'Ron', 'Sam', 'Messi']
s_manes = list(filter(lambda name: name.lower().startswith('s'), names))
print(s_manes)
greetings = list(map(lambda name: 'Hey ' + name, s_manes))
print(greetings) |
{
"targets": [
{
"target_name": "MagickCLI",
"sources": ["src/magick-cli.cc"],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
'dependencies': [
"<!(node -p \... | {'targets': [{'target_name': 'MagickCLI', 'sources': ['src/magick-cli.cc'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")'], 'dependencies': ['<!(node -p "require(\'node-addon-api\').gyp")'], 'conditions': [['OS=="linux" or OS=="s... |
# -*- coding: utf-8 -*-
##############################################
# Export CloudWatch metric data to csv file
# Configuration file
##############################################
METRICS = {
'CPUUtilization': ['AWS/EC2', 'AWS/RDS'],
'CPUCreditUsage': ['AWS/EC2', 'AWS/RDS'],
'CPUCreditBalance': ['AWS/EC2', 'AWS/... | metrics = {'CPUUtilization': ['AWS/EC2', 'AWS/RDS'], 'CPUCreditUsage': ['AWS/EC2', 'AWS/RDS'], 'CPUCreditBalance': ['AWS/EC2', 'AWS/RDS'], 'DiskReadOps': ['AWS/EC2'], 'DiskWriteOps': ['AWS/EC2'], 'DiskReadBytes': ['AWS/EC2'], 'DiskWriteBytes': ['AWS/EC2'], 'NetworkIn': ['AWS/EC2'], 'NetworkOut': ['AWS/EC2'], 'NetworkPa... |
NORTH, EAST, SOUTH, WEST = range(4)
class Compass(object):
compass = [NORTH, EAST, SOUTH, WEST]
def __init__(self, bearing=NORTH):
self.bearing = bearing
def left(self):
self.bearing = self.compass[self.bearing - 1]
def right(self):
self.bearing = self.compass[(self.bearing ... | (north, east, south, west) = range(4)
class Compass(object):
compass = [NORTH, EAST, SOUTH, WEST]
def __init__(self, bearing=NORTH):
self.bearing = bearing
def left(self):
self.bearing = self.compass[self.bearing - 1]
def right(self):
self.bearing = self.compass[(self.bearing... |
class SavingsAccount:
'''Defines a savings account'''
#static variables
RATE = 0.02
MIN_BALANCE = 25
def __init__(self, name, pin, balance = 0.0):
self.name = name
self.pin = pin
self.balance = balance
def __str__(self):
result = "Name: " + self.name + "\n... | class Savingsaccount:
"""Defines a savings account"""
rate = 0.02
min_balance = 25
def __init__(self, name, pin, balance=0.0):
self.name = name
self.pin = pin
self.balance = balance
def __str__(self):
result = 'Name: ' + self.name + '\n'
result += 'PIN: ' + ... |
MICROSERVICES = {
# Map locations to their microservices
"LOCATION_MICROSERVICES": [
{
"module": "intelligence.welcome.location_welcome_microservice",
"class": "LocationWelcomeMicroservice"
}
]
}
| microservices = {'LOCATION_MICROSERVICES': [{'module': 'intelligence.welcome.location_welcome_microservice', 'class': 'LocationWelcomeMicroservice'}]} |
ADDRESS_STR = ''
PRIVATE_KEY_STR = ''
GAS = 210000
GAS_PRICE = 5000000000
SECONDS_LEFT = 25
SELL_AFTER_WIN = False | address_str = ''
private_key_str = ''
gas = 210000
gas_price = 5000000000
seconds_left = 25
sell_after_win = False |
track_width = 0.6603288840524426
track_original = [(3.9968843292236325, -2.398085115814209), (4.108486819458006, -2.398085115814209),
(4.220117408752442, -2.398085115814209), (4.331728619384766, -2.3980848251342772),
(4.443350294494627, -2.398085115814209), (4.554988441467286, -2.398... | track_width = 0.6603288840524426
track_original = [(3.9968843292236325, -2.398085115814209), (4.108486819458006, -2.398085115814209), (4.220117408752442, -2.398085115814209), (4.331728619384766, -2.3980848251342772), (4.443350294494627, -2.398085115814209), (4.554988441467286, -2.398085115814209), (4.666571746826172, -... |
class DealProposal(object):
'''
Holds details about a deal proposed by one player to another.
'''
def __init__(
self,
propose_to_player=None,
properties_offered=None,
properties_wanted=None,
maximum_cash_offered=0,
minimum_cash_wan... | class Dealproposal(object):
"""
Holds details about a deal proposed by one player to another.
"""
def __init__(self, propose_to_player=None, properties_offered=None, properties_wanted=None, maximum_cash_offered=0, minimum_cash_wanted=0):
"""
The 'constructor'.
properties_offere... |
email = input()
while True:
line = input()
if line == 'Complete':
break
args = line.split()
command = args[0]
if command == 'Make':
result = ''
if args[1] == 'Upper':
for ch in email:
if ch.isalpha():
ch = ch.upp... | email = input()
while True:
line = input()
if line == 'Complete':
break
args = line.split()
command = args[0]
if command == 'Make':
result = ''
if args[1] == 'Upper':
for ch in email:
if ch.isalpha():
ch = ch.upper()
... |
# B_R_R
# M_S_A_W
# Accept a string
# Encode the received string into unicodes
# And decipher the unicodes back to its original form
# Convention of assigning characters with unicodes
# A - Z ---> 65-90
# a - z ---> 97-122
# ord("A") ---> 65
# chr(65) ---> A
# Enter a string to encode in uppercase
giv... | given_str = input('What is your word in mind(in uppercase please): ').upper()
secret_str = ''
norm_str = ''
for char in givenStr:
secret_str += str(ord(char))
print('The encrypted string is --->', secretStr)
for i in range(0, len(secretStr) - 1, 2):
char_code = secretStr[i] + secretStr[i + 1]
norm_str += ch... |
# Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably
# constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate
# ("backtracks") as soon as it determines that the candidate cannot possibly be complete... | def backtracking(self, data, candidate):
if self.reject(data, candidate):
return
if self.accept(data, candidate):
return self.output(data, candidate)
for cur_candidate in self.all_extension(data, candidate):
if not self.should_to_be_pruned(cur_candidate):
self.backtrackin... |
f = open('input.txt').readlines()
f = [line.strip().split(')') for line in f]
nodes = {}
for line in f:
nodes[line[1]] = set()
nodes['COM'] = set()
for line in f:
nodes[line[0]].add(line[1])
def predecessors(n):
global nodes
if n == 'COM':
return set([n])
for p in nodes:
if n ... | f = open('input.txt').readlines()
f = [line.strip().split(')') for line in f]
nodes = {}
for line in f:
nodes[line[1]] = set()
nodes['COM'] = set()
for line in f:
nodes[line[0]].add(line[1])
def predecessors(n):
global nodes
if n == 'COM':
return set([n])
for p in nodes:
if n in nod... |
#Creating a single link list static (Example-1)
class Node:
def __init__(self):
self.data=None
self.nxt=None
def assign_data(self,val):
self.data=val
def assign_add(self,addr):
self.nxt=addr
class ListPrint:
def printLinklist(self,tmp):
while(tm... | class Node:
def __init__(self):
self.data = None
self.nxt = None
def assign_data(self, val):
self.data = val
def assign_add(self, addr):
self.nxt = addr
class Listprint:
def print_linklist(self, tmp):
while tmp:
print(tmp.data, end=' ')
... |
# a *very* minimal conversion from a bitstream only fpga to fpga binary format
# that can be loaded by the qorc-sdk bootloader(v2.1 or above)
# 8 word header:
# bin version = 0.1 = 0x00000001
# bitstream size = 75960 = 0x000128B8
# bitstream crc = 0x0 (not used)
# meminit size = 0x0 (not used)
# meminit crc = 0x0 (n... | header = [1, 75960, 0, 0, 0, 0, 0, 0]
fpga_binary_bytearray = bytearray()
for each_word in header:
fpga_binary_bytearray.extend(int(each_word).to_bytes(4, 'little'))
with open('usb2serial.bit', 'rb') as fpga_bitstream:
fpga_binary_bytearray.extend(fpga_bitstream.read())
with open('usb2serial_fpga.bin', 'wb') as... |
class WrapperBase(object):
def __init__(self, instance_to_wrap):
self.wrapped = instance_to_wrap
def __getattr__(self, item):
assert item not in dir(self)
return self.wrapped.__getattribute__(item) | class Wrapperbase(object):
def __init__(self, instance_to_wrap):
self.wrapped = instance_to_wrap
def __getattr__(self, item):
assert item not in dir(self)
return self.wrapped.__getattribute__(item) |
# coding: utf-8
"""
Common utilities for the Widgets.
"""
TYPE_BTN_CONFIRM = "\u25a3"
TYPE_BTN_REJECT = "\u25c9"
TYPE_BTN_SELECT = "\u25c8"
def make_button_label(label: str, type=TYPE_BTN_CONFIRM, selected: bool = True) -> str:
"""
Turns any label into a button label standard.
:param label: Text
:re... | """
Common utilities for the Widgets.
"""
type_btn_confirm = '▣'
type_btn_reject = '◉'
type_btn_select = '◈'
def make_button_label(label: str, type=TYPE_BTN_CONFIRM, selected: bool=True) -> str:
"""
Turns any label into a button label standard.
:param label: Text
:return: button label string
"""
... |
def busca(inicio, fim, elemento, A):
if (fim >= inicio):
terco1 = inicio + (fim - inicio) // 3
terco2 = fim - (fim - inicio) // 3
if (A[terco1] == elemento):
return terco1
if (A[terco2] == elemento):
return terco2
if (elemento < A[terco1]):
... | def busca(inicio, fim, elemento, A):
if fim >= inicio:
terco1 = inicio + (fim - inicio) // 3
terco2 = fim - (fim - inicio) // 3
if A[terco1] == elemento:
return terco1
if A[terco2] == elemento:
return terco2
if elemento < A[terco1]:
return ... |
for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
s = ""
for i in range(n):
b[i] -= a[i]
for i in range(1,n):
s += str(abs(b[i] - b[i - 1]))
print("TAK") if (s == s[::-1]) else print("NIE") | for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
s = ''
for i in range(n):
b[i] -= a[i]
for i in range(1, n):
s += str(abs(b[i] - b[i - 1]))
print('TAK') if s == s[::-1] else print('NIE') |
#!/usr/bin/python3
class Complex:
def __init__(self, realpart, imagpart):
self.realpart = realpart
self.imagpart = imagpart
x = complex(3.0, -4.5)
print(x.real, x.imag)
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()
| class Complex:
def __init__(self, realpart, imagpart):
self.realpart = realpart
self.imagpart = imagpart
x = complex(3.0, -4.5)
print(x.real, x.imag)
class Test:
def prt(self):
print(self)
print(self.__class__)
t = test()
t.prt() |
__version__ = 0.1
__all__ = [
"secure",
"mft",
"logfile",
"usnjrnl",
]
| __version__ = 0.1
__all__ = ['secure', 'mft', 'logfile', 'usnjrnl'] |
def transform_type(val):
if val == 'payment':
return 3
elif val == 'transfer':
return 4
elif val == 'cash_out':
return 1
elif val == 'cash_in':
return 0
elif val == 'debit':
return 2
else:
return 0
def transform_nameDest(val):
dest = val[0]
if dest == 'M':
return 1
elif dest == '... | def transform_type(val):
if val == 'payment':
return 3
elif val == 'transfer':
return 4
elif val == 'cash_out':
return 1
elif val == 'cash_in':
return 0
elif val == 'debit':
return 2
else:
return 0
def transform_name_dest(val):
dest = val[0]
... |
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
# sketchy but works
greaterThanZero = (num > 0)
powerOfTwo = ((num & (num - 1)) == 0)
oneInOddPosition = ((num & 0x55555555) == num)
return greaterThanZe... | class Solution(object):
def is_power_of_four(self, num):
"""
:type num: int
:rtype: bool
"""
greater_than_zero = num > 0
power_of_two = num & num - 1 == 0
one_in_odd_position = num & 1431655765 == num
return greaterThanZero and powerOfTwo and oneInOdd... |
locs, labels = xticks()
xticks(locs, ("-10%", "-6.7%", "-3.3%", "0", "3.3%", "6.7%", "10%"))
xlabel("Percentage change")
ylabel("Number of Stocks")
title("Simulated Market Performance")
| (locs, labels) = xticks()
xticks(locs, ('-10%', '-6.7%', '-3.3%', '0', '3.3%', '6.7%', '10%'))
xlabel('Percentage change')
ylabel('Number of Stocks')
title('Simulated Market Performance') |
{ 'targets': [
{
'target_name': 'yajl',
'type': 'static_library',
'sources': [
'yajl/src/yajl.c',
'yajl/src/yajl_lex.c',
'yajl/src/yajl_parser.c',
'yajl/src/yajl_buf.c',
'yajl/src/yajl_encode.c',
'yajl/src/yajl_gen.c',
'yajl/src/yajl_alloc.c'... | {'targets': [{'target_name': 'yajl', 'type': 'static_library', 'sources': ['yajl/src/yajl.c', 'yajl/src/yajl_lex.c', 'yajl/src/yajl_parser.c', 'yajl/src/yajl_buf.c', 'yajl/src/yajl_encode.c', 'yajl/src/yajl_gen.c', 'yajl/src/yajl_alloc.c', 'yajl/src/yajl_tree.c', 'yajl/src/yajl_version.c'], 'cflags': ['-Wall', '-fvisib... |
"""Numerai main tournament metadata.
Convenience module defining some of the more static variables of the
Numerai main tournament.
The tournament is constantly evolving. Metadata from this module might
be outdated. Retrieving the most recent information using the `fetch_`
functions of the `nntm.datasets` module shoul... | """Numerai main tournament metadata.
Convenience module defining some of the more static variables of the
Numerai main tournament.
The tournament is constantly evolving. Metadata from this module might
be outdated. Retrieving the most recent information using the `fetch_`
functions of the `nntm.datasets` module shoul... |
def letUsCalculate():
print("Where n is the number of ELEMENTS in the SET, and R is the samples taken in the function\n")
print("///////////////////////////////\n")
print("///////////////////////////////\n")
print("///////////////////////////////\n")
print("///////////////////////////////\n")
pr... | def let_us_calculate():
print('Where n is the number of ELEMENTS in the SET, and R is the samples taken in the function\n')
print('///////////////////////////////\n')
print('///////////////////////////////\n')
print('///////////////////////////////\n')
print('///////////////////////////////\n')
... |
n=int(input('Numero:\n'))
i=1
while(i*i<=n):
i=i+1
print('La parte entera de la raiz cuadrada es: '+str(i-1)) | n = int(input('Numero:\n'))
i = 1
while i * i <= n:
i = i + 1
print('La parte entera de la raiz cuadrada es: ' + str(i - 1)) |
# Drop Tables
songplay_table_drop = "DROP TABLE IF EXISTS songplays"
user_table_drop = "DROP TABLE IF EXISTS users"
song_table_drop = "DROP TABLE IF EXISTS songs"
artist_table_drop = "DROP TABLE IF EXISTS artists"
time_table_drop = "DROP TABLE IF EXISTS time"
# Create Tables
songplay_table_create =("""
CREATE T... | songplay_table_drop = 'DROP TABLE IF EXISTS songplays'
user_table_drop = 'DROP TABLE IF EXISTS users'
song_table_drop = 'DROP TABLE IF EXISTS songs'
artist_table_drop = 'DROP TABLE IF EXISTS artists'
time_table_drop = 'DROP TABLE IF EXISTS time'
songplay_table_create = "\n CREATE TABLE IF NOT EXISTS songplays (\n ... |
dados = []
lista = []
maior = menor = 0
while True:
lista.append(str(input('Digite um nome: ')))
lista.append(float(input('Digite seu peso: ')))
while True:
escol = str(input('Quer continuar?[S/N] ')).upper().split()[0]
if escol in 'SN':
break
dados.append(lista[:])
lista... | dados = []
lista = []
maior = menor = 0
while True:
lista.append(str(input('Digite um nome: ')))
lista.append(float(input('Digite seu peso: ')))
while True:
escol = str(input('Quer continuar?[S/N] ')).upper().split()[0]
if escol in 'SN':
break
dados.append(lista[:])
lista... |
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
... | class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
... |
"""
Given a string s, find the longest palindromic substring in it.
I/P : "babad"
O/P : "bab"
"aba" is also a valid answer
I/P: "cbbd"
O/P: "bb
"""
# Approach 0 - get all possible substrings and check for palindrome.
# Approach 1: Using sliding window - Expanding around the center
"""
The core logic in this is:
1. Kee... | """
Given a string s, find the longest palindromic substring in it.
I/P : "babad"
O/P : "bab"
"aba" is also a valid answer
I/P: "cbbd"
O/P: "bb
"""
'\nThe core logic in this is:\n1. Keep one-pointer from the start of the string\n2. Keep second-pointer from the end of the string\n3. Because you are starting from revers... |
def print_rules(bit):
rules = []
# Bit Toggle
rules.append((
"// REG ^= (1 << %d)" % bit,
"replace restart {",
" ld a, %1",
" xor a, #%s" % format((1 << bit) & 0xff, '#04x'),
" ld %1, a",
"} by {",
" bcpl %%1, #%d ; peephole replaced xor b... | def print_rules(bit):
rules = []
rules.append(('// REG ^= (1 << %d)' % bit, 'replace restart {', ' ld a, %1', ' xor a, #%s' % format(1 << bit & 255, '#04x'), ' ld %1, a', '} by {', ' bcpl %%1, #%d ; peephole replaced xor by bcpl.' % bit, "} if notUsed('a')"))
rules.append(('// REG |= (1 << %d)' ... |
class RedirectException(Exception):
def __init__(self, redirect_to: str):
super().__init__()
self.redirect_to = redirect_to
| class Redirectexception(Exception):
def __init__(self, redirect_to: str):
super().__init__()
self.redirect_to = redirect_to |
AMAZON_COM: str = "https://www.amazon.com/"
DBA_DK: str = "https://www.dba.dk/"
EXAMPLE_COM: str = "http://example.com/"
GOOGLE_COM: str = "https://www.google.com/"
JYLLANDSPOSTEN_DK: str = "https://jyllands-posten.dk/"
IANA_ORG: str = "https://www.iana.org/domains/reserved"
W3SCHOOLS_COM: str = "https://www.w3sc... | amazon_com: str = 'https://www.amazon.com/'
dba_dk: str = 'https://www.dba.dk/'
example_com: str = 'http://example.com/'
google_com: str = 'https://www.google.com/'
jyllandsposten_dk: str = 'https://jyllands-posten.dk/'
iana_org: str = 'https://www.iana.org/domains/reserved'
w3_schools_com: str = 'https://www.w3schools... |
def read_file_to_string(filename):
with open(filename, 'r') as fin:
return fin.read()
def write_string_to_file(filename, content):
with open(filename, 'w') as fout:
fout.write(content)
| def read_file_to_string(filename):
with open(filename, 'r') as fin:
return fin.read()
def write_string_to_file(filename, content):
with open(filename, 'w') as fout:
fout.write(content) |
class SongLine:
# Uniquely ids all song lines
next_id = 0
def __init__(self, song_text: str, song):
"""A song line of a song
:type song_text: str
:param song_text: The lines text
:type song: Song.Song
:param song: The song this line is a part of
"""
#... | class Songline:
next_id = 0
def __init__(self, song_text: str, song):
"""A song line of a song
:type song_text: str
:param song_text: The lines text
:type song: Song.Song
:param song: The song this line is a part of
"""
self.id = self.next_id
Song... |
# Coding up the SVM Quiz
clf.fit(features_train, labels_train)
pred = clf.predict(features_test)
| clf.fit(features_train, labels_train)
pred = clf.predict(features_test) |
# https://www.hackerrank.com/challenges/grading/problem
def gradingStudents(grades):
rounded = []
for g in grades:
if (g < 38) or ((g % 5) < 3) :
rounded.append(g)
else:
rounded.append(g + (5 - (g % 5)))
return rounded
| def grading_students(grades):
rounded = []
for g in grades:
if g < 38 or g % 5 < 3:
rounded.append(g)
else:
rounded.append(g + (5 - g % 5))
return rounded |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
class ChineseChef:
def make_chicken(self):
print("The Chef makes Chicken")
def make_salad(self):
print("The Chef Makes Salad")
def make_special_dish(self):
print("The Chef makes Orange Chicken")
def make_fried_rice(self):
... | class Chinesechef:
def make_chicken(self):
print('The Chef makes Chicken')
def make_salad(self):
print('The Chef Makes Salad')
def make_special_dish(self):
print('The Chef makes Orange Chicken')
def make_fried_rice(self):
print('The Chef maked Fried Rice') |
Experiment(description='Multi d regression experiment',
data_dir='../data/uci-regression',
max_depth=20,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=2,
sd=2,
jitter_sd=0.1,
max_job... | experiment(description='Multi d regression experiment', data_dir='../data/uci-regression', max_depth=20, random_order=False, k=1, debug=False, local_computation=False, n_rand=2, sd=2, jitter_sd=0.1, max_jobs=400, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2014-04-21-uci-regressio... |
N, S = map(int, input().split())
ans = 0
for i in range(1, N+1):
for j in range(1, N+1):
if i + j <= S:
ans += 1
print(ans) | (n, s) = map(int, input().split())
ans = 0
for i in range(1, N + 1):
for j in range(1, N + 1):
if i + j <= S:
ans += 1
print(ans) |
class Model(object):
__db = None
__cache_engine = None
@classmethod
def set_db(cls, db):
cls.__db = db\
@classmethod
def get_db(cls):
return cls.__db
@property
def db(self):
return self.__db
@classmethod
def set_cache_engine(cls, cache_engine):
... | class Model(object):
__db = None
__cache_engine = None
@classmethod
def set_db(cls, db):
cls.__db = db
@classmethod
def get_db(cls):
return cls.__db
@property
def db(self):
return self.__db
@classmethod
def set_cache_engine(cls, cache_engine):
... |
# Using third argument in range
lst = [x for x in range(2,21,2)]
print(lst)
# Without using third argument in range
lst1 = [x for x in range(1,21) if(x%2 == 0)]
print(lst1) | lst = [x for x in range(2, 21, 2)]
print(lst)
lst1 = [x for x in range(1, 21) if x % 2 == 0]
print(lst1) |
COLUMNS = [
'tipo_registro',
'nro_pv',
'nro_rv',
'dt_rv',
'bancos',
'nro_parcela',
'vl_parcela_bruto',
'vl_desconto_sobre_parcela',
'vl_parcela_liquida',
'dt_credito',
'livre'
] | columns = ['tipo_registro', 'nro_pv', 'nro_rv', 'dt_rv', 'bancos', 'nro_parcela', 'vl_parcela_bruto', 'vl_desconto_sobre_parcela', 'vl_parcela_liquida', 'dt_credito', 'livre'] |
"""Calculate the Hamming Distance between two DNA Strands.
Given two strings each representing a DNA strand,
return the Hamming Distance between them.
"""
def distance(strand_a, strand_b):
"""Calculates the Hamming distance between two strands.
Args:
strand_a: A string representing a DNA strand.
... | """Calculate the Hamming Distance between two DNA Strands.
Given two strings each representing a DNA strand,
return the Hamming Distance between them.
"""
def distance(strand_a, strand_b):
"""Calculates the Hamming distance between two strands.
Args:
strand_a: A string representing a DNA strand.
... |
# 1. Write a line of Python code that displays the sum of 468 + 751
print(0.7 * (220-33) +0.3 * 55)
print(0.8 * (225-33) +0.35 * 55)
| print(0.7 * (220 - 33) + 0.3 * 55)
print(0.8 * (225 - 33) + 0.35 * 55) |
class CyCyError(Exception):
"""
Base class for non-runtime internal errors.
"""
def rstr(self):
name = self.__class__.__name__
return "%s\n%s\n\n%s" % (name, "-" * len(name), self.__str__())
| class Cycyerror(Exception):
"""
Base class for non-runtime internal errors.
"""
def rstr(self):
name = self.__class__.__name__
return '%s\n%s\n\n%s' % (name, '-' * len(name), self.__str__()) |
# https://leetcode.com/problems/insert-into-a-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def insertIntoBST(self, root: TreeNode, v... | class Solution:
def insert_into_bst(self, root: TreeNode, val: int) -> TreeNode:
def insert(root, node):
if root is None:
root = node
elif root.val < node.val:
if root.right is None:
root.right = node
else:
... |
#1
f = open('Grade2.txt', "a")
Score = open('Score1.txt',"r")
g=0
ll = Score.readline()
while ll != "":
l = ll.split(",")
#print(l)
eee = l[4][0:2]
e = int(eee)
if g <= e:
g=e
else:
g=g
ll = Score.readline()
print(ll)
f.write(str(g))
f.close()
Score.close() | f = open('Grade2.txt', 'a')
score = open('Score1.txt', 'r')
g = 0
ll = Score.readline()
while ll != '':
l = ll.split(',')
eee = l[4][0:2]
e = int(eee)
if g <= e:
g = e
else:
g = g
ll = Score.readline()
print(ll)
f.write(str(g))
f.close()
Score.close() |
def multiplyTwoList(head1, head2):
# Code here
a=""
b=""
temp1=head1
while temp1!=None:
a+=str(temp1.data)
temp1=temp1.next
# print a
temp2=head2
while temp2!=None:
b+=str(temp2.data)
temp2=temp2.next
# print b
return (int(a)*int(b))%MOD
| def multiply_two_list(head1, head2):
a = ''
b = ''
temp1 = head1
while temp1 != None:
a += str(temp1.data)
temp1 = temp1.next
temp2 = head2
while temp2 != None:
b += str(temp2.data)
temp2 = temp2.next
return int(a) * int(b) % MOD |
"""
Insertion sort
A simple sorting algorithm that builds the final sorted
array (or list) one item at a time. It is much less efficient on
large lists than more advanced algorithms such as quicksort, heapsort,
or merge sort.
Best Average Worst
n n2 n2
""" | """
Insertion sort
A simple sorting algorithm that builds the final sorted
array (or list) one item at a time. It is much less efficient on
large lists than more advanced algorithms such as quicksort, heapsort,
or merge sort.
Best Average Worst
n n2 n2
""" |
""" local enclosing local enclosing local ,global,builtin (legb)"""
name = 'rajat puri'# global
def greet():
name = 'rajat' #local
def hello():
print("hello"+name) #enclosing local
hello()
greet()
len(hello()) #builtin
| """ local enclosing local enclosing local ,global,builtin (legb)"""
name = 'rajat puri'
def greet():
name = 'rajat'
def hello():
print('hello' + name)
hello()
greet()
len(hello()) |
'''
Created on Sep 22, 2012
@author: Jason
'''
class DatasetError(Exception):
'''
I will use this class to raise dataset-related exceptions.
Common errors: Empty datasets provided, datasets with wrong
number of features, datasets lacking some feature or labels, etc
Used the ready-baked ... | """
Created on Sep 22, 2012
@author: Jason
"""
class Dataseterror(Exception):
"""
I will use this class to raise dataset-related exceptions.
Common errors: Empty datasets provided, datasets with wrong
number of features, datasets lacking some feature or labels, etc
Used the ready-baked template on... |
class App(object):
@property
def ScreenWidth(self):
return 1024
@property
def ScreenHeight(self):
return 768 | class App(object):
@property
def screen_width(self):
return 1024
@property
def screen_height(self):
return 768 |
#!/usr/bin/env python
one_kb = 1024
def to_mega_byte(data_size):
return (data_size * one_kb) * 1024
def calculate_symbol_size(generation_size, data_size):
return data_size / generation_size
def encoding_calculate(generation_size, symbols_size):
return generation_size * symbol_size
| one_kb = 1024
def to_mega_byte(data_size):
return data_size * one_kb * 1024
def calculate_symbol_size(generation_size, data_size):
return data_size / generation_size
def encoding_calculate(generation_size, symbols_size):
return generation_size * symbol_size |
length = 21
for i in range(length):
for j in range(length):
if (i == j):
print('*', end="")
elif (i == length-1-j):
print('*', end="")
elif (j == length//2 and i > length//10 and i < 0.9*length ):
print('*', end="")
else:
print(' ', e... | length = 21
for i in range(length):
for j in range(length):
if i == j:
print('*', end='')
elif i == length - 1 - j:
print('*', end='')
elif j == length // 2 and i > length // 10 and (i < 0.9 * length):
print('*', end='')
else:
print(' '... |
def max_window_sum(arr,w_size):
if len(arr) < w_size:
return None
running_sum = run_index = 0
max_val = float("-inf")
for item in range(w_size):
running_sum += arr[item]
for item in range (w_size , len(arr)):
if running_sum > max_val:
max_val = running_sum
running_sum -= arr[run_index]
running_sum ... | def max_window_sum(arr, w_size):
if len(arr) < w_size:
return None
running_sum = run_index = 0
max_val = float('-inf')
for item in range(w_size):
running_sum += arr[item]
for item in range(w_size, len(arr)):
if running_sum > max_val:
max_val = running_sum
... |
#
# PySNMP MIB module RADLAN-PIM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-PIM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:39:06 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, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint, constraints_union) ... |
class TagAdditionsEnum:
TAG_NAME = "name"
TAG_SMILES = "smiles"
TAG_ORIGINAL_SMILES = "original_smiles"
TAG_LIGAND_ID = "ligand_id"
# try to find the internal value and return
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
# pro... | class Tagadditionsenum:
tag_name = 'name'
tag_smiles = 'smiles'
tag_original_smiles = 'original_smiles'
tag_ligand_id = 'ligand_id'
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def __setattr__(self, key, value):
raise value_... |
def helper(memo, nums, i, j):
if i > j: return 0
if j == i: return nums[i]
if (i, j) in memo: return memo[(i, j)]
ans1 = nums[i] + min(helper(memo, nums, i + 2, j), helper(memo, nums, i + 1, j - 1))
ans2 = nums[j] + min(helper(memo, nums, i + 1, j - 1), helper(memo, nums, i, j - 2))
memo... | def helper(memo, nums, i, j):
if i > j:
return 0
if j == i:
return nums[i]
if (i, j) in memo:
return memo[i, j]
ans1 = nums[i] + min(helper(memo, nums, i + 2, j), helper(memo, nums, i + 1, j - 1))
ans2 = nums[j] + min(helper(memo, nums, i + 1, j - 1), helper(memo, nums, i, j ... |
# O(n) time with caching, O(n) space
def count_steps(n, cache = {}):
if n <= 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
if n in cache:
return cache[n]
cache[n] = count_steps(n - 1) + count_steps(n - 2) + count_steps(n - 3)
... | def count_steps(n, cache={}):
if n <= 0:
return 0
if n == 1:
return 1
if n == 2:
return 2
if n == 3:
return 4
if n in cache:
return cache[n]
cache[n] = count_steps(n - 1) + count_steps(n - 2) + count_steps(n - 3)
return cache[n]
'\n# O(3^n) time, naive... |
""" project-scoped settings """
LOGGING_LEVEL = 'INFO'
CSV_MAX_FILE_SIZE_MB = 1024
S3_BUCKET_NAME = 'migrations-redshift-123'
S3_TARGET_DIR = 'files_to_copy_to_redshift'
REDSHIFT_DB = 'dev'
| """ project-scoped settings """
logging_level = 'INFO'
csv_max_file_size_mb = 1024
s3_bucket_name = 'migrations-redshift-123'
s3_target_dir = 'files_to_copy_to_redshift'
redshift_db = 'dev' |
class Paren:
def __init__(self, paren):
if paren == '(':
LParen()
@staticmethod
def getParen(paren):
if paren == '(': return LParen()
elif paren == ')': return RParen()
elif paren == '{': return LBrace()
elif paren == '}': return RBrace()
def __str__... | class Paren:
def __init__(self, paren):
if paren == '(':
l_paren()
@staticmethod
def get_paren(paren):
if paren == '(':
return l_paren()
elif paren == ')':
return r_paren()
elif paren == '{':
return l_brace()
elif pare... |
# Escreva um algoritmo para ler um valor (do teclado) e escrever (na tela) o seu antecessor. (SOMENTE NUMERO INTEIRO)
num = int(input('Digite um valor na tela: '))
res = num - 1
print(res)
| num = int(input('Digite um valor na tela: '))
res = num - 1
print(res) |
class Wotd():
def __init__(
self,
definition: str,
englishExample: str,
foreignExample: str,
language: str,
transliteration: str,
word: str
):
if definition is None or len(definition) == 0 or definition.isspace():
raise ValueError(
... | class Wotd:
def __init__(self, definition: str, englishExample: str, foreignExample: str, language: str, transliteration: str, word: str):
if definition is None or len(definition) == 0 or definition.isspace():
raise value_error(f'definition argument is malformed: "{definition}"')
elif l... |
"""
63. Unique Paths II
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Now consider if some obst... | """
63. Unique Paths II
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Now consider if some obst... |
"""Submodule for the `Namespace` class, which tracks `Named` objects to detect
conflicts."""
class Namespace:
"""Managed set of uniquely named `Named` and nested `Namespace` objects.
This is used to check uniqueness of the `name` and `mnemonic` values."""
def __init__(self, name, check_mnemonics=True):
... | """Submodule for the `Namespace` class, which tracks `Named` objects to detect
conflicts."""
class Namespace:
"""Managed set of uniquely named `Named` and nested `Namespace` objects.
This is used to check uniqueness of the `name` and `mnemonic` values."""
def __init__(self, name, check_mnemonics=True):
... |
n = int(input("Enter n: "))
x = 2
y = 2
x1 = 0
flag = False
''' Gives false at 2 and 3 because powers start from 2'''
if n == 1:
print("Output: True\n" + str(n) + " can be expressed as " + str(1) + "^(0, 1, 2, 3, 4, 5, ......)")
else:
while x <= n:
#print(x)
while x1 < n:
... | n = int(input('Enter n: '))
x = 2
y = 2
x1 = 0
flag = False
' Gives false at 2 and 3 because powers start from 2'
if n == 1:
print('Output: True\n' + str(n) + ' can be expressed as ' + str(1) + '^(0, 1, 2, 3, 4, 5, ......)')
else:
while x <= n:
while x1 < n:
x1 = x ** y
if x1 == ... |
SECRET_KEY = 'Software_Fellowship_Day_4'
DEBUG = True
ENV = 'development'
API_KEY = "API_KEY_GOES_HERE"
| secret_key = 'Software_Fellowship_Day_4'
debug = True
env = 'development'
api_key = 'API_KEY_GOES_HERE' |
def output():
test_case = int(input())
if 2 <= test_case <= 99:
for i in range(test_case):
i_put = input()
print('gzuz')
if __name__ == '__main__':
output()
| def output():
test_case = int(input())
if 2 <= test_case <= 99:
for i in range(test_case):
i_put = input()
print('gzuz')
if __name__ == '__main__':
output() |
# DFS
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
res = 0
visited = [0]*len(M)
for i in range(len(M)):
if visited[i] == 0:
res += 1
visited[i] = 1
self.dfs(M, i, visited)
return res
... | class Solution:
def find_circle_num(self, M: List[List[int]]) -> int:
res = 0
visited = [0] * len(M)
for i in range(len(M)):
if visited[i] == 0:
res += 1
visited[i] = 1
self.dfs(M, i, visited)
return res
def dfs(self, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.