content stringlengths 7 1.05M |
|---|
DECIMALS = {"GNG-8d7e05" : 1000000000000000000,
"MEX-4183e7" : 1000000000000000000,
"LKMEX-9acade" : 1000000000000000000,
"WATER-104d38" : 1000000000000000000}
TOKEN_TYPE = {"GNG-8d7e05" : "token",
"MEX-4183e7" : "token",
"WARMY-cc922b": "NFT",
... |
def bubblesort(unsorted):
counter = 0
# Vorerst Endlosschleife
while True:
# Bis auf Weiteres gilt die Liste als sortiert
is_sorted = True
# Erstes bis vorletztes Element
for i in range(0, len(unsorted) - 1):
counter += 1
# Aktuelles Element größer als... |
class Mime(object):
def __init__(self,content_type, category, extension, stream=False, use_file_name=False):
self.content_type = content_type
self.category = category
self.extension = extension
self.stream = stream
self.use_file_name = use_file_name
class Mimes(object):
... |
class Peak:
"""A peak found in spectra.
Attributes:
id: Rounded X-coordinate used to collate peak data
x: X-coordinates of peak along its traversal through spectra
y: Y-coordinates of peak along its traversal through spectra
z: Z-coordinates of peak along its traversal through s... |
_base_ = './classifier.py'
model = dict(
type='TaskIncrementalLwF',
head=dict(
type='TaskIncLwfHead'
)
)
|
if 'photo' in longpoll[pack['userid']]['object']['attachments'][0]:
ret = longpoll[pack['userid']]['object']['attachments'][0]['photo']['sizes']
num = 0
for size in ret:
if size['width'] > num:
num = size['width']
url = size['url']
index = requests.get('https://yandex.ru/images/search?url='+url+'&rpt=imagev... |
def part_one(inputs):
return get_acc(inputs, False)
def part_two(inputs):
for current_line in range(len(inputs)):
backup = inputs[current_line]
try:
if inputs[current_line][:3] == 'nop' and inputs[current_line][4:] != '+0':
inputs[current_line] = 'jmp' + inp... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Make subpackages available:
__all__ = ['blockstorage', 'compute', 'config', 'database', 'dns', 'firewall', 'identity', 'images', 'loa... |
DWARVES_NUM = 9
dwarves = [int(input()) for _ in range(DWARVES_NUM)]
sum = sum(dwarves)
two_fake_sum = sum - 100
for i in range(DWARVES_NUM):
for j in range(DWARVES_NUM):
if i != j and dwarves[i] + dwarves[j] == two_fake_sum:
fake1 = i
fake2 = j
dwarves.pop(fake1)
dwarves.pop(fak... |
'''
Since lists are mutable, this means that we will be using lists for
things where we might intend to manipulate the list of data, so how
can we do that? Turns out we can do all sorts of things.
We can add, remove, count, sort, search, and do quite a few other things
to python lists.
'''
# first we need an example... |
while True:
try:
a = float(input())
except EOFError:
break
print('|{:.4f}|={:.4f}'.format(a, abs(a)))
|
# Given an array with n objects colored red, white or blue,
# sort them in-place so that objects of the same color are adjacent,
# with the colors in the order red, white and blue.
# Here, we will use the integers 0, 1, and 2
# to represent the color red, white, and blue respectively.
# Note: You are not suppose to u... |
def computador_escolhe_jogada(fn, fm):
repetir = True
pecas_tirar_pc = 1
aux = fn
while pecas_tirar_pc <= fm and repetir:
fn = aux - pecas_tirar_pc
if fn % (fm + 1) == 0:
repetir = False
else:
pecas_tirar_pc = pecas_tirar_pc + 1
if pecas_tira... |
# lower case because appears as wcl section and wcl sections are converted to lowercase
META_HEADERS = 'h'
META_COMPUTE = 'c'
META_WCL = 'w'
META_COPY = 'p'
META_REQUIRED = 'r'
META_OPTIONAL = 'o'
FILETYPE_METADATA = 'filetype_metadata'
FILE_HEADER_INFO = 'file_header'
USE_HOME_ARCHIVE_INPUT = 'use_home_archive_input... |
"""Top-level package for mkdocs-github-dashboard."""
__author__ = """mkdocs-github-dashboard"""
__email__ = 'ms.kataoka@gmail.com'
__version__ = '0.1.0'
|
# -*- coding: utf-8 -*-
def main():
m, n = map(int, input().split())
unit = m // n
print(m - (unit * (n - 1)))
if __name__ == '__main__':
main()
|
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
n=len(prices)
if k>n//2:
return sum([prices[i+1]-prices[i] if prices[i+1]>prices[i] else 0 ... |
rows = int(input())
number = 1
for i in range(rows):
for j in range(i + 1):
print(number, end=' ')
number += 1
print()
|
# list examples
z=[1,2,3]
assert z.__class__ == list
assert isinstance(z,list)
assert str(z)=="[1, 2, 3]"
a=['spam','eggs',100,1234]
print(a[:2]+['bacon',2*2])
print(3*a[:3]+['Boo!'])
print(a[:])
a[2]=a[2]+23
print(a)
a[0:2]=[1,12]
print(a)
a[0:2]=[]
print(a)
a[1:1]=['bletch','xyzzy']
print(a)
a[:0]=a
print(a)
a[:]=[... |
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
# initialization:
dp = [0 for _ in range(n + 1)]
dp[0] = 1
dp[1] = 1
# state: dp[i] represents how many ways to reach step i
# f... |
Name=input("enter the name ")
l=len(Name)
s=""
while l>0:
s+=Name[l-1]
l-=1
if s==Name:
print(" Name Plindrome "+Name)
else:
print("Name not Plindrome "+Name) |
#
# PySNMP MIB module OPENBSD-SENSORS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OPENBSD-SENSORS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
"""
After an apology from the opponent (they play C while it plays D, only happens when they play D first), if the opponent
immediately plays D, it plays another C instead of punishing in order to encourage the opponent to get back to CC-chain
(i.e. olive branch). If it plays D in this turn or the next one, go full D.
... |
# Define a Product class. Objects should have 3 variables for price, code, and quantity
class Product:
def __init__(self, price=0.00, code='aaaa', quantity=0):
self.price = price
self.code = code
self.quantity = quantity
def __repr__(self):
return f'Product({self.price... |
"""
Counts total number of documents.
"""
def do_query(archives, config_file=None, logger=None, context=None):
"""
Iterate through archives and return all titles grouped by year.
"""
# [archive, archive, ...]
documents = archives.flatMap(
lambda archive: [(document.year, document) for docu... |
class Solution:
def sumZero(self, n: int) -> List[int]:
ans = []
for i in range(n//2):
ans.append(i+1)
ans.append(-i-1)
if n % 2 != 0:
ans.append(0)
return ans |
INCHES_PER_FOOT = 12.0 # 12 inches in a foot
INCHES_PER_YARD = INCHES_PER_FOOT * 3.0 # 3 feet in a yard
UNITS = ("in", "ft", "yd")
def inches_to_feet(x, reverse=False):
"""
Terminal command | pyment -w -o numpydoc inches_to_feet.py
Flags
-w | overwrite
-o <style> | styleput in NumPy D... |
"""
Initial settings for Up and Down the River
"""
class Settings() :
def __init__(self) :
"""Initializes static settings"""
#Screen Settings
self.screen_width = 1400
self.screen_height = 800
self.bg_color = (34, 139, 34)
#Basic settings
self.number_of_play... |
test = {
'name': 'Problem 5',
'points': 2,
'suites': [
{
'cases': [
{
'code': r"""
>>> expr = read_line('(+ 2 2)')
>>> scheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors
4
>>> expr = read_line('(+ (+ 2 2) (+ 1 3)... |
class A:
def __init__(self, a):
pass
class B(A):
def __init__(self, a=1):
A.__init__(self, a) |
#!/usr/bin/env python
# coding: utf-8
# # section 7: Exceptions :
#
# ### writer : Faranak Alikhah 1954128
# ### 1.Exceptions :
#
#
# In[ ]:
n=int(input())
for i in range(n):
try:
a,b=map(int,input().split())
print(a//b)# need to be integer
except Exception as e:
print ("Erro... |
class HealthController:
"""
Manages interactions with the /health endpoints
"""
def __init__(self, client):
self.client = client
def check_health(self):
"""
GET request ot the /health endpoint
:return: Requests Response Object
"""
return self.client.c... |
class ContainerSpec():
REPLACEABLE_ARGS = ['randcon', 'oracle_server', 'bootnodes', 'genesis_time']
def __init__(self, cname, cimage, centry):
self.name = cname
self.image = cimage
self.entrypoint = centry
self.args = {}
def append_args(self, **kwargs):
self.args.... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/80471495
# IDEA : OPERATION : INVERSE -> Exclusive or (1->0, 0->1)
# NOTE : Exclusive or
# In [29]: x=1
# In [30]: x
# Out[30]: 1
# In [31]: x^=1
# In [32]: x
# Out[32]: 0
# In [33]: x=0
# In [34]: x
# Out[34]: 0
# In [35]: x^=1
# In [36]: x
# Out... |
#
# This file is part of snmpresponder software.
#
# Copyright (c) 2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpresponder/license.html
#
class Numbers(object):
current = 0
def getId(self):
self.current += 1
if self.current > 65535:
self.current = 0
... |
"""
This is the "Rotate Image" problem on Leetcode: https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/770
"""
# Out of Place Solution
def rotate_out_of_place(matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
"""
Idea #1: Swaps
A: movin... |
def _get_dart_host(config):
elb_params = config['cloudformation_stacks']['elb']['boto_args']['Parameters']
rs_name_param = _get_element(elb_params, 'ParameterKey', 'RecordSetName')
dart_host = rs_name_param['ParameterValue']
return dart_host
def _get_element(l, k, v):
for e in l:
if e[k]... |
# Calculate the smallest Multiple
def smallestMultiple(n):
smallestMultiple = 1
while(True):
evenMultiple = True
for i in range(1, int(n) + 1):
if(smallestMultiple % i != 0):
evenMultiple = False
break
if(evenMultiple):
return small... |
class User:
'''
Class that generates a new instance of a passlocker user
__init__method that helps us to define properties for our objects
Args:
name:New user name
password:New user password
'''
user_list=[]
def __init__(self,name,password):
self.na... |
# output: ok
def foo(x):
yield 1
yield x
iter = foo(2)
assert next(iter) == 1
assert next(iter) == 2
def bar(array):
for x in array:
yield 2 * x
iter = bar([1, 2, 3])
assert next(iter) == 2
assert next(iter) == 4
assert next(iter) == 6
def collect(iter):
result = []
for x in iter:
... |
RTL_LANGUAGES = {
'he', 'ar', 'arc', 'dv', 'fa', 'ha',
'khw', 'ks', 'ku', 'ps', 'ur', 'yi',
}
COLORS = {
'primary': '#0d6efd', 'blue': '#0d6efd', 'secondary': '#6c757d',
'success': '#198754', 'green': '#198754', 'danger': '#dc3545',
'red': '#dc3545', 'warning': '#ffc107', 'yellow': '#ffc107',
... |
COINBASE_MATURITY = 500
INITIAL_BLOCK_REWARD = 20000
INITIAL_HASH_UTXO_ROOT = 0x21b463e3b52f6201c0ad6c991be0485b6ef8c092e64583ffa655cc1b171fe856
INITIAL_HASH_STATE_ROOT = 0x9514771014c9ae803d8cea2731b2063e83de44802b40dce2d06acd02d0ff65e9
MAX_BLOCK_BASE_SIZE = 2000000
BEERCHAIN_MIN_GAS_PRICE = 40
BEERCHAIN_MIN_GAS_PRICE... |
class AgentTrainer(object):#作为MADDPGtrainer的父类,以下函数在子类中被重构
def __init__(self, name, model, obs_shape, act_space, args):
raise NotImplemented()
def action(self, obs):
raise NotImplemented()#如果这个方法行不通就找别的方法来完成https://www.jianshu.com/p/a8613baefa30
def process_experience(self, obs, act, rew, ... |
# 461. Hamming Distance
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count('1') |
print("Trick or Treat!")
row1 = ["🎃", "🎃", "🎃"]
row2 = ["🎃", "🎃", "🎃"]
row3 = ["🎃", "🎃", "🎃"]
maps = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = str(input("Where do you want to put the skull?: "))
horizontal = int(position[0])
vertical = int(position[1])
selected_row = maps[vertical - 1]
sel... |
MATERIALS = [
"gold", "silver", "bronze", "copper",
"iron", "titanium", "stone", "lithium",
"wood", "glass", "bone", "diamond"
]
PLACES = [
"cemetery", "forest", "desert", "cave",
"church", "school", "montain", "waterfall",
"prison", "garden", "crossroad", "nexus"
]
AMULETS = [
"warrior", ... |
# -*- coding: utf-8 -*-
a = ['doge1','doge2','doge3','doge4']
print(a)
|
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] < target:
lo = mid + 1
elif nums[mid] > target:
hi = mid
else:
... |
#
# PySNMP MIB module DAVID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DAVID-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:21:39 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23... |
journey_cost = float(input())
months = int(input())
saved_money = 0
for i in range(1, months+1):
if i % 2 != 0 and i != 1:
saved_money = saved_money * 0.84
if i % 4 == 0:
saved_money = saved_money * 1.25
saved_money += journey_cost / 4
diff = abs(journey_cost - saved_money)
if saved_mo... |
#Crie um programa que calcule determinado(Qualquer valor) desconto,
# e aplique esse desconto no final da comprar daquele usuario
#Entrada de Dados
nomeC = str(input('Seja Bem-Vindo!\nInfome seu nome completo, por favor.')).upper()
nomeProduto = str(input('Informe o nome do produto: ')).upper()
valorP = float(input('I... |
subscription_data=\
{
"description": "A subscription to get info about Room1",
"subject": {
"entities": [
{
"id": "Room1",
"type": "Room",
}
],
"condition": {
"attrs": [
"p3"
]
}
},
"notification": {
"http": {
"url": "http://192.168.100.162:88... |
with open('file_example.txt', 'r') as file:
contents = file.read()
print(contents)
|
class HistoryStatement:
def __init__(self, hashPrev, hashUploaded, username, comment=""):
self.hashPrev = hashPrev
self.hashUploaded = hashUploaded
self.username = username
self.comment = comment
def to_bytes(self):
buf = bytearray()
buf.extend(self.hashPrev)
buf.extend(self.hashUploaded)
... |
_base_ = [
'../_base_/models/upernet_swin.py', '../_base_/datasets/uvo_finetune.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(
pretrained='PATH/TO/YOUR/swin_large_patch4_window12_384_22k.pth',
backbone=dict(
pretrain_img_size=384,
embed_dims=... |
class IDependency:
pass
class IScoped(IDependency):
pass
def __del__(self):
pass
class ISingleton(IDependency):
pass
|
h = int(input())
x = int(input())
y = int(input())
result = 'Outside'
# Base, left vertical, left horizontal, middle left etc.
if (3*h >= x >= 0 == y) or (x == 0 <= y <= h) or (0 <= x <= h == y) or (x == h <= y <= 4*h) or \
(h <= x <= 2*h and y == 4*h) or (x == 2*h and h <= y <= 4*h) or (2*h <= x <= 3*h and... |
# https://stackoverflow.com/questions/24852345/hsv-to-rgb-color-conversion
def hsv_to_rgb(h, s, v):
if s == 0.0: return (v, v, v)
i = int(h*6.) # XXX assume int() truncates!
f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6
if i == 0: return (v, t, p)
if i == 1: r... |
class Parameter:
def __init__(self,
name,
prior,
initial_value,
transform=None,
fixed=False):
self.name = name
self.prior = prior
self.transform = (lambda x: x) if transform is None else transform
se... |
class Solution:
labs = []
def __init__(self, T):
self.z = 0
self.x = []
for i in range(T):
self.x.append(0)
def calculate_z(self):
if len(self.labs) == 0:
return 0
self.z = 0
for i in range(len(self.labs)):
for j in range(s... |
symbol = input()
count = int(input())
c = 0
for i in range(count):
if input() == symbol:
c += 1
print(c)
|
#!/usr/bin/python
'''
Priority queue with random access updates
-----------------------------------------
.. autoclass:: PrioQueue
:members:
:special-members:
'''
#-----------------------------------------------------------------------------
class PrioQueue:
'''
Priority queue that supports updating pr... |
SETTINGS_TMPL = '''import os
from glueplate import Glue as _
settings = _(
blog = _(
title = '{blog_title}',
base_url = '{base_url}',
language = '{language}',
),
dir = _(
output = os.path.abspath(os.path.join('..', 'out'))
),
GLUE_PLATE_PLUS_BEFORE_template_dirs = [o... |
# code to find if given string
# is K-Palindrome or not
"""
Explanation
Process all characters one by one staring from either from left or right sides of both strings.
Let us traverse from the right corner, there are two possibilities for every pair of character being traversed.
If last characters of two strings a... |
class Dog:
kind = 'canine'
tricks = [] #mistaken use
def __init__(self, name):
self.name = name
self.tricksInstance = []
def add_trick(self, trick):
self.tricks.append(trick)
def add_trick_instance(self, trick):
self.tricksInstance.append(trick)
d = Dog('Fido'... |
#!/usr/bin/env python3
#----------------------------------------------------------------------------------------------------------------------#
# #
# Tuplex: Blazing... |
# The following is the homework 4 for course MIS3500
# This assignment is Home Work 4
def file_read():
add = 0 # variable for adding total
counter = 0 # counter to understand how many counts are there
prices = []
buy = 0
iterative_profit = 0
total_profit = 0
first_buy = 0
file = open("... |
# -*- coding: utf-8 -*-
# @Time : 2021-07-31 19:34
# @Author : Ze Yi Sun
# @Site : BUAA
# @File : question.py
# @Software: PyCharm
class Question(object):
def __init__(self, statement: str):
self.statement = statement
def show(self):
return "None"
def check_correctness(self, answer: str) -... |
class Solution(object):
def validMountainArray(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
i=0
j=len(arr)-1
while i<j and (arr[i] < arr[i+1]):
i+=1
while j>0 and (arr[j-1] > arr[j]):
j-=1
return i > 0 and j <... |
"""Top-level package for BakpdlBot."""
__author__ = """Mick Boekhoff"""
__email__ = 'mickboekhoff@hotmail.com'
__version__ = '0.1.0'
|
class Solution:
def countSubstrings(self, s: str) -> int:
p = len(s)
dp = [[i,i+1] for i in range(len(s))]
for i in range(1, len(s)):
for j in dp[i-1]:
if j-1 >= 0 and s[j-1] == s[i]:
p += 1
dp[i].append(j-1)
... |
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
'''
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
#
r... |
artifacts = {
"io_bazel_rules_scala_scala_library": {
"artifact": "org.scala-lang:scala-library:2.11.12",
"sha256": "0b3d6fd42958ee98715ba2ec5fe221f4ca1e694d7c981b0ae0cd68e97baf6dce",
},
"io_bazel_rules_scala_scala_compiler": {
"artifact": "org.scala-lang:scala-compiler:2.11.12",
... |
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
|
# The opcode tables were taken from Mammon_'s Guide to Writing Disassemblers in Perl, You Morons!"
# and the bastard project. http://www.eccentrix.com/members/mammon/
INSTR_PREFIX = 0xF0000000
ADDRMETH_MASK = 0x00FF0000
ADDRMETH_A = 0x00010000 # Direct address with segment prefix
ADDRMETH_B = 0x00020000 # VEX.v... |
class StubCursor(object):
column = 0
row = 0
def __iter__(self):
return iter([self.row, self.column])
@property
def coords(self):
return self.row, self.column
@coords.setter
def coords(self, coords):
self.row, self.column = coords
|
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2010-2019 fasiondog/hikyuu
#
# 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 r... |
cont = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez')
n = int(input('Digite um número entre 0 e 10: '))
print(f'Você digitou o número {cont[n]}.')
|
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
def sub(self):
return self.a - self.b
def add2(self, a, b):
... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'verbose_libraries_build%': 0,
'instrumented_libraries_jobs%': 1,
'instrumented_libraries_cc%': '<!(cd <(DEPTH) && pwd -P)/<(m... |
'''
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
'''
class S... |
# Write a Python program to add an item in a tuple
tuplex = ('physics', 'chemistry', 1997, 2000)
tuple = tuplex + (5,)
print(tuple)
#2nd method
tuple = tuplex[:3] + (23,56,7)
print(tuple)
#3rd method
listx = list(tuplex)
listx.append(30)
tuplex = tuple(listx)
print(tuplex) |
class ActionBatchAppliance(object):
def __init__(self):
super(ActionBatchAppliance, self).__init__()
def updateNetworkApplianceConnectivityMonitoringDestinations(self, networkId: str, **kwargs):
"""
**Update the connectivity testing destinations for an MX network**
https://dev... |
contador = 0
file = open("funciones_matematicas.py","w")
funcs = {}
def print_contador():
print(contador)
def aumentar_contador():
global contador
contador += 1
def crear_funcion():
ecuacion = input("Ingrese ecuacion: ")
def agregar_funcion():
f = open("funciones_matematicas.py","w")
ecuacion = input("Ingrese ... |
class SlotPickleMixin(object):
"""
This mixin makes it possible to pickle/unpickle objects with __slots__ defined.
Origin: http://code.activestate.com/recipes/578433-mixin-for-pickling-objects-with-__slots__/
"""
def __getstate__(self):
return dict(
(slot, getattr(self, slot))
... |
N = int(input())
a = sorted(map(int, input().split()), reverse=True)
print(sum([a[n] for n in range(1, N * 2, 2)]))
|
p = int(input('Digite o primeiro termo de uma PA: '))
r = int(input('Digite uma razão de uma PA: '))
d = p + 9 * r
print('OS 10 PRIMEIROS TERMOS DESSA PA É:')
for c in range(p, d + r, r):
print(c, end=' ')
|
def solution(lottos, win_nums):
answer = []
zeros=0
for i in lottos:
if(i==0) : zeros+=1
correct = list(set(lottos).intersection(set(win_nums)))
_dict = {6:1,5:2,4:3,3:4,2:5,1:6,0:6}
answer.append(_dict[len(correct)+zeros])
answer.append(_dict[len(correct)])
return answer
|
class Solution:
def solve(self, path):
ans = []
for part in path:
if part == "..":
if ans: ans.pop()
elif part != ".": ans.append(part)
return ans
|
# https://www.codewars.com/kata/523a86aa4230ebb5420001e1
def letterCounter(word):
letters = {}
for letter in word:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
return letters
def anagrams(word, words):
anag = []
wordMap = letterCounter... |
# %%
def Naive(N):
is_prime = True
if N <= 1 :
is_prime = False
else:
for i in range(2, N, 1):
if N % i == 0:
is_prime = False
return(is_prime)
def main():
N = 139
print(f"{N} prime ? : {Naive(N)}")
if __name__=="__main__":
main()... |
'''
313B. Ilya and Queries
dp, 1300, https://codeforces.com/contest/313/problem/B
'''
sequence = input()
length = len(sequence)
m = int(input())
dp = [0] * length
if sequence[0] == sequence[1]:
dp[1] = 1
for i in range(1, length-1):
if sequence[i] == sequence[i+1]:
dp[i+1] = dp[i] + 1
else:
... |
def has_adjacent_digits(password):
digit = password % 10
while password != 0:
password = password // 10
if digit == password % 10:
return True
else:
digit = password % 10
return False
def has_two_adjacent_digits(password):
adjacent_digits = {}
digit ... |
def all_perms(str):
if len(str) <=1:
yield str
else:
for perm in all_perms(str[1:]):
for i in range(len(perm)+1):
#nb str[0:1] works in both string and list contexts
yield perm[:i] + str[0:1] + perm[i:]
|
print('Vamos calcular o aumento do seu salário')
salario = float(input('Digite o valor do seu salário R$'))
if salario > 1250:
aumento = salario * 0.10
print('Seu \033[4;31maumento\033[m será de \033[1;34mR${:.2f}\033[m, salário total R${:.2f}'.format(aumento, salario + aumento))
else:
aumento = salario * 0... |
#!/usr/bin/env python2
#-*- coding:utf-8 -*-
"""
Author: Wang, Jun
Email: wangjun41@baidu.com
Date: 2018-11-16
"""
class BaseException(Exception):
"base exception"
def __init__(self, msg):
self.msg = msg
class UnsupportedError(BaseException):
"""Not support"""
def __init__(self, msg):
... |
# Copyright 2010 Google Inc.
#
# 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 applicable law or agreed to ... |
# Problem 1- Summation of primes
# https://projecteuler.net/problem=10
# Answer =
def question():
print("""The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.""")
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if n... |
#!/usr/bin/env python
# coding: utf-8
# # 7: Dictionaries Solutions
#
# 1. Below are two lists, `keys` and `values`. Combine these into a single dictionary.
#
# ```python
# keys = ['Ben', 'Ethan', 'Stefani']
# values = [1, 29, 28]
# ```
# Expected output:
# ```python
# {'Ben': 1, 'Ethan': 29, 'Stefani': 28}
# ```
# ... |
np = int(input('Say a number: '))
som = 0
for i in range(1,np):
if np%i == 0:
print (i),
som += i
if som == np:
print('It is a perfect number!')
else:
print ('It is not a perfect number')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.