content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# > \brief \b DROTMG
#
# =========== DOCUMENTATION ===========
#
# Online html documentation available at
# http://www.netlib.org/lapack/explore-html/
#
# Definition:
# ===========
#
# def DROTMG(DD1,DD2,DX1,DY1,DPARAM)
#
# .. Scalar Arguments ..
# DOUBLE PRECISION DD1,DD2,DX1,DY1
# ... | def drotmg(DD1, DD2, DX1, DY1, DPARAM):
gam = 4096
gamsq = 16777216
rgamsq = 5.9604645e-08
if DD1 < 0:
dflag = -1
dh11 = 0
dh12 = 0
dh21 = 0
dh22 = 0
dd1 = 0
dd2 = 0
dx1 = 0
else:
dp2 = DD2 * DY1
if DP2 == 0:
... |
"""
10. Regular Expression Matching
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be e... | """
10. Regular Expression Matching
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be e... |
#!/usr/bin/env python
IRC_BASE = ["ircconnection", "irclib", "numerics", "baseircclient", "irctracker", "commandparser", "commands", "ircclient", "commandhistory", "nicknamevalidator", "ignorecontroller"]
PANES = ["connect", "embed", "options", "about", "url"]
UI_BASE = ["menuitems", "baseui", "baseuiwindow", "colour",... | irc_base = ['ircconnection', 'irclib', 'numerics', 'baseircclient', 'irctracker', 'commandparser', 'commands', 'ircclient', 'commandhistory', 'nicknamevalidator', 'ignorecontroller']
panes = ['connect', 'embed', 'options', 'about', 'url']
ui_base = ['menuitems', 'baseui', 'baseuiwindow', 'colour', 'url', 'theme', 'noti... |
#!/usr/env python
class Queue:
def __init__(self, size=16):
self.queue = []
self.size = size
self.front = 0
self.rear = 0
def is_empty(self):
return self.rear == 0
def is_full(self):
if (self.front - self.rear + 1) == self.size:
return ... | class Queue:
def __init__(self, size=16):
self.queue = []
self.size = size
self.front = 0
self.rear = 0
def is_empty(self):
return self.rear == 0
def is_full(self):
if self.front - self.rear + 1 == self.size:
return True
else:
... |
class FenwickTree:
data: []
def __init__(self, n: int):
self.data = [0] * (n + 1)
@staticmethod
def __parent__(i: int) -> int:
return i - (i & (-i))
def __str__(self):
return str(self.data) | class Fenwicktree:
data: []
def __init__(self, n: int):
self.data = [0] * (n + 1)
@staticmethod
def __parent__(i: int) -> int:
return i - (i & -i)
def __str__(self):
return str(self.data) |
party_size = int(input())
days = int(input())
coins = 0
for i in range(1, days + 1):
coins += 50
if i % 10 == 0:
party_size -= 2
if i % 15 == 0:
party_size += 5
coins -= party_size * 2
if i % 3 == 0:
coins -= party_size * 3
if i % 5 == 0:
coins += party_size * 2... | party_size = int(input())
days = int(input())
coins = 0
for i in range(1, days + 1):
coins += 50
if i % 10 == 0:
party_size -= 2
if i % 15 == 0:
party_size += 5
coins -= party_size * 2
if i % 3 == 0:
coins -= party_size * 3
if i % 5 == 0:
coins += party_size * 20
... |
'''
Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a... | """
Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a... |
def random_board():
'''
Creates the dice which have letters on each side --> Array of length 6 per die
'''
self.cube_one = ["A","A","E","E","G","N"]
self.cube_two = ["A","O","O","T","T","W"]
self.cube_three = ["D","I","S","T","T","Y"]
self.cube_four = ["E","I","O","S","S","T"]
self.c... | def random_board():
"""
Creates the dice which have letters on each side --> Array of length 6 per die
"""
self.cube_one = ['A', 'A', 'E', 'E', 'G', 'N']
self.cube_two = ['A', 'O', 'O', 'T', 'T', 'W']
self.cube_three = ['D', 'I', 'S', 'T', 'T', 'Y']
self.cube_four = ['E', 'I', 'O', 'S', ... |
# Print N reverse
# https://www.acmicpc.net/problem/2742
print('\n'.join(list(map(str, [x for x in range(int(input()), 0, -1)]))))
| print('\n'.join(list(map(str, [x for x in range(int(input()), 0, -1)])))) |
class Camera:
def __init__(): #Need to have all information necessary to calibrate camera input into here as arguements
#Calibrate Camera - constant
#Locate Camera Relative to Centerpoint - constant
#Define GPIO pins for synchronization - constant
#Change camera settings - tunable
... | class Camera:
def __init__():
return None |
# 33. Search in Rotated Sorted Array
class Solution:
def search(self, nums, target: int) -> int:
def binSearchPiv(l, r, target):
while l < r:
m = (l+r)//2
if nums[m] > nums[m+1]: return m+1
if nums[m] > target: l = m+1
else: r = m
... | class Solution:
def search(self, nums, target: int) -> int:
def bin_search_piv(l, r, target):
while l < r:
m = (l + r) // 2
if nums[m] > nums[m + 1]:
return m + 1
if nums[m] > target:
l = m + 1
... |
#
# PySNMP MIB module Juniper-System-Clock-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-System-Clock-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:53:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ... |
#
# PySNMP MIB module CTRON-SFPS-CALL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SFPS-CALL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:15:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
""" Tuple as Data Structure
""" | """ Tuple as Data Structure
""" |
class RPMReqException(Exception):
msg_fmt = "An unknown error occurred"
def __init__(self, msg=None, **kwargs):
self.kwargs = kwargs
if not msg:
try:
msg = self.msg_fmt % kwargs
except Exception:
msg = self.msg_fmt
super(RPMReqExce... | class Rpmreqexception(Exception):
msg_fmt = 'An unknown error occurred'
def __init__(self, msg=None, **kwargs):
self.kwargs = kwargs
if not msg:
try:
msg = self.msg_fmt % kwargs
except Exception:
msg = self.msg_fmt
super(RPMReqExce... |
# coding: utf-8
# In[43]:
alist = [54,26,93,17,77,31,44,55,20]
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
return a... | alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
def bubble_sort(alist):
for passnum in range(len(alist) - 1, 0, -1):
for i in range(passnum):
if alist[i] > alist[i + 1]:
temp = alist[i]
alist[i] = alist[i + 1]
alist[i + 1] = temp
return alist
pri... |
# Defining the Movie Class
# Creates an instance of a movie with related details
class Movie():
def __init__(self, movie_title, poster_image, trailer_id,
movie_year, movie_rating, movie_release_date, movie_imdb_rating):
self.title = movie_title
self.poster_image_url = poster_imag... | class Movie:
def __init__(self, movie_title, poster_image, trailer_id, movie_year, movie_rating, movie_release_date, movie_imdb_rating):
self.title = movie_title
self.poster_image_url = poster_image
self.youtube_id = trailer_id
self.year = movie_year
self.rated = movie_ratin... |
# -*- coding: utf-8 -*-
system_proxies = None;
disable_proxies = {'http': None, 'https': None};
proxies_protocol = "http";
proxies_protocol = "socks5";
defined_proxies = {
'http': proxies_protocol+'://127.0.0.1:8888',
'https': proxies_protocol+'://127.0.0.1:8888',
};
proxies = system_proxies;
if __name_... | system_proxies = None
disable_proxies = {'http': None, 'https': None}
proxies_protocol = 'http'
proxies_protocol = 'socks5'
defined_proxies = {'http': proxies_protocol + '://127.0.0.1:8888', 'https': proxies_protocol + '://127.0.0.1:8888'}
proxies = system_proxies
if __name__ == '__main__':
pass |
test = {
'name': 'multiples_3',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
scm> (car multiples-of-three)
3
scm> (list? (cdr multiples-of-three)) ; Check to make sure variable contains a stream
#f
scm> (list? (cdr (cdr-stream m... | test = {'name': 'multiples_3', 'points': 1, 'suites': [{'cases': [{'code': "\n scm> (car multiples-of-three)\n 3\n scm> (list? (cdr multiples-of-three)) ; Check to make sure variable contains a stream\n #f\n scm> (list? (cdr (cdr-stream multiples-of-three))) ; Check to make ... |
#
# PySNMP MIB module NBS-OTNPM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-OTNPM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:17:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) ... |
# Collin Pearce 100%
# performance O(log(n))
# all states with less tables than the optimal are correct states
# all states with more tables than the optimal are incorrect states
# therefore, the state space can be binary searched
# mid represents the number of tables produced
# pockets available are total_po... | (c, n, p, w) = [int(x) for x in input().split()]
(l, r) = (0, W // C)
while l != r:
mid = (1 + l + r) // 2
pockets = N - mid
wood = W - mid * C
if P * pockets >= wood:
l = mid
else:
r = mid - 1
print(l) |
"""
Write a function that takes an unsigned integer and returns the number of 1 bits it has.
Example:
The 32-bit integer 11 has binary representation
00000000000000000000000000001011
so the function should return 3.
Note that since Java does not have unsigned int, use long for Java
"""
class Solution:
# @param... | """
Write a function that takes an unsigned integer and returns the number of 1 bits it has.
Example:
The 32-bit integer 11 has binary representation
00000000000000000000000000001011
so the function should return 3.
Note that since Java does not have unsigned int, use long for Java
"""
class Solution:
def num... |
class Solution:
def countSubstrings(self, s: str) -> int:
count = 0
for center in range(len(s)*2 - 1):
left = center // 2
right = left + (center&1)
while left >= 0 and right < len(s) and s[left] == s[right]:
count += 1
left -= 1
... | class Solution:
def count_substrings(self, s: str) -> int:
count = 0
for center in range(len(s) * 2 - 1):
left = center // 2
right = left + (center & 1)
while left >= 0 and right < len(s) and (s[left] == s[right]):
count += 1
left ... |
expected_output={
"interfaces": {
"Tunnel100": {
"autoroute_announce": "enabled",
"src_ip": "Loopback0",
"tunnel_bandwidth": 500,
"tunnel_dst": "2.2.2.2",
"tunnel_mode": "mpls traffic-eng",
"tunnel_path_option": {
"1": {
"path_type": "dynamic"
... | expected_output = {'interfaces': {'Tunnel100': {'autoroute_announce': 'enabled', 'src_ip': 'Loopback0', 'tunnel_bandwidth': 500, 'tunnel_dst': '2.2.2.2', 'tunnel_mode': 'mpls traffic-eng', 'tunnel_path_option': {'1': {'path_type': 'dynamic'}}, 'tunnel_priority': ['7 7']}}} |
def act(robot):
val = robot.ir_sensor.read()
if val == 1:
robot.forward(200)
if val == 2:
robot.forward_right(200)
if val == 3:
robot.reverse_right(200)
if val == 4 or val == 5:
robot.reverse(200)
if val == 6:
robot.reverse_left(200)
if val == 7:
... | def act(robot):
val = robot.ir_sensor.read()
if val == 1:
robot.forward(200)
if val == 2:
robot.forward_right(200)
if val == 3:
robot.reverse_right(200)
if val == 4 or val == 5:
robot.reverse(200)
if val == 6:
robot.reverse_left(200)
if val == 7:
... |
"""
Module for representing PredPatt and UDS graphs
This module represents PredPatt and UDS graphs using networkx. It
incorporates the dependency parse-based graphs from the syntax module
as subgraphs.
"""
| """
Module for representing PredPatt and UDS graphs
This module represents PredPatt and UDS graphs using networkx. It
incorporates the dependency parse-based graphs from the syntax module
as subgraphs.
""" |
"""{{ cookiecutter.package_name }} - {{ cookiecutter.package_description }}"""
__version__ = '{{ cookiecutter.package_version }}'
__author__ = '{{ cookiecutter.author_name }} <{{ cookiecutter.author_email }}>'
__all__ = [] | """{{ cookiecutter.package_name }} - {{ cookiecutter.package_description }}"""
__version__ = '{{ cookiecutter.package_version }}'
__author__ = '{{ cookiecutter.author_name }} <{{ cookiecutter.author_email }}>'
__all__ = [] |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
while head:
if not hasattr(head, 'flag'):
head.flag = False
... | class Solution:
def has_cycle(self, head: ListNode) -> bool:
while head:
if not hasattr(head, 'flag'):
head.flag = False
if not head.flag:
head.flag = True
else:
return True
head = head.next
return False |
#!/usr/bin/env python
# encoding: utf-8
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# 0001 XOR 0000 = 0001
# a XOR 0 = a
# a XOR a = 0
# a XOR b XOR a = a XOR a XOR b = b
a = 0
for num in nums:
a ^= num
return a
| class Solution:
def single_number(self, nums: List[int]) -> int:
a = 0
for num in nums:
a ^= num
return a |
def remove_all(input_string,to_be_removed):
''' removes all instance of a substring from a string '''
while(to_be_removed in input_string):
input_string = ''.join(input_string.split(to_be_removed))
return(input_string)
if __name__ == '__main__':
print(remove_all('hello world','l'))
| def remove_all(input_string, to_be_removed):
""" removes all instance of a substring from a string """
while to_be_removed in input_string:
input_string = ''.join(input_string.split(to_be_removed))
return input_string
if __name__ == '__main__':
print(remove_all('hello world', 'l')) |
# 1. The format_address function separates out parts of the address string
# into new strings: house_number and street_name, and returns: "house
# number X on street named Y". The format of the input string is: numeric
# house number, followed by the street name which may contain numbers,
# but never by the... | def format_address(address_string):
street = []
number = ''
for s in address_string.split():
if s.isdigit():
number = s
else:
street.append(s)
return 'house number {} on street named {}'.format(number, ' '.join(street))
def highlight_word(sentence, word):
ret... |
x=list(input())
y=list(input())
x.reverse()
y.reverse()
updi=False
a=max(x,y)
b=min(x,y)
out=[]
for i in range(len(a)):
tem1=int(a[i])
try:
tem2=int(b[i])
pass
except :
tem2=0
tem=tem1+tem2
tem= tem+1 if updi else tem
out.insert(0,str(tem%10))
updi= tem/10>=1
if updi and len(a)-1==i:
out.insert(0,str(1)... | x = list(input())
y = list(input())
x.reverse()
y.reverse()
updi = False
a = max(x, y)
b = min(x, y)
out = []
for i in range(len(a)):
tem1 = int(a[i])
try:
tem2 = int(b[i])
pass
except:
tem2 = 0
tem = tem1 + tem2
tem = tem + 1 if updi else tem
out.insert(0, str(tem % 10))... |
sns.catplot(data=density_mean, kind="bar",
x='Bacterial_genotype',
y='optical_density',
hue='Phage_t',
row="experiment_time_h",
sharey=False,
aspect=3, height=3,
palette="colorblind") | sns.catplot(data=density_mean, kind='bar', x='Bacterial_genotype', y='optical_density', hue='Phage_t', row='experiment_time_h', sharey=False, aspect=3, height=3, palette='colorblind') |
"""matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matriz[0][0])
print(matriz[0][1])
print(matriz[0][2])
print(matriz[1][0])
print(matriz[1][1])
print(matriz[1][2])
print(matriz[2][0])
print(matriz[2][1])
print(matriz[2][2])
print(matriz[0][0] + matriz[0][1] + matriz[0][2] + matriz[1][0] + matriz[1][1] + matriz[1][2] ... | """matriz = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matriz[0][0])
print(matriz[0][1])
print(matriz[0][2])
print(matriz[1][0])
print(matriz[1][1])
print(matriz[1][2])
print(matriz[2][0])
print(matriz[2][1])
print(matriz[2][2])
print(matriz[0][0] + matriz[0][1] + matriz[0][2] + matriz[1][0] + matriz[1][1] + matriz[1][2] ... |
# -*- coding:utf-8 -*-
"""This module is used to test call stack"""
# def greet(name):
# print(name)
# fun(name)
# print('bye bye !!!')
# bye()
#
#
# def fun(name):
# print('how are you', name)
#
#
# def bye():
# print('good bye')
#
#
# greet('feifei')
def fact(x):
if x == 1:
retu... | """This module is used to test call stack"""
def fact(x):
if x == 1:
return 1
else:
return x * fact(x - 1)
print(fact(3)) |
# Copyright 2019 Google LLC
#
# 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 agreed to in writing, s... | """Constants used acros google.cloud.storage modules."""
standard_storage_class = 'STANDARD'
'Storage class for objects accessed more than once per month.\n\nSee: https://cloud.google.com/storage/docs/storage-classes\n'
nearline_storage_class = 'NEARLINE'
'Storage class for objects accessed at most once per month.\n\nS... |
class WolphinException(Exception):
"""
Base class for wolphin related exceptions
"""
def __init__(self, message=None):
"""
WolphinException constructor
:param message: error message for the exception
"""
self.message = message
def __str__(self):
ret... | class Wolphinexception(Exception):
"""
Base class for wolphin related exceptions
"""
def __init__(self, message=None):
"""
WolphinException constructor
:param message: error message for the exception
"""
self.message = message
def __str__(self):
ret... |
def sub(
_str:str,
_from:int,
_to:int=None
) -> str:
_to = _from + 1 if _to == None else _to
return _str[_from:_to]
def tostr(
val,
_hex:bool=False
) -> str:
return str(val) if not _hex else str(hex(val))
def tonum(
_str:str
) -> float or int:
try:
return int(_str)
... | def sub(_str: str, _from: int, _to: int=None) -> str:
_to = _from + 1 if _to == None else _to
return _str[_from:_to]
def tostr(val, _hex: bool=False) -> str:
return str(val) if not _hex else str(hex(val))
def tonum(_str: str) -> float or int:
try:
return int(_str)
except ValueError:
... |
# Invert Binary Tree: https://leetcode.com/problems/invert-binary-tree/
# Given the root of a binary tree, invert the tree, and return its root.
# Okay this is another problem where we use a dfs solution except we should just be flipping as we go down
# Basic solution
class Solution:
def invertTree(self, root):
... | class Solution:
def invert_tree(self, root):
def dfs(root):
if root:
(root.left, root.right) = (root.right, root.left)
dfs(root.left)
dfs(root.right)
dfs(root)
return root
class Solution2:
def invert_tree(self, root):
... |
class FloatMana:
def __init__(self, content):
pass
| class Floatmana:
def __init__(self, content):
pass |
# Applied once at the beginning of the algorithm.
INITIAL_PERMUTATION = [
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
... | initial_permutation = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7]
final_permutation = [40, 8, 48, 16, 56, 24, 64, 32... |
# Ordered (indexing is allowed): List, Tuple
# Unordered (indexing is not allowed): Dictionary, and Set
# Mutable (can be changed after creation): List, Dictionary, and Set
# Immutable ((can not be changed after creation)): Tuple, and Frozen Set
# LIST: is a mutable data type i.e items can be added to list later afte... | var_list = ['hello', 100, 200, 500, 'world', 123.3, 100]
print(var_list)
item = var_list[1]
var_list[2] = 500
var_list.append('Python')
print(var_list) |
# Style
# Uncomment the following code, then
# fix the style in this file so that it runs properly
# and there are comments explaining the program
"""
print("Hello World!")
print("This is a Python program")
age =
input("Enter your age: ")
print("Your age is " + age)
"""
| """
print("Hello World!")
print("This is a Python program")
age =
input("Enter your age: ")
print("Your age is " + age)
""" |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def isPalindrome(n):
return str(n) == str(n)[::-1]
ans = 0
for i in range(100, 1000):
for j in range(i, 1000):
if (isPalindrome(i * j)):
ans = max(ans, i * j)
print(ans)
| def is_palindrome(n):
return str(n) == str(n)[::-1]
ans = 0
for i in range(100, 1000):
for j in range(i, 1000):
if is_palindrome(i * j):
ans = max(ans, i * j)
print(ans) |
def initialize_3d_list(a, b, c):
"""
:param a:
:param b:
:param c:
:return:
"""
lst = [[[None for _ in range(c)] for _ in range(b)] for _ in range(a)]
return lst | def initialize_3d_list(a, b, c):
"""
:param a:
:param b:
:param c:
:return:
"""
lst = [[[None for _ in range(c)] for _ in range(b)] for _ in range(a)]
return lst |
def ld_env_arg_spec():
return dict(
environment_key=dict(type="str", required=True, aliases=["key"]),
color=dict(type="str"),
name=dict(type="str"),
default_ttl=dict(type="int"),
tags=dict(type="list", elements="str"),
confirm_changes=dict(type="bool"),
requir... | def ld_env_arg_spec():
return dict(environment_key=dict(type='str', required=True, aliases=['key']), color=dict(type='str'), name=dict(type='str'), default_ttl=dict(type='int'), tags=dict(type='list', elements='str'), confirm_changes=dict(type='bool'), require_comments=dict(type='bool'), default_track_events=dict(t... |
# Link : https://leetcode.com/problems/valid-palindrome-ii/submissions/
# Two pointer approach
# TC : O(n)
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# Use two pointers at the start and end of the string
# To iterate ove... | class Solution(object):
def valid_palindrome(self, s):
"""
:type s: str
:rtype: bool
"""
a_pointer = 0
b_pointer = len(s) - 1
while a_pointer <= b_pointer:
if s[a_pointer] != s[b_pointer]:
s1 = s[:a_pointer] + s[a_pointer + 1:]
... |
#!/usr/bin/env python
# encoding: utf-8
"""
search_in_rotated_array_ii.py
Created by Shengwei on 2014-07-24.
"""
# https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
# tags: medium / hard, array, search, rotated, edge cases
"""
Follow up for "Search in Rotated Sorted Array":
What if duplicates are a... | """
search_in_rotated_array_ii.py
Created by Shengwei on 2014-07-24.
"""
'\nFollow up for "Search in Rotated Sorted Array":\nWhat if duplicates are allowed?\n\nWould this affect the run-time complexity? How and why?\n\nWrite a function to determine if a given target is in the array.\n'
'\nGeneral approach for searchin... |
# the Node class - contains value and address to next node
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def get_data(self):
return self.val
def set_data(self, val):
self.val = val
def get_next(self):
return self.next
def set... | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
def get_data(self):
return self.val
def set_data(self, val):
self.val = val
def get_next(self):
return self.next
def set_next(self, next):
self.next = next
class Linkedl... |
def color(val):
if val < 60:
r = 0
g = 255
b = 0
if val >= 60:
r = ((val - 60) / 20) * 255
g = 255
b = 120
if val >= 80:
r = 255
g = 255 - (((val - 80) / 20) * 255)
b = 120 - (((val - 80) / 20) * 120)
return 'rgb({},{},{})'.format(... | def color(val):
if val < 60:
r = 0
g = 255
b = 0
if val >= 60:
r = (val - 60) / 20 * 255
g = 255
b = 120
if val >= 80:
r = 255
g = 255 - (val - 80) / 20 * 255
b = 120 - (val - 80) / 20 * 120
return 'rgb({},{},{})'.format(r, g, b) |
class Music:
def __init__(self):
self._ch0 = []
self._ch1 = []
self._ch2 = []
self._ch3 = []
@property
def ch0(self):
return self._ch0
@property
def ch1(self):
return self._ch1
@property
def ch2(self):
return self._ch2
@property... | class Music:
def __init__(self):
self._ch0 = []
self._ch1 = []
self._ch2 = []
self._ch3 = []
@property
def ch0(self):
return self._ch0
@property
def ch1(self):
return self._ch1
@property
def ch2(self):
return self._ch2
@propert... |
def regularized_MSE_loss(output, target, weights=None, L2_penalty=0, L1_penalty=0):
"""loss function for MSE
Args:
output (torch.Tensor): output of network
target (torch.Tensor): neural response network is trying to predict
weights (torch.Tensor): fully-connected layer weights of network (net.out_layer... | def regularized_mse_loss(output, target, weights=None, L2_penalty=0, L1_penalty=0):
"""loss function for MSE
Args:
output (torch.Tensor): output of network
target (torch.Tensor): neural response network is trying to predict
weights (torch.Tensor): fully-connected layer weights of network (net.out_lay... |
"""
An Autoencoder accepts input, compresses it, and recreates it. On the other hand,
VAEs assume that the source data has some underlying distribution and attempts
to find the distribution parameters. So, VAEs are similar to GANs
(but note that GANs work differently, as we will see in the next tutorials).
"""; | """
An Autoencoder accepts input, compresses it, and recreates it. On the other hand,
VAEs assume that the source data has some underlying distribution and attempts
to find the distribution parameters. So, VAEs are similar to GANs
(but note that GANs work differently, as we will see in the next tutorials).
""" |
"""
Hill Pattern
"""
print("")
n = 5
# Method 1
print("Method 1")
for a in range(n):
for b in range(a, n):
print(" ", end="")
for c in range(a + 1):
print(" * ", end="")
for d in range(a):
print(" * ", end="")
print("")
print("\n*~*~*~*~*~*~*~*~*~*~*... | """
Hill Pattern
"""
print('')
n = 5
print('Method 1')
for a in range(n):
for b in range(a, n):
print(' ', end='')
for c in range(a + 1):
print(' * ', end='')
for d in range(a):
print(' * ', end='')
print('')
print('\n*~*~*~*~*~*~*~*~*~*~*~*\n')
print('Method 2')
for a in range... |
n,m = map(int, input().split())
width = m
msg = "WELCOME"
design = ".|."
#upper piece
lines = int((n-1)/2)
count = 1
for i in range(1,lines+1):
a = design*count
print(a.center(width,'-'))
count += 2
#center piece
print(msg.center(width,'-'))
#bottom piece
count = n-2
for i in range(1,lines+1):
a = des... | (n, m) = map(int, input().split())
width = m
msg = 'WELCOME'
design = '.|.'
lines = int((n - 1) / 2)
count = 1
for i in range(1, lines + 1):
a = design * count
print(a.center(width, '-'))
count += 2
print(msg.center(width, '-'))
count = n - 2
for i in range(1, lines + 1):
a = design * count
print(a.... |
def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add
>>> curried_add = lambda_curry2(add)
>>> add_three = curried_add(3)
>>> add_three(5)
8
"""
"*** YOUR CODE HERE ***"
return ______
def compose1(f, g):
"""Retu... | def lambda_curry2(func):
"""
Returns a Curried version of a two-argument function FUNC.
>>> from operator import add
>>> curried_add = lambda_curry2(add)
>>> add_three = curried_add(3)
>>> add_three(5)
8
"""
'*** YOUR CODE HERE ***'
return ______
def compose1(f, g):
"""Retur... |
def percent_str( expected, received ):
received = received*100
output = int(received/expected)
return str(output) + "%"
def modsendall( to_socket, content, expected_msg_bytes):
record = 0
single_attempt_size = 1024
while True:
try:
ret = to_socket.send( content[record:record... | def percent_str(expected, received):
received = received * 100
output = int(received / expected)
return str(output) + '%'
def modsendall(to_socket, content, expected_msg_bytes):
record = 0
single_attempt_size = 1024
while True:
try:
ret = to_socket.send(content[record:record... |
def hey(phrase):
phrase = phrase.strip()
if not phrase:
return "Fine. Be that way!"
elif phrase.isupper():
return "Whoa, chill out!"
elif phrase.endswith("?"):
return "Sure."
else:
return 'Whatever.'
| def hey(phrase):
phrase = phrase.strip()
if not phrase:
return 'Fine. Be that way!'
elif phrase.isupper():
return 'Whoa, chill out!'
elif phrase.endswith('?'):
return 'Sure.'
else:
return 'Whatever.' |
# Created by MechAviv
# High Noon Damage Skin | (2438671)
if sm.addDamageSkin(2438671):
sm.chat("'High Noon Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() | if sm.addDamageSkin(2438671):
sm.chat("'High Noon Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | class Resourceloadexception(Exception):
pass
class Noversionfound(Exception):
pass
class Retriesexceedederror(Exception):
def __init__(self, last_exception, msg='Max Retries Exceeded'):
super(RetriesExceededError, self).__init__(msg)
self.last_exception = last_exception
class S3Transferf... |
async def is_guild_admin(self, guildid, userid):
settings = self.database.get_settings(guildid)
guild = await self.fetch_guild(guildid)
user = await guild.fetch_member(userid)
if user.id == 110838934644211712:
return True # This is so i can test and help without server admin /shrug
for role... | async def is_guild_admin(self, guildid, userid):
settings = self.database.get_settings(guildid)
guild = await self.fetch_guild(guildid)
user = await guild.fetch_member(userid)
if user.id == 110838934644211712:
return True
for role in user.roles:
if role.id == settings['AdminRole']:
... |
# game settings:
RENDER_MODE = True
REF_W = 24*2
REF_H = REF_W
REF_U = 1.5 # ground height
REF_WALL_WIDTH = 1.0 # wall width
REF_WALL_HEIGHT = 5
PLAYER_SPEED_X = 10*1.75
PLAYER_SPEED_Y = 10*1.35
MAX_BALL_SPEED = 15*1.5
TIMESTEP = 1/30.
NUDGE = 0.1
FRICTION = 1.0 # 1 means no FRICTION, less means FRICTION
INIT_DELAY_F... | render_mode = True
ref_w = 24 * 2
ref_h = REF_W
ref_u = 1.5
ref_wall_width = 1.0
ref_wall_height = 5
player_speed_x = 10 * 1.75
player_speed_y = 10 * 1.35
max_ball_speed = 15 * 1.5
timestep = 1 / 30.0
nudge = 0.1
friction = 1.0
init_delay_frames = 30
gravity = -9.8 * 2 * 1.5
maxlives = 5
window_width = 1200
window_heig... |
class Generator:
def __init__(self):
self.buffer = ""
self.ident = 0
def push_ident(self):
self.ident = self.ident + 1
def pop_ident(self):
self.ident = self.ident - 1
def emit(self, *code):
if (''.join(code) == ""):
self.buffer += "\n"
else... | class Generator:
def __init__(self):
self.buffer = ''
self.ident = 0
def push_ident(self):
self.ident = self.ident + 1
def pop_ident(self):
self.ident = self.ident - 1
def emit(self, *code):
if ''.join(code) == '':
self.buffer += '\n'
else:... |
"""
Problem Statement:
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3,5,6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
"""
def solution(n):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>... | """
Problem Statement:
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3,5,6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below N.
"""
def solution(n):
"""Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
... |
'''
Explain the operation of Lists and basic operations of lists
'''
l = [5, 6, 7, 8]
print(l)
#prints the element in position 1, remembering that it starts 0
print(l[2])
# List size use len () function
print(len(l))
l.append(10)
print("New list after adding 10 at the end = " + str(l))
position, value = 0, 20
... | """
Explain the operation of Lists and basic operations of lists
"""
l = [5, 6, 7, 8]
print(l)
print(l[2])
print(len(l))
l.append(10)
print('New list after adding 10 at the end = ' + str(l))
(position, value) = (0, 20)
l.insert(position, value)
print('New list after adding the 20 in the first position = ' + str(l))
l.... |
# encoding: utf-8
# module _symtable
# from (built-in)
# by generator 1.145
# no doc
# no imports
# Variables with simple values
CELL = 5
DEF_BOUND = 134
DEF_FREE = 32
DEF_FREE_CLASS = 64
DEF_GLOBAL = 1
DEF_IMPORT = 128
DEF_LOCAL = 2
DEF_PARAM = 4
FREE = 4
GLOBAL_EXPLICIT = 2
GLOBAL_IMPLICIT = 3
LOCAL = 1
SCOP... | cell = 5
def_bound = 134
def_free = 32
def_free_class = 64
def_global = 1
def_import = 128
def_local = 2
def_param = 4
free = 4
global_explicit = 2
global_implicit = 3
local = 1
scope_mask = 15
scope_off = 11
type_class = 1
type_function = 0
type_module = 2
use = 16
def symtable(*args, **kwargs):
""" Return symbol... |
# Write a function that takes in a graph
# represented as a list of tuples
# and return a list of nodes that
# you would follow on an Eulerian Tour
#
# For example, if the input graph was
# [(1, 2), (2, 3), (3, 1)]
# A possible Eulerian tour would be [1, 2, 3, 1]
def find_eulerian_tour(graph):
a = 0
graph2 = ... | def find_eulerian_tour(graph):
a = 0
graph2 = graph
tour = []
tour2 = []
while len(graph2) > 0:
[tour, graph2] = onetour(graph2, a)
for b in range(0, len(tour2)):
if tour2[b] == tour[0]:
tour2[b:b + 1] = tour
tour = [-1]
if len(tour... |
load("@io_bazel_rules_dotnet//dotnet/private:rules/nuget.bzl", "nuget_package")
def dotnet_repositories_nunit():
### Generated by the tool
nuget_package(
name = "nunit",
package = "nunit",
version = "3.12.0",
sha256 = "62b67516a08951a20b12b02e5d20b5045edbb687c3aabe9170286ec5bb90... | load('@io_bazel_rules_dotnet//dotnet/private:rules/nuget.bzl', 'nuget_package')
def dotnet_repositories_nunit():
nuget_package(name='nunit', package='nunit', version='3.12.0', sha256='62b67516a08951a20b12b02e5d20b5045edbb687c3aabe9170286ec5bb9000a1', core_lib={'netcoreapp2.0': 'lib/netstandard2.0/nunit.framework.d... |
target_num = int(input())
sum_nums = 0
while sum_nums < target_num:
input_num = int(input())
sum_nums += input_num
print(sum_nums) | target_num = int(input())
sum_nums = 0
while sum_nums < target_num:
input_num = int(input())
sum_nums += input_num
print(sum_nums) |
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
if len(grid) <= 0 or grid is None:
return 0
rows = len(grid)
cols = len(grid[0])
for r in range(rows):
for c in range(cols):
if r==0 and c==0:
con... | class Solution:
def min_path_sum(self, grid: List[List[int]]) -> int:
if len(grid) <= 0 or grid is None:
return 0
rows = len(grid)
cols = len(grid[0])
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0:
contin... |
""" Asked by: Amazon [Medium]
Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less.
You must break it up so that words don't break across lines.
Each line has to have the maximum possible amount of words.
If there's no way to break the text up, the... | """ Asked by: Amazon [Medium]
Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less.
You must break it up so that words don't break across lines.
Each line has to have the maximum possible amount of words.
If there's no way to break the text up, the... |
n1=input()
def OddEvenSum(n1):
listNum=[]
for j in range(0,len(n1)):
listNum.append(int(n1[j]))
oddSum=0; evenSum=0
for k in range(0,len(listNum)):
if listNum[k]%2==0:
evenSum+=listNum[k]
else:
oddSum+=listNum[k]
print(f"Odd sum = {oddSum}, ... | n1 = input()
def odd_even_sum(n1):
list_num = []
for j in range(0, len(n1)):
listNum.append(int(n1[j]))
odd_sum = 0
even_sum = 0
for k in range(0, len(listNum)):
if listNum[k] % 2 == 0:
even_sum += listNum[k]
else:
odd_sum += listNum[k]
print(f'Od... |
# -*- coding: utf-8 -*-
'''
Created on Aug-31-19 10:07:28
@author: hustcc/webhookit
'''
# This means:
# When get a webhook request from `repo_name` on branch `branch_name`,
# will exec SCRIPT on servers config in the array.
WEBHOOKIT_CONFIGURE = {
# a web hook request can trigger multiple servers.
'repo_name... | """
Created on Aug-31-19 10:07:28
@author: hustcc/webhookit
"""
webhookit_configure = {'repo_name/branch_name': [{'HOST': '', 'PORT': '', 'USER': '', 'PWD': '', 'SCRIPT': '/home/hustcc/exec_hook_shell.sh'}]} |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Resource base classes.
"""
__docformat__ = "reStructuredText en"
__all__ = ['RELATION_BASE_URL',
]
RELATION_BASE_URL = 'http://relations.thelm... | """
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Resource base classes.
"""
__docformat__ = 'reStructuredText en'
__all__ = ['RELATION_BASE_URL']
relation_base_url = 'http://relations.thelma.org' |
test = {
'name': 'FooBar',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> class Foo:
... def print_one(self):
... print('foo')
... def print_two():
... print('foofoo')
>>> f = Foo()
... | test = {'name': 'FooBar', 'points': 0, 'suites': [{'cases': [{'code': "\n >>> class Foo:\n ... def print_one(self):\n ... print('foo')\n ... def print_two():\n ... print('foofoo')\n >>> f = Foo()\n >>> f.print_one()\n foo\n ... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/lachlan/catkin_ws/devel/share/fetchit_challenge/msg/SchunkMachineAction.msg;/home/lachlan/catkin_ws/devel/share/fetchit_challenge/msg/SchunkMachineActionGoal.msg;/home/lachlan/catkin_ws/devel/share/fetchit_challenge/msg/SchunkMachineActionResult... | messages_str = '/home/lachlan/catkin_ws/devel/share/fetchit_challenge/msg/SchunkMachineAction.msg;/home/lachlan/catkin_ws/devel/share/fetchit_challenge/msg/SchunkMachineActionGoal.msg;/home/lachlan/catkin_ws/devel/share/fetchit_challenge/msg/SchunkMachineActionResult.msg;/home/lachlan/catkin_ws/devel/share/fetchit_chal... |
'''
Lab 0, Task 2. Archakov Vsevolod
GitHub link: https://github.com/SevkavTV/Lab0_Task2.git
'''
def validate_lst(element: list) -> bool:
'''
Return True if element is valid and False in other case
>>> validate_lst([1, 1])
False
'''
for item in range(1, 10):
if element.count(item) > 1:... | """
Lab 0, Task 2. Archakov Vsevolod
GitHub link: https://github.com/SevkavTV/Lab0_Task2.git
"""
def validate_lst(element: list) -> bool:
"""
Return True if element is valid and False in other case
>>> validate_lst([1, 1])
False
"""
for item in range(1, 10):
if element.count(item) > 1:
... |
si, sj = map(int, input().split())
T = []
for i in range(50):
t = list(map(int, input().split()))
T.append(t)
P = []
for i in range(50):
p = list(map(int, input().split()))
P.append(p)
chack = [[0] * 50 for i in range(50)]
chack[si][sj] = -1
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for i, j in move:... | (si, sj) = map(int, input().split())
t = []
for i in range(50):
t = list(map(int, input().split()))
T.append(t)
p = []
for i in range(50):
p = list(map(int, input().split()))
P.append(p)
chack = [[0] * 50 for i in range(50)]
chack[si][sj] = -1
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for (i, j) in move... |
"""
error models for pybugsnag
"""
class PyBugsnagException(Exception):
"""base pybugsnag exception class"""
def __init__(self, *args, **kwargs):
extra = ""
if args:
extra = '\n| extra info: "{extra}"'.format(extra=args[0])
print(
"[{exception}]: {doc}{extra}".... | """
error models for pybugsnag
"""
class Pybugsnagexception(Exception):
"""base pybugsnag exception class"""
def __init__(self, *args, **kwargs):
extra = ''
if args:
extra = '\n| extra info: "{extra}"'.format(extra=args[0])
print('[{exception}]: {doc}{extra}'.format(excepti... |
DECIMALS = {"GNG-8d7e05" : 1000000000000000000,
"MEX-4183e7" : 1000000000000000000,
"LKMEX-9acade" : 1000000000000000000,
"WATER-104d38" : 1000000000000000000}
TOKEN_TYPE = {"GNG-8d7e05" : "token",
"MEX-4183e7" : "token",
"WARMY-cc922b": "NFT",
... | decimals = {'GNG-8d7e05': 1000000000000000000, 'MEX-4183e7': 1000000000000000000, 'LKMEX-9acade': 1000000000000000000, 'WATER-104d38': 1000000000000000000}
token_type = {'GNG-8d7e05': 'token', 'MEX-4183e7': 'token', 'WARMY-cc922b': 'NFT', 'LKMEX-9acade': 'META', 'WATER-104d38': 'token', 'COLORS-14cff1': 'NFT'}
authoriz... |
class Mime(object):
def __init__(self,content_type, category, extension, stream=False, use_file_name=False):
self.content_type = content_type
self.category = category
self.extension = extension
self.stream = stream
self.use_file_name = use_file_name
class Mimes(object):
... | class Mime(object):
def __init__(self, content_type, category, extension, stream=False, use_file_name=False):
self.content_type = content_type
self.category = category
self.extension = extension
self.stream = stream
self.use_file_name = use_file_name
class Mimes(object):
... |
class Peak:
"""A peak found in spectra.
Attributes:
id: Rounded X-coordinate used to collate peak data
x: X-coordinates of peak along its traversal through spectra
y: Y-coordinates of peak along its traversal through spectra
z: Z-coordinates of peak along its traversal through s... | class Peak:
"""A peak found in spectra.
Attributes:
id: Rounded X-coordinate used to collate peak data
x: X-coordinates of peak along its traversal through spectra
y: Y-coordinates of peak along its traversal through spectra
z: Z-coordinates of peak along its traversal through s... |
_base_ = './classifier.py'
model = dict(
type='TaskIncrementalLwF',
head=dict(
type='TaskIncLwfHead'
)
)
| _base_ = './classifier.py'
model = dict(type='TaskIncrementalLwF', head=dict(type='TaskIncLwfHead')) |
def part_one(inputs):
return get_acc(inputs, False)
def part_two(inputs):
for current_line in range(len(inputs)):
backup = inputs[current_line]
try:
if inputs[current_line][:3] == 'nop' and inputs[current_line][4:] != '+0':
inputs[current_line] = 'jmp' + inp... | def part_one(inputs):
return get_acc(inputs, False)
def part_two(inputs):
for current_line in range(len(inputs)):
backup = inputs[current_line]
try:
if inputs[current_line][:3] == 'nop' and inputs[current_line][4:] != '+0':
inputs[current_line] = 'jmp' + inputs[curre... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Make subpackages available:
__all__ = ['blockstorage', 'compute', 'config', 'database', 'dns', 'firewall', 'identity', 'images', 'loa... | __all__ = ['blockstorage', 'compute', 'config', 'database', 'dns', 'firewall', 'identity', 'images', 'loadbalancer', 'networking', 'objectstorage', 'vpnaas'] |
DWARVES_NUM = 9
dwarves = [int(input()) for _ in range(DWARVES_NUM)]
sum = sum(dwarves)
two_fake_sum = sum - 100
for i in range(DWARVES_NUM):
for j in range(DWARVES_NUM):
if i != j and dwarves[i] + dwarves[j] == two_fake_sum:
fake1 = i
fake2 = j
dwarves.pop(fake1)
dwarves.pop(fak... | dwarves_num = 9
dwarves = [int(input()) for _ in range(DWARVES_NUM)]
sum = sum(dwarves)
two_fake_sum = sum - 100
for i in range(DWARVES_NUM):
for j in range(DWARVES_NUM):
if i != j and dwarves[i] + dwarves[j] == two_fake_sum:
fake1 = i
fake2 = j
dwarves.pop(fake1)
dwarves.pop(fake2)
... |
'''
Since lists are mutable, this means that we will be using lists for
things where we might intend to manipulate the list of data, so how
can we do that? Turns out we can do all sorts of things.
We can add, remove, count, sort, search, and do quite a few other things
to python lists.
'''
# first we need an example... | """
Since lists are mutable, this means that we will be using lists for
things where we might intend to manipulate the list of data, so how
can we do that? Turns out we can do all sorts of things.
We can add, remove, count, sort, search, and do quite a few other things
to python lists.
"""
x = [1, 6, 3, 2, 6, 1, 2, 6... |
while True:
try:
a = float(input())
except EOFError:
break
print('|{:.4f}|={:.4f}'.format(a, abs(a)))
| while True:
try:
a = float(input())
except EOFError:
break
print('|{:.4f}|={:.4f}'.format(a, abs(a))) |
# lower case because appears as wcl section and wcl sections are converted to lowercase
META_HEADERS = 'h'
META_COMPUTE = 'c'
META_WCL = 'w'
META_COPY = 'p'
META_REQUIRED = 'r'
META_OPTIONAL = 'o'
FILETYPE_METADATA = 'filetype_metadata'
FILE_HEADER_INFO = 'file_header'
USE_HOME_ARCHIVE_INPUT = 'use_home_archive_input... | meta_headers = 'h'
meta_compute = 'c'
meta_wcl = 'w'
meta_copy = 'p'
meta_required = 'r'
meta_optional = 'o'
filetype_metadata = 'filetype_metadata'
file_header_info = 'file_header'
use_home_archive_input = 'use_home_archive_input'
use_home_archive_output = 'use_home_archive_output'
fm_prefer_uncompressed = [None, '.fz... |
"""Top-level package for mkdocs-github-dashboard."""
__author__ = """mkdocs-github-dashboard"""
__email__ = 'ms.kataoka@gmail.com'
__version__ = '0.1.0'
| """Top-level package for mkdocs-github-dashboard."""
__author__ = 'mkdocs-github-dashboard'
__email__ = 'ms.kataoka@gmail.com'
__version__ = '0.1.0' |
# -*- coding: utf-8 -*-
def main():
m, n = map(int, input().split())
unit = m // n
print(m - (unit * (n - 1)))
if __name__ == '__main__':
main()
| def main():
(m, n) = map(int, input().split())
unit = m // n
print(m - unit * (n - 1))
if __name__ == '__main__':
main() |
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n=len(prices)
if k>n//2:
return sum([prices[i+1]-prices[i] if prices[i+1]>prices[i] else 0 ... | class Solution(object):
def max_profit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n = len(prices)
if k > n // 2:
return sum([prices[i + 1] - prices[i] if prices[i + 1] > p... |
rows = int(input())
number = 1
for i in range(rows):
for j in range(i + 1):
print(number, end=' ')
number += 1
print()
| rows = int(input())
number = 1
for i in range(rows):
for j in range(i + 1):
print(number, end=' ')
number += 1
print() |
# list examples
z=[1,2,3]
assert z.__class__ == list
assert isinstance(z,list)
assert str(z)=="[1, 2, 3]"
a=['spam','eggs',100,1234]
print(a[:2]+['bacon',2*2])
print(3*a[:3]+['Boo!'])
print(a[:])
a[2]=a[2]+23
print(a)
a[0:2]=[1,12]
print(a)
a[0:2]=[]
print(a)
a[1:1]=['bletch','xyzzy']
print(a)
a[:0]=a
print(a)
a[:]=[... | z = [1, 2, 3]
assert z.__class__ == list
assert isinstance(z, list)
assert str(z) == '[1, 2, 3]'
a = ['spam', 'eggs', 100, 1234]
print(a[:2] + ['bacon', 2 * 2])
print(3 * a[:3] + ['Boo!'])
print(a[:])
a[2] = a[2] + 23
print(a)
a[0:2] = [1, 12]
print(a)
a[0:2] = []
print(a)
a[1:1] = ['bletch', 'xyzzy']
print(a)
a[:0] = ... |
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
# initialization:
dp = [0 for _ in range(n + 1)]
dp[0] = 1
dp[1] = 1
# state: dp[i] represents how many ways to reach step i
# f... | class Solution:
"""
@param n: An integer
@return: An integer
"""
def climb_stairs(self, n):
dp = [0 for _ in range(n + 1)]
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n] |
Name=input("enter the name ")
l=len(Name)
s=""
while l>0:
s+=Name[l-1]
l-=1
if s==Name:
print(" Name Plindrome "+Name)
else:
print("Name not Plindrome "+Name) | name = input('enter the name ')
l = len(Name)
s = ''
while l > 0:
s += Name[l - 1]
l -= 1
if s == Name:
print(' Name Plindrome ' + Name)
else:
print('Name not Plindrome ' + Name) |
#
# PySNMP MIB module OPENBSD-SENSORS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPENBSD-SENSORS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ... |
"""
After an apology from the opponent (they play C while it plays D, only happens when they play D first), if the opponent
immediately plays D, it plays another C instead of punishing in order to encourage the opponent to get back to CC-chain
(i.e. olive branch). If it plays D in this turn or the next one, go full D.
... | """
After an apology from the opponent (they play C while it plays D, only happens when they play D first), if the opponent
immediately plays D, it plays another C instead of punishing in order to encourage the opponent to get back to CC-chain
(i.e. olive branch). If it plays D in this turn or the next one, go full D.
... |
# Define a Product class. Objects should have 3 variables for price, code, and quantity
class Product:
def __init__(self, price=0.00, code='aaaa', quantity=0):
self.price = price
self.code = code
self.quantity = quantity
def __repr__(self):
return f'Product({self.price... | class Product:
def __init__(self, price=0.0, code='aaaa', quantity=0):
self.price = price
self.code = code
self.quantity = quantity
def __repr__(self):
return f'Product({self.price!r}, {self.code!r}, {self.quantity!r})'
def __str__(self):
return f'The product code ... |
"""
Counts total number of documents.
"""
def do_query(archives, config_file=None, logger=None, context=None):
"""
Iterate through archives and return all titles grouped by year.
"""
# [archive, archive, ...]
documents = archives.flatMap(
lambda archive: [(document.year, document) for docu... | """
Counts total number of documents.
"""
def do_query(archives, config_file=None, logger=None, context=None):
"""
Iterate through archives and return all titles grouped by year.
"""
documents = archives.flatMap(lambda archive: [(document.year, document) for document in list(archive)])
info = docum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.