content stringlengths 7 1.05M |
|---|
# Space: O(n)
# Time: O(n!)
class Solution:
def permuteUnique(self, nums):
def backtracking(nums_list, temp_list, res, visited):
if len(nums_list) == len(temp_list):
res.append(temp_list[:])
for i, num in enumerate(nums_list):
if visited[i]: contin... |
#
# PySNMP MIB module HH3C-NVGRE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-NVGRE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:16:01 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... |
def isPrime(n):
if n<=3 :
return True
for i in range(2, n):
if n%i==0:
return False
return True
a,b = map(int, input().split())
flag = True
if not isPrime(a) or not isPrime(b):
flag = False
print("NO")
else :
for i in range(a+1,b):
if isPrime(i):
... |
def binary_search_recursive(array, element, start, end):
if start > end:
return -1
mid = (start + end) // 2
if element < array[mid]:
return binary_search_recursive(array, element, start, mid - 1)
else:
return binary_search_recursive(array, element, mid + 1, end)
element = 1... |
_base_ = './faster_rcnn_r50_fpn_1x_voc0712_cocofmt.py'
model = dict(
rpn_head=dict(loss_bbox=dict(type='MSELoss', loss_weight=1.0)),
roi_head=dict(
bbox_head=dict(
loss_bbox=dict(type='MSELoss', loss_weight=1.0))))
optimizer_config = dict(
_delete_=True, grad_clip=dict(max_norm=35, norm... |
no_of_labels=4
no_of_iterations = 10
graph = {
'a': {('b', 1), ('e', 4),('c',2)},
'b': {('a',1),('c', 3), ('d',3),('e',4)},
'c': {('a',2),('d',1),('b',3)},
'd': {('b',3),('e',1), ('c',1)},
'e': {('d',1),('a',4),('b',4)}
} |
# Read one line of data
file = open('myfile.txt', 'r')
line_of_data = file.readline()
print(line_of_data, end='')
file.close()
|
#
# PySNMP MIB module Nortel-Magellan-Passport-VnetEtsiQsigMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-VnetEtsiQsigMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:19:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davw... |
# -*- coding: utf-8 -*-
# (N.B : the site root is also related to the nginx conf!)
SITE_ROOT = "__YNH_APP_WEBPATH__"
DEBUG = False
TEMPLATE_DEBUG = False
|
#VERSION: 1.0
INFO = {"initwin":("init_window","Window initializer(only for Windows)")}
RLTS = {"cls":("iccode","os","json"),"funcs":("echo","get_args","edit_userconf"),"vars":("BLOCK","ECHO","OS")}
def init_window(cmd):
global ECHO
opts = get_args(cmd)
for i in opts:
if i in ("-h,--help"):
echo(1,"""Window i... |
class TestarosaPyError(Exception):
...
class AnotherError(TestarosaPyError):
...
|
def upper_case_first_param(func):
def wrapper(text):
return func(text.upper())
return wrapper
@upper_case_first_param
def recibed_a_msg(name: str) -> str:
return f"{name}, you has received a message."
@upper_case_first_param
def uppercase(msg: str) -> str:
return msg
if __name__ == "__mai... |
"""
This file analyzes a game state and determines the next (group of) cells to mark grey or blue.
The output file for this will be "${GAMESTATE_FILENAME}_soln".
The data output will consist of:
1. An array of cells to mark as blue
2. An array of cells to mark as grey
3. An array of data structures to mark ... |
class FlagRegion:
def __init__(self, name, format, icon, mode):
self.name = name
self.format = format
self.icon = icon
self.mode = mode
|
class Status(object):
'''Object to represent row in status table
Attributes:
conn: database connection, usually sqlite3 connection object
name: name of pipeline job running
display_name: pretty formatted display name for pipeline
last_ran: UNIX timestamp (number) for last comple... |
"""
9. Palindrome Number
https://leetcode.com/problems/palindrome-number/description/
"""
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x % 10 == x:
return True
before, after ... |
# clean = open("../data/fics_2017_HvC.pgn", "w+")
# with open("../data/fics_2017_HvC_raw.pgn") as raw:
# for i, line in enumerate(raw):
# if (i % 1000): print(i)
# if "\r\n" in line:
# clean.write(line.replace("\r\n", "\n"))
# else:
# clean.write("\n\n")
# clean.... |
ABSATER = 'ABSATER'
ATTRIB = 'ATTRIB'
INVATR = 'INVATR'
OBJECT = 'OBJECT'
RDSET = 'RDSET'
RSET = 'RSET'
SET = 'SET'
ComponentRole = {
'000': ABSATER,
'001': ATTRIB,
'010': INVATR,
'011': OBJECT,
'100': 'reserved',
'101': RDSET,
'110': RSET,
'111': SET
}
"""
- An EFLR begins with a Se... |
# Multiple Choice
# Return the answer to the multiple choice question in the handout.
# If you think option c is the correct answer,
# return 'c'
def question_1():
# [Image] The first hidden layer has 4 filters of kernel-width 2 and stride 2;
# the second layer has 3 filters of kernel-width 8 and stride 2; th... |
"""
entrada
cantidad invertida-->float-->c
tasa de intereses-->float-->t
salida
intereses-->float-->i
ganancia total-->float-->total
"""
c=float(input("Escriba la cantidad invertida:"))
t=float(input("Escriba la tasa de interes:"))
i=(c*t)/100
if (i>100.000):
print("Los intereses son:"+str(i))
total=c + t
print("el... |
class WorkflowNotFound(Exception):
pass
class WorkflowSyntaxError(Exception):
pass
|
# Copyright 2021 Tianmian Tech. 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 la... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# CDS-ILS is free software; you can redistribute it and/or modify it under
# the terms of the MIT License; see LICENSE file for more details.
"""CDS-ILS CDS Importer ignored fields."""
CDS_IGNORE_FIELDS = {
"003",
"005",
"020__q",
"020__c",
"0... |
#
# PySNMP MIB module ALVARION-BANDWIDTH-CONTROL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALVARION-BANDWIDTH-CONTROL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:21:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... |
# Solution by PauloBA
def sum_of_minimums(numbers):
ans = 0
for i in numbers:
i.sort()
ans = ans + i[0]
return ans |
"""
[2017-08-11] Challenge #326 [Hard] Multifaceted alphabet blocks
https://www.reddit.com/r/dailyprogrammer/comments/6t0zua/20170811_challenge_326_hard_multifaceted_alphabet/
# Description
You are constructing a set of N alphabet blocks. The first block has 1 face. The second block has 2 faces, and so on up
to the N... |
s=str(input()) # Number n in binary format
s='0'+s # Trailing zero will make the code run for '11111' etc. without changes
first1=-1
seqend=-1
if s[-1]=='0':
'''
If s ends with '0', the next biggest number will be '1' followed by the
number of '0's + one extra '0' followed by the number of '1's. For ex:
... |
# -*- coding: utf-8 -*-
tl = [42, 38, 'HongKong', 'Jimmy', [9, 4, 23, -3, 'Stock']]
print(tl[0])
print(len(tl))
tl.append(34)
tl.append('34')
tl.extend([12, 98, 'mnk'])
tl.insert(3, 55)
ml = tl.copy()
print(ml)
# list 很适合用作栈,后进先出,但不适合用作queue
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print(stack)
print(s... |
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
# Don't know why the following solution doesn't work on 100000 calls case.
class Solution:
def rand10(self):
"""
:rtype: int
"""
a, b = rand7() - 1, rand7() - 1
num = ... |
n = int(input())
case = 0
l = []
for i in range(n):
item = int(input())
l.append(item)
for i in l:
for j in range(1, i+1):
x = j
y = i - j
lx = [int(a) for a in str(x)]
ly = [int(b) for b in str(y)]
if((4 in lx) or (4 in ly)):
con... |
# If Expression
# if expr:
if True:
print("it is true")
else:
print("it is false")
if False:
print("it is false")
print("print intented next line")
else:
print("it is not false")
if bool("python"):
print("it is python")
else:
print("it is not python")
h = 50
if h > 50:
print("h is n... |
'''
test cases and facts for unit tests
'''
# list for testing fibonacci output
fib_list = [
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418,
317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465,
... |
#Imagina un hotel. Es un hotel enorme que consta de tres edificios, de 15 pisos cada uno.
#Hay 20 habitaciones en cada piso.
#Para esto, necesitas un arreglo que pueda recopilar y procesar información
#sobre las habitaciones ocupadas/libres.
#Primer paso: El tipo de elementos del arreglo. En este caso, sería un valor ... |
# https://docs.google.com/document/d/1LTf2-077v4KF1LKgR6tUA68Z6iIHGz-qcLTrs7pF8Js/edit
'''
Ve vozovém parku jsou i hybridní vozy. To znamená, že určitou vzdálenost jedou
levně, dokud se nevybijí baterky, a pak jedou dál na naftu, ale o něco dráž.
Zkus to nějak zohlednit při výběru optimálního autobusu pro školní výlet... |
# Copyright 2015 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': {
'chromium_code': 1,
},
'includes': [
'../../build/common_untrusted.gypi',
],
'conditions': [
['disable_nacl==0 and dis... |
# Given two integers representing the numerator and denominator of a fraction,
# return the fraction in string format.
# If the fractional part is repeating, enclose the repeating part in parentheses.
class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
(integer, rem... |
credentials = dict(
email = '',
password = '',
telegram_api_token = '__telegram_api_token__',
telegram_userid = '__telegram_userid__'
)
|
"""
A Python 3 library for the analysis of data produced by AMIGA's Halo Finder (AHF).
For more information visit https://github.com/BenDavisonPetch/ahfhalotools
Usage and Examples
------------------
The majority of analysis is done via the ahfhalotools.objects.Cluster class. For
examples on usage, there are example ... |
with open("0404.csv", 'r', encoding='utf-8') as f:
lines = f.readlines()
new_Json = {}
hospital_Json = {}
hospital_Json['date'] = '0404'
school_list = []
for line in lines:
#print(len(line))
if len(line)<=1:
continue
lineList = line.split(",")
doc = ... |
"""
constants used throughout the application/
"""
ESC_KEY = 27
CHAR_Q = ord('q')
EXIT_KEYS = [ESC_KEY, CHAR_Q]
# Data fetch interval time.
REFRESH_INTERVAL = 1.5
"""
Describes the way screen should be divides. There
may be a better way to do this, but this works fine
for the current application since all boxes are ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: sda_host_onboarding_access_point
short_description: Manage SdaHostOnboardingAccessPoint objects of Sda
descriptio... |
num = int(input())
def f(n):
if n <= 0:
return 0
return f(n-1) + n
print(f(num))
|
all_heroes = {}
n = int(input())
max_hp = 100
max_mp = 200
for _ in range(n):
info = input().split(" ")
name = info[0]
hp = int(info[1])
mp = int(info[2])
# collect info in dict
if name not in all_heroes:
all_heroes[name] = {}
all_heroes[name]["hit points"] = hp
all_he... |
# -*- coding: utf-8 -*-
pytest_plugins = [
u'ckan.tests.pytest_ckan.ckan_setup',
u'ckan.tests.pytest_ckan.fixtures',
u'ckanext.harvest.tests.fixtures',
]
|
#!/usr/bin/env python3
# import numpy as np
# import time
class AIDASim:
def __init__(self):
self.ke = 5.4 # l/hr
self.k1 = 0.025 # /hr
self.k2 = 1.25 # /hr
self.Ibasal = 10 # mU/l
self.Km = 10 # mmol/l
self.GI = 0.54 # mmol/hr/kg
se... |
# -*- coding:utf-8 -*-
class Solution:
stack1 = []
stack2 = []
def push(self, node):
# write code here
self.stack1.append(node)
def pop(self):
# return xx
if len(self.stack2)==0:
while len(self.stack1)!=0:
self.stack2.append(self.stack1[-1])
... |
def validate_columns(table_catalog, column_family_id, keys, values_batch):
columns = table_catalog["column_families"][column_family_id]["columns"].keys()
row_key_identifiers = table_catalog["row_key_identifiers"]
unregisterd_keys = set(keys) - (set(row_key_identifiers) | set(columns))
if unregisterd_ke... |
#Given an integer n, return 1 - n in lexicographical order.
#
#For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].
#
#Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.
class Solution(object):
def lexicalOrder(self, n):
"""
:type n: int
:rtype: Li... |
""" Asked by: Twitter
Implement an autocomplete system. That is, given a query string s and a set of all possible query strings,
return all strings in the set that have s as a prefix.
For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].
Hint: Try preprocessing the dicti... |
#!/usr/bin/env python3
# -*- coidng=utf-8 -*-
'''
learn MOEA/D
'''
def main():
pass
if __name__ == '__main__':
main() |
def displayPermuation(s):
return displayPermuationHelper("", s)
def displayPermuationHelper(s1, s2):
if len(s2) == 0:
print (s1)
for i in range(len(s2)):
displayPermuationHelper(s1 + s2[i], s2[0: i] + s2[i + 1 : ])
def main():
str = input("Please enter a string: ").replace(' ', '')
... |
"""
Settings for app
"""
READONLY_MODEL = {
'NAME': 'readonly_model',
'META_ATTR': 'read_only_model',
'DATABASE_ROUTER': 'readonly_model.dbrouters.ReadOnlyModelRouter'
}
|
Version = "{{VERSION}}"
if __name__ == "__main__":
print(Version)
|
# Problem URL: https://leetcode.com/problems/4sum/
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
solution = set()
nums.sort()
if len(nums) < 4:
return []
for i in range(len(nums)-3):
for j in range(... |
class Cursor:
def __init__(self, wnd):
self.wnd = wnd
self.pos = 0
self.preferred_col = 0
self.preferred_linecol = 0
self.last_screenpos = (-1, -1)
def refresh(self, top=None, middle=None, bottom=None,
align_always=False):
self.pos, y, x = self.w... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 5 17:15:00 2018
@author: User
"""
## find max list 07_04
#
#testList = [-2,1,-3,4,-1,2,1,-5,4]
#aList = [-1,2,-5,1]
##aList = [1, 2, 3]
#
#def maxSum(lst, left, right):
# leftSum = 0
# rightSum = 0
# maxLeft = 0
# maxRight = 0
#
# middl... |
### Types to hold CTR's data
class catboost_model_ctr(object):
def __init__(self, base_hash, base_ctr_type, target_border_idx, prior_num, prior_denom, shift, scale):
self.base_hash = base_hash
self.base_ctr_type = base_ctr_type
self.target_border_idx = target_border_idx
self.prior_n... |
"""
装饰器语法
闭包最佳实践
1. 有外有内:外函数接收旧功能,内函数包装新旧功能
2. 内使用外:需要在旧功能(外部嵌套变量)基础上增加新功能
3. 外返回内:为了客户端代码可以反复执行内部函数
本质作用:拦截调用
"""
def new_func(func):
def wrapper():
print("新功能") # 执行新功能
func() # 执行旧功能
return wrapper
# func01 = new_func(func01)
# 调用n... |
def solve(a, b):
larger = max(a, b)
return larger
def main():
a, b = map(int, input().strip().split())
a, b = int(str(a)[::-1]), int(str(b)[::-1])
return solve(a, b)
if __name__ == "__main__":
print(main()) |
"""
"""
encrypted_message=""
def convert_text(x):
"""
convert letters in text into the coresspoding alphabetic order
"""
l = list()
x = x.lower()
for i in x:
num = ord(i) - ord("a") + 1
l.append(num)
return l
def cal_occurence(correspoding_text_number_list):
"""
... |
if __name__ == '__main__':
samples = [
[0, 0, 2, 'EA'],
[1, 'QRI', 0, 4, 'RRQR'],
[1, 'QFT', 1, 'QF', 7, 'FAQFDFQ'],
[1, 'EEZ', 1, 'QE', 7, 'QEEEERA'],
[0, 1, 'QW', 2, 'QW']
]
for sample in samples:
haha
|
# Copyright 2021 Robert Grimm
#
# 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 or agreed to in writing,... |
LOG_FILE_NAME = "logs/log.txt"
SUCESS_FILE_NAME = "logs/success.txt"
FAIL_FILE_NAME = "logs/fail.txt"
EXCEPTION_FILE_NAME = "logs/exception.txt"
ALL_PATHS = [LOG_FILE_NAME, SUCESS_FILE_NAME, FAIL_FILE_NAME, EXCEPTION_FILE_NAME] |
day = ["saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"]
for _ in range(int(input())):
a = [x for x in input().split()]
# gap = abs(d[a[0]] - d[a[1]]) + 1
l,r = int(a[2]),int(a[3])
c,d = 0,0
for i in range(len(day)):
if(a[0] == day[i]): c = i
if(a[1] == day[i]): d = i
if(c == d):g... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Jeremy Parks
# Note: Requires Python 3.3.x or higher
desc = "Animate Weapon target"
# types intended for this is "animate melee" and "animate range"
# Base type : settings pair
items = {
"0 animate melee white 4x1": {"other": ["Class Dagger \"One Hand\" Stave \"Two... |
class Solution:
def buildtree(self, preorder, inorder):
if inorder:
root_index = inorder.index(preorder.pop(0))
root = TreeNode(inorder[root_index])
root.left = self.buildtree(preorder, inorder[:root_index])
rootright = self.buildtree(preorder, inorder[root_in... |
# b_flow
# Flow constraint vector
__all__ = ["b_flow"]
def b_flow(a_vertices):
# b_flow
#
# Construct flow constraint vector
# (vector of size |V| x 1 representing the sum of flow for each vertex.
# Having removed source and drain nodes. Now require:
# L nodes = -1
# R nodes = +1
# A... |
# Leemos el posible dividendo
dividendo = input("Ingrese el dividendo: ")
#Intentamos convertirlo a número
try:
dividendo = int(dividendo)
# print("Su dividendo es", dividendo)
# Leemos el posible divisor
divisor = input("Ingrese el divisor: ")
#Intentamos convertirlo a número
try:
di... |
"""
There is a road consisting of N segments, numbered from 0 to N-1, represented by a string S.
Segment S[K] of the road may contain a pothole, denoted by a single uppercase "x" character, or may be a good segment without any potholes, denoted by a single dot,".".
For example, string".X. .X" means that there are two... |
class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + last + "@compani.com"
def fullname(self):
return f"{self.first} {self.last}"
def add_raise(self):
self.pay ... |
n = int(input())
while(n != 0):
jogadas = list(map(int, input().split()))
contMary = contJonh = 0
for i in range(len(jogadas)):
if(jogadas[i] == 0):
contMary = contMary + 1
else:
contJonh = contJonh + 1
print("Mary won {} times and John won {} times".form... |
def lowestCommonAncestor(self, root, p, q):
if root in (None, p, q): return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
return root if left and right else left or right |
class Ordenation:
def selection_sort(self, lista):
fim = len(lista)
for i in range(fim-1):
# Inicialmente, o menor elemento ja visto e o i-esimo
posicao_do_menor = i
for j in range(i+1, fim):
if lista[j] < lista[posicao_do_menor]:
... |
class heap(list):
"""docstring for heap"""
def __init__(self, heap_size):
super(heap, self).__init__()
self.heap_size = heap_size
def parent(i):
return ((i+1) / 2) - 1
def left(i):
return 2*i+1
def right(i):
return 2*i+2
def max_heapify(A, i):
while i < A.heap_size:
l = left(i)
r = left(i)
largest =... |
def minimumMovement(obstacleLanes):
# Write your code here
pass
minimumMovement([2, 3, 2, 1, 3, 1]) # 2
minimumMovement([2, 1, 3, 3, 3, 1]) # 2
minimumMovement([3, 2, 2, 1, 2, 1]) # 1 |
class MyList(list):
def append(self, *args):
self.extend(args)
m = MyList()
m.append(0)
m.append(1,2,3,4,5,6)
print(m)
class MyList1(list):
def sort(self):
return 'eae vey? ta afim de ordenar?'
l = [4,1,78,34,4,9]
'''l.sort()
print(l)'''
lista = MyList1()
print(lista.sort())
|
"""
Fibonacci number sequence problem, find the nearest Fibonacci number
"""
def fibs():
a, b = 0, 1
yield a
yield b
while True:
a, b = b, a + b
yield b
def nearestFib(n):
"""If n is fibo num return True and n
Otherwiise return False and nearest Fibo"""
for fib in fi... |
n1 = input('Digite algo:')
print('isnumeric:', n1.isnumeric())
print('isalpha:', n1.isalpha())
print('islower:', n1.islower())
print('isalnum:', n1.isalnum())
|
#===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===============================================================
RgbColour(75,0,130)
|
def calc_result(home, away):
if home < away:
return 'lose'
elif home > away:
return 'win'
else:
return 'draw'
def calc_bet_result(
home_score, away_score,
home_bet, away_bet,
shootout_winner=None,
shootout_bet=None,
):
if home_score == home_bet a... |
#: Okay
GLOBAL_UPPER_CASE = 0
#: N816
mixedCase = 0
#: N816:1:1
mixed_Case = 0
#: Okay
_C = 0
#: Okay
__D = 0
#: N816
__mC = 0
#: N816
__mC__ = 0
#: Okay
__C6__ = 0
#: Okay
C6 = 0
#: Okay
C_6 = 0.
#: Okay(--ignore-names=mixedCase)
mixedCase = 0
|
cid = input('Digite o nome de sua cidade aqui: ')
cid2 = cid.lstrip()
cid3 = cid2[:5].upper()
cid6 = 'SANTO' in cid3
print('Sua cidade começa com a palavra Santo: {}'.format(cid6)) |
def sumOfNumbers(n):
if n <= 1:
return n
else:
return n + sumOfNumbers(n-1)
print(sumOfNumbers(10)) |
WIDTH = 32
HEIGHT = 32
FIRST = 0x20
LAST = 0x7f
_font =\
b'\x00\x4a\x5a\x0e\x4d\x57\x52\x46\x51\x48\x52\x54\x53\x48\x52'\
b'\x46\x20\x52\x52\x48\x52\x4e\x20\x52\x52\x59\x51\x5a\x52\x5b'\
b'\x53\x5a\x52\x59\x15\x49\x5b\x4e\x46\x4d\x47\x4d\x4d\x20\x52'\
b'\x4e\x47\x4d\x4d\x20\x52\x4e\x46\x4f\x47\x4d\x4d\x20\x52\x57'\
b'... |
"""
UCL Academic Modelling Project
Fast Code Processing
"""
STUDENT_TYPES = {
'A': "Campus-based, numeric mark scheme",
'B': "Campus-based, non-numeric mark scheme",
'C': "Distance learner, numeric mark scheme",
'D': "Distance learner, non-numeric mark scheme",
'E': "MBBS Resit"
}
c... |
"""
题目:最小的第k个数
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4
思路:借助Partition函数 我们每次运行Partition函数将会排好一个元素的位置 如果该位置是倒数第k个元素 完成任务 另倒数第k个元素是第n-k+1个元素(n
是数组长度)
"""
class Solution:
def GetLeastNumbers_Solution(self, tinput, k):
if tinput is None:
return -1
lens = len(t... |
for c in range(0, 6, -1):
print('Oi')
print(c)
print('FIM')
n = int(input('Digite um número: '))
for c in range(0, n+1):
print(c)
i = int(input('Início: '))
f = int(input('Fim: '))
p = int(input('Passo: '))
for c in range(i, f, p):
print(c)
s = 0
for c in range(0, 3):
n = int(input('Digite um va... |
# encoding: UTF-8
RISK_MANAGER = u'Risk Manager'
RISK_MANAGER_STOP = u'RM Stop'
RISK_MANAGER_RUNNING = u'RM Running'
CLEAR_ORDER_FLOW_COUNT = u'Clear Flow Count'
CLEAR_TOTAL_FILL_COUNT = u'Clear Fill Count'
SAVE_SETTING = u'Save Setting'
WORKING_STATUS = u'Working Status'
ORDER_FLOW_LIMIT = u'Flow Limit'
ORDER_FLOW_... |
# lst = [1, 2, 3, 4, 6, 9]
# integ = 15
# result = []
# if len(lst) < 2:
# raise ValueError
# for i in lst:
# for j in lst:
# if i + j == integ:
# result.append([i, j])
# if len(result) != 0:
# print(result)
# lst = [1, 2, 3, 4, 6, 9]
# integ = 15
# result = []
# if... |
n1 = int(input('Digite um valor: '))
d = n1 * 2
t = n1 * 3
r = n1 **(1/2)
print('O dobro de {} é: {} \nO triplo de {} é: {}\nA raiz quadrada de {} é: {:.2f}'.format(n1, d, n1, t, n1, r))
|
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE I... |
class SqlQueries:
staging_songs_table_create = ("""
CREATE TABLE IF NOT EXISTS staging_songs (
num_songs int4,
artist_id varchar(256),
artist_name varchar(256),
artist_latitude numeric(18,0),
artist_longitude numeric(18,0),
artist_locat... |
#
# PySNMP MIB module CODIMA-EXPRESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CODIMA-EXPRESS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
if not arr or len(arr) < 3:
return
start, end = 0, len(arr) - 1
while start + 1 < end:
mid = (start + end) // 2
if arr[mid] > arr[mid - 1]:
start =... |
#!/usr/bin/env qork
img = "player.png"
camera.mode = "3D"
camera.z = 1
p = add(img)
level = add("map.png", scale=25, pos=-Z * 10)
nodes = [None] * 4
nodes[0] = p.add(img, scale=0.25, pos=(-0.5, 0.5, 0.1))
nodes[1] = p.add(img, scale=0.25, pos=(0.5, -0.5, 0.1))
nodes[2] = p.add(img, scale=0.25, pos=(-0.5, -0.5, 0.1... |
"""
Comprehensions - constructs that allow sequences to be built
from other sequences
Three types -
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
"""
# List Comprehensions
# variable = [out_exp for out_exp in input_list if out_exp == 2]
multiples = [i for i in range(30) if i % 3 is 0]
print(m... |
#!/usr/bin/python
table_cols = 9
table_rows = 9
list_size = 9
with open("vimwiki.snippets", "w") as file:
# generate tables
for i in range(1, table_cols+1):
for j in range(1, table_rows+1):
file.write("snippet table{}x{} \"table{}x{}\" A\n".format(i, j, i, j))
for k in range... |
# -*- coding: utf-8 -*-
def main():
h, w = map(int, input().split())
grids = [list(input()) for _ in range(h)]
up = [[1 for __ in range(w)] for _ in range(h)]
down = [[1 for __ in range(w)] for _ in range(h)]
left = [[1 for __ in range(w)] for _ in range(h)]
right = [[1 for __ in rang... |
def solution(nums):
setNums = set(nums)
if len(setNums) > (len(nums) // 2): return len(nums) // 2
return len(setNums)
# print(solution([3,1,2,3]))
# print(solution([3,3,3,2,2,4]))
print(solution([3, 3, 3, 2, 2, 2]))
|
def test1():
for i in range(2):
print('+' + str(i))
yield str(i)
for a in test1():
print("-" + a)
for a in list(test1()):
print('-' + a) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.