content stringlengths 7 1.05M |
|---|
def setUpModule() -> None:
print("[Module sserender Test Start]")
def tearDownModule() -> None:
print("[Module sserender Test End]") |
print('begin program')
# This program says hello and asks for my name.
print('Hello, World!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
print('end program')
|
# -*- coding: utf-8 -*-
def generate_translations(item):
"""Generate French and Spanish translations for the given `item`."""
fr_prefix = u'(français) '
es_prefix = u'(español) '
oldname = str(item.name)
item.name = {'en': oldname,
'fr': fr_prefix + oldname,
'es':... |
""" Mehmet Said Turken 180401030"""
dosya = open("veriler.txt.txt", "r")
veri = []
for i in dosya.read().split():
veri.append(int(i))
n = len(veri)
yitoplam = sum(veri)
def x_degerleri(list, n):
valuex = []
for i in range(13):
x = 0
for k in range(n):
... |
#!/usr/bin/env python
'''
primes.py
@author: Lorenzo Cipriani <lorenzo1974@gmail.com>
@contact: https://www.linkedin.com/in/lorenzocipriani
@since: 2017-10-23
@see:
'''
primesToFind = 1000000
num = 0
found = 0
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0: return Fa... |
#
# @lc app=leetcode id=705 lang=python3
#
# [705] Design HashSet
#
# https://leetcode.com/problems/design-hashset/description/
#
# algorithms
# Easy (53.97%)
# Likes: 145
# Dislikes: 39
# Total Accepted: 23.6K
# Total Submissions: 43.5K
# Testcase Example: '["MyHashSet","add","add","contains","cont... |
class ExportingTemplate():
def __init__(self, exporting_template_name=None, channel=None, target_sample_rate=None, duration=None, created_date=None, modified_date=None, id=None):
self.exporting_template_name = exporting_template_name
self.channel = channel
self.target_sample_rate = target_sa... |
# -*- coding: utf-8 -*-
"""
indico_payment_stripe
~~~~~~~~~~~~~~~~~~~~~
Indico plugin for Stripe payment support.
:license: MIT
"""
RELEASE = False
__version_info__ = ('0', '0', '1')
__version__ = '.'.join(__version_info__)
__version__ += '-dev' if not RELEASE else ''
__author__ = 'NeIC'
__homepa... |
# Based on container/push.bzl from rules_docker
# Also based on pkg/pkg.bzl from bazel_tools
# Copyright 2015, 2017 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 t... |
"""文字列基礎
フォーマット済み文字列リテラル(f-string)の使い方
「=」で変数や式を含めて表示する方法
※ python 3.8 で追加
[説明ページ]
https://tech.nkhn37.net/python-str-format-f-string/#_Python_38
"""
# フォーマット文字列で変数や式を表示する方法
name = '太郎'
sex = '男性'
age = 20
# f-stringで変数や式を含めて表示する方法
print(f'{name=}は{age=}歳の{sex=}です。')
print(f'{name=}は{age*2=}歳の{sex=}です。')
|
# Given an array of strings strs, group the anagrams together. You can return the answer in any order.
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
# Example 1:
# Input: strs = ["eat","tea","tan","ate","nat... |
instructions = []
for line in open('input.txt', 'r').readlines():
readline = line.strip()
instructions.append((readline[0], int(readline[1:])))
directions = {
'E': [1, 0],
'S': [0, -1],
'W': [-1, 0],
'N': [0, 1],
}
direction = 'E'
x, y = 0, 0
for action, value in instructions:
if action in [*directions]:
x ... |
a = [ 1, 2, 3, 4, 5 ]
print(a)
print(a[0])
for i in range(len(a)):
print(a[i])
a.append(10)
a.append(20)
print(a) |
# -*- coding: utf-8 -*-
# 从头到尾打印单链表
class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class ChainTable(object):
def __init__(self, data):
self.head = Node(data[0])
p = self.head
for val in data[1:]:
p.next = Node(val)
p = p.next
# 方法 1: 递归
def print... |
def buble_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
nums[i], nums[i - 1] = nums[i - 1], nums[i]
def check_sort(nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
return False
return True
def main():
count_nums = int(input()... |
def temperature_statistics(t):
mean = sum(t)/len(t)
return mean, (sum((val-mean)**2 for val in t)/len(t))**0.5
print(temperature_statistics([4.4, 4.2, 7.0, 12.9, 18.5, 23.5, 26.4, 26.3, 22.5, 16.6, 11.2, 7.3])) |
"""Top-level package for diffcalc-core."""
__author__ = """Diamond Light Source Ltd. - Scientific Software"""
__email__ = "scientificsoftware@diamond.ac.uk"
__version__ = "0.3.0"
|
# Helper function to print out relation between losses and network parameters
# loss_list given as: [(name, loss_variable), ...]
# named_parameters_list using pytorch function named_parameters(): [(name, network.named_parameters()), ...]
def print_loss_params_relation(loss_list, named_parameters_list):
loss_variabl... |
"""
【Python魔术方法】增量赋值魔术方法 2019/10/30 22:36
"""
# TODO: 增量赋值魔术方法
"""
1.__iadd__(self,other)魔术方法:在给对象做+=运算的时候会执行的方法
2.__isub__(self,other)魔术方法:在给对象做-=运算的时候会执行的方法。
3.__imul__(self,other)魔术方法:在给对象做*=运算的时候会执行的方法。
4.__idiv__(self,other)魔术方法:在给对象做/=运算的时候会执行的方法。 -- Python2
5.__itruediv__(self,other)魔术方法:在给对象做真/=运算的时候会执行的方法。 --... |
# %% [287. Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
for i, v in enumerate(nums, 1):
if v in nums[i:]:
return v
|
def staircase(n):
asteriscos = 1
# Write your code here
for espacios in range(n, 0, -1):
for i in range (espacios):
print(' ', end='')
for j in range(asteriscos):
print('*', end='')
print()
asteriscos+=2
staircase(7)
|
#!/usr/bin/env python
class Host(object):
def __init__(self, name, groups,region, image, tags, size, meta=None):
self.name = name
self.groups = groups
self.meta = meta or {}
self.region = region
self.image = image
self.tags = tags
self.size = size
swifty_ho... |
'''
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: 2
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: 1
'''
#Approach 1: Priority Queues
'''
Algorithm
A... |
#!/usr/bin/env python3.5
#-*- coding: utf-8 -*-
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
main()
|
# -*- coding: UTF-8 -*-
#
# You are given an n x n 2D matrix representing an image.
#
# Rotate the image by 90 degrees (clockwise).
#
# Note:
# You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
#
# Example 1:
#
# Gi... |
class Libro:
def __init__(self, paginas, tapa,nombre, autor, genero, isbn):
self.paginas = paginas
self.tapa = tapa
self.nombre= nombre
self.autor = autor
self.genero = genero
self.isbn = isbn
def set_nombre(self,nombre):
self.nombre = nombre
def set... |
#
# @lc app=leetcode id=68 lang=python3
#
# [68] Text Justification
#
class Solution:
def split(self, words: List[str], maxWidth: int) -> List[List[str]]:
if not words:
return []
lines, cur_len = [[words[0]]], len(words[0])
for w in words[1:]:
if cur_len + 1 + len(w) ... |
"""
Build microservices with Python
"""
__author__ = "Vlad Calin"
__email__ = "vlad.s.calin@gmail.com"
__version__ = "0.12.0"
|
"""
Author: André Bento
Date last modified: 01-02-2019
"""
|
#
# Copyright 2020- IBM Inc. All rights reserved
# SPDX-License-Identifier: Apache2.0
#
class K8sNamespace:
"""
Represents a K8s Namespace, storing its name and labels
"""
def __init__(self, name):
self.name = name
self.labels = {} # Storing the namespace labels in a dict as key-value ... |
class Solution(object):
def numEquivDominoPairs(self, dominoes):
"""
:type dominoes: List[List[int]]
:rtype: int
"""
hashmap = dict()
for a, b in dominoes:
key = tuple([min(a, b), max(a, b)])
hashmap[key] = hashmap.setdefault(key, 0) + 1
... |
def update_data(hyper_params):
return dict(
train=dict(
samples_per_gpu=hyper_params['batch_size'],
workers_per_gpu=hyper_params['workers_per_gpu'],
dataset=dict(
root_dir=hyper_params['dataset_root'],
cifar_type=hyper_params['dataset_name'... |
class Person:
def __init__(self, name, age=21, gender='unspecified',
occupation='unspecified'):
self.name = name
self.gender = gender
self.occupation = occupation
if age >= 0 and age <= 120:
self.age = age
else:
self.age = 21
def... |
"""
Test group missing the last item
.. pii: Group 2 - Annotation 1
.. pii_types: id, name
"""
|
def obj_sort_by_lambda(obj_list, lmbd):
new_obj_list = obj_list.copy()
new_obj_list.sort(key=lmbd)
return new_obj_list
def obj_sort_by_property_name(obj_list, prop_name):
return obj_sort_by_lambda(obj_list, lambda x:getattr(x, prop_name))
def obj_list_decrypt(obj_list, enc):
new_obj_list = []
... |
# -*- coding: utf-8 -*-
"""Top-level package for appliapps."""
__author__ = """Lars Malmstroem"""
__email__ = 'lars@malmstroem.net'
__version__ = '0.1.0'
|
class InvalidUrl(Exception):
pass
class UnableToGetPage(Exception):
pass
class UnableToGetUploadTime(Exception):
pass
class UnableToGetApproximateNum(Exception):
pass
|
''' LISTA 02 - EXERCICIO 11
Nome: Guilherme Augusto Sbizero Correa
Data: Setembro /2020
Enunciado: Faça um programa solicite o preço de uma mercadoria e o
percentual de desconto. Exiba o valor de desconto e o preço a pagar.
'''
valorProduto = float(input("Digite o valor da mercadoria: "))
desc... |
# *******************************************************************************************
# *******************************************************************************************
#
# Name : error.py
# Purpose : Error class
# Date : 13th November 2021
# Author : Paul Robson (paul@robsons.org.uk)
#
# ***... |
# coding=utf-8
worker_thread_pool = None
key_loading_thread_pool = None
key_holder = None
is_debug = False
is_debug_requests = False
is_no_validate = False
is_only_validate_key = False
is_override = False
is_preview_filename = False
is_resize = False
thread_num = 1
src_dir = None
dest_dir = None
filename_pattern =... |
from_ = 1
to_ = 999901
# to_ = 1
output_file = open("result.txt", "w", encoding="utf-8")
for i in range(from_, to_ + 1, 100):
input_file = open("allTags/" + str(i) + ".txt", "r", encoding="utf-8")
data = input_file.read()
ind = 0
for j in range(100):
ind = data.find("class=\"i-tag\"", ind)
... |
#!/usr/bin/env python3
''' In this question , we are going to find the longest common substring, among two given substrings. in order to solve this question
we will be making use of dynamic programming. so we will create a matrix with all 0s in the initial row and column
Step 1: we need to initialise a matrix with siz... |
'''
Author : Govind Patidar
DateTime : 10/07/2020 11:30AM
File : AllPageLocators
'''
class AllPageLocators():
def __init__(self, driver):
'''
:param driver:
'''
self.driver = driver
'''Home page locator'''
# get XPATH current temperature text
text_curr_temp = '... |
word = input()
out = ''
prev = ''
# remove same letters which are the same as the previous
for x in word:
if x != prev:
out+=x
prev = x
print(out)
|
#
# PySNMP MIB module TPLINK-IPADDR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-IPADDR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:17:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
# Exercício 064:
'''Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar 999,
que é a condição de parada. No final mostre quantos números foram digitados e qual foi a soma entre eles,
desconsiderando o "flag".'''
numero = soma = contador = 0
while numero != ... |
""" Write a method/function DISPLAYWORDS() in python to read lines
from a text file STORY.TXT,
using read function
and display those words, which are less than 4 characters. """
F = open("story.txt", "r")
value = F.read()
lines = value.split()
count = 0
for i in lines:
if len(i) < 4:
print(i... |
#Programa que leia um nome completo e diga o primeiro e ultimo nome
nome = input('Digite seu nome completo: ').title()
splt = nome.split()
print(splt[0],splt[-1]) |
name = "chris alan"
name = name.title()
name = "1 w 2 r 3g"
# Complete the solve function below.
def solve(string):
"""
Capitalizing function
"""
list_strings = string.rstrip().split(" ")
result = ""
for item in list_strings:
if item[0].isalpha():
item = item.title()
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Esta class, contiene procedimientos de uso común.
class Utils:
# Devuelve S con Ancho caracteres (padding derecho con espacios). (Padding singnifica "relleno").
def FieldLeft(self, S, Ancho):
return S + Utils.Espacios(self, Ancho - len(S))
# Devuelve... |
def binary_search(ary, tar):
head = 0
tail = len(ary) - 1
found = False
while head <= tail and not found:
mid = (head + tail) / 2
if ary[mid] == tar:
found = True
elif ary[mid] < tar:
head = mid + 1
elif ary[mid] > tar:
tail = mid - 1... |
# example solution.
# You are not expected to make a nice plotting function,
# you can simply call plt.imshow a number of times and observe
print(faces.DESCR) # this shows there are 40 classes, 10 samples per class
print(faces.target) #the targets i.e. classes
print(np.unique(faces.target).shape) # another way to se... |
#python 3.5.2
def areAnagram(firstWord, secondWord):
firstList = list(firstWord)
secondList = list(secondWord)
result = True
if len(firstList) == len(secondList) and result:
#Sort both list alphabetically
firstList.sort()
secondList.sort()
i = 0
length =... |
#!/bin/zsh
'''
Regex Search
Write a program that opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results should be printed to the screen.
''' |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 16:11:48 2019
@author: Administrator
"""
#class Solution:
# def canJump(self, nums: list) -> bool:
# if 0 not in nums:
# return True
## if nums == [0]:
## return True
# a = []
# for k in range(len(nums)-1):
# ... |
''' Q1. Write a python code for creating a password for E-Aadhar card. The details used are the
first 4 letters of your name, date and month of your birth. The task is to generate a password
with the lambda function and display it.'''
name = input("Input your name (as on your Aadhar)\n")
dob = input("Please enter you... |
'''
给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。
例如,从根到叶子节点路径 1->2->3 代表数字 123。
计算从根到叶子节点生成的所有数字之和。
说明: 叶子节点是指没有子节点的节点。
示例 1:
输入: [1,2,3]
1
/ \
2 3
输出: 25
解释:
从根到叶子节点路径 1->2 代表数字 12.
从根到叶子节点路径 1->3 代表数字 13.
因此,数字总和 = 12 + 13 = 25.
示例 2:
输入: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
输出: 1026
解释:
从... |
# число N записали 100 раз поспіль і потім піднесли в квадрат. Що вийшло?
## Формат введення
# Вводиться ціле невід'ємне число N не перевищує 1000.
## Формат виведення
# Виведіть відповідь до задачі.
n = int(100*input())
print(n ** 2)
|
# Follow up for N-Queens problem.
# Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution(object):
result = 0
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
cols = []
self.search(n, cols)
... |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
'''
|
# -*- coding: utf-8 -*-
"""
PRTG Exceptions
"""
class PrtgException(Exception):
"""
Base PRTG Exception
"""
pass
class PrtgBadRequest(PrtgException):
"""
Bad request
"""
pass
class PrtgBadTarget(PrtgException):
"""
Invalid target
"""
pass
class PrtgUnknownRespons... |
# Faça um algoritimo que leia o preço de um produto e mostre seu novo preco com 5% de desconto
# Fazendo a leitura do preço antigo do produto
p = float(input('Informe qual preço do produto: '))
# Informar na tela o valor do novo preço com desconto calculado dentro do método .format.
print('O valor pago com desconto s... |
def getSampleMetadata(catalogName, tagName, digest):
return {
'schemaVersion': 2,
'mediaType': 'application/vnd.docker.distribution.manifest.v2+json',
'config': {
'mediaType': 'application/vnd.docker.container.image.v1+json',
'size': 1111,
'digest': digest
},
'layers': [
{... |
class Solution:
def count(self, s, target):
ans = 0
for i in s:
if i == target:
ans += 1
return ans
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0 for i in range(n+1)] for j in range(m+1)]
for s in strs:
zer... |
# remove nth node from end
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# brute
# create a new linked list without that element
# Time O(n)
# Space O(n)
# optimal
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.n... |
def readFile(fileName):
try:
with open(fileName,'r') as f:
print (f.read())
except FileNotFoundError:
print (f'File {fileName} is not found')
readFile('1.txt')
readFile('2.txt')
readFile('3.txt')
|
'''
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Examples:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
* The number can be negative already, in which case no change is required.
* Zero (0... |
cards = {'SPADE' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'HEART' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'CLUB' : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'],
'DIAMOND' : ['1', '2', '3', '4', '5', '6',... |
CR_ATTACHMENT_AVAILABLE = 'cr_available'
CR_ATTACHMENT_REQUEST = 'cr_request'
TRR_ATTACHMENT_AVAILABLE = 'trr_available'
TRR_ATTACHMENT_REQUEST = 'trr_request'
ATTACHMENT_TYPE_CHOICES = [
[CR_ATTACHMENT_AVAILABLE, 'CR attachment available'],
[CR_ATTACHMENT_REQUEST, 'CR attachment request'],
[TRR_ATTACHMENT_... |
# Description: Sample Code to Run mypy
# Variables without types
i:int = 200
f:float = 2.34
str = "Hello"
# A function without type annotations
def greet(name:str)-> str:
return str + " " + name
if __name__ == '__main__':
greet("Dilbert")
|
class GameObject:
def __init__(self, *, x=0, y=0, size=None):
self.x = x
self.y = y
self.size = size
self.half_width = self.size[0] / 2.
def to_rect(self):
"""Return the gameobject to be display by qs.anim"""
return [[self.x, self.y], self.size]
def update(s... |
"""Top-level package for ZotUtil."""
__author__ = """Cheng Cui"""
__email__ = "cheng.cui.95@gmail.com"
__version__ = "0.1.1"
|
numbers = [1,45,31,12,60]
for number in numbers:
if number % 8 == 0:
# Reject the list
print("The numbers are unacceptable")
break
else:
print("List okay!") |
velocidade = int(input('Qual a velocidade do carro(Km/h)? '))
if velocidade > 80:
print('VOCÊ ESTÁ A {} Km/h,ACIMA DA VELOCIDADE PERMITIDA!'.format(velocidade))
print('VOCÊ FOI MULTADO!')
print('VALOR DA MULTA R${:.2f}'.format((velocidade - 80)* 7))
'''else:
print('PARABÉNS! VOCÊ ESTÁ NO LIMITE DE VELOC... |
class WeatherResponse(object):
"""
Specifies the response to be sent for one weather object.
"""
def __init__(self, *args, **kwargs):
"""
Set values for object.
:param args:
:param kwargs:
"""
self.temp = kwargs.get("temp", None)
self.temp_units ... |
file = "01.data.txt"
f = open(file)
data = f.read()
f.close()
lines = data.split("\n")
readings = []
for line in lines:
readings.append(int(line))
print(readings)
# count all the increases
# have a counter
counter = 0
# each time number icreases increment the counter
for i in range(1, len(readings)):
pr... |
"""Holds documentation for the bot in dict form."""
def help_book(p):
return [
# Table of Contents
{
"title": "Table of Contents",
"description": f"Navigate between pages with the reaction buttons",
"1. Vibrant Tutorial": ["Learn how to use the bot and its comma... |
class EmptyDiscretizeFunctionError(ValueError):
"""Raise in place of empty discretize function when loading dataset."""
def __init__(self):
message = self.message()
super(EmptyDiscretizeFunctionError, self).__init__(message)
@staticmethod
def message():
return "Please ... |
"""
spam
~~~~
Toy functions for testing.
"""
def spam_eggs():
pass
def spam_bacon():
pass
def spam_baked_beans():
pass
|
'''Refaça o desafio 035 dos triângulos, acrescentando o recurso de mostrar que tipo de triângulo será formado:
-Equilátero: Todos os lados iguais
-Isósceles: Dois lados iguais
-Escaleno: Todos os lados diferentes'''
l1 = float(input('Digite o valor do primeiro lado: '))
l2 = float(input('Digite o valor do segundo lado... |
'''
Machine Learning
* Machine Learning is making the computer learn from studying data and statistics.
* Machine Learning is a step into the direction of artificial intelligence (AI).
* Machine Learning is a program that analyses data and learns to predict the outcome.
Where To Start?
* In this tutorial we will go... |
class Subscriber:
"""
Class that defines a subscriber to a specific event
"""
def __init__(self, callback_method, program, event_type, object_id):
self._callback_method = callback_method
self._program = program
self._event_type = event_type
self._object_id = object_id
... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"expand_dim_to_3": "00_core.ipynb",
"parametric_ellipse": "00_core.ipynb",
"elliplise": "00_core.ipynb",
"EllipticalSeparabilityFilter": "00_core.ipynb"}
modules = ["core.py"]
doc... |
LOG = []
def flush_log(filename):
with open(filename, 'w') as logfile:
for l in LOG:
logfile.write("%s\n" % l)
def log_message(msg):
LOG.append(msg) |
# print('hello world')
# name = input('please input your name:')
# print(name)
a1 = 0.1
a2 = 0.2
print(a1 + a2)
a3 = 1.23e10
print(a3)
a4 = "I'm xiaogang"
print(a4)
a5 = 'I\' xiaogang'
print(a5)
print('\\\\t\\')
print(r'\\\t\\')
# 换行
print('line1\nlin22')
print('''
line1
line2
'''
)
# 布尔值
#
print... |
is_correct = executor_result["is_correct"]
test_feedback = executor_result["test_feedback"]
test_comments = executor_result["test_comments"]
congrats = executor_result["congrats"]
feedback = ""
output = (test_comments + "\n" + test_feedback).strip()
if output == "":
output = "No issues!"
if is_correct:
feedb... |
"""
Given an array of integers nums and an integer threshold, we will choose
a positive integer divisor and divide all the array by it and sum the
result of the division. Find the smallest divisor such that the result
mentioned above is less than or equal to threshold.
Each result of division is... |
"""
Manages the character's self regeneration.
--
Author : DrLarck
Last update : 18/07/19
"""
# charcter regen
class Character_regen:
"""
Manages the character's self regeneration.
- Attribute :
`health` : Represents the health regen per turn.
`ki` : Represents the ki regen per turn.
"""
... |
## \file OutputFormat.py
# \author Dong Chen
# \brief Provides the function for writing outputs
## \brief Writes the output values to output.txt
# \param theta dependent variables (rad)
def write_output(theta):
outputfile = open("output.txt", "w")
print("theta = ", end="", file=outputfile)
print(theta, file... |
# LevPy: A Python JSON level-loader
# for easier level abstraction
# in text-based py games
# Copyright (c) Finn Lancaster 2021
# Please Keep in mind that the JSONvar name must
# also be the same as the function that
# contains more data on it in LevPy.py
# Valid JSON, names can be anything, with data after the
# ... |
class Solution:
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
func = lambda x : sum(int(ch) ** 2 for ch in str(x))
seen = set()
while True:
if n == 1:
return True
if n in seen:
return False
... |
# STACKS, QUEUES & HEAPS
# Stacks
'''
A stack is a last in first out (LIFO) data structure.
- Push an item onto the stack
- Pop an item out of the stack
All push and pop operations are to/from the top of the stack.
The only way to access the bottom items in the stack is to
first remove all items above it
Peek - g... |
SETTINGS = {
'app': {
'schema': 'http://',
'host': 'localhost',
'port': 9000
}
}
|
__name__ = "python-crud"
__version__ = "0.1.3"
__author__ = "Derek Merck"
__author_email__ = "derek.merck@ufl.edu"
__desc__ = "CRUD endpoint API with Python",
__url__ = "https://github.com/derekmerck/pycrud",
|
# -*- coding: utf-8 -*-
"""
SQLpie License (MIT License)
Copyright (c) 2011-2016 André Lessa, http://sqlpie.com
See LICENSE file.
"""
class CustomException(Exception):
RECORD_NOT_FOUND = "Record Not Found."
INVALID_ARGUMENTS = "Bad Request. Invalid Arguments."
CACHE_IS_EMPTY = "Cache Is Empty."
CACHE... |
"""
.. module:: build_features.py
:synopsis:
"""
|
#!/usr/bin/env python
__author__ = "Kishori M Konwar"
__copyright__ = "Copyright 2013, MetaPathways"
__credits__ = ["r"]
__version__ = "1.0"
__maintainer__ = "Kishori M Konwar"
__status__ = "Release"
exit_code=0
|
edges = {
(1,'q'):1
}
accepting = [1]
def fsmsim(string, current, edges, accepting):
if string == "":
return current in accepting
else:
letter = string[0]
if (current, letter) in edges:
destination = edges[(current, letter)]
remaining_string = string[1:]
... |
class Solution(object):
def flipAndInvertImage(self, A):
for row in A:
for i in xrange((len(row) + 1) / 2):
# ~ operator (not operator) x*-1-1 <- gets the element on the oposite side
row[i], row[~i] = ~row[~i] ^ 1, row[i] ^ 1
return A
|
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = str(first + '.' + last + '@company.com').lower() # see that we don't need to input all the
# attributes. Some of th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.