content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
X = int(input())
Y = int(input())
soma = 0
if X > Y:
troca = Y
Y = X
X = troca
sam = X
while sam <= Y:
if sam%13 != 0:
soma = soma + sam
sam += 1
print(soma)
| x = int(input())
y = int(input())
soma = 0
if X > Y:
troca = Y
y = X
x = troca
sam = X
while sam <= Y:
if sam % 13 != 0:
soma = soma + sam
sam += 1
print(soma) |
pMMO_dna_seq = 'ATGAAAACTATTAAAGATAGAATTGCTAAATGGTCTGCTATTGGTTTGTTGTCTGCTGTTGCTGCTACTGCTTTTTATGCTCCATCTGCTTCTGCTCATGGTGAAAAATCTCAAGCTGCTTTTATGAGAATGAGGACTATTCATTGGTATGACTTATCTTGGTCTAAGGAAAAGGTTAAAATAAACGAAACTGTTGAGATTAAAGGTAAATTTCATGTTTTTGAAGGTTGGCCTGAAACTGTTGATGAACCTGATGTTGCTTTTTTGAATGTTGGTATGCCTGGTCCTGTTTTTATTAGAAAAG... | p_mmo_dna_seq = 'ATGAAAACTATTAAAGATAGAATTGCTAAATGGTCTGCTATTGGTTTGTTGTCTGCTGTTGCTGCTACTGCTTTTTATGCTCCATCTGCTTCTGCTCATGGTGAAAAATCTCAAGCTGCTTTTATGAGAATGAGGACTATTCATTGGTATGACTTATCTTGGTCTAAGGAAAAGGTTAAAATAAACGAAACTGTTGAGATTAAAGGTAAATTTCATGTTTTTGAAGGTTGGCCTGAAACTGTTGATGAACCTGATGTTGCTTTTTTGAATGTTGGTATGCCTGGTCCTGTTTTTATTAGAAAA... |
c = int(input('digite o primeiro numero: '))
b = int(input('digite o segundo numero: '))
a = int(input('digite o terceiro numero: '))
cores= {'vermelho': '\033[0;31m',
'azul' : '\033[1;34m',
'zero': '\033[m' }
# qual o maior
maior = a
if b > c and b > a:
maior = b
if c > b and c > a:
maior = c
p... | c = int(input('digite o primeiro numero: '))
b = int(input('digite o segundo numero: '))
a = int(input('digite o terceiro numero: '))
cores = {'vermelho': '\x1b[0;31m', 'azul': '\x1b[1;34m', 'zero': '\x1b[m'}
maior = a
if b > c and b > a:
maior = b
if c > b and c > a:
maior = c
print('O maior valor foi {}{}{}'.... |
class ACCOUNTS():
def __init__(self):
self.CodeChef = {
"username": "username",
"password": "password"
}
self.Hackerrank = {
"username": "username",
"password": "password",
"tracks": ["python"]
# Available (... | class Accounts:
def __init__(self):
self.CodeChef = {'username': 'username', 'password': 'password'}
self.Hackerrank = {'username': 'username', 'password': 'password', 'tracks': ['python']}
def get_accounts(self):
return vars(self) |
# Source and destination file names.
test_source = "data/math.txt"
test_destination = "math_output_html.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
parser_name = "rst"
writer_name = "html"
# Extra setting
settings_overrides['math_output'] = 'HTML'
settings_overrides['stylesheet_path... | test_source = 'data/math.txt'
test_destination = 'math_output_html.html'
reader_name = 'standalone'
parser_name = 'rst'
writer_name = 'html'
settings_overrides['math_output'] = 'HTML'
settings_overrides['stylesheet_path'] = '../docutils/writers/html4css1/html4css1.css, ../docutils/writers/html4css1/math.css ' |
def test_valid(cldf_dataset, cldf_logger):
assert cldf_dataset.validate(log=cldf_logger)
def test_parameters(cldf_dataset):
assert len(list(cldf_dataset["ParameterTable"])) == 100
def test_languages(cldf_dataset):
assert len(list(cldf_dataset["LanguageTable"])) > 4000
| def test_valid(cldf_dataset, cldf_logger):
assert cldf_dataset.validate(log=cldf_logger)
def test_parameters(cldf_dataset):
assert len(list(cldf_dataset['ParameterTable'])) == 100
def test_languages(cldf_dataset):
assert len(list(cldf_dataset['LanguageTable'])) > 4000 |
description = 'setup for the status monitor'
group = 'special'
_expcolumn = Column(
Block('Experiment', [
BlockRow(
# Field(name='Proposal', key='exp/proposal', width=7),
# Field(name='Title', key='exp/title', width=20,
# istext=True, maxlen=20),
Field(name... | description = 'setup for the status monitor'
group = 'special'
_expcolumn = column(block('Experiment', [block_row(field(name='Current status', key='exp/action', width=40, istext=True, maxlen=40), field(name='Data file', key='exp/lastpoint'))]))
_sampletable = column(block('Sample table', [block_row(field(dev='omgs')), ... |
def shellSort(alist):
gap = len(alist) // 2
while gap > 0:
for i in range(gap, len(alist)):
val = alist[i]
j = i
while j >= gap and alist[j - gap] > val:
alist[j] = alist[j - gap]
j -= gap
alist[j] = val
gap //= 2
| def shell_sort(alist):
gap = len(alist) // 2
while gap > 0:
for i in range(gap, len(alist)):
val = alist[i]
j = i
while j >= gap and alist[j - gap] > val:
alist[j] = alist[j - gap]
j -= gap
alist[j] = val
gap //= 2 |
#!/usr/bin/env python3
def foo():
a = 10
# infer that b is an int
b = a
assert b == 10
print(b)
if __name__ == "__main__":
foo()
| def foo():
a = 10
b = a
assert b == 10
print(b)
if __name__ == '__main__':
foo() |
x="There are %d types of people."%10
binary="binary"
do_not="don't"
y="Those who know %s and those who %s."%(binary,do_not)
print(x)
print(y)
print("I said: '%s'."%y)
hilarious=False
joke_evaluation="Isn't that joke so funny?! %r"
print (joke_evaluation % hilarious)
w="This is the left side of ..."
e="a string with a r... | x = 'There are %d types of people.' % 10
binary = 'binary'
do_not = "don't"
y = 'Those who know %s and those who %s.' % (binary, do_not)
print(x)
print(y)
print("I said: '%s'." % y)
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print(joke_evaluation % hilarious)
w = 'This is the left side of ...'
... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
ANSI_COLORS ... | ansi_colors = {'emacs': {'black': '#000000', 'red': '#800000', 'green': '#005100', 'yellow': '#abab67', 'blue': '#151d51', 'magenta': '#510051', 'cyan': '#105151', 'white': '#ffffff', 'brightBlack': '#555555', 'brightRed': '#c80000', 'brightGreen': '#00aa00', 'brightYellow': '#cbcb7b', 'brightBlue': '#3c51e8', 'brightM... |
def printVal(state, name):
val = state[name]
print("%s:" % state.fuzzy_names[name], val)
def print_all(state):
printVal(state, "var_default")
printVal(state, "var_default_override")
printVal(state, "var_default_override_twice")
printVal(state, "var_default_override_twice_and_cli")
def regis... | def print_val(state, name):
val = state[name]
print('%s:' % state.fuzzy_names[name], val)
def print_all(state):
print_val(state, 'var_default')
print_val(state, 'var_default_override')
print_val(state, 'var_default_override_twice')
print_val(state, 'var_default_override_twice_and_cli')
def reg... |
class Node():
def __init__(self,data):
self.data=data
self.ref=None
class LinkedList():
def __init__(self):
self.head=None
def Print_ll(self):
n=self.head
if n is None:
print("LinkedList is empty")
else:
while n is not None:
... | class Node:
def __init__(self, data):
self.data = data
self.ref = None
class Linkedlist:
def __init__(self):
self.head = None
def print_ll(self):
n = self.head
if n is None:
print('LinkedList is empty')
else:
while n is not None:
... |
#!/usr/bin/env python3
#encoding=utf-8
#------------------------------------------------
# Usage: python3 3-desc-state-inst.py
# Description: descriptor for attribute intercept
#------------------------------------------------
class InstState: # Using instance state, (object) in 2.X
def __get__(self, inst... | class Inststate:
def __get__(self, instance, owner):
print('InstState get')
return instance._X * 10
def __set__(self, instance, value):
print('InstState set')
instance._X = value
class Calcattrs:
x = inst_state()
y = 3
def __init__(self):
self._X = 2
... |
bind = "0.0.0.0:5000"
backlog = 2048
workers = 1
worker_class = "sync"
threads = 16
spew = False
reload = True
loglevel = "debug"
| bind = '0.0.0.0:5000'
backlog = 2048
workers = 1
worker_class = 'sync'
threads = 16
spew = False
reload = True
loglevel = 'debug' |
for t in range(int(input())):
n=int(input())
if n%2==0:
print(int(n/2-1))
else:
print(int(n//2)) | for t in range(int(input())):
n = int(input())
if n % 2 == 0:
print(int(n / 2 - 1))
else:
print(int(n // 2)) |
value1 = int(input()); value2 = value1//100
if value1 % 2==0 and value2 % 2==0:
print("Even")
elif value1 % 2==0 and value2 % 2==1:
print("Even Odd")
elif value1 % 2==1 and value2 % 2==1:
print("Odd")
elif value1 % 2==1 and value2 % 2==0:
print("Odd Even")
| value1 = int(input())
value2 = value1 // 100
if value1 % 2 == 0 and value2 % 2 == 0:
print('Even')
elif value1 % 2 == 0 and value2 % 2 == 1:
print('Even Odd')
elif value1 % 2 == 1 and value2 % 2 == 1:
print('Odd')
elif value1 % 2 == 1 and value2 % 2 == 0:
print('Odd Even') |
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
money = [0, 0, 0]
for x in bills:
if x == 5:
money[0] += 1
if x == 10:
if money[0] >= 1:
money[1] += 1
money[0] -= 1
... | class Solution:
def lemonade_change(self, bills: List[int]) -> bool:
money = [0, 0, 0]
for x in bills:
if x == 5:
money[0] += 1
if x == 10:
if money[0] >= 1:
money[1] += 1
money[0] -= 1
e... |
config = {}
with open("config.txt", "r") as f:
lines = f.readlines()
for line in lines:
key, value = line.split("=")
value = value.replace("\n", "")
config[key] = value
print(f"Added key {key} with value {value}")
user_key = input("Which key would you like to see? ")
if user_ke... | config = {}
with open('config.txt', 'r') as f:
lines = f.readlines()
for line in lines:
(key, value) = line.split('=')
value = value.replace('\n', '')
config[key] = value
print(f'Added key {key} with value {value}')
user_key = input('Which key would you like to see? ')
if user_ke... |
# A little bit of molecular biology
# Codons are non-overlapping triplets of nucleotides.
# ATG CCC CTG GTA ... - this corresponds to four codons; spaces added for emphasis
# The start codon is 'ATG'
# Stop codons can be 'TGA' , 'TAA', or 'TAG', but they must be 'in frame' with the start codon. The first stop codon ... | dna = 'GGGATGTTTGGGCCCTACGGGCCCTGATCGGCT'
def start_codon_index(seq):
start_idx = seq.find('ATG')
return start_idx
def stop_codon_index(seq, start_codon):
stop_idx = -1
codon_length = 3
search_start = start_codon + codon_length
search_stop = len(seq)
for i in range(search_start, search_sto... |
# REMISS
for i in range(int(input())):
A,B = map(int,input().split())
if A>B: print(str(A) + " " + str(A+B))
else: print(str(B) + " " + str(A+B)) | for i in range(int(input())):
(a, b) = map(int, input().split())
if A > B:
print(str(A) + ' ' + str(A + B))
else:
print(str(B) + ' ' + str(A + B)) |
#!/usr/bin/env python3
def hello(**kwargs):
print(f'Hello')
if __name__ == '__main__':
hello(hello())
| def hello(**kwargs):
print(f'Hello')
if __name__ == '__main__':
hello(hello()) |
#!/usr/bin/env python3
with open("dnsservers.txt", "r") as dnsfile:
for svr in dnsfile:
svr = svr.rstrip('\n')
if svr.endswith('org'):
with open("org-domain.txt", "a") as srvfile:
srvfile.write(svr + "\n")
elif svr.endswith('com'):
with open("com-dom... | with open('dnsservers.txt', 'r') as dnsfile:
for svr in dnsfile:
svr = svr.rstrip('\n')
if svr.endswith('org'):
with open('org-domain.txt', 'a') as srvfile:
srvfile.write(svr + '\n')
elif svr.endswith('com'):
with open('com-domain.txt', 'a') as srvfile... |
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
res = 0
q = deque([root])
while q:
node = q.popleft()
if node.left:
if not node.left.left and not node.left.right:
res += no... | class Solution:
def sum_of_left_leaves(self, root: TreeNode) -> int:
if not root:
return 0
res = 0
q = deque([root])
while q:
node = q.popleft()
if node.left:
if not node.left.left and (not node.left.right):
res... |
'''
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddd... | """
Given a string s, the power of the string is the maximum length of a non-empty substring that contains only one unique character.
Return the power of the string.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddd... |
MAP_HEIGHT_MIN = 20
MAP_HEIGHT_MAX = 50
MAP_WIDTH_MIN = 20
MAP_WIDTH_MAX = 50
MAP_KARBONITE_MIN = 0
MAP_KARBONITE_MAX = 50
ASTEROID_ROUND_MIN = 10
ASTEROID_ROUND_MAX = 20
ASTEROID_KARB_MIN = 20
ASTEROID_KARB_MAX = 100
ORBIT_FLIGHT_MIN = 50
ORBIT_FLIGHT_MAX = 200
ROUND_LIMIT = 1000
def validate_map_dims(h, w):
ret... | map_height_min = 20
map_height_max = 50
map_width_min = 20
map_width_max = 50
map_karbonite_min = 0
map_karbonite_max = 50
asteroid_round_min = 10
asteroid_round_max = 20
asteroid_karb_min = 20
asteroid_karb_max = 100
orbit_flight_min = 50
orbit_flight_max = 200
round_limit = 1000
def validate_map_dims(h, w):
retu... |
string = input().split(", ")
beggars = int(input())
beggars_list = []
for x in range(0, beggars):
temp = string[x::beggars]
for j in range(0, len(temp)):
temp[j] = int(temp[j])
beggars_list.append(sum(temp))
print(beggars_list) | string = input().split(', ')
beggars = int(input())
beggars_list = []
for x in range(0, beggars):
temp = string[x::beggars]
for j in range(0, len(temp)):
temp[j] = int(temp[j])
beggars_list.append(sum(temp))
print(beggars_list) |
# python to locate 1 in a 2D array
#below save it into a dictionary
# python to locate 1 in a 2D array
def check_zero(array1):
d = {}
print("array index zeros at:")
for i in range(len(array1)):
index = [k for k, v in enumerate(array1[i]) if v == 0]
d[i] = index
#print(i, index)
... | def check_zero(array1):
d = {}
print('array index zeros at:')
for i in range(len(array1)):
index = [k for (k, v) in enumerate(array1[i]) if v == 0]
d[i] = index
return d
array1 = [[1, 1, 0, 0], [0, 0, 1, 1], [0, 1, 0, 1]]
array2 = [[1, 1, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 1, 0, 1]]
print... |
name = "Sharalanda"
age = 10
hobbies = ["draw", "swim", "dance"]
address = {"city": "Sebastopol", "Post Code": 1234, "country": "Enchantia"}
print("My name is", name)
print("I am", age, "years old")
print("My favourite hobbie is", hobbies[0])
print("I live in", address["city"])
| name = 'Sharalanda'
age = 10
hobbies = ['draw', 'swim', 'dance']
address = {'city': 'Sebastopol', 'Post Code': 1234, 'country': 'Enchantia'}
print('My name is', name)
print('I am', age, 'years old')
print('My favourite hobbie is', hobbies[0])
print('I live in', address['city']) |
# Copyright (c) 2018 Javier M. Mellid <jmunhoz@igalia.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... | class S3Owner:
def __init__(self, xid, display_name, id):
self.xid = xid
self.display_name = display_name
self.id = id
def __str__(self):
return '{} - {} - {}'.format(self.xid, self.display_name, self.id)
class S3Object:
pass
class S3Version(S3Object):
xid = 0
las... |
#Create a list using []
a = [1,2,3,7,66]
#print the list using print() function
print(a)
#Access using index using a[0], a[1], ....
print(a[2])
#Changing the value of the list
a[0] = 777
print(a)
#We can create a list with items of different type
b = [77,"Root",False,6.9]
print(b)
#List Slicing
friends = ["Root","... | a = [1, 2, 3, 7, 66]
print(a)
print(a[2])
a[0] = 777
print(a)
b = [77, 'Root', False, 6.9]
print(b)
friends = ['Root', 'Groot', 'Sam', 'Alex', 99]
print(friends[0:3])
print(friends[-4:]) |
singular = [
'this','as','is','thesis','hypothesis','less','obvious','us','yes','cos',
'always','perhaps','alias','plus','apropos',
'was','its','bus','his','is','us',
'this','thus','axis','bias','minus','basis',
'praxis','status','modulus','analysis',
'aparatus'
]
invariable = [ #frozen_li... | singular = ['this', 'as', 'is', 'thesis', 'hypothesis', 'less', 'obvious', 'us', 'yes', 'cos', 'always', 'perhaps', 'alias', 'plus', 'apropos', 'was', 'its', 'bus', 'his', 'is', 'us', 'this', 'thus', 'axis', 'bias', 'minus', 'basis', 'praxis', 'status', 'modulus', 'analysis', 'aparatus']
invariable = ['a', 'an', 'all',... |
#
# PySNMP MIB module JUNIPER-MOBILE-GATEWAY-SGW-GTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-MOBILE-GATEWAY-SGW-GTP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:00:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) ... |
if __name__ == '__main__':
n = int(input())
s = set()
for i in range (n):
s.add(input())
print((len(s)))
| if __name__ == '__main__':
n = int(input())
s = set()
for i in range(n):
s.add(input())
print(len(s)) |
# -*- coding:utf-8 -*-
# @Time:2020/6/15 11:38
# @Author:TimVan
# @File:leetcode.py
# @Software:PyCharm
# Definition for singly-linked list.
# for j in range(10, 5, -1):
# print(j)
print('a'.find(' '))
| print('a'.find(' ')) |
def main():
a = ["a", 1, "5", 2.3, 1.2j]
some_condition = True
for x in a:
# If it's all isinstance, we can use a type switch
if isinstance(x, (str, float)):
print("String or float!")
elif isinstance(x, int):
print("Integer!")
else:
print("... | def main():
a = ['a', 1, '5', 2.3, 1.2j]
some_condition = True
for x in a:
if isinstance(x, (str, float)):
print('String or float!')
elif isinstance(x, int):
print('Integer!')
else:
print('Dunno!')
print(':)')
if isinstance(x, s... |
___assertIs(isinstance(True, bool), True)
___assertIs(isinstance(False, bool), True)
___assertIs(isinstance(True, int), True)
___assertIs(isinstance(False, int), True)
___assertIs(isinstance(1, bool), False)
___assertIs(isinstance(0, bool), False)
| ___assert_is(isinstance(True, bool), True)
___assert_is(isinstance(False, bool), True)
___assert_is(isinstance(True, int), True)
___assert_is(isinstance(False, int), True)
___assert_is(isinstance(1, bool), False)
___assert_is(isinstance(0, bool), False) |
# Copyright (c) 2013 Huan Do, http://huan.do
class Declaration(object):
def __init__(self, name):
self.name = name
self.delete = False
self._conditional = None
@property
def conditional(self):
assert self._conditional is not None
return self.delete or self._conditio... | class Declaration(object):
def __init__(self, name):
self.name = name
self.delete = False
self._conditional = None
@property
def conditional(self):
assert self._conditional is not None
return self.delete or self._conditional
def generator():
_ = '_'
while T... |
description = 'Verify the user can add an action to the teardown'
pages = ['common',
'index',
'tests',
'test_builder']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
index.create_access_project('test')
common.navigate_menu('Tests')
tests.create_access_ra... | description = 'Verify the user can add an action to the teardown'
pages = ['common', 'index', 'tests', 'test_builder']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
index.create_access_project('test')
common.navigate_menu('Tests')
tests.create_access_random_test()
def test(data):
... |
def process(record):
ids = (record.get('idsurface', '') or '').split(' ')
if len(ids) > 4:
return {'language': record['language'],
'longitude': float(record['longitude'] or 0),
'latitude': float(record['latitude'] or 0),
'idsurface': ids}
| def process(record):
ids = (record.get('idsurface', '') or '').split(' ')
if len(ids) > 4:
return {'language': record['language'], 'longitude': float(record['longitude'] or 0), 'latitude': float(record['latitude'] or 0), 'idsurface': ids} |
a = 2 ** 50
b = 2 ** 50 * 3
c = 2 ** 50 * 3 - 1000
d = 400 / 2 ** 50 + 50
print(a,b,c,d) | a = 2 ** 50
b = 2 ** 50 * 3
c = 2 ** 50 * 3 - 1000
d = 400 / 2 ** 50 + 50
print(a, b, c, d) |
G = 6.67408e-11 # N-m2/kg2
#
# Normalize the constants such that m, r, t and v are of the order 10^1.
#
def get_normalization_constants_alphacentauri():
# Normalize the masses to the mass of our sun
m_nd = 1.989e+30 # kg
# Normalize distances to the distance between Alpha Centauri A and Alpha Centa... | g = 6.67408e-11
def get_normalization_constants_alphacentauri():
m_nd = 1.989e+30
r_nd = 5326000000000.0
v_nd = 30000
t_nd = 79.91 * 365 * 24 * 3600 * 0.51
return (m_nd, r_nd, v_nd, t_nd)
def get_normalization_constants_earthsun():
m_nd = 1.989e+30
r_nd = 149470000000.0
v_nd = 29780.0
... |
# Time: 0.72 s
movies = []
for _ in range(int(input())):
movies.append(tuple(map(int, input().split())))
movies.sort(key=lambda x: x[1])
last_end_time = 0
movie_count = 0
for start_time, end_time in movies:
if start_time >= last_end_time:
last_end_time = end_time
movie_count += 1
print(movi... | movies = []
for _ in range(int(input())):
movies.append(tuple(map(int, input().split())))
movies.sort(key=lambda x: x[1])
last_end_time = 0
movie_count = 0
for (start_time, end_time) in movies:
if start_time >= last_end_time:
last_end_time = end_time
movie_count += 1
print(movie_count) |
# 072220
# CodeSignal
# https://app.codesignal.com/arcade/intro/level-6/mCkmbxdMsMTjBc3Bm/solutions
def array_replace(inputArray, elemToReplace, substitutionElem):
# loop through input array
# if element = elemToReplace
# replace that element
for index,i in enumerate(inputArray):
if i == elemT... | def array_replace(inputArray, elemToReplace, substitutionElem):
for (index, i) in enumerate(inputArray):
if i == elemToReplace:
inputArray[index] = substitutionElem
return inputArray |
while True:
print('\n--- MULTIPLICATION TABLE ---')
num = int(input('Type a number integer: '))
if num < 0:
break
for c in range(1, 11):
print(f'{c} X {num} = {c*num}')
print('END PROGRAM') | while True:
print('\n--- MULTIPLICATION TABLE ---')
num = int(input('Type a number integer: '))
if num < 0:
break
for c in range(1, 11):
print(f'{c} X {num} = {c * num}')
print('END PROGRAM') |
def plot(width, height):
for j in range(height):
y = height - j - 1
print("y = {0:3} |".format(y), end="")
for x in range(width):
print("{0:3}".format(f(x,y)), end="")
print()
print(" +", end="")
for x in range(width):
print("---", end="")
prin... | def plot(width, height):
for j in range(height):
y = height - j - 1
print('y = {0:3} |'.format(y), end='')
for x in range(width):
print('{0:3}'.format(f(x, y)), end='')
print()
print(' +', end='')
for x in range(width):
print('---', end='')
prin... |
'''
Psuedo-joystick object for playback of recorded macros
'''
class PlaybackJoystick():
def __init__(self, playback_data):
self.playback_data = playback_data
self.t = 0
def setTime(self, t=0):
self.t = t
def getRawAxis(self, axis):
#TODO fix me, get correct index for ... | """
Psuedo-joystick object for playback of recorded macros
"""
class Playbackjoystick:
def __init__(self, playback_data):
self.playback_data = playback_data
self.t = 0
def set_time(self, t=0):
self.t = t
def get_raw_axis(self, axis):
index = self.t
if index < len(... |
default_app_config = "freight.apps.FreightConfig"
__version__ = "1.5.1"
__title__ = "Freight"
| default_app_config = 'freight.apps.FreightConfig'
__version__ = '1.5.1'
__title__ = 'Freight' |
words_file = open('wordlist.txt')
print("export const VALIDGUESSES6 = [")
for word in words_file.read().split('\n'):
word = word.strip()
if word.isalpha() and len(word) == 6:
print(' "%s",' % word.lower())
print("];") | words_file = open('wordlist.txt')
print('export const VALIDGUESSES6 = [')
for word in words_file.read().split('\n'):
word = word.strip()
if word.isalpha() and len(word) == 6:
print(' "%s",' % word.lower())
print('];') |
graph = {}
n = input().split(' ')
node, edge, start = map(int, n)
for i in range(edge):
edge_number = input().split(' ')
n1, n2 = map(int, edge_number)
if n1 not in graph:
graph[n1] = [n2]
elif n2 not in graph[n1]:
graph[n1].append(n2)
if n2 not in graph:
graph[n2] = [... | graph = {}
n = input().split(' ')
(node, edge, start) = map(int, n)
for i in range(edge):
edge_number = input().split(' ')
(n1, n2) = map(int, edge_number)
if n1 not in graph:
graph[n1] = [n2]
elif n2 not in graph[n1]:
graph[n1].append(n2)
if n2 not in graph:
graph[n2] = [n1]... |
#
# PySNMP MIB module TPLINK-COMMANDER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-COMMANDER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:16:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint) ... |
def hello(name):
return 'Hello ' + 'name'
def test_hello():
assert hello('name') == 'Hello name' | def hello(name):
return 'Hello ' + 'name'
def test_hello():
assert hello('name') == 'Hello name' |
#!/usr/bin/env python
class MatrixUtil:
@classmethod
def allocateMatrix(cls, numRows, numCols):
rv = [0.0] * numRows
for i in range(numRows):
rv[i] = [0.0] * numCols
return rv
@classmethod
def allocateMatrixAsRowMajorArray(cls, numRows, numCols):
return [0.... | class Matrixutil:
@classmethod
def allocate_matrix(cls, numRows, numCols):
rv = [0.0] * numRows
for i in range(numRows):
rv[i] = [0.0] * numCols
return rv
@classmethod
def allocate_matrix_as_row_major_array(cls, numRows, numCols):
return [0.0] * numRows * nu... |
with open("input.txt") as input_file:
lines = input_file.readlines()
result = 0
for line in lines:
print(line.strip(), result)
result += int(line.strip())
print(result)
| with open('input.txt') as input_file:
lines = input_file.readlines()
result = 0
for line in lines:
print(line.strip(), result)
result += int(line.strip())
print(result) |
#License: https://bit.ly/3oLErEI
def test(strs):
return [*map(len, strs)]
strs = ['cat', 'car', 'fear', 'center']
print("Original strings:")
print(strs)
print("Lengths of the said list of non-empty strings:")
print(test(strs))
strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
print("\nOriginal string... | def test(strs):
return [*map(len, strs)]
strs = ['cat', 'car', 'fear', 'center']
print('Original strings:')
print(strs)
print('Lengths of the said list of non-empty strings:')
print(test(strs))
strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
print('\nOriginal strings:')
print(strs)
print('Lengths of the... |
# Write a Python program to compute the greatest common divisor (GCD) of two positive integers.
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
a1 = []
a2 = []
a3 = []
for i in range(1, n1 + 1):
if n1 % i == 0:
a1.append(i)
for i in range(1, n2 + 1):
if n2 % ... | n1 = int(input('Enter the first number: '))
n2 = int(input('Enter the second number: '))
a1 = []
a2 = []
a3 = []
for i in range(1, n1 + 1):
if n1 % i == 0:
a1.append(i)
for i in range(1, n2 + 1):
if n2 % i == 0:
a2.append(i)
for i in a1:
if i in a2:
a3.append(i)
print(max(a3)) |
# Only used for PyTorch open source BUCK build
IGNORED_ATTRIBUTE_PREFIX = [
"apple",
"fbobjc",
"windows",
"fbandroid",
"macosx",
]
IGNORED_ATTRIBUTES = [
"feature",
"platforms",
]
def filter_attributes(kwgs):
keys = list(kwgs.keys())
# drop unncessary attributes
for key in ke... | ignored_attribute_prefix = ['apple', 'fbobjc', 'windows', 'fbandroid', 'macosx']
ignored_attributes = ['feature', 'platforms']
def filter_attributes(kwgs):
keys = list(kwgs.keys())
for key in keys:
if key in IGNORED_ATTRIBUTES:
kwgs.pop(key)
else:
for invalid_prefix in I... |
def media_suicida (mediaProvas, mediaTrabalhos):
if mediaProvas >= 5 and mediaTrabalhos >= 5:
return mediaProvas * 0.6 + mediaTrabalhos * 0.4
return min(mediaProvas, mediaTrabalhos)
notasProva = []
notasTrabalho = []
quantidadeProva = int(input("Quantidade de provas: "))
for item in range(quantidade... | def media_suicida(mediaProvas, mediaTrabalhos):
if mediaProvas >= 5 and mediaTrabalhos >= 5:
return mediaProvas * 0.6 + mediaTrabalhos * 0.4
return min(mediaProvas, mediaTrabalhos)
notas_prova = []
notas_trabalho = []
quantidade_prova = int(input('Quantidade de provas: '))
for item in range(quantidadePr... |
print('Begin', __name__)
print('Defines fA')
def fA():
print('Inside fA')
if __name__ == "__main__":
print('Calls fA')
fA()
print('End', __name__)
| print('Begin', __name__)
print('Defines fA')
def f_a():
print('Inside fA')
if __name__ == '__main__':
print('Calls fA')
f_a()
print('End', __name__) |
def find_missing_number(sequence):
try:
numbers = sorted(int(word) for word in sequence.split(" ") if word)
except ValueError:
return 1
return next((i + 1 for i, n in enumerate(numbers) if i + 1 != n), 0) | def find_missing_number(sequence):
try:
numbers = sorted((int(word) for word in sequence.split(' ') if word))
except ValueError:
return 1
return next((i + 1 for (i, n) in enumerate(numbers) if i + 1 != n), 0) |
# Lucas Reicher Prompt #3 - Coding Journal #1
def main():
# Uses formatted strings to output the required info (result & type)
# Adds floats
x = 1.342 # float
y = 3.433 # float
z = x + y # float
float_sum_string = "Addition: {0} + {1} = {2} with type = {3}".format(str(x),str(y),str(z)... | def main():
x = 1.342
y = 3.433
z = x + y
float_sum_string = 'Addition: {0} + {1} = {2} with type = {3}'.format(str(x), str(y), str(z), str(type(z)))
print(float_sum_string)
x = 5
y = 2
z = x - y
float_difference_string = 'Subtraction: {0} - {1} = {2} with type = {3}'.format(str(x), ... |
# OpenWeatherMap API Key
weather_api_key = "e1067d92d6b631a16363bf4db3023b19"
# Google API Key
g_key = "AIzaSyA4RYdQ1nxoMTIW854C7wvVJMf0Qz5qjNk"
| weather_api_key = 'e1067d92d6b631a16363bf4db3023b19'
g_key = 'AIzaSyA4RYdQ1nxoMTIW854C7wvVJMf0Qz5qjNk' |
class DmsRequestError(Exception):
def __init__(self, error_message, status_code):
self.message = "Error requesting DMS API %s with code %s" \
% (error_message, status_code)
super(DmsRequestError, self).__init__(self.message)
| class Dmsrequesterror(Exception):
def __init__(self, error_message, status_code):
self.message = 'Error requesting DMS API %s with code %s' % (error_message, status_code)
super(DmsRequestError, self).__init__(self.message) |
class Keyword:
def __init__(self, keyword):
if keyword in ['add', 'find']:
self.value = keyword
else:
self.value = 'find'
| class Keyword:
def __init__(self, keyword):
if keyword in ['add', 'find']:
self.value = keyword
else:
self.value = 'find' |
# import datetime
# import logging
# logger = logging.getLogger(__name__)
# logger.setLevel(logging.INFO)
def run(event, context):
# current_time = datetime.datetime.now().time()
# name = context.function_name
# logger.info("Your cron function " + name + " ran at " + str(current_time))
return "hello ... | def run(event, context):
return 'hello world!' |
# coding: utf-8
class RurouniException(Exception):
pass
class ConfigException(RurouniException):
pass
class TokenBucketFull(RurouniException):
pass
class UnexpectedMetric(RurouniException):
pass | class Rurouniexception(Exception):
pass
class Configexception(RurouniException):
pass
class Tokenbucketfull(RurouniException):
pass
class Unexpectedmetric(RurouniException):
pass |
# Write a program that reads a word and prints all substrings, sorted by length. For
# example, if the user provides the input "rum" , the program prints
# r
# u
# m
# ru
# um
# rum
word = str(input("Enter a word: "))
wordLen = len(word)
subLen = 1
start = 0
for i in range(wordLen):
star... | word = str(input('Enter a word: '))
word_len = len(word)
sub_len = 1
start = 0
for i in range(wordLen):
start = 0
while start + subLen <= wordLen:
print(word[start:start + subLen])
start += 1
sub_len += 1 |
x = 100
y = 50
print('x=', x, 'y=', y)
| x = 100
y = 50
print('x=', x, 'y=', y) |
BASE_CASE = {
"model": {
"random_seed": 495279142,
"default_age_grid": "0 0.01917808 0.07671233 1 5 10 20 30 40 50 60 70 80 90 100",
"default_time_grid": "1990 1995 2000 2005 2010 2015 2016",
"add_calc_emr": "from_both",
"birth_prev": 0,
"ode_step_size": 5,
"m... | base_case = {'model': {'random_seed': 495279142, 'default_age_grid': '0 0.01917808 0.07671233 1 5 10 20 30 40 50 60 70 80 90 100', 'default_time_grid': '1990 1995 2000 2005 2010 2015 2016', 'add_calc_emr': 'from_both', 'birth_prev': 0, 'ode_step_size': 5, 'minimum_meas_cv': 0.2, 'rate_case': 'iota_pos_rho_zero', 'data_... |
#Write a function named "falling_distance" that accepts an object's falling time
#(in seconds) as an argument. The function should return the distance, in meters
#, that the object has fallen during the time interval.Write a program that
#calls the function in a loop that passes the values 1 through 10 as arguments
... | def main():
print("This program shows an object's fall distance (in meters) with each")
print('passing second from 1 to 10.')
print()
print('Time(s)\tDistance(m)')
print('--------------------')
for time in range(10 + 1):
distance = falling_distance(time)
print(time, '\t', format(... |
a=list(input().split(','))
st,num=[],[]
for i in a:
s1,n=i.split(':')
st.append(s1)
num.append(n)
print(st)
print(num)
for i in range(len(num)):
for j in range(i):
print(st[j])
| a = list(input().split(','))
(st, num) = ([], [])
for i in a:
(s1, n) = i.split(':')
st.append(s1)
num.append(n)
print(st)
print(num)
for i in range(len(num)):
for j in range(i):
print(st[j]) |
GitHubTarballPackage ('mono', 'mono-basic', '3.0', 'a74642af7f72d1012c87d82d7a12ac04a17858d5',
configure = './configure --prefix="%{prefix}"',
override_properties = { 'make': 'make' }
)
| git_hub_tarball_package('mono', 'mono-basic', '3.0', 'a74642af7f72d1012c87d82d7a12ac04a17858d5', configure='./configure --prefix="%{prefix}"', override_properties={'make': 'make'}) |
# Asking for height and weight input
height = float(input("What is your height in meters: "))
weight = float(input("What is your weight in kilograms: "))
# Calculating BMI (formula is weight/height^2)
bmi = str(round(weight/(height ** 2), 2))
# Printing BMI
print("Your BMI is " + bmi)
| height = float(input('What is your height in meters: '))
weight = float(input('What is your weight in kilograms: '))
bmi = str(round(weight / height ** 2, 2))
print('Your BMI is ' + bmi) |
# IMAGES #
# UI NAVIGATION #
img_addFriend = "add_friend.png"
img_allow = "allow.png"
img_allowFlash = "enableflash_0.png"
img_allowFlash1 = "enableflash_1.png"
img_allowFlash2 = "enableflash_2.png"
img_alreadyStarted = "alreadystarted.png"
img_alreadyStarted1 = "alreadystarted1.png"
img_backButton = "back_button.png... | img_add_friend = 'add_friend.png'
img_allow = 'allow.png'
img_allow_flash = 'enableflash_0.png'
img_allow_flash1 = 'enableflash_1.png'
img_allow_flash2 = 'enableflash_2.png'
img_already_started = 'alreadystarted.png'
img_already_started1 = 'alreadystarted1.png'
img_back_button = 'back_button.png'
img_beginning_game = '... |
class EfficiencyMeasurement():
# input_voltage = None
# input_current = None
# output_voltage = None
# output_current = None
# input_power = None
# output_power = None
# loss_power = None
# efficiency = None
def __init__(self, input_voltage: float, input_current: float,
... | class Efficiencymeasurement:
def __init__(self, input_voltage: float, input_current: float, output_voltage: float, output_current: float):
self.input_voltage = input_voltage
self.input_current = input_current
self.output_voltage = output_voltage
self.output_current = output_current
... |
class Y:
def __init__(self, v0):
self.v0 = v0
self.g = 9.81
def value(self, t):
return self.v0*t - 0.5*self.g*t**2
def formula(self):
return "v0*t - 0.5*g*t**2; v0=%g" % self.v0
| class Y:
def __init__(self, v0):
self.v0 = v0
self.g = 9.81
def value(self, t):
return self.v0 * t - 0.5 * self.g * t ** 2
def formula(self):
return 'v0*t - 0.5*g*t**2; v0=%g' % self.v0 |
class ATMOS(object):
'''
class ATMOS
- attributes:
- self defined
- methods:
- None
'''
def __init__(self,info):
self.info = info
for key in info.keys():
setattr(self, key, info[key])
def __repr__(self):
return 'Instance of class AT... | class Atmos(object):
"""
class ATMOS
- attributes:
- self defined
- methods:
- None
"""
def __init__(self, info):
self.info = info
for key in info.keys():
setattr(self, key, info[key])
def __repr__(self):
return 'Instance of class ATMOS' |
t=int(input())
if not (1 <= t <= 100000): exit(-1)
dp=[0]*100001
dp[3]=3
for i in range(4,100001):
if i%3==0 or i%7==0: dp[i]=i
dp[i]+=dp[i-1]
query=[*map(int,input().split())]
if len(query)!=t: exit(-1)
for i in query:
if not (10 <= int(i) <= 80000): exit(-1)
print(dp[int(i)])
succ=False
try: input(... | t = int(input())
if not 1 <= t <= 100000:
exit(-1)
dp = [0] * 100001
dp[3] = 3
for i in range(4, 100001):
if i % 3 == 0 or i % 7 == 0:
dp[i] = i
dp[i] += dp[i - 1]
query = [*map(int, input().split())]
if len(query) != t:
exit(-1)
for i in query:
if not 10 <= int(i) <= 80000:
exit(-1)... |
N = int(input())
A = list(map(int, input().split()))
ans = 0
for a in A:
if a > 10:
ans += a - 10
print(ans) | n = int(input())
a = list(map(int, input().split()))
ans = 0
for a in A:
if a > 10:
ans += a - 10
print(ans) |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "espcms")
whatweb.recog_from_file(pluginname, "templates/wap/cn/public/footer.html", "espcms")
| def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, 'espcms')
whatweb.recog_from_file(pluginname, 'templates/wap/cn/public/footer.html', 'espcms') |
vetor = []
entradaUsuario = int(input())
repetir = 1000
indice = 0
adicionar = 0
while(repetir > 0):
vetor.append(adicionar)
adicionar += 1
if(adicionar == entradaUsuario):
adicionar = 0
repetir -= 1
repetir = 1000
while(repetir>0):
repetir -= 1
print("N[{}] = {}".format(indice, vetor[indice]))
indic... | vetor = []
entrada_usuario = int(input())
repetir = 1000
indice = 0
adicionar = 0
while repetir > 0:
vetor.append(adicionar)
adicionar += 1
if adicionar == entradaUsuario:
adicionar = 0
repetir -= 1
repetir = 1000
while repetir > 0:
repetir -= 1
print('N[{}] = {}'.format(indice, vetor[in... |
# AUTHOR = PAUL KEARNEY
# DATE = 2018-02-05
# STUDENT ID = G00364787
# EXERCISE 03
#
# filename= gmit--exercise03--collatz--20180205d.py
#
# the Collatz conjecture
print("The COLLATZ CONJECTURE")
# define the variables
num = ""
x = 0
# obtain user input
num = input("A start nummber: ")
x = int(... | print('The COLLATZ CONJECTURE')
num = ''
x = 0
num = input('A start nummber: ')
x = int(num)
print('--Start of sequence.')
print(x)
while x != 1:
if x % 2 == 0:
x = x / 2
else:
x = x * 3 + 1
print(int(x))
print('--End of sequence') |
DEFAULT_TEXT_TYPE = "mrkdwn"
class BaseBlock:
def generate(self):
raise NotImplemented("Subclass missing generate implementation")
class TextBlock(BaseBlock):
def __init__(self, text, _type=DEFAULT_TEXT_TYPE):
self._text = text
self._type = _type
def __repr__(self):
retu... | default_text_type = 'mrkdwn'
class Baseblock:
def generate(self):
raise not_implemented('Subclass missing generate implementation')
class Textblock(BaseBlock):
def __init__(self, text, _type=DEFAULT_TEXT_TYPE):
self._text = text
self._type = _type
def __repr__(self):
ret... |
#Script to calc. area of circle.
print("enter the radius")
r= float(input())
area= 3.14*r**2
print("area of circle is",area)
| print('enter the radius')
r = float(input())
area = 3.14 * r ** 2
print('area of circle is', area) |
#doc4
#1.
print([1, 'Hello', 1.0])
#2
print([1, 1, [1,2]][2][1])
#3. out: 'b', 'c'
print(['a','b', 'c'][1:])
#4.
weekDict= {'Sunday':0,'Monday':1,'Tuesday':2,'Wednesday':3,'Thursday':4,'Friday':5,'Saturday':6, }
#5. out: 2 if you replace D[k1][1] with D['k1][1]
D={'k1':[1,2,3]}
print(D['k1'][1])
#6.
tup = ( ... | print([1, 'Hello', 1.0])
print([1, 1, [1, 2]][2][1])
print(['a', 'b', 'c'][1:])
week_dict = {'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6}
d = {'k1': [1, 2, 3]}
print(D['k1'][1])
tup = ('a', [1, [2, 3]])
print(tup)
x = set('Missipi')
print(x)
x.add('X')
print(x)
prin... |
description = 'Resi instrument setup'
group = 'basic'
includes = ['base']
| description = 'Resi instrument setup'
group = 'basic'
includes = ['base'] |
def quick_sort(array):
'''
Prototypical quick sort algorithm using Python
Time and Space Complexity:
* Best: O(n * log(n)) time | O(log(n)) space
* Avg: O(n * log(n)) time | O(log(n)) space
* Worst: O(n^2) time | O(log(n)) space
'''
return _quick_sort(array, 0, len(array)-1)
def _quick_sort(arr... | def quick_sort(array):
"""
Prototypical quick sort algorithm using Python
Time and Space Complexity:
* Best: O(n * log(n)) time | O(log(n)) space
* Avg: O(n * log(n)) time | O(log(n)) space
* Worst: O(n^2) time | O(log(n)) space
"""
return _quick_sort(array, 0, len(array) - 1)
def _quick_sor... |
def loops():
# String Array
names = ["Apple", "Orange", "Pear"]
# \n is a newline in a string
print('\n---------------')
print(' For Each Loop')
print('---------------\n')
# For Each Loop
for i in names:
print(i)
print('\n---------------')
print(' For Loop')
prin... | def loops():
names = ['Apple', 'Orange', 'Pear']
print('\n---------------')
print(' For Each Loop')
print('---------------\n')
for i in names:
print(i)
print('\n---------------')
print(' For Loop')
print('---------------\n')
for i in range(5):
if i == 1:
... |
class Node:
def __init__(self, value, next_p=None):
self.next = next_p
self.value = value
def __str__(self):
return f'{self.value}'
class InvalidOperationError(Exception):
pass
class Stack:
def __init__(self):
self.top = None
def push(self, value):
curren... | class Node:
def __init__(self, value, next_p=None):
self.next = next_p
self.value = value
def __str__(self):
return f'{self.value}'
class Invalidoperationerror(Exception):
pass
class Stack:
def __init__(self):
self.top = None
def push(self, value):
curre... |
def main():
number = int(input("Enter number (Only positive integer is allowed)"))
print(f'{number} square is {number ** 2}')
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
main()
| def main():
number = int(input('Enter number (Only positive integer is allowed)'))
print(f'{number} square is {number ** 2}')
if __name__ == '__main__':
main() |
number_of_computers = int(input())
number_of_sales = 0
real_sales = 0
made_sales = 0
counter_sales = 0
total_ratings = 0
for i in range (number_of_computers):
rating = int(input())
rating_scale = rating % 10
possible_sales = rating // 10
total_ratings += rating_scale
if rating_scale == 2:
r... | number_of_computers = int(input())
number_of_sales = 0
real_sales = 0
made_sales = 0
counter_sales = 0
total_ratings = 0
for i in range(number_of_computers):
rating = int(input())
rating_scale = rating % 10
possible_sales = rating // 10
total_ratings += rating_scale
if rating_scale == 2:
rea... |
def main():
valid_passwords_by_range_policy = 0
valid_passwords_by_position_policy = 0
with open('input') as f:
for line in f:
policy_string, password = parse_line(line.strip())
policy = Policy.parse(policy_string)
if policy.is_valid_by_range_policy(password):
... | def main():
valid_passwords_by_range_policy = 0
valid_passwords_by_position_policy = 0
with open('input') as f:
for line in f:
(policy_string, password) = parse_line(line.strip())
policy = Policy.parse(policy_string)
if policy.is_valid_by_range_policy(password):
... |
def tree_16b(features):
if features[12] <= 0.0026689696301218646:
if features[2] <= 0.00825153129312639:
if features[19] <= 0.005966400067336508:
if features[19] <= 0.0029812112336458085:
if features[17] <= 0.001915214421615019:
return 0
else: # if features[17] > 0.0... | def tree_16b(features):
if features[12] <= 0.0026689696301218646:
if features[2] <= 0.00825153129312639:
if features[19] <= 0.005966400067336508:
if features[19] <= 0.0029812112336458085:
if features[17] <= 0.001915214421615019:
return ... |
class Employee:
def __init__(self, name, emp_id, email_id):
self.__name=name
self.__emp_id=emp_id
self.__email_id=email_id
def get_name(self):
return self.__name
def get_emp_id(self):
return self.__emp_id
def get_email_id(self):
return self.__email_id
... | class Employee:
def __init__(self, name, emp_id, email_id):
self.__name = name
self.__emp_id = emp_id
self.__email_id = email_id
def get_name(self):
return self.__name
def get_emp_id(self):
return self.__emp_id
def get_email_id(self):
return self.__ema... |
class tablecloumninfo:
col_name=""
data_type=""
comment=""
def __init__(self,col_name,data_type,comment):
self.col_name=col_name
self.data_type=data_type
self.comment=comment
| class Tablecloumninfo:
col_name = ''
data_type = ''
comment = ''
def __init__(self, col_name, data_type, comment):
self.col_name = col_name
self.data_type = data_type
self.comment = comment |
# See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='dansbecker',
course_name='Machine Learning',
course_url='https://www.kaggle.com/learn/intro-to-machine-learning'
)
lessons = [
dict(
topic='Your First BiqQuery ML Model',
... | track = dict(author_username='dansbecker', course_name='Machine Learning', course_url='https://www.kaggle.com/learn/intro-to-machine-learning')
lessons = [dict(topic='Your First BiqQuery ML Model')]
notebooks = [dict(filename='tut1.ipynb', lesson_idx=0, type='tutorial', scriptid=4076893), dict(filename='ex1.ipynb', les... |
class Solution:
def canThreePartsEqualSum(self, A: List[int]) -> bool:
# Since all the three parts are equal, if we sum all element of arrary it should be a multiplication of 3
# so the sum of each part must be equal to sum of all element divided by 3
quotient, remainder = divmod(sum(A), 3)
... | class Solution:
def can_three_parts_equal_sum(self, A: List[int]) -> bool:
(quotient, remainder) = divmod(sum(A), 3)
if remainder != 0:
return False
subarray = 0
partitions = 0
for num in A:
subarray += num
if subarray == quotient:
... |
STATE_CITY = "fluids_state_city"
OBS_QLIDAR = "fluids_obs_qlidar"
OBS_GRID = "fluids_obs_grid"
OBS_BIRDSEYE = "fluids_obs_birdseye"
OBS_NONE = "fluids_obs_none"
BACKGROUND_CSP = "fluids_background_csp"
BACKGROUND_NULL = "fluids_background_null"
REWARD_PATH = "fluids_reward_path"
REWARD_NONE = "fluids_rew... | state_city = 'fluids_state_city'
obs_qlidar = 'fluids_obs_qlidar'
obs_grid = 'fluids_obs_grid'
obs_birdseye = 'fluids_obs_birdseye'
obs_none = 'fluids_obs_none'
background_csp = 'fluids_background_csp'
background_null = 'fluids_background_null'
reward_path = 'fluids_reward_path'
reward_none = 'fluids_reward_none'
right... |
class Solution:
def generate(self, num_rows):
if num_rows == 0:
return []
ans = [1]
result = [ans]
for _ in range(num_rows - 1):
ans = [1] + [ans[i] + ans[i + 1] for i in range(len(ans[:-1]))] + [1]
result.append(ans)
return result
| class Solution:
def generate(self, num_rows):
if num_rows == 0:
return []
ans = [1]
result = [ans]
for _ in range(num_rows - 1):
ans = [1] + [ans[i] + ans[i + 1] for i in range(len(ans[:-1]))] + [1]
result.append(ans)
return result |
for testcase in range(int(input())):
n = int(input())
dict = {}
comb = 1
m = (10**9)+7
for x in input().split():
no = int(x)
try:
dict[no] = dict[no] + 1
except:
dict[no] = 1
dict = list(dict.items())
dict.sort(key=lambda x: x[0], reverse=Tru... | for testcase in range(int(input())):
n = int(input())
dict = {}
comb = 1
m = 10 ** 9 + 7
for x in input().split():
no = int(x)
try:
dict[no] = dict[no] + 1
except:
dict[no] = 1
dict = list(dict.items())
dict.sort(key=lambda x: x[0], reverse=Tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.