content stringlengths 7 1.05M |
|---|
"""
https://leetcode.com/problems/degree-of-an-array/
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
... |
# Multiple servers "should" work but actually totally don't.
# port, username, password, and channels are optional
# username will use defaults if not defined here
servers = [
dict(
network='FreeNode',
server='chat.freenode.net',
#port=6665,
#password='SuperSecretPassword',
#... |
def wifi_deal_ap_info(info):
res = []
for ap_str in info:
ap_str = ap_str.split(",")
info_one = []
for node in ap_str:
if node.startswith('"'):
info_one.append(node[1:-1])
else:
info_one.append(int(node))
res.append(info_on... |
"""
GameBoy Emulator Written in Python
MIT License
Copyright (c) 2017 Ryan Sheffer
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... |
"""
This is a module in a separate package
"""
def hello_stranger():
"""
hello
"""
print("pylint does not like empty modules")
|
"""
Classifiers predict the class of an example.
Most of the Classifier classes are wrappers for external, publicly available
classifier implementations. They are used to predict the classes of examples
generated by ExampleBuilders. The correctness of these predictions can then
be measured with Evaluators.
""" |
class Winratio:
def __init__(self, **kwargs):
self.losses = kwargs.get("Losses", kwargs.get("losses", 0)) or 0
self.wins = kwargs.get("Wins", kwargs.get("wins", 0)) or 0
@property
def winratio(self):
_w = self.wins /(self.matches_played if self.matches_played > 1 else 1) * 100.0
return int(_w) if _w % 2 == 0... |
# Balanced binary search tree (AVL tree) implementation
class Node:
def __init__(self, key, value=None, parent=None, left=None, right=None):
self.key, self.value, self.parent = key, value, parent
self.child = [left, right]
self.balance, self.height = 0, 1
def __str__(self) -> str:
... |
def input_to_int(value):
"""
Checks that user (string) input is an integer.
Parameters
----------
value : user input to check
Returns
-------
integer : n cast to an integer
Raises
------
ValueError : if n is not an integer
"""
if str(value).isdigit():
retur... |
c = int(input("\033[1;31mInforme a temperatura em °C\033[m: "))
#Conversor de Temperatura de °C para °F
f = ((9 * c) / 5) + 32
print("A temperatura de \033[1;34m{}°C\033[m, correspende a \033[1;33m{}°F.\033[m".format(c,f))
|
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
stops = []
for n, s, e in trips:
stops.append((s, n, 's'))
stops.append((e, n, 'e'))
stops.sort()
p = 0
for i in range(len(stops)):
stop, n, c = stops[i]
... |
class C1:
def meth1(self): self.__X = 88 # Теперь X - мой атрибут
def meth2(self): print(self.__X) # Превратится в _C1__X
class C2:
def metha(self): self.__X = 99 # И мой тоже
def methb(self): print(self.__X) # Превратится в _C2__X
class C3(C1, C2): pass
I = C3() # В I два имени X
I.meth1(); I.metha(... |
n11 = input("Digite algo! ")
print('o tipo primitivo desse valor é ', type(n11))
print('\033[4;31m{}\033[m, É um número?'.format(n11), n11.isnumeric())
print('\033[1;31m{}\033[m, \033[1;31mÉ alfabetico?\033[1;31m, {}{}{}'.format(n11,'\033[4;31m',n11.isalpha(),'\033[m'))
print(n11, "\033[4;34mÉ alfanumérico?\033[m", n1... |
data = (
'Ruo ', # 0x00
'Bei ', # 0x01
'E ', # 0x02
'Yu ', # 0x03
'Juan ', # 0x04
'Yu ', # 0x05
'Yun ', # 0x06
'Hou ', # 0x07
'Kui ', # 0x08
'Xiang ', # 0x09
'Xiang ', # 0x0a
'Sou ', # 0x0b
'Tang ', # 0x0c
'Ming ', # 0x0d
'Xi ', # 0x0e
'Ru ', # 0x0f
'Chu ', # 0x10
'Zi ... |
class NotIndicPythonFileException(Exception):
"""
Raised when a file is not in Indic Python format.
"""
def __init__(self, file_path) -> None:
super().__init__(f"File {file_path} is not a indic python file.")
self.file_path = file_path
class UnknownLanguageException(Exception):
"""
Raised when a IndicPy file... |
"""
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contains-duplicate
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
... |
data = {
"color": {
"black": "30",
"red": "31",
"green": "32",
"yellow": "33",
"blue": "34",
"magenta": "35",
"cyan": "36",
"white": "37"
},
"bgcolor": {
"black": "40",
"red": "41",
"green": "42",
... |
load("//:compile.bzl", "proto_compile")
def gateway_swagger_compile(**kwargs):
proto_compile(
plugins = [
str(Label("//github.com/grpc-ecosystem/grpc-gateway:swagger")),
],
**kwargs
)
|
__all__ = [
'q1_exceptions',
'q2_incorrect_regex'
]
|
output_colors = {
"white":(255, 255, 255)
}
chat_prefix = "[c/00cc00:<python>] "
console_chat_prefix = "<python> "
default_color = (150, 150, 255)
def puts(*args):
SendMessage(", ".join([str(arg) for arg in args]), default_color[0], default_color[1], default_color[2])
def putsc(color, *args):
SendMessage(", ".join... |
""" Includes a unified framework for representation and learning of coreference
resolution approaches."""
__author__ = 'martscsn'
|
# Celery
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERYD_MAX_TASKS_PER_CHILD = 100
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
|
# filename Specifies that a FileHandler be created, using the specified
# filename, rather than a StreamHandler.
# filemode Specifies the mode to open the file, if filename is specified
# (if filemode is unspecified, it defaults to 'a').
# format Use the specified format string for the handler... |
# BinGrep, version 1.0.0
# Copyright 2017 Hiroki Hada
# coding:UTF-8
class Node(object):
def __init__(self, label):
(self.label, self.children) = (label, list())
@staticmethod
def get_children(node): return node.children
@staticmethod
def get_label(node): return node.label
... |
def bytes_to_int(bytes_string):
'''
pack of the int.from_bytes
'''
return int.from_bytes(bytes_string, byteorder="big") |
'''
Task 7.
Реализовать проект «Операции с комплексными числами».
Создайте класс «Комплексное число», реализуйте перегрузку методов сложения и умножения комплексных чисел.
Проверьте работу проекта, создав экземпляры класса (комплексные числа)
и выполнив сложение и умножение созданных экземпляров.
Проверьте корректност... |
"""
The :mod:`fatf.fairness.models` module holds fairness algorithms for models.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
|
num = int(input('Digite um número para ver sua tabuada: '))
print('\033[1;97m-'*20)
print(f'{num} x {1:>2} = {num * 1}')
print(f'{num} x {2:>2} = {num * 2}')
print(f'{num} x {3:>2} = {num * 3}')
print(f'{num} x {4:>2} = {num * 4}')
print(f'{num} x {5:>2} = {num * 5}')
print(f'{num} x {6:>2} = {num * 6}')
print(f'{num} ... |
# -*- coding: utf-8 -*-
###################################################################################
# Copyright (C) 2019 SuXueFeng GNU
###################################################################################
{
'name': "Authing",
'summary': """集成Authing登录""",
'description': """ 集成Authi... |
number_to_factorial = int(input("Enter a number:"))
factorial = 1
if number_to_factorial < 0:
print("The factorial isn't exist")
elif number_to_factorial == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,number_to_factorial + 1):
factorial = factorial*i
print ("The factorial... |
class Solution(object):
def adder(self, a, b):
cin, sum_out = 0, 0
for i in range(32):
a_bit = (a & (1 << i)) >> i
b_bit = (b & (1 << i)) >> i
s = b_bit ^ a_bit ^ cin
sum_out |= (s << i)
cin = ((a_bit | b_bit | cin) & ~s) | (cin & a_bit & b... |
class InertiaExpansionBehavior(object):
"""
Controls the deceleration of a resizing manipulation during inertia.
InertiaExpansionBehavior()
"""
DesiredDeceleration=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the rate that resizing slows in device-independent un... |
# Is This a Binary Search Tree?
# Developer: Murillo Grubler
# https://www.hackerrank.com/challenges/is-binary-search-tree/problem
# Time complexity: O(n)
# Rules:
# The inOrder function must return an ordered list
# No duplication
def in_order(root, arr):
if root.left is not None:
in_order(root.left, arr... |
# Autor: Abdel G. Martinez L.
#
# Instrucciones: Simular un directorio telefonico
def imprimirNumero(numeros):
print("Numeros Telefonicos:")
for k, v in numeros.items():
print("Nombre:", k, "\tNumero:", v)
print()
def agregarNumero(numeros, nombre, numero):
numeros[nombre] = numero
def buscar... |
# Testing basic features
expected_results = {
"test_target": {
"desc": "test basic features",
"expected_features": ["IPV4"]
}
}
|
with open('advent_of_code/03_toboggan_trajectory/input.txt', 'r') as f:
lines = [l[:-1] for l in f.readlines()]
length = len(lines)
indices = [i*3 for i in range(length)]
modulo = len(lines[0])
moduled_indices = [i % modulo for i in indices]
counts = [1 if lines[x][y] == '#' else 0 for x, y in zip(range(length), ... |
# Desafio 064 -> Faça um programa que leia vários números int pelo teclado.
# o programa só vai parar quando o usuário digitar 999
# No final, mostre quantos números foram digitados e qual foi a soma entre eles
# (desconsiderando o flag)
vzs = 0
entrada = 0
total = 0
# ou vz... |
# @Sk70249 TwoSum solution in Python
'''
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
'''
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
a = ... |
####################################################### some combinatoric first
def genPerm(n):
if n==0: return [[]]
res=[]
prev=genPerm(n-1)
for p in prev:
for i in range(n-1):
k=p[i]
tmp=p+[k]
tmp[i]=n
res.append(tmp)
res.appen... |
#!/usr/bin/env python
# coding: utf8
""" Browser error pages package. """
__author__ = 'fv'
__version__ = '1.0.0'
|
class LinkedNode(object):
def __init__(self, val):
self.val = val
self.next = None
class BinaryNode(object):
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
class DoublyLinkedNode(object):
def __init__(self, val, prev=None, next... |
# An example util module that we want to test.
# `reverse` takes a list and returns a new list with the same
# elements, but with their order reversed.
def reverse(l):
return [element for element in reversed(l)]
|
n=int(input('How many numbers: '))
k=[]
for i in range(n):
x=int(input('Enter number '))
k.append(x)
print('Maximum element in the list is :',max(k),'')
print('Minimum element in the list is :',min(k))
sum=0
for i in k:
sum+=i
print('Average = ',sum/len(k))
|
nome = str(input('Qual é o seu nome? '))
if nome == 'Breno' or nome == 'Cézar' or nome == 'Renan' or nome == 'Roberto':
print('Que nome de homen bonito')
elif nome == 'Ellen' or nome == 'Elis' or nome == 'Josefa' or nome == 'Daniele':
print('Que nome de mulher bonito')
else:
print('Que nome comum')
print('T... |
class Token:
def __init__(self, value = None, type = None) -> None:
self.type = type
self.value = value
def __repr__(self) -> str:
if self.type: return f'{self.type} : {self.value}'
return f'{self.value}'
|
#!/usr/bin/env python
"""
This module contains various exceptions raised by agate.
"""
class NullCalculationError(Exception): # pragma: no cover
"""
Exception raised if a calculation which can not logically
account for null values is attempted on a :class:`Column` containing
nulls.
"""
pass
... |
#***Max-Out Memory**
giant_string = ''
while True:
with open('long_file.txt', 'r') as f:
for line in f:
giant_string += line
|
USERNAME_MAX_LENGTH = 30
EMAIL_TO_USERNAME_HASH_LENGTH = USERNAME_MAX_LENGTH
EMAIL_ACTIVATION_KEY_EXPIRATION_HOURS = 48
EMAIL_ACTIVATION_KEY_REUSE_THRESHOLD_HOURS = EMAIL_ACTIVATION_KEY_EXPIRATION_HOURS - 1
SOCIAL_AUTH_PROVIDER_FACEBOOK = 'facebook'
SOCIAL_AUTH_PROVIDER_LINKEDIN = 'linkedin'
SOCIAL_AUTH_PROVIDER_TWIT... |
#
# ktool | kmacho
# structs.py
#
# Custom Struct implementation reflecting behavior of named tuples while also handling behind-the-scenes packing/unpacking.
#
# This file is part of ktool. ktool is free software that
# is made available under the MIT license. Consult the
# file "LICENSE" that is distribu... |
# -*- coding: UTF-8 -*-
#
"""
Internet related stuff, URL's, domains, email
"""
__version__ = '4.0'
# ------------------------------------------------------
# internet
#
content = {
'i_tld' : ['.com','.net','.org'],
'i_tld_misc' : ['.edu','.gov','.mil','.arpa','.nato'],
'i_tl... |
while True:
n = int(input('Quer ver a tabuada de qual numero? '))
if n <= 0:
break
for c in range(1, 11):
print(f'\033[1;31m{n}\033[m x \033[1;32m{c}\033[m = \033[1;33m{n*c}\033[m')
print('Fim do progama, obrigado por utilizar!')
|
def Dragon_and_cow(thoughts, eyes, eye, tongue):
return f"""
{thoughts} ^ /^
{thoughts} / \\ // \\
{thoughts} |\\___/| / \\// .\\
{thoughts}"""+""" /O O \\__ / // ... |
n1 = input("Digite o nome de uma placa de vídeo: ")
n2 = input("Digite o nome de mais uma placa de vídeo: ")
n3 = input("Digite o nome de outra placa de vídeo: ")
lista = [n1, n2, n3]
print(lista)
if "RTX 3080" in lista:
print("A RTX 3080 está na posição {} na lista".format(lista.index("RTX 3080")))
else:
print... |
#!/usr/bin/env python
#conding:utf-8
print('Hello world')
|
"""This problem was asked by Netflix.
Given a sorted list of integers of length N, determine if an element x is in the
list without performing any multiplication, division, or bit-shift operations.
Do this in O(log N) time
"""
|
__author__ = 'Dani'
class Deal(object):
#Negotiation status
INTENDED = "Intended"
CONCLUDED = "Concluded"
FAILED = "Failed"
#Sectors
AGRICULTURE = "Agriculture"
CONSERVATION = "Conservation"
FORESTRY = "Forestry"
INDUSTRY = "Industry"
RENEWABLE_ENERGY = "RenewableEnergy"
... |
list_number = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615,
953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950,
626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81,
379, 843, 831, 445, 742, 717, 958, 743, 527]
for ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 19 00:31:06 2021
@author: Benjamin
"""
class Abis(object):
def __init__(self):
self.test = 'sksisj'
print("Instantiate class A")
def printA(self):
print("AAAAAAAAAAAAAA") |
class UserModel(Tower):
@model_property
def inference(self):
assert self.input_shape[0]==224, 'Input shape should be 224 pixels'
assert self.input_shape[1]==224, 'Input shape should be 224 pixels'
# Create some wrappers for simplicity
def conv2d(x, W, b, s, padding='SAME'):
... |
job_freqs = {
"clk": 286,
"lab": 269,
"stenog": 68,
"salesman": 66,
"machinist": 58,
"carp": 57,
"teamster": 57,
"mngr": 43,
"bkpr": 34,
"engineer": 32,
"driver": 32,
"painter": 31,
"grocer": 31,
"pres": 30,
"foreman": 29,
"teacher": 27,
"sec": 26,
... |
result = []
for x in range(1, 201):
if x % 5 == 0 and x % 7 == 0:
result.append(x)
print(result)
|
"""solved, easy"""
class Solution:
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
mid = len(A) // 2
A.sort(key=lambda x: x % 2)
return [item for sub in zip(A[:mid], A[mid:]) for item in sub]
if __name__ == "__main__":
ass... |
# class Solution:
# def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
# # build lookup table
# tb1 = {v:i for i,v in enumerate(list1)}
# tb2 = {v:i for i,v in enumerate(list2)}
# # traverse list1
# leastSum = len(list1) + len(list2) - 2
# ... |
"""
Calm-DSL constants
"""
class CACHE:
"""Cache constants"""
class ENTITY:
AHV_SUBNET = "ahv_subnet"
AHV_DISK_IMAGE = "ahv_disk_image"
ACCOUNT = "account"
PROJECT = "project"
USER = "user"
ROLE = "role"
DIRECTORY_SERVICE = "directory_service"
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 23 10:38:08 2022
@author: danie
"""
common = '''{
return (
<div>
<header>navbar</header>
<main>page content</main>
<footer>footer</footer>
</div>
);
};
'''
def get_template(file_name):
template = f'export interface {file_name}Props'
template += '... |
'''
This example shows how to colorize atoms
based on their position (x, y, or z)
see: https://documentation.samson-connect.net/scripting-guide/colorization/
Open any molecule in SAMSON
'''
class HaltException(Exception): pass
indexer = SAMSON.getNodes('n.t atom') # get all atom nodes
if indexer.... |
# Angelas solution
print("Welcome to the tip calculator!")
total = float(input("What was the total bill? $"))
tip = int(input("How much tip would you like to give? 10, 12, or 15? "))
people = int(input("How many people to split the bill? "))
tip_calculation = tip / 100 * total + total
split_total = tip_calculation / ... |
__all__ = ["ActorDeadError", "Timeout"]
class ActorDeadError(Exception):
"""Exception raised when trying to use a dead or unavailable actor."""
pass
class Timeout(Exception):
"""Exception raised at future timeout."""
pass
|
# -*- coding: utf-8 -*-
"""
File Name: findNthDigit
Author : jing
Date: 2020/4/13
https://leetcode-cn.com/problems/nth-digit/
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
"""
class Solution:
def findNthDigit(self, ... |
class BranchAgent(object):
"""Branch Agent class for LTD"""
def __init__(self, mirror, area, newBranch):
# mirror Reference
self.mirror = mirror
self.Area = area
self.Ck = str(newBranch.Ck) # string
self.Id = self.Ck # used in __repr__
self.ScanBus = int(newBranc... |
print('Calculo do aumento do salario de funcionario em 15%')
n=int(input('Qual o salario atual do funcionario?'))
p=n*0.15
a=n+p
print('O salario do funcionario com aumento é {:.2f}!'.format(a))
|
# -*- coding: utf-8 -*-
'''
File name: code\gathering_the_beans\sol_335.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #335 :: Gathering the beans
#
# For more information see:
# https://projecteuler.net/problem=335
# Problem Statement ... |
"""
Replacement for the scikit-learn single channel pipeline.
"""
__all__ = ['Pipeline']
class Pipeline(Clonable, Saveable):
pass
|
# file: vecops.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Copyright © 2013-2020 R.F. Smith <rsmith@xs4all.nl>. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause
# Created: 2013-06-10 22:41:00 +0200
# Last modified: 2020-10-04T17:41:39+0200
"""Operations on two or three dimensional vectors."""
def... |
# -*- coding: utf-8 -*-
""" Incident Reporting System - Controllers
@author: Sahana Taiwan Team
"""
module = request.controller
if module not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Function... |
def company_list():
company = dict()
command = input()
while command != 'End':
current = command.split(' -> ')
company_name = current[0]
employee_id = current[1]
if company_name not in company:
company[company_name] = []
if employee_id not in company... |
__description__ = "Librato Silverline process monitoring and management"
__config__ = {
"librato.api_token": dict(
description = "API token for account",
default = "0",
),
"librato.server_id_cmd": dict(
description = "Command to run to generate server ID",
default = None,
... |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... |
def gcd(x: int, y: int) -> int:
while y:
x, y = y, x % y
return x
def solve(n: int) -> None:
"""Solve project euler problem 91 with x, y <= n."""
count_triangles = 3 * n * n
for x in range(1, n+1):
for y in range(1, x+1):
xy_gcd = gcd(x, y)
move_x, move_y = x... |
def format_time(time):
""" Formats the given time into HH:MM:SS. """
hours, remainder = divmod(time / 1000, 3600)
minutes, seconds = divmod(remainder, 60)
return '%02d:%02d:%02d' % (hours, minutes, seconds)
|
"""
Problem 44
Pentagonal numbers are generated by the formula, Pn = n*(3n−1)/2. The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and ... |
class Node:
def __init__(self, id, raw_id=None):
self.id = id
self.raw_id = raw_id
self.children = []
self.parent = None
def get_level(self):
return self.id.split('_')[0]
def add_child(self, node):
self.children.append(node)
def is_raw(self):
re... |
# -*- coding: utf-8 -*-
"""
error code define
:create: 2018/9/23
:copyright: smileboywtu
"""
ERRORS = {
"success": {
"code": 0,
"message": "api request ok"
},
"params_err": {
"code": 1001,
"message": "client params error"
},
"internal_err": {
"code": 1... |
MAPPER = {
'head': [
'okulista',
'neurolog',
'chirurg'
],
'limb': [
'chirurg',
'dermatolog',
'fizjoterapeuta'
],
'chest': [
'pulmonolog',
'kardiolog',
],
'back': [
'fizjoterapeuta',
],
'eye': [
'okulista'... |
FieldSize = 3
field = [['*' for i in range(FieldSize + 1)] for k in range(FieldSize + 1)]
command = input()
while command != 'Stop':
x, y = [int(i) for i in input().split()]
if x > len(field) - 1 or y > len(field) - 1:
print('Такой координаты не существует!')
else:
if fi... |
class Rational:
def __init__(self, c, z=1):
self.c = c
self.z = z
print('Создана новая дробь:', self)
self.sokr()
def __repr__(self):
self.sokr()
return '%s/%s = %s' % (str(self.c), str(self.z), str(self.to_float()))
def to_float(self):
return self.... |
#Gestor de Visitas
#Programa Principal
pacientes = {}
listatempnome = list()
listatempidade = list()
while True:
listatempnome.append(input('Nome: '))
listatempidade.append(input('Idade: '))
pacientes['nome'] = listatempnome[:]
pacientes['idade'] = listatempidade[:]
listatempidade.clear
l... |
class Solution(object):
def __init__(self):
self.root = dict()
def findWords(self, board, words):
"""
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
matches = list()
if len(words) == 0:
return matches
... |
def secant(a, b, E, n):
k = 0
while k < n:
t_x = ((a * f(b)) - (b * f(a))) \
/ (f(b) - f(a))
if abs(b-a) < E or abs(f(b)) < E:
print ("Raiz = {}".format(t_x))
break
a = b
b = t_x
k += 1
f = lambda x: x**3 - 3*x -1
Er... |
# -*- coding: utf-8 -*-
def heating_requirement_table_9c (
temperature_reduction_when_heating_is_off_1_weekday_living_room,
temperature_reduction_when_heating_is_off_2_weekday_living_room,
temperature_reduction_when_heating_is_off_1_weekend_living_room,
temperature_reduction_when_heati... |
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
print(number)
print()
for number in numbers:
print(number**2)
|
#
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
#
# SPDX-License-Identifier: Apache-2.0
#
SOC_IRAM_LOW = 0x40020000
SOC_IRAM_HIGH = 0x40070000
SOC_DRAM_LOW = 0x3ffb0000
SOC_DRAM_HIGH = 0x40000000
SOC_RTC_DRAM_LOW = 0x3ff9e000
SOC_RTC_DRAM_HIGH = 0x3ffa0000
SOC_RTC_DATA_LOW = 0x50000000
SOC_RTC_DAT... |
def omp_sections_private():
sum = 7
sum0 = 0
if 'omp parallel':
if 'omp sections private(sum0)':
if 'omp section':
sum0 = 0
for i in range(0, 400):
sum0 += i
if 'omp critical':
sum += sum0
... |
ELIGIBILITY_TRANSACTION_CODE = '270'
SUPPORTED_TRANSACTION_CODES = [ELIGIBILITY_TRANSACTION_CODE]
class UnsupportedTransactionException(Exception):
"""
Indicates that a X12 Transaction Type is not currently supported
"""
pass
class InvalidControlSegment(Exception):
"""
Raised when a X12 mess... |
class Section:
def __init__(self, name):
self.name = name
self.tasks = []
def add_task(self, new_task):
if new_task in self.tasks:
return f"Task is already in the section {self.name}"
self.tasks.append(new_task)
return f"Task {new_task.details()} is added to... |
class Tokenizer:
def __init__(self, exp):
self.tokens = self._parse_exp(exp);
self.index = 0;
def _parse_exp(self,exp):
list = [];
for el in exp:
if el.isspace():
continue;
list.append(el);
return list;
def get_next_token(sel... |
heights = [45, 34, 37, 30, 44, 50]
for height in heights:
if height < 31:
print(f'{height} is too short to ride')
|
{
'variables': {
'chromium_code': 1,
'chrome_grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/chrome',
'app_grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/app',
'webkit_grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/webkit',
# TODO(sgk): eliminate this; see comment in build/common.gypi
'msvs_debug_link_inc... |
#!/usr/bin/env python
#coding=utf-8
class EmptyError(Exception):
pass
|
'''
Fibonacci series: 1 1 2 3 5 8 13 ...
Write a function to spit out the nth Fibonacci number
input:
5
output:
5
'''
def fib(limit):
a, b = 0, 1
for i in range(limit):
a, b = b, a+b
return a
print(fib(10))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.