content stringlengths 7 1.05M |
|---|
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... |
"""
Dana jest tablica T[N][N] (reprezentująca szachownicę) wypełniona liczbami naturalnymi.
Proszę napisać funkcję która ustawia na szachownicy dwie wieże, tak aby suma liczb na „szachowanych”
przez wieże polach była największa. Do funkcji należy przekazać tablicę, funkcja powinna zwrócić
położenie wież. Uwaga: zakłada... |
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 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... |
# -*- coding: utf-8 -*-
"""Module for flask views.
Only the home page view is defined in this scope. All other views are defined
in nested modules for partitioning.
"""
|
leap = Runtime.start("leap","LeapMotion")
leap.addLeapDataListener(python)
def onLeapData(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... |
podcast_title = 'Chaos im Radio'
hello_text = r'''<p>Der ChaosTreff Potsdam macht mit beim <a href="http://frrapo.de/player/">Freien Radio Potsdam</a>.</p>
<p>Hier könnt ihr Sendungen nachhören.</p>'''
website = 'https://radio.ccc-p.org'
media_base_url = website + '/files'
cover_image = website + '/cover.jpg'
small_... |
"""Implement an algorithm that takes a BST and transform it into a
circular double linked list. The transformation must be done in place.
BST:
4
2 6
1 5 10
CDLL:
______________________
/ \
1 <> 2 <> 4 <> 5 <> 6 <> 10
\__________________... |
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()) |
# O programa calculará o preço da passagem sabendo a distância. Para viagens de até 200km o preço por km
# é de R$ 0,50. Para viagens acima de 200km o preço do km rodado é R$ 0,45
k = float(input('Olá! Qual a distância da sua rota em km? '))
preço = k * 0.5 if k <= 200 else k * 0.45
print('O preço da passagem será de: ... |
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... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 CERN.
#
# Invenio-App-RDM is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Test that all export formats are working."""
def test_export_formats(client, running_app, record):
"""Tes... |
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)
|
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)
|
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> |
# -*- 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):
... |
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")
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
""" Unit test cases for cellular environment and algorithms """
__author__ = 'Ari Saha (arisaha@icloud.com), Mingyang Liu(liux3941@umn.edu)'
|
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',
... |
"""
Xilinx primitive tokens
"""
ASYNC_PORTS = "async_ports"
CLK_PORTS = "clk_ports"
CLOCK_BUFFERS = "clock_buffers"
COMBINATIONAL_CELLS = "combinational_cells"
COMPLEX_SEQUENTIAL_CELLS = "complex_sequential_cells"
DESCRIPTION = "description"
FF_CELLS = "ff_cells"
MISC_CELLS = "misc_cells"
NAME = "name"
POWER_GROUND_CEL... |
#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 combine_toxic_classes(df):
"""""""""
Reconfigures the Jigsaw Toxic Comment dataset from a
multi-label classification problem to a
binary classification problem predicting if a text is
toxic (class=1) or non-toxic (class=0).
Input:
- df: A pandas DataFrame with columns:
... |
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) |
# -*- coding: utf-8 -*-
"""
@Time : 2020/11/26 15:38
@Author : PyDee
@File : __init__.py.py
@description :
"""
|
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... |
colocacao = ('São Paulo','Coritiba','Corinthians','Atlétigo-MG','Ceará','Avaí','Cuiabá','Bragantino','Juventude','Flamengo','Atlético-GO','Santos','Fluminense','Palmeiras','Fortaleza','América-MG','Botafogo','Internacional',
'Goiás','Athletico-PR')
print('=-'*20)
print(f'Lista de times do Brasileirão 2022: {colocacao}'... |
# 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... |
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self, name, score):
# 实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问
self.__name = name
self.__score = score
def get_grade(self):
if self.__score >= 90:
return 'A'
elif sel... |
'''
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
... |
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1 = num1[: : -1]
num2 = num2[: : -1]
multi = [0 for i in range(len(num1) + len(num2))]
for i in range(len(num1)):
... |
# coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015,2017
"""
SPL primitive operators that call a Python function or
callable class are created by decorators provided :py:mod:`streamsx.spl.spl`
Once created the operators become part of a toolkit and may be used
like any other SPL operator.
"... |
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)
|
'''
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... |
frase = str(input('Escreva uma frase: ')).strip().lower()
numA = frase.count('a')
pos1A = frase.find('a') + 1
posFA = frase.rfind('a') + 1
print('A frase digitada possui {} letras A.'.format(numA))
print('A primeira ocorrência da letra A esta na posição {}'.format(pos1A))
print('A última ocorrência da letra A esta na p... |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# https://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
# GENERATED VERSION FILE
# TIME: Fri Mar 20 02:18:57 2020
__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))
|
#Exemplo 2
n1 = float(input('Digite sua primeira nota: '))
n2 = float(input('Digite sua segunda nota: '))
media = (n1 + n2)/ 2
if media >= 5:
print('Muito bem, sua media é de {:.1f} e está ótima!'.format(media))#{:.1f}formatação para uma casa decimal
else:
print('Sua média é de {:.1f}, você precisa estudar mai... |
# 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
... |
# -*- 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) |
"""Top-level package for Webex Bot."""
__author__ = """Finbarr Brady"""
__version__ = '0.2.5'
|
# 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... |
# Error codes due to an invalid request
INVALID_REQUEST = 400
INVALID_ALGORITHM = 401
DOCUMENT_NOT_FOUND = 404
|
# -*- coding: utf-8 -*-
"""This module contains all the LUA code that needs to be on the device
to perform whats needed. They will be uploaded if they doesn't exist"""
# Copyright (C) 2015-2019 Peter Magnusson <peter@kmpm.se>
# pylint: disable=C0301
# flake8: noqa
LUA_FUNCTIONS = ['recv_block', 'recv_name', 'recv', ... |
# 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... |
# 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... |
"""
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This pr... |
# 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()
|
#!/usr/bin/env python3
"""project: Block Letters, created: 2022-01-13, author: seraph★776"""
def letter_S():
"""This function prints uppercase "S" in block letters."""
for row in range(7):
for col in range(5):
if row in [0, 3, 6] and col in [1, 2, 3] or (
col in [0] an... |
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... |
"""
categories: Types,bytearray
description: Array slice assignment with unsupported RHS
cause: Unknown
workaround: Unknown
"""
b = bytearray(4)
b[0:1] = [1, 2]
print(b)
|
"""
Given an integer, write an algorithm to convert it to hexadecimal. For negative
integer, two’s complement method is used.
Note:
All letters in hexadecimal (a-f) must be in lowercase.
The hexadecimal string must not contain extra leading 0s. If the number is
zero, it is represented by a single zer... |
'''
'''
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) |
# Exercício Python 65: Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores.
N = int(input('Numero: '))
lista = []
coun... |
_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(
... |
# Copy this file to config.py and fill the blanks
QCLOUD_APP_ID = ''
QCLOUD_SECRET_ID = ''
QCLOUD_SECRET_KEY = ''
QCLOUD_BUCKET = ''
QCLOUD_REGION = 'sh'
|
class MICOptimizer(object):
"""A simple wrapper class for learning rate scheduling"""
def __init__(self, optimizer):
self.optimizer = optimizer
self.step_num = 0
self.lr = 3e-5
def zero_grad(self):
self.optimizer.zero_grad()
def step(self):
self._update_lr()
... |
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())
|
# 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
... |
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... |
# -*- coding: utf-8 -*-
"""
File Name: two_sum
Author : jing
Date: 2020/3/18
https://leetcode-cn.com/explore/interview/card/tencent/221/array-and-strings/894/
返回的是索引
只有一个结果
不能利用相同的数字
"""
class Solution:
def twoSum(self, nums, target: int):
if nums is None or len(... |
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,
... |
# -*- coding: utf-8 -*-
blupFiles = blupf90(AlphaSimDir, way='burnin_milk', sel='gen')
blupFiles.makeDat_sex(2)
shutil.copy(blupFiles.blupgenParamFile, blupFiles.AlphaSimDir) # skopiraj template blupparam file
# uredi blupparam file
# get variance components from AlphaSim Output Files
OutputFiles = AlphaSim_OutputFil... |
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... |
"""Uma linha de documentação"""
variavel = 'valor'
def funcao():
return 1
|
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
"""
+===================================================+
| © 2019 Privex Inc. |
| https://www.privex.io |
+===================================================+
| ... |
#Cristian Chitiva
#cychitvav@unal.educo
#16/Sept/2018
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... |
#!/usr/bin/python
# vim:fileencoding=utf-8:noet
# (C) 2017 Michał Górny, distributed under the terms of 2-clause BSD license
PV = '0.2.1'
|
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'... |
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)
|
#!/usr/bin/python3
"""
Main module for demo
"""
if __name__ == "__main__":
pass |
"""Exceptions for OpenZWave MQTT."""
class BaseOZWError(Exception):
"""Base OpenZWave MQTT exception."""
class NotFoundError(BaseOZWError):
"""Exception that is raised when an entity can't be found."""
class NotSupportedError(BaseOZWError):
"""Exception that is raised when an action isn't supported.""... |
# Crie uma função que recebe como parâmetro 3 inteiros e retorna a soma dos 3.
def s(a, b, c):
soma = a + b + c
print(soma)
a = int(input('digite o numero: '))
b = int(input('digite o mnumero: '))
c = int(input('digite um numero: '))
s(a, b, c)
|
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!')
|
"""
PASSENGERS
"""
numPassengers = 31043
passenger_arriving = (
(10, 4, 10, 7, 4, 5, 6, 5, 3, 4, 0, 0, 0, 5, 15, 5, 4, 4, 3, 0, 2, 3, 4, 1, 0, 0), # 0
(2, 10, 11, 8, 5, 3, 3, 2, 5, 2, 0, 0, 0, 9, 10, 2, 5, 6, 4, 3, 5, 2, 8, 1, 0, 0), # 1
(1, 9, 6, 9, 8, 5, 5, 4, 1, 1, 2, 2, 0, 10, 4, 8, 11, 12, 5, 4, 2, 4, 4, 2... |
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... |
# 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... |
def compute_epsg(lon, lat):
"""
Compute the EPSG code of the UTM zone which contains
the point with given longitude and latitude
Args:
lon (float): longitude of the point
lat (float): latitude of the point
Returns:
int: EPSG code
"""
# UTM zone number starts from 1 ... |
"""
**kwargs
"""
def print_info(**kwargs):
for key in kwargs:
print('{}: {}'.format(key, kwargs[key]))
if __name__ == '__main__':
print_info(name='Mike', lastname='Red', age=22) |
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... |
# 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... |
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... |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
"""
Documents docstring
"""
|
class Solution(object):
def findPeakElementLinear(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
while i < len(nums):
# check dangerous condition first
if i == len(nums) - 1 or (nums[i + 1] < nums[i]):
return i
... |
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)) |
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def deep_subsets(nums):
r = []
n = len(nums)
if n == 1:
return [nums]
for idx, num in enumerate(nums):
... |
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# 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... |
'''
In this module, we implement selection sort
Time complexity: O(n ^ 2)
'''
def selection_sort(arr):
'''
Sort array using selection sort
'''
for index_x in range(len(arr)):
min_index = index_x
for index_y in range(index_x + 1, len(arr)):
if arr[index_y] < arr[min_index... |
# Link : https://leetcode.com/problems/subtree-of-another-tree/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def sameTree(self , roo... |
"""Cabal packages"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
load(":cc.bzl", "cc_interop_info")
load(":private/context.bzl", "haskell_context", "render_env")
load(":private/dep... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.