content stringlengths 7 1.05M |
|---|
"""
Bucket by height, similar to last problem
I need a lookup for i, j to know how much "volume" is interior and occupied between "i, j"
Make a lookup table of value -> [min index of at least value, max index of at least value]
Lookup (i, j) -> volume of walls between i, j
"""
"""
i, j = 0, 1
total = 0
walVolume = 0... |
class TweetParser(object):
def __init__(self):
pass
'''
get an entity from a tweet if it exists
'''
def get_entity(self, entity_type, tweet):
if self.contains_entity(entity_type, tweet):
return [entity for entity in tweet["entities"][entity_type]]
return []
... |
""" Standard exceptions
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2021-04-29
:Copyright: 2021, SED-ML Editors
:License: Apache 2.0
"""
__all__ = [
'AlgorithmCannotBeSubstitutedException',
]
class AlgorithmCannotBeSubstitutedException(Exception):
""" Exception that the algorithm substitution policy does... |
class Headers(object):
def __init__(self):
self.app_key = None
self.Authorization = None
def getApp_key(self):
return self.app_key
def setApp_key(self, app_key):
self.app_key = app_key
def getAuthorization(self):
return self.Authorization
def setAuthoriza... |
#!/usr/bin/python3
# -- coding: utf-8 --
# Date: Tue 01 June 2021 14:04:28 CET
# Author: Margaux Fouque
# Description:
# SOLARIUS est un outil technique permettant de suivre la course du soleil
# tout au long de la journée.
# Python Version 3.9
# ECAM - AAM 1
''' Contrôle d'un servomoteur avec un ... |
#finding sum of elements of a list
lst=[10,20,30]
sum=0
for i in lst:
sum=sum+i
print(sum)
print('\n')
#printing index values along with their names
for i in range(1,11):
print(i,'CHENNAI')
print('\n')
#dsplaying elements of a list using for
lst=[10,20,30]
for i in (lst):
print(i) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
'''
dfs, bottom up
... |
def laceStringsRecur(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
def helpLaceStrings(s1, s2, out):
if s1 == '':
r... |
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def work(self):
print(f'{self.name} is working ...')
class SoftwareEngineer(Employee):
def __init__(self, name, age, level, salary):
super().__init__(... |
# Crie um programa que leia vários números inteiros pelo
# teclado. No final da execução, mostre a média entre
# todos os valores e qual foi o maior e o menor valores
# lidos. O programa deve perguntar ao usuário se ele quer
# ou não continuar a digitar valores.
soma = count = 0
menor = 99999
maior = -1
#n = int(inpu... |
# Začína, končí alebo obsahuje?
# Na vstupe získate dva reťazca. Otestujte či prvý reťazec začína, končí alebo iba obsahuje druhý reťazec.
# Možné výstupy:
# "{}" začína a končí "{}"
# "{}" začína "{}"
# "{}" končí "{}"
# "{}" obsahuje "{}"
# "{}" neobsahuje "{}"
# Miesto {} doplňte prvý a druhý reťazec.
# Sample In... |
print('Welcome to the YES/NO POLLiNG APP.')
issue = input('\nWhat is the yes/no issue you will be voting on today? : ')
vote_number = int(input('What is the number of voters you will allow on the issue? : '))
password = input('Enter a password for the polling results: ')
yes = 0
no = 0
results = {}
for i in range(vo... |
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
n1 = len(nums1)
n2 = len(nums2)
even = 1
if (n1+n2) == 1:
if n1==1:
return ... |
def onlyFlag():
flag = hero.findFlag()
if flag:
if hero.isReady("jump"):
hero.jumpTo(flag.pos)
hero.pickUpFlag(flag)
def summonIt():
if hero.canCast("summon-burl"):
hero.cast("summon-burl")
if hero.canCast("summon-undead"):
hero.cast("summon-unde... |
end = 6
total = 0
for num in range(end + 1):
total += num
print(total)
|
class BaseButton:
def __init__(self):
pass
def onclick(self):
pass
|
def getSumOf3Numbers(array , target):
"""
Write a function that takes in a non-empty array of distinct integers
and an integer representing a target sum. The function should find all
triplets in the array that sum up to the target sum and return a
two-dimensional array of all these triplets. The n... |
n = int(input("Enter the number to be rotated:"))
a = int(input("Enter the bits to be rotated:"))
print("1.Left Rotation 2.Right Rotation")
b = int(input("Enter your choice:"))
if b == 1:
print("The number",n,"after left rotation by",a,"bits is", n << a)
elif b == 2:
print("The number",n,"after right rot... |
"""
Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent.
"""
print("Welcome to Binary to Decimal & Back converter!")
while True:
action = input("Choose Your action:\n[1] - Convert binary to decimal\n[2] - Convert decimal to b... |
def ws_message(message):
# ASGI WebSocket packet-received and send-packet message types
# both have a "text" key for their textual data.
message.reply_channel.send({
"text": message.content['text'],
})
|
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
count1 = Counter(word1)
count2 = Counter(word2)
if count1.keys() != count2.keys():
return False
return sorted(count1.values()) == sorted(count2.values())
|
# The Western Suburbs Croquet Club has two categories of membership, Senior and Open. They would like your help with an application form that will tell prospective members which category they will be placed.
#
# To be a senior, a member must be at least 55 years old and have a handicap greater than 7. In this croquet c... |
# Copyright 2015 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.
{
'targets': [
{
'target_name': 'woff2_dec',
'type': 'static_library',
'include_dirs': [
'src',
'<(DEPTH)/third_party... |
"""
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
Example :
Input: [1,2,3]
O... |
# encoding: utf-8
# convert dictionary to object
class dict2obj(object):
def __init__(self, dictionary):
self.__dict__ = dictionary |
a = "test"
b = 0
def fun1(val):
global b
b = b + 1
#a = "hello"
def fun2():
global b
nonlocal val
b += 5
val += 1000
print(val)
fun2()
print(a)
fun1(100)
print(b) |
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
prev = 0
for letter in s:
found = False
for i in range(prev, len(t)):
if letter == t[i]:
prev = i+1
found = True
break
... |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '8/24/2020 11:04 PM'
class Solution:
def findSubsequences(self, nums):
self.res = []
def backtrace(nums, temp):
if len(temp) >= 2 and temp not in self.res:
self.res.append(temp)
if not num... |
'''
Clase que maneja datos de historial (Resultados de solicitud pasados)
'''
class History:
def __init__(self,message,arrReqRes):
self.__message=message # requests
self.__arrReqRes=arrReqRes
def getHistory(self):
data=[]
for reqRes in self.__arrReqRes:
data.append(... |
class Loss(object):
def __init__(self, dout):
self.dout = dout
def eval(self, _ytrue, _ypred):
"""
Subclass should implement log p(Y | F)
:param output: (batch_size x Dout) matrix containing true outputs
:param latent_val: (MC x batch_size x Q) matrix
of late... |
__all__ = [
"WriteError",
"InvalidQueryError",
"DoesNotExistError",
"MultipleObjectsReturnedError",
"FieldDoesNotExistError",
]
class WriteError(Exception):
pass
class InvalidQueryError(Exception):
pass
class DoesNotExistError(Exception):
pass
class MultipleObjectsReturnedError(E... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/3/9 4:19 PM
# @Author : xiaoliji
# @Email : yutian9527@gmail.com
"""
矩阵中的路径
>>> hasPath('ABEESFCSADME', rows=3, cols=4, path='SEE')
True
>>> hasPath('abtgcfcsjdeh', rows=3, cols=4, path='bfce')
True
>>> hasPath('abtgcfcsjdeh',... |
'''
Install mysql connector for python
Use the command in CMD: "pip install mysql-connector-python"
Also, install "MySQL Workbench"
Create a Database in workbench within 'root' user, here "myDB"
create a table in the database, here 'emp'
Now, go to any IDE or text editor to connect python with Database
''' |
def decode_orientation(net, n_classes, loss_fn,
train_data, train_labels, test_data, test_labels,
n_iter=1000, L2_penalty=0, L1_penalty=0):
""" Initialize, train, and test deep network to decode binned orientation from neural responses
Args:
net (nn.Module): deep ... |
'''
Utilitários Python para auxiliar na programação.
dir -> Apresenta todos os atributos/propriedades e funções/métodos disponíveis para
determinado tipo de dado ou variável.
dir(tipo de dado/variável)
dir(help)
help -> Apresenta a documentação/como utilizar osa tributos/propriedades e funções/métodos
disponívei... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created: April 2019
Author: A. P. Naik
Description: Physical constants and unit conversions, for general use. All SI
units.
"""
# constants
pi = 3.141592653589793
G = 6.67408e-11 # m^3 kg s^-2
# units
pc = 3.0857e+16 # metres
kpc = 3.0857e+19 # metres
Mpc = 3.0857... |
"""
Connect and manage field sensor in the area or centralized end points.
Also collects local temperature, humidity, air pressure, movement (gyroscope)
Comm method: wifi and mesh. Sat Comm, LoRa and GSM are still in development
"""
|
"""Npm integration testing
"""
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test")
# Returns the manifest path of a file: `workspace/path/to/file`
def _to_manifest_path(ctx, file):
if file.short_path.startswith("../"):
# Strip the ../ from short_path to external repository
return file.sho... |
## Multiples of 3 or 5
## 6 kyu
## https://www.codewars.com/kata/514b92a657cdc65150000006
def solution(n):
mult_sum = 0
for i in range (3, n):
if i % 3 == 0 or i % 5 ==0:
mult_sum += i
return mult_sum |
#******************************************************************************
# (C) 2018, Stefan Korner, Austria *
# *
# The Space Python Library is free software; you can redistribute it and/or *
... |
class Compliance:
def __init__(self, Status=None):
self.Status = Status
class Malware:
def __init__(self, Name=None, Path=None, State=None, Type=None):
self.Name = Name
self.Path = Path
self.State = State
self.Type = Type
class Network:
def __init__(self, Destinat... |
"""
Maintain version for CropMl.
"""
MAJOR = 0
"""(int) Version major component."""
MINOR = 0
"""(int) Version minor component."""
POST = 2
"""(int) Version post or bugfix component."""
__version__ = ".".join([str(s) for s in (MAJOR, MINOR, POST)])
|
train_task_id = '2T736'
initial_epoch = 0
epoch_num = 24
lr = 1e-3
decay = 5e-4
# clipvalue = 0.5 # default 0.5, 0 means no clip
patience = 2
load_weights = True
lambda_inside_score_loss = 4.0
lambda_side_vertex_code_loss = 1.0
lambda_side_vertex_coord_loss = 1.0
total_img = 222199
validation_split_ratio = 0.1
max_tr... |
peso_maior = 0
peso_menor = 0
for i in range(1, 6):
peso_pessoa = float(input(f'Peso da {i}ª pessoa em Kg: '))
if i == 1:
peso_maior = peso_pessoa
peso_menor = peso_pessoa
else:
if peso_pessoa > peso_maior:
peso_maior = peso_pessoa
if peso_pessoa < peso_menor:
... |
# Section07-2
# 파이썬 클래스 상세 이해
# 상속, 다중상속
# 예제1
# 상속 기본
# 슈퍼클래스(부모) 및 서브 클래스(자식) -> 모든 속성, 메소드 사용 가능
# 중복 코드 최소화 코드의 생산성..
# 라면 -> 속성(종류, 회사, 맛, 면 종류, 이름) : 부모 클래스
# car class 인스턴스 화
class car:
""" parent calss """
def __init__(self, tp, color):
self.type = tp
self.color = ... |
#encoding:utf-8
subreddit = 'tifu'
t_channel = '@r_channels_tifu'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
#
# @lc app=leetcode id=217 lang=python3
#
# [217] Contains Duplicate
#
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
# first approach: use a hashtable, add the number to the hashtable
# if the number is already there, return True
# second approach: use a set. retur... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class LookupCache:
"""
Prime a cache of all valid knowledge base phrases to prevent costly DB lookups for phrases that do not exist.
"""
def __init__(self,
resource_path='../kb-classifier/data-wiki/resources.txt',
red... |
def dictionary_masher(dict_a, dict_b):
for key, value in dict_b.items():
if key not in dict_a:
dict_a[key] = value
return dict_a |
class Accessor(property):
"""Accessor is a property factory for structure fields
The Accessor is used by the Meta metaclass to generate accessors for the
structure fields inside a new strcuture class.
"""
def __init__(self, item, key):
super().__init__(
lambda s: item.getter(s._... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
class Solution:
def thirdMax(self, nums: List[int]) -> int:
if len(set(nums))<3:
return max(nums)
for i in range(2):
for i in range(nums.count(max(nums))):
nums.remove(max(nums))
return max(nums)
|
# Copyright 2019 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... |
#
# PySNMP MIB module GSM7312-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GSM7312-QOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:20:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
'''
You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.
You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.
For each query queries[j], com... |
class Solution(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 1:
return n
dp = [0] * (n + 1)
dp[0] = 0
dp[1] = 1
dp[2] = 1
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] + ... |
def extractWwwWhimsicalstargazersNet(item):
'''
Parser for 'www.whimsicalstargazers.net'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('The Reborn Little Girl Won\'t Give Up', 'The... |
#!/usr/bin/env python3
"""
This document is created by magic at 2018/8/16
"""
class BaseStack:
"""
doc 利用python实现一个栈
"""
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def pop(self):
item = self.items[-1]
self.items = sel... |
def somaAll(x,y):
s = c = 0
l = [x]
while x < y:
s = x + 1
l.append(s)
x+=1
s=0
while c <len(l):
s += l[c]
c+=1
return s
def somaintervalo(ini,fim):
c=ini
s=0
while(c<=fim):
s+=c
c+=1
return s
print(somaAll(1,3))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Fibonacci:
def __init__(self, max_n):
self.MaxN = max_n
self.N = 0
self.A = 0
self.B = 0
def __iter__(self):
self.N = 0
self.A = 0
self.B = 1
return self
def __next__(self):
if self... |
# 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. Программа
# должна подсчитывать сумму чисел в файле и выводить ее на экран.
with open('numbers.txt', 'w+') as f:
is_writing = True
while is_writing:
new_string = input('> ')
new_string = ne... |
def addr(regs, a, b, c):
result = regs[:]
result[c] = regs[a] + regs[b]
return result
def addi(regs, a, b, c):
result = regs[:]
result[c] = regs[a] + b
return result
def mulr(regs, a, b, c):
result = regs[:]
result[c] = regs[a] * regs[b]
return result
def muli(regs, a, b, c):
... |
n = int(input())
m = int(input())
dif = n - m
print(dif)
|
def alphabetically_first(s1, s2):
sorted_list = sorted(list([s1, s2]))
return sorted_list[0]
|
class Solution:
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
pressed=[0]*26
lastRelease=0
for i in range(len(releaseTimes)):
index=ord(keysPressed[i])-ord('a')
pressed[index]=max(pressed[index],releaseTimes[i]-lastRelease)
... |
# Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
class DigitsError(Exception):
"""
DIGITS custom exception
"""
pass
class DeleteError(DigitsError):
"""
Errors that occur when deleting a job
"""
pass
class LoadImageError(DigitsError):
"""
Errors that occur w... |
# 打印输出可变参数的信息
def print_args(*args):
"""打印输出接收可变参数的args的信息"""
print('type(args) = ', type(args))
print('len(args) = ', len(args))
print('args = ', args)
print_args()
print()
print_args(1, 2, 3)
|
class TestApi:
def test_api_with_valid_url_bitly(self, post):
# when we ask to shorten a valid url
response = post(
'/shortlinks',
data={'url': 'https://www.withnottplum.com', 'provider': 'bitly'}
)
# then
assert response.status_code == 200
... |
def classify_numbers(numbers):
pos = [n for n in numbers if n >= 0]
neg = [n for n in numbers if n < 0]
even = [n for n in numbers if n % 2 == 0]
odd = [n for n in numbers if n % 2 != 0]
return pos, neg, even, odd
pos, neg, even, odd = classify_numbers([int(x) for x in input().split(', ')])
print(... |
sexo = ''
while sexo != 'M' or sexo != 'F':
sexo = str(input('Digite seu sexo (M/F): ')).upper().strip()[0]
if sexo == 'M' or sexo == 'F':
break
else:
print('Digite um dado válido!')
print('Sexo registrado com sucesso!') |
#!/usr/bin/python3
k, t = list(map(int, input().split()))
a = t // k
result = 0
if (a % 2 == 0):
result = t % k
else:
# print("k - t%k + 1", k, t)
result = k - t % k
print(result) |
# 题意:反转数组
# 解法1:递归,终止条件为head为None返回[],其余返回‘递归+head.val’
# 解法2:辅助栈,Python在遍历一个链表的时候,将值依次放入到一个list中,遍历结束后,翻转list输出即可。
# 注意这里的head就是listNode结构,head其实就相当于一个头节点,调用字节点需要通过.next函数。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solu... |
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def quicksort(left,right):
if left>=right:return
pivot = left
i=j=pivot+1
while j<=right:
if nums[j]<nums[pivot]:
nums[i],nums[j] = nums[j],nums[i]
... |
#!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 09.04.2018 14:18
:Licence MIT
Part of grammpy
"""
|
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function normalizes the encoding names before
doing the lookup, so the mapping will have to map normalized
encoding names to module names.
... |
class GridResizeDirection(Enum, IComparable, IFormattable, IConvertible):
"""
Specifies whether a System.Windows.Controls.GridSplitter control redistributes space between rows or between columns.
enum GridResizeDirection,values: Auto (0),Columns (1),Rows (2)
"""
def __eq__(self, *args):
... |
"""
简单工厂模式
实现一个肯德基类
可以生产汉堡
"""
class Foodstuff:
"""食材"""
vegetables = 'vegetables' # 蔬菜
meat = 'meat' # 肉
fruits = 'fruits' # 水果
eggs = 'eggs' # 鸡蛋
class Hamburger:
"""汉堡对象"""
def __init__(self, *args):
j = "".join([i + ' ' for i in args])
self.name = "this is a {} ha... |
#! /usr/bin/env python3
def ins_sort_indices(A):
F = list(range(len(A)))
for j in range(len(A)):
key = A[F[j]]
i = j-1
while i >= 0 and A[F[i]] > key:
F[i+1] = F[i]
i = i-1
F[i+1] = j
return F
def T(F):
T = list(range(len(F)))
for (i, f) in... |
"""
Django accounts management made easy.
"""
VERSION = (1, 0, 2)
__version__ = '.'.join((str(each) for each in VERSION[:4]))
def get_version():
"""
Returns string with digit parts only as version.
"""
return '.'.join((str(each) for each in VERSION[:3]))
|
#addListElements.py
list1 = [5, 4, 9, 10, 3, 5]
list2 = [6, 3, 2, 1, 5, 3]
print("list1 elements:", list1[0], list1[1], list1[2], list1[3], list1[4])
print("list2 elements:", list2[0], list2[1], list2[2], list2[3], list2[4])
list3 = []
j = len(list1)
for i in range(j):
list3.insert(0,list1[i] + list2[i])
print("l... |
"""TEST that will not run, because the filename does not start with 'test_'"""
def test_what_will_not_run():
assert True is False
|
class Account:
def __init__(self, name, balance, min_balance):
self.name = name
self.balance = balance
self.min_balance = min_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance - amount >= self.min_balan... |
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by Michael Inden
def quick_sort(values):
# rekursiver Abbruch
if len(values) <= 1:
return values
# Aufsammeln kleiner gleich / größer als Pivot
pivot = values[0]
below_or_equals = [value for value in values[1:] if valu... |
# 定义了失败类型的异常信息
""" failure type exceptions
these exceptions will mark test as failure
"""
class MyBaseFailure(Exception):
pass
class ParseTestsFailure(MyBaseFailure):
pass
class ValidationFailure(MyBaseFailure):
pass
class ExtractFailure(MyBaseFailure):
pass
class SetupHooksFailure(MyBase... |
#
# PySNMP MIB module JUNIPER-LSYSSP-SCHEDULER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-LSYSSP-SCHEDULER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:00:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
class solution:
def __init__(self):
self.best = 0
self.bestIndividual = []
self.solutions = []
self.population_fitness = []
self.optimizer = ""
self.objfname = ""
self.lb = 0
self.ub = 0
self.dim = 0
self.popnum = 0
self.maxiers... |
name = "Waldo"
text = "Can you find where Wally is?"
if text.find(name):
print("Found Waldo")
else:
print("Cannot find Waldo")
|
## maintain two array to keep track of dfs particular movement and visited vertex also..
def checkcycle( node, adj:list, visited:list, dfsvisited:list):
visited[node] = 1
dfsvisited[node] = 1
for i in adj[node]:
if(visited[i] == 0):
if(checkcycle(i, adj, visited, dfsvisited) ... |
# -*- coding: utf-8 -*-
"""
This file is part of the open source project py-dynasynthetic
(see https://github.com/micha-k/py-dynasynthetic).
Author: Michael Kessel
Contact: I have an email account 'dev' on a host called 'michaelkessel' listed
in the toplevel domain 'de'.
"""
__version__ = '0.5'
|
def insertion_sort(l):
for x in range(len(l)):
pos = x
while pos > 0 and l[pos-1] > l[pos]:
l[pos-1], l[pos] = l[pos], l[pos-1]
pos -= 1
list1 = [9, 2, 6, 5, 1, 7]
insertion_sort(list1)
print(list1)
|
"""
B. Fair Division
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Alice and Bob received n candies from their parents.
Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies
among themselves fairly so that the total weight o... |
# encoding: utf-8
# module GH_IO.Types calls itself Types
# from GH_IO,Version=1.0.0.0,Culture=neutral,PublicKeyToken=6a29997d2e6b4f97
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no imports
# no functions
# classes
class GH_BoundingBox(object):
"""
Represents a 3D bounding... |
def _parse_categories(lines):
"""
Read (category_id, category_name) pairs from the categories section.
Each line consists of an integer followed a tab and then the category name.
This section is separated from the lexicon by a line consisting of a single "%".
"""
for line in lines:
line ... |
def test_example() -> None:
assert True, "not True"
assert 1 + 1 == 2
assert 4 / 2 == 2
assert 2 * 2 == 4
assert "ab" + "bc" == "abbc"
|
soma = contador = 0
while True:
numero = int(input('Digite um número: '))
if numero == 999:
break
soma += numero
contador += 1
print(f'Você digitou {contador} e a soma deles vale {soma}.') |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/config/hp_defaults.ipynb (unless otherwise specified).
__all__ = ['allow_base_class', 'name_epoch', 'name_last_epoch', 'name_model_history', 'model_file_name',
'path_experiments', 'defaults', 'root', 'metric', 'op', 'result_file', 'min_iterations', 'use_previo... |
# Given the head of a singly linked list, group all thenodes
# # with odd indices together followed by the nodes with even indices, and return the reordered list.
# #
# # The first node is considered odd, and the secondnode is even, and so on.
# #
# # Note that the relative order inside both the even and odd groups sho... |
days = {
'mon': 'Понедельник',
'tue': 'Вторник',
'wed': 'Среда',
'thu': 'Четверг',
'fri': 'Пятница',
'sat': 'Суббота',
'sun': 'Воскресенье'
}
|
# -*- coding: utf-8 -*-
"""
Исключения NewEraAI
"""
class NewEraAIException(Exception):
"""Базовый класс для всех пользовательских исключений NewEraAI"""
pass
class LanguagesSRError(NewEraAIException):
"""Указан неподдерживаемый язык для распознавания речи"""
pass
class DictSRError(NewEraAIException... |
class Atom:
__slots__ = ["name", "type", "resname", "resid", "x", "y", "z",
"diameter", "rotmass", "charge", "mass",
"sigma", "epsilon", "dipole"]
def __init__(self, **kwargs):
for key in self.__slots__:
try:
setattr(self, key, kwargs[key])... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.