content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# WAP to demonstrate simple exception handling in Python
def ExceptionHandling():
try:
a += 10
except NameError as e:
print(e)
def main():
ExceptionHandling()
if __name__ == "__main__":
main() | def exception_handling():
try:
a += 10
except NameError as e:
print(e)
def main():
exception_handling()
if __name__ == '__main__':
main() |
SECRET_KEY = 'gk2ptgp9mB'
SALT = 'SALT'
PERM_FILE = 'perms.json'
UPLOAD_FOLDER = 'uploads'
DB_FILE = 'db.db' | secret_key = 'gk2ptgp9mB'
salt = 'SALT'
perm_file = 'perms.json'
upload_folder = 'uploads'
db_file = 'db.db' |
# Uses python3
def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current % 10
def get_digit_fast(n):
if n <= 1:
return n
prev, curr = 0, 1
for _ i... | def get_fibonacci_last_digit_naive(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
(previous, current) = (current, previous + current)
return current % 10
def get_digit_fast(n):
if n <= 1:
return n
(prev, curr) = (0, 1)
for _ in range(n - ... |
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # The first and second items (index zero and one)
print(first)
middle = suitcase[2:4] # Third and fourth items (index two and three)
print(middle)
last = suitcase[4:6] # The last two items (index four and five)
| suitcase = ['sunglasses', 'hat', 'passport', 'laptop', 'suit', 'shoes']
first = suitcase[0:2]
print(first)
middle = suitcase[2:4]
print(middle)
last = suitcase[4:6] |
# https://leetcode.com/problems/decode-ways/submissions/
# https://leetcode.com/problems/decode-ways/discuss/253018/Python%3A-Easy-to-understand-explanation-bottom-up-dynamic-programming
class Solution_recursion_memo:
def numDecodings(self, s):
L = len(s)
def helper(idx, memo):
... | class Solution_Recursion_Memo:
def num_decodings(self, s):
l = len(s)
def helper(idx, memo):
if idx == L:
return 1
if idx > L or s[idx] == '0':
return float('-inf')
if idx in memo:
return memo[idx]
else... |
#!/usr/bin/env python3
all_cases = [[[8, 1, 6], [3, 5, 7], [4, 9, 2]],
[[6, 1, 8], [7, 5, 3], [2, 9, 4]],
[[4, 9, 2], [3, 5, 7], [8, 1, 6]],
[[2, 9, 4], [7, 5, 3], [6, 1, 8]],
[[8, 3, 4], [1, 5, 9], [6, 7, 2]],
[[4, 3, 8], [9, 5, 1], [2, 7, 6]],
... | all_cases = [[[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[2, 7, 6], [9, 5, 1], [4, 3, 8]]]
s = []
for s_i in range(3):... |
def CountWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
count = {}
# insert your code here
for symbol in "ACGT":
count[symbol] = []
for j in range(k):
count[symbol].append(1)
for i in range(t):
for j in range(k):
symbol = Motifs[i][j... | def count_with_pseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
count = {}
for symbol in 'ACGT':
count[symbol] = []
for j in range(k):
count[symbol].append(1)
for i in range(t):
for j in range(k):
symbol = Motifs[i][j]
count[symbol]... |
DEBUG = True
SECRET_KEY = 'trinity kevin place'
SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/angular_flask.db'
| debug = True
secret_key = 'trinity kevin place'
sqlalchemy_database_uri = 'sqlite:////tmp/angular_flask.db' |
def cb(result):
print('Service has been created')
heartbeatTimeout = 15
payload = {'tags': ['tag1', 'tag2', 'tag3']}
d = client.services.register('serviceId', heartbeatTimeout, payload)
d.addCallback(cb)
reactor.run()
| def cb(result):
print('Service has been created')
heartbeat_timeout = 15
payload = {'tags': ['tag1', 'tag2', 'tag3']}
d = client.services.register('serviceId', heartbeatTimeout, payload)
d.addCallback(cb)
reactor.run() |
# Code generated by font-to-py.py.
# Font: DejaVuSans.ttf
version = '0.26'
def height():
return 20
def max_width():
return 20
def hmap():
return False
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font =\
b'\x0a\x00\x0c\x... | version = '0.26'
def height():
return 20
def max_width():
return 20
def hmap():
return False
def reverse():
return False
def monospaced():
return False
def min_ch():
return 32
def max_ch():
return 126
_font = b'\n\x00\x0c\x00\x00\x06\x00\x00\x06n\x00\x86o\x00\xce\x01\x00|\x00\x008\x00... |
DEFAULT_MAPPING = {
"login": "login",
"password": "password",
"account": "account",
}
MODULE_KEY = "click_creds.classes.ClickCreds"
| default_mapping = {'login': 'login', 'password': 'password', 'account': 'account'}
module_key = 'click_creds.classes.ClickCreds' |
if __name__ == "__main__":
im = 256
ih = 256
print("P3\n",im," ",ih,"\n255\n")
for j in range(ih, 0, -1):
for i in range(im):
r = i / (im-1)
g = j / (ih -1)
b = 0.25
ir = int(255.999 * r)
ig = int(255.999 * g)
ib = int(255.... | if __name__ == '__main__':
im = 256
ih = 256
print('P3\n', im, ' ', ih, '\n255\n')
for j in range(ih, 0, -1):
for i in range(im):
r = i / (im - 1)
g = j / (ih - 1)
b = 0.25
ir = int(255.999 * r)
ig = int(255.999 * g)
ib = in... |
def maxRepeating(str):
l = len(str)
count = 0
res = str[0]
for i in range(l):
cur_count = 1
for j in range(i + 1, l):
if (str[i] != str[j]):
break
cur_count += 1
# Update result if required
if cur_count > ... | def max_repeating(str):
l = len(str)
count = 0
res = str[0]
for i in range(l):
cur_count = 1
for j in range(i + 1, l):
if str[i] != str[j]:
break
cur_count += 1
if cur_count > count:
count = cur_count
res = str[i]
... |
dot3StatsTable = u'.1.3.6.1.2.1.10.7.2.1'
dot3StatsAlignmentErrors = dot3StatsTable + u'.2'
dot3StatsFCSErrors = dot3StatsTable + u'.3'
dot3StatsFrameTooLongs = dot3StatsTable + u'.13'
dots3stats_table_oids = [dot3StatsFCSErrors, dot3StatsAlignmentErrors, dot3StatsFrameTooLongs]
| dot3_stats_table = u'.1.3.6.1.2.1.10.7.2.1'
dot3_stats_alignment_errors = dot3StatsTable + u'.2'
dot3_stats_fcs_errors = dot3StatsTable + u'.3'
dot3_stats_frame_too_longs = dot3StatsTable + u'.13'
dots3stats_table_oids = [dot3StatsFCSErrors, dot3StatsAlignmentErrors, dot3StatsFrameTooLongs] |
x1 = 1
y1 = 0
x2 = 0
y2 = -2
m1 = (y2 / x1)
print(f'X-intercept = {x1, x2} and Y-intercept = {y1, y2}\nSlope = {m1}') # 8
| x1 = 1
y1 = 0
x2 = 0
y2 = -2
m1 = y2 / x1
print(f'X-intercept = {(x1, x2)} and Y-intercept = {(y1, y2)}\nSlope = {m1}') |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on: 2021/07/10 12:48
@Author: Merc2
'''
| """
Created on: 2021/07/10 12:48
@Author: Merc2
""" |
class Xbpm(Device):
x = Cpt(EpicsSignalRO, 'Pos:X-I')
y = Cpt(EpicsSignalRO, 'Pos:Y-I')
a = Cpt(EpicsSignalRO, 'Ampl:ACurrAvg-I')
b = Cpt(EpicsSignalRO, 'Ampl:BCurrAvg-I')
c = Cpt(EpicsSignalRO, 'Ampl:CCurrAvg-I')
d = Cpt(EpicsSignalRO, 'Ampl:DCurrAvg-I')
total = Cpt(EpicsSignalRO, 'Ampl:Cur... | class Xbpm(Device):
x = cpt(EpicsSignalRO, 'Pos:X-I')
y = cpt(EpicsSignalRO, 'Pos:Y-I')
a = cpt(EpicsSignalRO, 'Ampl:ACurrAvg-I')
b = cpt(EpicsSignalRO, 'Ampl:BCurrAvg-I')
c = cpt(EpicsSignalRO, 'Ampl:CCurrAvg-I')
d = cpt(EpicsSignalRO, 'Ampl:DCurrAvg-I')
total = cpt(EpicsSignalRO, 'Ampl:Cur... |
#
# PySNMP MIB module V2H124-24-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/V2H124-24-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:33:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint) ... |
def func():
a = (input("enter a letter : "))
if a.isalpha():
print("alphabet")
else:
print("NO")
func()
| def func():
a = input('enter a letter : ')
if a.isalpha():
print('alphabet')
else:
print('NO')
func() |
class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
nums = deque(arr)
win_count = 0
winner = nums[0]
while True:
a = nums.popleft()
b = nums.popleft()
if a > b:
if winner == a:
win_count ... | class Solution:
def get_winner(self, arr: List[int], k: int) -> int:
nums = deque(arr)
win_count = 0
winner = nums[0]
while True:
a = nums.popleft()
b = nums.popleft()
if a > b:
if winner == a:
win_count += 1
... |
class Solution:
def fb(self, A):
d3 = A % 3 == 0
d5 = A % 5 == 0
if d3 and d5:
return "FizzBuzz"
elif d3:
return "Fizz"
elif d5:
return "Buzz"
else:
return str(A)
# @param A : integer
#... | class Solution:
def fb(self, A):
d3 = A % 3 == 0
d5 = A % 5 == 0
if d3 and d5:
return 'FizzBuzz'
elif d3:
return 'Fizz'
elif d5:
return 'Buzz'
else:
return str(A)
def fizz_buzz(self, A):
return [self.fb(i) ... |
l=[0]*10
for i in range(len(l)):
l[i]=i*2
print(0 in l)
print(1 in l)
print(2 in l)
print(3 in l)
print(4 in l) | l = [0] * 10
for i in range(len(l)):
l[i] = i * 2
print(0 in l)
print(1 in l)
print(2 in l)
print(3 in l)
print(4 in l) |
#import os
#import glob
#modules = glob.glob(os.path.dirname(__file__)+"/*.py")
#__all__ = [ os.path.basename(f)[:-3] for f in modules]
__user_users_tablename__ = 'users'
__user_users_head__ = 'admin'
__user_online_tablename__ = 'online'
__user_online_head__ = 'online'
__user_admingroup_tablename__ = 'admingroup'
__use... | __user_users_tablename__ = 'users'
__user_users_head__ = 'admin'
__user_online_tablename__ = 'online'
__user_online_head__ = 'online'
__user_admingroup_tablename__ = 'admingroup'
__user_admingroup_head__ = 'admingroup' |
# https://adventofcode.com/2020/day/13
infile = open('input.txt', 'r')
earliest_time_to_depart = int(infile.readline())
buses = []
for bus in infile.readline().rstrip().split(','):
if bus != 'x':
buses.append(int(bus))
buses.sort()
infile.close()
earliest_bus = -1
minimum_wait_time = max(buses)
for bus in... | infile = open('input.txt', 'r')
earliest_time_to_depart = int(infile.readline())
buses = []
for bus in infile.readline().rstrip().split(','):
if bus != 'x':
buses.append(int(bus))
buses.sort()
infile.close()
earliest_bus = -1
minimum_wait_time = max(buses)
for bus in buses:
latest_bus_departure = int(ea... |
# pcinput
# input functions that check for type
# Pieter Spronck
# These functions are rather ugly as they print error messages if something is wrong.
# However, they are meant for a course, which means they are used by students who
# are unaware (until the end of the course) of exceptions and things like that.
# Thi... | def get_float(prompt):
while True:
try:
num = float(input(prompt))
except ValueError:
print('That is not a number -- please try again')
continue
return num
def get_integer(prompt):
while True:
try:
num = int(input(prompt))
... |
class Chord(object):
def __init__(self):
self.tones = []
def add_tone(self, tone):
self.tones.append(tone) | class Chord(object):
def __init__(self):
self.tones = []
def add_tone(self, tone):
self.tones.append(tone) |
n = int(input())
print('+', end='')
for i in range(n-2):
print(' -', end='')
print(' +')
for k in range(n-2):
print('|', end='')
for row in range(n-2):
print(' -', end='')
print(' |')
print('+', end='')
for j in range(n-2):
print(' -', end='')
print(' +')
| n = int(input())
print('+', end='')
for i in range(n - 2):
print(' -', end='')
print(' +')
for k in range(n - 2):
print('|', end='')
for row in range(n - 2):
print(' -', end='')
print(' |')
print('+', end='')
for j in range(n - 2):
print(' -', end='')
print(' +') |
d = int(input("Enter the decimal number:"))
m = d
r,t = 0,[]
while(d>0):
r = d % 8
t.append(chr(r+48))
d = d//8
t = t[::-1]
print("The octal of the decimal number",m,"is",end = " ")
for i in range(0,len(t)):
print(t[i],end='')
| d = int(input('Enter the decimal number:'))
m = d
(r, t) = (0, [])
while d > 0:
r = d % 8
t.append(chr(r + 48))
d = d // 8
t = t[::-1]
print('The octal of the decimal number', m, 'is', end=' ')
for i in range(0, len(t)):
print(t[i], end='') |
class Ship():
def __init__(self, name, ship_head, ship_size):
self.ship_head = ship_head
self.name = name
self.size = ship_size
self.generate_position()
#pensar numa nova nomenclatura
def generate_position(self):
self.position = []
ship_column = self.ship... | class Ship:
def __init__(self, name, ship_head, ship_size):
self.ship_head = ship_head
self.name = name
self.size = ship_size
self.generate_position()
def generate_position(self):
self.position = []
ship_column = self.ship_head[1]
ship_row = self.ship_he... |
def lambda_handler(event, context):
message = 'Hello {} {}! Keep being awesome!'.format(event['first_name'], event['last_name'])
#print to CloudWatch logs
print(message)
return {
'message' : message
} | def lambda_handler(event, context):
message = 'Hello {} {}! Keep being awesome!'.format(event['first_name'], event['last_name'])
print(message)
return {'message': message} |
#imported from https://bitbucket.org/pypy/benchmarks/src/846fa56a282b0e8716309f891553e0af542d8800/own/fannkuch.py?at=default
# the export line is in fannkuch.pythran
#runas fannkuch(9);fannkuch2(9)
#bench fannkuch(9)
def fannkuch(n):
count = range(1, n+1)
max_flips = 0
m = n-1
r = n
check = 0
p... | def fannkuch(n):
count = range(1, n + 1)
max_flips = 0
m = n - 1
r = n
check = 0
perm1 = range(n)
perm = range(n)
while 1:
if check < 30:
check += 1
while r != 1:
count[r - 1] = r
r -= 1
if perm1[0] != 0 and perm1[m] != m:
... |
# Copyright 2020-2021 The MathWorks, Inc.
# Configure MATLAB_DESKTOP_PROXY to extend for Jupyter
config = {
# Link the documentation url here. This will show up on the website UI
# where users can create issue's or make enhancement requests
"doc_url": "https://github.com/mathworks/jupyter-matlab-proxy",
... | config = {'doc_url': 'https://github.com/mathworks/jupyter-matlab-proxy', 'extension_name': 'Jupyter', 'extension_name_short_description': 'Jupyter'} |
# Ex1
def naturalSum(min, max):
__min = min
__max = max
__value = 0
for x in range(__min, __max + 1):
if x%7 == 0 or x%9 == 0:
__value += x
return __value
print("natural sum to 20: " + str(naturalSum(0,20)))
print("natural sum to 10000: " + str(naturalSum(0,10000)))
| def natural_sum(min, max):
__min = min
__max = max
__value = 0
for x in range(__min, __max + 1):
if x % 7 == 0 or x % 9 == 0:
__value += x
return __value
print('natural sum to 20: ' + str(natural_sum(0, 20)))
print('natural sum to 10000: ' + str(natural_sum(0, 10000))) |
print(2)
for i in range(3, 101):
found = False
for j in range(2, i // 2 + 1):
if i % j == 0:
found = True
break
if not found:
print(i)
| print(2)
for i in range(3, 101):
found = False
for j in range(2, i // 2 + 1):
if i % j == 0:
found = True
break
if not found:
print(i) |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
def transform(logdata):
if 'errorCode' in logdata or 'errorMessage' in logdata:
logdata['event']['outcome'] = 'failure'
else:
logdata['event']['outcome'] = 'success'
try:
name = lo... | def transform(logdata):
if 'errorCode' in logdata or 'errorMessage' in logdata:
logdata['event']['outcome'] = 'failure'
else:
logdata['event']['outcome'] = 'success'
try:
name = logdata['user']['name']
if ':' in name:
logdata['user']['name'] = name.split(':')[-1].... |
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class BotWrapper:
def __init__(self):
self.bot = None
def se... | def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
@singleton
class Botwrapper:
def __init__(self):
self.bot = None
def set... |
#! /usr/bin/python
# -*- coding: iso-8859-15 -*-
for n in (1, 6):
c = n ** 2
print(n,c) | for n in (1, 6):
c = n ** 2
print(n, c) |
# dp
class Solution:
def numSquares(self, n: int) -> int:
dp = [float("inf")] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j * j] + 1)
j += 1
return dp[n]
| class Solution:
def num_squares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
j = 1
while j * j <= i:
dp[i] = min(dp[i], dp[i - j * j] + 1)
j += 1
return dp[n] |
# ---
# jupyter:
# jupytext:
# cell_markers: region,endregion
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
1+2+3
# region active=""
# This is a raw cell
# endregion
# This is a markdown cell
| 1 + 2 + 3 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def tree2str(self, t: TreeNode) -> str:
if not t: return ''
left = '({})'.format(self.t... | class Solution:
def tree2str(self, t: TreeNode) -> str:
if not t:
return ''
left = '({})'.format(self.tree2str(t.left)) if t.left or t.right else ''
right = '({})'.format(self.tree2str(t.right)) if t.right else ''
return '{}{}{}'.format(t.val, left, right) |
_constant_id = 0
def _create_constant_id():
global _constant_id
_constant_id += 1
return f'<Game Constant (id={_constant_id})'
text_relative_margin_size = _create_constant_id()
margin_relative_text_spawn = _create_constant_id()
mutable_text_size = _create_constant_id()
default_font_path = 'nsr.ttf' | _constant_id = 0
def _create_constant_id():
global _constant_id
_constant_id += 1
return f'<Game Constant (id={_constant_id})'
text_relative_margin_size = _create_constant_id()
margin_relative_text_spawn = _create_constant_id()
mutable_text_size = _create_constant_id()
default_font_path = 'nsr.ttf' |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def contnum(n):
# initializing starting number
num = 1
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):... | def contnum(n):
num = 1
for i in range(0, n):
for j in range(0, i + 1):
print(num, end=' ')
num = num + 1
print('\r')
n = 5
contnum(n) |
class PlayerInfo:
def __init__(self, manager):
self.window = manager.window
self.game = manager.game
self.manager = manager
self._bottom_index = 0
self._top_index = 0
self.bottom_num_pages = 3
self.top_num_pages = 2
def __call__(self):
self.setup_... | class Playerinfo:
def __init__(self, manager):
self.window = manager.window
self.game = manager.game
self.manager = manager
self._bottom_index = 0
self._top_index = 0
self.bottom_num_pages = 3
self.top_num_pages = 2
def __call__(self):
self.setup... |
class Solution:
def nearestPalindromic(self, n: str) -> str:
def getPalindromes(s: str) -> tuple:
num = int(s)
k = len(s)
palindromes = []
half = s[0:(k + 1) // 2]
reversedHalf = half[:k // 2][::-1]
candidate = int(half + reversedHalf)
if candidate < num:
palindr... | class Solution:
def nearest_palindromic(self, n: str) -> str:
def get_palindromes(s: str) -> tuple:
num = int(s)
k = len(s)
palindromes = []
half = s[0:(k + 1) // 2]
reversed_half = half[:k // 2][::-1]
candidate = int(half + reversedH... |
def is_prime(num: int) -> bool:
prime_nums_list: list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
if num in prime_nums_list:
return True
elif list(str(num))[-1] in ['2', '5']:
return False
else:
for n in range(2, num):
... | def is_prime(num: int) -> bool:
prime_nums_list: list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
if num in prime_nums_list:
return True
elif list(str(num))[-1] in ['2', '5']:
return False
else:
for n in range(2, num):
... |
# create a simple tree data structure with python
# First of all: a class implemented to present tree node
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
self.size = 0
def a... | class Treenode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
self.size = 0
def addnode(self, new):
if self.root == None:
self.root = new
self.size += 1
... |
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
if k == 0: return 0
maxLen = 0
d = {}
i, j = 0, 0
while j < len(s):
d[s[j]] = d.get(s[j], 0) + 1
if len(d) <= k:
tempMax = 0
for key, va... | class Solution:
def length_of_longest_substring_k_distinct(self, s: str, k: int) -> int:
if k == 0:
return 0
max_len = 0
d = {}
(i, j) = (0, 0)
while j < len(s):
d[s[j]] = d.get(s[j], 0) + 1
if len(d) <= k:
temp_max = 0
... |
leap = Runtime.start("leap","LeapMotion")
leap.addLeapDataListener(python)
def onLeapData(data):
print (data.rightHand.index)
leap.startTracking()
| leap = Runtime.start('leap', 'LeapMotion')
leap.addLeapDataListener(python)
def on_leap_data(data):
print(data.rightHand.index)
leap.startTracking() |
language="java"
print("Checking if else conditions")
if language=='Python':
print(Python)
elif language=="java":
print("java")
else:
print("no match")
print("\nChecking Boolean Conditions")
user='Admin'
logged_in=False
if user=='Admin' and logged_in:
print("ADMIN PAGE")
else:
print("Bad Creds")
i... | language = 'java'
print('Checking if else conditions')
if language == 'Python':
print(Python)
elif language == 'java':
print('java')
else:
print('no match')
print('\nChecking Boolean Conditions')
user = 'Admin'
logged_in = False
if user == 'Admin' and logged_in:
print('ADMIN PAGE')
else:
print('Bad ... |
class Adder:
a = 0
b = 0
def add(self):
return self.a + self.b
def __init__(self,a,b):
self.a = a;
self.b = b;
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
x = Adder(a,b)
print(x.add()) | class Adder:
a = 0
b = 0
def add(self):
return self.a + self.b
def __init__(self, a, b):
self.a = a
self.b = b
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
x = adder(a, b)
print(x.add()) |
def char_sum(s: str):
sum = 0
for char in s:
sum += ord(char)
return sum
# Time complexity: O(M+N)
# Space complexity: O(1)
def check_permutation(s1: str, s2: str):
sum1 = char_sum(s1)
sum2 = char_sum(s2)
return sum1 == sum2
print(check_permutation("same", "same"))
print(check_perm... | def char_sum(s: str):
sum = 0
for char in s:
sum += ord(char)
return sum
def check_permutation(s1: str, s2: str):
sum1 = char_sum(s1)
sum2 = char_sum(s2)
return sum1 == sum2
print(check_permutation('same', 'same'))
print(check_permutation('same', 'smae'))
print(check_permutation('same',... |
class APIError(RuntimeError):
def __init__(self, message):
self.message = message
def __str__(self):
return "%s" % (self.message)
def __repr__(self):
return self.__str__()
| class Apierror(RuntimeError):
def __init__(self, message):
self.message = message
def __str__(self):
return '%s' % self.message
def __repr__(self):
return self.__str__() |
kumas, inus, ookamis = 10, 4, 16
if (kumas > inus) and (kumas > ookamis):
print(ookamis)
elif (inus > kumas) and (inus > ookamis):
print(kumas)
elif (ookamis > kumas) and (ookamis > inus):
print(inus)
| (kumas, inus, ookamis) = (10, 4, 16)
if kumas > inus and kumas > ookamis:
print(ookamis)
elif inus > kumas and inus > ookamis:
print(kumas)
elif ookamis > kumas and ookamis > inus:
print(inus) |
L = [92,456,34,7234,24,7,623,5,35]
maxSoFar = L[0]
for i in range(len(L)):
if L[i] > maxSoFar:
maxSoFar = L[i]
print(maxSoFar)
| l = [92, 456, 34, 7234, 24, 7, 623, 5, 35]
max_so_far = L[0]
for i in range(len(L)):
if L[i] > maxSoFar:
max_so_far = L[i]
print(maxSoFar) |
class Empleado:
cantidad_empleados = 0
tasa_incremento = 1.03
def __init__(self, nombre, apellido, email, sueldo):
self.nombre = nombre
self.apellido = apellido
self.email = email
self.sueldo = sueldo
def get_full_name(self):
return '{} {}'.format(self.nombre, s... | class Empleado:
cantidad_empleados = 0
tasa_incremento = 1.03
def __init__(self, nombre, apellido, email, sueldo):
self.nombre = nombre
self.apellido = apellido
self.email = email
self.sueldo = sueldo
def get_full_name(self):
return '{} {}'.format(self.nombre, s... |
class A:
def long_unique_identifier(self): pass
def foo(x):
x.long_unique_identifier()
# <ref> | class A:
def long_unique_identifier(self):
pass
def foo(x):
x.long_unique_identifier() |
# -*- coding: utf-8 -*-
def parametrized(dec):
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer
@parametrized
def dependency(module, *_deps):
module.deps = _deps
return module
@parametrized
def source(module, _source):
... | def parametrized(dec):
def layer(*args, **kwargs):
def repl(f):
return dec(f, *args, **kwargs)
return repl
return layer
@parametrized
def dependency(module, *_deps):
module.deps = _deps
return module
@parametrized
def source(module, _source):
module.source = _source
... |
print("Enter The Number n")
n = int(input())
if (n%2)!=0:
print("Weird")
elif (n%2)==0:
if n in range(2,5):
print("Not Weird")
elif n in range(6,21):
print("Weird")
elif n > 20:
print("Not Weird")
| print('Enter The Number n')
n = int(input())
if n % 2 != 0:
print('Weird')
elif n % 2 == 0:
if n in range(2, 5):
print('Not Weird')
elif n in range(6, 21):
print('Weird')
elif n > 20:
print('Not Weird') |
model = dict(
type='TSN2D',
backbone=dict(
type='ResNet',
pretrained='modelzoo://resnet50',
nsegments=8,
depth=50,
out_indices=(3,),
tsm=True,
bn_eval=False,
partial_bn=False),
spatial_temporal_module=dict(
type='SimpleSpatialModule',
... | model = dict(type='TSN2D', backbone=dict(type='ResNet', pretrained='modelzoo://resnet50', nsegments=8, depth=50, out_indices=(3,), tsm=True, bn_eval=False, partial_bn=False), spatial_temporal_module=dict(type='SimpleSpatialModule', spatial_type='avg', spatial_size=7), segmental_consensus=dict(type='SimpleConsensus', co... |
#AUTHOR: Pornpimol Kaewphing
#Python3 Concept: Twosum in Python
#GITHUB: https://github.com/gympohnpimol
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
... | def two_sum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
else:
pass |
list1 = [1, 2, 3]
list2 = ["One", "Two"]
print("list1: ", list1)
print("list2: ", list2)
print("\n")
list12 = list1 + list2
print("list1 + list2: ", list12)
list2x3 = list2 * 3
print("list2 * 3: ", list2x3)
hasThree = "Three" in list2
print("'Three' in list2? ", hasThree) | list1 = [1, 2, 3]
list2 = ['One', 'Two']
print('list1: ', list1)
print('list2: ', list2)
print('\n')
list12 = list1 + list2
print('list1 + list2: ', list12)
list2x3 = list2 * 3
print('list2 * 3: ', list2x3)
has_three = 'Three' in list2
print("'Three' in list2? ", hasThree) |
def print_in_blocks(li, bp):
dli = []
temp_list = []
for i in range(len(li)):
temp_list.append(li[i])
if i != 0 and (i+1)%bp == 0:
dli.append(temp_list)
temp_list = []
cols = bp
max_col_len = []
for _ in range(cols):
max_col_len.append(0)
f... | def print_in_blocks(li, bp):
dli = []
temp_list = []
for i in range(len(li)):
temp_list.append(li[i])
if i != 0 and (i + 1) % bp == 0:
dli.append(temp_list)
temp_list = []
cols = bp
max_col_len = []
for _ in range(cols):
max_col_len.append(0)
f... |
# These should reflect //ci/prebuilt/BUILD declared targets. This a map from
# target in //ci/prebuilt/BUILD to the underlying build recipe in
# ci/build_container/build_recipes.
TARGET_RECIPES = {
"ares": "cares",
"backward": "backward",
"event": "libevent",
"event_pthreads": "libevent",
# TODO(htu... | target_recipes = {'ares': 'cares', 'backward': 'backward', 'event': 'libevent', 'event_pthreads': 'libevent', 'gcovr': 'gcovr', 'googletest': 'googletest', 'tcmalloc_and_profiler': 'gperftools', 'http_parser': 'http-parser', 'lightstep': 'lightstep', 'nghttp2': 'nghttp2', 'protobuf': 'protobuf', 'protoc': 'protobuf', '... |
# Python3 program to solve Rat in a Maze
# problem using backracking
# Maze size
N = 4
# A utility function to print solution matrix sol
def printSolution( sol ):
for i in sol:
for j in i:
print(str(j) + " ", end ="")
print("")
# A utility function to check if x, y is valid
# index for N * N Maze
def isSaf... | n = 4
def print_solution(sol):
for i in sol:
for j in i:
print(str(j) + ' ', end='')
print('')
def is_safe(maze, x, y):
if x >= 0 and x < N and (y >= 0) and (y < N) and (maze[x][y] == 1):
return True
return False
def solve_maze(maze):
sol = [[0 for j in range(4)] f... |
# We use this to create easily readable errors for when debugging elastic beanstalk deployment configurations
class DynamicParameter(Exception): pass
#NOTE: integer values need to be strings
def get_base_eb_configuration():
return [
# Instance launch configuration details
{
'N... | class Dynamicparameter(Exception):
pass
def get_base_eb_configuration():
return [{'Namespace': 'aws:autoscaling:launchconfiguration', 'OptionName': 'InstanceType', 'Value': dynamic_parameter('InstanceType')}, {'Namespace': 'aws:autoscaling:launchconfiguration', 'OptionName': 'IamInstanceProfile', 'Value': dyna... |
'''
Context:
String compression
using counts
of repeated characters
Definitions:
Objective:
Assumptions:
Only lower and upper case letters present
Constraints:
Inputs:
string value
Algorithm flow:
Compress the string
... | """
Context:
String compression
using counts
of repeated characters
Definitions:
Objective:
Assumptions:
Only lower and upper case letters present
Constraints:
Inputs:
string value
Algorithm flow:
Compress the string
... |
def slow_fib(n: int) -> int:
if n < 1:
return 0
if n == 1:
return 1
return slow_fib(n-1) + slow_fib(n-2)
| def slow_fib(n: int) -> int:
if n < 1:
return 0
if n == 1:
return 1
return slow_fib(n - 1) + slow_fib(n - 2) |
def word_frequency(list):
words = {}
for word in list:
if word in words:
words[word] += 1
else:
words[word] = 1
return words
frequency_counter = word_frequency(['hey', 'hi', 'more', 'hey', 'hi'])
print(frequency_counter)
| def word_frequency(list):
words = {}
for word in list:
if word in words:
words[word] += 1
else:
words[word] = 1
return words
frequency_counter = word_frequency(['hey', 'hi', 'more', 'hey', 'hi'])
print(frequency_counter) |
'''
Task
Given an integer, , and space-separated integers as input, create a tuple, , of those integers. Then compute and print the result of
.
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
Input Format
The first line contains an integer,
, denoting the number of eleme... | """
Task
Given an integer, , and space-separated integers as input, create a tuple, , of those integers. Then compute and print the result of
.
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
Input Format
The first line contains an integer,
, denoting the number of eleme... |
# GENERATED VERSION FILE
# TIME: Fri Mar 20 02:18:57 2020
__version__ = '1.1.0+58a3f02'
short_version = '1.1.0'
| __version__ = '1.1.0+58a3f02'
short_version = '1.1.0' |
bruin = set(["Boxtel","Best","Beukenlaan","Helmond 't Hout","Helmond","Helmond Brouwhuis","Deurne"])
groen = set(["Boxtel","Best","Beukenlaan","Geldrop","Heeze","Weert"])
print(bruin.intersection(groen))
print(bruin.difference(groen))
print(bruin.union(groen))
| bruin = set(['Boxtel', 'Best', 'Beukenlaan', "Helmond 't Hout", 'Helmond', 'Helmond Brouwhuis', 'Deurne'])
groen = set(['Boxtel', 'Best', 'Beukenlaan', 'Geldrop', 'Heeze', 'Weert'])
print(bruin.intersection(groen))
print(bruin.difference(groen))
print(bruin.union(groen)) |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return head
prevHead = head
... | class Solution:
def reverse_list(self, head: ListNode) -> ListNode:
if not head:
return head
prev_head = head
while prevHead.next:
curr = prevHead.next
prevHead.next = curr.next
curr.next = head
head = curr
return head
cla... |
# -*- coding: utf-8 -*-
X = int(input())
Y = int(input())
start, end = min(X, Y), max(X, Y)
firstDivisible = start if (start % 13 == 0) else start + (13 - (start % 13))
answer = sum(range(start, end + 1)) - sum(range(firstDivisible, end + 1, 13))
print(answer) | x = int(input())
y = int(input())
(start, end) = (min(X, Y), max(X, Y))
first_divisible = start if start % 13 == 0 else start + (13 - start % 13)
answer = sum(range(start, end + 1)) - sum(range(firstDivisible, end + 1, 13))
print(answer) |
# variables
notasV = 0
soma = 0
# while there are not 2 grades between [0,10], so the loop continue
while notasV < 2:
# receive float
nota = float(input())
# if nota is >= 0 and nota <= 10
if (nota >= 0) and (nota <= 10):
notasV = notasV + 1
soma = soma + nota
# if... | notas_v = 0
soma = 0
while notasV < 2:
nota = float(input())
if nota >= 0 and nota <= 10:
notas_v = notasV + 1
soma = soma + nota
else:
print('nota invalida')
if notasV == 2:
soma = soma / 2
print('media = {:.2f}'.format(soma)) |
# Error codes due to an invalid request
INVALID_REQUEST = 400
INVALID_ALGORITHM = 401
DOCUMENT_NOT_FOUND = 404
| invalid_request = 400
invalid_algorithm = 401
document_not_found = 404 |
# https://en.wikipedia.org/wiki/Trifid_cipher
def __encryptPart(messagePart, character2Number):
one, two, three = "", "", ""
tmp = []
for character in messagePart:
tmp.append(character2Number[character])
for each in tmp:
one += each[0]
two += each[1]
thre... | def __encrypt_part(messagePart, character2Number):
(one, two, three) = ('', '', '')
tmp = []
for character in messagePart:
tmp.append(character2Number[character])
for each in tmp:
one += each[0]
two += each[1]
three += each[2]
return one + two + three
def __decrypt_p... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
# Unless required by appli... | __all__ = ['model_alias']
model_alias = {'deepspeech2offline': ['paddlespeech.s2t.models.ds2:DeepSpeech2Model'], 'deepspeech2online': ['paddlespeech.s2t.models.ds2:DeepSpeech2Model'], 'conformer': ['paddlespeech.s2t.models.u2:U2Model'], 'conformer_online': ['paddlespeech.s2t.models.u2:U2Model'], 'transformer': ['paddle... |
# Find minimum number without using conditional statement or ternary operator
def main():
a = 4
b = 3
print((a > b) * a + (a < b) * b)
if __name__ == '__main__':
main()
| def main():
a = 4
b = 3
print((a > b) * a + (a < b) * b)
if __name__ == '__main__':
main() |
class Author:
def __init__(self, name, familyname=None):
self.name = name
self.familyname = familyname
def __repr__(self):
return u'{0}'.format(self.name)
authors = {'1': Author('Test Author'), '2': Author('Testy McTesterson')}
print(list(authors.values()))
print(u'Found {0} unique au... | class Author:
def __init__(self, name, familyname=None):
self.name = name
self.familyname = familyname
def __repr__(self):
return u'{0}'.format(self.name)
authors = {'1': author('Test Author'), '2': author('Testy McTesterson')}
print(list(authors.values()))
print(u'Found {0} unique aut... |
'''
'''
def main():
info('Fill Pipette 1')
close(description='Outer Pipette 1')
sleep(1)
if analysis_type=='blank':
info('not filling cocktail pipette')
else:
info('filling cocktail pipette')
open(description='Inner Pipette 1')
sleep(15)
close(description='Inner Pipette 1')
sleep(1) | """
"""
def main():
info('Fill Pipette 1')
close(description='Outer Pipette 1')
sleep(1)
if analysis_type == 'blank':
info('not filling cocktail pipette')
else:
info('filling cocktail pipette')
open(description='Inner Pipette 1')
sleep(15)
close(description='Inner Pi... |
_base_ = [
'../_base_/models/regproxy/regproxy-l16.py',
'../_base_/datasets/cityscapes.py',
'../_base_/default_runtime.py',
'../_base_/schedules/adamw+cr+lr_6e-5+wd_0.01+iter_80k.py'
]
model = dict(
backbone=dict(
img_size=(768, 768),
out_indices=[5, 23]),
test_cfg=dict(
... | _base_ = ['../_base_/models/regproxy/regproxy-l16.py', '../_base_/datasets/cityscapes.py', '../_base_/default_runtime.py', '../_base_/schedules/adamw+cr+lr_6e-5+wd_0.01+iter_80k.py']
model = dict(backbone=dict(img_size=(768, 768), out_indices=[5, 23]), test_cfg=dict(mode='slide', crop_size=(768, 768), stride=(512, 512)... |
# Copy this file to config.py and fill the blanks
QCLOUD_APP_ID = ''
QCLOUD_SECRET_ID = ''
QCLOUD_SECRET_KEY = ''
QCLOUD_BUCKET = ''
QCLOUD_REGION = 'sh'
| qcloud_app_id = ''
qcloud_secret_id = ''
qcloud_secret_key = ''
qcloud_bucket = ''
qcloud_region = 'sh' |
class SubSystemTypes:
aperture = 'Aperture'
client = 'Client'
config = 'Config'
rights = 'Rights'
secret_store_config = 'SecretStoreconfig'
websdk = 'WebSDK'
| class Subsystemtypes:
aperture = 'Aperture'
client = 'Client'
config = 'Config'
rights = 'Rights'
secret_store_config = 'SecretStoreconfig'
websdk = 'WebSDK' |
user_0 = {'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
print(user_0.items())
| user_0 = {'username': 'efermi', 'first': 'enrico', 'last': 'fermi'}
for (key, value) in user_0.items():
print('\nKey: ' + key)
print('Value: ' + value)
print(user_0.items()) |
# Solution
def part1(data):
frequency = sum(int(x) for x in data)
return frequency
def part2(data):
known_frequency = { 0: True }
frequency = 0
while True:
for x in data:
frequency += int(x)
if frequency in known_frequency:
return frequency
... | def part1(data):
frequency = sum((int(x) for x in data))
return frequency
def part2(data):
known_frequency = {0: True}
frequency = 0
while True:
for x in data:
frequency += int(x)
if frequency in known_frequency:
return frequency
known_fre... |
data_file = open('us_cities.txt', 'r')
for line in data_file:
city, population = line.split(':') # Tuple unpacking
city = city.title() # Capitalize city names
population = '{0:,}'.format(int(population)) # Add commas to numbers
print(city.ljust(15) + population)
dat... | data_file = open('us_cities.txt', 'r')
for line in data_file:
(city, population) = line.split(':')
city = city.title()
population = '{0:,}'.format(int(population))
print(city.ljust(15) + population)
data_file.close() |
class Veiculo:
def __init__(self, tipo) -> None:
self.tipo = tipo
self.propriedades = {}
def get_propriedades(self):
return self.propriedades
def set_propriedades(self, cor: str, cambio: str, capacidade: int) -> None:
self.propriedades = {
'cor': cor,
... | class Veiculo:
def __init__(self, tipo) -> None:
self.tipo = tipo
self.propriedades = {}
def get_propriedades(self):
return self.propriedades
def set_propriedades(self, cor: str, cambio: str, capacidade: int) -> None:
self.propriedades = {'cor': cor, 'cambio': cambio, 'cap... |
turno = input("Qual perido voce estuda? V para vespertino, D para diurno ou N para noturno: ").upper()
if turno == "V":
print("Boa Tarde")
elif turno == "D":
print("Bom dia")
elif turno == "N":
print("Boav Noite")
else:
print("Entrada invalida") | turno = input('Qual perido voce estuda? V para vespertino, D para diurno ou N para noturno: ').upper()
if turno == 'V':
print('Boa Tarde')
elif turno == 'D':
print('Bom dia')
elif turno == 'N':
print('Boav Noite')
else:
print('Entrada invalida') |
#
# This file is part of snmpresponder software.
#
# Copyright (c) 2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpresponder/license.html
#
def expandMacro(option, context):
for k in context:
pat = '${%s}' % k
if option and '${' in option:
option = option.repl... | def expand_macro(option, context):
for k in context:
pat = '${%s}' % k
if option and '${' in option:
option = option.replace(pat, str(context[k]))
return option
def expand_macros(options, context):
options = list(options)
for (idx, option) in enumerate(options):
opti... |
#Cristian Chitiva
#cychitvav@unal.educo
#16/Sept/2018
class Cat:
def __init__(self, name):
self.name = name | class Cat:
def __init__(self, name):
self.name = name |
class RestWriter(object):
def __init__(self, file, report):
self.file = file
self.report = report
def write(self, restsection):
assert len(restsection) >= 3
for separator, collection1 in self.report:
self.write_header(separator, restsection[0], 80)
f... | class Restwriter(object):
def __init__(self, file, report):
self.file = file
self.report = report
def write(self, restsection):
assert len(restsection) >= 3
for (separator, collection1) in self.report:
self.write_header(separator, restsection[0], 80)
for... |
d = DiGraph(loops=True, multiedges=True, sparse=True)
d.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'),
(0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'),
(0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
GP = d.graphplot(vertex_size=100, edge_labels=True,
color_by_label=True, edge_style='dashed'... | d = di_graph(loops=True, multiedges=True, sparse=True)
d.add_edges([(0, 0, 'a'), (0, 0, 'b'), (0, 1, 'c'), (0, 1, 'd'), (0, 1, 'e'), (0, 1, 'f'), (0, 1, 'f'), (2, 1, 'g'), (2, 2, 'h')])
gp = d.graphplot(vertex_size=100, edge_labels=True, color_by_label=True, edge_style='dashed')
GP.set_edges(edge_style='solid')
GP.set_... |
class Pessoa:
def __init__(self, nome):
self.nome = nome
@classmethod
def outro_contrutor(cls, nome, sobrenome):
cls.sobrenome = sobrenome
return cls(nome)
p = Pessoa('samuel')
print(p.nome)
p = Pessoa.outro_contrutor('saulo', 'nunes')
print(p.sobrenome)
| class Pessoa:
def __init__(self, nome):
self.nome = nome
@classmethod
def outro_contrutor(cls, nome, sobrenome):
cls.sobrenome = sobrenome
return cls(nome)
p = pessoa('samuel')
print(p.nome)
p = Pessoa.outro_contrutor('saulo', 'nunes')
print(p.sobrenome) |
while True:
print('-=-' * 6)
n=float(input('Digite um valor (negativo para sair do programa): '))
if n<0:
break
print('-=-'*6)
for c in range(1,11):
print('\033[35m{:.0f} x {} = {:.0f}\033[m'.format(n,c,n*c))
print('\033[33mPrograma encerrado. Volte sempre!')
| while True:
print('-=-' * 6)
n = float(input('Digite um valor (negativo para sair do programa): '))
if n < 0:
break
print('-=-' * 6)
for c in range(1, 11):
print('\x1b[35m{:.0f} x {} = {:.0f}\x1b[m'.format(n, c, n * c))
print('\x1b[33mPrograma encerrado. Volte sempre!') |
n = int(input())
teams = [int(x) for x in input().split()]
carrying = 0
for i in range(n):
if teams[i] == 0 and carrying == 1:
print("NO")
exit()
if teams[i] % 2 == 1:
if carrying == 0:
carrying = 1
else:
carrying = 0
if carrying == 0:
pr... | n = int(input())
teams = [int(x) for x in input().split()]
carrying = 0
for i in range(n):
if teams[i] == 0 and carrying == 1:
print('NO')
exit()
if teams[i] % 2 == 1:
if carrying == 0:
carrying = 1
else:
carrying = 0
if carrying == 0:
print('YES')
els... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Midokura PTE LTD.
# All Rights Reserved
#
# 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/LICENS... | application_octet_stream = 'application/octet-stream'
application_json_v5 = 'application/vnd.org.midonet.Application-v5+json'
application_error_json = 'application/vnd.org.midonet.Error-v1+json'
application_tenant_json = 'application/vnd.org.midonet.Tenant-v1+json'
application_tenant_collection_json = 'application/vnd.... |
def clean_gdp(gdp):
# get needed columns from gdplev excel file
columns_to_keep = ['Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6']
gdp = gdp[columns_to_keep]
gdp.columns = ['Quarter', 'GDP Current', 'GDP Chained']
gdp = gdp[~gdp['Quarter'].isnull()]
# only keep data from 2000 onwards
gdp = gd... | def clean_gdp(gdp):
columns_to_keep = ['Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6']
gdp = gdp[columns_to_keep]
gdp.columns = ['Quarter', 'GDP Current', 'GDP Chained']
gdp = gdp[~gdp['Quarter'].isnull()]
gdp = gdp[gdp['Quarter'].str.startswith('2')]
gdp.reset_index(drop=True, inplace=True)
gdp['... |
# Can be used in the test data like ${MyObject()} or ${MyObject(1)}
class MyObject:
def __init__(self, index=''):
self.index = index
def __str__(self):
return '<MyObject%s>' % self.index
UNICODE = (u'Hyv\u00E4\u00E4 y\u00F6t\u00E4. '
u'\u0421\u043F\u0430\u0441\u0438\u0431\u043E!')
LI... | class Myobject:
def __init__(self, index=''):
self.index = index
def __str__(self):
return '<MyObject%s>' % self.index
unicode = u'Hyvää yötä. Спасибо!'
list_with_objects = [my_object(1), my_object(2)]
nested_list = [[True, False], [[1, None, my_object(), {}]]]
nested_tuple = ((True, False), [... |
def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
els... | def fibonacci(n):
if n < 0:
print('Incorrect input')
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(40)) |
for t in range(int(input())):
a,b = input().split()
cnt1,cnt2 = 0,0
for i in range(len(a)):
if a[i] != b[i]:
if b[i] == '0':
cnt1+=1
else:
cnt2+=1
print(max(cnt1,cnt2)) | for t in range(int(input())):
(a, b) = input().split()
(cnt1, cnt2) = (0, 0)
for i in range(len(a)):
if a[i] != b[i]:
if b[i] == '0':
cnt1 += 1
else:
cnt2 += 1
print(max(cnt1, cnt2)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.