content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
CR_ATTACHMENT_AVAILABLE = 'cr_available'
CR_ATTACHMENT_REQUEST = 'cr_request'
TRR_ATTACHMENT_AVAILABLE = 'trr_available'
TRR_ATTACHMENT_REQUEST = 'trr_request'
ATTACHMENT_TYPE_CHOICES = [
[CR_ATTACHMENT_AVAILABLE, 'CR attachment available'],
[CR_ATTACHMENT_REQUEST, 'CR attachment request'],
[TRR_ATTACHMENT_... | cr_attachment_available = 'cr_available'
cr_attachment_request = 'cr_request'
trr_attachment_available = 'trr_available'
trr_attachment_request = 'trr_request'
attachment_type_choices = [[CR_ATTACHMENT_AVAILABLE, 'CR attachment available'], [CR_ATTACHMENT_REQUEST, 'CR attachment request'], [TRR_ATTACHMENT_AVAILABLE, 'T... |
# Description: Sample Code to Run mypy
# Variables without types
i:int = 200
f:float = 2.34
str = "Hello"
# A function without type annotations
def greet(name:str)-> str:
return str + " " + name
if __name__ == '__main__':
greet("Dilbert")
| i: int = 200
f: float = 2.34
str = 'Hello'
def greet(name: str) -> str:
return str + ' ' + name
if __name__ == '__main__':
greet('Dilbert') |
numbers = [1,45,31,12,60]
for number in numbers:
if number % 8 == 0:
# Reject the list
print("The numbers are unacceptable")
break
else:
print("List okay!") | numbers = [1, 45, 31, 12, 60]
for number in numbers:
if number % 8 == 0:
print('The numbers are unacceptable')
break
else:
print('List okay!') |
file = "01.data.txt"
f = open(file)
data = f.read()
f.close()
lines = data.split("\n")
readings = []
for line in lines:
readings.append(int(line))
print(readings)
# count all the increases
# have a counter
counter = 0
# each time number icreases increment the counter
for i in range(1, len(readings)):
pr... | file = '01.data.txt'
f = open(file)
data = f.read()
f.close()
lines = data.split('\n')
readings = []
for line in lines:
readings.append(int(line))
print(readings)
counter = 0
for i in range(1, len(readings)):
previous = readings[i - 1]
current = readings[i]
is_greater = current > previous
if is_grea... |
'''
Machine Learning
* Machine Learning is making the computer learn from studying data and statistics.
* Machine Learning is a step into the direction of artificial intelligence (AI).
* Machine Learning is a program that analyses data and learns to predict the outcome.
Where To Start?
* In this tutorial we will go... | """
Machine Learning
* Machine Learning is making the computer learn from studying data and statistics.
* Machine Learning is a step into the direction of artificial intelligence (AI).
* Machine Learning is a program that analyses data and learns to predict the outcome.
Where To Start?
* In this tutorial we will go... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"expand_dim_to_3": "00_core.ipynb",
"parametric_ellipse": "00_core.ipynb",
"elliplise": "00_core.ipynb",
"EllipticalSeparabilityFilter": "00_core.ipynb"}
modules = ["core.py"]
doc... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'expand_dim_to_3': '00_core.ipynb', 'parametric_ellipse': '00_core.ipynb', 'elliplise': '00_core.ipynb', 'EllipticalSeparabilityFilter': '00_core.ipynb'}
modules = ['core.py']
doc_url = 'https://AtomScott.github.io/circle_finder/'
git_url = 'https:/... |
LOG = []
def flush_log(filename):
with open(filename, 'w') as logfile:
for l in LOG:
logfile.write("%s\n" % l)
def log_message(msg):
LOG.append(msg) | log = []
def flush_log(filename):
with open(filename, 'w') as logfile:
for l in LOG:
logfile.write('%s\n' % l)
def log_message(msg):
LOG.append(msg) |
is_correct = executor_result["is_correct"]
test_feedback = executor_result["test_feedback"]
test_comments = executor_result["test_comments"]
congrats = executor_result["congrats"]
feedback = ""
output = (test_comments + "\n" + test_feedback).strip()
if output == "":
output = "No issues!"
if is_correct:
feedb... | is_correct = executor_result['is_correct']
test_feedback = executor_result['test_feedback']
test_comments = executor_result['test_comments']
congrats = executor_result['congrats']
feedback = ''
output = (test_comments + '\n' + test_feedback).strip()
if output == '':
output = 'No issues!'
if is_correct:
feedback... |
## \file OutputFormat.py
# \author Dong Chen
# \brief Provides the function for writing outputs
## \brief Writes the output values to output.txt
# \param theta dependent variables (rad)
def write_output(theta):
outputfile = open("output.txt", "w")
print("theta = ", end="", file=outputfile)
print(theta, file... | def write_output(theta):
outputfile = open('output.txt', 'w')
print('theta = ', end='', file=outputfile)
print(theta, file=outputfile)
outputfile.close() |
# LevPy: A Python JSON level-loader
# for easier level abstraction
# in text-based py games
# Copyright (c) Finn Lancaster 2021
# Please Keep in mind that the JSONvar name must
# also be the same as the function that
# contains more data on it in LevPy.py
# Valid JSON, names can be anything, with data after the
# ... | jso_nvar = '{"":""}' |
# STACKS, QUEUES & HEAPS
# Stacks
'''
A stack is a last in first out (LIFO) data structure.
- Push an item onto the stack
- Pop an item out of the stack
All push and pop operations are to/from the top of the stack.
The only way to access the bottom items in the stack is to
first remove all items above it
Peek - g... | """
A stack is a last in first out (LIFO) data structure.
- Push an item onto the stack
- Pop an item out of the stack
All push and pop operations are to/from the top of the stack.
The only way to access the bottom items in the stack is to
first remove all items above it
Peek - getting an item on top of the stack... |
SETTINGS = {
'app': {
'schema': 'http://',
'host': 'localhost',
'port': 9000
}
}
| settings = {'app': {'schema': 'http://', 'host': 'localhost', 'port': 9000}} |
__name__ = "python-crud"
__version__ = "0.1.3"
__author__ = "Derek Merck"
__author_email__ = "derek.merck@ufl.edu"
__desc__ = "CRUD endpoint API with Python",
__url__ = "https://github.com/derekmerck/pycrud",
| __name__ = 'python-crud'
__version__ = '0.1.3'
__author__ = 'Derek Merck'
__author_email__ = 'derek.merck@ufl.edu'
__desc__ = ('CRUD endpoint API with Python',)
__url__ = ('https://github.com/derekmerck/pycrud',) |
#!/usr/bin/env python
__author__ = "Kishori M Konwar"
__copyright__ = "Copyright 2013, MetaPathways"
__credits__ = ["r"]
__version__ = "1.0"
__maintainer__ = "Kishori M Konwar"
__status__ = "Release"
exit_code=0
| __author__ = 'Kishori M Konwar'
__copyright__ = 'Copyright 2013, MetaPathways'
__credits__ = ['r']
__version__ = '1.0'
__maintainer__ = 'Kishori M Konwar'
__status__ = 'Release'
exit_code = 0 |
edges = {
(1,'q'):1
}
accepting = [1]
def fsmsim(string, current, edges, accepting):
if string == "":
return current in accepting
else:
letter = string[0]
if (current, letter) in edges:
destination = edges[(current, letter)]
remaining_string = string[1:]
... | edges = {(1, 'q'): 1}
accepting = [1]
def fsmsim(string, current, edges, accepting):
if string == '':
return current in accepting
else:
letter = string[0]
if (current, letter) in edges:
destination = edges[current, letter]
remaining_string = string[1:]
... |
class Solution(object):
def flipAndInvertImage(self, A):
for row in A:
for i in xrange((len(row) + 1) / 2):
# ~ operator (not operator) x*-1-1 <- gets the element on the oposite side
row[i], row[~i] = ~row[~i] ^ 1, row[i] ^ 1
return A
| class Solution(object):
def flip_and_invert_image(self, A):
for row in A:
for i in xrange((len(row) + 1) / 2):
(row[i], row[~i]) = (~row[~i] ^ 1, row[i] ^ 1)
return A |
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = str(first + '.' + last + '@company.com').lower() # see that we don't need to input all the
# attributes. Some of th... | class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = str(first + '.' + last + '@company.com').lower()
Employee.num_of_emps += 1
def fullname(self):
return '... |
numbers_of_electrons = int(input())
electrons = []
cell_number = 1
while numbers_of_electrons > 0:
possible_electrons = 2*cell_number**2
if possible_electrons > numbers_of_electrons:
electrons.append(numbers_of_electrons)
break
electrons.append(possible_electrons)
numbers_of_electrons -... | numbers_of_electrons = int(input())
electrons = []
cell_number = 1
while numbers_of_electrons > 0:
possible_electrons = 2 * cell_number ** 2
if possible_electrons > numbers_of_electrons:
electrons.append(numbers_of_electrons)
break
electrons.append(possible_electrons)
numbers_of_electron... |
# Jerry Landeros
def userInput():
number = int(input("Please enter a number: "))
return number
def primeChecker(number):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
print(number, "is not a prime number.")
break
else:
... | def user_input():
number = int(input('Please enter a number: '))
return number
def prime_checker(number):
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a prime number.')
break
else:
print(number, '... |
_base_ = [
'../_base_/models/deeplabv3_unet_s5-d16.py',
'./dataset.py', '../_base_/default_runtime.py',
'./schedule_20k.py'
]
model = dict(
decode_head=dict(
num_classes=2,loss_decode=dict(
_delete_=True, type='LovaszLoss', loss_weight=1.0, per_image=True)
# type='CrossEn... | _base_ = ['../_base_/models/deeplabv3_unet_s5-d16.py', './dataset.py', '../_base_/default_runtime.py', './schedule_20k.py']
model = dict(decode_head=dict(num_classes=2, loss_decode=dict(_delete_=True, type='LovaszLoss', loss_weight=1.0, per_image=True)), auxiliary_head=dict(num_classes=2, loss_decode=dict(_delete_=True... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n ) :
if ( n == 1 ) :
return True
i = 1
for i in range ( 1 , n ) :
if arr [ i - 1... | def f_gold(arr, n):
if n == 1:
return True
i = 1
for i in range(1, n):
if arr[i - 1] < arr[i]:
if i == n:
return True
j = i
while arr[j] < arr[j - 1]:
if i > 1 and arr[j] < arr[i - 2]:
return False
j += 1
if j == n:
... |
# Maria O Sullivan
# Project Euler 5
# https://projecteuler.net/problem=5
i = 20
while 1:
i+=20
#i remainder 11 equals 0
if i%11==0 and i%12==0 and i%13==0 and i%14==0 and i%15==0\
and i%15==0 and i%16==0 and i%17==0 and i%18==0 and i%19==0:
print(i)
break
... | i = 20
while 1:
i += 20
if i % 11 == 0 and i % 12 == 0 and (i % 13 == 0) and (i % 14 == 0) and (i % 15 == 0) and (i % 15 == 0) and (i % 16 == 0) and (i % 17 == 0) and (i % 18 == 0) and (i % 19 == 0):
print(i)
break |
HTML_CODE_OPEN = "<code>"
HTML_CODE_CLOSE = "</code>"
HTML_NEW_LINE = "\n"
ETH_NULL_ADDRESS = '0x0000000000000000000000000000000000000000'
ETH_WETH_ADDRESS = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
| html_code_open = '<code>'
html_code_close = '</code>'
html_new_line = '\n'
eth_null_address = '0x0000000000000000000000000000000000000000'
eth_weth_address = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' |
question_data = [
{"category": "Science & Nature", "type": "boolean", "difficulty": "medium",
"question": "The Neanderthals were a direct ancestor of modern humans.",
"correct_answer": "False", "incorrect_answers": ["True"]},
{"category": "Science & Nature", "type": "boolean", "difficulty": "medium",
... | question_data = [{'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The Neanderthals were a direct ancestor of modern humans.', 'correct_answer': 'False', 'incorrect_answers': ['True']}, {'category': 'Science & Nature', 'type': 'boolean', 'difficulty': 'medium', 'question': 'The Do... |
# -*- coding: utf-8 -*-
class TrieNode:
def __init__(self):
self.children = {}
self.leaf = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
current = self.root
for char in word:
if char not in current.children:
... | class Trienode:
def __init__(self):
self.children = {}
self.leaf = False
class Trie:
def __init__(self):
self.root = trie_node()
def insert(self, word):
current = self.root
for char in word:
if char not in current.children:
current.chil... |
class ActionRow:
def __init__(self, components: list):
self.base = {"type": 1, "components": [component.base for component in components]}
class SelectMenuOption:
def __init__(self, label: str, value, description: str ='', emoji: dict = {}):
self.base = {"label": label, "description": descripti... | class Actionrow:
def __init__(self, components: list):
self.base = {'type': 1, 'components': [component.base for component in components]}
class Selectmenuoption:
def __init__(self, label: str, value, description: str='', emoji: dict={}):
self.base = {'label': label, 'description': descriptio... |
f_no = 1
s_no = 2
print(f_no)
print(s_no)
result = 2
while True:
t_no = f_no + s_no
if t_no >= 4000000:
break
if t_no % 2 == 0:
result += t_no # result = result + t_no
print(t_no)
f_no = s_no
s_no = t_no
print()
print("Sum of even numbers till 4000000 is ", result) | f_no = 1
s_no = 2
print(f_no)
print(s_no)
result = 2
while True:
t_no = f_no + s_no
if t_no >= 4000000:
break
if t_no % 2 == 0:
result += t_no
print(t_no)
f_no = s_no
s_no = t_no
print()
print('Sum of even numbers till 4000000 is ', result) |
class Bidict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.inverse = {}
for key, value in self.items():
self.inverse.setdefault(value, []).append(key)
def __setitem__(self, key, value):
if key in self:
self.inverse[sel... | class Bidict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.inverse = {}
for (key, value) in self.items():
self.inverse.setdefault(value, []).append(key)
def __setitem__(self, key, value):
if key in self:
self.inverse[... |
L=[]
for i in range(int(input())):
L.append([i+1]+list(map(int,input().split())))
L.sort(key = lambda t : t[3])
L.sort(key = lambda t : t[2])
L.sort(key = lambda t: 700-t[1])
print(L[0][0]) | l = []
for i in range(int(input())):
L.append([i + 1] + list(map(int, input().split())))
L.sort(key=lambda t: t[3])
L.sort(key=lambda t: t[2])
L.sort(key=lambda t: 700 - t[1])
print(L[0][0]) |
# ======================================================================
# Seating System
# Advent of Code 2020 Day 11 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# ===========================... | """A solver for the Advent of Code 2020 Day 11 puzzle"""
floor = '.'
empty = 'L'
occup = '#'
delta = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
class Conway(object):
"""Object for Seating System"""
def __init__(self, text=None, part2=False):
self.part2 = part2
self.... |
#
# PySNMP MIB module BENU-TWAG-STATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-TWAG-STATS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) ... |
class utils:
def __init__(self):
pass
def readFile(self, fileName):
pass
| class Utils:
def __init__(self):
pass
def read_file(self, fileName):
pass |
pole = [1, 2, 5, -1, 3]
maximum = pole[0]
i = 1
while i < len(pole):
maximum = max(maximum, pole[i])
i += 1
print(maximum)
| pole = [1, 2, 5, -1, 3]
maximum = pole[0]
i = 1
while i < len(pole):
maximum = max(maximum, pole[i])
i += 1
print(maximum) |
class Solution:
def findDisappearedNumbers(self, nums):
# since num in nums belongs to [1, len(nums)], we just need loop i from 1 to len(nums) and check if i in nums.
# But the time complexity of checking whether an item in a list is O(n). We need O(1). So make a list to a set.
length = le... | class Solution:
def find_disappeared_numbers(self, nums):
length = len(nums)
nums = set(nums)
return [i for i in range(1, length + 1) if i not in nums]
print(solution().findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1])) |
# declaring random seed
randomseed = 0
C, H, W = 3,112,112
input_resize = 171,128#
test_batch_size = 1
m1_path = 'models/model_CNN_94.pth'
m2_path = 'models/model_my_fc6_94.pth'
m3_path = 'models/model_score_regressor_94.pth'
m4_path = 'models/model_dive_classifier_94.pth'
c3d_path = 'models/c3d.pickle'
with_dive_cl... | randomseed = 0
(c, h, w) = (3, 112, 112)
input_resize = (171, 128)
test_batch_size = 1
m1_path = 'models/model_CNN_94.pth'
m2_path = 'models/model_my_fc6_94.pth'
m3_path = 'models/model_score_regressor_94.pth'
m4_path = 'models/model_dive_classifier_94.pth'
c3d_path = 'models/c3d.pickle'
with_dive_classification = Fals... |
class _DoublyLinkedBase:
class _Node:
__slots__ = '_element', '_prev', '_next'
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
... | class _Doublylinkedbase:
class _Node:
__slots__ = ('_element', '_prev', '_next')
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
... |
class TV:
def __init__(self):
self.__mysonytvprice = 55000
def mysell(self):
print("The Selling Price is : {}".format(self.__mysonytvprice))
def myMaxPrice(self, myprice):
self.__mysonytvprice = myprice
myobj = TV()
myobj.mysell()
# trying to change the price
myobj.__mysony... | class Tv:
def __init__(self):
self.__mysonytvprice = 55000
def mysell(self):
print('The Selling Price is : {}'.format(self.__mysonytvprice))
def my_max_price(self, myprice):
self.__mysonytvprice = myprice
myobj = tv()
myobj.mysell()
myobj.__mysonytvprice = 56000
myobj.mysell()
myo... |
f1 = open("../../../prachi/kbi/kbi-pytorch/hits_id/fb15k_hits_10_pred.txt",'r').readlines()
f2 = open("../../../prachi/kbi/kbi-pytorch/hits_id/fb15k_hits_10_true.txt",'r').readlines()
f3 = open("fb15k_hits10_not_hits1_pred.txt",'w')
for i in range(len(f1)):
if(f1[i]!=f2[i]):
print(f1[i].strip(),file=f3)
f3... | f1 = open('../../../prachi/kbi/kbi-pytorch/hits_id/fb15k_hits_10_pred.txt', 'r').readlines()
f2 = open('../../../prachi/kbi/kbi-pytorch/hits_id/fb15k_hits_10_true.txt', 'r').readlines()
f3 = open('fb15k_hits10_not_hits1_pred.txt', 'w')
for i in range(len(f1)):
if f1[i] != f2[i]:
print(f1[i].strip(), file=f3... |
# Returned function
def mult_by_x(x):
def inner(y):
return y * x
return inner
# Global?
def alt_mult_by_x(x):
return alt_inner
def alt_inner(y):
return y * x
# Called function
def apply(f, x):
return f(x)
def id(x):
return x
# print(id(id)(id(13)))
def combine_funcs(op):
def... | def mult_by_x(x):
def inner(y):
return y * x
return inner
def alt_mult_by_x(x):
return alt_inner
def alt_inner(y):
return y * x
def apply(f, x):
return f(x)
def id(x):
return x
def combine_funcs(op):
def combined(f, g):
def val(x):
return op(f(x), g(x))
... |
##############################################
# DESCRIPTION : Format Based Steganography #
# Algorithm : Open space encoding #
# Author : Kishore #
##############################################
def to_ascii(charector):
# a method to convert charector into ascii int
assert ... | def to_ascii(charector):
assert type(charector) == str
return ord(charector)
def to_str(ascii):
assert type(ascii) == int
return chr(ascii)
def to_binary(ascii):
assert type(ascii) == int
return '{0:08b}'.format(ascii)
def to_int(binary):
assert type(binary) == str
return int(binary, ... |
def GetRoutes(area):
query = 'select distinct Route from [dimensions].[wells] where [Area] = \'' + area + '\''
return query
def GetWells(area, route):
query = 'select distinct WellName from [dimensions].[wells] where [Route] = \'' + route + '\' and [Area] = \'' + area + '\''
return query
... | def get_routes(area):
query = "select distinct Route from [dimensions].[wells] where [Area] = '" + area + "'"
return query
def get_wells(area, route):
query = "select distinct WellName from [dimensions].[wells] where [Route] = '" + route + "' and [Area] = '" + area + "'"
return query |
# Problem: https://www.hackerrank.com/challenges/diagonal-difference/problem
# Score: 10
a = []
result = 0
for i in range(int(input())):
a = list(map(int, input().split()))
result += a[i] - a[- 1 - i]
print(abs(result))
| a = []
result = 0
for i in range(int(input())):
a = list(map(int, input().split()))
result += a[i] - a[-1 - i]
print(abs(result)) |
sm.removeEscapeButton()
sm.setSpeakerID(1102102)
sm.sendNext("THERE YOU ARE! I told you not to move! You're going to pay for that. Maybe not today, maybe not tomorrow, but one day, when you're on a particularly annoying mission, know that I've secretly arranged it. Now get back to the Drill Hall!")
sm.startQuest(pare... | sm.removeEscapeButton()
sm.setSpeakerID(1102102)
sm.sendNext("THERE YOU ARE! I told you not to move! You're going to pay for that. Maybe not today, maybe not tomorrow, but one day, when you're on a particularly annoying mission, know that I've secretly arranged it. Now get back to the Drill Hall!")
sm.startQuest(parent... |
t = int(input())
for i in range(t):
n,m,k = map(int,input().split())
l = list(map(int,input().split()))
x = {}
for j in range(n):
x[j] = []
for j in range(n):
temp = l[j]
x[temp-1].append(j+1)
print(x)
j=0
me = l[0]
while m>0 and j+1<=me:
m-=len(x[j])
print(m)
k-=1
j+=1
if j-1>me:
print("YES")... | t = int(input())
for i in range(t):
(n, m, k) = map(int, input().split())
l = list(map(int, input().split()))
x = {}
for j in range(n):
x[j] = []
for j in range(n):
temp = l[j]
x[temp - 1].append(j + 1)
print(x)
j = 0
me = l[0]
while m > 0 and j + 1 <= me:
... |
class PaginationHelper():
''' Help keep track of pagination for the web UI, in terms of correct offsets '''
def __init__(self, bare_route, offset, interval=20, num_items=None):
self.bare_route = bare_route
self.interval = interval
self.num_items = num_items
if offset % interval ... | class Paginationhelper:
""" Help keep track of pagination for the web UI, in terms of correct offsets """
def __init__(self, bare_route, offset, interval=20, num_items=None):
self.bare_route = bare_route
self.interval = interval
self.num_items = num_items
if offset % interval or... |
class TestingError(BaseException): pass
class MisnamedFunctionError(TestingError): pass
class TestNotFoundError(TestingError): pass
class SolutionNotFoundError(TestingError): pass
| class Testingerror(BaseException):
pass
class Misnamedfunctionerror(TestingError):
pass
class Testnotfounderror(TestingError):
pass
class Solutionnotfounderror(TestingError):
pass |
#
# 1763. Longest Nice Substring
#
# Q: https://leetcode.com/problems/longest-nice-substring/
# A: https://leetcode.com/problems/longest-nice-substring/discuss/1074560/Kt-Js-Py3-Cpp-Recursive
#
class Solution:
def longestNiceSubstring(self, s: str) -> str:
best = ''
def go(s):
nonlocal ... | class Solution:
def longest_nice_substring(self, s: str) -> str:
best = ''
def go(s):
nonlocal best
seen = set(s)
is_nice = lambda c: c.lower() in seen and c.upper() in seen
for i in range(len(s)):
if not is_nice(s[i]):
... |
#frequency function for cities (could be used for all of the columns)
def freq_function(col):
city = []
for item in col:
for j in item:
city.append(j)
freq= {x:city.count(x) for x in city}
sorted_freq = {k: v for k, v in sorted(freq.items(), key=lambda item: item[1], ... | def freq_function(col):
city = []
for item in col:
for j in item:
city.append(j)
freq = {x: city.count(x) for x in city}
sorted_freq = {k: v for (k, v) in sorted(freq.items(), key=lambda item: item[1], reverse=True)}
return sorted_freq |
class solution:
def max_distance(A):
if len(A) < 2:
return 0
A.sort()
pre = A[0]
max_gap = float("-inf")
for i in A:
max_gap = max(max_gap, i - pre)
pre = i
return max_gap
print(solution.max_distance([3, 5, 4, 2]))
| class Solution:
def max_distance(A):
if len(A) < 2:
return 0
A.sort()
pre = A[0]
max_gap = float('-inf')
for i in A:
max_gap = max(max_gap, i - pre)
pre = i
return max_gap
print(solution.max_distance([3, 5, 4, 2])) |
# Casting an integer to a string
# EXPECTED OUTPUT:
# case5.py: x -> int
# case5.py: y -> int
# case5.py: z -> int
# case5.py: my_function() -> str
def my_function():
x = 5
y = 10
z = x + y
return str(z)
| def my_function():
x = 5
y = 10
z = x + y
return str(z) |
animals = ['bear' , 'python 3.6' , 'peacock' , 'kangroo' , 'whale' , 'zebra']
print(f"The animal at 1 is the 2nd animal and is a {animals[1]}.")
print(f"The third (3rd) animal is at 2 and is a {animals[2]}.")
print(f"The first (1st) animal is at 0 and is a {animals[0]}.")
print(f"The animal at 3 is the forth animal an... | animals = ['bear', 'python 3.6', 'peacock', 'kangroo', 'whale', 'zebra']
print(f'The animal at 1 is the 2nd animal and is a {animals[1]}.')
print(f'The third (3rd) animal is at 2 and is a {animals[2]}.')
print(f'The first (1st) animal is at 0 and is a {animals[0]}.')
print(f'The animal at 3 is the forth animal and is a... |
#inputArray is the input dataset
#x is the searching integer in the array
def binarySearch(inputArray,x):
if (inputArray[-1] > x):
mid = len(inputArray)//2 # get the mid index of the inputArray
if (inputArray[mid] == x): #check it the with the searching number
return true #if yes return true
if (inputArray... | def binary_search(inputArray, x):
if inputArray[-1] > x:
mid = len(inputArray) // 2
if inputArray[mid] == x:
return true
if inputArray[mid] > x:
return binary_search(inputArray[:mid], x)
return binary_search(inputArray[mid:], x)
else:
return false |
WALL = 'w'
FOOD = 'f'
SNAKEBODY = 'b'
SNAKEHEAD = 'h'
width = 5
height = 10
board = [[0 for i in range(width)] for j in range(height)]
board[0][0] = 5
print(board) | wall = 'w'
food = 'f'
snakebody = 'b'
snakehead = 'h'
width = 5
height = 10
board = [[0 for i in range(width)] for j in range(height)]
board[0][0] = 5
print(board) |
#program to compute the values of n
n = float(input( 'Enter the values of n.\n'))
Values = (n+(n*n)+(n*n*n))
print(f'Sample value of n is {n}')
print(f'The expected result:{Values} ') | n = float(input('Enter the values of n.\n'))
values = n + n * n + n * n * n
print(f'Sample value of n is {n}')
print(f'The expected result:{Values} ') |
# problem name: Array Shrinking
# problem link: https://codeforces.com/contest/1312/problem/E
# contest link: https://codeforces.com/contest/1312
# time: (?)
# author: reyad
# other_tags: greedy
# this solution style is a bit different for this problem than most of the cf solutions
# so i'm providing a tutor... | n = int(input())
b = [int(_) for _ in input().split()]
e = [[-1] * (n + 1) for _ in range(2002)]
d = [[] for _ in range(n)]
for (i, v) in enumerate(b):
e[v][i] = i
d[i].append(i)
for v in range(1, 2002):
for i in range(n):
j = e[v][i]
h = e[v][j + 1] if j != -1 else -1
if j != -1 and... |
class colored:
def __init__(self, text, color='\033[1000m', highlight='\033[1000m', effect='\033[1000m'):
self.text = text
none = '\033[1000m'
#---- color ----
Lred = '\033[91m'
red = '\033[31m'
Lblue = '\033[94m'
blue = '\033[34m'
Lgreen = '\033[92m'
green = '\033[32m'
yellow = '\033[93m'
cyan... | class Colored:
def __init__(self, text, color='\x1b[1000m', highlight='\x1b[1000m', effect='\x1b[1000m'):
self.text = text
none = '\x1b[1000m'
lred = '\x1b[91m'
red = '\x1b[31m'
lblue = '\x1b[94m'
blue = '\x1b[34m'
lgreen = '\x1b[92m'
green = '\x1b[32... |
# Algo's described clearly on the following link
# https://math.stackexchange.com/questions/60742/finding-the-n-th-lexicographic-permutation-of-a-string
def nth_permutation(alpha, n):
# alpha is the list of item, and
# n is the nth permutation, that is to be found out
perm = []
t = len(alpha)
fact... | def nth_permutation(alpha, n):
perm = []
t = len(alpha)
fact = [1 for i in range(t)]
for i in range(2, t):
fact[i] = fact[i - 1] * i
for i in range(t - 1, 0, -1):
if n % fact[i]:
p = int(n // fact[i])
perm.append(alpha[p])
n %= fact[i]
... |
#Que 14 Bigger Number (x,y)
x= int(input('Enter first Number :- '))
y= int(input('Enter second Number :- '))
def Big_Number(x,y):
if x>y:
print ("Bigger Number is :- ",x)
if y>x:
print ("Bigger Number is :- ",y)
Big_Number(x,y)
| x = int(input('Enter first Number :- '))
y = int(input('Enter second Number :- '))
def big__number(x, y):
if x > y:
print('Bigger Number is :- ', x)
if y > x:
print('Bigger Number is :- ', y)
big__number(x, y) |
# coding=utf-8
__author__ = 'mlaptev'
if __name__ == "__main__":
input_array = sorted([int(i) for i in input().split()])
amount = 0
for i in range(len(input_array) - 1):
if input_array[i] == input_array[i+1]:
amount += 1
elif amount > 0:
print(input_array[i], end=' '... | __author__ = 'mlaptev'
if __name__ == '__main__':
input_array = sorted([int(i) for i in input().split()])
amount = 0
for i in range(len(input_array) - 1):
if input_array[i] == input_array[i + 1]:
amount += 1
elif amount > 0:
print(input_array[i], end=' ')
... |
{
'targets': [{
'target_name': 'meow_hash_node',
'cflags': [ '-fno-exceptions', '-O3', '-mavx', '-maes', '-msse4' ],
'cflags_cc!': [ '-fno-exceptions', '-O3', '-mavx', '-maes', '-msse4' ],
'sources': [
'lib/cpp/meow_hash_native_stream.cpp',
'lib/cpp/main.cpp'
... | {'targets': [{'target_name': 'meow_hash_node', 'cflags': ['-fno-exceptions', '-O3', '-mavx', '-maes', '-msse4'], 'cflags_cc!': ['-fno-exceptions', '-O3', '-mavx', '-maes', '-msse4'], 'sources': ['lib/cpp/meow_hash_native_stream.cpp', 'lib/cpp/main.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').includ... |
class ErrorResponse:
'''
This class handles if an Exception isreturn in a function.
'''
def __init__(self):
self.__error_response = self.__default_error_response
def __default_error_response(self, req, res, error_messages=None):
res.send_json({
"errors": error_messag... | class Errorresponse:
"""
This class handles if an Exception isreturn in a function.
"""
def __init__(self):
self.__error_response = self.__default_error_response
def __default_error_response(self, req, res, error_messages=None):
res.send_json({'errors': error_messages})
de... |
# dataset settings
dataset_type = 'ICCV09Dataset'
data_root = 'data/custom/iccv09Data'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (512, 512) # reduce crop size to avoid cuda memory issue, have to match with model input (if fine-tune from a pretrained m... | dataset_type = 'ICCV09Dataset'
data_root = 'data/custom/iccv09Data'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
crop_size = (512, 512)
img_scale = (320, 240)
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations'), dict(type='Resize', img_scale=im... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
r = int(input("Enter no of matrix rows : "))
#c = input("Enter no of matrix column")
A = []
max = 0
for i in range(r):
a = []
row_list = input("Enter row "+str(i+1)+" columns : ")
a=list(map(int,row_list.split()))
A.append(a)
if l... | r = int(input('Enter no of matrix rows : '))
a = []
max = 0
for i in range(r):
a = []
row_list = input('Enter row ' + str(i + 1) + ' columns : ')
a = list(map(int, row_list.split()))
A.append(a)
if len(A[i]) > max:
max = len(A[i])
print('Original Matrix : ', A)
print('Maximum columns : ', ma... |
numbers = input().split(' ')
sorted_numbers = sorted(numbers)
reversed_numbers = list(reversed(sorted_numbers))
result = [print(x, end='') for x in reversed_numbers]
| numbers = input().split(' ')
sorted_numbers = sorted(numbers)
reversed_numbers = list(reversed(sorted_numbers))
result = [print(x, end='') for x in reversed_numbers] |
ACCOUNT_ID = '75ce4cee-6829-4274-80e1-77e89559ddfb'
JOB_CONFIG = {
'image': 'registry.console.elementai.com/eai.issam/ssh',
'data': ['c76999a2-05e7-4dcb-aef3-5da30b6c502c:/mnt/home',
'20552761-b5f3-4027-9811-d0f2f5... | account_id = '75ce4cee-6829-4274-80e1-77e89559ddfb'
job_config = {'image': 'registry.console.elementai.com/eai.issam/ssh', 'data': ['c76999a2-05e7-4dcb-aef3-5da30b6c502c:/mnt/home', '20552761-b5f3-4027-9811-d0f2f50a3e60:/mnt/results', '9b4589c8-1b4d-4761-835b-474469b77153:/mnt/datasets'], 'preemptable': True, 'resource... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
cursorA, cursorB = headA, headB
while cursorA != cursorB:
cursorA =... | class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def get_intersection_node(self, headA: ListNode, headB: ListNode) -> ListNode:
(cursor_a, cursor_b) = (headA, headB)
while cursorA != cursorB:
cursor_a = cursorA.next if cursorA el... |
#!/usr/bin/env python3
countryList = ["Unites States", "Russian Federation", "Germany", "Ireland"]
capitalLetters = [ country[0] for country in countryList ]
for i in range(len(capitalLetters)):
lineToPrint = str.join(" stands for ", [capitalLetters[i], countryList[i]])
print(lineToPrint)
| country_list = ['Unites States', 'Russian Federation', 'Germany', 'Ireland']
capital_letters = [country[0] for country in countryList]
for i in range(len(capitalLetters)):
line_to_print = str.join(' stands for ', [capitalLetters[i], countryList[i]])
print(lineToPrint) |
n = int(input())
test_list = []
q = 0
for i in range(n):
entr = list(map(int, input().split()))
if 0 <= entr[0] <= 100 and 0 <= entr[1] <= 100:
test_list.append(entr)
for tests in test_list:
if tests[0] > tests[1]:
q += tests[1]
# if l > c:
# q += l - c
print(q) | n = int(input())
test_list = []
q = 0
for i in range(n):
entr = list(map(int, input().split()))
if 0 <= entr[0] <= 100 and 0 <= entr[1] <= 100:
test_list.append(entr)
for tests in test_list:
if tests[0] > tests[1]:
q += tests[1]
print(q) |
def main():
determine_powerconsumption('src/december03/diagnostics.txt')
def determine_powerconsumption(diagnostics):
counter = [0] * 24
position = 0
with open(diagnostics, 'r') as diagnostics:
for diagnostic in diagnostics:
for position in range(12):
if diagnostic[... | def main():
determine_powerconsumption('src/december03/diagnostics.txt')
def determine_powerconsumption(diagnostics):
counter = [0] * 24
position = 0
with open(diagnostics, 'r') as diagnostics:
for diagnostic in diagnostics:
for position in range(12):
if diagnostic[p... |
class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
ans = 0
l = 0
r = len(height) - 1
maxL = height[l]
maxR = height[r]
while l < r:
if maxL < maxR:
ans += maxL - height[l]
l += 1
maxL = max(maxL, height[l])
else:
... | class Solution:
def trap(self, height: List[int]) -> int:
if not height:
return 0
ans = 0
l = 0
r = len(height) - 1
max_l = height[l]
max_r = height[r]
while l < r:
if maxL < maxR:
ans += maxL - height[l]
... |
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
# is 0
if not numerator or not denominator:
return "0"
ans = ""
# negative
if (numerator < 0) != (denominator < 0):
ans += '-'
... | class Solution:
def fraction_to_decimal(self, numerator: int, denominator: int) -> str:
if not numerator or not denominator:
return '0'
ans = ''
if (numerator < 0) != (denominator < 0):
ans += '-'
numerator = abs(numerator)
denominator = abs(denominat... |
_base_config_ = ["base.py"]
generator = dict(
use_norm=True,
style_cfg=dict(
type="SemanticStyleEncoder",
encoder_modulator="SPADE",
decoder_modulator="SPADE",middle_modulator="SPADE",
nhidden=256),
use_cse=False
)
discriminator=dict(pred_only_cse=True)
loss = dict(
gan_c... | _base_config_ = ['base.py']
generator = dict(use_norm=True, style_cfg=dict(type='SemanticStyleEncoder', encoder_modulator='SPADE', decoder_modulator='SPADE', middle_modulator='SPADE', nhidden=256), use_cse=False)
discriminator = dict(pred_only_cse=True)
loss = dict(gan_criterion=dict(type='fpn_cse', l1_weight=1, lambda... |
class Doc:
date = None
def __init__(self, title, content, data_src):
self.title = title
self.content = content
self.data_src = data_src
| class Doc:
date = None
def __init__(self, title, content, data_src):
self.title = title
self.content = content
self.data_src = data_src |
# https://www.hackerrank.com/challenges/python-mod-divmod/problem
if __name__ == '__main__':
number1 = int(input())
number2 = int(input())
division_oldWays = number1 // number2
division_mod_oldWays = number1 % number2
division_modernWays = number1.__divmod__(number2)
print(division_oldW... | if __name__ == '__main__':
number1 = int(input())
number2 = int(input())
division_old_ways = number1 // number2
division_mod_old_ways = number1 % number2
division_modern_ways = number1.__divmod__(number2)
print(division_oldWays)
print(division_mod_oldWays)
print(division_modernWays) |
data_list = input().split(' -> ')
names_dict = {}
while not data_list[0] == 'end':
name = data_list[0]
tokens = data_list[1].split(', ')
if tokens[0].isdigit():
if name not in names_dict.keys():
names_dict[name] = []
else:
names_dict[name].extend(tokens)
else:
... | data_list = input().split(' -> ')
names_dict = {}
while not data_list[0] == 'end':
name = data_list[0]
tokens = data_list[1].split(', ')
if tokens[0].isdigit():
if name not in names_dict.keys():
names_dict[name] = []
else:
names_dict[name].extend(tokens)
elif toke... |
#!/usr/bin/python
def lagFib():
k=1
mod=1000000
d=[None]
while True:
tmp = None
if k <= 55:
tmp = (100003 - 200003*k + 300007*k*k*k) % mod
else:
tmp = (d[32]+d.pop(1)) % mod
d.append(tmp)
yield tmp
k+=1
| def lag_fib():
k = 1
mod = 1000000
d = [None]
while True:
tmp = None
if k <= 55:
tmp = (100003 - 200003 * k + 300007 * k * k * k) % mod
else:
tmp = (d[32] + d.pop(1)) % mod
d.append(tmp)
yield tmp
k += 1 |
class CleanData():
def __init__(self):
pass
def clear_question_marks(self, df):
df = df[df['horsepower'] != '?']
df.astype({"horsepower": float})
return df
def drop_unused_columns(self, df):
return df.drop(['mpg', 'car_name'], axis=1)
def drop_car_name(self, ... | class Cleandata:
def __init__(self):
pass
def clear_question_marks(self, df):
df = df[df['horsepower'] != '?']
df.astype({'horsepower': float})
return df
def drop_unused_columns(self, df):
return df.drop(['mpg', 'car_name'], axis=1)
def drop_car_name(self, df)... |
s={}
def update_s(s):
s.update({"a":1})
print(s)
update_s(s)
print(s)
class A:
def __init__(self):
self.test()
@property
def val(self):
print("call val")
return 1
def test(self):
self.val
a=A() | s = {}
def update_s(s):
s.update({'a': 1})
print(s)
update_s(s)
print(s)
class A:
def __init__(self):
self.test()
@property
def val(self):
print('call val')
return 1
def test(self):
self.val
a = a() |
#
# PySNMP MIB module PDN-CROSSCONNECT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-CROSSCONNECT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:29:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) ... |
cont = 1
def linha():
print('=' * 30)
def titulo(msg):
print('=' * 30)
print(f'{msg:^30}')
print('=' * 30)
def opc(msg):
global cont
print(f'{cont} - \033[34m{msg}\033[m')
cont = cont + 1
| cont = 1
def linha():
print('=' * 30)
def titulo(msg):
print('=' * 30)
print(f'{msg:^30}')
print('=' * 30)
def opc(msg):
global cont
print(f'{cont} - \x1b[34m{msg}\x1b[m')
cont = cont + 1 |
class SubOperation:
def diferenca(self, number1, number2):
return number1 - number2
| class Suboperation:
def diferenca(self, number1, number2):
return number1 - number2 |
Names = {
"Shakeel": "1735-2015",
"Usman": "2370-2015",
"Sohail": "1432-2015"
}
print("ID for Shakeel is " + Names["Shakeel"])
for k,v in Names.items():
print(k,v) | names = {'Shakeel': '1735-2015', 'Usman': '2370-2015', 'Sohail': '1432-2015'}
print('ID for Shakeel is ' + Names['Shakeel'])
for (k, v) in Names.items():
print(k, v) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def fact(n):
if n == 1:
return 1
else:
return n * fact(n-1)
def facte(n):
return facter(n, 1)
def facter(num, result):
if num == 1:
return result
return facter(num - 1, num * result)
print(fact(6))
print(fact(100))
print(facte(6))
print(facte(100))
| def fact(n):
if n == 1:
return 1
else:
return n * fact(n - 1)
def facte(n):
return facter(n, 1)
def facter(num, result):
if num == 1:
return result
return facter(num - 1, num * result)
print(fact(6))
print(fact(100))
print(facte(6))
print(facte(100)) |
n = int(input())
def is_Prime(n):
is_Prime = True
if n > 1:
for i in range(2,n):
if n % i == 0:
is_Prime = False
break
else:
is_Prime = False
return is_Prime
def next_prime(n):
aux = n
while aux >= n:
if is_Prime(aux) == True:... | n = int(input())
def is__prime(n):
is__prime = True
if n > 1:
for i in range(2, n):
if n % i == 0:
is__prime = False
break
else:
is__prime = False
return is_Prime
def next_prime(n):
aux = n
while aux >= n:
if is__prime(aux) ==... |
filter_cfg = dict(
type='OneEuroFilter',
min_cutoff=0.004,
beta=0.7,
)
| filter_cfg = dict(type='OneEuroFilter', min_cutoff=0.004, beta=0.7) |
#
# PySNMP MIB module Nortel-Magellan-Passport-GeneralVcInterfaceMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-GeneralVcInterfaceMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:27:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) ... |
# If the universe is 15 billions years old, how many seconds is it?
# Var declarations
number = 15000000000
# Assuming that
yearinseconds = 1*12*31*24*60*60
# Code
total = number * yearinseconds
print (total)
# Result
| number = 15000000000
yearinseconds = 1 * 12 * 31 * 24 * 60 * 60
total = number * yearinseconds
print(total) |
# https://leetcode.com/problems/pascals-triangle-ii/
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
return self.getRowRecur([1], rowIndex)
def getRowRecur(self, prevRow, rowIndex):
if rowIndex == 0:
return prevRow
curRow = [prevRow[0]]
for... | class Solution:
def get_row(self, rowIndex: int) -> List[int]:
return self.getRowRecur([1], rowIndex)
def get_row_recur(self, prevRow, rowIndex):
if rowIndex == 0:
return prevRow
cur_row = [prevRow[0]]
for i in range(1, len(prevRow)):
curRow.append(prevR... |
# Season 16 rank information
# Assumes rank 18-11 give a free star same as season 15 https://worldofwarships.com/en/news/general-news/ranked-15/
# TODO: Fix rank 17 logic since stars can't be lost (see https://worldofwarships.com/en/news/general-news/ranked-15/).
regular_ranks = {
18: {
'stars': 1,
... | regular_ranks = {18: {'stars': 1, 'irrevocable': True, 'free-star': False}, 17: {'stars': 2, 'irrevocable': True, 'free-star': True}, 16: {'stars': 2, 'irrevocable': True, 'free-star': True}, 15: {'stars': 2, 'irrevocable': True, 'free-star': True}, 14: {'stars': 2, 'irrevocable': False, 'free-star': True}, 13: {'stars... |
class Instruction:
def __init__(self, direction, distance):
self.direction = direction
self.distance = distance
| class Instruction:
def __init__(self, direction, distance):
self.direction = direction
self.distance = distance |
##The program will recieve 3 English words inputs from STDIN
##
##These three words will be read one at a time, in three separate line
##The first word should be changed like all vowels should be replaced by *
##The second word should be changed like all consonants should be replaced by @
##The third word should b... | a = str(input())
b = str(input())
c = str(input())
v = ['a', 'e', 'i', 'o', 'u']
con = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
for i in a:
if i in v:
x = a.replace(i, '*')
for i in b:
if i in con:
y = b.replace(i, '@')
else:
... |
class Coordinate:
#Built this structure only to make the code more readable
def __init__(self, x, y):
self.x = x
self.y = y
class Atom:
#This structure represents a molecule
def __init__(self, start_coordinate):
self.coordinate = start_coordinate
self.is_alive = False
... | class Coordinate:
def __init__(self, x, y):
self.x = x
self.y = y
class Atom:
def __init__(self, start_coordinate):
self.coordinate = start_coordinate
self.is_alive = False
'\n Function used the determine if a molecule will survive or not\n @param: self is th... |
def fibonacci_recursive(n):
# Base case
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
def main():
x = 10 # compute the x-th Fibonacci number
for i in range(x):
re... | def fibonacci_recursive(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
def main():
x = 10
for i in range(x):
result = fibonacci_recursive(i)
print(result, end=', ')
main() |
test2()
test()
def foo():
pass
test1()
| test2()
test()
def foo():
pass
test1() |
#61: Average
count=0
a=1
summ=0
while a!=0:
a=float(input("Enter the number:"))
summ+=a
count+=1
print("Average:",(summ)/(count-1))
| count = 0
a = 1
summ = 0
while a != 0:
a = float(input('Enter the number:'))
summ += a
count += 1
print('Average:', summ / (count - 1)) |
def cul_a1(N, n):
first_value = (2 * N - n * (n - 1)) // (2 * n)
flag = (2 * N - n * (n - 1)) / (2 * n) == first_value
return flag, first_value
def print_sequence(a1, n):
for a in range(a1, a1 + n-1):
print(a, end=" ")
print(a1 + n-1, end="")
class Sum:
def sum_sequence(self, N, L):
... | def cul_a1(N, n):
first_value = (2 * N - n * (n - 1)) // (2 * n)
flag = (2 * N - n * (n - 1)) / (2 * n) == first_value
return (flag, first_value)
def print_sequence(a1, n):
for a in range(a1, a1 + n - 1):
print(a, end=' ')
print(a1 + n - 1, end='')
class Sum:
def sum_sequence(self, N,... |
#There's a reduced form of range() - range(max_value), in which case min_value is implicitly set to zero:
for i in range(3):
print(i)
| for i in range(3):
print(i) |
def unique(s):
seen = set()
seen_add = seen.add
return [x for x in s if not (x in seen or seen_add(x))]
| def unique(s):
seen = set()
seen_add = seen.add
return [x for x in s if not (x in seen or seen_add(x))] |
class InvalidColorMapException(Exception):
def __init__(self, *args):
if len(args)==1 and isinstance(args[0], str):
self.message = args[0]
else:
self.message = "Invalid colormap."
class InvalidFileFormatException(Exception):
def __init__(self, *args):
if ... | class Invalidcolormapexception(Exception):
def __init__(self, *args):
if len(args) == 1 and isinstance(args[0], str):
self.message = args[0]
else:
self.message = 'Invalid colormap.'
class Invalidfileformatexception(Exception):
def __init__(self, *args):
if len(... |
line = input().split(', ')
my_dict = {}
counter = 1
country = []
while counter <= 2:
for n in range(len(line)):
if counter ==1:
country.append(line[n])
else:
my_dict[country[n]] = line[n]
counter+=1
if counter >2:
break
line = input(). split(', ')
for ... | line = input().split(', ')
my_dict = {}
counter = 1
country = []
while counter <= 2:
for n in range(len(line)):
if counter == 1:
country.append(line[n])
else:
my_dict[country[n]] = line[n]
counter += 1
if counter > 2:
break
line = input().split(', ')
for (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.