content stringlengths 7 1.05M |
|---|
def collatzChain(n):
lengthChain=0
while n!=1:
if n%2==0:
n=int(n/2)
else:
n=int((3*n)+1)
print(n)
def collatzChainLength(n):
lengthChain=0
while n!=1:
if n%2==0:
n=int(n/2)
else:
n=int((3*n)+1)
... |
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyz"; consonants+=consonants.upper()
#The f means final, I thought acually writing final would take to long
fvowels = ""
fcon=""
fother=""
userInput = input("Please input sentance to split: ")
print ("Splitting sentance: " + userInput)
#Iterates through inputed char... |
#!/usr/bin/env python3
# Replace by your own program
print("hello world") |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author:lichunhui
@Time: 2018/7/12 10:12
@Description:
""" |
"""
Module: 'flowlib.faces._encode' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
class Encode:
''
def _available():
pass
def _update():
pass
d... |
"""
Database module
"""
class Database(object):
"""
Defines data structures and methods to store article content.
"""
def save(self, article):
"""
Saves an article.
Args:
article: article metadata and text content
"""
def complete(self):
"""
... |
def is_mechanic(user):
return user.groups.filter(name='mechanic')
# return user.is_superuser
def is_mechanic_above(user):
return user.groups.filter(name='mechanic') or user.is_superuser
# return user.is_superuser |
# -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
class ClassTools(object):
def copyattrs(self, source, names):
for name in names:
setattr(self, name, getattr(source, name))
def copyvalues(self, *a... |
less = "Nimis";
more = "Non satis";
requiredGold = 104;
def sumCoinValues(coins):
totalValue = 0;
for coin in coins:
totalValue += coin.value
return totalValue
def collectAllCoins():
item = hero.findNearest(hero.findItems())
while item:
hero.moveXY(item.pos.x, item.pos.y)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 02/12/2017 8:57 PM
# @Project : BioQueue
# @Author : Li Yao
# @File : svn.py
def get_sub_protocol(db_obj, protocol_parent, step_order_start=1):
steps = list()
steps.append(db_obj(software='svn',
parameter='checkout {{InputF... |
n = int(input("> "))
suma = 0
while n > 0:
suma += n % 10
n //= 10
print(suma) |
# Author: Ashish Jangra from Teenage Coder
var_int = 3
var_float = -3.14
var_boolean = False
var_string = "True"
print(type(var_int))
print(type(var_boolean))
print(type(var_string))
print(type(var_float)) |
def transform_string(number: int) -> str:
if number % 10 == 1:
return f'{number} процент'
elif number % 10 == 4:
return f'{number} процента'
elif number % 10 <= 9 :
return f'{number} процентов'
elif number % 10 <= 0:
return f'{number} процентов'
for n in range(1, 10... |
class Saml:
def __init__(self, britive):
self.britive = britive
self.base_url = f'{self.britive.base_url}/saml'
def settings(self, as_list: bool = False) -> any:
"""
Retrieve the SAML settings for the tenant.
For historical reasons there was a time in which multiple SA... |
# version code d345910f07ae
coursera = 1
# Please fill out this stencil and submit using the provided submission script.
## 1: (Task 1) Movie Review
## Task 1
def movie_review(name):
"""
Input: the name of a movie
Output: a string (one of the review options), selected at random using randint
"""
... |
ultimo = 0
fila1 = []
fila2 = []
while True:
print("\nExistem %d clientes na fila 1 e %d na fila 2." % (len(fila1), len(fila2)))
print("Fila 1 atual:", fila1)
print("Fila 2 autal:", fila2)
print("Digite F para adicionar um cliente ao fim da fila 1 (ou G para fila 2),")
print("ou A para realizar o at... |
a, b, c, x, y = map(int, input().split())
ans = 5000*(10**5)*2
for i in range(max(x, y)+1):
tmp_ans = i*2*c
if x > i:
tmp_ans += (x-i)*a
if y > i:
tmp_ans += (y-i)*b
ans = min(ans, tmp_ans)
print(ans)
|
# Python - 2.7.6
def AddExtra(listOfNumbers):
return listOfNumbers + ['']
|
@dataclass
class Position:
x: int = 0
y: int = 0
def __matmul__(self, other: tuple[int, int]) -> None:
self.x = other[0]
self.y = other[1]
|
# -*- coding: utf-8 -*-
info = {
"name": "is",
"date_order": "DMY",
"january": [
"janúar",
"jan"
],
"february": [
"febrúar",
"feb"
],
"march": [
"mars",
"mar"
],
"april": [
"apríl",
"apr"
],
"may": [
"maí... |
# testlist_comp
# : (test | star_expr) (comp_for | (COMMA (test | star_expr))* COMMA?)
# ;
# test
[x]
# star_expr comp_for
[z for z in a]
# test COMMA star_expr COMMA
[x, *a,]
# star_expr COMMA test COMMA star_expr
[*u, a, *i]
|
"""Errors not related to the Telegram API itself"""
class ReadCancelledError(Exception):
"""Occurs when a read operation was cancelled."""
def __init__(self):
super().__init__(self, 'The read operation was cancelled.')
class TypeNotFoundError(Exception):
"""
Occurs when a type is not found, ... |
def foo(x):
return 1/x
def zoo(x):
res = foo(x)
return res
print(zoo(0))
|
# Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
# A) Quantas vezes apareceu o valor 9.
# B) Em que posição foi digitado o primeiro valor 3.
# C) Quais foram os números pares.
numero = (int(input('Digite o 1º número: ')),
int(input('Digite o 2º número... |
# Email Configuration
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'bob@bobmail.com'
EMAIL_HOST_PASSWORD = 'bob'
EMAIL_USE_TLS = True
|
self.description = "dir->symlink change during package upgrade (conflict)"
p1 = pmpkg("pkg1", "1.0-1")
p1.files = ["test/",
"test/file1",
"test/dir/file1",
"test/dir/file2"]
self.addpkg2db("local", p1)
p2 = pmpkg("pkg2")
p2.files = ["test/dir/file3"]
self.addpkg2db("local", p2)
p3... |
# __about__.py
#
# Copyright (C) 2006-2020 wolfSSL Inc.
#
# This file is part of wolfSSL.
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any ... |
class Notifier:
def __init__(self, transporter):
self.transporter = transporter
def log(self, s):
self.transporter.send('logs', s)
def error(self, message, stack):
self.transporter.send('process:exception', {
'message': message,
'stack': stack
})
|
# sub_tasks_no_name.py
data_sets = ['Tmean', 'Sunshine']
def task_reformat_data():
"""Reformats all raw files for easier analysis"""
for data_type in data_sets:
yield {
'actions': ['python reformat_weather_data.py %(dependencies)s > %(targets)s'],
'file_dep': ['UK_... |
def isPalindrome(s):
"""
:type s: str
:rtype: bool
"""
s = "".join([i.lower() for i in s if i.isalnum()])
if len(s) == 0:
return True
count = -1
for i in range(len(s)):
if s[i] == s[count]:
count -= 1
else:
return False
re... |
class Registry:
def __init__(self):
self._registered_methods = {}
def namespaces(self):
return list(self._registered_methods)
def methods(self, *namespace_path):
return self._registered_methods[namespace_path]
def clear(self):
self._registered_methods = {}
def reg... |
#Crie um programa que leia a idade e o sexo de várias pessoas.
#A cada pessoa cadastrada, o programa deverá perguntar se o usuário
#quer ou não continuar. No final, mostre:
#A) - Quantas pessoas são maiores de 18 anos
#B) - Quantos homens foram cadastrados
#C) - Quantas mulheres tem menos de 20 anos
maiores = homens = ... |
class AppRoutes:
def __init__(self) -> None:
self.prefix = "/api"
self.users_sign_ups = "/api/users/sign-ups"
self.auth_token = "/api/auth/token"
self.auth_token_long = "/api/auth/token/long"
self.auth_refresh = "/api/auth/refresh"
self.users = "/api/users"
s... |
release_major = 2
release_minor = 3
release_patch = 0
release_so_abi_rev = 2
# These are set by the distribution script
release_vc_rev = None
release_datestamp = 0
release_type = 'unreleased'
|
# -*- coding: utf-8 -*-
def two_sum(nums, target):
if ((nums is None)
or not isinstance(nums, list)
or len(nums) == 0):
return False
nums.sort()
low, high = 0, len(nums) - 1
while low < high:
total = nums[low] + nums[high]
if total < target:
... |
"""Top-level package for Nexia."""
__version__ = "0.1.0"
ROOT_URL = "https://www.mynexia.com"
MOBILE_URL = f"{ROOT_URL}/mobile"
DEFAULT_DEVICE_NAME = "Home Automation"
PUT_UPDATE_DELAY = 0.5
HOLD_PERMANENT = "permanent_hold"
HOLD_RESUME_SCHEDULE = "run_schedule"
OPERATION_MODE_AUTO = "AUTO"
OPERATION_MODE_COOL = ... |
"""Device capabilities."""
# API Version 1.0.5
DEV_TYPES = {
1: "Washing Machine",
2: "Thumble Dryer",
7: "Dishwasher",
19: "Fridge",
20: "Freezer",
74: "TwoInOne Hob",
}
STATE_CAPABILITIES = {
19: {
"ProgramID",
"status",
"programType",
"targetTemperature"... |
'''
Python program which adds up columns and rows of given table as shown in the specified figure
Input number of rows/columns (0 to exit)
4
Input cell value:
25 69 51 26
68 35 29 54
54 57 45 63
61 68 47 59
Result:
25 69 51 26 171
68 35 29 54 186
54 57 45 63 219
61 68 47 59 235
208 229 172 202 811
Input number of rows/... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 19:29:10 2019
@author: ASUS
"""
#import numpy as np
#def factorial():
# my_array = []
# for i in range(5):
# my_array.append(int(input("Enter number: ")))
# my_array = np.array(my_array)
# print(np.floor(my_array))
#
#factorial()
def factorial... |
# Set up the winner variable to hold None
winner = None
print('winner:', winner)
print('winner is None:', winner is None)
print('winner is not None:', winner is not None)
print(type(winner))
# Now set winner to be True
print('Set winner to True')
winner = True
print('winner:', winner)
print('winner is None:', winner i... |
# This should cover all the syntactical constructs that we hope to support
# Intended sources should be the variable `SOURCE` and intended sinks should be
# arguments to the function `SINK` (see python/ql/test/experimental/dataflow/testConfig.qll).
#
# Functions whose name ends with "_with_local_flow" will also be test... |
'''
@Description:
@Author: 妄想
@Date: 2020-06-23 13:27:00
@LastEditTime: 2020-06-25 14:42:17
@LastEditors: 妄想
'''
# -*- coding: utf-8 -*-
# Scrapy settings for myspider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the docume... |
n = int(input())
prime=0
for i in range(n-1,0,-1):
if i==2:
prime = i
elif(i>2):
st=True
for j in range(2,int(n**0.5)+1):
if(i%j==0):
st=False
break
if(st):
prime = i
break
s_prime=0
for i in range(n+1,n+(n... |
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', 'Cherokee', 'Trailhawk', 'Trackhawk']
}
def get_al... |
"""
Entradas
Salario-->float-->s
Ventas_1-->float-->v1
Ventas_2-->float-->v2
Ventas_3-->float-->v3
Salidas
Total_1-->float-->t1
Total_2-->float-->t2
Total_3-->float-->t3
"""
s=float(input("Ingrese su salario bruto: "))
v1=float(input("Ingrese las ventas del departamento 1: "))
v2=float(input("Ingrese las ventas del dep... |
version_defaults = {
'param_keys': {
'grid5': ['accrate', 'x', 'z', 'qb', 'mass'],
'synth5': ['accrate', 'x', 'z', 'qb', 'mass'],
'grid6': ['accrate', 'x', 'z', 'qb', 'mass'],
'he1': ['accrate', 'x', 'z', 'qb', 'mass'],
'he2': ['accrate', 'qb'],
},
'bprops': {
... |
fname = input("Enter file name: ")
try:
fhand = open(fname)
except:
print('Something wrong with the file')
for line in fhand:
print((line.upper()).rstrip()) |
# -*- coding: utf-8 -*-
def ULongToHexHash(long: int):
buffer = [None] * 8
buffer[0] = (long >> 56).to_bytes(28,byteorder='little').hex()[:2]
buffer[1] = (long >> 48).to_bytes(28,byteorder='little').hex()[:2]
buffer[2] = (long >> 40).to_bytes(28,byteorder='little').hex()[:2]
buffer[3] = (long >> 32)... |
def hide_spines(ax, positions=["top", "right"]):
"""
Pass a matplotlib axis and list of positions with spines to be removed
args:
ax: Matplotlib axis object
positions: Python list e.g. ['top', 'bottom']
"""
assert isinstance(positions, list), "Position must be passed ... |
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result_len = 0
result_str = ''
if len(strs) == 1:
return strs[0]
# get the smallest str
min_len = None
smalles... |
"""Top-level package for Freud API Crawler."""
__author__ = """Peter Andorfer"""
__email__ = 'peter.andorfer@oeaw.ac.at'
__version__ = '0.19.0'
|
expected_output = {
"peer_type": {
"vbond": {
"downtime": {
"2021-12-15T04:19:41+0000": {
"domain_id": "0",
"local_color": "gold",
"local_error": "DCONFAIL",
"peer_organization": "",
... |
map = {'corridor':['room1','','','room2'],'room1':['','','corridor',''],'room2':['','corridor','','']}
commands = {'room1':room1,'room2':room2,'corridor':corridor}
def Moving(location):
rooms = map[location]
directions = ['North','East','South','West']
availableDirections = [directions[i] for i,j in enume... |
"""
https://edabit.com/challenge/2jcxK7gpn6Z474kjz
Casino Security
You're head of security at a casino that has money being stolen from it. You get the data in the form of strings and you have to set off an alarm if a thief is detected.
If there is no guard between thief and money, return "ALARM!"
If the money is pro... |
# -*- coding:utf-8 -*-
"""
OOP: Object-Oriented Programming/Paradigm
3 main characteristics:
* Encapsulation: Scope of data is limited to the Object
* Inheritance: Object fields can be implicitly used in extended classes
* Polymorphism: Same name can have different signatures
"""
# ###########################... |
def fence_pattern(rails, message_size):
pass
def encode(rails, message):
pass
def decode(rails, encoded_message):
pass
|
# python3
def last_digit_of_fibonacci_number_naive(n):
assert 0 <= n <= 10 ** 7
if n <= 1:
return n
return (last_digit_of_fibonacci_number_naive(n - 1) + last_digit_of_fibonacci_number_naive(n - 2)) % 10
def last_digit_of_fibonacci_number(n):
assert 0 <= n <= 10 ** 7
if (n < 2):
... |
"""
A python program for Dijkstra's single source shortest path algorithm.
The program is for adjacency list representation of the graph
"""
# Function that implements Dijkstra's single source shortest path algorithm
# for a graph represented using adjacency list representation
def dijkstra(N, graph, src):
S = lis... |
# From pep-0318 examples:
# https://www.python.org/dev/peps/pep-0318/#examples
def accepts(*types):
def check_accepts(f):
assert len(types) == f.func_code.co_argcount
def new_f(*args, **kwds):
for (a, t) in zip(args, types):
assert isinstance(a, t), "arg %r does not ma... |
# coding=utf-8
#
# @lc app=leetcode id=43 lang=python
#
# [43] Multiply Strings
#
# https://leetcode.com/problems/multiply-strings/description/
#
# algorithms
# Medium (29.97%)
# Likes: 1015
# Dislikes: 472
# Total Accepted: 205.7K
# Total Submissions: 666.4K
# Testcase Example: '"2"\n"3"'
#
# Given two non-nega... |
# -*- coding: utf-8 -*-
"""
669. Trim a Binary Search Tree
Given the root of a binary search tree and the lowest and highest boundaries as low and high,
trim the tree so that all its elements lies in [low, high].
Trimming the tree should not change the relative structure of the elements that will remain in the tree
(i... |
historical_yrs = [i + 14 for i in range(6)]
future_yrs = [5*i + 20 for i in range(7)]
cities = {
'NR':
{
'Delhi': (28.620198, 77.207953),
'Jaipur': (26.913310, 75.800162),
'Lucknow': (26.850000, 80.949997),
'Kanpur': (26.460681, 80.313318),
'Ghaz... |
port="COM3"
#
if ('virtual' in globals() and virtual):
virtualArduino = Runtime.start("virtualArduino", "VirtualArduino")
virtualArduino.connect(port)
ard = Runtime.createAndStart("Arduino","Arduino")
ard.connect(port)
#
i2cmux = Runtime.createAndStart("i2cMux","I2cMux")
# From version 1.0.2316 use attach inste... |
READ_ONLY_FS = 'Операции записи на диск запрещены'
TIMEOUT = 'Превышен лимит времени на выполнение программы'
CHECKER_ERROR = 'Возникла ошибка при проверке результата работы программы'
NEED_CONSOLE_INPUT = 'Указажите входные данные'
|
"""
looks for parameter values that are reflected in the response.
Author: maradrianbelen.com
The scan function will be called for request/response made via ZAP, excluding some of the automated tools
Passive scan rules should not make any requests
Note that new passive scripts will initially be disabled
Right click th... |
#
# PySNMP MIB module NBS-CMMCENUM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-CMMCENUM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:17:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
#! /usr/bin/env python3
'''A library of functions for our cool app'''
def add(a, b):
return a + b
def add1(a):
return a - 1
def sub1(a):
pass
|
def test_ports(api, utils):
"""Demonstrates adding ports to a configuration and setting the
configuration on the traffic generator.
The traffic generator should have no items configured other than
the ports in this test.
"""
tx_port = utils.settings.ports[0]
rx_port = utils.settings.ports[1... |
"""
39 / 39 test cases passed.
Runtime: 340 ms
Memory Usage: 34.7 MB
"""
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
graph = [[] for _ in range(n)]
for i in range(n):
id = manager[i]
if id != -1:
... |
'''21 - Faça um Programa para um caixa eletrônico.
O programa deverá perguntar ao usuário a valor do saque e depois informar quantas notas de cada valor serão fornecidas.
As notas disponíveis serão as de 1, 5, 10, 50 e 100 reais.
O valor mínimo é de 10 reais e o máximo de 600 reais.
O programa não deve se preocupar com... |
# V0
# IDEA : DP
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for k in range(i):
... |
#
# PySNMP MIB module LANART-AGENT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LANART-AGENT
# Produced by pysmi-0.3.4 at Mon Apr 29 19:54:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
class PoolUserConfiguration:
def __init__(self,
pool_name: str,
username: str,
password: str):
self.pool_name = pool_name
self.username = username
self.password = password
def __eq__(self, other):
if not isinstance(other, PoolU... |
if not ( ( 'a' in vars() or 'a' in globals() ) and type(a) == type(0) ):
print("no suitable a")
else:
print("good to go")
|
# coding: utf-8
def boo():
a = '这是导入的自定义模块'
print(a)
return a |
"""
0147. Insertion Sort List
Medium
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
... |
#!/usr/bin/python3
'''
Usando no gerador de html v5
**kwargs
Unpacking de dicionario, passando o dicionario e
desempacotanto ele
Criado exercicio inverso com o nome packing_nomeado
'''
def resultado_f1(primeiro, segundo, terceiro):
print(f'1) {primeiro}')
print(f'2) {segundo}')
print(f'3) {terceiro}')
... |
# Part of the awpa package: https://github.com/pyga/awpa
# See LICENSE for copyright.
"""Token constants (from "token.h")."""
# This file is automatically generated; please don't muck it up!
#
# To update the symbols in this file, 'cd' to the top directory of
# the python source tree after building the interpreter... |
'''
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contai... |
class Node:
"""
Class that represent a tile or node in a senku game.
...
Attributes
----------
"""
def __init__(self, matrix):
self.step = 0 # The step or node geneared
self.parent_id = 0 # The Node parent id
self.name = f'Node: {str(self.step)}!' # Node... |
#計算用関数
def subset_sum(d,numbers, target, partial=[]): #d,numbers(1からnまでの値のリスト),target(合計x),partial(取り出した値の組み合わせリスト)
s = sum(partial) #取り出した組み合わせの合計を求める
result = "" #結果出漁用変数初期化
# 組み合わせの合計(s)がtarget(xの値)と等しいかどうかを確認
if s == target:
if len(partial) == d: #組み合わせの内、dの数の組み合わせのみ出力
for i in r... |
l = [0,1,2,3,4,5,6,7,8,9,]
def f(x):
return x**2
print(list(map(f,l)))
def fake_map(function,list):
list_new = []
for n in list:
i = function(n)
list_new.append(i)
return list_new
print(fake_map(f,l))
|
working = True
match working:
case True:
print("OK")
case False:
print() |
"""
tdc_helper.py - tdc helper functions
Copyright (C) 2017 Lucas Bates <lucasb@mojatatu.com>
"""
def get_categorized_testlist(alltests, ucat):
""" Sort the master test list into categories. """
testcases = dict()
for category in ucat:
testcases[category] = list(filter(lambda x: category in x['ca... |
def test_scout_tumor_normal(invoke_cli, tumor_normal_config):
# GIVEN a tumor-normal config file
# WHEN running analysis
result = invoke_cli([
'plugins', 'scout', '--sample-config', tumor_normal_config,
'--customer-id', 'cust000'
])
# THEN it should run without any error
print(r... |
'''
# Copyright (C) 2020 by ZestIOT. All rights reserved. The
# information in this document is the property of ZestIOT. Except
# as specifically authorized in writing by ZestIOT, the receiver
# of this document shall keep the information contained herein
# confidential and shall protect the same in whole or ... |
# funcs01.py
def test_para_02(l1: list ):
l1.append(42)
def test_para(a: int, b: int, c: int = 10 ):
print("*"*34, "test_para", "*"*35)
print("Parameter a: ", a)
print("Parameter b: ", b)
print("Parameter c: ", c)
print("*"*80, "\n")
x: int = 10
y = 12
z = 13
test_para(x, y, z)
print("x: ... |
"""
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
"""... |
##
## This file is maintained by Ansible - CHANGES WILL BE OVERWRITTEN
##
USERS = (
'nate@bx.psu.edu',
'clements@galaxyproject.org',
'outreach@galaxyproject.org'
)
NORM_USERS = [ u.lower() for u in USERS ]
def dynamic_normal_reserved( user_email ):
if user_email is not None and user_email.lower() in ... |
# Game
GAME_NAME = 'Pong-v0'
# Preprocessing
STACK_SIZE = 4
FRAME_H = 84
FRAME_W = 84
# Model
STATE_SHAPE = [FRAME_H, FRAME_W, STACK_SIZE]
# Training
NUM_EPISODES = 2500
# Discount factor
GAMMA = 0.99
# RMSProp
LEARNING_RATE = 2.5e-4
# Save the model every 50 episodes
SAVE_EVERY = 50
SAVE_PATH = './checkpoints' |
SECRET_KEY = 'dev'
SQLALCHEMY_DATABASE_URI = 'postgresql:///sopy'
SQLALCHEMY_TRACK_MODIFICATIONS = False
ALEMBIC_CONTEXT = {
'compare_type': True,
'compare_server_default': True,
'user_module_prefix': 'user',
}
# Set the following in <app.instance_path>/config.py
# On dev that's <project>/instance/config... |
class Tagger(object):
tags = []
def __call__(self, tokens):
raise NotImplementedError
def check_tag(self, tag):
return tag in self.tags
class PassTagger(Tagger):
def __call__(self, tokens):
for token in tokens:
yield token
class TaggersComposition(Tagger):
... |
sys.stdout = open("3-letter.txt", "w")
data = "abcdefghijklmnopqrstuvwxyz"
data += data.upper()
for a in data:
for b in data:
for c in data:
print(a+b+c)
sys.stdout.close()
|
# date: 17/07/2020
# Description:
# Given a set of words,
# find all words that are concatenations of other words in the set.
class Solution(object):
def findAllConcatenatedWords(self, words):
seen = []
wrds = []
for i,a in enumerate(words):
for j,b in enumerate(... |
#定义简单加减乘除函数
def add(x, y):
return (x + y)
def subtract(x, y):
return(x -y)
def multipy(x, y):
return(x * y)
def devide(x, y):
return(x / y)
print('请选择想要进行的运算:')
print('1.相加')
print('2.相减')
print('3.相乘')
print('4.相除')
i = int(input('请选择需要进行的运算:'))
num1 = float(input('请输入第一个数:'))
num2 = float(input(... |
# iterators/iterator.py
class OddEven:
def __init__(self, data):
self._data = data
self.indexes = (list(range(0, len(data), 2)) +
list(range(1, len(data), 2)))
def __iter__(self):
return self
def __next__(self):
if self.indexes:
return s... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# Scratch buffer slice with manual indexing
class BufferSlice:
def __init__(self, buf, name):
self.name = name
self.buf = buf
self.offset = -1 # Offset into the global scratch buffer
self.chunks = []
# Ret... |
# Generated by h2py from stdin
TCS_MULTILINE = 0x0200
CBRS_ALIGN_LEFT = 0x1000
CBRS_ALIGN_TOP = 0x2000
CBRS_ALIGN_RIGHT = 0x4000
CBRS_ALIGN_BOTTOM = 0x8000
CBRS_ALIGN_ANY = 0xF000
CBRS_BORDER_LEFT = 0x0100
CBRS_BORDER_TOP = 0x0200
CBRS_BORDER_RIGHT = 0x0400
CBRS_BORDER_BOTTOM = 0x0800
CBRS_BORDER_ANY = 0x0F0... |
"""Remove Dups: Write code to remove duplicates from an unsorted linked list."""
def remove_dups(linked_list):
"""Remove duplicates from a linked list."""
prev_node = None
curr_node = linked_list.head
vals_seen = set()
while curr_node:
if curr_node.val in vals_seen:
prev_node.n... |
x = 1
if x == 1:
# indented four spaces
print("Hello World")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.