content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def x(city, name):
city = open(city,'r').read()
city = city.replace('\n', ';')
city = city.split(';')
success = []
for i in city:
if i:
success.append(i.lstrip().rstrip())
success = {k: v for k, v in zip(success[::2], success[1::2])}
file = open('{0}.txt'.format(name), 'w... | def x(city, name):
city = open(city, 'r').read()
city = city.replace('\n', ';')
city = city.split(';')
success = []
for i in city:
if i:
success.append(i.lstrip().rstrip())
success = {k: v for (k, v) in zip(success[::2], success[1::2])}
file = open('{0}.txt'.format(name),... |
users = [
{"first_name": "Helen", "age": 39},
{"first_name": "anni", "age": 9},
{"first_name": "Buck", "age": 10},
]
def get_user_name(users):
"""Get name of the user in lower case"""
return users["first_name"].lower()
def get_sorted_dictionary(users):
"""Sort the nested dictionary"""
if... | users = [{'first_name': 'Helen', 'age': 39}, {'first_name': 'anni', 'age': 9}, {'first_name': 'Buck', 'age': 10}]
def get_user_name(users):
"""Get name of the user in lower case"""
return users['first_name'].lower()
def get_sorted_dictionary(users):
"""Sort the nested dictionary"""
if not isinstance(u... |
'''Libraries used by the main program
All the libraries that will be used by the
main program will be placed here.
Contains Library with functions to create latex report.
''' | """Libraries used by the main program
All the libraries that will be used by the
main program will be placed here.
Contains Library with functions to create latex report.
""" |
"""
Author: Ao Wang
Date: 08/27/19
Description: Brute force decryption of the Simplified Columnar Cipher w/o asking the key
"""
LETTERS_AND_SPACE = "abcdefghijklmnopqrstuvwxyz" + ' \t\n'
# The function returns a list of words from two word text files
def loadDictionary():
with open("words.txt", "r") as f1:
... | """
Author: Ao Wang
Date: 08/27/19
Description: Brute force decryption of the Simplified Columnar Cipher w/o asking the key
"""
letters_and_space = 'abcdefghijklmnopqrstuvwxyz' + ' \t\n'
def load_dictionary():
with open('words.txt', 'r') as f1:
file1 = f1.read().split('\n')
with open('morewords.txt', '... |
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py'
]
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
... | _base_ = ['../_base_/models/retinanet_r50_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py']
cudnn_benchmark = True
norm_cfg = dict(type='BN', requires_grad=True)
model = dict(pretrained='torchvision://resnet50', backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3)... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
s = input().strip()
ans = ... | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
n = int(input())
s = input().strip()
ans = max(s)
idx = s.index(ans... |
"""
Name : Breaking the records
Category : Implementation
Difficulty : Easy
Language : Python3
Question Link : https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
"""
n = int(input())
score = list(map(int, input().split()))
a = b = score[0]
r1 = r2 = 0
for i in score[... | """
Name : Breaking the records
Category : Implementation
Difficulty : Easy
Language : Python3
Question Link : https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem
"""
n = int(input())
score = list(map(int, input().split()))
a = b = score[0]
r1 = r2 = 0
for i in score[1:... |
#
# PySNMP MIB module HH3C-SESSION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-SESSION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:16:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) ... |
def getYears():
"""Return a list of years for which data is available."""
years = [1900, 1901, 1902, 1903, 1905, 1905, 1906, 1907, 1908, 1909, 1910]
return years
def getSentencesForYear(year):
"""Return list of sentences in given year.
Each sentence is a list of words.
Each word is a string.
... | def get_years():
"""Return a list of years for which data is available."""
years = [1900, 1901, 1902, 1903, 1905, 1905, 1906, 1907, 1908, 1909, 1910]
return years
def get_sentences_for_year(year):
"""Return list of sentences in given year.
Each sentence is a list of words.
Each word is a string... |
# class object to store neural signal data
class NeuralBit:
def __init__(self, value):
self.value = value
def bit(self):
return self.value
class NeuralWave:
def __init__(self, path, label, output_matrix_size):
""" Specify the path to the data set, upload the data points""... | class Neuralbit:
def __init__(self, value):
self.value = value
def bit(self):
return self.value
class Neuralwave:
def __init__(self, path, label, output_matrix_size):
""" Specify the path to the data set, upload the data points"""
self.label = label
self.raw_data ... |
file_path = 'D12/input.txt'
#file_path = 'D12/test.txt'
#file_path = 'D12/test2.txt'
with open(file_path) as f:
text = f.read().split('\n')
def reset(text):
data = []
for i in text:
data.append(i.split('-'))
distinctNodes = []
for i in data:
if i[0] not in distinctNodes:
... | file_path = 'D12/input.txt'
with open(file_path) as f:
text = f.read().split('\n')
def reset(text):
data = []
for i in text:
data.append(i.split('-'))
distinct_nodes = []
for i in data:
if i[0] not in distinctNodes:
distinctNodes.append(i[0])
if i[1] not in disti... |
def generate_permutations(perm, n):
if len(perm) == n:
print(perm)
return
for k in range(n):
if k not in perm:
perm.append(k)
generate_permutations(perm, n)
perm.pop()
generate_permutations(perm=[], n=4)
| def generate_permutations(perm, n):
if len(perm) == n:
print(perm)
return
for k in range(n):
if k not in perm:
perm.append(k)
generate_permutations(perm, n)
perm.pop()
generate_permutations(perm=[], n=4) |
hip = 'hip'
thorax = 'thorax'
r_hip = 'r_hip'
r_knee = 'r_knee'
r_ankle = 'r_ankle'
r_ball = 'r_ball'
r_toes = 'r_toes'
l_hip = 'l_hip'
l_knee = 'l_knee'
l_ankle = 'l_ankle'
l_ball = 'l_ball'
l_toes = 'l_toes'
neck_base = 'neck'
head_center = 'head-center'
head_back = 'head-back'
l_uknown = 'l_uknown'
l_shoulder = 'l_s... | hip = 'hip'
thorax = 'thorax'
r_hip = 'r_hip'
r_knee = 'r_knee'
r_ankle = 'r_ankle'
r_ball = 'r_ball'
r_toes = 'r_toes'
l_hip = 'l_hip'
l_knee = 'l_knee'
l_ankle = 'l_ankle'
l_ball = 'l_ball'
l_toes = 'l_toes'
neck_base = 'neck'
head_center = 'head-center'
head_back = 'head-back'
l_uknown = 'l_uknown'
l_shoulder = 'l_s... |
# Time complexity is O(n)
def leaders_to_right(iterable):
"""
Leaders-to-right in the iterable is defined as if an element in the iterable
is greater than all other elements to it's right side
:param iterable: It should be of either list or tuple types containing numbers
:return: list of... | def leaders_to_right(iterable):
"""
Leaders-to-right in the iterable is defined as if an element in the iterable
is greater than all other elements to it's right side
:param iterable: It should be of either list or tuple types containing numbers
:return: list of tuples containing leader element an... |
a=0
b=1
while a<10:
print(a)
a,b=b,a+b
| a = 0
b = 1
while a < 10:
print(a)
(a, b) = (b, a + b) |
class Distances(object):
"""description of class"""
def __init__(self, root):
self.root = root
self.cells = {}
"""Root cell is distance 0"""
self.cells[root] = 0
def GetCellDistance(self, cell):
"""Gets the cell distance from the root cell"""
dist = self.ce... | class Distances(object):
"""description of class"""
def __init__(self, root):
self.root = root
self.cells = {}
'Root cell is distance 0'
self.cells[root] = 0
def get_cell_distance(self, cell):
"""Gets the cell distance from the root cell"""
dist = self.cells... |
#program to read the mass data and find the number of islands.
c=0
def f(x,y,z):
if 0<=y<10 and 0<=z<10 and x[z][y]=='1':
x[z][y]='0'
for dy,dz in [[-1,0],[1,0],[0,-1],[0,1]]:f(x,y+dy,z+dz)
print("Input 10 rows of 10 numbers representing green squares (island) as 1 and blue squares (sea) as zeros") ... | c = 0
def f(x, y, z):
if 0 <= y < 10 and 0 <= z < 10 and (x[z][y] == '1'):
x[z][y] = '0'
for (dy, dz) in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
f(x, y + dy, z + dz)
print('Input 10 rows of 10 numbers representing green squares (island) as 1 and blue squares (sea) as zeros')
while 1:
tr... |
def seq(a, d, n):
res = str(a)
for i in range(n-1):
a += d
a %= 10
res += str(a)
return res[::-1]
l = input()
r = input()
limits = set()
for a in range(10):
for d in range(10):
limits.add(int(seq(a, d, len(l))))
limits.add(int(seq(a, d, len(r))))
res = max(99*(... | def seq(a, d, n):
res = str(a)
for i in range(n - 1):
a += d
a %= 10
res += str(a)
return res[::-1]
l = input()
r = input()
limits = set()
for a in range(10):
for d in range(10):
limits.add(int(seq(a, d, len(l))))
limits.add(int(seq(a, d, len(r))))
res = max(99 * ... |
"""This is my module.
Pretty pointless tbh, has only one function, welcome()
Don't judge me this was a primer on using help()"""
def welcome(person='Person'):
"""The welcome() function
Takes an argument person, or defaults person to "Person", prints __name__
and welcomes the person.
Now scram."""
... | """This is my module.
Pretty pointless tbh, has only one function, welcome()
Don't judge me this was a primer on using help()"""
def welcome(person='Person'):
"""The welcome() function
Takes an argument person, or defaults person to "Person", prints __name__
and welcomes the person.
Now scram."""
... |
def part1():
data = []
with open("C:\\Dev\\projects\\advent-of-code\\python\\day10\\input.txt") as f:
data = [int(x) for x in f.readlines()]
data.append(0)
data.append(max(data) + 3)
data.sort()
diffs = [0] * 4
for i in range(1, len(data)):
d = data[i] - data[i-1]
di... | def part1():
data = []
with open('C:\\Dev\\projects\\advent-of-code\\python\\day10\\input.txt') as f:
data = [int(x) for x in f.readlines()]
data.append(0)
data.append(max(data) + 3)
data.sort()
diffs = [0] * 4
for i in range(1, len(data)):
d = data[i] - data[i - 1]
d... |
class Facility:
id = 0
operator = None
name = None
bcghg_id = None
type = None
naics = None
description = None
swrs_facility_id = None
production_calculation_explanation = None
production_additional_info = None
production_public_info = None
ciip_db_id = None
def __init__(self, operator):
... | class Facility:
id = 0
operator = None
name = None
bcghg_id = None
type = None
naics = None
description = None
swrs_facility_id = None
production_calculation_explanation = None
production_additional_info = None
production_public_info = None
ciip_db_id = None
def __in... |
numero1=int(input("Digite Numero Uno: "))
numero2=int(input("Digite Numero Dos: "))
operador=input(" * / + - %: ")
if(operador=="+"):
funcion=lambda a,b: a+b
elif(operador=="-"):
funcion=lambda a,b: a-b
elif(operador=="/"):
funcion=lambda a,b:a/b
elif(operador=="*"):
funcion=lambda a,b:a*b
elif(oper... | numero1 = int(input('Digite Numero Uno: '))
numero2 = int(input('Digite Numero Dos: '))
operador = input(' * / + - %: ')
if operador == '+':
funcion = lambda a, b: a + b
elif operador == '-':
funcion = lambda a, b: a - b
elif operador == '/':
funcion = lambda a, b: a / b
elif operador == '*':
funcion =... |
a = 1
b = a+10
print(b)
| a = 1
b = a + 10
print(b) |
n=99999
t=n
while(t//10!=0):
x=t
sum=0
while(x!=0):
sum += x%10
x=x//10
t=sum
print(sum)
| n = 99999
t = n
while t // 10 != 0:
x = t
sum = 0
while x != 0:
sum += x % 10
x = x // 10
t = sum
print(sum) |
"""
persistor base class
"""
class PersistorBase():
def __init__(self):
pass
def write(self, feature, dumps, **kwargs):
raise NotImplementedError("Persistor write method implementation error!")
def read(self, uid, **kwargs):
raise NotImplementedError("Persistor read method... | """
persistor base class
"""
class Persistorbase:
def __init__(self):
pass
def write(self, feature, dumps, **kwargs):
raise not_implemented_error('Persistor write method implementation error!')
def read(self, uid, **kwargs):
raise not_implemented_error('Persistor read method ... |
def sum_odd_numbers(numbers):
total = 0
odd_numbers = [num for num in numbers if num % 2 == 0]
for num in odd_numbers:
total += num
return total
sum_odd_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9])
| def sum_odd_numbers(numbers):
total = 0
odd_numbers = [num for num in numbers if num % 2 == 0]
for num in odd_numbers:
total += num
return total
sum_odd_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9]) |
# 247. Strobogrammatic Number II
# ttungl@gmail.com
# A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
# Find all strobogrammatic numbers that are of length = n.
# For example,
# Given n = 2, return ["11","69","88","96"].
class Solution(object):
# s... | class Solution(object):
def __init__(self):
self.maps = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
def find_strobogrammatic(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
c = ['#'] * n
self.dfs(c, 0, n - 1, res)
return ... |
# Copyright 2000-2002 by Andrew Dalke.
# Revisions copyright 2007-2010 by Peter Cock.
# All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included ... | """Alphabets were previously used to declare sequence type and letters (OBSOLETE).
The design of Bio.Aphabet included a number of historic design choices
which, with the benefit of hindsight, were regretable. Bio.Alphabet was
therefore removed from Biopython in release 1.78. Instead, the molecule type is
included as a... |
# Tot's reward lv 20
sm.completeQuest(5519)
# Lv. 20 Equipment box
sm.giveItem(2431876, 1)
sm.dispose()
| sm.completeQuest(5519)
sm.giveItem(2431876, 1)
sm.dispose() |
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
l = -1
r = len(arr)
while l < r - 1:
m = (l + r) >> 1
if arr[m - 1] < arr[m] and arr[m] > arr[m + 1]:
return m
elif arr[m - 1] < arr[m]:
l = m
... | class Solution:
def peak_index_in_mountain_array(self, arr: List[int]) -> int:
l = -1
r = len(arr)
while l < r - 1:
m = l + r >> 1
if arr[m - 1] < arr[m] and arr[m] > arr[m + 1]:
return m
elif arr[m - 1] < arr[m]:
l = m
... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
IGNORED_FILE_PREFIXES = ["."]
IGNORED_FILE_SUFFIXES = ["~", ".swp"]
IGNORED_DIRS = [".git", ".svn", ".hg"]
def filter_... | ignored_file_prefixes = ['.']
ignored_file_suffixes = ['~', '.swp']
ignored_dirs = ['.git', '.svn', '.hg']
def filter_filenames(filenames, ignored_files=['.hgignore']):
for filename in filenames:
if filename in ignored_files:
continue
if any([filename.startswith(suffix) for suffix in IG... |
# CHANGEME
w = str(input("Pattern: "))
S = str(input("Search string (s): "))
B = {}
or_mask = [0]*len(w)
or_mask[len(w)-1] = 1
D = [0]*len(w)
done = []
for i in list(set(w)):
tmp = [0]*len(w)
for pos in [pos for pos, char in enumerate(w) if char == i]:
tmp[len(w)-pos-1] = 1
B[i] = tmp
for c in w... | w = str(input('Pattern: '))
s = str(input('Search string (s): '))
b = {}
or_mask = [0] * len(w)
or_mask[len(w) - 1] = 1
d = [0] * len(w)
done = []
for i in list(set(w)):
tmp = [0] * len(w)
for pos in [pos for (pos, char) in enumerate(w) if char == i]:
tmp[len(w) - pos - 1] = 1
B[i] = tmp
for c in w:... |
"""
A set of common vocabularies used in MIDAS queries.
"""
UK_COUNTIES = """ABERDEENSHIRE,ALDERNEY,ANGUS,ANTRIM,ARGYLL (IN HIGHLAND REGION),
ARGYLL (IN STRATHCLYDE REGION),ARGYLLSHIRE,ARMAGH,ASCENSION IS,
AUSTRALIA (ADDITIONAL ISLANDS),AVON,AYRSHIRE,BANFFSHIRE,BEDFORDSHIRE,
BERKSHIRE,BERWICKSHIRE,BORDERS,BOU... | """
A set of common vocabularies used in MIDAS queries.
"""
uk_counties = 'ABERDEENSHIRE,ALDERNEY,ANGUS,ANTRIM,ARGYLL (IN HIGHLAND REGION),\nARGYLL (IN STRATHCLYDE REGION),ARGYLLSHIRE,ARMAGH,ASCENSION IS,\nAUSTRALIA (ADDITIONAL ISLANDS),AVON,AYRSHIRE,BANFFSHIRE,BEDFORDSHIRE,\nBERKSHIRE,BERWICKSHIRE,BORDERS,BOUVET ISLA... |
# -*- coding: utf-8 -*-
"""
smash.models.encryption_model_response
This file was automatically generated for SMASH by SMASH v2.0 ( https://smashlabs.io )
"""
class EncryptionModelResponse(object):
"""Implementation of the 'Encryption Model Response' model.
TODO: type model description here.
A... | """
smash.models.encryption_model_response
This file was automatically generated for SMASH by SMASH v2.0 ( https://smashlabs.io )
"""
class Encryptionmodelresponse(object):
"""Implementation of the 'Encryption Model Response' model.
TODO: type model description here.
Attributes:
data (st... |
N, M = list(map(int, input().split()))
grid = [['@' for x in range(M)] for y in range(N)]
for i in range(N):
line = input()
for j in range(M):
grid[i][j] = line[j]
alreadySeen = False
jr = jc = -1
for i in range(N):
if alreadySeen:
break
for j in range(M):
if (alreadySeen):
... | (n, m) = list(map(int, input().split()))
grid = [['@' for x in range(M)] for y in range(N)]
for i in range(N):
line = input()
for j in range(M):
grid[i][j] = line[j]
already_seen = False
jr = jc = -1
for i in range(N):
if alreadySeen:
break
for j in range(M):
if alreadySeen:
... |
'''
Author : MiKueen
Level : Hard
Problem Statement : Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
... | """
Author : MiKueen
Level : Hard
Problem Statement : Median of Two Sorted Arrays
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
... |
# -*- coding: utf-8 -*-
class JoinMixin(object):
"""Provide join related functionality to statement classes.
Note:
This class is not to be instantiated directly.
"""
def __init__(self, **kwargs):
"""Constructor
Keyword Arguments:
**kwargs: Base class arguments.
... | class Joinmixin(object):
"""Provide join related functionality to statement classes.
Note:
This class is not to be instantiated directly.
"""
def __init__(self, **kwargs):
"""Constructor
Keyword Arguments:
**kwargs: Base class arguments.
"""
super(J... |
def main():
# Ask for the user's weight in pounds.
weight = int(input('Please enter your weight in pounds: '))
# Ask for the user's height in inches.
height = int(input('Please enter your height in inches: '))
# Calculate the BMI (BMI = weight*703/height^2)
BMI = (weight * 703.0) / (height*hei... | def main():
weight = int(input('Please enter your weight in pounds: '))
height = int(input('Please enter your height in inches: '))
bmi = weight * 703.0 / (height * height)
print('Your BMI is %.1f' % BMI)
if BMI < 18.5:
print('You are underweight.')
elif BMI > 25:
print('It would... |
class Employee:
def __init__(self, name, ID, department, job_title):
self.__name = name
self.__id = ID
self.__department = department
self.__job_title = job_title
def set_name(self, name):
self.__name = name
def set_id(self, ID):
self.__id = ID
def ... | class Employee:
def __init__(self, name, ID, department, job_title):
self.__name = name
self.__id = ID
self.__department = department
self.__job_title = job_title
def set_name(self, name):
self.__name = name
def set_id(self, ID):
self.__id = ID
def set... |
def selecao_em_vetor():
vetor = list()
for i in range(100):
vetor.append(float(input()))
for j in range(100):
if vetor[j] <= 10.0:
print(f'A[{j}] = {vetor[j]:.1f}')
selecao_em_vetor()
| def selecao_em_vetor():
vetor = list()
for i in range(100):
vetor.append(float(input()))
for j in range(100):
if vetor[j] <= 10.0:
print(f'A[{j}] = {vetor[j]:.1f}')
selecao_em_vetor() |
def pythoagorialTripletSum(sum1):
if sum == 0:
return 0
for i in range(1, int(sum1/3)+1):
for j in range(i +1, int(sum1/2) + 1):
k = sum1 - i - j
if (i * i + j *j == k * k):
print(i, j, k, end = " ")
return
print("No Triplet... | def pythoagorial_triplet_sum(sum1):
if sum == 0:
return 0
for i in range(1, int(sum1 / 3) + 1):
for j in range(i + 1, int(sum1 / 2) + 1):
k = sum1 - i - j
if i * i + j * j == k * k:
print(i, j, k, end=' ')
return
print('No Triplets')
... |
class Scene:
def __init__(self, name = ""):
#print("new Scene Object created")
self.srcs = [] #all sources with visible state of this scene, including srcs from nested scenes
self.scenes = [] #list of all nested scenes
self.name = name
| class Scene:
def __init__(self, name=''):
self.srcs = []
self.scenes = []
self.name = name |
with open("dane/liczby.txt") as f:
lines = [l.strip() for l in f.readlines()]
wynik42 = open("wynik42.txt", "w")
div_2 = 0
div_8 = 0
for line in lines:
if line[-1] == "0":
div_2 += 1
if line[-1] == "0" and line[-2] == "0" and line[-3] == "0":
div_8 += 1
wynik42.write(f"zadanie 4.2: {div... | with open('dane/liczby.txt') as f:
lines = [l.strip() for l in f.readlines()]
wynik42 = open('wynik42.txt', 'w')
div_2 = 0
div_8 = 0
for line in lines:
if line[-1] == '0':
div_2 += 1
if line[-1] == '0' and line[-2] == '0' and (line[-3] == '0'):
div_8 += 1
wynik42.write(f'zadanie 4.2: {div_2}... |
st = ['id', 'pwd', 'name', 'age']
data = ['id01', 'pwd01', 'james', 30]
cust = zip(st,data)
print(cust)
for s,d in cust:
print('%s : %s' % (s,d))
dic_cust = dict(zip(st,data))
print(dic_cust) | st = ['id', 'pwd', 'name', 'age']
data = ['id01', 'pwd01', 'james', 30]
cust = zip(st, data)
print(cust)
for (s, d) in cust:
print('%s : %s' % (s, d))
dic_cust = dict(zip(st, data))
print(dic_cust) |
### Quicksort 1 - Partition - Solution
def quickSort(arr):
pivotNum = arr[0]
for i in range(1, len(arr)):
if pivotNum > arr[i]:
for j in range(i, 0, -1):
temp = arr[j]
arr[j] = arr[j-1]
arr[j-1] = temp
print(*arr)
n = int(input())
arr = l... | def quick_sort(arr):
pivot_num = arr[0]
for i in range(1, len(arr)):
if pivotNum > arr[i]:
for j in range(i, 0, -1):
temp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = temp
print(*arr)
n = int(input())
arr = list(map(int, input().split()[:n]))
... |
atuple = 'dev', "tst", '''acc''', """prd """
print(atuple,type(atuple),id(atuple), len(atuple))
| atuple = ('dev', 'tst', 'acc', 'prd ')
print(atuple, type(atuple), id(atuple), len(atuple)) |
# 2021-01-30
# Emma Benjaminson
# Quick Sort Implementation
# Source: https://www.educative.io/edpresso/how-to-implement-quicksort-in-python
def QuickSort(arr):
elements = len(arr)
# base case
if elements < 2:
return arr
current_position = 0 # position of the partitioning element
# part... | def quick_sort(arr):
elements = len(arr)
if elements < 2:
return arr
current_position = 0
for i in range(1, elements):
if arr[i] <= arr[0]:
current_position += 1
temp = arr[i]
arr[i] = arr[current_position]
arr[current_position] = temp
... |
#
# PySNMP MIB module HPR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:30:23 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:15)... | (sna_control_point_name,) = mibBuilder.importSymbols('APPN-MIB', 'SnaControlPointName')
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraint... |
def get_binary_rep(data, spacing=0, separator=" "):
format(i,'b').zfill(8)
def bin_rep_string_arr(data):
map()
return []
def bin_rep_int_arr(data):
return []
def bin_rep_unicode_arr(data):
return []
def bin_rep_bytes_arr(data):
return []
def hex_rep_string_arr(data):
return []
d... | def get_binary_rep(data, spacing=0, separator=' '):
format(i, 'b').zfill(8)
def bin_rep_string_arr(data):
map()
return []
def bin_rep_int_arr(data):
return []
def bin_rep_unicode_arr(data):
return []
def bin_rep_bytes_arr(data):
return []
def hex_rep_string_arr(data):
return []
def hex... |
# Accessing tuple elements using slicing
my_tuple = ('p','r','o','g','r','a','m','i','n','g')
# elements 2nd to 4th
print(my_tuple[1:4])
# elements beginning to 4nd
print(my_tuple[:-7])
# elements 8th to end
print(my_tuple[7:])
# elements beginning to end
print(my_tuple[:])
| my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'n', 'g')
print(my_tuple[1:4])
print(my_tuple[:-7])
print(my_tuple[7:])
print(my_tuple[:]) |
image_width = 400
image_height = 400
prediction_size = 8
batch_size = 10
noise_ratio = 0.1 | image_width = 400
image_height = 400
prediction_size = 8
batch_size = 10
noise_ratio = 0.1 |
#
# PySNMP MIB module ALTEON-CHEETAH-NETWORK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALTEON-CHEETAH-NETWORK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:05:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... | (aws_switch,) = mibBuilder.importSymbols('ALTEON-ROOT-MIB', 'aws-switch')
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constrai... |
#
# PySNMP MIB module PDN-IFDEV-IWF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-IFDEV-IWF-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:30:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
n = int(input())/10e2
if 0.1 > n:
print("00")
elif 5 >= n:
if len(str(int(n*10))) == 1:
print("0{}".format(int(n*10)))
else:
print(int(n*10))
elif 30 >= n:
print(int(n)+50)
elif 70 >= n:
print((int(n) - 30)//5 + 80)
else:
print(89)
| n = int(input()) / 1000.0
if 0.1 > n:
print('00')
elif 5 >= n:
if len(str(int(n * 10))) == 1:
print('0{}'.format(int(n * 10)))
else:
print(int(n * 10))
elif 30 >= n:
print(int(n) + 50)
elif 70 >= n:
print((int(n) - 30) // 5 + 80)
else:
print(89) |
# Gareth Duffy 2-3-2018
# example of for loop using range function as iterator
# for loops are definite iterators compared to e.g. while loops (indefinite)
for i in range(1, 99, 2): # change range to experiment (third value is the 'step')
print(i, end=' ') # end prints all on one line instead of separate lines
| for i in range(1, 99, 2):
print(i, end=' ') |
fairumei = "alphabet.java"
henkou = fairumei.split(".")
print(henkou[-1])
| fairumei = 'alphabet.java'
henkou = fairumei.split('.')
print(henkou[-1]) |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"boto3_available": "00_utils.ipynb",
"setStockDataRoot": "00_utils.ipynb",
"stockDataRoot": "00_utils.ipynb",
"requestUrl": "00_utils.ipynb",
"setSecUserAgent": "00_utils.i... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'boto3_available': '00_utils.ipynb', 'setStockDataRoot': '00_utils.ipynb', 'stockDataRoot': '00_utils.ipynb', 'requestUrl': '00_utils.ipynb', 'setSecUserAgent': '00_utils.ipynb', 'secIndexUrl': '00_utils.ipynb', 'appendSpace': '00_utils.ipynb', 'get... |
# ============================================
# Global Constants
# ============================================
# Shared variables
PUZZLE_ROWS = 9 # Number of rows on the board.
PUZZLE_COLUMNS = 9 # Number of columns on the board.
# Game variables
LEVEL_1_TOTAL_MEDALS = 3
LEVEL_2_TOTAL_MEDALS = 4
LEVEL_3_TOTAL_MED... | puzzle_rows = 9
puzzle_columns = 9
level_1_total_medals = 3
level_2_total_medals = 4
level_3_total_medals = 5
score = 0
moves_left = 20
gem_types = 6
bonus_types = 3
ice_rows = 5
ice_layers = 1
random_seed = None
hd_scale = 1.5
base_cell_size = 30
gem_ratio = 0.9
base_margin = 70
base_text_area = 75
animation_scale = 1... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if root is None:
return 0
... | class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
if root is None:
return 0
self.max_dist = 0
self.helper(root)
return self.max_dist - 1
def helper(self, root):
if root is None:
return 0
l = self.helper(root.left)
... |
""" Error classes for USGS Paremeter Codes"""
class Error(Exception):
"""Base class for other exceptions"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class AlreadyExistsError(Error):
"""Raises an error when data already exists"""
def __init__(self, *arg... | """ Error classes for USGS Paremeter Codes"""
class Error(Exception):
"""Base class for other exceptions"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
class Alreadyexistserror(Error):
"""Raises an error when data already exists"""
def __init__(self, *args,... |
class Dataset():
def __init__(self, train_images, test_images, train_labels, test_labels, emotion_index_map, time_delay=None):
self._train_images = train_images
self._test_images = test_images
self._train_labels = train_labels
self._test_labels = test_labels
self._emotion_i... | class Dataset:
def __init__(self, train_images, test_images, train_labels, test_labels, emotion_index_map, time_delay=None):
self._train_images = train_images
self._test_images = test_images
self._train_labels = train_labels
self._test_labels = test_labels
self._emotion_inde... |
"""
port
part of hwpy: an OO hardware interface library
home: https://www.github.com/wovo/hwpy
"""
class port:
"""A port is a set of pins.
port.n is the number of pins.
port.pins are the pins themselves.
"""
def __init__( self, pins ):
"""Create a port from a list of pins.
"""
... | """
port
part of hwpy: an OO hardware interface library
home: https://www.github.com/wovo/hwpy
"""
class Port:
"""A port is a set of pins.
port.n is the number of pins.
port.pins are the pins themselves.
"""
def __init__(self, pins):
"""Create a port from a list of pins.
"""
... |
__author__ = 'alvertisjo'
recommenderSE='http://snf-561492.vm.okeanos.grnet.gr:8080/recommender-se/rest/recommender/'
recommnederProductCategories=['Home Appliances', 'Electrical Supplies', 'Kitchen Merchandise', 'Pet Care - Food', 'Clothing', 'Sports Equipment', 'Healthcare', 'Communications', 'Lubricants', 'Audio Vi... | __author__ = 'alvertisjo'
recommender_se = 'http://snf-561492.vm.okeanos.grnet.gr:8080/recommender-se/rest/recommender/'
recommneder_product_categories = ['Home Appliances', 'Electrical Supplies', 'Kitchen Merchandise', 'Pet Care - Food', 'Clothing', 'Sports Equipment', 'Healthcare', 'Communications', 'Lubricants', 'Au... |
"""Probabilistic linear solvers.
Iterative probabilistic numerical methods solving linear systems :math:`Ax = b`.
"""
class ProbabilisticLinearSolver:
r"""Compose a custom probabilistic linear solver.
Class implementing probabilistic linear solvers. Such (iterative) solvers infer
solutions to problems o... | """Probabilistic linear solvers.
Iterative probabilistic numerical methods solving linear systems :math:`Ax = b`.
"""
class Probabilisticlinearsolver:
"""Compose a custom probabilistic linear solver.
Class implementing probabilistic linear solvers. Such (iterative) solvers infer
solutions to problems of ... |
# Python program showing no need to
# use global keyword for accessing
# a global value
# global variable
a = 15
b = 10
# function to perform addition
def add():
c = a + b
print(c)
# calling a function
add()
| a = 15
b = 10
def add():
c = a + b
print(c)
add() |
def test():
for i in xrange(1):
t = ''
for j in xrange(int(1e5)):
t += 'x'
#print(len(t))
test()
| def test():
for i in xrange(1):
t = ''
for j in xrange(int(100000.0)):
t += 'x'
test() |
"""
Copyright (c) 2009 Charles E. R. Wegrzyn
All Right Reserved.
chuck.wegrzyn at gmail.com
This application is free software and subject to the Version 1.0
of the Common Public Attribution License.
"""
| """
Copyright (c) 2009 Charles E. R. Wegrzyn
All Right Reserved.
chuck.wegrzyn at gmail.com
This application is free software and subject to the Version 1.0
of the Common Public Attribution License.
""" |
def miniPeaks(nums):
result = []
left = 0
right = 0
for i in range(1, len(nums) - 1):
left = nums[i - 1]
right = nums[i + 1]
if nums[i] > left and nums[i] > right:
result.append(nums[i])
return result
# Time Complexity : O(n)
# Space Co... | def mini_peaks(nums):
result = []
left = 0
right = 0
for i in range(1, len(nums) - 1):
left = nums[i - 1]
right = nums[i + 1]
if nums[i] > left and nums[i] > right:
result.append(nums[i])
return result |
#!/usr/bin/env python
__author__ = "Aditya Pahuja"
__copyright__ = "Copyright (c) 2020"
__maintainer__ = "Aditya Pahuja"
__email__ = "aditya.s.pahuja@gmail.com"
__status__ = "Production"
class Window:
def __init__(self, start_date, stop_date):
self.start_date = start_date
self.stop_date = stop_d... | __author__ = 'Aditya Pahuja'
__copyright__ = 'Copyright (c) 2020'
__maintainer__ = 'Aditya Pahuja'
__email__ = 'aditya.s.pahuja@gmail.com'
__status__ = 'Production'
class Window:
def __init__(self, start_date, stop_date):
self.start_date = start_date
self.stop_date = stop_date |
#!/usr/bin/python
def modular_helper(base, exponent, modulus, prefactor=1):
c = 1
for k in range(exponent):
c = (c * base) % modulus
return ((prefactor % modulus) * c) % modulus
def fibN(n):
phi = (1 + 5 ** 0.5) / 2
return int(phi ** n / 5 ** 0.5 + 0.5)
# Alternate problem solutions start... | def modular_helper(base, exponent, modulus, prefactor=1):
c = 1
for k in range(exponent):
c = c * base % modulus
return prefactor % modulus * c % modulus
def fib_n(n):
phi = (1 + 5 ** 0.5) / 2
return int(phi ** n / 5 ** 0.5 + 0.5)
def problem0012a():
p = primes(1000)
(n, dn, cnt) =... |
# List of lists, where each inner list corresponds to a bubble
class ListSet:
def __init__(self, N):
self.N = N
self._bubbles = []
for i in range(N):
self._bubbles.append({i})
def get_set_label(self, i):
"""
Return a number that is the same for every elem... | class Listset:
def __init__(self, N):
self.N = N
self._bubbles = []
for i in range(N):
self._bubbles.append({i})
def get_set_label(self, i):
"""
Return a number that is the same for every element in
the set that i is in, and which is unique to that s... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
... | class Solution(object):
def lowest_common_ancestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
p_list = []
q_list = []
self.computeList(root, p, pList)
self.computeList(root, q, ... |
def is_connected(node1,node2,G):
"""returns True if node1 and node2 are connected in G. Otherwise returns False
Prec:G is a dictionary. node1 and node2 are keys in G"""
to_visit=G[node1]
visit=[node1]
while(to_visit!=[]):
cur_node=to_visit[0]
visit.append(cur_node)
to... | def is_connected(node1, node2, G):
"""returns True if node1 and node2 are connected in G. Otherwise returns False
Prec:G is a dictionary. node1 and node2 are keys in G"""
to_visit = G[node1]
visit = [node1]
while to_visit != []:
cur_node = to_visit[0]
visit.append(cur_node)
t... |
class Vector2D:
def __init__(self, vec: List[List[int]]):
self.v = vec
self.row=0
self.col=0
def next(self) -> int:
if self.hasNext():
val=self.v[self.row][self.col]
self.col+=1
return val
else:
return
... | class Vector2D:
def __init__(self, vec: List[List[int]]):
self.v = vec
self.row = 0
self.col = 0
def next(self) -> int:
if self.hasNext():
val = self.v[self.row][self.col]
self.col += 1
return val
else:
return
def has... |
# Create a dictionary with the roll number, name and marks
# of n students in a class and display the names of students
# who have marks above 75.
n = int(input("Enter number of students: "))
result = {}
for i in range(n):
print("Enter Details of student No.", i+1)
rno = int(input("Roll No: "))
name = inp... | n = int(input('Enter number of students: '))
result = {}
for i in range(n):
print('Enter Details of student No.', i + 1)
rno = int(input('Roll No: '))
name = input('Name: ')
marks = int(input('Marks: '))
result[rno] = [name, marks]
for student in result:
if result[student][1] > 75:
print... |
def abs(x: str) -> float:
return x if x > 0 else -x
# print(abs(10))
# print(abs(-10))
x = set()
# print(type(x))
x.add(10)
x.add(10)
x.add(10)
# print(x)
# print(len(x))
# print([ord(character) for character in input()])
# print(x.__repr__())
# var = map(int, input().split())
# print(var)
n = int(input())
... | def abs(x: str) -> float:
return x if x > 0 else -x
x = set()
x.add(10)
x.add(10)
x.add(10)
n = int(input())
print(sum((x ** 2 for x in range(1, n + 1)))) |
first_number = 500 / 100 + 50 + 45
second_number = 250 - 50
print(first_number)
print(second_number)
total = first_number + second_number
print(total)
| first_number = 500 / 100 + 50 + 45
second_number = 250 - 50
print(first_number)
print(second_number)
total = first_number + second_number
print(total) |
CORE_URL = "https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/consultas/dados-publicos-cnpj"
CORE_URL_FILES = "http://200.152.38.155/CNPJ"
CNAE_JSON_NAME = 'cnaes.json'
NATJU_JSON_NAME = 'natju.json'
QUAL_SOCIO_JSON_NAME = 'qual_socio.json'
MOTIVOS_JSON_NAME = 'motivos.json'
PAIS_JS... | core_url = 'https://www.gov.br/receitafederal/pt-br/assuntos/orientacao-tributaria/cadastros/consultas/dados-publicos-cnpj'
core_url_files = 'http://200.152.38.155/CNPJ'
cnae_json_name = 'cnaes.json'
natju_json_name = 'natju.json'
qual_socio_json_name = 'qual_socio.json'
motivos_json_name = 'motivos.json'
pais_json_nam... |
CLIENT_LOCK_QUEUE_REQUEST_TIME_OUT = 30000
CLIENT_UNLOCK_QUEUE_REQUEST_TIME_OUT = 30000
CLIENT_DEFAULT_DECLARE_QUEUES_REQUEST_TIME_OUT = 30000
CLIENT_DEFAULT_DECLARE_QUEUE_REQUEST_TIME_OUT = 30000
CLIENT_DEFAULT_DECLARE_EXCHANGES_REQUEST_TIME_OUT = 30000
CLIENT_DEFAULT_DECLARE_EXCHANGE_REQUEST_TIME_OUT = 30000
CLIENT_D... | client_lock_queue_request_time_out = 30000
client_unlock_queue_request_time_out = 30000
client_default_declare_queues_request_time_out = 30000
client_default_declare_queue_request_time_out = 30000
client_default_declare_exchanges_request_time_out = 30000
client_default_declare_exchange_request_time_out = 30000
client_d... |
# Sometimes methods take arguments.
# Try changing the argument passed to lpad.
# Then try some whole different methods...
catcher = 'Joyce'
print(third_batter.lpad(10))
print(third_batter.startswith('M'))
print(third_batter.endswith(''))
| catcher = 'Joyce'
print(third_batter.lpad(10))
print(third_batter.startswith('M'))
print(third_batter.endswith('')) |
count_shiny_gold_bag = 0
rules = {}
with open("input.txt", "r") as f:
lines = [line.rstrip() for line in f.readlines()]
answered_yes_group = []
for line in lines:
line = line.split(" bags contain ")
line[1] = line[1].split(",")
bags = []
for bag in line[1]:
bag ... | count_shiny_gold_bag = 0
rules = {}
with open('input.txt', 'r') as f:
lines = [line.rstrip() for line in f.readlines()]
answered_yes_group = []
for line in lines:
line = line.split(' bags contain ')
line[1] = line[1].split(',')
bags = []
for bag in line[1]:
bag = ... |
class ParserInterface():
def open(self):
pass
def get_data(self):
pass
def close(self):
pass
| class Parserinterface:
def open(self):
pass
def get_data(self):
pass
def close(self):
pass |
# Number of bromine atoms in each species
cfc11 = 0
cfc12 = 0
cfc113 = 0
cfc114 = 0
cfc115 = 0
carb_tet = 0
mcf = 0
hcfc22 = 0
hcfc141b = 0
hcfc142b = 0
halon1211 = 1
halon1202 = 2
halon1301 = 1
halon2402 = 2
ch3br = 1
ch3cl = 0
aslist = [cfc11, cfc12, cfc113, cfc114, cfc115, ca... | cfc11 = 0
cfc12 = 0
cfc113 = 0
cfc114 = 0
cfc115 = 0
carb_tet = 0
mcf = 0
hcfc22 = 0
hcfc141b = 0
hcfc142b = 0
halon1211 = 1
halon1202 = 2
halon1301 = 1
halon2402 = 2
ch3br = 1
ch3cl = 0
aslist = [cfc11, cfc12, cfc113, cfc114, cfc115, carb_tet, mcf, hcfc22, hcfc141b, hcfc142b, halon1211, halon1202, halon1301, halon2402... |
class S:
ASSETS_PATH = "assets/"
WINDOW_SIZE = (432, 768)
@staticmethod
def save_sprite(name, image):
name = name.upper()
if not hasattr(S, name):
setattr(S, name, image)
setattr(S, name + "_RECT", image.get_rect())
| class S:
assets_path = 'assets/'
window_size = (432, 768)
@staticmethod
def save_sprite(name, image):
name = name.upper()
if not hasattr(S, name):
setattr(S, name, image)
setattr(S, name + '_RECT', image.get_rect()) |
#!/usr/bin/env python
count = 3
list1 = []
while count > 0:
num = int(input(">>> "))
list1.append(num)
count -= 1
list1.sort()
print(list1)
| count = 3
list1 = []
while count > 0:
num = int(input('>>> '))
list1.append(num)
count -= 1
list1.sort()
print(list1) |
def Fun():
pass
class A:
def __init__(self):
pass
def Fun(self):
pass
try:
print(Fun.__name__)
print(A.__init__.__name__)
print(A.Fun.__name__)
print(A().Fun.__name__)
except AttributeError:
print('SKIP')
| def fun():
pass
class A:
def __init__(self):
pass
def fun(self):
pass
try:
print(Fun.__name__)
print(A.__init__.__name__)
print(A.Fun.__name__)
print(a().Fun.__name__)
except AttributeError:
print('SKIP') |
a = input()
d = {'A':0,'B':0}
for i in range(0,len(a),2):
d[a[i]] += int(a[i+1])
if d['A'] > d['B']:
print("A")
else:
print("B") | a = input()
d = {'A': 0, 'B': 0}
for i in range(0, len(a), 2):
d[a[i]] += int(a[i + 1])
if d['A'] > d['B']:
print('A')
else:
print('B') |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... | @auth.requires_membership('admins')
def manage_author():
mydb.author.image.represent = lambda image, row: img(_src=url('admin', 'download', args=image), _class='author_image', _width='50px', _onclick='$("#image_container").attr("src","' + url('admin', 'download', args=image) + '");document.getElementById("text_cont... |
# Leetcode 94. Binary Tree Inorder Traversal
#
# Link: https://leetcode.com/problems/binary-tree-inorder-traversal/
# Difficulty: Easy
# Complexity:
# O(N) time | where N represent the number of nodes in the tree
# O(N) space | where N represent the number of nodes in the tree
# Definition for a binary tree node.
... | class Solution:
def inorder_traversal(self, root: Optional[TreeNode]) -> List[int]:
def recursive(root):
if not root:
return []
return recursive(root.left) + [root.val] + recursive(root.right)
def iterative(root):
stack = []
result =... |
"""
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge
is a pair of nodes), write a function to find the number of connected components
in an undirected graph.
Example 1:
0 3
| |
1 --- 2 4
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], retur... | """
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge
is a pair of nodes), write a function to find the number of connected components
in an undirected graph.
Example 1:
0 3
| |
1 --- 2 4
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], retur... |
def median(L):
L.sort()
return L[len(L) // 2]
if __name__ == "__main__":
L = [10, 17, 25, 1, 4, 15, 6]
print(median(L)) | def median(L):
L.sort()
return L[len(L) // 2]
if __name__ == '__main__':
l = [10, 17, 25, 1, 4, 15, 6]
print(median(L)) |
def greet(bot_name, birth_year):
print('Hello! My name is ' + bot_name + '.')
print('I was created in ' + birth_year + '.')
def remind_name():
print('Please, remind me your name.')
name = input()
print('What a great name you have, ' + name + '!')
def guess_age():
# Remainders are the remains... | def greet(bot_name, birth_year):
print('Hello! My name is ' + bot_name + '.')
print('I was created in ' + birth_year + '.')
def remind_name():
print('Please, remind me your name.')
name = input()
print('What a great name you have, ' + name + '!')
def guess_age():
remainder3 = int(input('Enter ... |
self.description = "Install packages with huge descriptions"
p1 = pmpkg("pkg1")
p1.desc = 'A' * 500 * 1024
self.addpkg(p1)
p2 = pmpkg("pkg2")
p2.desc = 'A' * 600 * 1024
self.addpkg(p2)
self.args = "-U %s %s" % (p1.filename(), p2.filename())
# We error out when fed a package with an invalid description; the second o... | self.description = 'Install packages with huge descriptions'
p1 = pmpkg('pkg1')
p1.desc = 'A' * 500 * 1024
self.addpkg(p1)
p2 = pmpkg('pkg2')
p2.desc = 'A' * 600 * 1024
self.addpkg(p2)
self.args = '-U %s %s' % (p1.filename(), p2.filename())
self.addrule('PACMAN_RETCODE=1')
self.addrule('!PKG_EXIST=pkg1')
self.addrule('... |
# 99 Days of Code - Sung to the tune of "99 bottles of beer"
x = 99
z = 1
while x > 1:
y = x - 1
print(x , "days of code to complete,", x, "days of code.")
print("Commit to win,then start again", y, "days of code to complete...")
print()
x = x - 1
if x == 1:
print("1 day of code to complete,",... | x = 99
z = 1
while x > 1:
y = x - 1
print(x, 'days of code to complete,', x, 'days of code.')
print('Commit to win,then start again', y, 'days of code to complete...')
print()
x = x - 1
if x == 1:
print('1 day of code to complete,', '1 day of code')
print('It wont be long so finish off stron... |
def dist(X, m):
S = 0
for x in X:
S += abs(x - m)
return S
T = int(input())
for ti in range(T):
N, M, F = map(int, input().split())
X = []
Y = []
for fi in range(F):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
X = sorted(X)
Y = sorted(Y)
F = 2
if F & 1:
xx = str(... | def dist(X, m):
s = 0
for x in X:
s += abs(x - m)
return S
t = int(input())
for ti in range(T):
(n, m, f) = map(int, input().split())
x = []
y = []
for fi in range(F):
(x, y) = map(int, input().split())
X.append(x)
Y.append(y)
x = sorted(X)
y = sorted(... |
# When squirrels get together for a party, they like to have acorns. A squirrel party is successful when the number of acorns is between 40 and 60, inclusively. During the weekends, there is no need for acorns. The party is always fun.
# input
num_acorns = int(input('Enter the number of acorns: '))
is_weekend = input... | num_acorns = int(input('Enter the number of acorns: '))
is_weekend = input('Is it the weekend? (Y/N): ')
if is_weekend == 'Y':
print('The party was a success.')
elif num_acorns >= 40 and num_acorns <= 60:
print('The party was a success.')
else:
print(':(') |
"""Supported Versions class."""
class SupportedVersions:
"""Container for all supported versions by the ONYX.CENTER."""
def __init__(self, versions: list):
"""Initialize the versions."""
self.versions = versions
def supports(self, version: str) -> bool:
"""Check if the provided v... | """Supported Versions class."""
class Supportedversions:
"""Container for all supported versions by the ONYX.CENTER."""
def __init__(self, versions: list):
"""Initialize the versions."""
self.versions = versions
def supports(self, version: str) -> bool:
"""Check if the provided ve... |
class Report(object):
""" Parent class for all reports """
__slots__ = (
'stats',
'start',
'end',
)
def __init__(self, start, end):
self.start = start
self.end = end
def render(self, output):
""" Render the report to the specified output file """
... | class Report(object):
""" Parent class for all reports """
__slots__ = ('stats', 'start', 'end')
def __init__(self, start, end):
self.start = start
self.end = end
def render(self, output):
""" Render the report to the specified output file """
raise not_implemented_erro... |
# MIN-MAX HACKER EARTH
n = int(input())
arr = str(input())
arr = arr.split()
arr1 = []
for i in range(0,n,1):
x = int(arr[i])
arr1 += [x]
min_arr = min(arr1)
max_arr = max(arr1)
count = 0
for i in range(min_arr+1,max_arr,1):
num = i
for j in range(0,n,1):
if num == arr1[j]:
... | n = int(input())
arr = str(input())
arr = arr.split()
arr1 = []
for i in range(0, n, 1):
x = int(arr[i])
arr1 += [x]
min_arr = min(arr1)
max_arr = max(arr1)
count = 0
for i in range(min_arr + 1, max_arr, 1):
num = i
for j in range(0, n, 1):
if num == arr1[j]:
count = count + 1
... |
#
# Collective Knowledge (MLPerf inference benchmark submitter)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, http://fursin.net
#
cfg = {} # Will be updated by CK (meta description of this module)
work = {} # Will be updated by CK (temporal d... | cfg = {}
work = {}
ck = None
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return': 0} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.