content stringlengths 7 1.05M |
|---|
sec = { # Security
1102: {"Descr": "The audit log was cleared",
"Provider": "Microsoft-Windows-Eventlog",
"SubjectUserSid": "SID",
"SubjectUserName": "Username",
"SubjectDomainName": "Domain",
"SubjectLogonId": "LogonId"},
4616: {"Descr": "The system time... |
"""Exceptions.py
Define exceptions used by the library."""
class ResponseError(Exception):
"""Own class for exceptions related
to response errors. Currently only present in two places."""
pass #Don't do anything else than just define the function
|
def get_friendly_dict(friend_list):
""" Accept a list of reciprocal friendship links between individuals and
return a dictionary of degree-one friends of each individual in a social
network. """
# first, we'll get all the individuals name using union set and put it into
# unique_name list
... |
class Solution:
def arrayRankTransform(self, arr2: List[int]) -> List[int]:
d = {}
if len(arr2)==0: return []
ct = 1
arr = sorted(arr2)
d[arr[0]] = 1
for i in range(1,len(arr)):
if arr[i]>arr[i-1]:
ct+=1
d[arr[i]] = ct
r... |
# Our server roles:
config.rdbms = ['127.0.0.1']
config.httpd = ['localhost']
def production():
# this would set `rdbms` and `httpd` to prod. values.
# for now we just switch them around in order to observe the effect
config.rdbms, config.httpd = config.httpd, config.rdbms
def build():
local('echo Bu... |
'''
- DESAFIO 03
- Crie um script Python que leia dois números e tente mostrar a soma entre eles
'''
n1 = int(input('\033[33mPrimeiro número:\033[m '))
n2 = int(input('\033[34mSegundo número:\033[m '))
print('\033[35mA soma entre\033[m \033[31m{}\033[m \033[35me\033[m \033[31m{}\033[m \033[35mé igual a\033[m'
... |
class Conto:
def __init__(self, numero_conto, cliente, saldo=0.00):
self.__numero_conto = numero_conto
self.__cliente = cliente
self.__saldo = saldo
# Definizione di getter e setter #
@property
def numero_conto(self):
return self.__numero_conto
@numero_conto.s... |
# --------------
##File path for the file
file_path
#Code starts here
#Function to read file
def read_file(path):
#Opening of the file located in the path in 'read' mode
file = open(path, 'r')
#Reading of the first line of the file and storing it in a variable
sentence=file.rea... |
def decompose(n):
return helper(n, n**2)
def helper(n, sum, arr=[]):
if sum==0:
return arr[::-1]
for i in range(n-1, -1, -1):
if i**2<=sum:
return helper(i, sum-i**2, arr+[i]) or helper(i, sum, arr) |
"""
Given three sorted arrays A, B and C of not necessarily same sizes.
Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that
a, b, c belongs arrays A, B, C respectively.
i.e. minimize | max(a,b,c) - min(a,b,c) |.
Example :
Input:
A : [ 1, 4, 5, 8, 10 ]
... |
"""
Check BinaryTree section
This question is also in the SDE Sheet
Learn : The Height can be defined over a binary tree,
but depth is defined over a node, ie there is a dept of each node
"""
|
def filterTags(attrs):
""" Convert some ShapeVIS attributes to OSM. """
result = {}
if 'HAALPLTSMN' in attrs:
result['name'] = attrs['HAALPLTSMN']
result['bus'] = 'yes'
# Default
result['public_transport'] = 'stop_position'
if 'station' in result['name'].lower() an... |
# Exercício Python 62: Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos.
# O programa encerrará quando ele disser que quer mostrar 0 termos.
print('GERADOR DE PA')
print('-=' * 10)
num = int(input('Primeiro termo: '))
razao = int(input('Razão da PA: '))
print('-=' * 10)
cont =... |
class person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def fullname(self):
return f"{self.first_name} {self.last_name}"
def email(self):
return f"{self.first_name}{self.last_name}@gmail.com"
|
class Blood(object):
"""
Most characters will have ordinary blood but some could have acidic blood or with other properties.
"""
def __init__(self, uid, name):
self.uid = uid
self.name = name |
class WorksharingUtils(object,IDisposable):
""" A static class that contains utility functions related to worksharing. """
@staticmethod
def CheckoutElements(document,elementsToCheckout,options=None):
"""
CheckoutElements(document: Document,elementsToCheckout: ICollection[ElementId]) -> ICollection[ElementI... |
'''
Set Matrix Zeros
Asked in: Oracle, Amazon
https://www.interviewbit.com/problems/set-matrix-zeros/
Given a matrix, A of size M x N of 0s and 1s. If an element is 0, set its entire row and column to 0.
Note: This will be evaluated on the extra memory used. Try to minimize the space and time complexity.
Input Fo... |
# -*- coding: utf-8 -*-
"""
Crie um programa que leia o nome e o preço de vários produtos. O programa deverá
perguntar se o usuário vai continuar. No final, mostre.
A) Qual é o total gasto na compra
B) Quantos produtos custam mais de R$1000.
C) Qual é o nome do produto mais barato
"""
barato = total = q... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
class MoviePipeline(object):
def process_item(self, item, spider):
with open('out/my_meiju.txt', 'a', encoding='U... |
"""
Covid-19 is spreading fast! There are N cities, numbered from 0 to (N−1), arranged in a circular manner. City 0 is connected to city 1, 1 to 2, …, city (N−2) to city (N−1), and city (N−1) to city 0.
The virus is currently at city X. Each day, it jumps from its current city, to the city K to its right, i.e., from c... |
number = int(input())
synonyms_dict = dict()
for num in range (number):
word = input()
synonym = input()
if word not in synonyms_dict.keys():
synonyms_dict[word] = list()
synonyms_dict[word].append(synonym)
for word in synonyms_dict:
synonyms = ", ".join(synonyms_dict[word])
print(f"{... |
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
#
# 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... |
"""
django_ocr_server/tests/__init__.py
+++++++++++++++++++++++++++++++++++
| Author: shmakovpn <shmakovpn@yandex.ru>
| Date: 2021-01-07
""" |
class Person:
# allocate space for only these attributes so we don't need to create a __dict__ property in the class and we save space when parsing large files
__slots__ = ["lastName", "firstName", "middleInitial",
"gender", "favoriteColor", "dateOfBirth"]
def __init__(self, lastName, fir... |
expected_output = {
'10.1.1.2': {
'conn_capability': 'IPv4-IPv6-Subnet',
'conn_inst': 1,
'conn_status': 'On (Speaker) :: On (Listener)',
'conn_version': 5,
'duration': '0:00:00:57 (dd:hr:mm:sec) :: 0:00:00:55 (dd:hr:mm:sec)',
'local_mode': 'Both',
'peer_ip': '... |
class Stack:
def __init__(self):
self.list = []
def push(self, element):
self.list.append(element)
def pop(self):
assert len(self.list) > 0, "Stack is empty"
return self.list.pop()
def isEmpty(self):
return len(self.list) == 0
|
""" Class that implements K stacks in an array """
class KStacks:
def __init__(self, cap, k):
self.tops = [-1] * k
self.arr = [0] * cap
self.next = [-1] * cap
self.free_top = 0
for i in range(cap-1):
self.next[i] = i+1
self.capacity = cap
def push(... |
#!/usr/bin/python
# Calculer la somme des valeurs du tableau
def somme_tab(tab):
somme = 0
for i in range(len(tab)):
somme += tab[i]
return somme
tab = [5, 18.5, 13.2, 8.75, 2, 15, 13.5, 6, 17]
print(somme_tab(tab))
|
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating an empty ... |
class Solution(object):
def twoSumLessThanK(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
# Guard
if not A or not K or len(A) <= 1:
return -1
# Sort inputs
inputs_sorted = sorted(A)
# Two pointers thro... |
def threeSum(nums):
s = set()
nums.sort()
for i in range(len(nums)):
m = {}
for j in range(i+1, len(nums)):
x = -nums[i] - nums[j]
if x not in m:
m[nums[j]] = j
else:
s.add((x,nums[i],nums[j]))
return list(s) |
array = [54, 26, 93, 17, 77, 31, 44, 55, 20]
def bubble_sort(nums: list):
for i in range(len(nums)):
for j in range(len(nums) - 1, i, -1):
if nums[j - 1] > nums[j]:
nums[j - 1], nums[j] = nums[j], nums[j - 1]
print(array)
bubble_sort(array)
print(array)
|
# 题意:判断树的子结构:输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)。B是A的子结构, 即 A中有出现和B相同的结构和节点值。
# 题解:递归。
# 本题属于匹配类二叉树题目,一般做法就是递归。可以分为两个步骤,首先是找到匹配的跟节点,其次是对于根节点接着匹配下去看是否能匹配成功
# 在本题,找到根节点需要递归调用自身,找到根节点后用自定义的递归函数递归地匹配。整个过程用or and 等bool算子来拼凑成最后结果。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# ... |
"""
This package contains the following entities:
1) Protocol
2) Attack Suite
3) Attack
4) Input Format
In this module, we have the backend entities to represent and structure our code
And these entities have the following relations in between: (Connection endpoints represent cardinality o... |
BLKNUM_OFFSET = 1000000000
TXINDEX_OFFSET = 10000
def decode_utxo_id(utxo_id):
blknum = utxo_id // BLKNUM_OFFSET
txindex = (utxo_id % BLKNUM_OFFSET) // TXINDEX_OFFSET
oindex = utxo_id % TXINDEX_OFFSET
return blknum, txindex, oindex
def encode_utxo_id(blknum, txindex, oindex):
return (blknum * BL... |
#!/usr/bin/python
isValueAccepted = True
largeur = int(input("Largeur >> "))
longueur = int(input("Longueur >> "))
while isValueAccepted:
unite = str(input("En quelle unité souhaitez vous obtenir le périmètre(m ou cm) >> "))
if unite == "m" or unite == "cm":
isValueAccepted = False
print("Nous calculons le p... |
#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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)... |
"""
Note: Moved to umpyre (pip install umpyre)
Get stats about packages. Your own, or other's.
Things like...
# >>> import collections
# >>> modules_info_df(collections)
# lines empty_lines ... num_of_functions num_of_classes
# collections.__init__ 1273 189 ... 1 ... |
# OAuth app keys
DROPBOX_KEY = None
DROPBOX_SECRET = None
DROPBOX_AUTH_CSRF_TOKEN = 'dropbox-auth-csrf-token'
# Max file size permitted by frontend in megabytes
MAX_UPLOAD_SIZE = 150
|
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', 'jobs.harenconstruction.com', 'www.harenconstruction.com', 'harenconstruction.com' '104.236.59.248']
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = '/home/applicant/' #os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#... |
#
# PySNMP MIB module ZhoneDsl-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZhoneDsl-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:52:33 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,... |
def is_on(S, j):
return (S & (1 << j)) >> j
def set_all(n):
return (1 << n) - 1
def low_bit(S):
return (S & (-S)).bit_length() - 1
def clear_bit(S, j):
return S & ~(1 << j)
|
"""
practice test cases for testing plugin
"""
def test_iequals1():
"""
practice test case 1 for testing plugin
"""
i = 1
assert i == 1
def test_iequals2():
"""
practice test case 2 for testing plugin
"""
i = 2
assert i == 2
|
def histogram(s):
"""Use get to write histogram more concisely"""
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
print(histogram('brontosaurus'))
|
class core50():
def __init__(self, paradigm, run):
self.batch_num = 5
self.rootdir = '/home/rushikesh/code/core50_dataloaders/dataloaders/task_filelists/'
self.train_data = []
self.train_labels = []
self.train_groups = [[],[],[],[],[]]
for b in range(self.batch_num):
with open( self.rootdir + paradig... |
def romanToInt(s):
"""Calculates value of Roman numeral string
Args:
s (string): String of Roman numeral characters being analyzed
Returns:
int: integer value of Roman numeral string
"""
sum = 0
i = 0
while i < len(s):
if s[i] == 'M':
sum += 1000
elif s[i] == 'D':
sum +=... |
User_name = input("What is your name? ")
User_age = input("How old are you? ")
User_liveplace = input("Where are you live? ")
print ( "This is", User_name)
print ( "It is" , User_age)
print ( "(S)he live in", User_liveplace) |
def includes(doc, path, title=3, **args):
j = doc.docsite._j
spath = j.sal.fs.processPathForDoubleDots(j.sal.fs.joinPaths(j.sal.fs.getDirName(doc.path), path))
if not j.sal.fs.exists(spath, followlinks=True):
doc.raiseError("Cannot find path for macro includes:%s" % spath)
docNames = [j.sal.fs... |
#!/usr/bin/env python
lista=[2,3,4,1]
lista2=lista[:] #Copia
lista.sort()
if lista == lista2:
print("Lista ordenada")
else:
print("Lista no ordenada") |
__author__ = "Andre Merzky"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
# ------------------------------------------------------------------------------
# FIXME: OS enums, ARCH enums
# resource type enum
COMPUTE = 1 # resource accepting jobs
STORAGE = 2 ... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
"""
lab 8
"""
#3.1
#def calcwords(input_str):
# return len(input_str.split())
#3.2
#demo_str = 'hello world!'
#print(calcwords(demo_str))
#3.3
def calnum(input_list):
min_item = input_list[0]
for eachnum in input_list:
if type(eachnum) is not str:
if min_item >= eachnum:
... |
def is_zigzag(numbers: list):
if len(numbers) != 3:
raise ValueError('must be 3 elements {}'.format(numbers))
return 1 if (numbers[0] < numbers[1] > numbers[2]) or (numbers[0] > numbers[1] < numbers[2]) else 0
if __name__ == "__main__":
#numbers = [1, 2, 1]
numbers = [1, 2, 1, 3, 4]
numb... |
def ext_here(props):
props['ext_ui']['filedir2']=props['ext_ui']['filedir']
props['music'].clickSon()
#print(filedir2)
decomp(props)
def ext_to(props):
filedir=props['ext_ui']['filedir']
root=props['root']
filedialog=props['filedialog']
props['music'].clickSon()
root.filename... |
def funcaoDocumentada(a,b):
"""
Dá a soma de dois números.
:param int a: Um valor numérico
:param int b: Um valor numérico
:return: A soma de a e b
"""
return a+b
def paramOpcional(a=0,b=0,c=0):
return a+b+c
def paramSilencioso():
# valorNoEscopo é global.
print(f'Fora do escopo, {valorNoEscopo}')
# Mas... |
class CartItem(object):
def __init__(self, url, title=None, abstract=None, mime_type=None, dataset=None):
self.url = url
self._title = title
self._abstract = abstract
self.mime_type = mime_type or 'application/x-netcdf'
self.dataset = dataset
@property
def title(self... |
class Node:
""" A Circular linked node. """
def __init__(self, data=None):
self.data = data
self.next = None
class CircularList:
def __init__ (self):
self.tail = None
self.head = None
self.size = 0
def append(self, data):
node... |
"""
Session: 10
Topic: A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.
"""
num = int(input("How many terms? "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
... |
class UserDoesNotExist(Exception):
pass
class PasswordDoesNotMatch(Exception):
pass
class EmailAlreadyRegistered(Exception):
pass
|
try:
basestring
except NameError:
basestring = str # Python 2 -> 3 alias
""" Exposes decorator class."""
__all__ = ["DocInheritDecorator"]
class DocInheritDecorator(object):
""" A decorator that merges provided parent docstring with the docstring of the decorated
function/method/property.
Meth... |
"""
Albert is playing with text. Instead of writing sentences as they should be, he decided to randomly swap pairs of letters in them. But not even in the whole text, only from some place in the middle of the text onward. At least he marked the places in the text, where each substitution starts, and what two letters ar... |
"""
NAME: DIBANSA, RAHMANI P.
COURSE-YEAR LEVEL-SECTION: BSCPE 2-2
SUBJECT: SOFTWARE DEVELOPMENT
PROGRAM DESCRIPTION: A PYTHON PROGRAM THAT SORTS A LIST THROUGH
MERGE SORT FUNCTION
"""
# THIS FUNCTION TAKES A THE USER'S INPUTTED LIST, A START VARIABLE THAT
# MARKS WHERE THE FUNCTION WO... |
class TestData():
BROWSER_PATH="C:/Python/Python37-32/chromedriver.exe"
BASE_URL = "https://www.amazon.com"
SEARCH_TERM = "adidas backpack men"
HOME_PAGE_TITLE = "Amazon.com"
NO_RESULTS_TEXT = "No results found." |
class Vec3():
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def length(self):
return (self.x * self.x + self.y * self.y + self.z * self.z)**0.5
def __add__(self, other):
return Vec3(self.x + other.x, self.y + other.y, self.z + other.z)
def... |
def dp(height, max_steps, memo):
if height == 0:
return 1
if memo[height] > 0:
return memo[height]
ways = 0
for i in range(max(height - max_steps, 0), height):
ways += dp(i, max_steps, memo)
memo[height] = ways
return ways
def staircaseTraversal(height, maxSteps):
... |
#Question 1342:
#Given a non-negative integer num, return the number of steps to reduce it to zero.
# If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.
#Example:
#Input: num = 14
#Output: 6
#Explanation:
#Step 1) 14 is even; divide by 2 and obtain 7.
#Step 2)... |
# Escreva um programa que converta uma temperatura digitada em °C e converta para °F.#
c = float(input('Informe a temperatura em °C: '))
f = ((9 * c) / 5) + 32
print(f'A temperatura de {c}°C corresponde a {f}°F')
|
class Variable(object):
BOOLEAN = 1
def __init__(self, name, type, value):
self.name = name
self.type = type
self.value = value
def __repr__(self):
return "Variable(%s, %s, %s)" % (self.name, self.type, self.value)
|
# Copyright 2016 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... |
print("CONVERSOR DE DECIMALES A OTRA BASE")
number = input("Ingresa un numero de base decimal: ")
base = input("Ingresa la base: ")
numbers = []
def residuo(number, base, iteration = 0):
cociente = number // base
res = number % base
print(" " * iteration, res, cociente)
numbers.append(res)
if (c... |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for _ in '0'*int(input()):
a,b,k=map(int,input().split())
print(k//2*(a-b)+k%2*a)
|
def draw(n):
for i in range(1, n+1):
for k in range(0,n-i):
print(" ", end=" ")
for j in range(0,i):
print("*", end=" ")
print("\n")
draw(4) |
i = 0
while i < 10:
print(i)
i = i + 1
i = 1
while i <= 2 ** 32:
print(i)
i *= 2
done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
attack = input("Does your elf attack the dragon? ")
if attack == "y":
print("Bad choice,... |
class Solution:
def reformatDate(self, date: str) -> str:
clean = date.split()
month = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
... |
# Crie um programa que converta graus Celsius em Fahrenheit
# C/5=F-32/9
# F = C * 1.8 + 32
print('Conversor de Temperatura\n C em F')
c = int(input('Digite a temperatura em Graus Celcios: '))
f = c * 1.8 + 32
print('{}ºC = {:.1f}ºF'.format(c, f,)) |
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
result = []
flag = 0
temp = digits[-1]
if temp < 9:
result = digits
result[-1] = result[-1] + 1
else:
... |
class Solution:
def XXX(self, height: List[int]) -> int:
area=0
i=0
j=len(height)-1
while i!=j:
# 双指针,最小高度的指针移动
max_height=min(height[i],height[j])
area=max(max_height*(j-i),area)
if height[i]<height[j]:
i=i+1
... |
# -*- coding: utf-8 -*-
"""Top-level package for {{ cookiecutter.project }}."""
__author__ = """{{ cookiecutter.author }}"""
__version__ = '{{ cookiecutter.version }}'
|
#Page 202, Figure 13.2
class Field(object):
def __init__(self):
self.drunks = {}
def addDrunk(self, drunk, loc):
if drunk in self.drunks:
raise ValueError('Duplicate drunk')
else:
self.drunks[drunk] = loc
def moveDrunk(self, drunk):
... |
# Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# This is a mixture of the javadoc_library rule in
# https://github.com/google/bazel-common and the one in
# https://github.com/stackb/rules_proto.
# The main two factors for why we ... |
# Notation for direction will be as follows:
# 0
# 3 1
# 2
# Turning to the rights = (d+1)%4
# Turning to the left = (d-1)%4
def move(d, cX, cY):
if (d == 0):
cX = cX-1
if (d == 1):
cY = cY+1
if (d == 2):
cX = cX+1
if (d == 3):
cY = cY-1
return cX, cY
def ... |
class Constants:
# Common Constants
mail: str = "prodcube@prodcube.dev"
version: str = "1.0.0"
# Production Constants
productionDescription: str = "Handles the ProDCube Backend Server. Currently in Production. " \
"Please change to development mode while development... |
def mergeSort(arr:[int]):
mid:int = 0
L:[int] = None
R:[int] = None
i:int = 0
j:int = 0
k:int = 0
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L=[]
while (i<mid):
L = L + [arr[i]]
... |
#Desafio: Crie um programa quue vai ler vários números e colocar em uma lista. Depois disso mostre:
#A) Quantos números foram digitados.
#B) A lista de valores, ordenada de forma decrescente.
#C) Se o valor 5 foi digitado e está ou não na lista.
num = list()
while True:
num.append(int(input('Digite um número: ')))... |
"""
This class implements common methods for all solving methods
"""
class BaseMethod:
""" """
def __init__(self):
""" """
self.time = None
def get_time(self):
""" """
return self.time
def show(self):
""" """
pass
def get_best(self):
""" ... |
# -*- coding: UTF-8 -*-
RULES = {
u'muriend': u'muerte',
u'querid': u'querer',
u'mirando': u'mirar',
u'miradit': u'mirar',
u'pudier': u'poder',
u'horas': u'hora',
u'gasta': u'gasto',
u'gasta': u'gasto',
u'mostró': u'mostrar',
u'destine': u'destinar',
u'presentó': u'presentar',
u'dudo': u'dudar',... |
"""Constants for integration_blueprint."""
# Base component constants
NAME = "Duolinguist"
DOMAIN = "duolingo"
VERSION = "0.1.0"
ISSUE_URL = "https://github.com/sphanley/duolinguist/issues"
# Platforms
BINARY_SENSOR = "binary_sensor"
PLATFORMS = [BINARY_SENSOR]
# Configuration and options
CONF_USERNAME = "username"
... |
class Solution:
'''
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "acca... |
n=int(input())
arr=[]
c=0
for _ in range(n):
arr.append(list(map(int,input().split())))
for i in range(len(arr)):
co=0
for j in range(len(arr[i])):
if(arr[i][j]==1):
co+=1
if(co>=2):
c+=1
print(c) |
# 21302 - [Job Adv] (Lv.60) Aran
sm.setSpeakerID(1201002)
sm.sendNext("Oh, isn't that... Hey, did you remember how to make the Red Jade? You may be a dummy who has amnesia, but this is why I can't leave you. Now hurry, give me the gem!")
if sm.sendAskYesNo("Okay, now that I have the power of Red Jade, I'll restore mo... |
"""
Class for server to store client types and data etc.
"""
class Client:
"""
Client class
"""
def __init__(self, controlled, conn):
"""
Constructor
Args:
controlled (boolean): Whether or not this client is being controlled
conn (socket.socket): the co... |
test = {
'name': 'switch',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
scm> (switch 1 ((1 (print 'a))
.... (2 (print 'b))
.... (3 (print 'c))))
a
scm> (switch (+ 1 1) ((1 (print 'a))
.... ... |
class Prunner(object):
def __init__(self):
pass
def fit(self, ensemble, X, y):
return self
def get(self, p=0.1):
return self.ensemble[:int(p * len(self.ensemble))]
|
# -*- coding: utf-8 -*-
'''
Author: Hannibal
Data:
Desc: local data config
NOTE: Don't modify this file, it's build by xml-to-python!!!
'''
simpleskillpassive_map = {};
simpleskillpassive_map[2001] = {"id":2001,"skilldata":[{"lv":1,"effect":"actor['atk']*=1.2","group":1,},{"lv":2,"effect":"actor['atk']*=1.3","group... |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Mytree:
def maketree(self, arr: list):
root = TreeNode(arr[0])
mystack = []
mystack.append(root)
nl = []
i = 0
whil... |
"""
缺省函数,就是参数可以有默认值,跟kotlin一样
返回值也可以简写,省略 -> int:
"""
def print_info(name, age=20):
print("姓名:%s, 年龄:%s" % (name, age))
print_info("张三", 28)
print_info("李四")
"""
元组[]不定长参数,参数的数量不确定, 调用类似于位置参数
参数名之前加上*表示这个星号表明参数的类型为元祖,但是传入实参的时候不需要中括号[]
"""
def my_func01(*args):
print(type(args))
print(args... |
# MTK GPS Command Sentence Generator for Python
# Copyright (c) 2015 Calvin McCoy (calvin.mccoy@gmail.com)
# 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 witho... |
asdasdfgs = 1
def add(x, y):
return x + y
print(add(asdasdfgs, 2))
print(add(asdasdfgs, 3))
print(add(asdasdfgs, 5))
|
''' Desenvolva um programa que leia o primeiro termo e a razão de uma "PA". No final, mostre as 10 primeiros
termos dessa progressão. '''
termo = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
decimo = termo + (10 - 1) * razao
for c in range(termo, decimo + razao, razao):
print(f'{c... |
#!/usr/bin/python
#coding=utf-8
class List(list):
def __getattr__(self, attr):
tmp = List()
for l in self:
tmp.append(l.__getattr__(attr))
return tmp
def equal(self, value, attr='class'):
tmp = List()
for l in self:
if hasattr(l, 'equal'):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.