content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
config file
'''
n_one_hot_slot = 6 # 0 - user_id, 1 - movie_id, 2 - gender, 3 - age, 4 - occ, 5 - release year
n_mul_hot_slot = 2 # 6 - title (mul-hot), 7 - genres (mul-hot)
max_len_per_slot = 5 # max num of fts in one mul-hot slot
num_csv_col_warm = 17
num_csv_col_w_ngb = 17 + 160 # num of cols in the csv file (... | """
config file
"""
n_one_hot_slot = 6
n_mul_hot_slot = 2
max_len_per_slot = 5
num_csv_col_warm = 17
num_csv_col_w_ngb = 17 + 160
layer_dim = [256, 128, 1]
n_one_hot_slot_ngb = 6
n_mul_hot_slot_ngb = 2
max_len_per_slot_ngb = 5
max_n_ngb_ori = 10
max_n_ngb = 10
pre = './data/'
suf = '.tfrecord'
train_file_name_a = [pre ... |
first_num_elements, second_num_elements2 = [int(num) for num in input().split()]
first_set = {input() for _ in range(first_num_elements)}
second_set = {input() for _ in range(second_num_elements2)}
print(*first_set.intersection(second_set), sep='\n')
# 4 3
# 1
# 3
# 5
# 7
# 3
# 4
# 5 | (first_num_elements, second_num_elements2) = [int(num) for num in input().split()]
first_set = {input() for _ in range(first_num_elements)}
second_set = {input() for _ in range(second_num_elements2)}
print(*first_set.intersection(second_set), sep='\n') |
def decode_index(index: int) -> str:
return {0: "ham", 1: "spam"}[index]
def probability_to_index(prediction: list) -> int:
return 0 if prediction[0] > prediction[1] else 1
| def decode_index(index: int) -> str:
return {0: 'ham', 1: 'spam'}[index]
def probability_to_index(prediction: list) -> int:
return 0 if prediction[0] > prediction[1] else 1 |
a = []
impar = []
par = []
while True:
n1 = int(input("Digite um valor: "))
a.append(n1)
if n1 % 2 == 0:
par.append(n1)
elif n1 % 2 != 0:
impar.append(n1)
s = str(input("Deseja continuar? [S/N]"))
if s in 'Nn':
break
print(f"Lista geral {a}")
print(f"Lista dos pares {par}... | a = []
impar = []
par = []
while True:
n1 = int(input('Digite um valor: '))
a.append(n1)
if n1 % 2 == 0:
par.append(n1)
elif n1 % 2 != 0:
impar.append(n1)
s = str(input('Deseja continuar? [S/N]'))
if s in 'Nn':
break
print(f'Lista geral {a}')
print(f'Lista dos pares {par}... |
# 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 findTilt(self, root):
def travel(node, tiles):
if node is None:
return 0
... | class Solution(object):
def find_tilt(self, root):
def travel(node, tiles):
if node is None:
return 0
sum_left = travel(node.left, tiles)
sum_right = travel(node.right, tiles)
diff = abs(sum_left - sum_right)
tiles.append(diff)
... |
class Triangle:
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def is_valid(self):
if (self.a+self.b>self.c) and (self.a+self.c>self.b) and (self.b+self.c>self.a):
return 'Valid'
else:
return 'Invalid'
def Side_Classification(sel... | class Triangle:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def is_valid(self):
if self.a + self.b > self.c and self.a + self.c > self.b and (self.b + self.c > self.a):
return 'Valid'
else:
return 'Invalid'
def side__classi... |
def main(app_config=None, q1=0, q2=2):
some_var = {'key': 'value'}
if q1 > 9:
return {
"dict_return": 1,
}
return some_var
if __name__ == "__main__":
main()
| def main(app_config=None, q1=0, q2=2):
some_var = {'key': 'value'}
if q1 > 9:
return {'dict_return': 1}
return some_var
if __name__ == '__main__':
main() |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2018 "Neo Technology,"
# Network Engine for Objects in Lund AB [http://neotechnology.com]
#
# This file is part of Neo4j.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | class Structure(list):
def __init__(self, capacity, signature):
self.capacity = capacity
self.signature = signature
def __repr__(self):
return repr(tuple(iter(self)))
def __eq__(self, other):
return list(self) == list(other)
def __ne__(self, other):
return not... |
# Python3 program to find the numbers
# of non negative integral solutions
# return number of non negative
# integral solutions
def countSolutions(n, val,indent):
print(indent+"countSolutions(",n,val,")")
# initialize total = 0
total = 0
# Base Case if n = 1 and val >= 0
# then it shoul... | def count_solutions(n, val, indent):
print(indent + 'countSolutions(', n, val, ')')
total = 0
if n == 1 and val >= 0:
return 1
for i in range(val + 1):
total += count_solutions(n - 1, val - i, indent + ' ')
return total
n = 4
val = 2
print(count_solutions(n, val, '')) |
# -*- coding: utf-8 -*-
DATABASE_MAPPING = {
'database_list': {
'resource': 'database/',
'docs': '',
'methods': ['GET'],
},
'database_get': {
'resource': 'database/{id}/',
'docs': '',
'methods': ['GET'],
},
'database_create': {
'resource': 'da... | database_mapping = {'database_list': {'resource': 'database/', 'docs': '', 'methods': ['GET']}, 'database_get': {'resource': 'database/{id}/', 'docs': '', 'methods': ['GET']}, 'database_create': {'resource': 'database/', 'docs': '', 'methods': ['POST']}, 'database_update': {'resource': 'database/{id}/', 'docs': '', 'me... |
def is_abundant(number):
mysum = 1 # Can always divide by 1, so start looking at divisor 2
for divisor in range(2, int(round(number / 2 + 1))):
if number % divisor == 0:
mysum += divisor
if mysum > number:
return True
else:
return False
| def is_abundant(number):
mysum = 1
for divisor in range(2, int(round(number / 2 + 1))):
if number % divisor == 0:
mysum += divisor
if mysum > number:
return True
else:
return False |
# Copyright European Organization for Nuclear Research (CERN)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Muhammad Aditya Hilmy... | class Didnotavailableexception(BaseException):
def __init__(self):
super().__init__('DID is not yet available.')
class Multipleitemdid(list):
def __init__(self, items, did_available=True):
super(MultipleItemDID, self).__init__(items)
self.items = items
self.did_available = did... |
def ispow2(n):
'''
True if n is a power of 2, False otherwise
>>> ispow2(5)
False
>>> ispow2(4)
True
'''
return (n & (n-1)) == 0
def nextpow2(n):
'''
Given n, return the nearest power of two that is >= n
>>> nextpow2(1)
1
>>> nextpow2(2)
2
>>> nextpow2(5)
... | def ispow2(n):
"""
True if n is a power of 2, False otherwise
>>> ispow2(5)
False
>>> ispow2(4)
True
"""
return n & n - 1 == 0
def nextpow2(n):
"""
Given n, return the nearest power of two that is >= n
>>> nextpow2(1)
1
>>> nextpow2(2)
2
>>> nextpow2(5)
... |
# Complete the fibonacciModified function below.
def fibonacciModified(t1, t2, n):
term = 3
while term <= n:
actual_number = t1 + t2**2
t1 = t2
t2 = actual_number
term += 1
return actual_number
| def fibonacci_modified(t1, t2, n):
term = 3
while term <= n:
actual_number = t1 + t2 ** 2
t1 = t2
t2 = actual_number
term += 1
return actual_number |
a=1;
b=2;
c=a+b;
print("hello world")
121213 | a = 1
b = 2
c = a + b
print('hello world')
121213 |
name = input()
age = int(input())
while name != 'Anton':
print(name)
name = input()
age = input()
print(f'I am Anton') | name = input()
age = int(input())
while name != 'Anton':
print(name)
name = input()
age = input()
print(f'I am Anton') |
class Task(object):
def __init__(self, name, description="", task_id=None):
self.id = task_id
self.name = name
self.description = description
def serialize(self):
return {
"id": self.id,
"name": self.name,
"description": self.d... | class Task(object):
def __init__(self, name, description='', task_id=None):
self.id = task_id
self.name = name
self.description = description
def serialize(self):
return {'id': self.id, 'name': self.name, 'description': self.description}
@staticmethod
def serialize_mul... |
# -*- coding: utf-8 -*-
_available_examples = ["ex_001_Molecule_Hamiltonian.py",
"ex_002_Molecule_Aggregate.py",
"ex_003_CorrFcnSpectDens.py",
"ex_004_SpectDensDatabase.py",
"ex_005_UnitsManagementHamiltonian.py",
... | _available_examples = ['ex_001_Molecule_Hamiltonian.py', 'ex_002_Molecule_Aggregate.py', 'ex_003_CorrFcnSpectDens.py', 'ex_004_SpectDensDatabase.py', 'ex_005_UnitsManagementHamiltonian.py', 'ex_006_Absorption_1.py', 'ex_010_RedfieldTheory_1.py', 'ex_011_LindbladForm_1.py', 'ex_012_Integrodiff.py', 'ex_013_HEOM.py', 'ex... |
def recursive_multiply(x, y):
if (x < y):
return recursive_multiply(y, x)
elif (y != 0):
return (x + recursive_multiply(x, y-1))
else:
return 0
x = int(input("Enter x"))
y = int(input("Enter y"))
print(recursive_multiply(x, y)) | def recursive_multiply(x, y):
if x < y:
return recursive_multiply(y, x)
elif y != 0:
return x + recursive_multiply(x, y - 1)
else:
return 0
x = int(input('Enter x'))
y = int(input('Enter y'))
print(recursive_multiply(x, y)) |
DEFAULT_STACK_SIZE = 8
class PcStack(object):
def __init__(self, programCounter, size: int=DEFAULT_STACK_SIZE):
self._programCounter = programCounter
self._size = size
self._stack = [0]*size
self._stackPointer = 0
@property
def programCounter(self):
return self._p... | default_stack_size = 8
class Pcstack(object):
def __init__(self, programCounter, size: int=DEFAULT_STACK_SIZE):
self._programCounter = programCounter
self._size = size
self._stack = [0] * size
self._stackPointer = 0
@property
def program_counter(self):
return self.... |
# -*- coding: utf-8 -*-
user_schema = {
'username': {
'type': 'string',
'minlength': 1,
'maxlength': 64,
'required': True,
'unique': True
},
'email': {
'type': 'string',
'regex': '^\S+@\S+.\S+',
'required': True,
'unique': True
},
... | user_schema = {'username': {'type': 'string', 'minlength': 1, 'maxlength': 64, 'required': True, 'unique': True}, 'email': {'type': 'string', 'regex': '^\\S+@\\S+.\\S+', 'required': True, 'unique': True}, 'password': {'type': 'string', 'minlength': 1, 'maxlength': 64, 'required': True}}
user = {'item_title': 'user', 'a... |
'''
https://www.geeksforgeeks.org/find-count-number-given-string-present-2d-character-array/
Given a 2-Dimensional character array and a string, we need to find the given string in 2-dimensional character array such that individual characters can be present left to right, right to left, top to down or down to top.
Exa... | """
https://www.geeksforgeeks.org/find-count-number-given-string-present-2d-character-array/
Given a 2-Dimensional character array and a string, we need to find the given string in 2-dimensional character array such that individual characters can be present left to right, right to left, top to down or down to top.
Exa... |
#
# PHASE: jvm flags
#
# DOCUMENT THIS
#
def phase_jvm_flags(ctx, p):
if ctx.attr.tests_from:
archives = _get_test_archive_jars(ctx, ctx.attr.tests_from)
else:
archives = p.compile.merged_provider.runtime_output_jars
serialized_archives = _serialize_archives_short_path(archives)
test_su... | def phase_jvm_flags(ctx, p):
if ctx.attr.tests_from:
archives = _get_test_archive_jars(ctx, ctx.attr.tests_from)
else:
archives = p.compile.merged_provider.runtime_output_jars
serialized_archives = _serialize_archives_short_path(archives)
test_suite = _gen_test_suite_flags_based_on_prefi... |
METADATA = 'metadata'
CONTENT = 'content'
FILENAME = 'filename'
PARAM_CREATION_DATE = '_audit_creation_date'
PARAM_R1 = '_diffrn_reflns_av_R_equivalents'
PARAM_SIGMI_NETI = '_diffrn_reflns_av_sigmaI/netI'
PARAM_COMPLETENESS = '_reflns_odcompleteness_completeness'
PARAM_SPACEGROUP = '_space_group_name_H-M_alt'
PARAM_SP... | metadata = 'metadata'
content = 'content'
filename = 'filename'
param_creation_date = '_audit_creation_date'
param_r1 = '_diffrn_reflns_av_R_equivalents'
param_sigmi_neti = '_diffrn_reflns_av_sigmaI/netI'
param_completeness = '_reflns_odcompleteness_completeness'
param_spacegroup = '_space_group_name_H-M_alt'
param_spa... |
class cves():
cve_url = "https://services.nvd.nist.gov/rest/json/cves/1.0?pubStartDate=2021-09-01T00:00:00:000+UTC-00:00&resultsPerPage=100&keyword="
keywords = ["RHCS", "RHEL", "Thales", "nShield", "Certificate+Authority&isExactMatch=true", "NSS", "tomcat", "TLS"]
| class Cves:
cve_url = 'https://services.nvd.nist.gov/rest/json/cves/1.0?pubStartDate=2021-09-01T00:00:00:000+UTC-00:00&resultsPerPage=100&keyword='
keywords = ['RHCS', 'RHEL', 'Thales', 'nShield', 'Certificate+Authority&isExactMatch=true', 'NSS', 'tomcat', 'TLS'] |
#!/usr/local/bin/python3
class Object(object):
def __init__(self, id):
self.id = id
self.children = []
root = Object("COM")
objects = {"COM": root}
def get_object(id):
if id not in objects:
objects[id] = Object(id)
return objects[id]
with open("input.txt") as f:
for line in f... | class Object(object):
def __init__(self, id):
self.id = id
self.children = []
root = object('COM')
objects = {'COM': root}
def get_object(id):
if id not in objects:
objects[id] = object(id)
return objects[id]
with open('input.txt') as f:
for line in f.readlines():
(pare... |
key = {'f':'l', 'd': 'l','j':'r', 'k':'r'}
words = {}
for _ in range(int(input())):
n = int(input())
for _ in range(n):
s = input()
if words.get(s): words[s] += 1
else : words[s] = 1
# print(words)
final_ans = 0
for i in words:
c_word_ans = 0.2
pre = key[i[0]]
for j in i[1::]:
if(key[j] == pre):c_wo... | key = {'f': 'l', 'd': 'l', 'j': 'r', 'k': 'r'}
words = {}
for _ in range(int(input())):
n = int(input())
for _ in range(n):
s = input()
if words.get(s):
words[s] += 1
else:
words[s] = 1
final_ans = 0
for i in words:
c_word_ans = 0.2
pre = k... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class PotentialEdgeColumnPair:
def __init__(self, source, destination, score):
self._source = source
self._destination = destination
self._score = score
def source(self):
return self._source
def dest... | class Potentialedgecolumnpair:
def __init__(self, source, destination, score):
self._source = source
self._destination = destination
self._score = score
def source(self):
return self._source
def destination(self):
return self._destination
def score(self):
... |
class ModelOutput:
# Class that defines model output structure
def __init__(self, arg_type, arg_size, is_spacial):
self.arg_type = arg_type
self.arg_size = arg_size
self.is_spacial = is_spacial
| class Modeloutput:
def __init__(self, arg_type, arg_size, is_spacial):
self.arg_type = arg_type
self.arg_size = arg_size
self.is_spacial = is_spacial |
class DateGetter:
'''Parse a date using the datetime format string defined in
the current jxn's config.
'''
def _get_date(self, label_text):
fmt = self.get_config_value('datetime_format')
text = self.get_field_text(label_text)
if text is not None:
dt = datetime.strpti... | class Dategetter:
"""Parse a date using the datetime format string defined in
the current jxn's config.
"""
def _get_date(self, label_text):
fmt = self.get_config_value('datetime_format')
text = self.get_field_text(label_text)
if text is not None:
dt = datetime.strpt... |
n = int(input())
alph = ["A",'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','Q','X','Y','Z']
boxes = []
for x in range(n):
box = []
length = int(input())
for y in range(length):
box.append([])
for i in range(length):
box[y].append("... | n = int(input())
alph = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'Q', 'X', 'Y', 'Z']
boxes = []
for x in range(n):
box = []
length = int(input())
for y in range(length):
box.append([])
for i in range(length):
b... |
PROCESS_CREATE = 0
PROCESS_EDIT = 1
PROCESS_VIEW = 2
PROCESS_DELETE = 3
PROCESS_EDIT_DELETE = 4 # Edit with delete button
PROCESS_VIEW_EDIT = 5 # View with edit button
PERMISSION_DISABLE = 2
PERMISSION_ON = 1
PERMISSION_OFF = 0
PERMISSION_AUTHENTICATED = 3
PERMISSION_STAFF = 4
PERMISSION_METHOD = 5
class P... | process_create = 0
process_edit = 1
process_view = 2
process_delete = 3
process_edit_delete = 4
process_view_edit = 5
permission_disable = 2
permission_on = 1
permission_off = 0
permission_authenticated = 3
permission_staff = 4
permission_method = 5
class Processsetup:
def __init__(self, modal_title, django_permi... |
# Copyright (c) 2020 Greg Dubicki
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
# MIT License
#
# Copyright (c) 2018 Shane ... | class Cachenode(object):
def __init__(self, key, value, freq_node, pre, nxt):
self.key = key
self.value = value
self.freq_node = freq_node
self.pre = pre
self.nxt = nxt
def free_myself(self):
if self.freq_node.cache_head == self.freq_node.cache_tail:
... |
def solution(clothes):
answer = {}
for i in clothes:
if i[1] in answer: answer[i[1]]+=1
else: answer[i[1]] = 1
cnt = 1
for i in answer.values():
cnt *= (i+1)
return cnt - 1 | def solution(clothes):
answer = {}
for i in clothes:
if i[1] in answer:
answer[i[1]] += 1
else:
answer[i[1]] = 1
cnt = 1
for i in answer.values():
cnt *= i + 1
return cnt - 1 |
# Request Link and Long Polling Use
TELEGRAM_TOKEN = ''
WEBHOOK_URL = ''
TELEGRAM_BASE = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}'
TELEGRAM_WEBHOOK_URL = TELEGRAM_BASE + f'/setWebhook?url={WEBHOOK_URL}/hook'
FUGLE_API_TOKEN = ''
# Other Chatbot Token
EXAMPLE_TOKEN = ''
# WEBHOOK_URL = ''
| telegram_token = ''
webhook_url = ''
telegram_base = f'https://api.telegram.org/bot{TELEGRAM_TOKEN}'
telegram_webhook_url = TELEGRAM_BASE + f'/setWebhook?url={WEBHOOK_URL}/hook'
fugle_api_token = ''
example_token = '' |
# Speed Fine Problem
# input
limit = int(input('Enter the speed limit: '))
speed = int(input('Enter the recorded speed of the car: '))
# processing & output
if speed <= limit:
print('Congratulations, you are within the speed limit!')
else:
difference = speed - limit
if difference > 30:
print('You ... | limit = int(input('Enter the speed limit: '))
speed = int(input('Enter the recorded speed of the car: '))
if speed <= limit:
print('Congratulations, you are within the speed limit!')
else:
difference = speed - limit
if difference > 30:
print('You are speeding and your fine is $500.')
elif differ... |
#
# PySNMP MIB module DEVICE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DEVICE
# Produced by pysmi-0.3.4 at Mon Apr 29 18:26:39 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)
... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) ... |
# Question
# 17. Write a menu driven program to find the area of circle, square, rectangle & triangle.
# Code
types = ["circle", "square", "rectangle", "triangle"]
print("-"*15) # 15 is length of Area Calculator. not intentional though it was a random rumber
print("Area Calculator")
print("-"*15)
print()
print("Plea... | types = ['circle', 'square', 'rectangle', 'triangle']
print('-' * 15)
print('Area Calculator')
print('-' * 15)
print()
print('Please enter the following numbers according to the shape you want to calculate the area of.')
print()
for (i, type) in enumerate(types):
print(i, ':', types[i])
print()
shape = int(input())... |
#######################
# Login configuration #
#######################
weblab_db_username = 'weblab'
weblab_db_password = 'weblab'
########################################
# User Processing Server configuration #
########################################
core_session_type = 'Memory'
core_coordinator_db_username = '... | weblab_db_username = 'weblab'
weblab_db_password = 'weblab'
core_session_type = 'Memory'
core_coordinator_db_username = 'weblab'
core_coordinator_db_password = 'weblab'
core_coordinator_laboratory_servers = {'laboratory:lab_and_experiment1@main_machine': {'exp1|ud-dummy|Dummy experiments': 'dummy1@ud-dummy', 'exp2|ud-d... |
# DomirScire
def get_final_line(filename):
final_line = ''
for current_line in open(filename):
final_line = current_line
return final_line
if __name__ == "__main__":
print(get_final_line('./'))
| def get_final_line(filename):
final_line = ''
for current_line in open(filename):
final_line = current_line
return final_line
if __name__ == '__main__':
print(get_final_line('./')) |
class Solution:
def makeString(self, s: str) -> str:
result = []
for c in s:
if c != '#':
result.append(c)
elif len(result) > 0:
result.pop()
return str(result)
def backspaceCompare(self, s: str, t: str) -> bool:
return sel... | class Solution:
def make_string(self, s: str) -> str:
result = []
for c in s:
if c != '#':
result.append(c)
elif len(result) > 0:
result.pop()
return str(result)
def backspace_compare(self, s: str, t: str) -> bool:
return ... |
# Get frequencies of attributes
def get_frequencies(plant_dict):
frequencies = {} # First keep count of how many times an attribute appears
count = 0 # Keep track of the number of plants
for plant in plant_dict:
plant_attributes = set() # Don't count duplicate attributes (such as a flower having... | def get_frequencies(plant_dict):
frequencies = {}
count = 0
for plant in plant_dict:
plant_attributes = set()
plant_tuples = plant_dict[plant]
for tup in plant_tuples:
attribute = tup[0]
if attribute in plant_attributes:
continue
if... |
squares = []
for value in range(1,11):
squares.append(value **2)
print(squares)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
squares = [value**2 for value in range(1,11)]
print(squares)
odd_numbers = list(range(1,20,1))
print(odd_numbers)
cars = ['audi', 'bmw... | squares = []
for value in range(1, 11):
squares.append(value ** 2)
print(squares)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
squares = [value ** 2 for value in range(1, 11)]
print(squares)
odd_numbers = list(range(1, 20, 1))
print(odd_numbers)
cars = ['audi', 'b... |
# Stub only, D support was broken with Python2.6 and unnecessary to Nuitka
def generate(env):
return
def exists(env):
return False
| def generate(env):
return
def exists(env):
return False |
class Base:
def __init__(self, x=0):
self.x = x
class Slave(Base):
def __init__(self, x):
super(Slave, self).__init__()
self.x = x
s1 = Slave(x=2)
print(s1.x) | class Base:
def __init__(self, x=0):
self.x = x
class Slave(Base):
def __init__(self, x):
super(Slave, self).__init__()
self.x = x
s1 = slave(x=2)
print(s1.x) |
def strStr(haystack: str, needle: str) -> int:
i = 0
j = 0
len1 = len(haystack)
len2 = len(needle)
while i < len1 and j < len2:
if haystack[i] == needle[j]:
i += 1
j += 1
else:
i = i - (j - 1)
j = 0
if j == len2:
return i-j
else:
return -1
print(strStr("abcdeabc", "bcd")) | def str_str(haystack: str, needle: str) -> int:
i = 0
j = 0
len1 = len(haystack)
len2 = len(needle)
while i < len1 and j < len2:
if haystack[i] == needle[j]:
i += 1
j += 1
else:
i = i - (j - 1)
j = 0
if j == len2:
return i -... |
'''
Program to count number of trees in a forest.
Approach:
The idea is to apply Depth First Search on every node.
If every connected node is visited from one source then increment count by one.
If some nodes yet not visited again perform DFS traversal.
Return the count.
Example:
Input : edges[] = {0, 1}, {0, ... | """
Program to count number of trees in a forest.
Approach:
The idea is to apply Depth First Search on every node.
If every connected node is visited from one source then increment count by one.
If some nodes yet not visited again perform DFS traversal.
Return the count.
Example:
Input : edges[] = {0, 1}, {0, ... |
def reverseInput(word):
# str[start:stop:step]
return word[::-1]
def reverseInput2(word):
new_word = ""
for char in word:
new_word = char + new_word
return new_word
if __name__ == "__main__":
word = input("Enter the word: ")
print(reverseInput(word))
print(reverseInput2(word)... | def reverse_input(word):
return word[::-1]
def reverse_input2(word):
new_word = ''
for char in word:
new_word = char + new_word
return new_word
if __name__ == '__main__':
word = input('Enter the word: ')
print(reverse_input(word))
print(reverse_input2(word)) |
EXAMPLE = '''\
|+1|-1|+2|-2|+3|-3|+sg|+pl|-sg|-pl|
1sg| X| | | X| | X| X| | | X|
1pl| X| | | X| | X| | X| X| |
2sg| | X| X| | | X| X| | | X|
2pl| | X| X| | | X| | X| X| |
3sg| | X| | X| X| | X| | | X|
3pl| | X| | X| X| | | X| X| |
'''
| example = ' |+1|-1|+2|-2|+3|-3|+sg|+pl|-sg|-pl|\n1sg| X| | | X| | X| X| | | X|\n1pl| X| | | X| | X| | X| X| |\n2sg| | X| X| | | X| X| | | X|\n2pl| | X| X| | | X| | X| X| |\n3sg| | X| | X| X| | X| | | X|\n3pl| | X| | X| X| | | X| X| |\n' |
def is_valid_row_col(next_r, next_c):
if 0 <= next_r < 8 and 0 <= next_c < 8:
return True
return False
matrix = []
queens = []
for _ in range(8):
data = input().split(" ")
matrix.append(data)
row_king = int
col_king = int
for row in range(8):
for column in range(8):
if matrix[ro... | def is_valid_row_col(next_r, next_c):
if 0 <= next_r < 8 and 0 <= next_c < 8:
return True
return False
matrix = []
queens = []
for _ in range(8):
data = input().split(' ')
matrix.append(data)
row_king = int
col_king = int
for row in range(8):
for column in range(8):
if matrix[row][co... |
# O(n) time and O(log n) space
def max_path_sum(tree):
_, max_path_sum = max_path_sum_helper(tree)
return max_path_sum
def max_path_sum_helper(tree):
if not tree:
# Base case of not a node
return (0, 0)
# Depth first bottom up approach to calculate the max path sum
left_branch_sum,... | def max_path_sum(tree):
(_, max_path_sum) = max_path_sum_helper(tree)
return max_path_sum
def max_path_sum_helper(tree):
if not tree:
return (0, 0)
(left_branch_sum, left_triangle_sum) = max_path_sum_helper(tree.left)
(right_branch_sum, right_triangle_sum) = max_path_sum_helper(tree.right)
... |
#
# PySNMP MIB module SW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:36:37 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)
... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_union, value_range_constraint, constraints_intersection, single_value_constraint) ... |
text = '''aaaaaa aaaaaa aaaa aaaa a aa aa a aa0
bbbbbb bbbbbb bbbbbbbbbb.ccc ccccc c0
dddd ddddd ddddd.eeeee eeeeeee.fffff0
fffff fff ffffff.ggg ggg gg g.eeefaa0.'''
lines = list(text.split('\n'))
words = list(text.split(' '))
sentenses = list(text.split('.'))
print(len(lines), lines, '\n')
print(len(words), words, '... | text = 'aaaaaa aaaaaa aaaa aaaa a aa aa a aa0\nbbbbbb bbbbbb bbbbbbbbbb.ccc ccccc c0\ndddd ddddd ddddd.eeeee eeeeeee.fffff0\nfffff fff ffffff.ggg ggg gg g.eeefaa0.'
lines = list(text.split('\n'))
words = list(text.split(' '))
sentenses = list(text.split('.'))
print(len(lines), lines, '\n')
print(len(words), words, '\n'... |
class BinaryTree:
def __init__(self, rootValue):
self.value = rootValue
self.left = None
self.right = None
def addLeftChild(self, val):
newNode = BinaryTree(val)
self.left = newNode
def addRightChild(self, val):
newNode = BinaryTree(val)
self.right... | class Binarytree:
def __init__(self, rootValue):
self.value = rootValue
self.left = None
self.right = None
def add_left_child(self, val):
new_node = binary_tree(val)
self.left = newNode
def add_right_child(self, val):
new_node = binary_tree(val)
sel... |
#a = 3
#b = 4
#c = a ** b
#print (c)
#x = 5
#print(x)
#x = 5
#x += 3
#
#print(x)
#x = 5
#x -= 3
#
#print(x)
#x = 5
#x *= 3
#print(x)
#x = 5
#x /= 3
#print(x)
#x = 5
#x%=3
#print(x)
# comparisin opperraters
#x = 5
#y = 3
#
#print(x == y)
#
# returns False because 5 is not equal to 3
#x = 5
#y = 3
... | x = 5
y = 3
print(x <= y) |
fruit = ["apple", "banana", "peach"]
fruit
# outputs
# >>> ['apple', 'banana', 'peach']
| fruit = ['apple', 'banana', 'peach']
fruit |
#!/usr/bin/env python
#--- Day 6: Universal Orbit Map ---
#You've landed at the Universal Orbit Map facility on Mercury. Because navigation in space often involves transferring between orbits, the orbit maps here are useful for finding efficient routes between, for example, you and Santa. You download a map of the loc... | puzzle_input = []
with open('day06.txt', 'r') as file:
for entry in file.readlines():
puzzle_input.append(entry.rstrip().split(')'))
orbit_dict = {key: value for (value, key) in puzzle_input}
calc_orbits = 0
for obj in orbit_dict.keys():
obj_tmp = obj
while obj_tmp in orbit_dict:
calc_orbits... |
def print_name(prefix):
print("searchingname with" + prefix)
try:
while True:
name = (yield)
if prefix in name:
print(name)
except GeneratorExit as identifier:
print("Coroutine Exited")
corou = print_name("Dear")
corou.__next__()
corou.send("Atul")... | def print_name(prefix):
print('searchingname with' + prefix)
try:
while True:
name = (yield)
if prefix in name:
print(name)
except GeneratorExit as identifier:
print('Coroutine Exited')
corou = print_name('Dear')
corou.__next__()
corou.send('Atul')
cor... |
n = int(input())
s = [1 if element == 'U' else -1 for element in input()]
counter = 0
status = 0
step = 0
while step < n:
if status == 0 and s[step] == -1:
status = 1
start_pt = step
step += 1
sum_val = -1
while step < n and status != 0:
sum_val += s[step]
if sum_val == 0:
counter += 1
... | n = int(input())
s = [1 if element == 'U' else -1 for element in input()]
counter = 0
status = 0
step = 0
while step < n:
if status == 0 and s[step] == -1:
status = 1
start_pt = step
step += 1
sum_val = -1
while step < n and status != 0:
sum_val += s[step]
... |
'''
Author: tusikalanse
Date: 2021-07-10 18:07:33
LastEditTime: 2021-07-10 18:10:07
LastEditors: tusikalanse
Description:
'''
cnt = 0
def gao(i: int) -> int:
for _ in range(50):
i = i + int(str(i)[::-1])
if str(i) == str(i)[::-1]:
return 0
return 1
for i in range(10000):
cnt ... | """
Author: tusikalanse
Date: 2021-07-10 18:07:33
LastEditTime: 2021-07-10 18:10:07
LastEditors: tusikalanse
Description:
"""
cnt = 0
def gao(i: int) -> int:
for _ in range(50):
i = i + int(str(i)[::-1])
if str(i) == str(i)[::-1]:
return 0
return 1
for i in range(10000):
cnt +=... |
# To demonstrate, we insert the number 8 to specify the available space for the value.
# Use "=" to place the plus/minus sign at the left most position:
txt = "The temperature is {:=8} degrees celsius."
print(txt.format(-5))
| txt = 'The temperature is {:=8} degrees celsius.'
print(txt.format(-5)) |
'''
Flask config.
'''
display = {}
CREDS_PATH = "app/creds.txt"
TEMPLATES_AUTO_RELOAD = True | """
Flask config.
"""
display = {}
creds_path = 'app/creds.txt'
templates_auto_reload = True |
# equation constants
# gas diffusivity
CONST_EQ_GAS_DIFFUSIVITY = {
"Chapman-Enskog": 1,
"Wilke-Lee": 2
}
# gas viscosity
CONST_EQ_GAS_VISCOSITY = {
"eq1": 1,
"eq2": 2
}
# sherwood number
CONST_EQ_Sh = {
"Frossling": 1,
"Rosner": 2,
"Garner-and-Keey": 3
}
# thermal conductivity
CONST_EQ_... | const_eq_gas_diffusivity = {'Chapman-Enskog': 1, 'Wilke-Lee': 2}
const_eq_gas_viscosity = {'eq1': 1, 'eq2': 2}
const_eq__sh = {'Frossling': 1, 'Rosner': 2, 'Garner-and-Keey': 3}
const_eq_gas_thermal_conductivity = {'eq1': 1, 'eq2': 2} |
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
list = []
num = int(input('check wich number is smaller than : '))
for x in a:
if x < num:
list.append(x)
# print(x)
print(list)
| a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
list = []
num = int(input('check wich number is smaller than : '))
for x in a:
if x < num:
list.append(x)
print(list) |
# Write a function named combine_sort that has two parameters named lst1 and lst2.
# The function should combine these two lists into one new list and sort the result. Return the new sorted list.
#print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10]))
def combine_sort(lst1, lst2):
new_lst = lst1 + lst2
return sor... | def combine_sort(lst1, lst2):
new_lst = lst1 + lst2
return sorted(new_lst)
print(combine_sort([4, 10, 2, 5], [-10, 2, 5, 10])) |
# Allows for easier debugging and unit testing. For example in dev mode functions don't expect a Flask request input.
DEV_MODE = False
KEYFILE = 'keyfile.json'
| dev_mode = False
keyfile = 'keyfile.json' |
elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43]
l=len(elements)
i=0
sum_even=0
sum_odd=0
average_even=0
average_odd=0
while i<l:
if elements[i]%2==0:
sum_even=sum_even+elements[i]
average_even+=1
else:
sum_odd=sum_odd+elements[i]
average_odd+=1
i+=1
print(sum_even//ave... | elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43]
l = len(elements)
i = 0
sum_even = 0
sum_odd = 0
average_even = 0
average_odd = 0
while i < l:
if elements[i] % 2 == 0:
sum_even = sum_even + elements[i]
average_even += 1
else:
sum_odd = sum_odd + elements[i]
average_odd += ... |
# for local
# It's probably helpful for us to demonstrate what the URL should be, etc.
SECRET_KEY = b'keycloak'
# http, not https for some reason
SERVER_URL = "http://keycloak-idp:8080/auth/"
ADMIN_USERNAME = "admin"
ADMIN_PASS = "admin"
REALM_NAME = "master"
# created in keycloak per https://github.com/keycloak/keyc... | secret_key = b'keycloak'
server_url = 'http://keycloak-idp:8080/auth/'
admin_username = 'admin'
admin_pass = 'admin'
realm_name = 'master'
client_id = 'keycloak-flask'
client_secret = '2da4a9a4-f6f0-48d9-82f6-12012402f03a'
ingress_host = 'http://www.google.com/' |
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(iname):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {iname}') # Pres... | def print_hi(iname):
print(f'Hi, {iname}')
print_hi('hi pycharm')
def days_to_hour(num_of_days):
calc_to_units = 24
name_of_units = 'hours'
return f'{num_of_days} days to {name_of_units} are {num_of_days * calc_to_units} {name_of_units}'
def validate_user_input():
try:
user_input_days = in... |
pi=22/7
r=float(input("enter radius of circle"))
Area=pi*r*r
print("Area of circle:%f",Area)
| pi = 22 / 7
r = float(input('enter radius of circle'))
area = pi * r * r
print('Area of circle:%f', Area) |
def upload(task_id, file_id, remote_path):
global responses
remote_path = remote_path.replace("\\", "")
upload = {
'action': "upload",
'file_id': file_id,
'chunk_size': 512000,
'chunk_num': 1,
'full_path': "",
'task_id': task_id,
}
res = send(upload,... | def upload(task_id, file_id, remote_path):
global responses
remote_path = remote_path.replace('\\', '')
upload = {'action': 'upload', 'file_id': file_id, 'chunk_size': 512000, 'chunk_num': 1, 'full_path': '', 'task_id': task_id}
res = send(upload, agent.get_UUID())
res = res['chunk_data']
respon... |
#!/usr/bin/env python
def constructCDS(features, coordinates):
exonCoordinates = [coordinates[featureIndex] for featureIndex in range(len(features)) if features[featureIndex][1] == "e"]
cdsMap = {}
cdsStart = 1
for exonCoord in exonCoordinates:
exonStart, exonEnd = exonCoord
cdsEnd = c... | def construct_cds(features, coordinates):
exon_coordinates = [coordinates[featureIndex] for feature_index in range(len(features)) if features[featureIndex][1] == 'e']
cds_map = {}
cds_start = 1
for exon_coord in exonCoordinates:
(exon_start, exon_end) = exonCoord
cds_end = cdsStart + (ex... |
class CodeParser():
#Parsing variables
SPEED = 0
ANGLE = 0
lineNum = 0
#Parsing libraries (or "keywords")
PORTS = ["THROTTLE", "TURN"]
#Initialize the CodeParser
def __init__(self, path):
self.SPEED = 0
self.ANGLE = 0
#Open racer file
racer = open(path, ... | class Codeparser:
speed = 0
angle = 0
line_num = 0
ports = ['THROTTLE', 'TURN']
def __init__(self, path):
self.SPEED = 0
self.ANGLE = 0
racer = open(path, 'r')
self.code = racer.readlines()
racer.close()
line = 0
while line < len(self.code):
... |
# If we want to find the shortest path or any path between 2 nodes
# BFS works better
# Breadth-First search needs a Queue
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __str__(self):
return "Node: {} Left: {} Right:{}".format(self.v... | class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def __str__(self):
return 'Node: {} Left: {} Right:{}'.format(self.val, self.left, self.right)
def visit(self):
print(self.val, end='')
def breadth_first_traversal(root):
qu... |
testcases = int(input().strip())
for test in range(testcases):
string = input().strip()
length = len(string)
half_length = length // 2
if length % 2:
print(-1)
continue
letters1 = [0] * 26
letters2 = [0] * 26
ascii_a = ord('a')
ascii_string = [ord(c) - ascii_a for c in... | testcases = int(input().strip())
for test in range(testcases):
string = input().strip()
length = len(string)
half_length = length // 2
if length % 2:
print(-1)
continue
letters1 = [0] * 26
letters2 = [0] * 26
ascii_a = ord('a')
ascii_string = [ord(c) - ascii_a for c in st... |
w, h, k = list(map(int, input().split()))
c=0
for i in range(k):
c = c+ ( (h-4*i)*2 +( w - 2-4*i)*2)
print(c)
| (w, h, k) = list(map(int, input().split()))
c = 0
for i in range(k):
c = c + ((h - 4 * i) * 2 + (w - 2 - 4 * i) * 2)
print(c) |
t = int(input())
h = (t // 3600) % 24
m1 = t // 60 % 60 // 10
m2 = t // 60 % 60 % 10
s1 = t % 60 // 10
s2 = t % 10
print(h, ":", m1, m2, ":", s1, s2, sep="")
| t = int(input())
h = t // 3600 % 24
m1 = t // 60 % 60 // 10
m2 = t // 60 % 60 % 10
s1 = t % 60 // 10
s2 = t % 10
print(h, ':', m1, m2, ':', s1, s2, sep='') |
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
def sumRootToLeaf(r, s):
li, x = [n for n in [r.left, r.right] if n], (s << 1) + r.val
return x if not li else sum(sumRootToLeaf(n, x) for n in li)
return sumRootToLeaf(root, 0) | class Solution:
def sum_root_to_leaf(self, root: TreeNode) -> int:
def sum_root_to_leaf(r, s):
(li, x) = ([n for n in [r.left, r.right] if n], (s << 1) + r.val)
return x if not li else sum((sum_root_to_leaf(n, x) for n in li))
return sum_root_to_leaf(root, 0) |
class SymbolTable:
def __init__(self):
self.table = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0,
'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7,
'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14,
... | class Symboltable:
def __init__(self):
self.table = {'SP': 0, 'LCL': 1, 'ARG': 2, 'THIS': 3, 'THAT': 4, 'R0': 0, 'R1': 1, 'R2': 2, 'R3': 3, 'R4': 4, 'R5': 5, 'R6': 6, 'R7': 7, 'R8': 8, 'R9': 9, 'R10': 10, 'R11': 11, 'R12': 12, 'R13': 13, 'R14': 14, 'R15': 15, 'SCREEN': 16384, 'KBD': 24576}
def add_ent... |
A,B = map(int, input().split())
#A,B = 4, 10
if A > B :
print('>')
elif A < B :
print('<')
else:
print('==')
| (a, b) = map(int, input().split())
if A > B:
print('>')
elif A < B:
print('<')
else:
print('==') |
# @Time: 2022/4/13 11:29
# @Author: chang liu
# @Email: chang_liu_tamu@gmail.com
# @File:LFU.py
class Node:
def __init__(self, key=None, val=None):
self.val = val
self.key = key
self.f = 1
self.left = None
self.right = None
class DLL:
def __init__(self):
self.... | class Node:
def __init__(self, key=None, val=None):
self.val = val
self.key = key
self.f = 1
self.left = None
self.right = None
class Dll:
def __init__(self):
self.size = 0
self.head = node()
self.tail = node()
self.head.left = self.tail... |
# -*- coding: utf-8 -*-
# @Time: 2020/7/16 11:36
# @Author: GraceKoo
# @File: interview_7.py
# @Desc: https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qr
# u=%2Fta%2Fcoding-interviews%2Fquestion-ranking
class Solution:
def fib(self, N: int) -> int:
... | class Solution:
def fib(self, N: int) -> int:
if N <= 1:
return N
f_dict = {0: 0, 1: 1}
for i in range(2, N):
f_dict[i] = f_dict[i - 1] + f_dict[i - 2]
return f_dict[N - 1]
so = solution()
print(so.fib(4)) |
#!/usr/bin/python3
def square_matrix_simple(matrix=[]):
if matrix:
new = []
for rows in matrix:
new.append([n ** 2 for n in rows])
return new
| def square_matrix_simple(matrix=[]):
if matrix:
new = []
for rows in matrix:
new.append([n ** 2 for n in rows])
return new |
# Adaptive Card Design Schema for a sample form.
# To learn more about designing and working with buttons and cards,
# checkout https://developer.webex.com/docs/api/guides/cards
BUSY_CARD_CONTENT = {
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.2",
... | busy_card_content = {'$schema': 'http://adaptivecards.io/schemas/adaptive-card.json', 'type': 'AdaptiveCard', 'version': '1.2', 'body': [{'type': 'ColumnSet', 'columns': [{'type': 'Column', 'width': 1, 'items': [{'type': 'Image', 'url': 'https://i.postimg.cc/2jMv5kqt/AS89975.jpg', 'size': 'Stretch'}]}, {'type': 'Column... |
# Map by afffsdd
# A map with four corners, with bots spawning in each of them.
# flake8: noqa
# TODO: Format this file.
{'spawn': [(1, 1), (14, 1), (15, 1), (16, 1), (17, 1), (1, 2), (1, 3), (1, 4), (17, 14), (17, 15), (17, 16), (1, 17), (2, 17), (3, 17), (4, 17), (17, 17)], 'obstacle': [(0, 0), (1, 0), (2, 0), (3, 0)... | {'spawn': [(1, 1), (14, 1), (15, 1), (16, 1), (17, 1), (1, 2), (1, 3), (1, 4), (17, 14), (17, 15), (17, 16), (1, 17), (2, 17), (3, 17), (4, 17), (17, 17)], 'obstacle': [(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), (15, 0), (16, 0), (17, 0),... |
# MACRO - calculate precision and recall for every class,
# then take their weigted sum and calculate ONE f1 score
# MICRO - calculate f1 scores for each class and take their weighted sum
def f1_score(precision, recall):
f = 0 if precision + recall == 0 \
else 2 * precision * recall / (precision + recall)
... | def f1_score(precision, recall):
f = 0 if precision + recall == 0 else 2 * precision * recall / (precision + recall)
return f
def main(k, confusion_matrix):
num_samples = [sum(confusion_matrix[idx]) for idx in range(k)]
weights = [s / sum(num_samples) for s in num_samples]
precisions = []
recal... |
name = "harry"
print(name[0])
# List
names = ["Harry", "Ron", "Hermione"]
print(names[0])
# Tuples
coordinateX = 10.0
coordinateY = 20.0
coordinate = (10.0,20.0)
print(coordinate) | name = 'harry'
print(name[0])
names = ['Harry', 'Ron', 'Hermione']
print(names[0])
coordinate_x = 10.0
coordinate_y = 20.0
coordinate = (10.0, 20.0)
print(coordinate) |
#!/usr/bin/env python
print (' ')
nome = input('Digite seu nome: ')
#Mensagem
print (' ')
print (f'Seja bem-vindo Sr(a) {nome}, Obrigado por vir!')
print (' ')
| print(' ')
nome = input('Digite seu nome: ')
print(' ')
print(f'Seja bem-vindo Sr(a) {nome}, Obrigado por vir!')
print(' ') |
#latin square
num=int(input("Enter the number of rows:="))
for i in range(1,num+1):
r=i #set the first roew element
for j in range(1,num+1):
print(r,end='\t')
if r==num:
r=1
else:
r=r+1
print()
| num = int(input('Enter the number of rows:='))
for i in range(1, num + 1):
r = i
for j in range(1, num + 1):
print(r, end='\t')
if r == num:
r = 1
else:
r = r + 1
print() |
if (isWindVpDefined == 1):
evapoTranspiration = evapoTranspirationPenman
else:
evapoTranspiration = evapoTranspirationPriestlyTaylor
| if isWindVpDefined == 1:
evapo_transpiration = evapoTranspirationPenman
else:
evapo_transpiration = evapoTranspirationPriestlyTaylor |
def add_time(start: str, duration: str, day: str = None) -> str:
days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
start_lst = list(map(int, start[:-3].split(':')))
duration_lst = list(map(int, duration.split(':')))
total_min = start_lst[1] + duration_lst[1]
extr... | def add_time(start: str, duration: str, day: str=None) -> str:
days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
start_lst = list(map(int, start[:-3].split(':')))
duration_lst = list(map(int, duration.split(':')))
total_min = start_lst[1] + duration_lst[1]
extra_h... |
#! /usr/bin/env python3
# Type of variable: Number
a, b = 5, 10
print(a, b)
a, b = b, a
print(a, b)
# Type of variable: List
myList = [1, 2, 3, 4, 5]
print("Initial Array :", myList)
myList[0], myList[1] = myList[1], myList[0]
print("Swapped Array :", myList)
| (a, b) = (5, 10)
print(a, b)
(a, b) = (b, a)
print(a, b)
my_list = [1, 2, 3, 4, 5]
print('Initial Array :', myList)
(myList[0], myList[1]) = (myList[1], myList[0])
print('Swapped Array :', myList) |
def up_egcd(m,n):
#Assume m>n
if n>m:
m,n=n,m
if m%n==0:
return n
else:
return up_egcd(n,m%n)
print(up_egcd(int(input('Number 1\n')),int(input('Number 2\n'))))
| def up_egcd(m, n):
if n > m:
(m, n) = (n, m)
if m % n == 0:
return n
else:
return up_egcd(n, m % n)
print(up_egcd(int(input('Number 1\n')), int(input('Number 2\n')))) |
inp = open('input.txt').read().split(", ") # Reading file
coord = (0, 0) # Setting original coordinates
p_dir = 0 # Setting original direction (north)
seen = set()
for instr in inp:
dir = instr[0]
step = int(instr[1:])
if dir == "R":
p_dir = p_dir + 1
if p_dir == 4:
p_dir = 0... | inp = open('input.txt').read().split(', ')
coord = (0, 0)
p_dir = 0
seen = set()
for instr in inp:
dir = instr[0]
step = int(instr[1:])
if dir == 'R':
p_dir = p_dir + 1
if p_dir == 4:
p_dir = 0
elif dir == 'L':
if p_dir == 0:
p_dir = 4
p_dir = p_di... |
class Human(object):
def __init__(self, world=None, age=20):
self.maxAge = 50
self.age = age
self.alive = True
self.world = world
def update(self):
self.age += 1
if self.age > self.maxAge:
self.alive = False
def get_age(self):
return sel... | class Human(object):
def __init__(self, world=None, age=20):
self.maxAge = 50
self.age = age
self.alive = True
self.world = world
def update(self):
self.age += 1
if self.age > self.maxAge:
self.alive = False
def get_age(self):
return sel... |
answerDict = {
"New York" : "albany",
"California" : "sacramento",
"Alabama" : "montgomery",
"Ohio": "columbus",
"Utah": "salt lake city"
}
def checkAnswer(answer):
resultsDict = {}
for k,v in answer.items():
if answerDict[k] == v:
resultsDict[k] = True
else:
resultsDict... | answer_dict = {'New York': 'albany', 'California': 'sacramento', 'Alabama': 'montgomery', 'Ohio': 'columbus', 'Utah': 'salt lake city'}
def check_answer(answer):
results_dict = {}
for (k, v) in answer.items():
if answerDict[k] == v:
resultsDict[k] = True
else:
resultsDic... |
# this will create a 60 GB dummy asset file for testing the upload via
# the admin GUI.
LARGE_FILE_SIZE = 60 * 1024**3 # this is 60 GB
with open("xxxxxxl_asset_file.zip", "wb") as dummy_file:
dummy_file.seek(int(LARGE_FILE_SIZE) - 1)
dummy_file.write(b"\0")
| large_file_size = 60 * 1024 ** 3
with open('xxxxxxl_asset_file.zip', 'wb') as dummy_file:
dummy_file.seek(int(LARGE_FILE_SIZE) - 1)
dummy_file.write(b'\x00') |
class Solution:
def calculate(self, s: str) -> int:
stack = []
zero = ord('0')
operand = 0
res = 0
sign = 1
for ch in s:
if ch.isdigit():
operand = operand * 10 + ord(ch) - zero
elif ch == '+':
res += sign * oper... | class Solution:
def calculate(self, s: str) -> int:
stack = []
zero = ord('0')
operand = 0
res = 0
sign = 1
for ch in s:
if ch.isdigit():
operand = operand * 10 + ord(ch) - zero
elif ch == '+':
res += sign * ope... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Requires python 3.6+
#######################################################################################################################
# Global variables
# Can be reassigned by the settings from the configuration file
##############################################... | config_path = 'gitmon.conf'
data_path = 'data.json'
update_interval = 0
github_base_url = 'https://api.github.com/repos'
app_logs_type = 'console'
app_logs_file = 'gitmon.log'
logger = None
options = {} |
def swap(i, j, arr):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def quicksort(arr, low, high):
if(low < high):
p = partition(arr, low, high);
quicksort(arr, low, p-1);
quicksort(arr, p+1, high);
def partition(arr, low, high):
pivot = arr[low]
i = low
j = high
while(i < j):
while(arr[i] <= pivot and i... | def swap(i, j, arr):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def quicksort(arr, low, high):
if low < high:
p = partition(arr, low, high)
quicksort(arr, low, p - 1)
quicksort(arr, p + 1, high)
def partition(arr, low, high):
pivot = arr[low]
i = low
j = high
w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.