content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
command = input()
numbers = [int(n) for n in input().split()]
command_numbers = []
def add_command_numbers(num):
if (num % 2 == 0 and command == "Even") or (num % 2 != 0 and command == "Odd"):
command_numbers.append(num)
for n in numbers:
add_command_numbers(n)
print(sum(command_number... | command = input()
numbers = [int(n) for n in input().split()]
command_numbers = []
def add_command_numbers(num):
if num % 2 == 0 and command == 'Even' or (num % 2 != 0 and command == 'Odd'):
command_numbers.append(num)
for n in numbers:
add_command_numbers(n)
print(sum(command_numbers) * len(numbers)) |
class Env(object):
user='test'
password='test'
port=5432
host='localhost'
dbname='todo'
development=False
env = Env()
| class Env(object):
user = 'test'
password = 'test'
port = 5432
host = 'localhost'
dbname = 'todo'
development = False
env = env() |
day09 = __import__("day-09")
process = day09.process_gen
rotor = {
0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'},
1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'},
}
diff = {
'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0),
}
def draw(data, panels):
direction = 'N'
coord = (0, 0)
try:
i... | day09 = __import__('day-09')
process = day09.process_gen
rotor = {0: {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}, 1: {'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N'}}
diff = {'N': (0, 1), 'E': (1, 0), 'S': (0, -1), 'W': (-1, 0)}
def draw(data, panels):
direction = 'N'
coord = (0, 0)
try:
inp = []
g = ... |
class MagicalGirlLevelOneDivTwo:
def theMinDistance(self, d, x, y):
return min(
sorted(
(a ** 2 + b ** 2) ** 0.5
for a in xrange(x - d, x + d + 1)
for b in xrange(y - d, y + d + 1)
)
)
| class Magicalgirllevelonedivtwo:
def the_min_distance(self, d, x, y):
return min(sorted(((a ** 2 + b ** 2) ** 0.5 for a in xrange(x - d, x + d + 1) for b in xrange(y - d, y + d + 1)))) |
test = 1
while True:
n = int(input())
if n == 0:
break
participantes = [int(x) for x in input().split()]
vencedor = [participantes[x] for x in range(n) if participantes[x] == (x + 1)]
print(f'Teste {test}')
test += 1
print(vencedor[0])
print()
| test = 1
while True:
n = int(input())
if n == 0:
break
participantes = [int(x) for x in input().split()]
vencedor = [participantes[x] for x in range(n) if participantes[x] == x + 1]
print(f'Teste {test}')
test += 1
print(vencedor[0])
print() |
# Check if there are two adjacent digits that are the same
def adjacent_in_list(li=()):
for c in range(0, len(li)-1):
if li[c] == li[c+1]:
return True
return False
# Check if the list doesn't get smaller as the index increases
def list_gets_bigger(li=()):
for c in range(0, len(li)-1):
... | def adjacent_in_list(li=()):
for c in range(0, len(li) - 1):
if li[c] == li[c + 1]:
return True
return False
def list_gets_bigger(li=()):
for c in range(0, len(li) - 1):
if li[c] > li[c + 1]:
return False
else:
return True
def password_criteria(n, mini, ... |
FARMINGPRACTICES_TYPE_URI = "https://w3id.org/okn/o/sdm#FarmingPractices"
FARMINGPRACTICES_TYPE_NAME = "FarmingPractices"
POINTBASEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#PointBasedGrid"
POINTBASEDGRID_TYPE_NAME = "PointBasedGrid"
SUBSIDY_TYPE_URI = "https://w3id.org/okn/o/sdm#Subsidy"
SUBSIDY_TYPE_NAME = "Subsidy... | farmingpractices_type_uri = 'https://w3id.org/okn/o/sdm#FarmingPractices'
farmingpractices_type_name = 'FarmingPractices'
pointbasedgrid_type_uri = 'https://w3id.org/okn/o/sdm#PointBasedGrid'
pointbasedgrid_type_name = 'PointBasedGrid'
subsidy_type_uri = 'https://w3id.org/okn/o/sdm#Subsidy'
subsidy_type_name = 'Subsidy... |
#
# @lc app=leetcode id=49 lang=python3
#
# [49] Group Anagrams
#
# https://leetcode.com/problems/group-anagrams/description/
#
# algorithms
# Medium (60.66%)
# Likes: 7901
# Dislikes: 277
# Total Accepted: 1.2M
# Total Submissions: 1.9M
# Testcase Example: '["eat","tea","tan","ate","nat","bat"]'
#
# Given an ar... | class Solution:
def group_anagrams(self, strs: List[str]) -> List[List[str]]:
d = {}
for str in strs:
str_sort = ''.join(sorted(str))
if str_sort in d:
d[str_sort].append(str)
else:
d[str_sort] = [str]
return list(d.values(... |
# Copyright (c) 2019 Pavel Vavruska
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, d... | class Config:
def __init__(self, fov, is_perspective_correction_on, is_metric_on, pixel_size, dynamic_lighting, texture_filtering):
self.__fov = fov
self.__is_perspective_correction_on = is_perspective_correction_on
self.__is_metric_on = is_metric_on
self.__pixel_size = pixel_size
... |
def dijkstra(graph):
start = "A"
times = {a: float("inf") for a in graph.keys()}
times[start] = 0
a = list(times)
while a:
node_selected = min(a, key=lambda k: times[k])
print("node selected", node_selected)
a.remove(node_selected)
for node, t in graph[node_selected... | def dijkstra(graph):
start = 'A'
times = {a: float('inf') for a in graph.keys()}
times[start] = 0
a = list(times)
while a:
node_selected = min(a, key=lambda k: times[k])
print('node selected', node_selected)
a.remove(node_selected)
for (node, t) in graph[node_selected... |
globalVar = 0
dataset = 'berlin'
max_len = 1024
nb_features = 36
nb_attention_param = 256
attention_init_value = 1.0 / 256
nb_hidden_units = 512 # number of hidden layer units
dropout_rate = 0.5
nb_lstm_cells = 128
nb_classes = 7
frame_size = 0.025 # 25 msec segments
step = 0.01 # 10 msec time step
| global_var = 0
dataset = 'berlin'
max_len = 1024
nb_features = 36
nb_attention_param = 256
attention_init_value = 1.0 / 256
nb_hidden_units = 512
dropout_rate = 0.5
nb_lstm_cells = 128
nb_classes = 7
frame_size = 0.025
step = 0.01 |
# Problem: https://docs.google.com/document/d/1D-3t64PnsEpcF6kKz5ZaquoMMB-r5UyYGyZzM4hjyi0/edit?usp=sharing
def create_dict():
''' Create a dictionary including the roles and their damages. '''
n = int(input('Enter the number of your party members: '))
party = {} # initialize a dictionary named p... | def create_dict():
""" Create a dictionary including the roles and their damages. """
n = int(input('Enter the number of your party members: '))
party = {}
for _ in range(n):
inputs = input('Enter the role and its nominal damage (separated by a space): ').split()
role = inputs[0]
... |
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1:
return 0
noOfBits = (2 ** (n-1) ) / 2
if k <= noOfBits:
return self.kthGrammar(n-1, k)
else:
return int (not self.kthGrammar(n-1, k - noOfBits)) | class Solution:
def kth_grammar(self, n: int, k: int) -> int:
if n == 1:
return 0
no_of_bits = 2 ** (n - 1) / 2
if k <= noOfBits:
return self.kthGrammar(n - 1, k)
else:
return int(not self.kthGrammar(n - 1, k - noOfBits)) |
# Testing
def print_hi(name):
print(f'Hi, {name}')
# Spewcialized max function
# arr = [2, 5, 6, 1, 7, 4]
def my_bad_max(a_list):
temp_max = 0
counter = 0
for index, num in enumerate(a_list):
for other_num in a_list[0:index]:
counter = counter + 1
value = num - other_n... | def print_hi(name):
print(f'Hi, {name}')
def my_bad_max(a_list):
temp_max = 0
counter = 0
for (index, num) in enumerate(a_list):
for other_num in a_list[0:index]:
counter = counter + 1
value = num - other_num
if value > temp_max:
temp_max = va... |
class ForthException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class CompileException(ForthException):
pass
| class Forthexception(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Compileexception(ForthException):
pass |
detik_input = int(input())
jam = detik_input // 3600
detik_input -= jam * 3600
menit = detik_input // 60
detik_input -= menit * 60
detik = detik_input
print(jam)
print(menit)
print(detik)
| detik_input = int(input())
jam = detik_input // 3600
detik_input -= jam * 3600
menit = detik_input // 60
detik_input -= menit * 60
detik = detik_input
print(jam)
print(menit)
print(detik) |
word1 = input()
word2 = input()
# How many letters does the longest word contain?
len_word1 = len(word1)
len_word2 = len(word2)
max_len = 0
if len_word1 >= len_word2:
max_len = len_word1
else:
max_len = len_word2
print(max_len)
| word1 = input()
word2 = input()
len_word1 = len(word1)
len_word2 = len(word2)
max_len = 0
if len_word1 >= len_word2:
max_len = len_word1
else:
max_len = len_word2
print(max_len) |
def _(line):
new_indent = 0
for section in line:
if (section != ''):
break
new_indent = new_indent + 1
return new_indent
| def _(line):
new_indent = 0
for section in line:
if section != '':
break
new_indent = new_indent + 1
return new_indent |
class Something:
def __eq__(self, other: object) -> bool:
pass
class Reference:
pass
__book_url__ = "dummy"
__book_version__ = "dummy"
associate_ref_with(Reference)
| class Something:
def __eq__(self, other: object) -> bool:
pass
class Reference:
pass
__book_url__ = 'dummy'
__book_version__ = 'dummy'
associate_ref_with(Reference) |
class RSI(object):
def __init__(self, OHLC, period):
self.OHLC = OHLC
self.period = period
self.gain_loss = self.gain_loss_calc()
def gain_loss_calc(self):
data = self.OHLC["close"]
gain_loss = []
for i in range(1, len(data)):
change = f... | class Rsi(object):
def __init__(self, OHLC, period):
self.OHLC = OHLC
self.period = period
self.gain_loss = self.gain_loss_calc()
def gain_loss_calc(self):
data = self.OHLC['close']
gain_loss = []
for i in range(1, len(data)):
change = float(data[i])... |
# -*- coding: utf8 -*-
__author__ = 'D. Belavin'
class NodeTree:
__slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height']
def __init__(self, key, payload, parent=None, left=None, right=None):
self.key = key
self.payload = payload
self.parent = parent
self.left = le... | __author__ = 'D. Belavin'
class Nodetree:
__slots__ = ['key', 'payload', 'parent', 'left', 'right', 'height']
def __init__(self, key, payload, parent=None, left=None, right=None):
self.key = key
self.payload = payload
self.parent = parent
self.left = left
self.right = r... |
class Member(object):
def __init__(self, interval, membership):
self.interval = interval
self.membership = membership
def is_max(self):
return self.membership == 1.0
def __str__(self):
return str(self.membership) + "/" + str(self.interval)
def __hash__(self):
... | class Member(object):
def __init__(self, interval, membership):
self.interval = interval
self.membership = membership
def is_max(self):
return self.membership == 1.0
def __str__(self):
return str(self.membership) + '/' + str(self.interval)
def __hash__(self):
... |
class SparkConstants:
SIMPLE_CRED = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider'
TEMP_CRED = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider'
CRED_PROVIDER_KEY = 'spark.hadoop.fs.s3a.aws.credentials.provider'
CRED_ACCESS_KEY = 'spark.hadoop.fs.s3a.access.key'
CRED_SECRET_KEY = ... | class Sparkconstants:
simple_cred = 'org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider'
temp_cred = 'org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider'
cred_provider_key = 'spark.hadoop.fs.s3a.aws.credentials.provider'
cred_access_key = 'spark.hadoop.fs.s3a.access.key'
cred_secret_key = '... |
load(":providers.bzl", "PrismaDataModel")
def _prisma_datamodel_impl(ctx):
return [
PrismaDataModel(datamodels = ctx.files.srcs),
DefaultInfo(
files = depset(ctx.files.srcs),
runfiles = ctx.runfiles(files = ctx.files.srcs),
),
]
prisma_datamodel = rule(
impl... | load(':providers.bzl', 'PrismaDataModel')
def _prisma_datamodel_impl(ctx):
return [prisma_data_model(datamodels=ctx.files.srcs), default_info(files=depset(ctx.files.srcs), runfiles=ctx.runfiles(files=ctx.files.srcs))]
prisma_datamodel = rule(implementation=_prisma_datamodel_impl, attrs={'srcs': attr.label_list(all... |
instr = input()
deviate = int(input())
for x in instr:
if x.isalpha():
uni = ord(x)
if x.islower():
x = chr(97 + ((uni + deviate) - 97) % 26)
elif x.isupper():
x = chr(65 + ((uni + deviate) - 65) % 26)
print(x, end="")
print()
| instr = input()
deviate = int(input())
for x in instr:
if x.isalpha():
uni = ord(x)
if x.islower():
x = chr(97 + (uni + deviate - 97) % 26)
elif x.isupper():
x = chr(65 + (uni + deviate - 65) % 26)
print(x, end='')
print() |
dd, mm, aa = input().split('/')
print(f'{dd}-{mm}-{aa}')
print(f'{mm}-{dd}-{aa}')
print(f'{aa}/{mm}/{dd}')
| (dd, mm, aa) = input().split('/')
print(f'{dd}-{mm}-{aa}')
print(f'{mm}-{dd}-{aa}')
print(f'{aa}/{mm}/{dd}') |
MODULUS_NUM = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787
MODULUS_BITS = 381
LIMB_SIZES = [55, 55, 51, 55, 55, 55, 55]
WORD_SIZE = 64
# Check that MODULUS_BITS is correct
assert(2**MODULUS_BITS > MODULUS_NUM)
assert(2**(MODULUS_BITS - 1) < MODULUS... | modulus_num = 4002409555221667393417789825735904156556882819939007885332058136124031650490837864442687629129015664037894272559787
modulus_bits = 381
limb_sizes = [55, 55, 51, 55, 55, 55, 55]
word_size = 64
assert 2 ** MODULUS_BITS > MODULUS_NUM
assert 2 ** (MODULUS_BITS - 1) < MODULUS_NUM
tmp = 0
for i in range(0, len(... |
DICTIONARY = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful',
'E': 'eager', 'D': 'disturbing', 'G': 'gregarious',
'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy',
'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal',
'O': 'oscillating', 'N': 'newtoni... | dictionary = {'A': 'awesome', 'C': 'confident', 'B': 'beautiful', 'E': 'eager', 'D': 'disturbing', 'G': 'gregarious', 'F': 'fantastic', 'I': 'ingestable', 'H': 'hippy', 'K': 'klingon', 'J': 'joke', 'M': 'mustache', 'L': 'literal', 'O': 'oscillating', 'N': 'newtonian', 'Q': 'queen', 'P': 'perfect', 'S': 'stylish', 'R': ... |
# find the non-repeating integer in an array
# set operations (including 'in' operation) are O(1) on average, and one loop that runs n times makes O(n)
def single(array):
repeated = set()
not_repeated = set()
for i in array:
if i in repeated:
continue
elif i in not_repeated:
... | def single(array):
repeated = set()
not_repeated = set()
for i in array:
if i in repeated:
continue
elif i in not_repeated:
repeated.add(i)
not_repeated.remove(i)
else:
not_repeated.add(i)
return not_repeated
array1 = [2, 'a', 'l', ... |
def lstrip0(iterable, obj):
i = 0
iterable_list = list(iterable)
while i < len(iterable_list):
if iterable_list[i] != obj:
break
i += 1
for k in range(i, len(iterable_list)):
yield iterable_list[k]
def lstrip(iterable, obj, key_func=None):
if not key_func:
... | def lstrip0(iterable, obj):
i = 0
iterable_list = list(iterable)
while i < len(iterable_list):
if iterable_list[i] != obj:
break
i += 1
for k in range(i, len(iterable_list)):
yield iterable_list[k]
def lstrip(iterable, obj, key_func=None):
if not key_func:
... |
def extendList(val, lst=[]):
lst.append(val)
return lst
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print("list1 = %s" % list1)
print("list2 = %s" % list2)
print("list3 = %s" % list3) | def extend_list(val, lst=[]):
lst.append(val)
return lst
list1 = extend_list(10)
list2 = extend_list(123, [])
list3 = extend_list('a')
print('list1 = %s' % list1)
print('list2 = %s' % list2)
print('list3 = %s' % list3) |
# Given an array nums of integers,
# return how many of them contain an even number of digits.
def find_numbers_easy(nums):
even_number_count = 0
for num in nums:
if len(str(num)) % 2 == 0:
even_number_count += 1
return even_number_count
def find_numbers_hard(nums):
even_numb... | def find_numbers_easy(nums):
even_number_count = 0
for num in nums:
if len(str(num)) % 2 == 0:
even_number_count += 1
return even_number_count
def find_numbers_hard(nums):
even_number_count = 0
for num in nums:
digit_count = 0
while num > 0:
digit_cou... |
# GENERATED VERSION FILE
# TIME: Tue Sep 28 14:27:47 2021
__version__ = '1.0rc1+c42460f'
short_version = '1.0rc1'
| __version__ = '1.0rc1+c42460f'
short_version = '1.0rc1' |
#!/usr/bin/env python3
bag_of_words = __import__('0-bag_of_words').bag_of_words
sentences = ["Holberton school is Awesome!",
"Machine learning is awesome",
"NLP is the future!",
"The children are our future",
"Our children's children are our grandchildren",
... | bag_of_words = __import__('0-bag_of_words').bag_of_words
sentences = ['Holberton school is Awesome!', 'Machine learning is awesome', 'NLP is the future!', 'The children are our future', "Our children's children are our grandchildren", 'The cake was not very good', 'No one said that the cake was not very good', 'Life is... |
x=4
itersLeft=x
Sum=0
while(itersLeft!=0):
Sum=Sum+x
itersLeft=itersLeft-1
print(Sum)
print(itersLeft)
print(str(x)+"**"+" 2 = "+str(Sum))
| x = 4
iters_left = x
sum = 0
while itersLeft != 0:
sum = Sum + x
iters_left = itersLeft - 1
print(Sum)
print(itersLeft)
print(str(x) + '**' + ' 2 = ' + str(Sum)) |
class BinarySearch:
def __init__(self, arr, target):
self.arr = arr
self.target = target
def binary_search(self):
lo, hi = 0, len(self.arr)
while lo<hi:
mid = lo + (hi-lo)//2
# dont use (lo+hi)//2. Integer overflow.
# https://en.wikipedia.or... | class Binarysearch:
def __init__(self, arr, target):
self.arr = arr
self.target = target
def binary_search(self):
(lo, hi) = (0, len(self.arr))
while lo < hi:
mid = lo + (hi - lo) // 2
if self.arr[mid] == self.target:
return mid
... |
class connectionFinder:
def __init__(self, length):
self.id = [0] * length
self.size = [0] * length
for i in range(length):
self.id[i] = i
self.size[i] = i
# Id2 will become a root of Id1 :
def union(self, id1, id2):
rootA = self.find(id1)
ro... | class Connectionfinder:
def __init__(self, length):
self.id = [0] * length
self.size = [0] * length
for i in range(length):
self.id[i] = i
self.size[i] = i
def union(self, id1, id2):
root_a = self.find(id1)
root_b = self.find(id2)
self.id... |
expected_output = {
"vrf": {
"vrf1": {
"lib_entry": {
"10.11.0.0/24": {
"rev": "7",
"remote_binding": {
"label": {
"imp-null": {
"lsr_id": {"10.132.0.1": {"... | expected_output = {'vrf': {'vrf1': {'lib_entry': {'10.11.0.0/24': {'rev': '7', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'label_space_id': {0: {}}}}}}}}, '10.12.0.0/24': {'label_binding': {'label': {'17': {}}}, 'rev': '8', 'remote_binding': {'label': {'imp-null': {'lsr_id': {'10.132.0.1': {'la... |
nmr = int(input("Digite um numero: "))
if nmr %2 == 0:
print("Numero par")
else:
print("Numero impar") | nmr = int(input('Digite um numero: '))
if nmr % 2 == 0:
print('Numero par')
else:
print('Numero impar') |
class DefaultConfig(object):
# Flask Settings
# ------------------------------
# There is a whole bunch of more settings available here:
# http://flask.pocoo.org/docs/0.11/config/#builtin-configuration-values
DEBUG = False
TESTING = False
| class Defaultconfig(object):
debug = False
testing = False |
n = int(input())
ss = input().split()
s = int(ss[0])
a = []
for i in range(n):
ss = input().split()
a.append((int(ss[0]), int(ss[1])))
a.sort(key=lambda x: x[0] * x[1])
ans = 0
for i in range(n):
if (s // (a[i])[1] > ans):
ans = s // (a[i])[1]
s *= (a[i])[0]
print(ans) | n = int(input())
ss = input().split()
s = int(ss[0])
a = []
for i in range(n):
ss = input().split()
a.append((int(ss[0]), int(ss[1])))
a.sort(key=lambda x: x[0] * x[1])
ans = 0
for i in range(n):
if s // a[i][1] > ans:
ans = s // a[i][1]
s *= a[i][0]
print(ans) |
def city_formatter(city, country):
formatted = f"{city.title()}, {country.title()}"
return formatted
print(city_formatter('hello', 'world')) | def city_formatter(city, country):
formatted = f'{city.title()}, {country.title()}'
return formatted
print(city_formatter('hello', 'world')) |
'''
Given an integer array sorted in non-decreasing order,
there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Example:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
- 1 <= arr.length <= 10^4
- 0 <= arr[i] ... | """
Given an integer array sorted in non-decreasing order,
there is exactly one integer in the array that occurs
more than 25% of the time.
Return that integer.
Example:
Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Constraints:
- 1 <= arr.length <= 10^4
- 0 <= arr[i] ... |
class json_to_csv():
def __init__(self):
self.stri=''
self.st=''
self.a=[]
self.b=[]
self.p=''
def read_js(self,path):
self.p=path
l=open(path,'r').readlines()
for i in l:
i=i.replace('\t','')
i=i.replace('... | class Json_To_Csv:
def __init__(self):
self.stri = ''
self.st = ''
self.a = []
self.b = []
self.p = ''
def read_js(self, path):
self.p = path
l = open(path, 'r').readlines()
for i in l:
i = i.replace('\t', '')
i = i.replac... |
def es5(tree):
# inserisci qui il tuo codice
d={}
for x in tree.f:
d1=es5(x)
for x in d1:
if x in d:
d[x]=d[x] | d1[x]
else:
d[x]=d1[x]
y=len(tree.f)
if y in d:
d[y]=d[y]| {tree.id}
else: d[y]= {tree.id}
... | def es5(tree):
d = {}
for x in tree.f:
d1 = es5(x)
for x in d1:
if x in d:
d[x] = d[x] | d1[x]
else:
d[x] = d1[x]
y = len(tree.f)
if y in d:
d[y] = d[y] | {tree.id}
else:
d[y] = {tree.id}
return d |
#!/home/jepoy/anaconda3/bin/python
def main():
x = dict(Buffy = 'meow', Zilla = 'grrr', Angel = 'purr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k, kwargs[k]))
else:
print('Meow.')
if __name__ == '__main__':
ma... | def main():
x = dict(Buffy='meow', Zilla='grrr', Angel='purr')
kitten(**x)
def kitten(**kwargs):
if len(kwargs):
for k in kwargs:
print('Kitten {} says {}'.format(k, kwargs[k]))
else:
print('Meow.')
if __name__ == '__main__':
main() |
def resolve():
'''
code here
'''
x, y = [int(item) for item in input().split()]
res = 0
if x < 0 and abs(y) - abs(x) >= 0:
res += 1
elif x > 0 and abs(y) - abs(x) <= 0:
res += 1
res += abs(abs(x) - abs(y))
if y > 0 and abs(y) - abs(x) < 0:
res += 1
eli... | def resolve():
"""
code here
"""
(x, y) = [int(item) for item in input().split()]
res = 0
if x < 0 and abs(y) - abs(x) >= 0:
res += 1
elif x > 0 and abs(y) - abs(x) <= 0:
res += 1
res += abs(abs(x) - abs(y))
if y > 0 and abs(y) - abs(x) < 0:
res += 1
elif ... |
def asm2(param_1, param_2): # push ebp
# mov ebp,esp
# sub esp,0x10
eax = param_2 # mov eax,DWORD PTR [ebp+0xc]
local_1 = eax # mov DWORD PTR [ebp-0x4],eax
eax = param_1 # mov eax,DWORD PTR [ebp+... | def asm2(param_1, param_2):
eax = param_2
local_1 = eax
eax = param_1
local_2 = eax
while param_1 <= 39046:
local_1 += 1
param_1 += 65
eax = local_1
return eax
print(hex(asm2(14, 33))) |
class _SpeechOperation():
def add_done_callback(callback):
pass | class _Speechoperation:
def add_done_callback(callback):
pass |
def main():
a = 1 if True else 2
print(a)
if __name__ == '__main__':
main()
| def main():
a = 1 if True else 2
print(a)
if __name__ == '__main__':
main() |
# Birth should occur before death of an individual
def userStory03(listOfPeople):
flag = True
def changeDateToNum(date): # date format must be like "2018-10-06"
if date == "NA":
return 0 # 0 will not larger than any date, for later comparison
else:
tempDate = dat... | def user_story03(listOfPeople):
flag = True
def change_date_to_num(date):
if date == 'NA':
return 0
else:
temp_date = date.split('-')
return int(tempDate[0] + tempDate[1] + tempDate[2])
for people in listOfPeople:
if people.Death != 'NA':
... |
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + " ! Your are " + age + " Years old now.")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = num1 + num2
print(result)
# We need int casting number num1 and num2
result = int(num1) + int(num2)
print(... | name = input('Enter your name: ')
age = input('Enter your age: ')
print('Hello ' + name + ' ! Your are ' + age + ' Years old now.')
num1 = input('Enter a number: ')
num2 = input('Enter another number: ')
result = num1 + num2
print(result)
result = int(num1) + int(num2)
print(result)
num1 = input('Enter a number: ')
num... |
# -*- coding: utf-8 -*-
def find_message(message: str) -> str:
result: str = ""
for i in list(message):
if i.isupper():
result += i
return result
# another pattern
return ''.join(i for i in message if i.isupper())
if __name__ == '__main__':
print("Example:")
print(fin... | def find_message(message: str) -> str:
result: str = ''
for i in list(message):
if i.isupper():
result += i
return result
return ''.join((i for i in message if i.isupper()))
if __name__ == '__main__':
print('Example:')
print(find_message('How are you? Eh, ok. Low or Lower? ' ... |
class Vector(object):
SHORTHAND = 'V'
def __init__(self, **kwargs):
super(Vector, self).__init__()
self.vector = kwargs
def dot(self, other):
product = 0
for member, value in self.vector.items():
product += value * other.member(member)
return product
... | class Vector(object):
shorthand = 'V'
def __init__(self, **kwargs):
super(Vector, self).__init__()
self.vector = kwargs
def dot(self, other):
product = 0
for (member, value) in self.vector.items():
product += value * other.member(member)
return product
... |
#!/usr/bin/env python3
def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el is not None:
return el
else:
for el in iterable:
if key(el) is not None:
return el
return default
| def first(iterable, default=None, key=None):
if key is None:
for el in iterable:
if el is not None:
return el
else:
for el in iterable:
if key(el) is not None:
return el
return default |
pattern_zero=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_odd=[0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667,... | pattern_zero = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666667, 0.805555555556, 0.888888888889, 0.916666666667]
pattern_odd = [0.0, 0.138888888889, 0.222222222222, 0.25, 0.333333333333, 0.472222222222, 0.555555555556, 0.583333333333, 0.666666666... |
Pathogen = {
'name': 'pathogen',
'fields': [
{'name': 'reported_name'},
{'name': 'drug_resistance'},
{'name': 'authority'},
{'name': 'tax_order'},
{'name': 'class'},
{'name': 'family'},
{'name': 'genus'},
{'name': 'species'},
{'name': 'sub_... | pathogen = {'name': 'pathogen', 'fields': [{'name': 'reported_name'}, {'name': 'drug_resistance'}, {'name': 'authority'}, {'name': 'tax_order'}, {'name': 'class'}, {'name': 'family'}, {'name': 'genus'}, {'name': 'species'}, {'name': 'sub_species'}]} |
def merge(di1, di2, fu=None):
di3 = {}
for ke in sorted(di1.keys() | di2.keys()):
if ke in di1 and ke in di2:
if fu is None:
va1 = di1[ke]
va2 = di2[ke]
if isinstance(va1, dict) and isinstance(va2, dict):
di3[ke] = m... | def merge(di1, di2, fu=None):
di3 = {}
for ke in sorted(di1.keys() | di2.keys()):
if ke in di1 and ke in di2:
if fu is None:
va1 = di1[ke]
va2 = di2[ke]
if isinstance(va1, dict) and isinstance(va2, dict):
di3[ke] = merge(va1... |
def read_list(t): return [t(x) for x in input().split()]
def read_line(t): return t(input())
def read_lines(t, N): return [t(input()) for _ in range(N)]
N, Q = read_list(int)
array = read_list(int)
C = [[0, 0, 0]]
for a in array:
c = C[-1][:]
c[a % 3] += 1
C.append(c)
for _ in range(Q):
l, r = read_li... | def read_list(t):
return [t(x) for x in input().split()]
def read_line(t):
return t(input())
def read_lines(t, N):
return [t(input()) for _ in range(N)]
(n, q) = read_list(int)
array = read_list(int)
c = [[0, 0, 0]]
for a in array:
c = C[-1][:]
c[a % 3] += 1
C.append(c)
for _ in range(Q):
... |
arr=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
n=4#col
m=4#row
#print matrix in spiral form
loop=0
while(loop<n/2):
for i in range(loop,n-loop-1):
print(arr[loop][i],end=" ")
for i in range(loop,m-loop-1):
print(arr[i][m-loop-1],end=" ")
for i in range(n-1-loop,loop-1+1,-... | arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
n = 4
m = 4
loop = 0
while loop < n / 2:
for i in range(loop, n - loop - 1):
print(arr[loop][i], end=' ')
for i in range(loop, m - loop - 1):
print(arr[i][m - loop - 1], end=' ')
for i in range(n - 1 - loop, loop - 1 + 1, ... |
class Color:
red = None
green = None
blue = None
white = None
bit_color = None
def __init__(self, red, green, blue, white=0):
self.red = red
self.green = green
self.blue = blue
self.white = white
def get_rgb(self):
return 'rgb(%d,%d,%d)' % (self.re... | class Color:
red = None
green = None
blue = None
white = None
bit_color = None
def __init__(self, red, green, blue, white=0):
self.red = red
self.green = green
self.blue = blue
self.white = white
def get_rgb(self):
return 'rgb(%d,%d,%d)' % (self.red,... |
N = int(input())
ano = N // 365
resto = N % 365
mes = resto // 30
dia = resto % 30
print(str(ano) + " ano(s)")
print(str(mes) + " mes(es)")
print(str(dia) + " dia(s)")
| n = int(input())
ano = N // 365
resto = N % 365
mes = resto // 30
dia = resto % 30
print(str(ano) + ' ano(s)')
print(str(mes) + ' mes(es)')
print(str(dia) + ' dia(s)') |
r, c = (map(int, input().split(' ')))
for row in range(r):
for col in range(c):
print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ')
print() | (r, c) = map(int, input().split(' '))
for row in range(r):
for col in range(c):
print(f'{chr(97 + row)}{chr(97 + row + col)}{chr(97 + row)}', end=' ')
print() |
'''Colocando cores no terminal do python'''
# \033[0;033;44m codigo para colocar as cores
# tipo de texto em cod (estilo do texto)
# 0 - sem estilo nenhum
# 1 - negrito
# 4 - sublinhado
# 7 - inverter as confgs
# cores em cod (cores do texto)
# 30 - branco
# 31 - vermelho
# 32 - verde
# 33 - amarelo
# 34 - azul
# 35... | """Colocando cores no terminal do python""" |
valid_passport = 0
invalid_passport = 0
def get_key(p_line):
keys = []
for i in p_line.split():
keys.append(i.split(':')[0])
return keys
def check_validation(keys):
for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))
# CID is optional
if 'cid' in keys:
... | valid_passport = 0
invalid_passport = 0
def get_key(p_line):
keys = []
for i in p_line.split():
keys.append(i.split(':')[0])
return keys
def check_validation(keys):
for_valid = ' '.join(sorted(['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))
if 'cid' in keys:
keys.remove('cid')
... |
class Security:
def __init__(self, name, ticker, country, ir_website, currency):
self.name = name.strip()
self.ticker = ticker.strip()
self.country = country.strip()
self.currency = currency.strip()
self.ir_website = ir_website.strip()
@staticmethod
def summary(name,... | class Security:
def __init__(self, name, ticker, country, ir_website, currency):
self.name = name.strip()
self.ticker = ticker.strip()
self.country = country.strip()
self.currency = currency.strip()
self.ir_website = ir_website.strip()
@staticmethod
def summary(name... |
def plot_frames(motion, ax, times=1, fps=0.01):
joints = [j for j in motion.joint_names() if not j.startswith('ignore_')]
x, ys = [], []
for t, frame in motion.frames(fps):
x.append(t)
ys.append(frame.positions)
if t > motion.length() * times:
break
for joint in join... | def plot_frames(motion, ax, times=1, fps=0.01):
joints = [j for j in motion.joint_names() if not j.startswith('ignore_')]
(x, ys) = ([], [])
for (t, frame) in motion.frames(fps):
x.append(t)
ys.append(frame.positions)
if t > motion.length() * times:
break
for joint in... |
default_vimrc = "\
set fileencoding=utf-8 fileformat=unix\n\
call plug#begin('~/.vim/plugged')\n\
Plug 'prabirshrestha/async.vim'\n\
Plug 'prabirshrestha/vim-lsp'\n\
Plug 'prabirshrestha/asyncomplete.vim'\n\
Plug 'prabirshrestha/asyncomplete-lsp.vim'\n\
Plug 'mattn/vim-lsp-settings'\n\
Plug 'prabirshrestha/asyncomplete... | default_vimrc = "set fileencoding=utf-8 fileformat=unix\ncall plug#begin('~/.vim/plugged')\nPlug 'prabirshrestha/async.vim'\nPlug 'prabirshrestha/vim-lsp'\nPlug 'prabirshrestha/asyncomplete.vim'\nPlug 'prabirshrestha/asyncomplete-lsp.vim'\nPlug 'mattn/vim-lsp-settings'\nPlug 'prabirshrestha/asyncomplete-file.vim'\nPlug... |
extensions = ["myst_parser"]
exclude_patterns = ["_build"]
copyright = "2020, Executable Book Project"
myst_enable_extensions = ["deflist"]
| extensions = ['myst_parser']
exclude_patterns = ['_build']
copyright = '2020, Executable Book Project'
myst_enable_extensions = ['deflist'] |
# Given a list and a num. Write a function to return boolean if that element is not in the list.
def check_num_in_list(alist, num):
for i in alist:
if num in alist and num%2 != 0:
return True
else:
return False
sample = check_num_in_list([2,7,3,1,6,9], 6)
print(sample)
| def check_num_in_list(alist, num):
for i in alist:
if num in alist and num % 2 != 0:
return True
else:
return False
sample = check_num_in_list([2, 7, 3, 1, 6, 9], 6)
print(sample) |
z = 10
y = 0
x = y < z and z > y or y > z and z < y
print(x)
# X = True
| z = 10
y = 0
x = y < z and z > y or (y > z and z < y)
print(x) |
# Merge Sort: D&C Algo, Breaks data into individual pieces and merges them, uses recursion to operate on datasets. Key is to understand how to merge 2 sorted arrays.
items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = da... | items = [6, 20, 8, 9, 19, 56, 23, 87, 41, 49, 53]
def mergesort(dataset):
if len(dataset) > 1:
mid = len(dataset) // 2
leftarr = dataset[:mid]
rightarr = dataset[mid:]
mergesort(leftarr)
mergesort(rightarr)
i = 0
j = 0
k = 0
while i < len(left... |
def nameCreator(playerName):
firstLetter = playerName.split(" ")[1][0]
try:
lastName = playerName.split(" ")[1][0:5]
except:
lastNameSize = len(playerName.split(" ")[1])
lastName = playerName.split(" ")[1][len(lastNameSize)]
firstName = playerName[0:2]
return lastName + fi... | def name_creator(playerName):
first_letter = playerName.split(' ')[1][0]
try:
last_name = playerName.split(' ')[1][0:5]
except:
last_name_size = len(playerName.split(' ')[1])
last_name = playerName.split(' ')[1][len(lastNameSize)]
first_name = playerName[0:2]
return (lastName... |
# Author : Aniruddha Krishna Jha
# Date : 22/10/2021
'''**********************************************************************************
Given an array nums of positive integers, return the longest possible length of an array prefix of nums,
such that it is possible to remove exactly one element from this pref... | """**********************************************************************************
Given an array nums of positive integers, return the longest possible length of an array prefix of nums,
such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have t... |
class BTNode:
'''Binary Tree Node class - do not modify'''
def __init__(self, value, left, right):
'''Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None.'''
self.value = value
self.left = left
self.right =... | class Btnode:
"""Binary Tree Node class - do not modify"""
def __init__(self, value, left, right):
"""Stores a reference to the value, left child node, and right child node. If no left or right child, attributes should be None."""
self.value = value
self.left = left
self.right =... |
checksum = 0
with open("Day 2 - input", "r") as file:
for line in file:
row = [int(i) for i in line.split()]
result = max(row) - min(row)
checksum += result
print(f"The checksum is {checksum}")
| checksum = 0
with open('Day 2 - input', 'r') as file:
for line in file:
row = [int(i) for i in line.split()]
result = max(row) - min(row)
checksum += result
print(f'The checksum is {checksum}') |
def bytes_to(bytes_value, to_unit, bytes_size=1024):
units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return round(float(bytes_value) / (bytes_size ** units[to_unit]), 2)
def convert_to_human(value):
if value < 1024:
return str(value) + 'b'
if value < 1048576:
return str(bytes_... | def bytes_to(bytes_value, to_unit, bytes_size=1024):
units = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return round(float(bytes_value) / bytes_size ** units[to_unit], 2)
def convert_to_human(value):
if value < 1024:
return str(value) + 'b'
if value < 1048576:
return str(bytes_to(... |
TLDS = [
"ABB",
"ABBOTT",
"ABOGADO",
"AC",
"ACADEMY",
"ACCENTURE",
"ACCOUNTANT",
"ACCOUNTANTS",
"ACTIVE",
"ACTOR",
"AD",
"ADS",
"ADULT",
"AE",
"AEG",
"AERO",
"AF",
"AFL",
"AG",
"AGENCY",
"AI",
"AIG",
"AIRFORCE",
"AL",
"ALLFINANZ",
"ALSACE",
"AM",
"AMSTERDAM",
"AN",
"ANDROID",
"AO",
"APARTMENTS",
"AQ",
"AQUARELLE",
"AR"... | tlds = ['ABB', 'ABBOTT', 'ABOGADO', 'AC', 'ACADEMY', 'ACCENTURE', 'ACCOUNTANT', 'ACCOUNTANTS', 'ACTIVE', 'ACTOR', 'AD', 'ADS', 'ADULT', 'AE', 'AEG', 'AERO', 'AF', 'AFL', 'AG', 'AGENCY', 'AI', 'AIG', 'AIRFORCE', 'AL', 'ALLFINANZ', 'ALSACE', 'AM', 'AMSTERDAM', 'AN', 'ANDROID', 'AO', 'APARTMENTS', 'AQ', 'AQUARELLE', 'AR',... |
class Bank:
def __init__(self):
self.inf = 0
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
def notify_observers(self):
print("Inflacja na poziomie: ", format(self.inf, '.2f'))
for observer in self._observers:
... | class Bank:
def __init__(self):
self.inf = 0
self._observers = []
def register_observer(self, observer):
self._observers.append(observer)
def notify_observers(self):
print('Inflacja na poziomie: ', format(self.inf, '.2f'))
for observer in self._observers:
... |
fruta = 'kiwi'
if fruta == 'kiwi':
print("El valor es kiwi")
elif fruta == 'manzana':
print("Es una manzana")
elif fruta == 'manzana2':
pass #si no sabemos que poner y no marque error
else:
print("No son iguales")
mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False
print(mensaje)
| fruta = 'kiwi'
if fruta == 'kiwi':
print('El valor es kiwi')
elif fruta == 'manzana':
print('Es una manzana')
elif fruta == 'manzana2':
pass
else:
print('No son iguales')
mensaje = 'El valor es kiwi' if fruta == 'kiwis' else False
print(mensaje) |
# Status code
API_HANDLER_OK_CODE = 200
API_HANDLER_ERROR_CODE = 400
# REST parameters
SERVICE_HANDLER_POST_ARG_KEY = "key"
SERVICE_HANDLER_POST_BODY_KEY = "body_key"
| api_handler_ok_code = 200
api_handler_error_code = 400
service_handler_post_arg_key = 'key'
service_handler_post_body_key = 'body_key' |
def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(
field < timestamp
)
try:
return new_query.paginate(
per_page=per_page,
page=page
).items, 20... | def get_paginated_result(query, page, per_page, field, timestamp):
new_query = query
if page != 1 and timestamp != None:
new_query = query.filter(field < timestamp)
try:
return (new_query.paginate(per_page=per_page, page=page).items, 200)
except:
response_object = {'status': 'err... |
#!/usr/bin/env python3
# encoding: utf-8
def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _SubclassNode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __r... | def _subclasses(cls):
try:
return cls.__subclasses__()
except TypeError:
return type.__subclasses__(cls)
class _Subclassnode:
__slots__ = frozenset(('cls', 'children'))
def __init__(self, cls, children=None):
self.cls = cls
self.children = children or []
def __repr... |
def longest_uppercase(input,k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k :
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
count = 0
for m in input :
if test_letters.find(m) ... | def longest_uppercase(input, k):
final_out = 0
for i in input:
test_letters = i
for j in input:
if len(test_letters) == k:
break
if test_letters.find(j) >= 0:
pass
else:
test_letters += j
max = 0
... |
# The following dependencies were calculated from:
#
# generate_workspace --artifact=io.opencensus:opencensus-api:0.12.2 --artifact=io.opencensus:opencensus-contrib-zpages:0.12.2 --artifact=io.opencensus:opencensus-exporter-trace-logging:0.12.2 --artifact=io.opencensus:opencensus-impl:0.12.2 --repositories=http://repo.... | def opencensus_maven_jars():
native.maven_jar(name='com_google_code_findbugs_jsr305', artifact='com.google.code.findbugs:jsr305:3.0.1', repository='http://repo.maven.apache.org/maven2/', sha1='f7be08ec23c21485b9b5a1cf1654c2ec8c58168d')
native.maven_jar(name='io_grpc_grpc_context', artifact='io.grpc:grpc-context... |
# -- Project information -----------------------------------------------------
project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
# -- General configuration ---------------------------------------------------
extensions = []
templates_path = ['_templates']
exclude_p... | project = 'showyourwork'
copyright = '2021, Rodrigo Luger'
author = 'Rodrigo Luger'
release = '1.0.0'
extensions = []
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
master_doc = 'index'
html_theme = 'sphinx_book_theme'
html_copy_source = True
html_show_sourcelink = True
html_sou... |
'''
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
'''
'''
#3-2
j = 0
for i in range(15):
s = 10... | """
#3-1
b=0
c=0
while 1 :
a=input("Enthe an integer, the input ends if it is :")
if((a>0)|(a<0)):
if a>0:
b=a
else:
c=-a
if(a==0):
print("zheng shu {},fushu {},pingjunshu {}".format(b,c,(b+c)))
break
"""
'\n#3-2\nj = 0\nfor i in range(15):\n s = 10... |
def mergeSort(myList):
print("Splitting ",myList)
if (len(myList) > 1):
mid = len(myList)//2
leftList = myList[:mid]
rightList = myList[mid:]
mergeSort(leftList)
mergeSort(rightList)
i = 0
j = 0
k = 0
while ((i < len(leftList)) and (j < len(rightList))):
if (leftList[i] < rightList[j]):
... | def merge_sort(myList):
print('Splitting ', myList)
if len(myList) > 1:
mid = len(myList) // 2
left_list = myList[:mid]
right_list = myList[mid:]
merge_sort(leftList)
merge_sort(rightList)
i = 0
j = 0
k = 0
while i < len(leftList) and j < l... |
while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = Model("KP")
knapsack.ModelSense=-1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype="I", name="y[%d]"%i)
knapsack.update()
knapsack.addConstr(quicksum(w[i]*y[... | while True:
relax = master.relax()
relax.optimize()
pi = [c.Pi for c in relax.getConstrs()]
knapsack = model('KP')
knapsack.ModelSense = -1
y = {}
for i in range(m):
y[i] = knapsack.addVar(ub=q[i], vtype='I', name='y[%d]' % i)
knapsack.update()
knapsack.addConstr(quicksum((w[... |
def hasDoubleDigits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def neverDecreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
ret... | def has_double_digits(p):
previous = ''
for c in p:
if c == previous:
return True
previous = c
return False
def never_decreases(p):
previous = -1
for c in p:
current = int(c)
if current < previous:
return False
previous = current
r... |
# a red shadow with some blur and a offset
cmykShadow((3, 3), 10, (1, 0, 0, 0))
# draw a rect
rect(100, 100, 30, 30) | cmyk_shadow((3, 3), 10, (1, 0, 0, 0))
rect(100, 100, 30, 30) |
#
# PySNMP MIB module NSLDAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSLDAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:25:08 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, 09:... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) ... |
def deleteDigit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(deleteDigit(152)) | def delete_digit(n):
n = str(n)
return max([int(n[:index] + n[index + 1:]) for index in range(len(n))])
print(delete_digit(152)) |
name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version
| name = 'tinymce'
authors = 'Joost Cassee'
version = 'trunk'
release = version |
#
# PySNMP MIB module PPVPN-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPVPN-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:33:05 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, 09:23:1... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, value_size_constraint, constraints_union, single_value_constraint) ... |
with open('../input.txt','rt') as f:
lst = set(map(int,f.readlines()))
for x in lst:
if 2020-x in lst:
print(x*(2020-x)) | with open('../input.txt', 'rt') as f:
lst = set(map(int, f.readlines()))
for x in lst:
if 2020 - x in lst:
print(x * (2020 - x)) |
print("Calculator has started")
while True:
a = float(input("Enter first number "))
b = float(input("Enter second number "))
chooseop=1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input("Enter 1 for addition, 2 for subtraction, 3 for multipli... | print('Calculator has started')
while True:
a = float(input('Enter first number '))
b = float(input('Enter second number '))
chooseop = 1
while (chooseop == 1) | (chooseop == 2) | (chooseop == 3) | (chooseop == 4):
chooseop = int(input('Enter 1 for addition, 2 for subtraction, 3 for multiplicati... |
class node:
def __init__(self,value=None):
self.value=value
self.left_child=None
self.right_child=None
self.parent=None # pointer to parent node in tree
self.height=1 # height of node in tree (max dist. to leaf) NEW FOR AVL
class AVLTree:
def __init__(self):
self.root=None
def __repr__(self):
if self... | class Node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
self.parent = None
self.height = 1
class Avltree:
def __init__(self):
self.root = None
def __repr__(self):
if self.root == None:
... |
class Boid():
def __init__(self, x,y,width,height):
self.position = Vector(x,y)
| class Boid:
def __init__(self, x, y, width, height):
self.position = vector(x, y) |
# Area of a Triangle
print("Write a function that takes the base and height of a triangle and return its area.")
def area():
base = float(int(input("Enter the Base of the Triangle : ")))
height = float(int(input("Enter the height of the Triangle : ")))
total_area = (base * height)/2
print(total_area)
... | print('Write a function that takes the base and height of a triangle and return its area.')
def area():
base = float(int(input('Enter the Base of the Triangle : ')))
height = float(int(input('Enter the height of the Triangle : ')))
total_area = base * height / 2
print(total_area)
area()
input('Please C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.