content stringlengths 7 1.05M |
|---|
n = int(input())
if n%2!=0:
print('Weird')
elif 2<n<=5 and n%2==0:
print('Not Weird')
elif 6<n<=20 and n%2==0:
print('Weird')
elif n>20 and n%2==0:
print('Not Weird') |
expected_output = {
"interface": {
"FastEthernet2/1/1.2": {
"ethernet_vlan": {2: {"status": "up"}},
"status": "up",
"destination_address": {
"10.2.2.2": {
"default_path": "active",
"imposed_label_stack": "{16}",
... |
class merfishParams:
"""
An object that contains input variables.
"""
def __init__(self, **arguments):
for (arg, val) in arguments.items():
setattr(self, arg, val)
def to_string(self):
return ("\n".join(["%s = %s" % (str(key), str(val)) \
for (key, va... |
class InvalidResponseException(Exception):
def __init__(self, message):
self.message = f'Request was not success: {message}'
super()
|
# Contents:
# Ahoy! (or Should I Say Ahoyay!)
# Input!
# Check Yourself!
# Check Yourself... Some More
# Ay B C
# Word Up
# Move it on Back
# Ending Up
# Testing, Testing, is This Thing On?
print("### Ahoy! (or Should I Say Ahoyay!) ###")
print("Pig Latin")
print("### Input! ###")
original = input("Enter a word: ")
... |
# Exercício Python 51: Desenvolva um programa que leia o primeiro termo e a razão de uma PA.
# No final, mostre os 10 primeiros termos dessa progressão.
print('=' * 30)
print(' 10 TERMOS DE UMA PA')
print('=' * 30)
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
print(termo, ' -> ', end=' ')... |
class ContactList():
def __init__(self, names):
"""
names is a list of strings.
"""
self.names = names
def __hash__(self):
"""Conceptually we want to hash the set of names. Since set
type is mutable it cannot be hashed so we use a frozenset
"""
return hash(frozenset(self.names... |
# Write a programme to find sum of cubes of first n natural numbers.
n = int(input('Input : '))
sumofcubes = sum([x*x*x for x in [*range(1, n+1)]])
print('Output: ', sumofcubes)
|
Bin_Base=['0','1']
Oct_Base=['0', '1', '2', '3', '4', '5', '6', '7']
Hex_Base=['0', '1', '2', '3', '4', '5', '6', '7','8','9','A','B','C','D','E','F']
def BinTesting(n):
n=str(n)
for digit in n:
if digit in Bin_Base:
continue
else:
return False
return True
def OctTest... |
class Payment:
"""
Payment class
"""
def __init__(self,date, perceptions:dict=None, deductions:dict=None):
self._date = date
self.perceptions = perceptions
self.deductions = deductions
def __str__(self):
ret = f"""
Date: {self.date}
Total Perceptio... |
def minmax_decision(state):
def max_value(state):
if is_terminal(state):
return utility_of(state)
v = -infinity
for (a, s) in successors_of(state):
v = max(v, min_value(s))
print('V: ' + str(v))
return v
def min_value(state):
if is_termina... |
### tutorzzz
tutorzzzURL = 'https://tutorzzz.com/tutorzzz/orders/assignList'
tutorzzzCookie = 'SESSION_TUTOR=581fb89c-88c6-4942-a735-d082bf1a29db'
tutorzzzReqBody = {"pageNumber":1,"pageSize":20,"sortField":"id","order":"desc"}
openIDList = ['ouZ_Ys2FvyLlOk9o-B8oZOnme5n4', 'ouZ_Ys2uzq8fijTerZziXI69jVVY']
appID = 'wxe... |
"""
Exceptions for psz.
You can stringify these exceptions to get a message about the error type and
whatver extra string arguments that were passed in when the object was created.
"""
class PszError(Exception):
_msg = ''
def __str__(self):
s = []
if self._msg:
s.append(self._msg)... |
# -*- python -*-
load("@drake//tools/workspace:execute.bzl", "path", "which")
def _impl(repository_ctx):
command = repository_ctx.attr.command
additional_paths = repository_ctx.attr.additional_search_paths
found_command = which(repository_ctx, command, additional_paths)
if found_command:
repos... |
def loadfile(name):
numbers = []
f = open(name, "r")
for x in f:
for number in x.split(","):
number = int(number)
numbers.append(number)
return numbers
def caculateTravelLinear(numbers, endpoint):
travel = 0
for number in numbers:
distance = endpoint - nu... |
#!/usr/bin/env python3
def import_input(path):
with open(path, encoding='utf-8') as infile:
return [int(n) for n in infile.read().split()]
banks = import_input("input.txt")
class Redistributor:
def __init__(self, banks):
self._banks = banks
def redistribute(self, i):
blocks = s... |
"""
Tracebacks: <<< __traceback__ >>>
-> Attribute on an exception object that holds a reference to the traceback object
-> traceback: Standard library module containing functions for working with traceback objects.
"""
"""
More Traceback Functions
-> There are many more functions in the traceback module
-> format_tb... |
def test():
assert (
"if token.like_num" in __solution__
), "¿Estás revisando el atributo del token like_num?"
assert (
'next_token.text == "%"' in __solution__
), "¿Estás revisando si el texto del siguiente token es un símbolo de porcentaje?"
assert (
next_token.text == "%"
... |
prompt= "Enter a sentence which may be terminated by either’.’, ‘?’or’!’ only."
prompt += "The words may be separated by more than one blank space and are in UPPER CASE"
vowel=['A','E','I','O','U']
sentence = (input(prompt + "\n>"))
new_sentence = []
new_s = ""
new = ""
while True:
if sentence == sentence.upper():
... |
WordDic = {
# 形容词大类
'a': 'n2', # 形容词
'ad': 'n2', # 副行词
'ag': 'n2', # 形语素
'an': 'n2', # 名形词
'c': 'n16', # 连词
'b': 'n8', # 区别词
#副词大类
'd':'n11', #副词
'dg':'n11', #副语素
'e':'n18', #叹词
'f':'n4', #方位词
'i':'n23', #成语
'm':'n5', #数词
#名词大类
'n':'n0', #名词
... |
class ClientData:
"""
Class contains user info
"""
data = {}
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
counter = 1
curnode = head
while c... |
# https://leetcode.com/problems/search-a-2d-matrix
'''
Runtime Complexity: O(logNM)
Space Complexity: O(1)
'''
def search_matrix(matrix, target):
rows, columns = len(matrix), len(matrix[0])
start, end = 0, rows * columns - 1
while start <= end:
middle = (start + end) // 2
number = matrix[... |
class PaginatorFactory(object):
def __init__(self, http_client):
self.http_client = http_client
def make(self, uri, data=None, union_key=None):
return Paginator(self.http_client, uri, data, union_key)
class Paginator(object):
def __init__(self, http_client, uri, data=None, union_key=None)... |
def suppress_value(valuein: int, rc: str = "*", upper: int = 100000000) -> str:
"""
Suppress values less than or equal to 7, round all non-national values.
This function suppresses value if it is less than or equal to 7.
If value is 0 then it will remain as 0.
If value is at national level it will ... |
# Time: 93 ms
# Memory: 12 KB
n = int(input())
apy = list(map(int, input().split()))
apx = list(map(int, input().split()))
apset = set(apy[1:] + apx[1:])
# n*(n+1)//2 is 1 + 2 + 3... n
# https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
if sum(apset) == n*(n+1)//2:
print('I become the guy.')
else:
print... |
"""
znajdz największy palindrom utworzony poprzez przemnożenie przez siebie dwóch liczby 3-cyfrowych
odp:906609
"""
print("906609")
|
class Solution(object):
def isBadVersion(self, num):
return True
def firstBadVersion(self, n):
left, right = 1, n
while left <= right:
mid = left + (right - left)/2
if self.isBadVersion(mid):
right = mid - 1
else:
left ... |
#mengubah atau konversi tipe data
data = 20
print(data)
#konversi ke float
dataFloat = float(data)
print(dataFloat)
print(type(dataFloat))
#konversi sting
dataStr = str(data)
print(dataStr)
print(type(dataStr))
|
"""Object Oriented Programming Examples - Sprint 1, Module 2"""
# import pandas as pd
#
# class MyDataFrame(pd.DataFrame):
# def num_cells(self):
# return self.shape[0] * self.shape[1] # num cells of df
class BareMinimumClass:
pass
class Complex:
def __init__(self, real, imaginary):
"""
... |
#Solution 1
def search_and_insert(nums, target):
for i in range(0, len(nums)):
if target == nums[i]:
return i
elif target <nums[i]:
return i
return i+1
#Solution 2
def search_and_insert2(nums, target):
start_index = 0
half_index = len(nums)//2
end_index = len(nums)
while True:
... |
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# regions : Set or get regions and region appliance associations
def get_all_regions(self) -> dict:
"""Get all regions
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
... |
t = int(input())
answer = []
for a in range(t):
n = int(input())
if(n%4 == 0):
answer.append("YES")
else:
answer.append("NO")
for b in answer:
print(b)
|
#Faça um programa que leia três números e mostre qual é
# o maior e qual é o menor.
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
n3 = int(input('Terceiro valor: '))
#MAIOR
'''if n1 > n2:
if n1 > n3:
ma = n1
if n2 > n1:
if n2 > n3:
ma = n2
if n3 > n1:
if n3 > n2:
... |
"""
Copyright (C) 2014 Maruf Maniruzzaman
Website: http://cosmosframework.com
Author: Maruf Maniruzzaman
License :: OSI Approved :: MIT License
"""
PASSWORD_HMAC_SIGNATURE = "hmac:"
PASSWORD_COLUMN_NAME = "password"
USERNAME_COLUMN_NAME = "username"
USER_COOKIE_NAME = "usersecret"
USER_PLAINTEXT_COOKIE_NAME = "use... |
class Params:
"""
Validating input parameters and building jsons for chart init
-----
Attributes:
obj: a Chart object whose attributes will be checked and built by BuilderParams.
"""
def __init__(self,
obj):
"""
"""
self.obj = obj
def valid(... |
# when creating a function it can return nothing or it can return a value like so
# the return value can be any data type you wish including custom class you've made (see Object-oriented-programming file 1)
#main return nothing
def main():
result = sum(1, 5)
print(result)
# sum returns a inter or float depeni... |
"""
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as
shown in the figure.
![Example layout]
(https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum pos... |
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of
every node never differ by more than 1.
"""
__author__ = 'Danyang'
# Definition for a binary tree node
class TreeNode:
def __i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def recursion(n):
if n == 1:
return 1
return n + recursion(n - 1)
def main():
n = int(input("Введите n = "))
summa = 0
for i in range(1, n + 1):
summa += i
print(f"Сумма посчитаная без рекурсии = {summa}")
print(f"Сумма посчи... |
class Airport:
def __init__(self, code, lat, lng, airportName):
self.code = code
self.lat = lat
self.lng = lng
self.name = airportName
self.flightCategory = None
self.isCalculated = False
|
def gcd(a,b = None):
if b != None:
if a % b == 0:
return b
else:
return gcd( b, a % b)
else:
for i in range(len(a)):
a[0] = gcd(a[0],a[i])
return a[0]
print(gcd([18,12, 6]))
print(gcd(9, 12)) |
#!/usr/bin/env python3
# Copyright 20
# Python provides the open() function for opening file
# open() opens the file in read-only default mode.
def main():
# open the file - open() returns a file object. It takes the file name and opens that file and returns
# a file object. The file object itself is a iterato... |
#{
#Driver Code Starts
#Initial Template for Python 3
# } Driver Code Ends
#User function Template for python3
# Function to count even and odd
# c_e : variable to store even count
# c_o : variable to store odd count
def count_even_odd(n, arr):
c_e = 0
c_o = 0
pair = list()
# your cod... |
print('''
Exponent code
Exponent code
''')
print('''
def answer2(number, power):
result=1
for index in range(power):
result=result * number
return result
print(answer2(3,2))
''')
print('''
''')
def answer2(number, power):
result=1
for index in range(power):
result=... |
"""
Part and parcel of daily life?
lol why the fuck only got 2 spaces per indent
"""
def projector():
"""9 per cohort class"""
switch_on = "Nope. Please call tech support"
raise Exception(switch_on)
def fire_alarm():
'''random'''
for _ in range(10):
print("Ladies and gentlemen, it was a false alarm. I ... |
def intersect(nums1, nums2):
"""
Given two arrays, write a function to compute their intersection.
:param nums1: list
:param nums2: list
:return: list
"""
nums1, nums2 = sorted(nums1), sorted(nums2)
pt1 = pt2 = 0
res = []
while True:
try:
if nums1[pt1] > num... |
# test output stream only
print('begin')
for i in range(1, 5): # CHANGED FROM 20 TO 1,5
print('Spam!' * i)
print('end') |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def glm_repository():
maybe(
http_archive,
name = "glm",
urls = [
"https://github.com/g-truc/glm/archive/6ad79aae3eb5bf809c30bf1168171e9e55857e45.z... |
## -*- encoding: utf-8 -*-
"""
This file (./sol/nonlinear_doctest.sage) was *autogenerated* from ./sol/nonlinear.tex,
with sagetex.sty version 2011/05/27 v2.3.1.
It contains the contents of all the sageexample environments from this file.
You should be able to doctest this file with:
sage -t ./sol/nonlinear_doctest.sag... |
#Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de
#centenas, dezenas e unidades do mesmo.
#o Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo:
#o 326 = 3 centenas, 2 dezenas e 6 unidades
#o 12 = 1 dezena e 2 unidades Testar com: 326, 300, 100, 320,... |
min_computer_fish_size = 0.25
max_computer_fish_size = 3.7
min_computer_fish_speed = 100
max_computer_fish_speed = 500
player_fish_speed = 400
player_start_size = min_computer_fish_size*1.2
player_win_size = max_computer_fish_size*1.2
player_start_size_acceleration_time_constant = 0.13
player_final_size_acceleration_... |
#
# PySNMP MIB module CISCO-COMMON-ROLES-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-COMMON-ROLES-EXT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
#!/usr/bin/env python3
# coding:utf-8
def get_num(num_lst):
global count # count 是循环的重点
if len(num_lst) == 1: # num_lst=1 的时候,剩下的是答案
print("\nThe lucky number is:", num_lst[0])
else:
length = len(num_lst)
for i in range(length):
if count == 3: # 数到 3 出场
... |
# coding=utf-8
# python3
# https://leetcode.com/problems/combination-sum/
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = []
candidates.sort()
se... |
# x_2_6
#
# 問題を準備中です
first_name = '山田'
last_name = '太郎'
members = ['桃太郎', 'いぬ', 'さる', 'きじ']
fruits = {'apple': 'りんご', 'banana': 'バナナ'}
def change_first_name():
global first_name
first_name = '山村'
def change_last_name():
last_name = '四郎'
def change_list():
members[2] = 'ゴリラ'
def change_dict():
... |
class ServerCommands(dict):
def __init__(self):
super().__init__()
self.update({
'!connect': 'on_client_connect',
'!disconnect': 'on_client_disconnect'
})
def register_command(self, command, callback_name):
self[command] = callback_name
def remove_co... |
# _*_ coding: utf-8 _*_
__author__ = "吴飞鸿"
__date__ = "2019/11/26 0:54"
# 吴川一中2014届
URL_1 = 'https://weibo.com/p/1005052698466184/follow?relate=fans'
# 吴川一中
URL_2 = 'https://weibo.com/p/1005051916867493/follow?relate=fans'
|
# Get input
N, M = map(int, input().split()) # N - the number of restaurants, M - the number of pho restaurants
pho = list(map(int, input().split())) # A list of the pho restaurants
phos = [False for x in range(N)]
leaves = [True for x in range(N)]
paths = [[] for x in range(N)]
nodes = [False for x in range(N)]
tota... |
#entrada
while True:
n = int(input())
if n == 0:
break
for i in range(0, n):
planeta, anoRecebida, tempo = str(input()).split()
anoRecebida = int(anoRecebida)
tempo = int(tempo)
#processamento
if i == 0:
primeira = anoRecebida - tempo
... |
#
# PySNMP MIB module CISCO-WAN-CES-PORT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WAN-CES-PORT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:20:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
class ScopeError(Exception):
pass
class ScopeFormatError(ScopeError):
pass
class PendingExperimentsError(ValueError):
pass
class MissingArchivePathError(FileNotFoundError):
pass
class AsymmetricCorrelationError(ValueError):
"""Two conflicting values are given for correlation of two parameters."""
class ... |
class Frame:
def __init__(self, resume: int, store: int, locals_: list, arguments: list):
self.stack = []
self.locals = []
for i in range(len(locals_)):
self.locals.append(locals_[i])
if len(arguments) > i:
self.locals[i] == arguments[i]
self.a... |
#will ask the user for their age and then it will
#tell them how many months that age equals to
user_age = input("Enter your age : ")
years = int(user_age)
months = years * 12
print(f"Your age, {years}, equals to {months} months.")
|
a = [_.split('\t') for _ in open('a.txt', 'r').read().split('\n')]
b = [_.split('\t') for _ in open('b.txt', 'r').read().split('\n')]
for _ in range(len(a)):
for a_, b_ in zip(a[_], b[_]):
print(a_, b_, end='\t', sep='\t')
print('') |
# 불량 사용자
def solution(user_id, banned_id):
visited = set()
state_arr = []
backtrack(0, len(banned_id), visited, state_arr, user_id, banned_id)
return len(state_arr)
def backtrack(idx: int, max_cnt: int, visited: set, state_arr: list, user_id: list, banned_id: list):
if idx == max_cnt:
if v... |
#function -->mehgiclude sebuah nilai didalam fungsi
def input_barang(nama,harga):
print("Nama Barang:", nama)
print("Harga Barang", harga)
a=input("masukan nama barang:")
b=input("masukan harga barang")
input_barang(a,b)
|
#!/usr/bin/python3
class Bash_DB:
def __init(self, Parent):
self.Controller = Parent
def Create_DB(self, DB_Type):
if DB_Type.DB_Stack == "LAMP":
self.Controller.Bash_Script.subprocess.call("./Sensor_Database/LAMP_Server/LAMP_Setup.sh")
|
# @desc This is a code that determines whether a number is positive, negative, or just 0
# @desc by Merrick '23
def positive_negative(x):
if x > 0:
return "pos"
elif x == 0:
return "0"
else:
return "neg"
def main():
print(positive_negative(5))
print(positive_negative(-1))
... |
__all__ = [
'resp',
'user'
]
|
# ------------------------------------------------ EASTER EGG ------------------------------------------------
# Congratulations on finding this file! Please use the following methods below to decrypt the given cipher.
def decrypt(cipher, multiple):
text = ""
for idx, ch in enumerate(cipher):
if ch.isa... |
ueberweisungslimit = 50_000
kontostand = 3_500
ungueltiger_betrag = True
# Funktionsdefinition
def trenner(anzahl):
for zaehler in range(anzahl):
print("-", end="")
print()
# Funktionsaufruf
trenner(50)
print("Willkommen beim Online-Banking der DKB")
print("Ihr Überweisungslimit beträgt", ueberweisung... |
while True:
n = int(input())
if n == -1:
break
s = 0
last = 0
for i in range(n):
a,b=map(int,input().split())
s += a*(b-last)
last = b
print(s,"miles") |
no_of_adults = float(input())
no_of_childrens = float(input())
total_passenger_cost = 0
service_tax = 7/100
discount = 10/100
rate_per_adult = no_of_adults * 37550.0 + service_tax
rate_per_children = no_of_childrens * (37550.0/3.0) + service_tax
total_passenger_cost = (rate_per_adult + rate_per_children) - discount
... |
class Status(object):
SHUTTING_DOWN = 'Shutting Down'
RUNNING = 'Running'
class __State(object):
def __init__(self):
self._shutting_down = False
def set_to_shutting_down(self):
self._shutting_down = True
def is_shutting_down(self):
return self._shutting_down
@propert... |
"""Python Wavelet Imaging
PyWI is an image filtering library aimed at removing additive background noise
from raster graphics images.
* Input: a FITS file containing the raster graphics to clean (i.e. an image
defined as a classic rectangular lattice of square pixels).
* Output: a FITS file containing the cleaned r... |
class DynGraph():
def node_presence(self, nbunch=None):
raise NotImplementedError("Not implemented")
def add_interaction(self,u_of_edge,v_of_edge,time):
raise NotImplementedError("Not implemented")
def add_interactions_from(self, nodePairs, times):
raise NotImplementedError("Not i... |
def smallest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor)
def largest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor, low=False)
def is_palindrome(mn, mx, low=True):
"""
Throughout the method all ranges' upper bound is extended because in python it's ex... |
def get_sql(company, conn, gl_code, start_date, end_date, step):
# start_date = '2018-02-28'
# end_date = '2018-03-01'
# step = 1
sql = (
"WITH RECURSIVE dates AS "
f"(SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, "
f"{conn.constants.func_prefix}da... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
curr = self
vals = []
while curr:
vals.append(curr.val)
curr = curr.next
return str(vals)
@classmethod
def from_list(cls, vals):
head ... |
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 and num2 == num3:
print("yes")
else:
print("no")
print("let's see", end="")
print("?") |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
def test_simple(qipy_action, record_messages):
qipy_action.add_test_project("a_lib")
qipy_action.add_test_project("big_project")
qipy_acti... |
# Copyright Alexander Baranin 2016
Logging = None
EngineCore = None
def onLoad(core):
global EngineCore
EngineCore = core
global Logging
Logging = EngineCore.loaded_modules['engine.Logging']
Logging.logMessage('TestFIFOModule1.onLoad()')
EngineCore.schedule_FIFO(run1, 10)
EngineCore.sche... |
'''
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
668966489504... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################... |
#! /usr/bin/python3
# product.py -- This script prints out a product and it's price.
# Author -- Prince Oppong Boamah<regioths@gmail.com>
# Date -- 10th September, 2015
class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
# The program starts runn... |
# constantly ask the user for new names and phone numbers
# to add to the phone book, then save them
phone_book = {}
|
key_words = ["Trending", "Fact", "Reason", "Side Effect", "Index", "Stock", "ETF"]
knowledge_graph_dict = {
"Value Investing": {},
"Risk Management": {},
"Joe Biden": {
"Tax Increase Policy": {
"Tech Company": {
"Trending": "Negative",
},
"Corpora... |
# encoding: utf-8
'''
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
'''
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2)
|
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tomlplusplus_repository():
maybe(
http_archive,
name = "tomlplusplus",
urls = [
"https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip",
... |
#! /usr/bin/env python3
# hjjs.py - write some HJ J-sequences
EXTENSION = ".hjjs.txt"
MODE = "w"
J_MAX = 2 ** 32 - 1
def i22a(f, m):
n = 0
js = []
while True:
j = 2 ** (2 * n + m) - 2 ** n
if j > J_MAX:
break
js.append(j)
n += 1
print(*js, file = f)
for m in range(10):
with open... |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
"""Stack.
Running time: O(n) where n == len(s).
"""
d = {c: i for i, c in enumerate(s)}
st = []
seen = set()
for i, c in enumerate(s):
if c in seen:
continue
... |
# This should be subclassed within each
# class that gets registered with the API
class BaseContext:
def __init__(self, instance=None, serial=None):
pass
def serialized(self):
return ()
def instance(self, global_context):
return None
# This is actually very different from a contex... |
def pageCount(n, p):
print(min(p//2,n//2-p//2))
if __name__ == '__main__':
n = int(input())
p = int(input())
pageCount(n, p)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
self.a = [0] * 10
self.count = 0
... |
"""
Programming for linguists
Implementation of the class Circle
"""
class Circle:
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
pass
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
... |
class FLAGS:
data_url = ""
data_dir = None
background_volume = 0.1
background_frequency = 0
silence_percentage = 10.0
unknown_percentage = 10.0
time_shift_ms = 0
use_custom_augs = False
testing_percentage = 10
validation_percentage = 10
sample_rate = 16000
clip_duration_ms = 1000
window_size_ms = 30
wi... |
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
returnList = [0] * len(nums)
temp = 0
for i in range(0,n):
returnList[temp] = nums[i]
returnList[temp+1] = nums[n]
n+=1
temp+=2
return returnList
... |
'''
选择排序, 平均时间O(n^2), 最好O(n^2), 最坏O(n^2), 空间O(1), in-place, 不稳定
步骤:
1未排序序列中找最小(大)值,放到起始位置
2剩余的未排序序列中继续找最小(大)值,放到已排序序列的末尾
3重复步骤2
不管什么数据规模都是O(n^2),所以使用时数据规模越小越好
需要进行n*(n-1)/2次交换,比较冒泡排序,其交换次数更少
冒泡排序每次遍历后前者>后者就会交换,但是前者可能不是最小的,还会发生交换,需要多次才能确定,比较耗时
'''
def selectionSort(lst):
countCompare = 0
countSwap = 0... |
def get_player_score():
score = []
for i in range(0, 5):
while True:
try:
s = float(input('Enter golf scores between 78 and 100: '))
if 78 <= s <= 100:
score.append(s)
break
raise ValueError
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.