content stringlengths 7 1.05M |
|---|
## 6. Write a program that asks the user to input 10 integers, and
# then prints the largest odd number that was entered. If no odd number was
# entered, it should print a message to that effect.
# Kullaniciya 10 adet tamsayi isteyen ve girilen sayilar icindeki en buyuk tek
# sayiyi yazdiran programi yaziniz. Eg... |
""" Created by GigX Studio """
class RequestResult:
success = False
data = None
code = -1
def __init__(self, success, data, code):
self.success = success
self.data = data
self.code = code
def getCode(self):
return self.code
def getData(self):
return se... |
class Solution:
def countBalls(self, lowLimit: int, highLimit: int) -> int:
hashMap = {}
max_value = 0
for box_id in range(lowLimit, highLimit+1):
runner = box_id
box_num = 0
while runner > 0:
box_num += (runner%10)
runner /... |
"""Reforemast global settings."""
class Settings: # pylint: disable=locally-disabled,too-few-public-methods
"""Reforemast settings."""
def __init__(self):
self.auto_apply = False
self.gate_url = 'https://gate.spinnaker.com'
self.application_updaters = []
self.pipeline_update... |
# -*- coding: utf-8 -*-
class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
size = len(A)
res = [0] * size
l, r, i = 0, size - 1, size - 1
while l <= r:
if A[l] + A[r] < 0:
r... |
priorities = [
('Low', 'LOW'),
('Medium', 'MEDIUM'),
('High', 'HIGH'),
('Urgent', 'URGENT'),
('Emergency', 'EMERGENCY')
]
bootstrap_priorities = [
'text-default',
'text-success',
'text-info',
'text-warning',
'text-danger'
]
action_types = [
('PreProcessor', 'PREPROCESSOR'),... |
def decrescent(number_items, weight_max, values_items, weight_items):
items = {}
for i in range(number_items): items[i] = values_items[i],weight_items[i]
items = sorted(items.values(), reverse=True)
result_final = 0
weight = 0
for values_items,weight_items in items:
if weight_items+weight <= weight_max:
res... |
def add_one(number):
return number + 1
def add_one(number):
return number + 2
|
'''a = 10
b = 4
print("Value of a : ",a)
print("Background str method will invoke so that we are getting a value not address : ",a.__str__())
print("Addition : ", a + b)
print("Background Method addition using int class : ", int.__add__(a, b)) '''
class Student:
def __init__(self,m1,m2):
self.m1 = m1
... |
# Resta
x, y, z = 10, 23, 5
a = x - y - z # -18
a = x - x - x # -10
a = y - y - y - y # -46
a = z - y - z # -23
a = z - z - z # -5
a = y - y - z # -5
print("Final") |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2014 Michele Filannino
#
# gnTEAM, School of Computer Science, University of Manchester.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU General Public License.
#
# author: Michele Filannino
#... |
PHYSIO_LOG_RULES = [
{
"key": "ImageType",
"value": [("ORIGINAL", "PRIMARY", "RAWDATA", "PHYSIO")],
"lookup": "exact",
"operator": "any",
},
]
|
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test")
def _serialize_file(file):
"""Serializes a file into a struct that matches the `BazelFileInfo` type in the
packager implementation. Useful for transmission of such information."""
return struct(path = file.path, shortPath = file.short_path)
d... |
# 바둑판에 흰 돌 놓기
checkerboard = [[0 for j in range(20)] for i in range(20)]
times = int(input())
for count in range(times):
x, y = map(int, input().split())
checkerboard[x][y] = 1
print()
for i in range(1, 20):
for j in range(1, 20):
print(checkerboard[i][j], end =" ")
print() |
def solve(limit: int):
"""Solve project euler problem 95."""
sum_divs = [1] * (limit + 2) # Stores sum of proper divisors
amicables = {1} # Max numbers in amicable chains
max_length = 0
max_list_min = None
for i in range(2, limit + 1):
# As only sums up to i calculated, only chains st... |
class Solution:
def diffByOneCharacter(self, word1: str, word2: str) -> bool:
counter = 0
for i in range(len(word1)):
if word1[i] != word2[i]:
counter += 1
if counter > 1: return False
return counter == 1
def helper(self, beginWord: str, end... |
PICKUP = 'pickup'
DROPOFF = 'dropoff'
#
# Time complexity: O(n*log(n)) (due the sorting)
# Space complexity: O(1)
#
def active_time(events):
# sort the events by timestamp
events.sort(key=lambda event: event[1])
active_deliveries = 0
start_timestamp = 0
acc_active_time = 0
for event in events:
_, t... |
#
# Created on Wed Dec 22 2021
#
# Copyright (c) 2021 Lenders Cooperative, a division of Summit Technology Group, Inc.
#
def test_create_and_delete_subscriber_with_django_user(client, django_user):
results = client.create_subscriber(email=django_user.email, name=django_user.username)
data = results["data"]
... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict = {}
for i, v in enumerate(nums):
if target - v in dict:
return dict[target - v] , i
elif v not in dict:
dict[v] = i
return []
|
class DataGridTextColumn(DataGridBoundColumn):
"""
Represents a System.Windows.Controls.DataGrid column that hosts textual content in its cells.
DataGridTextColumn()
"""
DataGridOwner = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets the Sys... |
def solution(participant, completion):
answer = ''
val={}
for i in participant:
if i in val.keys():
val[i]=val[i]+1
else:
val[i]=1
for i in completion:
val[i]-=1
for i in val.keys():
if val[i]>0:
answer... |
soma = lambda a, b: a+b
multiplica = lambda a, b, c: (a + b) * c
r = soma(5, 10)
print(r)
print(multiplica(5, 3, 10))
print((lambda a, b: a + b)(3, 5))
r = lambda x, func: x + func(x)
print(r(2, lambda a: a*a))
|
file = open("input.txt", "r")
for line in file:
print(line)
file.close()
|
def increment_and_return(x):
return ++x
CONSTANT = 777
++CONSTANT |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def number_to_k_notation(number: int) -> str:
k = 0
while True:
if number // 1000 == 0:
break
number /= 1000
k += 1
return str(round(number)) + 'k' * k
if __name__ == '__main__':
print(numb... |
"""
Public exceptions and warnings
"""
class CasefileNotFoundError(FileNotFoundError):
"""
Raised when casefile cannot be found.
"""
class CasefileQueryError(ValueError):
"""
Raised if more than one casefile returned when querying database. Case ID
is unique, so should only return one file.
... |
"""
问题描述:给定一个字符串str1,只能往str1的后面添加字符变成str2。
要求1:str2必须包含两个str1,两个str1可以有重合,但是不能以同一个位置开头。
要求2:str2尽量短。
最终返回str2.
举例:
str1 = 123, 则str2 = 123123,这时候包含两个str1,且不以相同位置开头,且str2最短。
"""
class ShortestStr:
@classmethod
def get_shortest_str(cls, str1):
if not str1:
return str1
if len(str1) ... |
class ElementTypeGroup(Enum, IComparable, IFormattable, IConvertible):
"""
The element type group.
enum ElementTypeGroup,values: AnalyticalLinkType (136),AngularDimensionType (37),ArcLengthDimensionType (38),AreaLoadType (82),AreaReinforcementType (87),AttachedDetailGroupType (34),BeamSystemType (54),Bu... |
"""
Wextracto is a library for extracting data from web resources.
:copyright: (c) 2012-2017
"""
__version__ = '0.14.1' # pragma: no cover
|
class Solution:
"""
@param n: the given number
@return: the double factorial of the number
"""
def doubleFactorial(self, n):
# Write your code here
result=n
n=n-2
while n>0:
result*=n
n=n-2
return result |
# -*- coding: utf-8 -*-
"""Initialize the bits/{{ cookiecutter.project_slug }} module."""
# This Example class can be deleted. It is just used to prove this module is setup correctly.
class Example(object):
"""Example class."""
def __init__(self):
"""Initialize an Example class instance."""
p... |
def sort_tuple(l):
#sorts the list based on the last element of each tuple in the list
for i in range(0,len(l)):
for j in range(i,len(l)):
ti=l[i]
tj=l[j]
if(ti[len(ti)-1] >= tj[len(tj)-1]):
l[i],l[j]=l[j],l[i]
return l
l=[]
t=()
element=input('Enter the element STOP to stop the set and END to stop... |
# Databricks notebook source
EEPZPOYNTLXMQ
JJJRZNZJQBU
NWUICTFSCWRAXZCIVQH
ZLMARDXCEPBVABNCRDRZXBNYUYTTVVGVUQIUGDYFCWXKACFAQQGXLA
DEAMZLPRZOFVDN
YKUUXXBIWLRXVGXX
MVABNRSHUGM
QOOHHNCXMEXVNNWMJCUQJYOJLENEEYPJGEKJQAAENEZUIWRVSZKGTVYPTTDJKBQZPHCTMMBJXEJRWMIHKWDMALPNSLGSQRRRTYB
DHVRPMCZKDLIHCLAWFYKHMPZUFKVVCAQYIUAKISMVSEUVA... |
def get_digit(n):
result = []
while n>0:
result.insert(0,n%10)
n=n//10
return result
print(get_digit(12345)) |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np"
]
},
{
"cell_type": "markdown",
"metadata":... |
brandnum = {'삼성' :[],'애플' : [],'한성' : [],'레노버':[],'엘지':[],'아수스' : [],'기타': []}
num = list(map(int,input().split()))
for i in num :
if i>=1000 and i<2000 :
brandnum['삼성'] = [i]
elif i>=2000 and i<3000 :
brandnum['애플'] = [i]
elif i>=3000 and i<4000 :
brandnum['한성'] = [i]
elif i>=40... |
#!/usr/bin/env python
class CrossReference(object):
def __init__(self, db):
self.db = db
def check(self, tweet):
pass
|
"""
Descrição
Crie quatro funções básicas para simular uma Fila:
cria_fila(): Retorna uma fila vazia.
tamanho(fila): Recebe uma fila como parâmetro e retorna o seu tamanho.
adiciona(fila, valor): Recebe uma fila e um valor como parâmetro, adiciona esse valor na última posição da fila e a retorna.
remove(fila): Recebe ... |
'''
给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。
回想一下:
叶节点 是二叉树中没有子节点的节点
树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
如果我们假定 A 是一组节点 S 的 最近公共祖先,S 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。
注意:本题与力扣 865 重复:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/
示例 1:
输入:root = [3,5,1,6,2,0,8,null,null,7,... |
def check_target(ast):
pass
def check_iterator(ast):
pass
def check_lambda(ast):
pass |
fac_no_faction = 0
fac_commoners = 1
fac_outlaws = 2
fac_neutral = 3
fac_innocents = 4
fac_merchants = 5
fac_dark_knights = 6
fac_culture_1 = 7
fac_culture_2 = 8
fac_culture_3 = 9
fac_culture_4 = 10
fac_culture_5 = 11
fac_culture_6 = 12
fac_culture_7 = 13
fac_culture_8 = 14
fac_culture_9 = 15
fac_cultur... |
n = int(input("Enter the number to be checked:"))
m = (n//2)+1
c = 0
for i in range(2,m):
if n%i == 0:
c = 1
if c == 0:
print("The number",n,"is prime")
else:
print("The number",n,"is not prime")
|
# Class
# "The best material model of a cat is another, or preferably the same, cat."
#
# You probably won't define your own in this class, but you will have to know how to use someone else's.
#
# Stanley H.I. Lio
# hlio@hawaii.edu
# OCN318, S18, S19
# this defines a CLASS (indentation matters!):
class Mordor:
... |
def test_tags_tag(self):
"""
Comprobacion de que la etiqueta (keyword) coincide con su asociada
Returns:
"""
tags = Tags.objects.get(Tag="URGP")
self.assertEqual(tags.get_tag(), "URGP")
|
class SenderKeyDistributionMessageAttributes(object):
def __init__(self, group_id, axolotl_sender_key_distribution_message):
self._group_id = group_id
self._axolotl_sender_key_distribution_message = axolotl_sender_key_distribution_message
def __str__(self):
attrs = []
if self.gr... |
menu ='''
######################################################################
# Sla a vida é Boa #
######################################################################
1- Cadastrar uma Banda
2- Cadastrar um Album
3- Cadastrar uma Musica
4- Sair
Digite o Opção des... |
class Genre:
def __init__(self, genre_name: str):
if genre_name == "" or type(genre_name) is not str:
self.name = None
else:
self.name = genre_name.strip()
def __repr__(self):
return f"<Genre {self.name}>"
def __eq__(self, other: 'Genre') -> bool:
r... |
class frame_buffer():
def __init__(self):
self.frame1 = None
self.frame2 = None
def set_current(self, frame):
self.frame1 = self.frame2
self.frame2 = frame |
a, b, c, d = input().split(' ')
a = int(a)
b = int(b)
c = int(c)
d = int(d)
if a % 2 == 0 and c > 0 and d > 0:
if b > c and d > a and (c + d) > (a + b):
print('Valores aceitos')
else:
print('Valores não aceitos')
else:
print('Valores não aceitos')
|
"""
Strategy Design Pattern implementation.
Decorator implementation.
Templates.
Pattern in General.
Author: Vinicius Melo
"""
|
"""
384. Longest Substring Without Repeating Characters
https://www.lintcode.com/problem/longest-substring-without-repeating-characters/description
3. Longest Substring Without Repeating Characters
https://leetcode.com/problems/longest-substring-without-repeating-characters/
"""
class Solution:
"""
@param s: a... |
class Hero:
#private class variabel
__jumlah = 0
def __init__(self,name,health,attPower,armor):
self.__name = name
self.__healthStandar = health
self.__attPowerStandar = attPower
self.__armorStandar = armor
self.__level = 1
self.__exp = 0
self.__healthMax = self.__healthStandar * self.__level
self... |
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
@classmethod
def new_square(cls, side_length):
return cls(side_length, side_length)
class num:
@staticmethod
def add(a, ... |
#####################################
# Descriptions.py
#####################################
# Description:
# * Print run script description and
# json argument descriptions to screen.
def TestETLPipelineDescription():
"""
* Describe TestETLPipeline and arguments.
"""
pass
|
def area(l,c):
a = float(l)*float(c)
print(f'A area do terreno {l}X{c} é de {a}m²')
#main
print('-'*22)
print(' Controle de Terrenos ')
print('-'*22)
lar = float(input('LARGURA(m): '))
com = float(input('COMPRIMENTO(m): '))
area(lar,com)
|
a_factor = 16807
b_factor = 48271
generator_mod = 2147483647
check_mask = 0xffff
def part1(a_seed, b_seed):
judge = 0
a = a_seed
b = b_seed
for i in range(40*10**6):
a = (a*a_factor) % generator_mod
b = (b*b_factor) % generator_mod
if a & check_mask == b & check_mask:
... |
#
# PySNMP MIB module HP-SWITCH-ERROR-MSG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-SWITCH-ERROR-MSG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:36:45 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
"""
67 二进制求和
给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 1 和 0。
"""
def addBinary(a, b):
if len(a) < len(b):
a, b = b, a
a = [int(v) for v in a]
b = [int(v) for v in b]
for i in range(1, len(b) + 1):
res = a[-i] + b[-i]
if res < 2:
a[-i] = res
continu... |
"""
Dicionários
OBS: em algumas linguagens, os dicionários Python são conhecidos por mapas.
Dicionários são coleções do tipo chave/valor
Dicionarios são representados por chaves {}
OBS: Sobre dicionários:
— Chave e valor são representados por dois pontos 'chave: valor'
— Tanto chave quanto valor podem ser de ... |
def playeraction(action, amount, chipsleft, chipsinplay, lastraise, amounttocall):
chipstotal = chipsinplay + chipsleft
if action == 'fold':
if chipsinplay < amounttocall:
return { 'fold': True }
return { 'fail': True }
elif action == 'check':
if chipsinplay != amounttoc... |
# MIT License
#
# Copyright (c) 2020 Tony Wu <tony[dot]wu(at)nyu[dot]edu>
#
# 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 rights
# to u... |
#8-9
magic_name = ['zhoujielun','hemm','fangshiyu']
def show_magicians(name):
print(name)
new_magic_name = []
def make_great(name,names):
for old_name in name:
new_name = "the Great " + old_name
new_magic_name.append(new_name)
show_magicians(new_magic_name)
show_magicians(names)
make_great(magic_name[:],m... |
_base_ = ["./resnest50d_a6_AugCosyAAE_BG05_HBReal_200e_benchvise.py"]
OUTPUT_DIR = "output/gdrn/hbSO/resnest50d_a6_AugCosyAAEGray_BG05_mlBCE_HBReal_200e/driller"
DATASETS = dict(
TRAIN=("hb_bdp_driller_train",),
TEST=("hb_bdp_driller_test",),
)
MODEL = dict(
WEIGHTS="output/gdrn/lm_pbr/resnest50d_a6_AugC... |
# -*- coding: utf-8 -*-
__author__ = 'Christoph Herb'
__email__ = 'ch.herb@gmx.de'
__version__ = '0.1.0'
|
game_properties = ["current_score", "high_score", "number_of_lives", "items_in_inventory", "power_ups", "ammo", "enemies_on_screen", "enemy_kills", "enemy_kill_streaks", "minutes_played", "notifications", "achievements"]
print(f'{game_properties =}')
print(f'{dict.fromkeys(game_properties, 0) =}') |
# Simply prints a message
# Author: Isabella
message = 'I have eaten ' + str(99) + ' burritos.'
print(message) |
#
# Object-Oriented Python: Dice Roller
# Python Techdegree
#
# Created by Dulio Denis on 12/22/18.
# Copyright (c) 2018 ddApps. All rights reserved.
# ------------------------------------------------
# Challenge 4: Chance Scoring
# ------------------------------------------------
# Challenge Task 1 of 2
# I've ... |
class Conta:
def __init__(self, numero, titular, saldo, limite=1000):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
def imprimir_extrato(self):
print(f'O saldo do titular "{self.__titular}" é: R$ {self.__saldo:.2f}')
de... |
class ResponseHandler():
def error(self, content, title = 'Erro!'):
try:
resp = {'mensagem': {'titulo': title,
'conteudo': str(content)},
'status': 'erro'}
return resp
except:
return({'mensagem': {'titulo': 'Op... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Joel Pedraza"
__copyright__ = "Copyright 2014, Joel Pedraza"
__license__ = "MIT"
class HumbleException(Exception):
""" An unspecified error occurred. """
pass |
rules_file_path = "./input/rules.txt"
facts_file_path = "./input/facts.txt"
hypothesis_file_path = "./input/hypothesis.txt"
val = {} # valor de um item ou "?" caso seja indefinido
rules = {} # dicionário que guarda todas as regras nas quais o item x está presente como uma conclusao
rules2 = {} # dicionário que gua... |
default_queue_name = 'arku:queue'
job_key_prefix = 'arku:job:'
in_progress_key_prefix = 'arku:in-progress:'
result_key_prefix = 'arku:result:'
retry_key_prefix = 'arku:retry:'
abort_jobs_ss = 'arku:abort'
# age of items in the abort_key sorted set after which they're deleted
abort_job_max_age = 60
health_check_key_suff... |
class Scene:
"""
A scene has a name and a detector function, which returns true if the scene is
detected, false otherwise.
Attributes:
name (string): A descriptive name of what the scene consists of.
detector (function): A function that checks if that scene is present.
"""
def __init__(sel... |
"""
387. First Unique Character in a String
https://leetcode.com/problems/first-unique-character-in-a-string/
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Example:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
"""
# Runtime: 176ms (27.12... |
"""Helper functions to search class-map configurations"""
def is_instance(list_or_dict) -> list:
"""Converts dictionary to list"""
if isinstance(list_or_dict, list):
make_list = list_or_dict
else:
make_list = [list_or_dict]
return make_list
def is_mpls(outter_key, inn... |
# 给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
#
# 输入为三个整数:day、month 和 year,分别表示日、月、年。
#
# 您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}。
#
#
#
# 示例 1:
#
# 输入:day = 31, month = 8, year = 2019
# 输出:"Saturday"
# 示例 2:
#
# 输入:day = 18, month = 7, year = 1999
# 输出:"Sunday"
# 示例 3:
#
#... |
"""
All settings for Riakdb module
"""
RIAK_1 = '192.168.33.21'
RIAK_2 = '192.168.33.22'
RIAK_3 = '192.168.33.23'
RIAK_PORT = 8098
NUMBER_OF_NODES = 3 |
def test_rstrip(filetab):
filetab.textwidget.insert("end", 'print("hello") ')
filetab.update()
filetab.event_generate("<Return>")
filetab.update()
assert filetab.textwidget.get("1.0", "end - 1 char") == 'print("hello")\n'
|
matrix_size = int(input())
matrix = [[int(num) for num in input().split(", ")] for _ in range(matrix_size)]
primary_diagonal = [matrix[i][i] for i in range(matrix_size)]
secondary_diagonal = [matrix[i][matrix_size - 1 - i] for i in range(matrix_size)]
print(f"First diagonal: {', '.join([str(num) for num in primary_di... |
__version__ = '0.0.2-dev'
if __name__ == '__main__':
print(__version__)
|
# Flatten function from official compiler python module (decapriated in python 3.x)
# https://hg.python.org/cpython/file/3e7f88550788/Lib/compiler/ast.py#l7
#
# used to flatten a list or tupel
#
# [1,2[3,4],[5,[6,7]]] -> [1,2,3,4,5,6,7]
def flatten(seq):
l = []
for elt in seq:
t = type(elt)
... |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
dict = {'{': '}', '[': ']', '(': ')'}
for x in s:
if x in dict:
stack.append(x)
else:
if not stack and stack.po... |
# It was implemented quicksort iterative due "Fatal Python error: Cannot recover from stack overflow."
count = 0
# This function is same in both iterative and recursive
def partition(arr,l,h):
global count
i = ( l - 1 )
x = arr[h]
for j in range(l , h):
count = count + 1
if a... |
"""
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by
connecting adjacent lands horizontally or vertically.You may assume all four edges of the grid are all surrounded by water.
Input:
11110
11010
11000
00000
Output: 1
Input:
11000
1... |
"""
propagation_params.py
"""
class PropagationParams(object):
"""Represents the parameters to set for a propagation."""
DEFAULT_CONFIG_ID = "00000000-0000-0000-0000-000000000001"
DEFAULT_EXECUTOR = "STK"
@classmethod
def fromJsonResponse(cls, response_prop_params, description):
# Ig... |
class Solution:
def permute(self, nums):
res = []
self.helper(nums, res, [])
return res
def helper(self, nums, res, path):
if not nums:
res.append(path)
for i in range(len(nums)):
self.helper(nums[:i] + nums[i + 1:], res, path + [nums[i]])
i... |
class Auth0Exception(Exception):
pass
class InvalidTokenException(Auth0Exception):
def __init__(self, token):
self.token = token
|
class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
l = len(flowerbed)
if n == 0:
return True
if l == 1:
if n == 1:
if flowerbed[0] == 0:
... |
二十四桥明月夜
乾坤未定
unm = 1
unm2 = 2
unm5 = 55555
|
def zeros(n):
def factor_count(f):
sum = 0
F = f
while F < n:
sum += n // F
F *= f
return sum
return min( factor_count(2), factor_count(5) ) |
"""Package to show distinct data structures available in Python.
Data structures allow us to work with large data sets, group similar
data, organize (sorting, grouping, lookups, etc.).
The main Data Structure 'tools' are the following:
- Lists.
- Sets.
- Tuples.
- Dictionaries.
Data S... |
'''
***Cadeia de caracteres ou string***
São sequências de palavras, símbolos e/ou números colocadas entre aspas simples ou duplas.
Ex.: 'Curso em vídeo Python'
"Curso em vídeo Python"
'Aula 009'
Quando se atribui a uma variável uma string esses dados serão armazenados na memória do computador, porém esse ... |
""""
Question 9 :
Write a program that accepts sequence of lines as input
and print the lines after making all characters in the sentence
capitalized.Suppose the following input supplied to the program :
hello world practice makes perfect Then, output should be :
HELLO WORLD PRACTICE MAKES PERFECT.
... |
def formaREAL(x):
return f'R${x:.2f}'
def formaEURO(x):
return f'€{x:.2f}'
|
def log(string):
print(string)
def debug(string):
print(string)
|
# iterating over the keys:
words = {'hello': 90, 'i': 550, 'am': 120, 'batman': 13, 'ball': 120}
# for key in words.keys():
# print(key)
# for key in words:
# print(key)
# iterate over the values
# for value in words.values():
# print(value)
# total_words = sum(words.values())
# print(total_words)
# i... |
galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
print(galera)
print(galera[0])
print(galera[0][0])
print(galera[2][1])
for i in galera:
print(i)
print(i[0])
print(i[1])
input('\n\nPressione <enter> para continuar')
|
#PROGRAMA QUE RECEBA VÁRIAS NOTAS, E RETORNE UM DICIONARIO COM TOTAL DE NOTAS, MAIOR NOTA, MENOR, MÉDIA E SITUAÇÃO DO ALUNO COMO PARAMETRO OPICIONAL.
def notas(*num, sit=False):
dados = {}
dados['total'] = len(num)
dados['maior'] = max(num)
dados['menor'] = min(num)
dados['media'] = sum(num)/len(nu... |
"""Created by sgoswami on 7/26/17."""
"""Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, o... |
# exceptions.py -- custom exception classes for this module
class PayloadException(Exception):
'''
Something went wrong with the payload from the GitHub API.
'''
pass
class WorkerException(Exception):
'''
Something went wrong in the worker process.
'''
pass
class QueueException(Exc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.