content stringlengths 7 1.05M |
|---|
instr = [
"""Digit-symbol coding, part 1 (practice)
At the top of the screen you will see a row of symbols and
a row of numbers. Each symbol is paired with the number below
it.
You will also see one symbol and one number in the middle of
the screen. Your task is to decide whether they make a
correct pair. Respond... |
class Tile():
def __init__(self,bomb=False):
self.bomb = False
self.revealed = False
self.nearBombs = 0
def isBomb(self):
return self.bomb
def isRevealed(self):
return self.revealed
def setBomb(self):
self.bomb=True
def setNearBombs(self,... |
OCTICON_FILE = """
<svg class="octicon octicon-file" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M3.75 1.5a.25.25 0 00-.25.25v11.5c0 .138.112.25.25.25h8.5a.25.25 0 00.25-.25V6H9.75A1.75 1.75 0 018 4.25V1.5H3.75zm5.75.56v2.19c0 .138.112.25.25.25h2.19L9.5 2.... |
### CONFIGS ###
dataset = 'cora'
model = 'VGAE'
input_dim = 10
hidden1_dim = 32
hidden2_dim = 16
use_feature = True
num_epoch = 2000
learning_rate = 0.01 |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a=[*open(0)][1].split()
a,b=[a.count('100'),a.count('200')]
print('YNEOS'[(a+2*b)%2 or b%2 and a<2::2]) |
# clut.py.
#
# clut.py Teletext colour lookup table
# Maintains colour lookups
#
# Copyright (c) 2020 Peter Kwan
#
# 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, includi... |
# record all kinds of type
# pm type
LINKEDIN_TYPE = 1
PM_LANG_ITEM_TYPE = 0
PM_CITY_ITEM_TYPE = 1
PM_SERVICE_ITEM_TYPE = 2
REALTOR_MESSAGE_TYPE = 3
#quiz type
PM_QUIZ_TYPE = 0
#pm inspection report note type
PM_INSPECTION_REPORT_TYPE = 3
PM_EXPENSE_TYPE = 4
#user progress bar
USER_PROGRESS_BAR_TYPE = 0
HOME_PROGRES... |
if request.isInit:
lastVal = 0
else:
if lastVal == 0:
lastVal = 1
else:
lastVal = (lastVal << 1) & 0xFFFFFFFF
request.value = lastVal
|
# Copyright 2009, UCAR/Unidata
# Enumerate the kinds of Sax Events received by the SaxEventHandler
STARTDOCUMENT = 1
ENDDOCUMENT = 2
STARTELEMENT = 3
ENDELEMENT = 4
ATTRIBUTE = 5
CHARACTERS = 6
# Define printable output
_MAP = {
STARTDOCUMENT: "STARTDOCUMENT",
ENDDOCUMENT: "ENDDOCUMENT",
STARTELEMENT: "STARTELEMENT"... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
def select_k_items(stream, n, k):
reservoir = []
for i in range(k):
reservoir.append(stream[i])
if __name__ == '__main__':
stream = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
n = len(stream)
k = 5
select_k_items(stream, n, k) |
#! python3
"""A printing shop runs 16 batches (jobs) every week and each batch requires a
sheet of special colour-proofing paper of size A5.
Every Monday morning, the foreman opens a new envelope, containing a large
sheet of the special paper with size A1.
He proceeds to cut it in half, thus getting two sheets of siz... |
class Solution:
def majorityElement(self, nums: list[int]) -> list[int]:
candidate1, candidate2 = 0, 0
count1, count2 = 0, 0
for num in nums:
if candidate1 == num:
count1 += 1
continue
if candidate2 == num:
count2 += 1... |
# Copyright (c) 2013 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
def GetNumSuffixes(start_state):
"""Compute number of minimal suffixes automaton accepts from each state.
For each state reachable from given s... |
memo=[0, 1]
def fib_digits(n):
if len(memo)==2:
for i in range(2, 100001):
memo.append(memo[i-1]+memo[i-2])
num=str(memo[n])
res=[]
for i in range(0,10):
check=num.count(str(i))
if check:
res.append((check, i))
return sorted(res, reverse=True) |
# Question 1: Write a program that asks the user to enter a string. The program should then print the following:
# a) The total number of characters in the string
# b) The string repeated 10 times
# c) The first character of the string
# d) The first three characters of the string
# e) The last three ... |
_base_ = [
'../swin/cascade_mask_rcnn_swin_small_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py'
]
model = dict(
backbone=dict(
type='CBSwinTransformer',
),
neck=dict(
type='CBFPN',
),
test_cfg = dict(
rcnn=dict(
score_thr=0.001,
nms... |
def test_index(man):
errors = []
G = man.writeTest()
G.addIndex("Person", "name")
G.addVertex("1", "Person", {"name": "marko", "age": "29"})
G.addVertex("2", "Person", {"name": "vadas", "age": "27"})
G.addVertex("3", "Software", {"name": "lop", "lang": "java"})
G.addVertex("4", "Person"... |
DEFAULT_CHUNK_SIZE = 1000
def chunked_iterator(qs, size=DEFAULT_CHUNK_SIZE):
qs = qs._clone()
qs.query.clear_ordering(force_empty=True)
qs.query.add_ordering('pk')
last_pk = None
empty = False
while not empty:
sub_qs = qs
if last_pk:
sub_qs = sub_qs.filter(pk__gt=la... |
indent = 3
key = "foo"
print('\n%s%*s' % (indent, len(key)+3, 'Hello')) # ok: variable length
print("%.*f" % (indent, 1.2345))
def myprint(x, *args):
print("%.3f %.4f %10.3f %1.*f" % (x, x, x, 3, x))
myprint(3)
|
class Admin_string_literal:
def __init__(self):
Admin_string_literal.admin_menu_string = """
Select the operation to perfrom:
1. Create a Topic
2. Remove a Topic
3. Restrict a Topic
4. Purge a Topic
5. Edit a Message
6. Delete a... |
def max_sum_of_increasing_subseq(seq: list[int]) -> int:
"""
O(n^2) time, O(n) extra space
"""
if not seq:
return 0
max_sum = [0 for _ in seq] # the answer to the question if you have end on index i
# max sum ending on index i is seq[i] + prev biggest sum, corresponding to some j < i
... |
class TextXLSError(Exception):
"""Indicates a generic textX-LS-core error."""
pass
class GenerateExtensionError(TextXLSError):
"""Indicates an error while generating an extension."""
def __init__(self, target, cmd_args):
super().__init__(
"Failed to generate the extension for '{}... |
class Floodfill:
"""abstract floodfill class, must specify _is_in_region() condition and
_fill() operation"""
def __init__(self):
pass
def floodfill(self, x, y):
Q = []
if not self._is_in_region(x,y):
return
Q.append([x,y])
while Q != []:
... |
#Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
#
#You may assume no duplicates in the array.
#
#Here are few examples.
#[1,3,5,6], 5 → 2
#[1,3,5,6], 2 → 1
#[1,3,5,6], 7 → 4
#[1,3,5,6], 0 → 0
class Solution(obje... |
PAGES_FOLDER = 'pages'
PUBLIC_FOLDER = 'public'
STATIC_FOLDER = 'static'
TEMPLATE_NAME = 'template.mustache'
|
teisuu = 1
suuji_kous = 3
aru = 2
zenn = 0
for ai in range(suuji_kous):
zenn += teisuu*aru**ai
print(zenn)
|
# elasticmodels/tests/test_settings.py
# author: andrew young
# email: ayoung@thewulf.org
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": ":memory:",
}
}
ROOT_URLCONF = ["elasticmodels.urls"]
INSTALLED_APPS = ["elasticmodels"]
|
# Python - 2.7.6
Test.describe('Basic Tests')
data = [2]
Test.assert_equals(print_array(data), '2')
data = [2, 4, 5, 2]
Test.assert_equals(print_array(data), '2,4,5,2')
data = [2, 4, 5, 2]
Test.assert_equals(print_array(data), '2,4,5,2')
data = [2.0, 4.2, 5.1, 2.2]
Test.assert_equals(print_array(data), '2.0,4.2,5.1... |
def result(score):
min = max = score[0]
min_count = max_count = 0
for i in score[1:]:
if i > max:
max_count += 1
max = i
if i < min:
min_count += 1
min = i
return max_count, min_count
n = input()
score = list(map(int, input().split()))
p... |
DEFAULT_PRAGMAS = (
"akamai-x-get-request-id",
"akamai-x-get-cache-key",
"akamai-x-get-true-cache-key",
"akamai-x-get-extracted-values",
"akamai-x-cache-on",
"akamai-x-cache-remote-on",
"akamai-x-check-cacheable",
"akamai-x-get-ssl-client-session-id",
"akamai-x-serial-no",
)
|
n1 = int(input("digite o valor em metros "))
n2 = int(input("digite o valor em metros "))
n3 = int(input("digite o valor em metros "))
r= (n1**2)+(n2**2)+(n3**2)
print(r) |
__author__ = 'ipetrash'
if __name__ == '__main__':
def getprint(str="hello world!"):
print(str)
def decor(func):
def wrapper(*args, **kwargs):
print("1 begin: " + func.__name__)
print("Args={} kwargs={}".format(args, kwargs))
f = func(*args, **kwargs)
... |
'''
https://youtu.be/-xRKazHGtjU
Smarter Approach: https://youtu.be/J7S3CHFBZJA
Dynamic Programming: https://youtu.be/VQeFcG9pjJU
'''
|
def fit_index(dataset, list_variables):
""" Mapping between index and category, for categorical variables
For each (categorical) variable, create 2 dictionaries:
- index_to_categorical: from the index to the category
- categorical_to_index: from the category to the index
Parameters
-... |
def model(outcome, player1, player2, game_matrix):
"""
outcome [N, 1] where N is games and extra dimension is just 1 or zero depending on whether
player 1 or player 2 wins
player1 is one-hot vector encoding of player id
player2 ""
game_matrix has entries [G,P] (use sparse multiplication COO... |
# inspired from spacy
def add_codes(err_cls):
"""Add error codes to string messages via class attribute names."""
class ErrorsWithCodes(object):
def __getattribute__(self, code):
msg = getattr(err_cls, code)
return '[{code}] {msg}'.format(code=code, msg=msg)
return ErrorsWi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def Insertion_sort(_list):
list_length = len(_list)
i = 1
while i < list_length:
key = _list[i]
j = i - 1
while j >= 0 and _list[j] > key:
_list[j+1] = _list[j]
j -= 1
_list[j+1] = key
i += 1
... |
duzina = 5
sirina = 2
povrsina = duzina * sirina
print('Povrsina je ', povrsina)
print('Obim je ', 2 * (duzina + sirina))
|
# -*- coding: utf-8 -*-
class Type(object):
jianshu_article = 'jianshu_article' # 类型是单篇的文章 TODO
jianshu = 'jianshu' # 类型是简书文章的集锦
jianshu_info = 'jianshu_info'
jianshu_article_type_list = ['jianshu']
info_table = {
'jianshu_info': jianshu_info
}
jianshu_ty... |
""" Constants for event handling in Eris. """
PRIO_HIGH = 0
PRIO_MEDIUM = 1
PRIO_LOW = 2
|
## Python Crash Course
# Exercise 4.10: Slices:
# Using one of the programs you wrote in this chapter, add several lines to the end of the program that do the following:
# • Print the message, The first three items in the list are:
# . Then use a slice to print the fir... |
class Contact:
def __init__(self, fname=None, sname=None, lname=None, address=None, email=None, tel=None):
self.fname = fname
self.sname = sname
self.lname = lname
self.address = address
self.email = email
self.tel = tel |
def response(number):
if number % 4 == 0:
return "Multiple of four"
elif number % 2 == 0:
return "Even"
else:
return "Odd"
def divisible(num, check):
if check % num == 0:
return "Yes, it's evenly divisible"
return "No, it's not evenly divisible"
if __name__ == "__... |
'''
x - Rozwiązania początkowe
x - Długość listy Tabu
x - Od wielkości instancji
x - Zależność od rozwiązania początkowego
x - Wielkość sąsiedztwa
x - Zaleznosc prd od dlugosci tabu list oraz wielkosci instancji (wykres 3D)
'''
def main():
instance_list = []
start_random_simulation()
start_nne_simu... |
class PipelineError(Exception):
pass
class PipelineParallelError(Exception):
pass
|
# 定数
LANG_OPT_JPN = 0 # ひらがな→英語
LANG_OPT_ENG = 0 # 英語→ひらがな
class MikakaConverter:
# みかか変換
def __init__(self):
# コンストラクタ
self.mkk_jp_list = ["ぬ", "ふ", "あ", "う", "え",
"お", "や", "ゆ", "よ", "わ",
"ほ", "へ", "た", "て", "い",
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 实用代码集锦
Desc :
"""
def cool():
print('sample cool,,')
|
# print statement, function definition
name = "Anurag"
age = 30
print(name, age, "python", 2020)
print(name, age, "python", 2020, sep=", ", end=" $$ ")
|
def isPermutation(string_1, string_2):
string_1 = list(string_1)
string_2 = list(string_2)
for i in range(0, len(string_1)):
for j in range(0, len(string_2)):
if string_1[i] == string_2[j]:
del string_2[j]
break
if len(string_2) == 0:
retu... |
""" Regular expressions """
def match(pattern, string, flags=0):
return _compile(pattern, flags).match(string)
def _compile(pattern, flags):
p = sre_compile.compile(pattern, flags)
return p
|
class Observer(object):
"""docstring for Observer"""
def __init__(self):
super(Observer, self).__init__()
self.signalFunc = None
def onReceive(self, signal, emitter):
if self.signalFunc != None and signal in self.signalFunc:
self.signalFunc[signal](emitter)
|
class _SCon:
esc : str = '\u001B'
bra : str = '['
eb : str = esc + bra
bRed : str = eb + '41m'
white : str = eb + '37m'
bold : str = eb + '1m'
right : str = 'C'
left : str = 'D'
down : str = 'B'
up : str = 'A'
reset : str = eb + '0m'
cy... |
#-- 포매팅(formatting)
# ● print만으로는 출력이 좀 불편하다고 느낄 수 있으나 format() 메소드를 사용하면 문자열을 그 이상으로 자유롭게 다루 수 있음
# ● 문자열 내에서 어떤 값이 들어가길 원하는 곳은 {}로 표시함
# ● {} 안의 값들은 숫자로 표한할 수 있으며, format 인자들의 인덱스를 사용함
# ● {0}는 첫 번째 인자인 'apple'을 나타내고
# ● {1}는 첫 번째 인자인 'red'을 나타내고
print('{0} is {1}'.format('apple', 'red'))
#-- 포매팅(formatting) - 키, 사전... |
# tree structure in decoder side
# divide sub-node by brackets "()"
class Tree():
def __init__(self):
self.parent = None
self.num_children = 0
self.children = []
def __str__(self, level = 0):
ret = ""
for child in self.children:
if isinstance(child,type(... |
print('-=-'*10)
print('Analisandor de Triângulos')
print('-=-'*10)
t0 = float(input('Primeiro segmento: '))
t1 = float(input('Segundo segmento:' ))
t2 = float(input('Terceiro segmento:' ))
#Fundamento dos triângulos===================================
if t0<t1+t2 and t1<t0+t2 and t2<t0+t1:
print('Os segmentos acima ... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
N = len(A)
l_sum = A[0]
r_sum = sum(A) - l_sum
diff = abs(l_sum - r_sum)
for i in range(1, N -1):
l_sum += A[i]
r_sum -= A[i]
c_diff = abs(l_sum - r_sum)
if di... |
#!/usr/bin/python3
def uppercase(str):
for c in str:
if (ord(c) >= ord('a')) and (ord(c) <= ord('z')):
c = chr(ord(c)-ord('a')+ord('A'))
print("{}".format(c), end='')
print()
|
# Copyright 2018 The Bazel 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 applicable la... |
ENTRY_POINT = 'split_words'
FIX = """
Add check for lower case and add test.
"""
#[PROMPT]
def split_words(txt):
'''
Given a string of words, return a list of words split on whitespace, if no whitespaces exists in the text you
should split on commas ',' if no commas exists you should return the number of... |
#In PowerShell
"""
function Get-Something {
param (
[string[]]$thing
)
foreach ($t in $things){
Write-Host $t
}
}
"""
#region functions
def powershell_python():
print('This is a function')
#return is key for returning values
return
#positional arguments mandatory,
def powers... |
def calcula_diferenca(A: int, B: int, C: int, D: int):
if (not isinstance(A, int) or
not isinstance(B, int) or
not isinstance(C, int) or
not isinstance(D, int)):
raise(TypeError)
D = A * B - C * D
return f'DIFERENCA = {D}' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################################################
#........../\./\...___......|\.|..../...\.........#
#........./..|..\/\.|.|_|._.|.\|....|.c.|.........#
#......../....../--\|.|.|.|i|..|....\.../.........#
# Mathtin (c) #
#############... |
""" TRABALHANDO COM CONDIÇÕES ANINHADAS - IF / ELIF / ELSE """
nome = str(input("Digite seu Nome: "))
if nome == "Fabio":
print("Que nome Bonito, {}".format(nome))
elif nome == "Gustavo":
print("Esse é o nome do seu professor, {}".format(nome))
else:
print("Não reconheço esse nome {}".format(nome)) |
#
# LeetCode
# Algorithm 104 Maximum depth of binary tree
#
# See LICENSE
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def traverse(self, root, depth):
"""... |
#Question link
#https://practice.geeksforgeeks.org/problems/smallest-subarray-with-sum-greater-than-x/0
def window(arr,n, k):
left=0
right=0
ans=n
sum1=0
while left<n and right<n+1:
if sum1>k:
if left==right:
ans=1
break
... |
s = input()
# s = ' name1'
list_stop = [' ', '@', '$', '%']
list_num = '0123456789'
# flag_true = 0
flag_false = 0
for i in list_num:
if s[0] == i:
flag_false += 1
break
for j in s:
for k in list_stop:
if j == k:
flag_false += 1
break
else:
# f... |
#
# @lc app=leetcode id=1232 lang=python3
#
# [1232] Check If It Is a Straight Line
#
# @lc code=start
class Solution:
def checkStraightLine(self, coordinates):
if len(coordinates) <= 2:
return True
x1, x2, y1, y2 = coordinates[0][0], coordinates[1][0], coordinates[0][1], coordinates[1]... |
class YggException(Exception): pass
class LoginFailed(Exception): pass
class TooManyFailedLogins(Exception): pass
|
class TriggerBase:
def __init__(self, q, events):
self.q = q
self.events = events
def trigger(self, name):
self.q.put(
{'req': 'trigger_animation', 'data': name, 'sender': 'Trigger'})
|
favcolor = {
"Jacob": "Magenta",
"Jason": "Red",
"Anais": "Purple"
}
for name, color in favcolor.items():
print("%s's favorite color is %s" %(name, color))
|
"""Constants for the Vivint integration."""
DOMAIN = "vivint"
EVENT_TYPE = f"{DOMAIN}_event"
RTSP_STREAM_DIRECT = 0
RTSP_STREAM_INTERNAL = 1
RTSP_STREAM_EXTERNAL = 2
RTSP_STREAM_TYPES = {
RTSP_STREAM_DIRECT: "Direct (falls back to internal if direct access is not available)",
RTSP_STREAM_INTERNAL: "Internal",
... |
'''
5. Write a Python program to check whether a specified value is contained in a group of values.
Test Data :
3 -> [1, 5, 8, 3] : True
-1 -> [1, 5, 8, 3] : False
'''
def check_value(group_data, n):
for x in group_data:
if n == x:
return True
else:
return False
print(check_value([1,... |
# Program corresponding to flowchart in this site https://automatetheboringstuff.com/2e/images/000039.jpg
print('Is raining? (Y)es or (N)o')
answer = input()
if answer == 'N':
print('Go outside.')
elif answer == 'Y':
print('Have umbrella? (Y)es or (N)o')
answer2 = input()
if answer2 == 'Y':
print('Go out... |
__all__ = ["TreeDict"]
class TreeDict:
"""Converts a nested dict to an object.
Items in the dict are set to object attributes.
ARTIQ python does not support dict type. Inherit this class to convert the dict to an object.
self.value_parser() can be inherited to parse non-dict values.
Args:
... |
# -*- coding: utf-8 -*-
################################################################################
# LexaLink Copyright information - do not remove this copyright notice
# Copyright (C) 2012
#
# Lexalink - a free social network and dating platform for the Google App Engine.
#
# Original author: Alexander Marqu... |
first_name = input()
second_name = input()
delimeter = input()
print(f"{first_name}{delimeter}{second_name}")
|
class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
class C:
def __init__(self):
self.x = 0
class D(C):
def __init__(self):
super().__init__()
self.y = 1
# super() 的另外一个常见用法出现在覆盖... |
#
# PySNMP MIB module CISCO-ITP-RT-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-RT-CAPABILITY
# Produced by pysmi-0.3.4 at Wed May 1 12:03:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
# -*- coding: utf-8 -*-
qntCaso = int(input())
for caso in range(qntCaso):
listStrTamanhoStr = list()
listStr = list(map(str, input().split()))
for indiceStr in range(len(listStr)): listStrTamanhoStr.append([listStr[indiceStr], len(listStr[indiceStr])])
strSequenciaOrdenadaTamanho = ""
for ch... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Chirstoph Reimers'
__email__ = 'creimers@byteyard.de'
__version__ = '0.1.0.b6'
|
#square pattern
'''
Print the following pattern for the given N number of rows.
Pattern for N = 4
4444
4444
4444
4444
'''
rows=int(input())
for i in range(rows):
for j in range(rows):
print(rows,end="")
print()
|
# PyPy なら通る
N = int(input())
S = input()
result = 0
for i in range(N - 1, 0, -1):
if i <= result:
break
t = 0
for j in range(N - i):
if S[j] == S[j+i]:
t += 1
if t > result:
result = t
if result == i:
break
else:
... |
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"instance": {
"10000": {
"summary_traffic_statistics": {
"ospf_packets_received_sent": {
... |
# Write your solutions for 1.5 here!
class superheroes:
def __int__(self, name, superpower, strength):
self.name=name
self.superpower=superpower
self.strength=strength
def print_me(self):
print(self.name +str( self.strength))
superhero = superheroes("tamara","fly", 10)
superhero.print_me()
|
'''
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?... |
N = int(input())
A, B, C = input(), input(), input()
ans = 0
for i in range(N):
abc = A[i], B[i], C[i]
ans += len(set(abc)) - 1
print(ans)
|
def lin(tam=42):
print('-' * tam)
def leia_int(menssage):
"""
-> Lê um número inteiro
:param menssage: chamada (descrição)
:return: :var numero: número inteiro após ser aprovado por tratamento de erro
"""
while True:
numero = input(menssage)
try:
numero = int(nu... |
contador = 0
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 1
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 2
print("2 elevado a " + str(contador) + " es igual a: " + str(2 ** contador))
contador = 3
print("2 elevado a " + str(contado... |
class Number:
def __init__(self):
self.num = 0
def setNum(self, x):
self.num = x
# na= Number()
# na.setNum(3)
# print(hasattr(na, 'id'))
a = ABCDEFGHIJKLMNOPQRSTUVWXYZ
b = BLUESKYACDFGHIJMNOPQRTVWXZ
class Point:
def __init__(self, x=0, y=0):
self.x = x
... |
n = int(input())
ans = 0
for i in range(n):
a, b = map(int, input().split())
ans += (a + b) * (b - a + 1) // 2
print(ans) |
def is_leap(year):
leap = False
# Write your logic here
if (year%400) == 0:
leap = True
elif (year%100) == 0:
leap = False
elif (year%4) == 0:
leap = True
return leap |
__version__ = '2.0.0'
print("*"*35)
print(f'SpotifyToVKStatus. Version: {__version__}')
print("*"*35)
|
file_name = input('Enter file name: ')
if file_name == 'na na boo boo':
print("NA NA BOO BOO TO YOU - You have been punk'd!")
exit()
else:
try:
file = open(file_name)
except:
print('File cannot be opened')
exit()
count = 0
numbers = 0
average = 0
for line in file:
if line.startswith('X-DSPAM-Confidence'):
... |
""" Module docstring """
def _write_file_impl(ctx):
f = ctx.actions.declare_file("out.txt")
ctx.actions.write(f, "contents")
def _source_list_rule_impl(ctx):
if len(ctx.attr.srcs) != 2:
fail("Expected two sources")
first = ctx.attr.srcs[0].short_path.replace("\\", "/")
second = ctx.attr.sr... |
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
cnt = 1
prod = 9
for i in range(min(n, 10)):
cnt += prod
prod *= 9 - i
return cnt
|
#
# @lc app=leetcode id=46 lang=python3
#
# [46] Permutations
#
# @lc code=start
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
results = []
prev_elements = []
def dfs(elements):
if len(elements) == 0:
results.append(prev_elements[:])
... |
def count_up(start, stop):
"""Print all numbers from start up to and including stop.
For example:
count_up(5, 7)
should print:
5
6
7
"""
# YOUR CODE HERE
# print(start)
# start += 1
# print(start)
# parameters can be modified
while start <= sto... |
def user(*args):
blank=[]
for num in args:
blank+=1
return arg
user() |
tag = 0
# Bestimme Uhrzeit, zu der Ebbe ist
ebbeStunde = 4.0
ebbeMinute = 47.0
println("Tag {} - Ebbe: {} Uhr und {} Minuten"
.format(tag, int(ebbeStunde), int(ebbeMinute)))
# Berechne Ebbezeit als Kommazahl
ebbeKomma = ebbeStunde + ebbeMinute / 60.0
# Berechne Zeit zwischen Ebbe und Ebbe als Kommazahl
tide... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.