content stringlengths 7 1.05M |
|---|
# 24. Swap Nodes in Pairs
'''
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Input: 1->2->3->4,
Output: 2->1->4->3.
'''
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
current = h... |
def encrypt_letter(msg, key):
enc_id = (ord(msg) + ord(key)) % 1114112
return chr(enc_id)
def decrypt_letter(msg, key):
dec_id = (1114112 + ord(msg) - ord(key)) % 1114112
return chr(dec_id)
def process_message(message, key, encrypt):
returned_message = ""
for i, letter in enumerate(message)... |
#MaBe
sexo = input("Digite seu sexo: [M/F] ").strip().upper()
while sexo not in "FM":
sexo = input("Dado inválido! Por favor, informe seu sexo: ").strip().upper()
print("Sexo {} registrado com sucesso!".format(sexo))
|
class Ticket():
def __init__(self,weekend=False,child=False):
self.price=100
#假如是周末,加收20%,非周末不加收
if weekend:
self.extra=1.2
else:
self.extra=1
#假如是小孩,打五折,成人不打折
if child:
self.discount=0.5
else:
self.discount=1
... |
def pre_save_operation(instance):
# If this is a new record, then someone has started it in the Admin using EITHER a legacy COVE ID
# OR a PBSMM UUID. Depending on which, the retrieval endpoint is slightly different, so this sets
# the appropriate URL to access.
if instance.pk is None:
if in... |
t = int(input().strip())
result = 0
current_time, current_value = 1, 3
def get_next_interval_cycle(time, value):
next_time = time + value
next_value = value * 2
return next_time, next_value
while True:
new_time, new_value = get_next_interval_cycle(
current_time,
current_value
... |
def acmTeam(topic):
maxtopic, maxteam = 0, 1
for i in range(n):
for j in range(i+1, n):
know = 0
for x in range(m):
if topic[i][x] == '1' or topic[j][x] == '1':
know += 1
if know > maxtopic:
maxtopic = know
... |
# flake8: noqa
# tor ref src\app\config\auth_dirs.inc
AUTHORITY_DIRS = """
"moria1 orport=9101 "
"v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
"128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
"tor26 orport=443 "
"v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
"ipv6=[2001:858:2:2:... |
def make_readable(seconds):
if seconds >= 0 and seconds <= 359999:
hrs = seconds // 3600
seconds %= 3600
mins = seconds // 60
seconds %= 60
secs = seconds
hour = str('{:02d}'.format(hrs))
minute = str('{:02d}'.format(mins))
second = str('{:02d}'.format... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Giraph(MavenPackage):
"""Apache Giraph is an iterative graph processing system built
for high scalability."... |
"""
Contains config variables unique to the user.
Copy this file to config.py and make any necessary changes.
"""
PYTHON_COMMAND = "python"
|
"""# `//ll:ll.bzl`
Rules for building C/C++ with an upstream LLVM/Clang toolchain.
Build files should import these rules via `@rules_ll//ll:defs.bzl`.
"""
load("//ll:providers.bzl", "LlCompilationDatabaseFragmentsInfo", "LlInfo")
load(
"//ll:internal_functions.bzl",
"resolve_binary_deps",
"resolve_librar... |
epsilon_d_ = {
"epsilon": ["float", "0.03", "0.01 ... 0.3"],
}
distribution_d_ = {
"distribution": ["string", "normal", "normal, laplace, logistic, gumbel"],
}
n_neighbours_d_ = {
"n_neighbours": ["int", "3", "1 ... 10"],
}
p_accept_d_ = {
"p_accept": ["float", "0.1", "0.01 ... 0.3"],
}
repulsion_factor... |
def fatorial(n):
if n == 0:
return 1
else:
return n * fatorial(n - 1)
while True:
try:
entrada = input()
entrada = entrada.split()
fat1 = fatorial(int(entrada[0]))
fat2 = fatorial(int(entrada[1]))
print(fat1 + fat2)
except EOFErro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
元组的使用
笔记:
1、元组在创建时间和占用的空间上面都优于列表。
2、元组中的元素是无法修改的:
如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组;
如果一个方法要返回多个值,使用元组也是不错的选择。
"""
# 定义元组
t = ('关茂柠', 25, True, '广东深圳')
print(t)
# 获取元组中的元素
print(t[0])
print(t[3])
# 遍历元组中的值
for member in t:
print(member)
# t[0] = '王大锤' # TypeError
pri... |
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.end = False
self.size = 0
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
retu... |
# coding=utf-8
"""
This is exceptions used in graph package
"""
class GraphError(Exception):
"""
This is base graph error
"""
pass
class GraphTypeError(GraphError, TypeError):
"""
This error occurs when there is a type mismatch in this package
"""
pass
class GraphExistenceError(G... |
class Database:
def __init__(self, row_counts):
self.row_counts = row_counts
self.max_row_count = max(row_counts)
n_tables = len(row_counts)
self.parents = list(range(n_tables))
def merge(self, src, dst):
src_parent = self.get_parent(src)
dst_parent = self.get_pa... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 clegg <clegg@baratheon>
#
# Distributed under terms of the MIT license.
"""
Gem and Enchant Lookup Tables
"""
"""
To save some API calls we're going to keep this data here. It'll cover most gems.
"""
gem_lookup = {
# Old Gems - N... |
# index_power
# Created by JKChang
# 16/04/2018, 14:49
# Tag:
# Description: You are given an array with positive numbers and a number N. You should find the N-th power of the
# element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first
# element has the index 0.
#
... |
# Find the Most Competitive Subsequence: https://leetcode.com/problems/find-the-most-competitive-subsequence/
# Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.
# An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elem... |
# Copyright (c) 2018 SMHI, Swedish Meteorological and Hydrological Institute
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
================================================================================
============================================================================... |
"""
5. Longest Palindromic Substring
"""
class Solution:
def expand(self, s, left, right):
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left+1:right]
def longestPalindrome(self, s: str) -> str:
len_s = len(s)
... |
# Template 1. preorder DFS
# O(N) / O(H)
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
arr = []
def preorder(node):
if not node:
return
arr.append(node.val)
preorder(node.left)
preorder(node.right)
pr... |
"""
Macro for supporting custom resource set typically defined in Gradle via source sets.
Bazel expects all resources to be in same root `res` directory but Gradle does not have this
limitation. This macro receives directory on file system and copies the required resources to
Bazel compatible `res` folder during build... |
"""Test Forex API"""
def test_forex_api_doc(client):
response = client.get("/api/forex/doc")
assert response.status_code == 200
def test_get_usd_rates(client):
response = client.get("/api/forex/rates/usd", follow_redirects=True)
assert response.status_code == 200
|
with open('artistsfollowed.txt') as af:
with open('/app/tosearch.txt', 'w') as ts:
for line in af:
if 'name' in line:
line = line.strip()
line = line.replace('name: ', '')
line = line.replace('\'', '')
line = line.replace(',', '')
... |
#coding:utf-8
'''
filename:palindrome.py
chap:4
subject:17
conditions:输入一个5位数
solution:判断是否为回文数
'''
number = input('Enter a 5 digits number : ')
if number.isdigit() and len(number) == 5:
if number == number[::-1]:
print(f'{number} is palindrome.')
else:
print(f'{number... |
SUSI_AGAT = "Agát"
SUSI_BLYSKAVICA = "Blýskavica"
SUSI_CIFERSKY_CECH = "Cíferský-cech"
SUSI_COMPETITION_ID = 9
SUSI_OUTDOOR_ROUND_NUMBER = 100
SUSI_AGAT_MAX_COEFFICIENT = 8
# If big hint is public, points won't be deducted for small hint regardless of
# whether it is public or not.
SUSI_POINTS_ALLOCATION = (
6, ... |
class Evaluator:
""" A superclass for metrics evaluations"""
def __init__(self, qp_ens):
"""Class constructor.
Parameters
----------
qp_ens: qp.Ensemble object
PDFs as qp.Ensemble
"""
self._qp_ens = qp_ens
def evaluate(self): #pragma: no cover
... |
'''a Python program to print out a set containing all the colors from color_list_1
which are not present in color_list_2'''
def main():
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print("Original set elements:")
print(color_list_1)
print(color_list_2)
pr... |
input = [
('Mamma Mia', ['ABBA']),
('Ghost Rule', ['DECO*27', 'Hatsune Miku']),
('Animals', ['Martin Garrix']),
('Remember The Name', ['Ed Sheeran', 'Eminem', '50 Cent']),
('404 Not Found', [])
]
def songTitle(song):
artists = ''
if len(song[1]) > 1:
for artist in range(len(song[1]... |
class FluidAudioDriver():
''' Represents the FluidSynth audio driver object as defined in audio.h.
This class is inspired by the FluidAudioDriver object from pyfluidsynth by MostAwesomeDude.
Member:
audio_driver -- The FluidSynth audio driver object (fluid_audio_driver_t).
handle -- The handle... |
class Writer:
def __init__(self, outfile):
self.outfile = outfile
def writeHeader(self):
pass
def write(self, record):
pass
def writeFooter(self):
pass
|
"""
Pyformlang
==========
Pyformlang is a python module to perform operation on formal languages.
How to use the documentation
----------------------------
Documentation is available in two formats: docstrings directly
in the code and a readthedocs website: https://pyformlang.readthedocs.io.
Available subpackages
-----... |
def b2tc(number: int):
"""
Funcion devuelve el complemento de un numero entero el cual se define como "inversion de todos los bits".
:param number: numero entero
:type number: int
:return: cadena conforme a resultado inverso de bit (XOR)
:rtype: str
"""
b2int = int(bin(number)[2:]) # [2... |
a='cdef'
b='ab'
print('a'/'b')
a=8
b='ab'
print('a'/'b')
|
## GroupID-8 (14114002_14114068) - Abhishek Jaisingh & Tarun Kumar
## Date: April 15, 2016
## bitwise_manipulations.py - Bitwise Manipulation Functions for Travelling Salesman Problem
def size(int_type):
length = 0
count = 0
while (int_type):
count += (int_type & 1)
length += 1
int_type >... |
class Solution:
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
result = []
for v in ops:
length = len(result)
if v == '+':
if length >= 2:
result.append(result[length-1] + result[length-2]... |
print("To change the data type of data")
int_data=int(input("Enter the integer data:"))
dec_data=float(input("Enter the decimal data:"))
int_str=str(int_data)
print(int_str)
dec_int=int(dec_data)
print(dec_int)
dec_str=str(dec_data) |
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
preço = float(input('Qual o preço do produto?'))
novo = preço - (preço * 5 / 100)
print('O produto que custava R${:.2f}, na promoção com desconto de 5% vai custar {:.2f}'.format(preço, novo))
|
# Personalizando a representação string de uma classe
class MinhasCores():
def __init__(self):
self.vermelho = 50
self.verde = 75
self.azul = 100
# Use getattr para retornar um valor de forma dinâmica
def __getattr__(self, attr):
if attr == "rgb":
return (self.... |
# Time: O(l)
# Space: O(l)
# Given an integer n, find the closest integer (not including itself), which is a palindrome.
#
# The 'closest' is defined as absolute difference minimized between two integers.
#
# Example 1:
# Input: "123"
# Output: "121"
# Note:
# The input n is a positive integer represented by string, ... |
@dataclass
class Point:
x: int
y: int
z: int
position = property()
@position.setter
def position(self, new_value):
if type(new_value) not in (list, tuple, set):
raise TypeError
elif len(new_value) != 3:
raise ValueError
else:
self.x, ... |
def get_sql_lite_conn_str(db_file: str):
db_file_stripped = db_file.strip()
if not db_file or not db_file_stripped:
# db_file = '../db/meet_app.db'
raise Exception("SQL lite DB file is not specified.")
return 'sqlite:///' + db_file_stripped |
# -*- coding: utf-8 -*-
__author__ = """Juan Eiros"""
__email__ = 'jeirosz@gmail.com'
|
# definitions used
# constants
DE = 'DE'
# variables
qhLen = None # number of rows of the quarter of an hour output vector (4 each hour)
header = None
zones = None
dataImport = None
dataExport = None
sumImport = None
sumExport = None
data = None
# output file names
output_file_name = 'GenerationAndLoad.csv'
# c... |
class IteratorBase(object):
"""Базовый класс итератора"""
def first(self):
"""Возвращает первый элемент коллекции.
Если элемента не существует возбуждается исключение IndexError."""
raise NotImplementedError()
def last(self):
"""Возвращает последний элемент коллекции.
... |
class StructureObject:
def __init__(self, name="", dir=""):
self.name = name
self.dir = dir
def getName(self): return self.name
def getDir(self): return self.dir
def getType(self): return type(self) |
def dbl_linear(n):
u = [1]
def func(nums):
global fin
new_nums = []
for i in nums:
new_nums.append(2 * i + 1)
new_nums.append(3 * i + 1)
u.extend(new_nums)
if len(u) > n*12:
fin = list(sorted(set(u)))
else:
... |
def write(filename, content):
with open(filename, 'w') as file_object:
file_object.write(content)
def appendWrite(filename, content):
with open(filename, 'a') as file_object:
file_object.write(content)
|
# Copyright (c) 2021 Qianyun, Inc. All rights reserved.
# smartx
SMARTX_INSTANCE_STATE_STOPPED = 'stopped'
|
print('Bem vindo ao conversor de medidas')
nome = input('Digite seu nome: ')
m = float(input('Digite sua altura em metros: '))
print('{} sua altura em centimetros é de {}cm,\n e em '
'milimetros é de {}mm'.format(nome,m*100,m*1000))
|
for i in range (6):
for j in range (7):
if (i==0 and j %3!=0) or (i==1 and j % 3==0) or (i-j==2) or (i+j==8):
print("*",end=" ")
else:
print(end=" ")
print()
|
A, B, K = map(int, input().split())
if A >= K:
A -= K
print(A, B)
else:
A, B = 0, max(0, B - (K - A))
print(A, B)
|
lista=[]
def main():
n = int(input("Digite o número de ímpares que você deseja saber!!!: "))
x = 0
z = 0
while x < (n):
z = z + 1
if z % 2 != 0:
x = x + 1
print(z)
global lista
lista.append(z)
|
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
carry = 0
for i in range(len(digits) - 1, -1, -1):
if i == len(digits) - 1:
digits[i] += 1
else:
digits[i] = digits[i] + carry
if digits[i] == 10:
di... |
def close(n, smallest=10, d=10):
""" A sequence is near increasing if each element but the last two is smaller than all elements
following its subsequent element. That is, element i must be smaller than elements i + 2, i + 3, i + 4, etc.
Implement close, which takes a non-negative integer n and returns the... |
#!/usr/bin/env python3
charlimit = 450
def isChan(chan, checkprefix):
if not chan:
return False
elif chan.startswith("#"):
return True
elif checkprefix and len(chan) >= 2 and not chan[0].isalnum() and chan[1] == "#":
return True
else:
return False
|
__title__ = 'MongoFlask'
__description__ = 'A Python Flask library for connecting a MongoDB instance to a Flask application'
__url__ = 'https://github.com/juanmanuel96/mongo-flask'
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__)
__author__ = 'Juan Vazquez'
__py_version__ = 3
|
JournalFame = {"4" : 1200,
"5" : 2400,
"6" : 4800,
"7" : 9600,
"8" : 19200}
FameGenerated = {"4": {"2Hweapon":720, "1Hweapon":540, "BigArmor":360, "SmallArmor":180},
"5": {"2Hweapon":2880, "1Hweapon":2160, "BigArmor":1440, "SmallArmor"... |
# -*- coding: utf-8 -*-
# Copyright 2017 Vector Creations Ltd
#
# 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 applica... |
class ExtraException(Exception):
def __init__(self, message: str = None, **kwargs):
if message:
self.message = message
self.extra = kwargs
super().__init__(message, kwargs)
def __str__(self) -> str:
return self.message
class PackageNotFoundError(ExtraException, L... |
class Solution:
# @param A : list of integers
# @return an integer
'''
Facebook Codelab
No hints or solutions needed
N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of ... |
def main():
recursion()
def recursion():
count = [0]
num = b(5, 2, count)
print(num)
# print(sum(count))
print(count[0])
def b(n, k, count):
# count.append(1) ## count the number of stack frame
count[0] += 1
if k == 0 or k == n:
print('Base Case!')
return 2
else:
return b(n-1... |
#
# @lc app=leetcode.cn id=547 lang=python3
#
# [547] friend-circles
#
None
# @lc code=end |
"""
Memoization decorator.
"""
def memoize(f):
memos = {}
def memoized(*args):
if args not in memos: memos[args] = f(*args)
return memos[args]
return memoized
|
class CaseInsensitiveKey( object ):
def __init__( self, key ):
self.key = key
def __hash__( self ):
return hash( self.key.lower() )
def __eq__( self, other ):
return self.key.lower() == other.key.lower()
def __str__( self ):
return self.key
GROK_PATTERN_CONF = dict()
# B... |
class ValueResolver:
def resolve(self, value):
if value.kind() == "id":
string = self._resolve_id_value(value)
elif value.kind() == "node":
string = f"Node({self.resolve(value.value)}.value)"
elif value.kind() == "arc":
string = f"Arc({self.resolve(value.s... |
""" Module docstring """
def _write_file_impl(ctx):
f = ctx.actions.declare_file("out.txt")
ctx.actions.write(f, "contents")
write_file = rule(
attrs = {},
implementation = _write_file_impl,
)
|
########################
### Feature combine ###
########################
#Combine Units:
df_tcad = merge_extraction(dfs=[df_tcad,df_units,gdf_16],val=['dba','type1','units','low','high','units_from_type','est_from_type','shape_area'])
replace_nan(df_tcad,['units_x','units_y','low','high'],val=0,reverse=True)
#Don't f... |
exports = {
"name": "Earth",
"aspects": {
"amulets": [
{
"item": "scholar",
"effect": "health",
"description": "Into the earth is the answer. "
"Into the earth lies existance. "
"In... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyCarputils(PythonPackage):
"""The carputils framework for running simulations with the openCARP software."""
... |
def perfect_number(number):
printing = "It's not so perfect."
checker = number
nums = 0
proper_devisors_sum = 0
for num in range(1, int(checker)):
if int(checker) % num == 0:
nums += int(num)
if nums == int(checker):
printing = "We have a perfect number!"
return p... |
class Car:
"""Defining a car with a class"""
def __init__(self, tillverkare, modell, year):
"""Initialisera delar som beskriver en bil"""
self.tillverkare = tillverkare
self.modell = modell
self.year = year
self.mil_tal = 230
def get_descriptive_name(self):
"... |
# Get all available modules
# help("modules")
module_names = [ "micropython", "uhashlib", "uselect", "_onewire", "sys", "uheapq", "ustruct", "builtins", "uarray", "uio", "utime", "cmath", "ubinascii", "ujson", "utimeq", "firmware", "ubluetooth", "umachine", "uzlib", "gc", "ucollections", "uos", "hub", "uctypes", "urand... |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Summary Functions\n",
"\n",
"def get_summ_combined_county_annual(state, county = '',verification = True, key = 'WaPo'):\n",
" '''(str(two letter abbreviation), str, bool, str) ... |
# -*- coding: utf-8 -*-
def ventilation_rates(
number_of_chimneys_main_heating,
number_of_chimneys_secondary_heating,
number_of_chimneys_other,
number_of_open_flues_main_heating,
number_of_open_flues_secondary_heating,
number_of_open_flues_other,
number_of_interm... |
# -*- coding: utf-8 -*-
class ProxyMiddleware(object):
def __init__(self, proxy_url):
self.proxy_url = proxy_url
def process_request(self, request, spider):
request.meta['proxy'] = self.proxy_url
@classmethod
def from_crawler(cls, crawler):
return cls(
proxy_url=c... |
if 5 == 2:
print("aaaa")
print("sjjdjdd")
else :
print("else")
|
n = int(input())
print('*' * (2*n+1))
print('.' + '*' + ' ' * (2*n - 3) + '*' + '.')
for i in range(1, n-1):
print('.' + '.' * i + '*' + '@' * ((2*n-3) -2*i) + '*' + '.' * i + '.')
print('.' * n +'*' + '.' * n)
for i in range(1, n-1):
print('.' * ((n)-i) + '*' + ' ' * (i-1) + '@' + ' ' * (i-1) + '*' + '.' * ... |
""" 03 - Crie um script Python que leia dois números e tente mostrar a soma entre eles."""
print('=' * 6, ' DESAFIO 03 - SOMANDO DOIS NÚMEROS ', '=' * 6)
print('\n*** MODO QUE VAI DAR RUIM ***')
n1 = input('Digite um número: ')
n2 = input('Digite mais um número: ')
s = n1 + n2
print(f'A soma entre {n1} e {n2} é {s}.')... |
class Enum:
def __init__(self,list):
self.list = list
def enume(self):
for index, val in enumerate(self.list,start=1):
print(index,val)
e1 = Enum([5,15,45,4,53])
e1.enume() |
# -*- coding: utf-8 -*-
# Copyright 2016 CloudFlare, Inc. All rights reserved.
#
# The contents of this file are 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... |
"""Module defining linked list."""
class LinkedList(object):
"""Classic linked list data structure."""
def __init__(self, iterable=None):
"""Initialize LinkedList instance."""
self.head = None
self._length = 0
try:
for el in iterable:
self.push(el)
... |
class UserState(object):
def __init__(self, user_id):
self.user_id = user_id
self.conversation_context = {}
self.conversation_started = False
self.user = None
self.ingredient_cuisine = None
self.recipe = None
|
class Solution:
def findKthNumber(self, n: int, k: int) -> int:
cur = 1
k -= 1
while k > 0:
step, first, last = 0, cur, cur + 1
while first <= n:
step += min(last, n + 1) - first
first *= 10
last *= 10
if ... |
mylines = []
with open('resume.txt', 'rt') as myfile:
for myline in myfile:
mylines.append(myline)
print("Name: ", end="")
for c in mylines[0]:
if c == "|":
break;
else:
print(c, end="")
|
"""
https://leetcode.com/problems/next-permutation/
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-pl... |
""" examples package.
Author:
- 2020-2021 Nicola Creati
- 2020-2021 Roberto Vidmar
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
2020-2021 Roberto Vidmar <rvidmar@inogs.it>
License:
MIT/X11 License (see
:download:`l... |
class Interaction:
current_os = -1
logger = None
def __init__(self, current_os, logger):
self.current_os = current_os
self.logger = logger
def print_info(self):
self.logger.raw("This is interaction with Maya")
# framework interactions
def schema_item_double_click(self,... |
class GameObject:
# this is a generic object: the player, a monster, an item, the stairs...
# it's always represented by a character on screen.
def __init__(self, x, y, char, color):
self.x = x
self.y = y
self.char = char
self.color = color
def move(self, dx, dy, tile_m... |
dados = {'nome':'Pedro', 'idade':25}
dados['sexo'] = 'M'
print(dados.values())
print(dados.keys())
print('-=' * 30)
for k, v in dados.items():
print(f'O {k} é {v}') |
# coding:utf-8
'''
Created on 2013-11-27
@author: tong
'''
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()
]
# 制作一个顺序编码, lastno 上一位, prestr 前缀, dig 编码位数
d... |
class Institution(object):
institution_name = None
website = None
industry = None
type = None
headquarters = None
company_size = None
founded = None
def __init__(self, name=None, website=None, industry=None, type=None, headquarters=None, company_size=None, founded=None):
self.n... |
numero = int(input('Escreva um número inteiro: '))
i = 1
print('-' * 15)
print('Tabuada de', numero)
print('-' * 15)
while i < 11:
resultado = numero * i
print('{} * {} = {}'.format(numero, i, resultado))
i = i + 1
|
class Num2WordsAr(object):
def __init__(self) -> None:
super().__init__()
self.table_scales = ["", "ألف", "مليون", "مليار", "ترليون", "كوادرليون", "كوينتليون", "سكستليون"]
self.table_scales_p = ["", "آلاف", "ملايين", "مليارات"]
self.table_female = ["", "واحدة", "اثنتان", "ثلاثة", "أر... |
class NoSuchPointError(ValueError):
pass
class Point(tuple):
"""
A point on an elliptic curve. This is a subclass of tuple (forced to a 2-tuple),
and also includes a reference to the underlying Curve.
"""
def __new__(self, x, y, curve):
return tuple.__new__(self, (x, y))
def __in... |
#!/usr/bin/env python3
def insertion_sort(lst): #times
for i in range(1,len(lst)): #n - 1
while i > 0 and lst[i-1] > lst[i]: #(n - 1)n
lst[i], lst[i-1] = lst[i-1], lst[i] #(n - 1)n/2
... |
"""
sp_tool package
Sub-Packages are
* sharepoint - the core library
* tool - the frontend tool
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.