content stringlengths 7 1.05M |
|---|
class Fencepost():
vertices = [(0.25,0,0),
(0.25,0.75,0),
(1,0.75,0),
(1,0,0),
(0.25,0,1.75),
(0.25,0.75,1.75),
(1,0.75,1.75),
(1,0,1.75), #7
# Back post
(0,0.75,0.575),
(0,1.05,0.575),
(1.25,1.05,0.575),
(1.25,0.75,0.57... |
################ modules for HSPICE sim ######################
##############################################################
######### varmap definition ####################
##############################################################
### This class is to make combinations of given variables ####
### ... |
def line_br_int(win, p1, p2):
if p1 == p2:
win.image.setPixel(p1[0], p1[1], win.pen.color().rgb())
return
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
sx = sign(dx)
sy = sign(dy)
dx = abs(dx)
dy = abs(dy)
x = p1[0]
y = p1[1]
change = False
if dy > dx:
temp ... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ADSBVehicle.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/ActuatorControl.msg;/home/arijitnoobstar/UAVProjectileCatcher/src/mavros/mavros_msgs/msg/Altitude... |
# *-* coding: utf-8 *-*
class Customer:
def __init__(self, firstname=None, lastname=None, address1=None, postcode=None, city=None, phone=None, email=None,
password=None, confirmed_password=None):
self.firstname = firstname
self.lastname = lastname
self.address1 = address1
... |
class Solution(object):
def longestValidParentheses(self, s):
if len(s) == 0:
return 0
stack = [-1]
result = 0
for idx, ch in enumerate(s):
if ch == "(":
stack.append(idx)
else:
stack.pop()
if len(sta... |
# Clase 32. Curso Píldoras Informáticas.
# Control de Flujo. POO9.
# Polimorfismo
class Car():
def desplaza(self):
print("El coche se desplaza sobre sus cuatro ruedas.")
class Moto():
def desplaza(self):
print("La moto se desplaza sobre sus dos ruedas.")
class Furgo():
def despl... |
# You are at the zoo, and the meerkats look strange.
# You will receive 3 strings: (tail, body, head).
# Your task is to re-arrange the elements in a list
# so that the animal looks normal again: (head, body, tail).
tail = input()
body = input()
head = input()
lst = [head,body,tail]
print(lst) |
def area(largura, comprimento):
print(f'A área do seu tereno ({largura} x {comprimento}) é de {largura * comprimento}m²')
print(' Controle de Terrenos ')
print('-' * len(' Controle de Terrenos '))
larg = float(input('Largura: m'))
comp = float(input('Comprimento: m'))
area(largura=larg, comprimento=comp)
|
tiles = [
# highway=steps, with route regional (Coastal Trail, Marin, II)
# https://www.openstreetmap.org/way/24655593
# https://www.openstreetmap.org/relation/2260059
[12, 653, 1582],
# highway=steps, no route, but has name, and designation (Levant St Stairway, SF)
# https://www.openstreetmap.... |
# Time: O(h * p^2), p is the number of patterns
# Space: O(p^2)
# bitmask, backtracking, dp
class Solution(object):
def buildWall(self, height, width, bricks):
"""
:type height: int
:type width: int
:type bricks: List[int]
:rtype: int
"""
MOD = 10**9+7
... |
# Copyright 2018 BlueCat Networks. All rights reserved.
# -*- coding: utf-8 -*-
type = 'api'
sub_pages = [
{
'name' : 'ipam_page',
'title' : u'Cisco_DNA_IPAM_Interface',
'endpoint' : 'ipam/ipam_endpoint',
'description' : u'Gateway workflow to be IPAM interface to int... |
n=int(input())
alpha_code = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'
NEW_INPUT = 9
NUMERIC = 1
ALPHA = 2
BYTE_CODE = 4
KANJI = 8
TERMINATION = 0
while n:
code = int(input(), 16)
state = NEW_INPUT
ans = ''
p = 38*4
ret_size = 0
while p>0:
if state == TERMINATION:
break
... |
# Read two rectangles, discern wheter rect1 is inside rect2
class Rectangle:
def __init__(self, *tokens):
self.left, self.top, self.width, self.height = list(map(float, tokens))
def is_inside(self, other_rect):
if type(other_rect) is not Rectangle:
raise TypeError('other_rect is n... |
#!/usr/bin/python
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print('I have', len(shoplist), 'item to purchase.')
print('These items are:', end=' ')
for item in shoplist:
print(item, end = ' ')
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping lis... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
tmp = list(nums[:len(nums) - k])
del nums[:len(nums) - k]
nums.extend(tmp) |
"""
entrada
suelto=>int=>su
ventas departamento 1=>int=>dep1
ventas departamento 2=>int=>dep2
ventas departamento 3=>int=>dep3
salida
sueldo total al final del mes 3 departamentos=>int=> total3dep
"""
su=int(input("ingrese sueldo "))
dep1=int(input("ingrese ventas echas "))
dep2=int(input("ingrese ventas ech... |
"""This module implements the abstract classes/interfaces of all variable pipeline components."""
class AbstractDataLoader:
"""The AbstractDataLoader defines the interface for any kind of IMU data loader."""
def __init__(self, raw_base_path, dataset, subject, run):
"""
Initialization of an Ab... |
graph={
'A':['B','C'],
'B':['A'],
'C':['D','E','F','S'],
'D':['C'],
'E':['C','H'],
'F':['C','G'],
'G':['F','G'],
'H':['E','G'],
'S':['A','C','G']
}
visited=[]
def dfs(graph,node):
if node not in visited:
visited.append(node)
for n in graph[node]... |
'''
Lec 7
while loop
'''
i=5
while i >=0 :
try:
print(1/(i-3))
except:
pass
i = i - 1
|
'''
'''
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License");... |
# udacity solution, normaly I would have ordered it, and the traverse it being O(nlogn + N).
# like this is O(2N)
def longest_consecutive_subsequence(input_list):
# Create a dictionary.
# Each element of the input_list would become a "key", and
# the corresponding index in the input_list would become the "v... |
# Problem Code: HDIVISR
def highest_divisor(n):
for i in range(10, 0, -1):
if not n % i:
return i
n = int(input())
print(highest_divisor(n))
|
# EJERCICIO 02
# Determina mentalmente (sin programar) el resultado que aparecerá
# por pantalla en las siguientes operaciones con variables:
a = 10
b = -5
c = "Hola "
d = [1, 2, 3]
print(a * 5) #50
print(a - b) #15
print(c + "Mundo") #"Hola Mundo"
print(c * 2) #"Hola" "Hola"
print(d[-1]) #3
print(d[1:]) #2,3
print(d... |
_settings = None
def set_settings(settings):
global _settings
_settings = settings
def get_settings():
global _settings
return _settings |
# 베르트랑 공준은 임의의 자연수 n에 대하여, n보다 크고, 2n보다 작거나 같은 소수는 적어도 하나 존재한다는 내용을 담고 있다.
#
# 이 명제는 조제프 베르트랑이 1845년에 추측했고, 파프누티 체비쇼프가 1850년에 증명했다.
#
# 예를 들어, 10보다 크고, 20보다 작거나 같은 소수는 4개가 있다. (11, 13, 17, 19) 또, 14보다 크고, 28보다 작거나 같은 소수는 3개가 있다. (17,19, 23)
#
# 자연수 n이 주어졌을 때, n보다 크고, 2n보다 작거나 같은 소수의 개수를 구하는 프로그램을 작성하시오.
# 입력은 여러 개의 테스트... |
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/s10-basic-statistics/problem
# Difficulty: Easy
# Max Score: 30
# Language: Python
# ========================
# Solution
# ========================
N = int(input())
NUMBER = list(map... |
# Module 3 Assignment
# Jordan Phillips
myfile = open("question.txt", "r+")
myquestion = myfile.read()
myresponse = input(myquestion)
myfile.write(myresponse)
myfile.close()
|
favorite_fruits = ['banana', 'orange', 'lemon']
listed_fruits = ['apple', 'banana', 'orange', 'grappe', 'blackberry', 'lemon']
for favorite_fruit in favorite_fruits:
for listed_fruit in listed_fruits:
if listed_fruit == favorite_fruit:
print ("You really like " + listed_fruit)
print ('\n')
fo... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 08:47:55 2018
@author: conta
"""
costprice=input()
costprice=int(costprice)
sellprice=input()
sellprice=int(sellprice)
if(costprice<sellprice):
print("Profit")
if(costprice==sellprice):
print("Neither")
if(costprice>sellprice):
print("Loss") |
class script(object):
START_MSG = """
╔┓┏╦━━╦┓╔┓╔━━╗
║┗┛║┗━╣┃║┃║╯╰║
║┏┓║┏━╣┗╣┗╣╰╯║
╚┛┗╩━━╩━╩━╩━━~~~
I'm Baymax
I'm a Simple Yet Powerful bot With Cool Modules. Made by Arosha_Kovida(t.me/Aro_Ediz)
Hit HELP button to find my list of available commands
ᴀʀᴏ|ᴇᴅɪᴢ • ᴘᴜʙʟɪᴄ ᴇᴅɪᴛɪᴏɴ"""
HELP_MSG = """H... |
numbers = list(map(int, input().split()))
expected = [2, 2, 2, 1.5, 1, 0]
ans = 0
for n, e in zip(numbers, expected):
ans += e * n
print(ans)
|
"""
Wave Gradient
by Ira Greenberg.
Generate a gradient along a sin() wave.
"""
amplitude = 30
fillGap = 2.5
def setup():
size(640, 360)
background(200)
noLoop()
def draw():
frequency = 0
for i in range(-75, height + 75):
# Reset angle to 0, so waves stack properly
angle = ... |
class Student:
def __init__(self):
self.name=input('Enter name')
self.age=int(input('Enter age'))
def display(self):
print(self.name,self.age)
s=Student()
s.display()
|
i4 = Int32Scalar("b4", 2)
i5 = Int32Scalar("b5", 2)
i6 = Int32Scalar("b6", 2)
i7 = Int32Scalar("b7", 0)
i2 = Input("op2", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}") # input 0
i3 = Output("op3", "TENSOR_QUANT8_ASYMM", "{1, 1, 1, 1}") # output 0
i0 = Parameter("op0", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}", [1, 1, 1, 1]) # par... |
# -*- coding: utf-8 -*-
translations = {
# Days
'days': {
0: 'sunnuntai',
1: 'maanantai',
2: 'tiistai',
3: 'keskiviikko',
4: 'torstai',
5: 'perjantai',
6: 'lauantai'
},
'days_abbrev': {
0: 'su',
1: 'ma',
2: 'ti',
3:... |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2021 plun1331
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 use, copy, mod... |
# ----------------------------------------------------------------
# SUNDIALS Copyright Start
# Copyright (c) 2002-2022, Lawrence Livermore National Security
# and Southern Methodist University.
# All rights reserved.
#
# See the top-level LICENSE and NOTICE files for details.
#
# SPDX-License-Identifier: BSD-3-Clause
... |
# Time: O(k * (m + n + k)) ~ O(k * (m + n + k^2))
# Space: O(m + n + k^2)
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def get_max_digits(nums, start, end, ... |
# Captain's Quarters (106030800)
blackViking = 3300110
sm.spawnMob(blackViking) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-06
Last_modify: 2016-03-06
******************************************
'''
'''
Given a binary tree,
return the zigzag lev... |
"""
Cadaster system in Chicago as of 2014
based on https://nationalmap.gov/small_scale/a_plss.html
"""
'''
Survery Township
The Public Land Survey System (PLSS) forms the foundation of
Cook County's cadastral system for identifying and locating
land records. Tax parcels are identified using township and
section not... |
# zadanie 1
# Wygeneruj liczby podzielne przez 4 i zapisz je do pliku.
plik = open('zadanie_1.txt', 'w')
for i in range(0, 1000, 1):
plik.write(str(i*4)+'\n')
plik.close() |
# File: forescoutcounteract_consts.py
#
# Copyright (c) 2018-2022 Splunk Inc.
#
# 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 req... |
def find_secret_message(paragraph):
unique = set()
result = []
for word in (a.strip('.,:!?').lower() for a in paragraph.split()):
if word in unique and word not in result:
result.append(word)
unique.add(word)
return ' '.join(result)
|
class EntityNotFoundException(Exception):
pass
class SessionExpiredException(Exception):
pass
|
def main():
NAME = input("What is your name?: ")
print("Hello "+ str(NAME) + "!")
if __name__ == '__main__':
main() |
#ipaddress validation
def ip_val(ipadd):
l=ipadd.split(".")
if len(l)!=4:
return False
for i in l:
if int(i) not in range(256):
return False
return True
print(ip_val("192.168.0.1"))
print(ip_val("192.168.0.1.1"))
print(ip_val("192.168.258.1"))
|
peso = 0
pesos = []
for temp in range(0, 5):
temp += 1
peso = input("Digite o peso da pessoa Nº {}: " .format(temp))
|
class Solution:
def XXX(self, digits: List[int]) -> List[int]:
digits = [str(i) for i in digits]
s = str(int(''.join(digits))+1)
ans = [int(i) for i in s]
return ans
|
X,Y,x,y=map(int,input().split())
while 1:
d=""
if y>Y:d+="N";y-=1
if y<Y:d+="S";y+=1
if x>X:d+="W";x-=1
if x<X:d+="E";x+=1
print(d)
|
with open("Input.txt", "r") as fp:
lines = fp.readlines()
# remove whitespace characters like `\n` at the end of each line
lines = [x.strip() for x in lines]
# clockwise
# N
# W E
# S
directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
cur_direction = 0 # East
pos_x, pos_y = (0, 0)
for line in lines:
in... |
# You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other
# items. We want to create the text that should be displayed next to such an item.
#
# Implement a function likes :: [String] -> String, which must take in input array, containing the names of people
# w... |
"""
Probably will roll a wxPython front end because web frameworks
hurt my soul, while Qt-esque front ends are only extraordinarily
annoying and repetitive nightmares written in some semblance of
python.
"""
|
class Solution:
def isValid(self, s: str) -> bool:
ans = list()
for x in s:
if x in ['(', '{', '[']:
ans.append(x)
elif x == ')':
if len(ans) < 1:
return False
if ans[-1] == '(':
ans.pop(-... |
COMMON = 'http://www.webex.com/schemas/2002/06/common'
SERVICE = 'http://www.webex.com/schemas/2002/06/service'
EP = '%s/ep' % SERVICE
EVENT = '%s/event' % SERVICE
ATTENDEE = '%s/attendee' % SERVICE
HISTORY = '%s/history' % SERVICE
SITE = '%s/site' % SERVICE
PREFIXES = {
'com': COMMON,
'serv': SERVICE,
'e... |
blosum ={
"SW": -3,
"GG": 6,
"EM": -2,
"AN": -2,
"AY": -2,
"WQ": -2,
"VN": -3,
"FK": -3,
"GE": -2,
"ED": 2,
"WP": -4,
"IT": -1,
"FD": -3,
"KV": -2,
"CY": -2,
"GD": -1,
"TN": 0,
"WW": 11,
"SS": 4,
"KC": -3,
"EF": -3,
"NL": -3,
"AK": -1,
"QP": -1,
"FG": -3,
"DS": 0,
"CV": -1,
"VT": 0,
"HP": -2,
"PV": -2,
"IQ": -3,
"FV": ... |
"""
Constants file
"""
ACCESS_TOKEN_KEY = 'access_token'
API_ID = 'API_ID'
APP_JSON_KEY = 'application/json'
AUTH0_AUDIENCE = 'AUTH0_AUDIENCE'
AUTH0_AUDIENCE_MNGNMT_API = 'AUTH0_AUDIENCE_MNGNMT_API'
AUTH0_CALLBACK_URL = 'AUTH0_CALLBACK_URL'
AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID'
AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRE... |
ALL = [
"add_logentry",
"change_logentry",
"delete_logentry",
"view_logentry",
"can_export_data",
"can_import_historical",
"can_import_third_party",
"can_import_website",
"add_donation",
"change_donation",
"delete_donation",
"destroy_donation",
"generate_tax_receipt",... |
a= True
b = False
c= a and b
print("jika A={} and B={} = {}". format(a,b,c))
c= a or b
print("jika A={} or B={} = {}". format(a,b,c))
c= not a
print("jika A={} maka not A = {}". format) |
class GameConstants:
# the maximum number of rounds, until the winner is decided by a coinflip
MAX_ROUNDS = 500
# the board size
BOARD_SIZE = 16
# the default seed
DEFAULT_SEED = 1337
|
"""
DAY 24 : Convert to Roman No.
https://www.geeksforgeeks.org/converting-decimal-number-lying-between-1-to-3999-to-roman-numerals/
QUESTION : Given an integer n, your task is to complete the function convertToRoman which prints the
corresponding roman number of n. Various symbols and their values are given bel... |
# read file function
def read_file():
file_data = open('./python_examples/file_io/input_file.txt')
for single_line in file_data:
print(single_line, end='')
if __name__ == "__main__":
read_file()
|
{
"variables": {
# Be sure to create OPENNI2 and NITE2 system vars
"OPENNI2%": "$(OPENNI2)",
"NITE2%": "$(NITE2)"
},
"targets": [
{
"target_name":"copy-files",
"conditions": [
[ "OS=='win'", {
"copies": [
{ "files": [ "<(OPENNI2)/Redist/OpenNI2/Drivers/Kinec... |
# Даны координаты двух точек на плоскости, требуется определить, лежат ли они в одной координатной четверти или нет (
# все координаты отличны от нуля).
# Формат ввода
# Вводятся 4 числа: координаты первой точки (x1,y1) и координаты второй точки (x2,y2).
# Формат вывода Программа должна вывести слово YES, если точки ... |
def is_palindrome(number):
if int(number)%15 == 0:
rev = number[::-1]
return True if rev == number else False
else: return False
num = input("Enter a number to check palindrome divisible by 3 and 5: ")
if is_palindrome(number=num):
print(num, "is a Palindrome divisible by 3 and 5")
else:
... |
# Container With Most Water
# https://www.interviewbit.com/problems/container-with-most-water/
#
# Given n non-negative integers a1, a2, ..., an,
# where each represents a point at coordinate (i, ai).
# 'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
#
# Find two lines, whic... |
# 8.请按alist中元素的age由大到小排序
# alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
a = sorted(alist,key = lambda x: x['age'],reverse=True)
print(a)
# 和题目4差不多,多考察了一下reverse |
class Mazmorra():
def __init__(self):
self.__salas = []
@property
def salas(self):
return self.__salas
def addSala(self, sala):
self.__salas.append(sala)
|
a = 33
b = 200
if b > a:
pass |
#
# PySNMP MIB module CISCO-WRED-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WRED-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:21:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
class SqlQueries:
test_result_table_insert = ("""
SELECT
test_id,
vehicle_id,
test_date,
test_class_id,
test_type,
test_result,
test_mileage,
postcode_area
FROM staging_results
WHERE test_mileage ... |
"""
Lec 7 while loop
"""
i = 5
while i >= 0:
try:
print(1/(i-3))
except:
pass
i = i -1
# if i ==3:
# pass
# print(i)
# try:
# print(1/0)
# except ZeroDivisionError:
# print('Zero Division Error')
# except:
# print('Other Errors') |
with open('fun_file.txt') as close_this_file:
setup = close_this_file.readline()
punchline = close_this_file.readline()
print(setup)
|
# Why a field must have prime order?
prime = 12
for k in (1, 3, 7, 13, 18):
print([k*i % prime for i in range(prime)])
print('sorted:')
for k in (1, 3, 7, 13, 18):
print(sorted([k*i % prime for i in range(prime)]))
# No matter what k you choose, as long as it’s
# greater than 0, multiplying the entire set by ... |
#!/usr/bin/env python3
BOLD = "\033[1m"
DIM = "\033[2m"
END = "\033[0m"
TOWERS = {
"": """
_
| |
| |
| |
| |
_____| |_____
""",
"123": """
_
| |
_|_|_
|_____|
|_______|
_|_________|_
""",
"23": """
_
... |
def teleport(a,b,x,y):
d1 = abs(a-b)
d2 = abs(a-x)+abs(b-y)
d3 = abs(a-y)+abs(b-x)
print(d1,d2,d3)
if d1 <= d2 and d1 <= d3:
return d1
elif d2 <= d1 and d2 <= d3:
return d2
else:
return d3
print(teleport(3,10,8,2))
print(teleport(86,84,15,78))
print(teleport(35,94,... |
# Write a program that reads an integer n. Then, for all numbers in the range [1, n], prints the number and if it is special or not (True / False).
# A number is special when the sum of its digits is 5, 7, or 11.
# Examples
# Input Output
# 15 1 -> False
# 2 -> False
# 3 -> False
# 4 -> False
# 5 -> True
# 6 -> False
... |
lista = ('Caderno', 5.35, 'Lápis', 1.50, 'Borracha', 0.75, 'Lapiseira', 2.50, 'Folhas A4', 18.50, 'Apontador',
3, 'Fichário', 22.50, 'Lápis de cor', 15.50)
print('\033[1;32m LISTA SUPER MERCADO\033[m')
print('-=' * 30)
for cont in range(0, len(lista), +1):
if cont % 2 == 0:
print(f'{lista[cont]:.<3... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
if l1 is None and l2 is None:
retu... |
print('=' * 25)
print(' 10 TERMOS DE UMA PA')
print('=' * 25)
p = int(input('Primeiro termo: '))
r = int(input('Razão: '))
n = p + (10-1)*r
for cont in range(p, n+r, r):
print(cont, end = ' -> ')
print('ACABOU') |
class Solution:
def XXX(self, root: TreeNode) -> int:
def dfs(root, level):
if not root: return
if self.res < level + 1:
self.res = level + 1
if root.left: dfs(root.left, level + 1)
if root.right: dfs(root.right, level + 1)
i... |
class Configuration(object):
"""Configuration describes how a benchmark should be run.
It selects the implementation (for example, different implementations) and
implementation-specific options (for example, whether replay compilation
should be used).
"""
def __init__(self, name):
self.... |
f = open("nine.txt", "r")
lines = [x.strip() for x in f.readlines()]
height = len(lines)
width = len(lines[0])
map = []
for line in lines:
cur = [int(ch) for ch in list(line)]
map.append(cur)
risk = 0
for y in range(height):
for x in range(width):
val = map[y][x]
if y !=0 and map[y-... |
adult = int(input())
crian = int(input())
preco = float(input())
preco_final = (crian * (preco/2)) + (adult * preco)
print('Total: R$ {:.2f}'.format(preco_final))
|
# ranges sets
#range1
ghmin1, ghmax1, gsdmin1, gsdmax1= 0.35, 0.4, 0.197, 0.207 #range chaos 1 gh/gsd T36
ghmin2, ghmax2, gsdmin2, gsdmax2= 0.1, 0.15, 0.197, 0.207 #range nonchaos 1 gh/gsd T36
#range2
ghmin1b, ghmax1b, gsdmin1b, gsdmax1b= 0.35, 0.40, 0.275, 0.285 #range chaos 4 gh/gsd T36
ghmin2b, ghmax2b, gsd... |
'''
Given an array of integers, sort the array into a wave like array and return it,
In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
Example
Given [1, 2, 3, 4]
One possible answer : [2, 1, 4, 3]
Another possible answer : [4, 1, 3, 2]
'''
def wave_list(A: list) -> list... |
KEYS = {
"SPOTIFY_CLIENT_ID": "PLACEHOLDER_CLIENT_ID", # Create an app from [here](https://developer.spotify.com/dashboard/applications)
"SPOTIFY_CLIENT_SECRET": "PLACEHOLDER_CLIENT_SECRET", # Create an app from [here](https://developer.spotify.com/dashboard/applications)
"SPOTIFY_REDIRECT_URI": "http://l... |
# https://www.codewars.com/kata/52c31f8e6605bcc646000082
def two_sum(numbers, target):
for i, n1 in enumerate(numbers):
for j, n2 in enumerate(numbers[i+1:]):
if n1+n2 == target: return [i, i+j+1]
|
"""
Custom exceptions raised by this local library
"""
class NoApisDefined(Exception):
"""
Raised when there are no APIs defined in the template
"""
pass
class OverridesNotWellDefinedError(Exception):
"""
Raised when the overrides file is invalid
"""
pass
|
class Constants:
NUM_ARMS = "num_arms"
NUM_LEGS = "num_legs"
PERSON = "person"
ANIMAL_TYPE = "animal_type"
CAT = "cat"
DOG = "dog"
ANIMAL = "animal"
NAME = "name"
SURNAME = "surname"
WHISKERS = "whiskers"
TYPE = "type" |
lista = [('Comestibles', 'Loby Bar', 1, 305.2),
('Comestibles', 'Loby Bar', 5, 87.23),
('Comestibles', 'Piano Bar', 2, 236.9),
('Comestibles', 'Piano Bar', 8, 412.69),
('Bebidas', 'Loby Bar', 3, 145.37),
('Bebidas', 'Loby Bar', 5, 640.81),
('Bebidas', 'Piano Bar', 1... |
'''
0.写一个元组生成器(类似于列表推导式)
'''
# 用tuple1.__next__()一个一个显示
tuple1 = (x**2 for x in range(10))
def jixu():
return tuple1.__next__()
|
for _ in range(int(input())):
t = 24*60
h, m = map(int, input().split())
print(t-(h*60)-m)
|
'''
My functions that I created to support me during my lessons.
'''
def title(msg):
#This function will show up a title covered by two lines, one above and other below the msg
print('-'*30)
print(msg)
print('-'*30)
|
N=int(input())
for i in range(1,10):
m=N/i
if m.is_integer() and 1<=m<=9:
print("Yes")
break
else:
print("No") |
"""
# Mobius Software LTD
# Copyright 2015-2018, Mobius Software LTD
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later ve... |
# Pancake Sorting
'''
Given an array of integers A, We need to sort the array performing a series of pancake flips.
In one pancake flip we do the following steps:
Choose an integer k where 0 <= k < A.length.
Reverse the sub-array A[0...k].
For example, if A = [3,2,1,4] and we performed a pancake flip choosing k = 2,... |
# The following code implements the knapsack problem with bottom-up dynamic programming approach.
def read_file(name):
"""Given the path/nname of a file ,return the Values list, Weights list,
capacity and number of jobs.
"""
file = open(name, 'r')
data = file.readlines()
capacity = int(... |
# postgress creadentials
DB_NAME = "DB_NAME"
DB_ADDRESS = "HOST:PORT"
USER_NAME = "USER_NAME"
DB_PASSWORD = "PASSWORD"
SQLALCHEMY_DATABASE_URI = "postgresql+psycopg2://{}:{}@{}/{}".format(
USER_NAME, DB_PASSWORD, DB_ADDRESS, DB_NAME
)
# twitter creadentials
# https://apps.twitter.com
CONSUMER_KEY = "YOUR_CONSUME... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.