content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
name = input("Please enter your name: ")
if name == 'Bob':
print("You are a part of the top 1 percent!")
elif name == 'Alice':
print("You are a part of the top 1 percent!")
else:
print("Go away filthy peasent")
| name = input('Please enter your name: ')
if name == 'Bob':
print('You are a part of the top 1 percent!')
elif name == 'Alice':
print('You are a part of the top 1 percent!')
else:
print('Go away filthy peasent') |
## Integer Type
num = 3
# type()
print(type(num)) # <class 'int'>
## Float Type
num = 3.14156
print(type(num)) # <class 'float'>
### Arithmetics operator
# Addition : 3 + 2 ==> 5
# Subtraction : 3 - 2 ==> 1
# Multiplication : 3 * 10 ==> 30
# Division : 3 / 2 ... | num = 3
print(type(num))
num = 3.14156
print(type(num))
print(3 + 2)
print(3 - 2)
print(3 * 2)
print(3 / 2)
print(3 // 2)
print(3 ** 2)
print(3 % 2)
print(4 % 2)
print(5 % 2)
print(abs(-3))
print(round(3.75))
print(round(3.45))
'\nHelp on built-in function round in module builtins:\n\nround(number, ndigits=None)\n R... |
"""Constants for the HomeSeer integration."""
DOMAIN = "homeseer"
ATTR_REF = "ref"
ATTR_LOCATION = "location"
ATTR_LOCATION2 = "location2"
ATTR_NAME = "name"
ATTR_VALUE = "value"
ATTR_STATUS = "status"
ATTR_DEVICE_TYPE_STRING = "device_type_string"
ATTR_LAST_CHANGE = "last_change"
CONF_HTTP_PORT = "http_port"
CONF_A... | """Constants for the HomeSeer integration."""
domain = 'homeseer'
attr_ref = 'ref'
attr_location = 'location'
attr_location2 = 'location2'
attr_name = 'name'
attr_value = 'value'
attr_status = 'status'
attr_device_type_string = 'device_type_string'
attr_last_change = 'last_change'
conf_http_port = 'http_port'
conf_asci... |
# Importable string for GQL query
org_team_members_query = """query orgTeamMembers($organization: String!, $team: String!) {
organization(login:$organization) {
team(slug:$team) {
name
members{
nodes {
login
name
... | org_team_members_query = 'query orgTeamMembers($organization: String!, $team: String!) {\n organization(login:$organization) {\n team(slug:$team) {\n name\n members{\n nodes {\n login\n name\n }\n }\n }... |
my_list = ["a", "b", "c", "d", "e"]
item_count = len(my_list)
print(f"My list has {item_count} items:")
for i in my_list:
print(i) | my_list = ['a', 'b', 'c', 'd', 'e']
item_count = len(my_list)
print(f'My list has {item_count} items:')
for i in my_list:
print(i) |
class Solution:
def isMajorityElement(self, nums: List[int], target: int) -> bool:
'''
T: O(log n) and S: O(1)
'''
def binarySearch(nums, target, side):
index = -1
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
... | class Solution:
def is_majority_element(self, nums: List[int], target: int) -> bool:
"""
T: O(log n) and S: O(1)
"""
def binary_search(nums, target, side):
index = -1
(lo, hi) = (0, len(nums) - 1)
while lo <= hi:
mid = lo + (hi - ... |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
result, count = nums[0], 1
for num in nums:
if result == num:
count += 1
else:
if count == 1:
result = num
else:
count -= 1
return result
| class Solution:
def majority_element(self, nums: List[int]) -> int:
(result, count) = (nums[0], 1)
for num in nums:
if result == num:
count += 1
elif count == 1:
result = num
else:
count -= 1
return result |
#
# PySNMP MIB module ENTERASYS-THREAT-NOTIFICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-THREAT-NOTIFICATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_range_constraint, value_size_constraint) ... |
def quick_sort(items):
if len(items) > 1:
pivot_index = 0
smaller_items = []
larger_items = []
for i, val in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
... | def quick_sort(items):
if len(items) > 1:
pivot_index = 0
smaller_items = []
larger_items = []
for (i, val) in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
... |
def test_one(camera):
assert "camera" in globals() or "camera" in locals()
"""def test_two(self):
camera.start_mjpg_streamer()
assert camera.check_mjpg_streamer()"""
"""def test_three(self):
camera.stop_mjpg_streamer()
assert not camera.check_mjpg_streamer()"""
"""def test_four(self):
fname ... | def test_one(camera):
assert 'camera' in globals() or 'camera' in locals()
'def test_two(self):\n camera.start_mjpg_streamer()\n assert camera.check_mjpg_streamer()'
'def test_three(self):\n camera.stop_mjpg_streamer()\n assert not camera.check_mjpg_streamer()'
'def test_four(self):\n fname = camera.... |
"""
Differences between alpa.parallelize and jax.pmap
=================================================
The most common tool for parallelization or distributed computing in jax is
`pmap <https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap>`_.
With several lines of code change, we can use ``pmap`` for da... | """
Differences between alpa.parallelize and jax.pmap
=================================================
The most common tool for parallelization or distributed computing in jax is
`pmap <https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap>`_.
With several lines of code change, we can use ``pmap`` for da... |
'''
#params: 9104483
[1] train-result=0.4161, valid-result=0.4865 [62.0 s]
[2] train-result=0.5830, valid-result=0.5648 [67.0 s]
[3] train-result=0.6017, valid-result=0.5805 [67.7 s]
[4] train-result=0.6100, valid-result=0.5874 [73.3 s]
[5] train-result=0.6135, valid-result=0.5911 [66.8 s]
[6] train-result=0.6151, val... | """
#params: 9104483
[1] train-result=0.4161, valid-result=0.4865 [62.0 s]
[2] train-result=0.5830, valid-result=0.5648 [67.0 s]
[3] train-result=0.6017, valid-result=0.5805 [67.7 s]
[4] train-result=0.6100, valid-result=0.5874 [73.3 s]
[5] train-result=0.6135, valid-result=0.5911 [66.8 s]
[6] train-result=0.6151, vali... |
"""Load dependencies needed to compile the protobuf library as a 3rd-party consumer."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
PROTOBUF_MAVEN_ARTIFACTS = [
"com.google.code.findbugs:jsr305:3.0.2",
"com.google.code.gson:gson:2.8.9",
"com.google.errorprone:error_prone_annotatio... | """Load dependencies needed to compile the protobuf library as a 3rd-party consumer."""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
protobuf_maven_artifacts = ['com.google.code.findbugs:jsr305:3.0.2', 'com.google.code.gson:gson:2.8.9', 'com.google.errorprone:error_prone_annotations:2.3.2', 'com... |
def search(min_, max_, els, dec, inc):
for c in els:
if c == dec:
max_ = (min_+max_)/2
elif c == inc:
min_ = (min_+max_)/2
return min_
def getid(card):
l = search(0, 128, card[:7], 'F', 'B')
c = search(0, 8, card[7:], 'L', 'R')
return l, c
with open('in... | def search(min_, max_, els, dec, inc):
for c in els:
if c == dec:
max_ = (min_ + max_) / 2
elif c == inc:
min_ = (min_ + max_) / 2
return min_
def getid(card):
l = search(0, 128, card[:7], 'F', 'B')
c = search(0, 8, card[7:], 'L', 'R')
return (l, c)
with open... |
# Binary search recursive version
def rec_binary_search(arr, ele):
if len(arr) == 0:
return False
else:
mid = int(len(arr)/2)
if arr[mid] == ele:
return True
else:
if ele < arr[mid]:
return rec_binary_search(arr[:mid], ele)
e... | def rec_binary_search(arr, ele):
if len(arr) == 0:
return False
else:
mid = int(len(arr) / 2)
if arr[mid] == ele:
return True
elif ele < arr[mid]:
return rec_binary_search(arr[:mid], ele)
else:
return rec_binary_search(arr[mid + 1:], el... |
class CabernetException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return 'CabernetException: %s' % self.value
| class Cabernetexception(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return 'CabernetException: %s' % self.value |
def get_coordinate(record):
pass
def convert_coordinate(coordinate):
pass
def compare_records(azara_record, rui_record):
pass
def create_record(azara_record, rui_record):
pass
def clean_up(combined_record_group):
pass
| def get_coordinate(record):
pass
def convert_coordinate(coordinate):
pass
def compare_records(azara_record, rui_record):
pass
def create_record(azara_record, rui_record):
pass
def clean_up(combined_record_group):
pass |
# This object is created to carry along the variables of interest for display purposes
class RegObject:
def __init__(self, res_list, interest, controls):
self.res = res_list
self.variables_of_interest = list(dict.fromkeys([x.lower() for x in interest]))
# This avoids errors in the formatte... | class Regobject:
def __init__(self, res_list, interest, controls):
self.res = res_list
self.variables_of_interest = list(dict.fromkeys([x.lower() for x in interest]))
self.controls = []
for item in list(dict.fromkeys([x.lower() for x in controls])):
if item not in self.v... |
# -*- coding: utf-8 -*-
def devices_info_all(pushbots):
return pushbots.devices_info_all()
def device_info(pushbots, token):
return pushbots.device_info(token=token)
| def devices_info_all(pushbots):
return pushbots.devices_info_all()
def device_info(pushbots, token):
return pushbots.device_info(token=token) |
def determine_config_type(config_parser):
'''Determines the type of a ceph.conf file and returns it.
Args:
config_parser (configparser): Parser object with read in ceph.conf to check.
Returns:
rados_deploy.StorageType of the ceph.conf.'''
if 'memstore device bytes' in config_parser['gl... | def determine_config_type(config_parser):
"""Determines the type of a ceph.conf file and returns it.
Args:
config_parser (configparser): Parser object with read in ceph.conf to check.
Returns:
rados_deploy.StorageType of the ceph.conf."""
if 'memstore device bytes' in config_parser['glo... |
class IgnoreMe:
def __init__(self, *args, **kwds): ...
def __call__(self, *args, **kwds): return self
def __getattr__(self, __name: str): return self
def __bool__(self): return False
def __nonzero__(self): return self.__bool__() | class Ignoreme:
def __init__(self, *args, **kwds):
...
def __call__(self, *args, **kwds):
return self
def __getattr__(self, __name: str):
return self
def __bool__(self):
return False
def __nonzero__(self):
return self.__bool__() |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 01:50:15 2018
@author: Akash
"""
class Queue:
def __init__(self):
self.queue = list()
def enqueue(self, data):
self.queue.insert(0, data)
return True
def dequeue(self):
return self.queue.p... | """
Created on Fri Jun 22 01:50:15 2018
@author: Akash
"""
class Queue:
def __init__(self):
self.queue = list()
def enqueue(self, data):
self.queue.insert(0, data)
return True
def dequeue(self):
return self.queue.pop()
def size_queue(self):
return len(self.q... |
# encoding: utf-8
# module select
# from (pre-generated)
# by generator 1.147
"""
This module supports asynchronous I/O on multiple file descriptors.
*** IMPORTANT NOTICE ***
On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.
"""
# no imports
# functions
def select(rlist, wlist, xlist... | """
This module supports asynchronous I/O on multiple file descriptors.
*** IMPORTANT NOTICE ***
On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptors.
"""
def select(rlist, wlist, xlist, timeout=None):
"""
select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)
Wa... |
def merge_ordered_list(in_list1: list, in_list2: list) -> list:
"""
Merge two ordered list
:param in_list1: the first source list
:param in_list2: the second source list
:return: the merged list
"""
_list1 = in_list1.copy()
_list2 = in_list2.copy()
_output_list = []
idx_2 = 0
... | def merge_ordered_list(in_list1: list, in_list2: list) -> list:
"""
Merge two ordered list
:param in_list1: the first source list
:param in_list2: the second source list
:return: the merged list
"""
_list1 = in_list1.copy()
_list2 = in_list2.copy()
_output_list = []
idx_2 = 0
... |
k=1
for i in range(1,6):
for j in range(i):
if k<10:
print(k,end='')
k+=1
if k==10:
print(1,end='')
else:
k=2
print()
| k = 1
for i in range(1, 6):
for j in range(i):
if k < 10:
print(k, end='')
k += 1
if k == 10:
print(1, end='')
else:
k = 2
print() |
def launch_network():
global network
global difficulty
network = set()
difficulty = 1
| def launch_network():
global network
global difficulty
network = set()
difficulty = 1 |
'''
@Date: 2019-12-08 19:58:01
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-12-08 20:01:19
'''
def count(s, ch):
num = 0
for char in s:
if char == ch:
num += 1
return num
def main():
strings = input("Input a string: ... | """
@Date: 2019-12-08 19:58:01
@Author: ywyz
@LastModifiedBy: ywyz
@Github: https://github.com/ywyz
@LastEditors: ywyz
@LastEditTime: 2019-12-08 20:01:19
"""
def count(s, ch):
num = 0
for char in s:
if char == ch:
num += 1
return num
def main():
strings = input('Input a string: ')
... |
# !/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Define a string containing special characters in #
# vario... | if __name__ == '__main__':
print()
print('\\#{\'}${"}@/')
print('\\#{\'}${"}@/')
print('\\#{\'}${"}@/')
print('\\#{\'}${"}@/')
print('\\#{\'}${"}@/')
print('\\#{\'}${"}@/')
print() |
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution2:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def dfs(node, depth):
if node is Non... | class Treenode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution2:
def level_order_bottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def dfs(node, depth):
if node is No... |
__all__ = ['getColMap', 'ColMapDict']
def getColMap(opsdb):
"""Get the colmap dictionary, if you already have a database object.
Parameters
----------
opsdb : rubin_sim.maf.db.Database or rubin_sim.maf.db.OpsimDatabase
Returns
-------
dictionary
"""
try:
version = opsdb.o... | __all__ = ['getColMap', 'ColMapDict']
def get_col_map(opsdb):
"""Get the colmap dictionary, if you already have a database object.
Parameters
----------
opsdb : rubin_sim.maf.db.Database or rubin_sim.maf.db.OpsimDatabase
Returns
-------
dictionary
"""
try:
version = opsdb.... |
class OptimizerWrapper:
"""
A wrapper to make optimizer more concise
"""
def __init__(self, model, optimizer, lr_scheduler=None):
self.model = model
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
def step(self, inputs, labels):
self.zero_grad()
... | class Optimizerwrapper:
"""
A wrapper to make optimizer more concise
"""
def __init__(self, model, optimizer, lr_scheduler=None):
self.model = model
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
def step(self, inputs, labels):
self.zero_grad()
... |
#
# PySNMP MIB module ORiNOCO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ORiNOCO-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:35:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, constraints_union, single_value_constraint) ... |
n = int(input())
segundos = n%60
minutos = (n / 60) % 60
horas = n / (60 * 60)
print("%i:%i:%i" % (horas, minutos, segundos)) | n = int(input())
segundos = n % 60
minutos = n / 60 % 60
horas = n / (60 * 60)
print('%i:%i:%i' % (horas, minutos, segundos)) |
# s <= ns
# 1. e <= ns: change
# 2. ns < e < ne: change
# => e < ne: change
# else: cnt += 1, don't change
class Solution:
def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
s = e = -1
cnt = 0
for ns, ne in intervals:
if e < ne:
... | class Solution:
def remove_covered_intervals(self, intervals: List[List[int]]) -> int:
intervals.sort()
s = e = -1
cnt = 0
for (ns, ne) in intervals:
if e < ne:
if s == ns:
cnt += 1
(s, e) = (ns, ne)
else:
... |
# List
grades=[12,60,15,70,90]
grades[0]=55 #update grades[0]
print (grades[0])
print (grades[1:4])
grades = grades + [12,33]
print (grades)
length = len(grades)
print(length)
# Nested List
data = [[3,4,5],[6,7,8]]
print(data[0][1])
print(data[0][0:2])
data[0][0:2] = [5,5,5]
print(data)
# Tuple
print ("///////////... | grades = [12, 60, 15, 70, 90]
grades[0] = 55
print(grades[0])
print(grades[1:4])
grades = grades + [12, 33]
print(grades)
length = len(grades)
print(length)
data = [[3, 4, 5], [6, 7, 8]]
print(data[0][1])
print(data[0][0:2])
data[0][0:2] = [5, 5, 5]
print(data)
print('///////////////////////// Tuple ///////////////////... |
# Copyright 2017 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | def get_switch_device(switches, switch_info=None, ngs_mac_address=None):
"""Return switch device by specified identifier.
Returns switch device from switches array that matched with any of
passed identifiers. ngs_mac_address takes precedence over switch_info,
if didn't match any address based on mac fa... |
# Variables
x = 15
price = 9.99
discount = 0.2
result = price * (1 - discount)
print(result)
| x = 15
price = 9.99
discount = 0.2
result = price * (1 - discount)
print(result) |
# Security misconfiguration is the most commonly seen issue. This is commonly a result of insecure
# default configurations, incomplete or ad hoc configurations, open cloud storage, misconfigured
# HTTP headers, and verbose error messages containing sensitive information. Not only must all
# operating systems, frame... | class Security_Misconfiguration:
def __init__(self, scopeURL, outOfScopeURL):
self.scopeURL = scopeURL
self.outOfScopeURL = outOfScopeURL |
"""
net: a set of processes;
compartment: a compartment consists of input:
space: [];
"""
"""
from sth import register, register into which net;
# function.py (external)
def process_a(data, parameter):
# data must be a regular objects.
pass
# assembling net
from function import process_a
net = Net()
n... | """
net: a set of processes;
compartment: a compartment consists of input:
space: [];
"""
'\nfrom sth import register, register into which net;\n\n# function.py (external)\ndef process_a(data, parameter):\n # data must be a regular objects.\n pass\n \n# assembling net\nfrom function import process_a\n\nnet =... |
class Solution:
def nextGreatestLetter(self, letters, target):
left, right = 0, len(letters) - 1
while left < right:
mid = left + (right - left) // 2
if letters[mid] > target:
right = mid
else:
left = mid + 1
if letters[lef... | class Solution:
def next_greatest_letter(self, letters, target):
(left, right) = (0, len(letters) - 1)
while left < right:
mid = left + (right - left) // 2
if letters[mid] > target:
right = mid
else:
left = mid + 1
if lette... |
class Document:
def __init__(self,SentenceList,id=-1):
self.id=id
self.value=SentenceList
self.attr={}
def __str__(self):
s ="Document id: {0}, value: {1}, attributes: {2}".format(self.id,self.value,self.attr)
return s
| class Document:
def __init__(self, SentenceList, id=-1):
self.id = id
self.value = SentenceList
self.attr = {}
def __str__(self):
s = 'Document id: {0}, value: {1}, attributes: {2}'.format(self.id, self.value, self.attr)
return s |
'''
At this point, you've got all the basics necessary to start employing modules.
We still have to teach classes, among a few other necessary basics, but now
would be a good time to talk about modules.
IF you are using linux, installing python modules is incredibly stupid easy.
For programming, linux is just lovely... | """
At this point, you've got all the basics necessary to start employing modules.
We still have to teach classes, among a few other necessary basics, but now
would be a good time to talk about modules.
IF you are using linux, installing python modules is incredibly stupid easy.
For programming, linux is just lovely... |
# You can customize these lists according to you're requirement.
#list for finding admin panels:
adminfinder_db = ["/acceso.asp", "/acceso.php", "/access/", "/access.php", "/account/", "/account.asp", "/account.html", "/account.php", "/acct_login/", "/_adm_/", "/_adm/", "/adm/", "/adm2/", "/adm/admloginuser.asp", "/ad... | adminfinder_db = ['/acceso.asp', '/acceso.php', '/access/', '/access.php', '/account/', '/account.asp', '/account.html', '/account.php', '/acct_login/', '/_adm_/', '/_adm/', '/adm/', '/adm2/', '/adm/admloginuser.asp', '/adm/admloginuser.php', '/adm.asp', '/adm_auth.asp', '/adm_auth.php', '/adm.html', '/_admin_/', '/_ad... |
class Intersection:
def __init__(self, no, x_p, y_p):
self.no = no
self.x = x_p
self.y = y_p | class Intersection:
def __init__(self, no, x_p, y_p):
self.no = no
self.x = x_p
self.y = y_p |
##Ejercicio 2
# el siguiente codigo identifica si existe alguna suma entre dos elementos
# distintos dentro de la listta , que sumen 10.
# Complejidad del algoritmo : O(n^2) por los dos for implementados uno dentro del otro
#
# Entrada:
# -
#Si hay entonces
# Salida:
# Son: 2 + 8 = 10
# True
#Si no
# Salida:
# Fal... | def two_sum(array):
for i in range(len(array)):
for j in range(len(array)):
if i != j and array[i] + array[j] == 10:
print('Hay al menos 2 numeros que suman 10')
print('Son: ' + str(array[i]) + ' + ' + str(array[j]) + ' = 10')
return True
retur... |
"""
Given two integer arrays of equal length target and arr.
In one step, you can select any non-empty sub-array of arr and reverse it.
You are allowed to make any number of steps.
Return True if you can make arr equal to target, or False otherwise.
Example:
Input: target = [1,2,... | """
Given two integer arrays of equal length target and arr.
In one step, you can select any non-empty sub-array of arr and reverse it.
You are allowed to make any number of steps.
Return True if you can make arr equal to target, or False otherwise.
Example:
Input: target = [1,2,... |
#fibbonancci numvers
def fibonancci(n):
if n <= 1:
return 1
l = [None]*(n+1)
# l[:n] = 0*(n)
l[0]= 0
l[1] = 1
# print(l)
for i in range(2,n+1):
l[i] = l[i-1]+l[i-2]
print(l)
return l[n+1]
def fib_rec(n):
if n <= 1:
return n
print(n)
retu... | def fibonancci(n):
if n <= 1:
return 1
l = [None] * (n + 1)
l[0] = 0
l[1] = 1
for i in range(2, n + 1):
l[i] = l[i - 1] + l[i - 2]
print(l)
return l[n + 1]
def fib_rec(n):
if n <= 1:
return n
print(n)
return fib_rec(n - 1) + fib_rec(n - 2)
if __name__... |
#Intersection class, the processing unit where traffic light control takes place
#coded by sayfeddine
DEFAULT_CYCLE = 60 # default cycle length to start with ( in seconds or "step" for SUMO)
"""
cycle length formula :
C = (1.5*L + 5)/(1.0 - SYi))
C : optimum cycle length that minimise the delay
cycle is always betwee... | default_cycle = 60
'\ncycle length formula : \nC = (1.5*L + 5)/(1.0 - SYi))\nC : optimum cycle length that minimise the delay\ncycle is always between 0.75*C and 1.5*C\nL = Unusable time per cycle in seconds usually taken as a sum of the vehicle signal change intervals.\nSYi = critical lane volume each phase/saturation... |
# Define a function to find the truth by shifting the letter by a specified amount
def lassoLetter( letter, shiftAmount ):
# Invoke the ord function to translate the letter to its ASCII code
# Save the code value to the variable called letterCode
letterCode = ord(letter.lower())
# The ASCII number repr... | def lasso_letter(letter, shiftAmount):
letter_code = ord(letter.lower())
a_ascii = ord('a')
alphabet_size = 26
true_letter_code = aAscii + (letterCode - aAscii + shiftAmount) % alphabetSize
decoded_letter = chr(trueLetterCode)
return decodedLetter
def lasso_word(word, shiftAmount):
decoded_... |
def isInterleave(s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
m, n, t = len(s1), len(s2), len(s3)
if m + n != t:
return False
dp = [False] * (n + 1)
dp[0] = True
for i in range(m + 1):
for j in range(n + 1):
if i > 0:... | def is_interleave(s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
(m, n, t) = (len(s1), len(s2), len(s3))
if m + n != t:
return False
dp = [False] * (n + 1)
dp[0] = True
for i in range(m + 1):
for j in range(n + 1):
if i... |
def reconcile(hub, high):
'''
Take the extend statement and reconcile it back into the highdata
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for id_, body in ext_chunk:
if id_ not in high:
... | def reconcile(hub, high):
"""
Take the extend statement and reconcile it back into the highdata
"""
errors = []
if '__extend__' not in high:
return (high, errors)
ext = high.pop('__extend__')
for ext_chunk in ext:
for (id_, body) in ext_chunk:
if id_ not in high:
... |
class SlabShapeVertexType(Enum, IComparable, IFormattable, IConvertible):
"""
An enumerated type listing all Vertex types of Slab Shape Edit.
enum SlabShapeVertexType,values: Corner (1),Edge (2),Interior (3),Invalid (0)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) ... | class Slabshapevertextype(Enum, IComparable, IFormattable, IConvertible):
"""
An enumerated type listing all Vertex types of Slab Shape Edit.
enum SlabShapeVertexType,values: Corner (1),Edge (2),Interior (3),Invalid (0)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx... |
"""
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer n, return its complement.
Example 1:
Input: n = 5
Output: ... | """
The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.
For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.
Given an integer n, return its complement.
Example 1:
Input: n = 5
Output: ... |
def approximation(x, x1, x2, y, y1, y2):
a1 = (y1-y)/(x1-x)
a2 = (1/(x2-x1))*(((y2-y)/(x2-x)) - ((y1-y)/(x1-x)))
return ((x1+x)/2) - (a1/(2*a2))
| def approximation(x, x1, x2, y, y1, y2):
a1 = (y1 - y) / (x1 - x)
a2 = 1 / (x2 - x1) * ((y2 - y) / (x2 - x) - (y1 - y) / (x1 - x))
return (x1 + x) / 2 - a1 / (2 * a2) |
'''
CLASS: VnfmDriverTemplate
AUTHOR: Vinicius Fulber-Garcia
CREATION: 21 Oct. 2020
L. UPDATE: 28 Jul. 2021 (Fulber-Garcia; Included the "vnfmAddress" attribute)
DESCRIPTION: Template for the implementation of VNFM drivers that run in the "Access Subsystem"
internal module. The drivers must inhert this class ... | """
CLASS: VnfmDriverTemplate
AUTHOR: Vinicius Fulber-Garcia
CREATION: 21 Oct. 2020
L. UPDATE: 28 Jul. 2021 (Fulber-Garcia; Included the "vnfmAddress" attribute)
DESCRIPTION: Template for the implementation of VNFM drivers that run in the "Access Subsystem"
internal module. The drivers must inhert this class and ov... |
# Optional Problem Set, Question 1
def ndigits(x):
'''
assumes x is an integer
returns the digits of x
'''
# If x equals 0 (due to integer division), it means that no digits are left.
if x == 0:
return 0
# Otherwise, it returns 1 + the digits of the integer divided by 10.
return... | def ndigits(x):
"""
assumes x is an integer
returns the digits of x
"""
if x == 0:
return 0
return 1 + ndigits(abs(x) / 10) |
version = '1.3.1'
major = 1
minor = 3
micro = 1
release_level = 'final'
serial = 0
version_info = (major, minor, micro, release_level, serial)
| version = '1.3.1'
major = 1
minor = 3
micro = 1
release_level = 'final'
serial = 0
version_info = (major, minor, micro, release_level, serial) |
#import math
res = set()
for i in range(2,101):
for j in range(2,101):
res.add(i ** j)
print(len(res)) | res = set()
for i in range(2, 101):
for j in range(2, 101):
res.add(i ** j)
print(len(res)) |
class Solution:
def addBinary(self, a: str, b: str) -> str:
c=int(a,2)+int(b,2)
return str(bin(c))[2:]
| class Solution:
def add_binary(self, a: str, b: str) -> str:
c = int(a, 2) + int(b, 2)
return str(bin(c))[2:] |
n=int(input())
if n%2!=0:
print("Weird")
if n in range(2,7) and n%2==0:
print("Not Weird")
if n in range(6,21) and n%2==0:
print("Weird")
if n>20 and n%2==0:
print("Not Weird") | n = int(input())
if n % 2 != 0:
print('Weird')
if n in range(2, 7) and n % 2 == 0:
print('Not Weird')
if n in range(6, 21) and n % 2 == 0:
print('Weird')
if n > 20 and n % 2 == 0:
print('Not Weird') |
class Solution:
def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
# n^2 runtime
degrees = [0] * n
graph = [[] for _ in range(n)]
for road in roads:
degrees[road[0]] += 1
degrees[road[1]] += 1
graph[road[0]].append(road[1])
... | class Solution:
def maximal_network_rank(self, n: int, roads: List[List[int]]) -> int:
degrees = [0] * n
graph = [[] for _ in range(n)]
for road in roads:
degrees[road[0]] += 1
degrees[road[1]] += 1
graph[road[0]].append(road[1])
graph[road[1]... |
__author__ = 'hs634'
'''
Given a binary tree where all the right nodes are leaf nodes, flip it upside down and turn it into a tree with left leaf nodes.
Keep in mind: ALL RIGHT NODES IN ORIGINAL TREE ARE LEAF NODE.
/* for example, turn these:
*
* 1 1
* / \ / \
* ... | __author__ = 'hs634'
'\n\nGiven a binary tree where all the right nodes are leaf nodes, flip it upside down and turn it into a tree with left leaf nodes.\n\nKeep in mind: ALL RIGHT NODES IN ORIGINAL TREE ARE LEAF NODE.\n\n\n/* for example, turn these:\n *\n * 1 1\n * / \\ / ... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyAutogradGamma(PythonPackage):
"""autograd compatible approximations to the derivatives of the
Gamma-famil... | class Pyautogradgamma(PythonPackage):
"""autograd compatible approximations to the derivatives of the
Gamma-family of functions."""
homepage = 'https://github.com/CamDavidsonPilon/autograd-gamma'
url = 'https://pypi.io/packages/source/a/autograd-gamma/autograd-gamma-0.4.3.tar.gz'
version('0.4.3', sh... |
a = 0
b = 0
c = 0
if a == b:
c = 100
else:
c = 10
print(c)
if c == 10:
print('c == 10')
else:
print('c == 100')
''' output
100
c == 100
'''
| a = 0
b = 0
c = 0
if a == b:
c = 100
else:
c = 10
print(c)
if c == 10:
print('c == 10')
else:
print('c == 100')
' output\n100\nc == 100\n' |
def simulation_parameter_validate(end_t, initial_conditions, rates_params, drain_params):
assert isinstance(end_t, (int, float)), "End_t must be a float or int"
assert end_t > 0, "End_t most be a positive number"
assert isinstance(initial_conditions, dict), "Expected {} got {} for initial conditions"\
... | def simulation_parameter_validate(end_t, initial_conditions, rates_params, drain_params):
assert isinstance(end_t, (int, float)), 'End_t must be a float or int'
assert end_t > 0, 'End_t most be a positive number'
assert isinstance(initial_conditions, dict), 'Expected {} got {} for initial conditions'.format... |
#
# This is the Robotics Language compiler
#
# Transform.py: Deep Inference code transformer
#
# Created on: 25 February, 2019
# Author: Gabriel Lopes
# Licence: license
# Copyright: Robot Care Systems BV
#
def transform(code, parameters):
return code, parameters
| def transform(code, parameters):
return (code, parameters) |
# Operators
PLUS = '+'
MINUS = '-'
MUL = '*'
DIV = '/'
FLOORDIV = '//'
MOD = '%'
POWER = '^'
ARITHMATIC_LEFT_SHIFT = '<<<'
ARITHMATIC_RIGHT_SHIFT = '>>>'
XOR = 'xor'
BINARY_ONES_COMPLIMENT = '~'
BINARY_LEFT_SHIFT = '<<'
BINARY_RIGHT_SHIFT = '>>'
AND = 'and'
OR = 'or'
NOT = 'not'
IN = 'in' # TODO
NOT_IN = 'not in' # T... | plus = '+'
minus = '-'
mul = '*'
div = '/'
floordiv = '//'
mod = '%'
power = '^'
arithmatic_left_shift = '<<<'
arithmatic_right_shift = '>>>'
xor = 'xor'
binary_ones_compliment = '~'
binary_left_shift = '<<'
binary_right_shift = '>>'
and = 'and'
or = 'or'
not = 'not'
in = 'in'
not_in = 'not in'
is = 'is'
is_not = 'is n... |
#!/usr/bin/env python3
"""
- domain: GoogleCode Jam 2019
- contest: Round 1C
- problem: B
- title: Power Arrangers
- link: https://codingcompetitions.withgoogle.com/codejam/round/00000000000516b9/0000000000134e91
- hash: GKS19_1B_B
- author: Vitor SRG
- version: 1.0 ... | """
- domain: GoogleCode Jam 2019
- contest: Round 1C
- problem: B
- title: Power Arrangers
- link: https://codingcompetitions.withgoogle.com/codejam/round/00000000000516b9/0000000000134e91
- hash: GKS19_1B_B
- author: Vitor SRG
- version: 1.0 04/05/2019
- tags: ... |
"""
Rabin-Karp or Karp-Robin is an pattern matching algorithm with average case and best case complexity O(m + n) and the worst case complexity O(mn), it is most efficient when used with multiple patterns
as it is able to check if any of a set of patterns match a section of text in O(1)
given the precomp... | """
Rabin-Karp or Karp-Robin is an pattern matching algorithm with average case and best case complexity O(m + n) and the worst case complexity O(mn), it is most efficient when used with multiple patterns
as it is able to check if any of a set of patterns match a section of text in O(1)
given the precomp... |
# 6-dars 1-uyga vazifa
# My_list = ['Dadam: O`ktam ', 'Onam: Dilrabo', 'Akam: Shoxrux', 'O`zim: Abduhalim', 'Ukam: Sardor']
# for elem in My_list:
# print(elem)
# 2-uyga vazifa
# Standart kiruvchi ma'lumotdagi vergul bilan ajratilgan so'zlar ketma-ketligini teskar... | names = input('Please input the names: ')
changed = names.split(sep=', ')
chosen_name = input('input the name you want to find its repitation: ')
print(changed.count(chosen_name)) |
class User:
def __init__(self, username, first, last):
self.username = username
self.password = None
self.first = first
self.last = last
self.bio = "Datau"
self.pic = "default.png" | class User:
def __init__(self, username, first, last):
self.username = username
self.password = None
self.first = first
self.last = last
self.bio = 'Datau'
self.pic = 'default.png' |
# appfat.cpp
MakeNameEx(LocByName("sub_401000"), "j_appfat_cpp_init", SN_NOWARN)
MakeNameEx(LocByName("sub_401005"), "appfat_cpp_init", SN_NOWARN)
MakeNameEx(LocByName("sub_401010"), "appfat_cpp_free", SN_NOWARN)
MakeNameEx(LocByName("sub_40102A"), "GetErr", SN_NOWARN)
MakeNameEx(LocByName("sub_4010CE"), "GetDDE... | make_name_ex(loc_by_name('sub_401000'), 'j_appfat_cpp_init', SN_NOWARN)
make_name_ex(loc_by_name('sub_401005'), 'appfat_cpp_init', SN_NOWARN)
make_name_ex(loc_by_name('sub_401010'), 'appfat_cpp_free', SN_NOWARN)
make_name_ex(loc_by_name('sub_40102A'), 'GetErr', SN_NOWARN)
make_name_ex(loc_by_name('sub_4010CE'), 'GetDDE... |
class reconnectionService():
def __init__(self, pebble, message):
self.targetPebble = pebble
def reconnect(self):
"""Reconnect Pebble"""
self.targetPebble.disconnect()
self.targetPebble.connect()
self.targetPebble.run_async()
self.targetPebble.startAppMessage... | class Reconnectionservice:
def __init__(self, pebble, message):
self.targetPebble = pebble
def reconnect(self):
"""Reconnect Pebble"""
self.targetPebble.disconnect()
self.targetPebble.connect()
self.targetPebble.run_async()
self.targetPebble.startAppMessageServi... |
# -*- coding: utf-8 -*-
def xstr(s):
if s is None:
return ""
else:
return str(s)
| def xstr(s):
if s is None:
return ''
else:
return str(s) |
"""Module initialization."""
__version__ = "0.0.1"
__name__ = "rxn_aa_mapper"
| """Module initialization."""
__version__ = '0.0.1'
__name__ = 'rxn_aa_mapper' |
fruits = ['grape', 'raspberry', 'apple', 'banana']
fruits_copy = fruits.copy()
print(f"fruits: {fruits}")
sorted_fruits = sorted(fruits)
assert fruits == fruits_copy
print(f"sorted(fruits): {sorted_fruits}")
sorted_fruits = sorted(fruits, reverse=True)
assert fruits == fruits_copy
print(f"sorted(fruits, reverse=True... | fruits = ['grape', 'raspberry', 'apple', 'banana']
fruits_copy = fruits.copy()
print(f'fruits: {fruits}')
sorted_fruits = sorted(fruits)
assert fruits == fruits_copy
print(f'sorted(fruits): {sorted_fruits}')
sorted_fruits = sorted(fruits, reverse=True)
assert fruits == fruits_copy
print(f'sorted(fruits, reverse=True): ... |
""" blueprint for a sample human being """
class Human:
"""
blueprint for a sample human being.
expected structure:
human_attributes = {
"name" : "Bob",
"age" : 38,
"gender" : "male",
"profession": "coder"
}
"""
def __init__(self, human_attri... | """ blueprint for a sample human being """
class Human:
"""
blueprint for a sample human being.
expected structure:
human_attributes = {
"name" : "Bob",
"age" : 38,
"gender" : "male",
"profession": "coder"
}
"""
def __init__(self, human_attri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""INTERNAL RUNS A COMMAND - Usage: run_command <arg 1> ... <arg n> [do_run_info=1]"""
INTERNAL = True
def func(root, display, *args, **kwargs):
# command name
command = args[0]
consoleout = []
try:
# Test For Index Air
args = args[1]
... | """INTERNAL RUNS A COMMAND - Usage: run_command <arg 1> ... <arg n> [do_run_info=1]"""
internal = True
def func(root, display, *args, **kwargs):
command = args[0]
consoleout = []
try:
args = args[1]
except IndexError:
args = []
out_args = []
out_kwargs = {}
for arg in args:
... |
# http://codeforces.com/problemset/problem/59/A
text = input()
upper_counter = 0
lower_counter = 0
for char in text:
if char.isupper():
upper_counter += 1
elif char.islower():
lower_counter += 1
if lower_counter > upper_counter:
text = text.lower()
elif upper_counter > lower_counter:
... | text = input()
upper_counter = 0
lower_counter = 0
for char in text:
if char.isupper():
upper_counter += 1
elif char.islower():
lower_counter += 1
if lower_counter > upper_counter:
text = text.lower()
elif upper_counter > lower_counter:
text = text.upper()
else:
text = text.lower()
p... |
class Base():
def __init__(self, agent, base_location):
self.base_location = base_location
self.agent = agent
self.mineral_fields = []
self.geysers = []
self.compute_mineral_fields()
self.compute_geysers()
def get_mineral_fields(self):
return se... | class Base:
def __init__(self, agent, base_location):
self.base_location = base_location
self.agent = agent
self.mineral_fields = []
self.geysers = []
self.compute_mineral_fields()
self.compute_geysers()
def get_mineral_fields(self):
return self.mineral_... |
# output: ok
assert str(None) == 'None'
assert str(1) == '1'
assert str(1.2) == '1.2'
assert str('a') == 'a'
assert str(()) == '()'
assert str((1,)) == '(1,)'
assert str(('a',)) == "('a',)"
assert str((1, 2, 3)) == '(1, 2, 3)'
assert str([]) == '[]'
assert str(['a']) == "['a']"
assert str([1, 2, 3]) == '[1, 2, 3]'
ass... | assert str(None) == 'None'
assert str(1) == '1'
assert str(1.2) == '1.2'
assert str('a') == 'a'
assert str(()) == '()'
assert str((1,)) == '(1,)'
assert str(('a',)) == "('a',)"
assert str((1, 2, 3)) == '(1, 2, 3)'
assert str([]) == '[]'
assert str(['a']) == "['a']"
assert str([1, 2, 3]) == '[1, 2, 3]'
assert str({}) ==... |
# Represents a single node in the Trie
class TrieNode:
def __init__(self, end_of_word=False):
# Initialize this node in the Trie
# Indicates whether the string ends here is a valid word
self.end_of_word = end_of_word
# A dictionary to store the possible characters in this node
... | class Trienode:
def __init__(self, end_of_word=False):
self.end_of_word = end_of_word
self.char_dict = dict()
def insert(self, char):
sub_char_node = trie_node()
self.char_dict[char] = sub_char_node
return sub_char_node
def suffixes(self, suffix=''):
output... |
host = "PASTE_YOUR_HOST_URL_HERE"
asrkey = 'PASTE_YOUR_ASR_API_KEY_HERE'
ttskey = 'PASTE_YOUR_TTS_API_KEY_HERE'
speaker = "nick"
| host = 'PASTE_YOUR_HOST_URL_HERE'
asrkey = 'PASTE_YOUR_ASR_API_KEY_HERE'
ttskey = 'PASTE_YOUR_TTS_API_KEY_HERE'
speaker = 'nick' |
# -*- coding: utf-8 -*-
#
# Copyright 2011, Toru Maesaka
# Copyright 2014, Carlos Rodrigues
#
# Redistribution and use of this source code is licensed under
# the BSD license. See COPYING file for license description.
#
class KyotoTycoonException(Exception):
pass
# EOF - kt_error.py
| class Kyototycoonexception(Exception):
pass |
#
# Catching this Exception captures all known/planned error conditions
#
class OAuthSSHError(Exception):
"Base class for all custom exceptions in this module"
def __init__(self, msg):
super(OAuthSSHError, self).__init__(msg)
| class Oauthssherror(Exception):
"""Base class for all custom exceptions in this module"""
def __init__(self, msg):
super(OAuthSSHError, self).__init__(msg) |
def factorial(n):
# test for a base case
if n == 0:
return 1
else:
return n*factorial(n-1) # make a calculation and a recursive call
print(factorial(4))
| def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(4)) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
binaryString = ""
node = head
while(node != None):
binaryString... | class Solution:
def get_decimal_value(self, head: ListNode) -> int:
binary_string = ''
node = head
while node != None:
binary_string += str(node.val)
node = node.next
length = len(binaryString)
decimal_value = 0
while head != None:
... |
#
# PySNMP MIB module HH3C-IFQOS2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-IFQOS2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, single_value_constraint, value_range_constraint) ... |
# ANSI color codes
RED = "\x1b[31m"
GREEN = "\x1b[32m"
RESET = "\x1b[0m"
| red = '\x1b[31m'
green = '\x1b[32m'
reset = '\x1b[0m' |
def dict_eq(d1, d2):
return (all(k in d2 and d1[k] == d2[k] for k in d1)
and all(k in d1 and d1[k] == d2[k] for k in d2))
assert dict_eq(dict(a=2, b=3), {'a': 2, 'b': 3})
assert dict_eq(dict({'a': 2, 'b': 3}, b=4), {'a': 2, 'b': 4})
assert dict_eq(dict([('a', 2), ('b', 3)]), {'a': 2, 'b': 3})
a = {'g... | def dict_eq(d1, d2):
return all((k in d2 and d1[k] == d2[k] for k in d1)) and all((k in d1 and d1[k] == d2[k] for k in d2))
assert dict_eq(dict(a=2, b=3), {'a': 2, 'b': 3})
assert dict_eq(dict({'a': 2, 'b': 3}, b=4), {'a': 2, 'b': 4})
assert dict_eq(dict([('a', 2), ('b', 3)]), {'a': 2, 'b': 3})
a = {'g': 5}
b = {'a... |
def square(number):
if number <= 0 or number > 64:
raise ValueError("square must be between 1 and 64")
return 2**(number - 1)
def total():
return 2**64 - 1
| def square(number):
if number <= 0 or number > 64:
raise value_error('square must be between 1 and 64')
return 2 ** (number - 1)
def total():
return 2 ** 64 - 1 |
class BoaExitException(Exception):
pass
class BoaRunBuildException(Exception):
pass
| class Boaexitexception(Exception):
pass
class Boarunbuildexception(Exception):
pass |
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
result = 0
anchor = 0
for ii, i in enumerate(nums):
if (ii > 0 and nums[ii-1] >= nums[ii]):
anchor = ii
result = max(result, ii - anchor + 1)
return result
| class Solution:
def find_length_of_lcis(self, nums: List[int]) -> int:
result = 0
anchor = 0
for (ii, i) in enumerate(nums):
if ii > 0 and nums[ii - 1] >= nums[ii]:
anchor = ii
result = max(result, ii - anchor + 1)
return result |
class Solution:
def halvesAreAlike(self, s: str) -> bool:
n = len(s)
half_n = int(n/2)
# print(half_n)
first = s[:half_n]
second = s[half_n:]
count_first = 0
count_second = 0
s = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for i... | class Solution:
def halves_are_alike(self, s: str) -> bool:
n = len(s)
half_n = int(n / 2)
first = s[:half_n]
second = s[half_n:]
count_first = 0
count_second = 0
s = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for i in first:
if i ... |
arr = [23, 34, 25, 12, 54, 11, 90]
def bubbleSort(arr):
"""
>>> bubbleSort(arr)
[11, 12, 23, 25, 34, 54, 90]
"""
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr... | arr = [23, 34, 25, 12, 54, 11, 90]
def bubble_sort(arr):
"""
>>> bubbleSort(arr)
[11, 12, 23, 25, 34, 54, 90]
"""
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j])
return ... |
BOT_NAME = 'amazon2'
SPIDER_MODULES = ['amazon2.spiders']
NEWSPIDER_MODULE = 'amazon2.spiders'
ROBOTSTXT_OBEY = False
CONCURRENT_REQUESTS = 32
COOKIES_ENABLED = False
SPIDER_MIDDLEWARES = {
'amazon2.middlewares.AmazonSpiderMiddleware.AmazonSpiderMiddleware': 543,
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.down... | bot_name = 'amazon2'
spider_modules = ['amazon2.spiders']
newspider_module = 'amazon2.spiders'
robotstxt_obey = False
concurrent_requests = 32
cookies_enabled = False
spider_middlewares = {'amazon2.middlewares.AmazonSpiderMiddleware.AmazonSpiderMiddleware': 543}
downloader_middlewares = {'scrapy.downloadermiddlewares.u... |
def good(num, name=None):
b = bad(num)
u = ugly(name)
return f"The GOOD({num}, name={name}), The BAD->{b}, and The UGLY->{u}"
def bad(num):
u = ugly(num)
return f"The BAD({num}) got UGLY->{u}"
def ugly(num):
return 42 / num
| def good(num, name=None):
b = bad(num)
u = ugly(name)
return f'The GOOD({num}, name={name}), The BAD->{b}, and The UGLY->{u}'
def bad(num):
u = ugly(num)
return f'The BAD({num}) got UGLY->{u}'
def ugly(num):
return 42 / num |
class AppControlInterface:
def __init__(self):
pass
def scroll_up(self, amount):
pass
def scroll_down(self, amount):
pass
| class Appcontrolinterface:
def __init__(self):
pass
def scroll_up(self, amount):
pass
def scroll_down(self, amount):
pass |
"""I suck in the dust."""
class Vacuum(object):
def input(self):
"Dust."
def output(self):
print('Sucking in dust...')
| """I suck in the dust."""
class Vacuum(object):
def input(self):
"""Dust."""
def output(self):
print('Sucking in dust...') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created: 02/07/2022(m/d/y) 16:44:11 UTC from "Archnemesis" data
desc = "Challenge Autogen"
# Base type : settings pair
items = {
}
| desc = 'Challenge Autogen'
items = {} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.