content stringlengths 7 1.05M |
|---|
# Title: Construct Binary Tree from Preorder and Inorder Traversal
# Runtime: 68 ms
# Memory: 18.1 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Time Complexity: O(n)
# Space Complexity: O(n)
class... |
class AnnotationObjectBase(RhinoObject):
"""
Provides a base class for Rhino.Geometry.AnnotationBase-derived
objects that are placed in a document.
"""
DisplayText=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the text that is displayed to users.
Get: DisplayText(... |
#H hours, M minutes and S seconds are passed since the midnight (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60).
# Determine the angle (in degrees) of the hour hand on the clock face right now.
H = int(input("H = ?"))
M = int(input("M = ?"))
S = int(input("S = ?"))
TotHours = round( (H + (M +(S/60))/60), 3)
print("Total num... |
"""Module containing all the controllers for the rest_api_to_db IEX service"""
IEX_REST_API_TO_DB_CONTROLLERS = [
]
|
c = float(input('Informe a temperatura em Celsius: '))
k = c + 273.15
print(f'A temperatura em Kelvin é de {k}°') |
class Config:
# AWS Information
ACCESS_KEY = ""
SECRET_KEY = ""
INSTANCE_ID = ""
EC2_REGION = ""
# SSH Key Path
SSH_KEY_FILE_NAME = ""
# Login Password
SERVER_PASSWORD = "1"
|
Patk = 15
Pdef = 12
Php = 25
Pgold = 250
choices = [ ' a) Fight like a champion.',
' b) Run like a coward.',
' c) Analyze the situation first.',
' d) Attempt to heal.'
]
wit_access_token = 'GIKG4P7FJTE44GV3U6YPUJGCRY7AYPDH'
|
largest = None
smallest = None
def Maximum(largest, num):
if largest is None:
largest = num
elif largest < num:
largest = num
return largest
def Minimum(smallest, num):
if smallest is None:
smallest = num
elif smallest > num:
smallest = num
re... |
print('''
A string is said to be palindrome if it reads
the same backward as forward. For e.g. "AKA" string
is a palindrome because if we try to read it from
backward, it is same as forward. One of the approach
to check this is iterate through the string till
middle of string and compare a character from bac... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"format_cookie_str": "01_Advanced_Request.ipynb",
"get_children": "01_Advanced_Request.ipynb",
"get_class": "01_Advanced_Request.ipynb",
"get_all_class": "01_Advanced_Request.ipynb"... |
"""
Terminal Returner Plugin
************************
**Plugin Name:** ``terminal``
This plugin prints rendered result to terminal screen
applying minimal formating to improve readability.
For instance if these are rendering results::
{'rt-1': 'interface Gi1/1\\n'
' description Customer A\\n'
... |
# -*- coding: utf-8 -*-
questoes = int(input())
respostas = input()
gabarito = input()
acertos = 0
for i in range(questoes):
if respostas[i] == gabarito[i]:
acertos += 1
print(acertos)
|
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
last = "NaN"
uniques = 0
i = 0
while i < len(nums): # len must be evaluated at every step for this to work
if nums[i] == last:
del n... |
#!/usr/bin/python
# Author: Wayne Keenan
# email: wayne@thebubbleworks.com
# Twitter: https://twitter.com/wkeenan
HCIPY_HCI_CMD_STRUCT_HEADER = "<BHB"
HCIPY_HCI_FILTER_STRUCT = "<LLLH"
# HCI ioctl Commands:
HCIDEVUP = 0x400448c9 # 201
HCIDEVDOWN = 0x400448ca # 202
HCIGETDEVINFO = -2147202861 #0x800448d3L # ... |
#Adapted from https://github.com/FakeNewsChallenge/fnc-1/blob/master/scorer.py
#Original credit - @bgalbraith
LABELS = ['agree', 'disagree', 'discuss', 'unrelated']
LABELS_RELATED = ['unrelated','related']
RELATED = LABELS[0:3]
def score_submission(gold_labels, test_labels):
score = 0.0
cm = [[0, 0, 0, 0],
... |
#
# @lc app=leetcode.cn id=1818 lang=python3
#
# [1818] 绝对差值和
#
# https://leetcode-cn.com/problems/minimum-absolute-sum-difference/description/
#
# algorithms
# Medium (38.79%)
# Likes: 72
# Dislikes: 0
# Total Accepted: 15.1K
# Total Submissions: 39.9K
# Testcase Example: '[1,7,5]\n[2,3,5]'
#
# 给你两个正整数数组 nums1 ... |
"""basics"""
def main():
a = [1,2,3,4]
TestError( len(a)==4 )
#b = list()
#TestError( len(b)==0 )
|
#CODE:
def create_stack():
stack = []
return stack
def peek(stack):
if len(stack) == 0:
return "Underflow"
else:
return stack[-1]
def isEmpty(stack):
if len(stack) == 0:
return True
else:
return False
def push(stack):
element=int(input("Enter the element:"))
#int should be used if we want to a... |
class ObjectBase(dict):
def __init__(self, data, client=None):
"""
Create a new object from API result data.
"""
super().__init__(data)
self.client = client
def _get_property(self, name):
"""Return the named property from dictionary values."""
if name not... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 05:59:19 2018
@author: Deepti Kulkarni
"""
"""Exercise 1: Chapter 5, Write a program which repeatedly reads numbers until the
user enters “done”. Once “done” is entered, print out the total, count,
and average of the numbers. If the user enters anything other than a
n... |
#GCD
a = int(input("Enter a: "))
b = int(input('Enter b: '))
gcd = 1 #initial gcd
k = 2 #possible gcd
while k <= a and k <= b:
if a%k == 0 and b%k == 0:
gcd = k
k += 1
print(gcd) |
ABCDE = list(map(int, input().split()))
t = []
for i in range(3):
for j in range(i + 1, 4):
for k in range(j + 1, 5):
t.append(ABCDE[i] + ABCDE[j] + ABCDE[k])
t.sort()
print(t[-3])
|
class CredentialsError(Exception):
pass
class InvalidSetup(Exception):
pass |
number_of_test_cases = int(input())
for i in range(number_of_test_cases):
number_of_candies = int(input())
one_gram_candies_number = 0
two_grams_candies_number = 0
for weight in map(int, input().split()):
if weight == 1:
one_gram_candies_number += 1
else:
two_g... |
"""Roman numerals
"""
def convert_roman_to_int(rn):
mapping = {
"I": 1,
"IV": 4,
"V": 5,
"IX": 9,
"X": 10,
"XL": 40,
"L": 50,
"XC": 90,
"C": 100,
"CD": 400,
"D": 500,
"CM": 900,
"M": 1000
... |
# Project Euler Problem 3
###############################
# Find the largest prime factor
# of the number 600851475143
###############################
#checks if a natural number n is prime
#returns boolean
def prime_check(n):
assert type(n) is int, "Non int passed"
assert n > 0, "No negative values allowed, o... |
# Origin dictionary of ABCnet
# CTLABELS = [' ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\\',']','^','_','`','a','b','c','d... |
#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: johnjim0816@gmail.com
Date: 2020-08-09 08:40:38
LastEditor: John
LastEditTime: 2020-08-10 10:38:59
Discription:
Environment:
'''
# Source : https://leetcode.com/problems/as-far-from-land-as-possible/
# Author : JohnJim0816
# Date : 2020-08-09
###########... |
#
# @lc app=leetcode.cn id=1734 lang=python3
#
# [1734] 解码异或后的排列
#
# https://leetcode-cn.com/problems/decode-xored-permutation/description/
#
# algorithms
# Medium (44.82%)
# Likes: 89
# Dislikes: 0
# Total Accepted: 17.4K
# Total Submissions: 24.9K
# Testcase Example: '[3,1]'
#
# 给你一个整数数组 perm ,它是前 n 个正整数的排列,且 ... |
# Given an array of integers arr, return true if and only if it is a valid mountain array.
# More info: https://leetcode.com/explore/learn/card/fun-with-arrays/527/searching-for-items-in-an-array/3251/
class Solution:
def is_mountain_array(self, arr: list([int])) -> bool:
if len(arr) < 3:
retur... |
#
# PySNMP MIB module A3COM-SWITCHING-SYSTEMS-ROUTEPOLICY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-SWITCHING-SYSTEMS-ROUTEPOLICY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:53:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwan... |
#This function prints the initial menu
def print_program_menu():
print("\n")
print("Welcome to the probability & statistics calculator. Please, choose an option:")
print("1. Descripive Statistics")
#print("2. ")
#print("3. ")
#print("4. ")
#print("5. ")
print("6. Exit")
#Checks if optio... |
# 10. Write a program to check whether an year is leap year or not.
year=int(input("Enter an year : "))
if (year%4==0) and (year%100!=0) or (year%400==0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
|
# 값 자체에 대한 자료형 확인
print(____(34))
# temperature 변수의 자료형을 확인
temperature = -1.5
print(____(_________))
|
def findone(L):
left = 0
right = len(L) - 1
while left < right:
mid = (left+right)// 2
isone = len(L[left:mid]) % 2
if L[mid] != L[mid-1] and L[mid] != L[mid+1]:
return L[mid]
if isone and L[mid] == L[mid-1]:
left = mid + 1
elif isone and L[mi... |
class BinarySearch:
def search(self, array, element):
first = 0
last = len(array) - 1
while first <= last:
mid = (first + last)//2
if array[mid] == element:
return mid
else:
if element < array[mid]:
last... |
"""
Given a singly linked list of n nodes and find the smallest and largest elements in linked list.
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def print_list(head):
while head:
print(f" {head.val} ->", end=" ")
head = head.next
... |
MAX_RESULTS = '50'
CHANNELS_PART = 'brandingSettings,contentDetails,contentOwnerDetails,id,localizations,snippet,statistics,status,topicDetails'
VIDEOS_PART = 'contentDetails,id,liveStreamingDetails,localizations,player,recordingDetails,snippet,statistics,status,topicDetails'
SEARCH_PARTS = 'snippet'
COMMENT_THREAD... |
# -*- coding: utf-8 -*-
"""db/tests/collection_test.py
By David J. Thomas, thePortus.com, dave.a.base@gmail.com
Unit test for the Collection, Publisher, Subject, and many-to-many tables
that join them
"""
|
heroes = {
"*Adagio*": "Adagio",
"*Alpha*": "Alpha",
"*Ardan*": "Ardan",
"*Baron*": "Baron",
"*Blackfeather*": "Blackfeather",
"*Catherine*": "Catherine",
"*Celeste*": "Celeste",
"*Flicker*": "Flicker",
"*Fortress*": "Fortress",
"*Glaive*": "Glaive",
"*Gwen*": "Gwen",
"*K... |
# Generated by h2py from /usr/include/netinet/in.h
# Included from net/nh.h
# Included from sys/machine.h
LITTLE_ENDIAN = 1234
BIG_ENDIAN = 4321
PDP_ENDIAN = 3412
BYTE_ORDER = BIG_ENDIAN
DEFAULT_GPR = 0xDEADBEEF
MSR_EE = 0x8000
MSR_PR = 0x4000
MSR_FP = 0x2000
MSR_ME = 0x1000
MSR_FE = 0x0800
MSR_FE0 = 0x0800
MSR_SE = ... |
characterMapNurse = {
"nurse_be1_001": "nurse_be1_001", # Auto: Same
"nurse_be1_002": "nurse_be1_002", # Auto: Same
"nurse_be1_003": "nurse_be1_003", # Auto: Same
"nurs... |
nombre="roberto"
edad=25
persona=["jorge","peralta",34256643,1987,0]
print(persona)
clave_personal=persona[2] * persona[-2]
print(clave_personal)
persona[-1]=clave_personal
print(persona)
|
Mystring = "Castlevania"
Mystring2 = "C a s t l e v a n i a"
Otherstring = "Mankind"
# Comando dir -> Sacar Metodos
# print(dir(Mystring))
# print(Mystring.title())
# print(Mystring.upper())
# print(Otherstring.lower())
# print(Mystring.lower())
# print(Mystring.swapcase())
# print(Otherstring.replace("Mankind", "Pale... |
# define the paths to the image directory
IMAGES_PATH = "../dataset/kaggle_dogs_vs_cats/train"
# since we do not have the validation data or acces to the testing
# labels we need to take a number of images from the training
# data and use them instead
NUM_CLASSES = 2
NUM_VALIDATION_IMAGES = 1250 * NUM_CLASSES
NUM_TEST... |
##
## code
##
pmLookup = {
b'00': 'Film',
b'01': 'Cinema',
b'02': 'Animation',
b'03': 'Natural',
b'04': 'HDR10',
b'06': 'THX',
b'0B': 'FrameAdaptHDR',
b'0C': 'User1',
b'0D': 'User2',
b'0E': 'User3',
b'0F': 'User4',
b'10': 'User5',
b'11': 'User6',
b'14': 'HLG',
... |
# Copyright 2019 The Vearch Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
class Test_2020(object):
def __init__(self):
self.a = 1
print(f'success')
def add_a(self):
self.a += 1
|
# Nº 9 - Tabuada
# Descrição: Faça um programa que leia um número Inteiro qualquer e mostre na tela a
# sua tabuada.
class CalculadoraDeTabuada():
'''Calcula um número indicado pelo usuário multiplicado de 1 a 10.'''
def __init__(self):
self.numero = 0
self.resultados = []
def iniciar(self... |
lista = list()
ficha = list()
print('-'*20)
print(' Escola Dueto')
print('-'*20)
while True:
lista.append(str(input('Digite seu 1ª nome = ')))
lista.append(float(input('Digite a 1ª nota: ')))
lista.append(float(input('Digite a 2ª nota: ')))
media = (lista[1] + lista[2])/ 2
lista.append(media)
... |
#
# PySNMP MIB module ALCATEL-IND1-VIRTUAL-FLOW-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-VIRTUAL-FLOW-CONTROL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:01:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... |
## While loop
# like if but it indicates the sequence of statements might be executed many times as long as the condition remains true
theSum = 0
data = input("Enter a number: ")
while (data!= ""):
number = float(data)
theSum += number
data = input("Enter a number or enter to quit: ")
print(f"the sum is:... |
# -*- coding: utf-8 -*-
API_BASE_URL = 'https://b-api.cardioqvark.ru:1443/'
API_PORT = 1443
CLIENT_CERT_PATH = '/tmp/'
QVARK_CA_CERT_NAME = 'qvark_ca.pem'
|
def dynamically_import():
mod = __import__('my_package.my_module', fromlist=['my_class'])
klass = getattr(mod, 'my_class')
if '__main__' == __name__:
dynamically_import()
|
class Mandatory:
def __init__(self, mandatory1, mandatory2):
self.mandatory1 = mandatory1
self.mandatory2 = mandatory2
def get_args(self):
return self.mandatory1, self.mandatory2
class Defaults:
def __init__(self, mandatory, default1='value', default2=None):
self.mandato... |
n = int(input())
a = list(map(int, input().split()))
count = 0
j = n - 1
#j là giới hạn bắt đầu của một lần vả: j giúp chống lặp người đã bị giết.
#j phải luôn bé hơn i, vì người ở i chỉ vả được những người ở bên trái nó.
#last_kill_pos: là giới hạn kết thúc của một lần vả.
for i in range(n - 1, -1 , -1):
j = min(i... |
"""リスト基礎
リストの要素位置を返すindex関数の使い方
(リストの検索開始位置、終了位置を指定する方法)
[説明ページ]
https://tech.nkhn37.net/python-list-index/#i
"""
# 開始位置と終了位置を指定する。
data = ['A', 'B', 'C', 'A', 'B', 'C', 'D']
idx = data.index('B', 2, 5)
print(f'idx: {idx}, data[idx]: {data[idx]}')
|
#!/usr/bin/env python3
def apples_and_oranges(pair):
first, second = pair
if first == "apples":
return True
elif second == "oranges":
return True
else:
return False
|
# 1)
a = [1, 4, 5, 7, 8, -2, 0, -1]
# 2)
print('At index 3:', a[3])
print('At index 5:', a[5])
# 3)
a_sorted = sorted(a, reverse = True)
print('Sorted a:', a_sorted)
# 4)
print('1...3:', a_sorted[1:4])
print('2...6:', a_sorted[2:7])
# 5)
del a_sorted[2:4]
# 6)
print('Sorted a:', a_sorted)
# 7)
b = ['grape... |
#encoding:utf-8
subreddit = 'PolHumor'
t_channel = '@r_PolHumor'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
"""
Tools for validating inputs or variables according to specifications detailing what format, datatype, etc. the data must be.
TODO:
- Add common specifications already created
- Change date, time and datetime to use isValid date, time and datetime methods so can call externally
- Change true_false to error if not o... |
"""
LC 775
You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].
The number of global inversions is the number of the different pairs (i, j) where:
0 <= i < j < n
nums[i] > nums[j]
The number of local inversions is the number of indices i where:
0... |
print("this is a test for branching")
print("this is on loopbranch")
#this will be added on the new file with out modifing the code before
l = list()
for i in range(6):
l.append(i)
print(l) |
"""Exceptions used by the FlickrAPI module."""
class IllegalArgumentException(ValueError):
"""Raised when a method is passed an illegal argument.
More specific details will be included in the exception message
when thrown.
"""
class FlickrError(Exception):
"""Raised when a Flickr method fails.
... |
# -*- coding: utf-8 -*-
"""Top-level package for napari-aicsimageio."""
__author__ = "Jackson Maxfield Brown"
__email__ = "jacksonb@alleninstitute.org"
# Do not edit this string manually, always use bumpversion
# Details in CONTRIBUTING.md
__version__ = "0.4.0"
def get_module_version() -> str:
return __version_... |
def show_dict(D):
for i,j in D.items():
print(f"{i}: {j}")
def sort_by_values(D):
L = sorted(D.items(), key=lambda kv: kv[1])
return L |
# coding = utf-8
# Create date: 2018-10-29
# Author :Bowen Lee
def test_dhcp_hostname(ros_kvm_init, cloud_config_url):
command = 'hostname'
feed_back = 'rancher'
kwargs = dict(cloud_config='{url}test_dncp_hostname.yml'.format(url=cloud_config_url),
is_install_to_hard_drive=True)
tupl... |
condition = 1
while condition < 10:
print(condition)
condition += 1
while True:
print('santhosh')
|
class ParsingError(Exception):
pass
class CastError(Exception):
original_exception = None
def __init__(self, exception):
if isinstance(exception, Exception):
message = str(exception)
self.original_exception = exception
else:
message = str(exception)
... |
"""Python library for Lyapunov Estimation and Policy Augmentation (LEAP).
controllers - All controller classes.
examples - Example implementations, simulations, and plotting code.
learning - Learning utilities.
lyapunov_functions - All Lyapunov function classes.
outputs - All output classes.
systems - All system class... |
# dataset settings
dataset_type = 'S3DISSegDataset'
data_root = './data/s3dis/'
class_names = ('ceiling', 'floor', 'wall', 'beam', 'column', 'window', 'door',
'table', 'chair', 'sofa', 'bookcase', 'board', 'clutter')
num_points = 4096
train_area = [1, 2, 3, 4, 6]
test_area = 5
train_pipeline = [
dict... |
# my_module.py is about the use of modules in python
# I did random things that came to mind
# makes use of the type function
# returns the type as expected from the type function
#
# put the bracket around a sequence of numbers before you cast,
# when you are looking for the type of the casted obj
# that is, pass it... |
def wind_stress_curl(Tx, Ty, x, y):
"""Calculate the curl of wind stress (Tx, Ty).
Args:
Tx, Ty: Wind stress components (N/m^2), 3d
x, y: Coordinates in lon, lat (degrees), 1d.
Notes:
Curl(Tx,Ty) = dTy/dx - dTx/dy
The different constants come from oblateness of the ellip... |
p = int(input("Enter a number: "))
def expand_x_1(p):
if p == 1:
print('Neither composite nor prime')
exit()
elif p < 1 or (p - int(p)) != 0:
print('Invalid Input')
exit()
coefficient = [1]
for i in range(p):
coefficient.append(coefficient[-1] * -(p ... |
class CFG:
random_state = 42
shuffle = True
test_size = 0.3
no_of_fold = 5
use_gpu = False |
def extractJapmtlWordpressCom(item):
'''
Parser for 'japmtl.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('one day, the engagement was suddenly cancelled. ......my little sister\... |
# a = dict(name="陈云老师",age=20)
# a = {"name":"陈云"}
# print(a['name'])
# def hello(name, age):
# print(f"Hello {name}, your age is {age}")
#
#
# hello(age=20,name="陈云老师")
# def add_numbers(a, b):
# return a + b
# print(add_numbers(2, 3))
# def get_info():
# return "Chen", 20
#
#
# name, age = get_info(... |
"""\
Imposer
=======
Main promise class for use of barriers/shared states.
"""
class Imposer:
def __init__(self, env):
self.env = env
return
def resolve(self):
"""Notify the states are ready"""
return
def reject(self):
"""Notify its rejection with exceptions"""
... |
class DataGridViewCellPaintingEventArgs(HandledEventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellPainting event.
DataGridViewCellPaintingEventArgs(dataGridView: DataGridView,graphics: Graphics,clipBounds: Rectangle,cellBounds: Rectangle,rowIndex: int,columnIndex: int,cellState: Data... |
resp = ''
resp2 = ''
lista = list()
alunos = list()
media = 0
while True:
alunos.append(str(input('Nome: ')))
alunos.append(float(input('Nota 1: ')))
alunos.append(float(input('Nota 2: ')))
resp = str(input('Quer continuar? [S/N] '))
lista.append(alunos[:])
alunos.clear()
if resp[0].upper() ... |
#
# PySNMP MIB module HPN-ICF-DHCPR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-DHCPR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:25:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
def sort_contacts(contacts):
newcontacts=[]
keys = contacts.keys()
for key in sorted(keys):
data = (key, contacts[key][0], contacts[key][1])
newcontacts.append(data)
return newcontacts
contacts = input("Please input the contacts.")
print(sort_contacts(contacts))
|
color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
celebrity = input("Enter the name of a Celebrity: ")
print("Roses are " + color)
print(plural_noun + " are blue")
print("I love " + celebrity)
## Mad Lib 1
date = input("Enter a date: ")
full_name = input("Enter a full name: ")
a_place = i... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'flapper_version_h_file%': 'flapper_version.h',
'flapper_binary_files%': [],
'conditions': [
[ 'branding == "Chrome"... |
# 204. Count Primes
# Runtime: 4512 ms, faster than 43.85% of Python3 online submissions for Count Primes.
# Memory Usage: 52.8 MB, less than 90.72% of Python3 online submissions for Count Primes.
class Solution:
# Sieve of Eratosthenes
def countPrimes(self, n: int) -> int:
if n <= 2:
re... |
""" Asked by: Google [Hard].
Given a string, split it into as few strings as possible such that each string is a palindrome.
For example, given the input string racecarannakayak, return ["racecar", "anna", "kayak"].
Given the input string abc, return ["a", "b", "c"].
"""
|
def ErrorHandler(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e: # pragma: no cover
pass
return wrapper
|
#
#
# Copyright 2016 Kirk A Jackson DBA bristoSOFT all rights reserved. All methods,
# techniques, algorithms are confidential trade secrets under Ohio and U.S.
# Federal law owned by bristoSOFT.
#
# Kirk A Jackson dba bristoSOFT
# 4100 Executive Park Drive
# Suite 11
# Cincinnati, OH 45241
# Phone (513) 401-9114
# e... |
"""Top-level package for investment_tracker."""
__author__ = """Ranko Liang"""
__email__ = "rankoliang@gmail.com"
__version__ = "0.1.0"
|
class Metadata:
def __init__(self, network, code, position, name, source=None):
self.network = network
self.code = code
self.position = position
self.name = name
self.source = source
self.enabled = True
class Polarization:
def __init__(self):
... |
class CommandNotFound(Exception):
def __init__(self, command_name):
self.name = command_name
def __str__(self):
return f"Command with name {self.name} not found"
|
def _merge(left, right, cmp):
res = []
leftI , rightI = 0, 0
while leftI<len(left) and rightI<len(right):
if cmp(left[leftI], right[rightI])<=0:
res.append(left[leftI])
leftI += 1
else:
res.append(right[rightI])
rightI += 1
while leftI<len(left):
res.append(left[leftI])
leftI += 1
while righ... |
tokentype = {
'INT': 'INT',
'FLOAT': 'FLOAT',
'STRING': 'STRING',
'CHAR': 'CHAR',
'+': 'PLUS',
'-': 'MINUS',
'*': 'MUL',
'/': 'DIV',
'=': 'ASSIGN',
'%': 'MODULO',
':': 'COLON',
';': 'SEMICOLON',
'<': 'LT',
'>': 'GT',
'[': 'O_BRACKET',
']': 'C_BRACKET',
... |
'''
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
'''
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
... |
# Takes the following input :- number of items, a weights array, a value array, and the capacity of knap_sack
def knap_sack(n, w, v, c):
if n == 0 or w == 0:
return 0
if w[n - 1] > c:
return knap_sack(n - 1, w, v, c)
else:
return max(v[n - 1] + knap_sack(n - 1, w, v, c - w[n - 1]... |
def maxXorSum(n, k):
if k == 1:
return n
res = 1
l = [1]
while res <= n:
res <<= 1
l.append(res)
print(l)
# return res - 1
n, k = map(int, input().split())
maxXorSum(n, k)
|
# 두 정수의 덧셈 (64비트)
# minso.jeong@daum.net
'''
문제링크 : https://www.codeup.kr/problem.php?id=1115
'''
a, b = list(map(int, input().split()))
print(a + b) |
#Gasolina
t=float(input())
v=float(input())
l=(t*v) /12
print("{:.3f}".format(l) )
|
# Code Listing #5
"""
Borg - Pattern which allows class instances to share state without the strict requirement
of Singletons
"""
class Borg(object):
""" I ain't a Singleton """
__shared_state = {}
def __init__(self):
print("self: ", self)
self.__dict__ = self.__shared_state
class IBo... |
# Copyright 2021 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
register_npcx_project(
project_name="volteer",
zephyr_board="volteer",
dts_overlays=[
"bb_retimer.dts",
"cbi_eeprom.dts",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.