content stringlengths 7 1.05M |
|---|
def main():
# Write code here
while True:
N=int(input())
if 1<=N and N<=100:
break
List_elements=[]
List_elements=[int(x) for x in input().split()]
#List_elements.append(element)
List_elements.sort()
print(List_elements)
Absent_students=[]
... |
# -*- coding: utf-8 -*-
def test_modules_durations(testdir):
# create a temporary pytest test module
testdir.makepyfile(
test_foo="""
def test_sth():
assert 2 + 2 == 4
"""
)
# run pytest with the following cmd args
result = testdir.runpytest("--modules-durations=2... |
load(":dev_binding.bzl", "envoy_dev_binding")
load(":genrule_repository.bzl", "genrule_repository")
load("@envoy_api//bazel:envoy_http_archive.bzl", "envoy_http_archive")
load("@envoy_api//bazel:external_deps.bzl", "load_repository_locations")
load(":repository_locations.bzl", "REPOSITORY_LOCATIONS_SPEC")
load("@com_go... |
class Solution:
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
Time: O(log n)
Space: O(1)
"""
low = 0
high = len(nums) - 1
while low < high:
m1 = (low + high) // 2
m2 = m1 + 1
if nums[... |
def get_gini(loc, sheet):
df = pd.read_excel(loc,sheet_name = sheet)
df_2 = df[['PD','Default']]
gini_df = df_2.sort_values(by=["PD"],ascending=False)
gini_df.reset_index()
D = sum(gini_df['Default'])
N = len(gini_df['Default'])
default = np.array(gini_df.Default)
proxy_data_arr = np.cum... |
VALID_COLORS = ['blue', 'yellow', 'red']
def print_colors():
while True:
color = input('Enter a color: ').lower()
if color == 'quit':
print('bye')
break
if color not in VALID_COLORS:
print('Not a valid color')
continue
prin... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return he... |
a = int(input())
b = {}
def fab(a):
if a<=1:
return 1
if a in b:
return b[a]
b[a]=fab(a-1)+fab(a-2)
return b[a]
print(fab(a))
print(b)
#1 1 2 3 5 8 13 21 34
|
# Mocapy: A parallelized Dynamic Bayesian Network toolkit
#
# Copyright (C) 2004 Thomas Hamelryck
#
# This library 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... |
def gen():
yield 3 # Like return but one by one
yield 'wow'
yield -1
yield 1.2
x = gen()
print(next(x)) # Use next() function to go one by one
print(next(x))
print(next(x))
print(next(x)) |
class MTransformationMatrix(object):
"""
Manipulate the individual components of a transformation.
"""
def __eq__(*args, **kwargs):
"""
x.__eq__(y) <==> x==y
"""
pass
def __ge__(*args, **kwargs):
"""
x.__ge__(y) <==> x>=y
... |
while True:
primeiro = int(input('primeiro valor '))
segundo = int(input('segundo valor '))
opcao = int()
while opcao != 4:
opcao = int(input('-==-==-==-==-==-==-==-==-==-==-==-==-\n [1] somar\n [2] multiplicar\n [3] maior\n [4] novos números\n [5] sair\n-==-==-==-==-==-==-==-==-==-==... |
# Fonction pour voir si une chaine de charactère peut être transformé en entier
def can_convert_to_int(msg: str) -> bool:
try:
int(msg)
return True
except:
return False |
def tokenize(sentence):
return sentence.split(" ")
class InvertedIndex:
def __init__(self):
self.dict = {}
def get_docs_ids(self, token):
if token in self.dict:
return self.dict[token]
else:
return []
def put_token(self, token, doc_i... |
VERSION = "1.1"
SOCKET_PATH = "/tmp/optimus-manager"
SOCKET_TIMEOUT = 1.0
STARTUP_MODE_VAR_PATH = "/var/lib/optimus-manager/startup_mode"
REQUESTED_MODE_VAR_PATH = "/var/lib/optimus-manager/requested_mode"
DPI_VAR_PATH = "/var/lib/optimus-manager/dpi"
TEMP_CONFIG_PATH_VAR_PATH = "/var/lib/optimus-manager/temp_conf_pa... |
'''from math import factorial
a = int(input('Digite um valor para calcular o fatorial: '))
b = a
c = factorial(a)
while b >= 2:
print(f'{a} x {b-1}', end=' > ')
b -= 1
print(c)'''
n = int(input('Digite um número para calcular seu Fatorial: '))
c = n
f = 1
while c > 0:
print(f'{c}',end='')
print(' x ' i... |
#!/usr/bin/env python3
"""
Copyright (c) 2019: Scott Atkins <scott@kins.dev>
(https://git.kins.dev/igrill-smoker)
License: MIT License
See the LICENSE file
"""
__author__ = "Scott Atkins"
__version__ = "1.4.0"
__license__ = "MIT" |
# OPERADORES ARITMÉTICOS
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
# + Adição
print('Adição', n1+n2)
# - Subtração
print('Subtração', n1-n2)
# * Multiplicação
print('Multiplicação', n1*n2)
# / Divisão
print('Divisão', n1/n2)
# ** Potenciação
print('Potenciação', n1**n2)
print('Poten... |
'''
Create a customer class
Add a constructor with parameters first, last, and phone_number
Create public attributes for first, last, and phone_number
STUDENT MUST ALSO MODIFY INVOICE CLASS TO USE THIS CLASS
SEE INVOICE file FOR INSTRUCTIONS
'''
class Customer:
def __init__(self, first, last, phone_number):
... |
d=[int(i) for i in input().split()]
s=sum(d)
result=0
if s%len(d)==0:
for i in range(len(d)):
if d[i]<(s//len(d)):
result=result+((s//len(d))-d[i])
print(result,end='')
else:
print('-1',end='') |
c = float(input('A temperatura em C°: '))
#f = ((9*c)/5)+32
f = 9*c/5+32
#Não precisamos usar os parenteses por causa da ordem de presedencia!!
print('A temperatura em {} °C é {} °F '.format(c, f))
|
N = int(input())
def brute_force(s, remain):
if remain == 0:
print(s)
else:
brute_force(s + "a", remain - 1)
brute_force(s + "b", remain - 1)
brute_force(s + "c", remain - 1)
brute_force("", N)
|
"""
"""
# Created on 2019.08.31
#
# Author: Giovanni Cannata
#
# Copyright 2014 - 2020 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Founda... |
class School:
def __init__(self, name, num_pupils, num_classrooms):
self.name = name
self.num_pupils = num_pupils
self.num_classrooms = num_classrooms
def calculate_average_pupils(self):
return self.num_pupils / self.num_classrooms
def show_info(self):
"""
>>> s = School("Eveyln Intermediate", 96, 15... |
class FatalErrorResponse:
def __init__(self, message):
self._message = message
self.result = message
self.id = "error"
def get_audit_text(self):
return 'error = "{0}", (NOT PUBLISHED)'.format(self._message)
|
"""
Copyright 2010 Rusty Klophaus <rusty@basho.com>
Copyright 2010 Justin Sheehy <justin@basho.com>
Copyright 2009 Jay Baird <jay@mochimedia.com>
This file is provided to you 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 o... |
def my_init(shape, dtype=None):
array = np.array([
[0.0, 0.2, 0.0],
[0.0, -0.2, 0.0],
[0.0, 0.0, 0.0],
])
# adds two axis to match the required shape (3,3,1,1)
return np.expand_dims(np.expand_dims(array,-1),-1)
conv_edge = Sequential([
Conv2D(kernel_size=(3,3), filters=1,... |
banks = [
# bank 0
{
'ram': {
'start': 0xB848,
'end': 0xBFCF
},
'rom': {
'start': 0x3858,
'end': 0x3FDF
},
'offset': 0
},
# bank 1
{
'ram': {
'start': 0xB8CC,
'end': 0xB... |
majors = {
"UND": "Undeclared",
"UNON": "Non Degree",
"ANTH": "Anthropology",
"APPH": "Applied Physics",
"ART": "Art",
"ARTG": "Art And Design: Games And Playable Media",
"ARTH": "See History Of Art And Visual Culture",
"BENG": "Bioengineering",
"BIOC": "Biochemistry And Molecular Biology",
"BINF": "Bioinformatics",
"B... |
class Solution:
def getWinner(self, arr: List[int], k: int) -> int:
"""
ints are unique
is it guaranteed there will be a winner? - YES
- YES: if the array is already sorted in reverse order
- YES: if array is in sorted order, and
arr = [1,11,22,33,44,55,66,77,88,99]... |
'''
from ..utils import gislib, utils, constants
from ..core.trajectorydataframe import *
import numpy as np
import pandas as pd
def stops(tdf, stop_radius_meters=20, minutes_for_a_stop=10):
""" Stops detection
Detect the stops for each individual in a TrajDataFrame. A stop is
detected when th... |
todo = []
todo_backup = []
def add_todo(task):
todo.append(task)
def list_todo():
return todo
def undo():
last_task = todo[-1]
todo_backup.append(last_task)
todo.pop()
def redo():
todo.append(todo_backup.pop())
add_todo("Aprender programação")
add_todo("Limpar a casa")
add_todo("Organi... |
unknown_error = (1000, 'unknown_error', 400)
access_forbidden = (1001, 'access_forbidden', 403)
unimplemented_error = (1002, 'unimplemented_error', 400)
not_found = (1003, 'not_found', 404)
illegal_state = (1004, 'illegal_state', 400)
|
_base_ = [
'../_base_/models/retinanet_r50_fpn.py',
'../_base_/datasets/waymo_open_2d_detection_f0.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(bbox_head=dict(num_classes=3))
data = dict(samples_per_gpu=4)
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, wei... |
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
class DataGridViewColumnStateChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.ColumnStateChanged event.
DataGridViewColumnStateChangedEventArgs(dataGridViewColumn: DataGridViewColumn,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __ne... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: identity_group_info
short_description: Information module for Identity Group
description:
- Get all Identity Group... |
# -*- coding: UTF-8 -*-
light = input('please input a light')
'''
if light =='red':
print('stop')
else:
if light =='green':
print('GoGoGO')
else:
if light=='yellow':
print('stop or Go fast')
else:
print('Light is bad!!!')
'''
if light == 'red':
print('Stop... |
class PluginInterface:
hooks = {}
load = False
defaultState = False
def getAuthor(self) -> str:
return ""
def getCommands(self) -> list:
return [] |
# Создайте словарь с количеством элементов не менее 5-ти.
person = {'first_name': 'Andrey',
'second_name': 'Trofimov',
'age': 25,
'city': 'Moscow',
'language': 'python'
}
print(person)
# Поменяйте местами первый и последний элемент объекта.
i_first = list(person.items())[0]... |
def enum(name, *sequential, **named):
values = dict(zip(sequential, range(len(sequential))), **named)
# NOTE: Yes, we *really* want to cast using str() here.
# On Python 2 type() requires a byte string (which is str() on Python 2).
# On Python 3 it does not matter, so we'll use str(), which acts as
... |
class Configuration(object):
"""Model hyper parameters and data information"""
""" Path to different files """
source_alphabet = './data/EnPe/source.txt'
target_alphabet = './data/EnPe/target.txt'
train_set = './data/EnPe/mytrain.txt'
dev_set = './data/EnPe/mydev.txt'
test_set = './data/EnP... |
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Webcam',
# list of one or more authors for the module
... |
# Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços,
# na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.
tupla = ('Lapis', 1.15,
'Borracha', 0.60,
'Caneta', 1.75,
'Lapiseira', 7.35,
'Caderno', 25,
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/BoundingBox.msg;/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/BoundingBoxes.msg;/home/pnu/catkin_ws/src/darknet_ros/darknet_ros_msgs/msg/ObjectCount.msg;/home/pnu/catkin_ws/devel/shar... |
""".. Ignore pydocstyle D400.
=========
Shortcuts
=========
Shortcut mixin classes
======================
.. autoclass:: resdk.shortcuts.collection.CollectionRelationsMixin
:members:
"""
|
class ExceptionMissingFile:
"""
An exception class for errors detected at runtime, thrown when OCIO cannot
find a file that is expected to exist. This is provided as a custom type to
distinguish cases where one wants to continue looking for missing files,
but wants to properly fail for other error ... |
"""Algorithm to select influential nodes in a graph using VoteRank."""
__all__ = ["voterank"]
def voterank(G, number_of_nodes=None):
"""Select a list of influential nodes in a graph using VoteRank algorithm
VoteRank [1]_ computes a ranking of the nodes in a graph G based on a
voting scheme. With VoteRan... |
"""
CPF = 168.995.350-09
------------------------------------------------
1 * 10 = 10 # 1 * 11 = 11 <-
6 * 9 = 54 # 6 * 10 = 60
8 * 8 = 64 # 8 * 9 = 72
9 * 7 = 63 # 9 * 8 = 72
9 * 6 = 54 # 9 * 7 = 63
5 * 5 = 25 # 5 * 6 = 30
3 * 4 = ... |
def arrayMaxConsecutiveSum(inputArray, k):
arr = [sum(inputArray[:k])]
for i in range(1, len(inputArray) - (k - 1)):
arr.append(arr[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
sort_arr = sorted(arr)
return sort_arr[-1]
|
# O(n) time | O(1) space
def find_loop(head):
"""
Returns the node that originates a loop if a loop exists
"""
if not head:
return None
slow, fast = head, head
while fast and fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if slow is fast:
... |
"""
问题描述: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,
返回它将会被按顺序插入的位置。
例子: [1,3,5,6], 5 => 2 [1,3,5,6], 2 => 1 [1,3,5,6], 7 => 4
"""
class Solution:
def searchInsert(self, nums, target):
if not nums:
return 0
start = 0
end = len(nums) - 1
while start <= end:
... |
# output: ok
input = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
expected = [11, 8, 30, 2.5, 2, 4, 10000000, 20, 2, 2, 14, 15]
def test(v):
v[0] += 1
v[1] -= 2
v[2] *= 3
v[3] /= 4
v[4] //= 5
v[5] %= 6
v[6] **= 7
v[7] <<= 1
v[8] >>= 2
v[9] &= 3
v[10] ^= 4
v[11] |= 5... |
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
#s = "ab"
#wordDict = ["a","b"]
#s="aaaaaaa"
#wordDict=["aaaa","aa","a"]
#wordDict=["a","aa","aaaa"]
s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Hans-Joachim Kliemeck <git@kliemeck.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported... |
# Program verificare nr prim/compus
num = int(input("Enter number: "))
# nr prime sunt mai mari decat 1
if num > 1:
# verificare
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"... |
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"routes": {
"10.121.65.0/24": {
"active": True,
"candidate_default": False,
"dat... |
#n=int(input('Diga o valor'))
#print('O quadrado {}'.format(n**2))
#print('O Antecessor {} Sucessor {}'.format(n+1,n-1))
dist=int(input('Diga o valor Distancia'))
comb=int(input('Diga o valor Combustivel'))
print('O consumo Medio {}'.format(dist/comb))
|
def ali_sta_seznama_enaka(sez1, sez2):
slo1 = {}
slo2 = {}
for i in sez1:
slo1[i] = slo1.get(i, 0) + 1
for i in sez2:
slo2[i] = slo2.get(i, 0) + 1
if slo1 == slo2:
return True
else:
return False
def permutacijsko_stevilo():
x = 1
while True:
sez1 ... |
# Tuples of RA,dec in degrees
ELAISS1 = (9.45, -44.)
XMM_LSS = (35.708333, -4-45/60.)
ECDFS = (53.125, -28.-6/60.)
COSMOS = (150.1, 2.+10./60.+55/3600.)
EDFS_a = (58.90, -49.315)
EDFS_b = (63.6, -47.60)
def ddf_locations():
"""Return the DDF locations as as dict. RA and dec in degrees.
"""
result = {}
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Default configurations.
默认的配置文件应该完全符合本地开发环境,这样,无需任何设置,就可以立刻启动服务器
'''
__author__ = 'Kubert'
configs = {
'debug': True,
'db': {
'host': '127.0.0.1',
'port': 3306,
'user': 'www-data',
'password': 'www-data',
'db': 'awesome... |
def solution(s: str) -> bool:
stack = []
left = 0
right = 0
for c in s:
if not stack:
if c == ")":
return False
stack.append(c)
left += 1
continue
if c == ")":
if stack[-1] == "(":
stack.pop()
... |
self.description = "Quick check for using XferCommand"
# this setting forces us to download packages
self.cachepkgs = False
#wget doesn't support file:// urls. curl does
self.option['XferCommand'] = ['/usr/bin/curl %u -o %o']
numpkgs = 10
pkgnames = []
for i in range(numpkgs):
name = "pkg_%s" % i
pkgnames.ap... |
class Solution:
def search(self, nums: List[int], target: int) -> bool:
start_idx = 0
for i in range(len(nums)-1):
if nums[i] > nums[i + 1]:
start_idx = i + 1
break
originList = nums[start_idx:] + nums[:start_idx]
... |
VERSION = (0, 6)
__version__ = '.'.join(map(str, VERSION))
__author__ = 'Ministry of Justice'
__email__ = 'dev@digital.justice.gov.uk'
default_app_config = 'govuk_forms.apps.FormsAppConfig'
|
# -*- coding: utf-8 -*-
VERSION = (1, 0, 0, 'beta')
__version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
__author__ = 'Kuba Janoszek'
|
"""Show how to use list comprehensions and zip"""
sunday_temps = [76, 78, 86, 54, 88, 77, 66, 55, 44, 57, 58, 58, 78, 79, 69, 65]
monday_temps = [68, 67, 68, 76, 77, 66, 61, 81, 73, 61, 83, 67, 89, 78, 67, 85]
tuesday_temps = [78, 79, 70, 76, 75, 74, 73, 72, 63, 64, 65, 58, 59, 85, 59, 85]
def show_temp_tuples():
... |
# Make an algorithm that reads an employee's salary and shows his new salary, with a 15% increase
n1 = float(input('Enter the employee`s salary: US$ '))
n2 = n1 * 1.15
print('The new salary, with 15% increase, is US${:.2f}'.format(n2))
|
def test():
test_instructions = """0
3
0
1
-3"""
assert run(test_instructions) == 5
def run(in_val):
instructions = [int(instruction) for instruction in in_val.split()]
rel_offsets = {}
register = 0
steps = 0
while True:
try:
instruction = instructions[register]
... |
def get_string_count_to_by(to, by):
if by < 1:
raise ValueError("'by' must be > 0")
if to < 1:
raise ValueError("'to' must be > 0")
if to <= by:
return str(to)
return get_string_count_to_by(to - by, by) + ", " + str(to)
def count_to_by(to, by):
print(get_string_count_to_by(t... |
def sol():
N, M = map(int, input().split(" "))
data = sorted(list(map(int, input().split(" "))))
visited = [False] * (N + 1)
save = set()
dfs(N, M, data, visited, save, 0, "")
def dfs(N, M, data, visited, save, cnt, line):
if cnt == M:
if line not in save:
save.add(line)
... |
#orderList=input("一组规律数字的序列")
#函数 ‘equalInList()’判断 参数:序列 内元素是否全部相同
'''def equalInList(numList):
No1=numList[0]
for i in numList:
if No1!=i:
No1=i
break
if No1==numList[0]:
return True
else:
return False'''
#函数 ‘orderNext_getTile()’ 判断 参数:序列 内元素是否重复排列,重复... |
def generate_instance_name(name):
out = name[0].lower()
for char in name[1:]:
if char.isupper():
out += "_%s" % char.lower()
else:
out += char
return out
def generate_human_name(name):
out = name[0]
for char in name[1:]:
if char.isupper():
... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
_base_ = [
'../_base_/models/upernet_convnext.py', '../_base_/datasets/ade20k.py',
'../_base_/default_runtime.py... |
#Programa que lê a velocidade de um carro .Se ultrapassar 80KM, ele foi multado. A multa vai ser de 7 reais por cada KM ultrapassado
print('{:=^20}'.format('Desafio 29'))
vel=float(input('Qual a velocidade atual do carro? '))
penalidade=7
permitido=80
if vel>80:
excesso=vel-permitido
multa=excesso*penalidade... |
"""Utils module."""
__all__ = ['convert_choice', 'convert_loglevel', 'convert_predicate',
'convert_string', 'create_getter', 'create_setter', 'create_deleter']
def convert_choice(choices, *, converter=None, default=None):
"""Return a function that can be used as a converter.
For an example see th... |
'''
Kompresi Benny
Menyederhanakan sebuah kata dengan membuat beberapa
karakter yang sama dan berurutan hanya akan menjadi
satu karakter saja.
'''
def kompresi(a_str):
'''
Mengompres a_str sehingga tidak ada
karakter yang sama yang bersebelahan.
Contoh: kompresi('aabbbbaaacddeae')
... |
__all__ = ['CommandError', 'CommandLineError']
class CommandError(Exception):
pass
class CommandLineError(Exception):
pass
class SubcommandError(Exception):
pass
class MaincommandError(Exception):
pass
class CommandCollectionError(Exception):
pass
|
#----
# Подавление вывода данных:
metadict_detail['-Рыночная цена (фоллисов)'] = {
}
metadict_detail['-Мёд (требуется/килограмм)'] = {
}
metadict_detail['-Сыворотка творожная коровья (требуется/килограмм)'] = {
}
metadict_detail['-Молоко коровье (требуется/килограмм)'] = {
}
metadic... |
# Copyright (c) 2021, Carlos Millett
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the Simplified BSD License. See the LICENSE file for details.
'''
Renamer renames your TV files into a nice new format.
The new filename includes the TV show name, season and episode num... |
s = open('input.txt','r').read()
s = [k for k in s.split("\n")]
ans = 0
p = ""
q = 0
for line in s:
if line == "":
x = [0]*26
for i in p:
j = ord(i) - 97
if 0 <= j < 26:
x[j] += 1
ans += len([k for k in x if k == q])
p = ""
q = 0
... |
# Python - 3.6.0
def presses(phrase):
keypads = ['1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9', '*', ' 0', '#']
times, i = 0, 0
for p in phrase.upper():
for keypad in keypads:
i = keypad.find(p)
if i >= 0:
break
times += i + 1
... |
#coding:utf-8
# 题目:利用递归方法求5!。
def factorial(num):
if num in (0,1):
return 1
return factorial(num-1) * num
print(factorial(5)) |
# Copyright 2017 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.
DEPS = [
'flavor',
'recipe_engine/properties',
'recipe_engine/raw_io',
'run',
'vars',
]
def test_exceptions(api):
try:
api.flavor.copy_dir... |
pass_marks = 70
if pass_marks == 70:
print('pass')
its_raining = True # you can change this to False
if its_raining:
print("It's raining!")
its_raining = True # you can change this to False
its_not_raining = not its_raining # False if its_raining, True otherwise
if its... |
a = 28
b = 1.5
c = "Hello!"
d = True
e = None
|
#1) Indexing lists and tuples
list_values = [1, 2, 3]
set_values = (10, 20, 30)
print(list_values[0])
print(set_values[0])
#2) Changing values: lists vs tuples
list_values = [1, 2, 3]
set_values = (10, 20, 30)
list_values[0] = 100
print(list_values)
set_values[0] = 100
#3) Tuple vs List Expanding
list_values = ... |
#!/usr/bin/env python3
"""
This reads a log file and verifies that all the 'action' entries are
corrent. And action entry looks like:
act: key value up-card action
"""
act_line = ''
def main():
global act_line
with open('trace.txt', 'rt') as fd:
for line in fd:
line = line.rstrip()
... |
dic_cal = {}
def cal(a, b):
if (a, b) in dic_cal:
return dic_cal[(a, b)]
return cal(a - 1, b) + cal(a, b - 1)
if __name__ == '__main__':
for j in range(0, 1):
for k in range(0, 21):
dic_cal[(j, k)] = 1
for j in range(0, 21):
for k in range(0, 1):
dic_c... |
# shorthand for tabulation
def get_tabs(num):
ret = ""
for _ in range(num):
ret += "\t"
return ret
|
n = int(input())
chars_of_each_string = [[char for char in input()] for _ in range(n)]
chars = []
for characters in chars_of_each_string:
chars += list(set(characters))
chars_used_in_all = []
for char in set(chars):
if chars.count(char) == n:
chars_used_in_all.append(char)
if not chars_us... |
'''
Description: exercise: finding the area
Version: 1.0.0.20210113
Author: Arvin Zhao
Date: 2021-01-13 12:20:06
Last Editors: Arvin Zhao
LastEditTime: 2021-01-13 12:48:56
'''
def display_square_area() -> None:
'''
Calculate and display the area of a square.
'''
while True:
try:
si... |
class MultiheadAttention(Module):
__parameters__ = ["in_proj_weight", "in_proj_bias", ]
__buffers__ = []
in_proj_weight : Tensor
in_proj_bias : Tensor
training : bool
out_proj : __torch__.torch.nn.modules.linear.___torch_mangle_9395._LinearWithBias
def forward(self: __torch__.torch.nn.modules.activation._... |
#
# PySNMP MIB module Nortel-MsCarrier-MscPassport-DataCollectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-DataCollectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:29:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ... |
# Algocia is placed on a great dessert and consists of cities and oases connected by roads. There is
# exactly one road leading from each gate to one oasis (but any given oasis can have any number of roads
# leading to them, oases can also be interconnected by roads). Algocian law requires that if someone
# enters a ci... |
'''
You are given a circular array nums of positive and negative integers.
If a number k at an index is positive, then move forward k steps.
Conversely, if it's negative (-k), move backward k steps.
Since the array is circular, you may assume that the last element's next element is the first element, and the first elem... |
revision = "a6d2d466e5"
revision_down = None
message = "create company model"
async def upgrade(connection):
sql = """
CREATE TABLE companies (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(200) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARACTER SET=... |
class PartyAnimal:
x = 0
name = ""
def __init__(self, nameCons):
self.name = nameCons
print("name: ", self.name)
def party(self):
self.x = self.x + 1
print(self.name," - party count: ", self.x)
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):... |
__author__ = 'Nathen'
input_str = input('Paste input nums: ')
k, m, n = map(lambda num: float(num), input_str.split(' '))
population = k + m + n
# odds when dominant first
pK = k / population
# odds when heterozygous first
pMK = (m / population) * (k / (population - 1.0))
pMM = (m / population) * ((m - 1.0) / (pop... |
with open("tinder_api/utils/token.txt", "r") as f:
tinder_token = f.read()
# it is best for you to write in the token to save yourself the file I/O
# especially if you have python byte code off
#tinder_token = ""
headers = {
'app_version': '6.9.4',
'platform': 'ios',
'content-type': 'application/json'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.