content stringlengths 7 1.05M |
|---|
def m2f_e(s, st):
return [[st.index(ch), st.insert(0, st.pop(st.index(ch)))][0] for ch in s]
def m2f_d(sq, st):
return ''.join([st[i], st.insert(0, st.pop(i))][0] for i in sq)
ST = list('abcdefghijklmnopqrstuvwxyz')
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = m2f_e(s, ST[::])
print('%14r... |
'''
堆是特殊空间的有顺序的完全二叉树,root是最大值的是大顶堆,其他未小顶堆
堆:数据流中的第K大(小)问题
'''
|
def get_pyenv_root():
return "/usr/local/pyenv"
def get_user():
return "root"
def get_group():
return "root"
def get_rc_file():
return "/etc/profile.d/pyenv.sh"
def get_python_test_case():
return "3.9.0", True
def get_venv_test_case():
return "neovim", True
|
# https://www.hackerrank.com/challenges/30-testing/forum/comments/138775
print("5")
print("5 3\n-1 90 999 100 0")
print("4 2\n0 -1 2 1")
print("3 3\n-1 0 1")
print("6 1\n-1 0 1 -1 2 3")
print("7 3\n-1 0 1 2 3 4 5")
|
def inorde_tree_walk(self, vertice = None):
if(self.raiz == None): #arvore vazia
return
if(verice == None): #Por padrao comeca pela raiz
vertice = self.raiz
if(vertice.left != None): #Decomposicao
self.inorde_tree_walk(vertice = vertice.left)
print(vertice)
if(ver... |
#
# PySNMP MIB module HM2-DHCPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DHCPS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:31:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(root, value):
"""
For a binary search tree
"""
if root is None:
return Node(value)
node = root
parent = None
new = Node(value)
while True:
parent = node
if value < parent.d... |
table_pkeys_map = {
"account": [
"account_id"
],
"account_assignd_cert": [
"account_id",
"x509_cert_id",
"x509_key_usg"
],
"account_auth_log": [
"account_id",
"account_auth_ts",
"auth_resource",
"account_auth_seq"
],
"account_co... |
""" Largest element in the array. """
class Solution:
""" Naive Solution.
Time complexity: O(n^2)
"""
def largestElementInArray(self, arr):
i = 0
while i <len(arr):
j =i+1
while j< len(arr):
if arr[i] > arr[j]:
arr[i], arr[... |
# LANGUAGE: Python
# AUTHOR: randy
# GITHUB: https://github.com/randy1369
print('Hello, python!') |
convidados = []
for _ in range(int(input())):
convidados.append(input())
if 'André' in convidados:
print('Cuidado!')
else:
print('Seguro!')
|
def test_opendota_api_type(heroes):
# Ensure data returned by fetch_hero_stats() is a list
assert isinstance(heroes, list)
def test_opendota_api_count(heroes, N_HEROES):
# Ensure all heroes are included
assert len(heroes) == N_HEROES
def test_opendota_api_contents(heroes, N_HEROES):
# Verify tha... |
class ParserException(Exception):
"""
Base exception for the email parser.
"""
pass
class ParseEmailException(ParserException):
"""
Raised when the parser can't create a email.message.Message object of the raw string or bytes.
"""
pass
class MessageIDNotExistException(ParserExcepti... |
# -*- coding:utf-8 -*-
"""
@author:SiriYang
@file: AppModel.py
@time: 2019.12.23 00:25
"""
class App (object):
#记录id
mId=None
#应用id
mAppId=None
#应用链接
mURL=None
#图标链接
mImgURL=None
#应用名称
mName=None
#应用类型
mApplicationCategory=None
#应用作者
mAuthor=None
#用户备注
mNote=None
#愿望单top
mStar=None
... |
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
# Runtime: 12 ms
# Memory: 13.5 MB
pascal = []
for r in range(1, numRows + 1):
row = []
for c in range(r):
i... |
"""
백준 17626번 : Four Squares
Dynamic Programming + pypy3
메모이제이션
"""
n = int(input())
dp = [0, 1]
for i in range(2, n + 1):
dp.append(dp[i - 1])
j = 1
while j ** 2 <= i:
dp[i] = min(dp[i], dp[i - j ** 2])
j += 1
dp[i] += 1
print(dp[n]) |
data=input();
A = (data[0:2]); # dia
B = (data[3:5]); # mês
C = (data[6:8]); # ano
print(B,A,C,sep="/"); # MM/DD/AA
print(C,B,A,sep="/"); # AA/MM/DD
print(A,B,C,sep="-"); # DD-MM-AA |
filename = 'programming.txt'
with open(filename, 'w') as file_obj:
file_obj.write("I love programming.\n")
file_obj.write("I love creating new games.\n")
# 附加到文件
with open(filename, 'a') as file_obj:
file_obj.write("I also love finding meaning in large datasets.\n") |
class Solution:
def lastRemaining(self, n):
"""
:type n: int
:rtype: int
"""
def helper(n,i):
if n == 1:
return 1
if i:
return 2 * helper(n//2,0)
elif n % 2 == 1:
return 2 * helper(n//2,1)
... |
'''
From: LeetCode - 141. Linked List Cycle
Level: Easy
Source: https://leetcode.com/problems/linked-list-cycle/description/
Status: AC
Solution: Using Hash Table
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next ... |
"""
Journals module of Spire library and API version.
"""
SPIRE_JOURNALS_VERSION = "0.1.1"
|
class Structure(object):
_fields = ()
def __init__(self, *args):
if len(_fields) != len(args):
raise TypeError(f"Expected {len(_fields)} arguments.")
for name, value in zip(self._fields, args):
setattr(self, name, value)
if __name__ == '__main__':
class Shares(... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
ID = 'ID'
TOKEN = 'TOKEN'
SUB_DOMAIN = 'xsy'
DOMAIN = 'admxj.pw'
|
'''
this program translates any integer base to decimal.
examples for testing:
assert checkio("101", 2) == 5, "Binary"
assert checkio("111112", 3) == 365, "Ternary"
assert checkio("200", 4) == 32, "Quaternary"
assert checkio("101", 5) == 26, "5 base"
assert checkio("25", 6) == 17, "Heximal/Senary" ... |
classes = [
{
'name': 'science-1',
'subjects': [
{
'name': 'Math',
'taughtBy': 'Turing',
'duration': 60
},
{
'name': 'English',
'taughtBy': 'Adele',
'duration': 60
... |
"""
snek.tests Package: Unit & integration tests for Snek.
"""
#-------------------------------------------------------------------------------
# Constants
#-------------------------------------------------------------------------------
MOCKS_FOLDER = './tests/mocks'
|
cont = 0
lista = []
while cont < 20:
x = input()
lista.append(x)
cont += 1
cont2 = 0
valor = -1
while cont2 < 20:
print("N[" + str(cont2) + "] = " + str(lista[valor]))
valor -= 1
cont2 += 1 |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x, y, dx, dy = 0, 0, 0, 1
for it in instructions:
if it == 'L':
dx, dy = -dy, dx
elif it == 'R':
dx, dy = dy, -dx
else:
x = x + dx
... |
### TODO use the details of your database connection
REGION = 'eu-west-2'
DBPORT = 1433
DBUSERNAME = 'admin' # the name of the database user you created in step 2
DBNAME = 'EventDatabase' # the name of the database your database user is granted access to
DBENDPOINT = 'eventdatabase.cu9s0xzhp0zw.eu-west-2.rds.amazonaws... |
MAILBOX_MOVIE_CLEAR = 2
MAILBOX_MOVIE_EMPTY = 3
MAILBOX_MOVIE_WAITING = 4
MAILBOX_MOVIE_READY = 5
MAILBOX_MOVIE_NOT_OWNER = 6
MAILBOX_MOVIE_EXIT = 7
|
def parse(data):
return [
[int(x) if x.replace("-", "").isdigit() else x for x in l.split()]
for l in data.split("\n")
]
def calc(data):
# ¯\_(ツ)_/¯ Just use the values that mater, automating decompile was too hard
stack = []
for i in range(len(data) // 18):
if data[i * 18 ... |
# Copyright (c) 2013 by pytest_pyramid authors and contributors
#
# This module is part of pytest_pyramid and is released under
# the MIT License (MIT): http://opensource.org/licenses/MIT
"""pytest_pyramid main module."""
__version__ = "1.0.1" # pragma: no cover
|
answer = int(input("How many times do you want to play? "))
for i in range(0,answer):
person1 = input("What is the first name? ")
person2 = input("What is the second name? ")
if person1 > person2:
print(person1)
print("has won")
elif person1 == person2:
print("friendship")
... |
__all__ = ['strip_comments']
def strip_comments(contents):
"""Strips the comments from coq code in contents.
The strings in contents are only preserved if there are no
comment-like tokens inside of strings. Stripping should be
successful and correct, regardless of whether or not there are
comment... |
"""This file contains macros to be called during WORKSPACE evaluation.
For historic reasons, pip_repositories() is defined in //python:pip.bzl.
"""
def py_repositories():
"""Pull in dependencies needed to use the core Python rules."""
# At the moment this is a placeholder hook, in that it does not actually
... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( X , Y , m , n ) :
LCSuff = [ [ 0 for k in range ( n + 1 ) ] for l in range ( m + 1 ) ]
result = 0
for i... |
#Simple declaration of Funtion
'''def say_hello():
print('hello')
say_hello()
'''
def greeting(name):
print(f'Hello {name}')
greeting('raj') |
def for_hyphen():
for row in range(3):
for col in range(3):
if row==1:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_hyphen():
row=0
while row<3:
col=0
while col<3:
if row==1:
... |
# 세트; 셋(set)
# 수학에서의 `집합`과 동일한 의미를 가집니다.
# 중복된 값을 가지지 않으며 순서를 갖지 않는 컨테이너 타입입니다.
# 리터럴 선언 방식
# 세트의 리터럴 선언은 `{}` 기호를 사용합니다.
# 단, 안에 값이 있어야 합니다.
# 값이 들어있지 않으면 `dict` 타입의 리터럴로 간주됩니다.
s = {0, }
# <class 'set'>
print(type(s))
# {0}
print(s)
s = {1, 2, 2, 3, 4, 5, 5}
# {1, 2, 3, 4, 5}
print(s)
# 생성자 선언 방식
s... |
class EmptyGraphHelper(object):
@staticmethod
def get_help_message():
return f"""
We are deeply sorry but unfortunately the result graph is empty.
Please try the following steps to fix the problem -
\t1. Try running again with other / no filters
\t2. Make sure to run 'ed... |
def tabuada(numero):
for i in range(1, 11):
print(f'{i} x {numero} = {i * numero}')
tabuada(int(input()))
|
#usar operador de incremento e atribuição
#count = 0
#while count != 5:
#count+=1 #é o mesmo que count = count + 1
#print(count)
#incrementar a contagem em 3
#count = 0
#while count <= 20:
#count+=3
#print(count)
#diminui a contagem em 3
count = 20
while count>=0:
count -= 3
print(count) |
class RadarSensor:
angle = None
axis = None
distance = None
property = None
|
# 838. Push Dominoes
# There are N dominoes in a line, and we place each domino vertically upright.
# In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
# After each second, each domino that is falling to the left pushes the adjacent domino on the left.
# Similarly, th... |
result = []
def PrimeFactor(n):
for i in range(2,int(n/2+1)):
if n % i == 0:
result.append(i)
return PrimeFactor(n/i)
result.append(int(n))
if __name__ == '__main__':
PrimeFactor(90)
print("90的质因数:",result)
|
#!/usr/bin/env python3
class Course:
'''Course superclass for any course'''
def __init__(self, dept, num, name='',
units=4, prereq=set(), restr=set(), coclass=None):
self.dept, self.num, self.name = dept, num, name
self.units = units
self.prereq, self.restr = prereq, restr
... |
"""Ecosystem exception."""
class QiskitEcosystemException(Exception):
"""Exceptions for qiskit ecosystem."""
|
# LIS2DW12 3-axis motion seneor micropython drive
# ver: 1.0
# License: MIT
# Author: shaoziyang (shaoziyang@micropython.org.cn)
# v1.0 2019.7
LIS2DW12_CTRL1 = const(0x20)
LIS2DW12_CTRL2 = const(0x21)
LIS2DW12_CTRL3 = const(0x22)
LIS2DW12_CTRL6 = const(0x25)
LIS2DW12_STATUS = const(0x27)
LIS2DW12_OUT_T_L = const(0x0D)... |
recomputation_vm_memory = 2048
haskell_vm_memory = 4096
recomputation_vm_cpus = 2
vagrantfile_templates_dict = {
"python": "python/python.vagrantfile",
"node_js": "nodejs/nodejs.vagrantfile",
"cpp": "cpp/cpp.vagrantfile",
"c++": "cpp/cpp.vagrantfile",
"c": "cpp/cpp.vagrantfile",
"haskell": "has... |
def pay(hours,rate) :
return hours * rate
hours = float(input('Enter Hours:'))
rate = float(input('Enter Rate:'))
print(pay(hours,rate)) |
{
"targets": [
{
"target_name": "mynanojs",
"sources": [ "./src/mynanojs.c", "./src/utility.c", "./src/mybitcoinjs.c" ],
"include_dirs":[ "./include", "./include/sodium" ],
"libraries": [
"../lib/libnanocrypto1.a", "../lib/libsodium.a"
],
}
]
}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def add(x, y):
"""Add two numbers together and return the result"""
return x + y
def subtract(x, y):
"""Subtract x from y and return result"""
return y - x
|
input00 = open("input/input00.txt", "r")
input01 = open("input/input01.txt", "r")
input00_list = input00.read().splitlines()
input01_list = input01.read().splitlines()
count_elements = int(input00_list[0])
dictionary = {}
for i in range(count_elements):
str_elements = input00_list[i+1].split()
dictionary[str... |
met = int(input('Digite o valor em metros:'))
cm = met*100
ml = met*1000
print('o valor de {}m em centimetros é: {}cm. E o mesmo em milimetros é {}ml'.format(met, cm, ml))
|
# In this program we'll be implementing variousthings using map()
# map() function applies some transformer function to every part
# of the list
def double_stuff (things) :
""" Returns a new list with doubl ethe values than the previous list """
# accum list
new_list = []
# iterate over each item in ... |
'''
Autor: Pedro Sousa
Data: 17/03/2021
Numero da questao: Questão 08
Descriçao do problema:
Nome na vertical. Faça um programa que solicite o nome do usuário
e imprima-o na vertical, em formato de escada, conforme exemplo
abaixo (para a entrada "JOSE"):
Descricao da solucao:
* Criei uma classe para usa... |
primeiro = int(input('Termo: '))
razao = int(input('Razão: '))
termo = primeiro
cont = 1
total = 0
mais = 10
while mais != 0:
total += mais
while cont <= total:
print(f'{termo} →', end='')
termo += razao
cont += 1
print(' PAUSA...')
mais = int(input('Deseja que monstre mais, quan... |
{
"variables": {
"library%": "shared_library",
"mikmod_dir%": "../libmikmod"
},
"target_defaults": {
"include_dirs": [
"include",
"<(mikmod_dir)/include"
],
"defines": [
"HAVE_CONFIG_H"
],
"cflags": [
"-Wall",
"-finline-functions",
"-funroll-loops",
"-ffast-math"
],
"target_... |
##
# Copyright (c) 2006-2016 Apple Inc. 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 l... |
units=int(input("Enter the number of units you used: "))
if(units>=0 and units <= 50):
amount = units * 0.50
elif(units <= 150):
amount = units * 0.75
elif(units <= 250):
amount = units * 1.25
else:
amount = units * 1.50
surcharge = amount * 17/100
ebill = amount + surcharge
print("Electricity Bill =... |
class matching_matrix_proportion():
def __init__(self, sol, n, * args, **kwargs):
self.rows = {i : {int(j):1} for i, j in enumerate(sol)}
self.n = n
self.k = len(Counter(sol))
self.update_A = {}
self.maximums = np.zeros(self.k)
self.where = np.zeros... |
class Solution:
def findNumbers(self, nums: List[int]) -> int:
ans = 0
if(len(nums) == 0):
return 0
for i in nums:
if(len(str(i))%2 == 0):
ans+=1;
return ans
|
"""
This file contains all the biological constants of Chlamy CCM.
--------------------------------------------------------------
"""
# ============================================================= #
# + Define relevant length scale, time scale, and conc. scale
Lnth = 3.14 * pow(10, -6) ... |
#! /usr/bin/env python
"""
RASPA file format and default parameters.
"""
GENERIC_PSEUDO_ATOMS_HEADER = [
['# of pseudo atoms'],
['29'],
['#type ', 'print ', 'as ', 'chem ', 'oxidation ', 'mass ', 'charge ', 'polarization ', 'B-factor radii ', 'connectivity ', 'anisotropic ', 'anisotropic-type ', 'tinker-typ... |
class Store:
def __init__(self):
self.store_item = []
def __str__(self):
if self.store_item == []:
return 'No items'
return '\n'.join(map(str,self.store_item))
def add_item(self,item):
self.store_item.append(item)
def count(self):
return len(self.store_item)
def filter(self, q_object):
stor... |
def add(x, y):
"""Sum two numbers"""
return x + y
def subtract(x, y):
"""Subtract two numbers"""
return x - y
|
# -*-coding:Utf-8 -*
# Programme testant si une année, saisie par l'utilisateur, est bissextile ou non
annee = input("Saisissez une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester
annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre
if annee % 400 == 0 or (annee... |
"""
# Why we use for else condition ?
# For checking the specific number or checking the condition is true
# if the condition is false we just print single line in else condition.
"""
# To check whether the given number is divisible by 5 then print the number
# if it's not then print "Given is not divisible by ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 10:26:43 2018
@author: francisco
"""
#1)
if 6 > 7:
print("Yep")
# Answer: Blank
# Since 6 is not greater than 7, it doesn't print anything and it doesn't have any
# more conditionals to evalutate.
#2)
if 6 > 7:
print("Yep")
else:
pr... |
'''Faça um Programa que verifique se uma letra digitada é "F" ou "M". Conforme a
letra escrever: F - Feminino, M - Masculino, Sexo Inválido.'''
letra = str(input("Digite m para masculino e f para feminino: "))
if letra == "m":
print(f"Você é do sexo Masculino {letra}")
elif letra == "f":
print(f"Você ... |
#!/usr/bin/python3.6
# created by cicek on 07.09.2018 09:44
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x) # 8
print(res... |
class A:
def __init__(self, *, kw_only, optional_kw_only=None):
pass
class B(A):
def __init__(self, *, kw_only):
super().__init__(kw_only=kw_only) |
'''
Problem description:
Given an array of unsorted integers, find the smallest positive integer not in the array.
'''
def find_smallest_missing_pos_int_sort(array):
'''
runtime: O(nlogn)
space : O(1) - this depends on the sort but python's list.sort() performs an in-place sort
This sort-based soluti... |
class Crawler:
def __init__(self, root):
self._root = root
def crawl(self):
pass
def crawl_into(self):
pass
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
def buildbuddy_deps():
maybe(
http_archive,
name = "rules_cc",
sha256 = "b6f34b3261ec02f85dbc5a8bdc9414ce548e1f5f67e000d7069571799cb88b25",
strip_prefi... |
def TP(target, prediction):
"""
True positives.
:param target: target value
:param prediction: prediction value
:return:
"""
return (target.float() * prediction.float().round()).sum()
def TN(target, prediction):
"""
True negatives.
:param target: target value
:param predict... |
# The @npm packages at the root node_modules are used by integration tests
# with `file:../../node_modules/foobar` references
NPM_PACKAGE_ARCHIVES = [
"@angular/animations-12",
"@angular/common-12",
"@angular/core-12",
"@angular/forms-12",
"@angular/platform-browser-12",
"@angular/platform-brows... |
# Copyright (C) 2016 Benoit Myard <myardbenoit@gmail.com>
# Released under the terms of the BSD license.
class BaseRemoteStorage(object):
def __init__(self, config, root):
self.config = config
self.root = root
def __enter__(self):
raise NotImplementedError
def __exit__(self, *args... |
get_f = float(input("Enter temperature in Fahrenheit: "))
convert_c = (get_f - 32) * 5/9
print(f"{get_f} in Fahrenheit is equal to {convert_c} in Celsius")
|
#!/usr/bin/env python
# coding: utf-8
# # Exercise 1. Regex and Parsing challenges :
# ### writer : Faranak Alikhah 1954128
# ### 14.Regex Substitution :
# In[ ]:
for _ in range(int(input())):
line = input()
while '&&'in line or '||'in line:
line = line.replace("&&", "and").replace("||", "or")
... |
def is_valid_story_or_comment(form_data):
parent = form_data.get('parent')
title = bool(form_data.get('title'))
url = bool(form_data.get('url'))
text = bool(form_data.get('text'))
if parent:
if title or url:
return (False, 'Invalid fields for a comment')
if not text:
... |
# метод трапеций s = (f(x[i]) + f(x[i+1])/2*h
def f(x):
return x
def integral(a, b, n, f):
total = 0
h = (b-a)/n
for i in range(n):
total += (f(a) + f(a + h))
a += h
total *= h/2
return total
a, b = map(float, input('Введите границы интегрирования: ').split()... |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, values = []):
self.head = None
for value in values:
self.append(value)
def append(self, value):
if self.head is None:
... |
""" A Symbol in a pushdown automaton """
class Symbol:
""" A Symbol in a pushdown automaton
Parameters
----------
value : any
The value of the state
"""
def __init__(self, value):
self._value = value
def __hash__(self):
return hash(str(self._value))
@proper... |
loss_fns = ['retrain_regu_mas', 'retrain_regu_mine', 'retrain_regu_minen', 'retrain_regu_fisher', 'retrain_regu_fishern',\
'retrain', 'retrain_regu', 'retrain_regu_selfless']#'retrain_regu_mine3', 'cnn'
model_log_map = {'fishern': 'EWCN', 'mine': 'Arms', 'minen': 'ArmsN', 'regu': 'RetrainRegu', \
'fisher': 'EWC', '... |
def digit_to_text(digit):
if digit == 1:
return "one"
elif digit == 2:
return "two"
elif digit == 3:
return "three"
elif digit == 4:
return "four"
elif digit == 5:
return "five"
elif digit == 6:
return "six"
elif digit == 7:
return "sev... |
def get_schema():
return {
'type': 'object',
'properties':
{
'aftale_id': {'type': 'string'},
'state': {'type': 'string'},
'gateway_fejlkode': {'type': 'string'}
},
'required': ['aftale_id', 'gateway_fejlkode']
}
|
w = h = 600
s = 40
off = s/4
shift = 3
x = y = 0
newPage(w, h)
strokeWidth(2)
stroke(.5)
while (y * s) < h:
while (x *s) < w:
fill(0) if x % 2 == 0 else fill(1)
rect(off + x * s, y * s, s, s)
x += 1
if y % 3 == 0: off *= -1
off += s/4
x = 0
y += 1
saveImage('imgs/cafe... |
"""
Caesar Cipher Encryptor:
Given a non-empty string of lowercase letters and a non-negative integer representing a key,
write a function that returns a new string obtained by shifting every letter in the input string by k positions in the alphabet,
where k is the key.
Note that letters should "wrap" around the alpha... |
class Pile:
"""Classe modélisant une Pile"""
# Constructeur
def __init__(self, iterable=None):
if iterable is None:
iterable = []
self.__elements = list(iterable)
def est_vide(self):
return len(self.__elements) == 0
def sommet(self):
return s... |
class Solution:
def recoverTree(self, root):
def inorder(node):
if node.left:
yield from inorder(node.left)
yield node
if node.right:
yield from inorder(node.right)
swap1 = swap2 = smaller = None
for node in inorder(root): ... |
'''
80. Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
'''
class Solut... |
expected_output = {
"dhcp_guard_policy_config":{
"policy_name":"pol1",
"trusted_port":True,
"device_role":"dhcp server",
"max_preference":255,
"min_preference":0,
"access_list":"acl2",
"prefix_list":"abc",
"targets":{
"vlan 2":{
"target":"vlan 2"... |
class Person:
Y = "You are young."
T = "You are a teenager."
O = "You are old."
age = int(0)
def __init__(self, initialAge):
if initialAge < 0:
print('Age is not valid, setting age to 0.')
else:
self.age = initialAge
def amIOld(self):
if self.age... |
"""
Stuff
"""
class Sequence(object):
def __init__(self, *_seq):
self.seq = tuple(_seq)
pass; |
# -*- coding: utf-8 -*-
# py_ornery.py
"""
This type of object gets along with nobody!
or·ner·y
ˈôrn(ə)rē/
adjective North American informal
adjective: ornery
bad-tempered and combative.
"some hogs are just mean and ornery"
synonyms: grouchy, grumpy, cranky, crotchety, cantankerous,
bad-tempered, ill... |
# Improved Position Calculation
# objectposncalc.py (improved)
print("This program calculates an object's final position.")
do_calculation = True
while(do_calculation):
# Get information about the object from the user
while (True):
try:
initial_position = float(input("\nEnter the object's... |
CELL_DIM = 46
NEXT_CELL_DISTANCE = 66
NEXT_ROW_DISTANCE_V = 57
NEXT_ROW_DISTANCE_H = 33
INITIAL_V = 44
INITIAL_H = 230
|
# (01-Gabarito/043.py)) Desenvolva uma lógica que leia o peso e a altura de uma pessoa,
# calcule seu IMC e mostre seu status, de acordo com a tabela abaixo:
# - Abaixo de 18.5: Abaixo do Peso
# - Entre 18.5 e 25: Peso ideal
# - 25 até 30: Sobrepeso
# - 30 até 40: Obesidade
# - Acima de 40... |
#ex035: Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
print('\033[1;32mANALISANDO TRIÂNGULOS\033[m')
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2 + r3 and r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.