content stringlengths 7 1.05M |
|---|
def insertData(db):
db.insert("RESTRICTION",('Titanic',1997,'M','Australia'))
db.insert("RESTRICTION",('Titanic',1997,'KT','Belgium'))
db.insert("RESTRICTION",('Titanic',1997,'TE','Chile'))
db.insert("RESTRICTION",('Titanic',1997,'K-12','Finland'))
db.insert("RESTRICTION",('Titanic',1997,'U','France... |
model = """# Stochastic Simulation Algorithm input format
R1:
$pool > TF
kTFsyn
R2:
TF > $pool
kTFdeg*TF
R3:
TFactive > $pool
kTFdeg*TFactive
R4:
TF > TFactive
kActivate*TF
R5:
TFactive > TF
kInactivate*TFactive
R6:
TFactive > mRNA + TFactive
kmRNAsyn*(TFactive/(TFact... |
class Solution:
def assignBikes(self, W: List[List[int]], B: List[List[int]]) -> List[int]:
ans, used = [-1] * len(W), set()
for d, w, b in sorted([abs(W[i][0] - B[j][0]) + abs(W[i][1] - B[j][1]), i, j] for i in range(len(W)) for j in range(len(B))):
if ans[w] == -1 and b not in used:
... |
class OneLayerActiveScriptGen:
def __init__(self, args):
self.valid = args.split('|')
pass
def GenerateScript(self, arg2):
if len(self.valid) == 1:
#OK, this uses sub-layers
Script = "for (i=0;i<app.activeDocument.layers.length;i++)\n"
... |
def downcase_keys(dict_):
return {k.lower(): v for k, v in dict_.items()}
def assert_aws4auth_in_headers(headers):
lc_headers = downcase_keys(headers)
assert 'authorization' in lc_headers
assert 'x-amz-date' in lc_headers
assert 'x-amz-content-sha256' in lc_headers
auth_header = lc_headers.get... |
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.n = 853
self.hashtable = [None] * self.n
def add(self, key: int) -> None:
idx = key % self.n
if not self.hashtable[idx]:
self.hashtable[idx] = BST(key)
... |
"""Useful literals"""
TABLE_LEVEL_PG_STAT_USER_TABLES_COLUMNS = [
"relid",
"schemaname",
"relname",
"seq_scan",
"seq_tup_read",
"idx_scan",
"idx_tup_fetch",
"n_tup_ins",
"n_tup_upd",
"n_tup_del",
"n_tup_hot_upd",
"n_live_tup",
"n_dead_tup",
"n_mod_since_analyze",... |
class PersonError(Exception):
def __init__(self, a, b):
self.a = a
self.b = b
def print_obj(self):
print(self.a, self.b)
class Person:
def __init__(self, name: str, surname: str, age: int, gender: str):
try:
if age <= 0:
raise PersonError("Perso... |
number_one = int(input("Enter a number: "))
number_two = int(input("Enter another number: "))
if (number_one > number_two):
print("Number one is greater than number two")
else:
print("Number two is greater than number one") |
# Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours.
# Enter Hours: 45
# Enter Rate: 10
# Pay: 475.0
hours = int(input('Enter hours: '));
rate = float(input('Enter rate: '));
if hours > 40:
rate = rate * 1.5
pay = hours * rate;
print('Pay',pay); |
#Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
print('-='*20)
print('Analisador de Triângulo')
print('-='*20)
r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))
if r1 < r2+ r... |
def Menu():
print("Bienvenido, seleccione la operacion que desea realizar")
print("1.) Añadir")
print("2.) Asignar||Adicionar||Cancelar Materias")
print("3.) Modificar")
print("4.) Eliminar usuario")
print("5.) Mostrar bases de datos")
print("6.) Calificar")
print("7.) Buscar")
print... |
n = int(input())
for i in range(n,0,-1):
if n%i==0:
n=i
print(i, end=' ') |
###############################################################
# Servers
###############################################################
class ServerType(models.Model):
name = models.CharField(max_length=40, verbose_name='Nome')
type = models.CharField(max_length=40, verbose_name='Tipo')
creat... |
# from math import factorial >>>> jeito mais fácil
n1 = -1
while n1 <= 0:
n1 = int(input('Qual número deseja calcular o fatorial? '))
if n1 <= 0:
print('Digite um número inteiro maior que 0...')
n2 = n1
f = 1
print('{}! = '.format(n1), end='')
while n2 > 0:
print('{}'.format(n2), end='')
... |
#AUTOGENERATED! DO NOT EDIT! File to edit: dev/92_set_directories.ipynb (unless otherwise specified).
__all__ = ['Dirs']
#Cell
"""
Directories for Image preparation training and testing
"""
class Dirs:
def __init__(obj, basepath):
obj.basepath = basepath
obj.originImages = basepath + '/Original'
... |
# import geopandas as gpd
# import folium
# import matplotlib.pyplot as plt
#
#
# def teste():
#
# # Lê os dados
# url = 'https://geoservicos.pbh.gov.br/geoserver/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=ide_bhgeo:BAIRRO&srsName=EPSG:31983&outputFormat=application%2Fjson'
# gdf = gpd.read_f... |
# Código utilizado no livro Aprenda Python Básico - Rápido e Fácil de entender, de Felipe Galvão
# Mais informações sobre o livro: http://felipegalvao.com.br/livros
# Capítulo 8: Dicionários
# Criando nosso primeiro dicionário
aluno = {"nome": "José", "idade": 20, "nota": 9.2}
print(aluno)
# Criando um dicionário va... |
class MyClass:
def func_1(self):
return "1"
def func_2(func):
return func()
def main():
a=func_2(MyClass().func_1)
print(a)
if __name__ == '__main__':
main()
|
people = ['Conrad', 'Deepak', 'Heinrich', 'Tom']
ages = [29, 30, 34, 36]
for position in range(len(people)):
person = people[position]
age = ages[position]
print(person, age)
|
# @Title: 数组中重复的数据 (Find All Duplicates in an Array)
# @Author: KivenC
# @Date: 2018-07-22 14:56:19
# @Runtime: 388 ms
# @Memory: N/A
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = []
for i in range(len(... |
income_tax=0
id = int(input("Enter Employee id: "))
basic_salary = int(input("Enter monthly gross salary: "))
allowance = int(input("Enter allowance: "))
gross_salary = basic_salary+allowance
if gross_salary<=5000:
income_tax = 0
elif gross_salary<=10000:
income_tax = 0.1 * gross_salary
elif gross_salary<=20... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-11-16 21:11:11
# Description:
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
count = 0
result = 0
dict_seen = {0: -1}
for i in range(len(nums)):
n = nums[i]
if n =... |
__author__ = 'prossi'
class DISK:
def __init__(self, obj, connection):
self.__dict__ = dict(obj.attrib)
self.connection = connection
|
class ResponseMaker(object):
__slot__ = ['error_verbose']
def __init__(self, error_verbose=True):
self.error_verbose = error_verbose
def get_response(self, result, request_id):
return {
"jsonrpc": "2.0",
"result": result,
"id": request_id
}
... |
def Sorting_array_data(A,i):
B = sorted(A, key=lambda a_entry: a_entry[i])
return B
|
contas = []
depositos = []
saldo = 0
def main():
opc = bool(int(input('[1] Criar conta\n[0] Fechar programa\nSua opção: ')))
while opc:
criaConta()
ver_saldo()
opc = bool(int(input('[1] Criar conta\n[0] Fechar programa\nSua opção: ')))
if opc == 0:
break
def criaC... |
#Desafio 49
#Programa Tabuada, Lê um número inteiro e mostra sua tabuada.
#Testando a estrutura de repetição "for" do python
num = int(input("Digite um número inteiro qualquer para saber sua tabuada: "))
for i in range(1,11):
print(f" {num} x {i} = {num*i}")
print("---Fim da Tabuada---")
|
class Tracker(object):
def __init__(self):
self.trk = [] # currently tracked 2D Points
self.trk_i = [] # self.pts[self.trk_i] are currently tracked
self.pts = [] # list of all known object feature point positions
self.kpt = [] # corresponding image coordinates for all points
... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-04-07 11:54:35
# @Last Modified by: 何睿
# @Last Modified time: 2019-04-07 12:22:34
class Solution:
def countBits(self, num: int) -> [int]:
# 结果数组
result, count = [0], 1
while count * 2 <= num:
# 从 re... |
# Write an efficient program to find the sum of contiguous subarray within
# a one-dimensional array of numbers which has the largest sum.
def max_sum_kadane(nums: list) -> int:
# kadane's algorithm
max_so_far = max_ending_here = 0
for value in nums:
max_ending_here = max(max_ending_here + value,... |
class Runtime:
"""Encapsulates the runtime state of execution itself, excluding I/O."""
def __init__(self, program, env):
self.program = program
self.env = env
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 15:54:59 2019
@author: janej
"""
print('name:'+__name__)
print('package:'+__package__)
print('doc:'+__doc__)
print('file:'+__file__)
|
# Copyright 2013 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,
'variables': {
'version_py_path': '<(DEPTH)/build/util/version.py',
'version_path': 'VERSION',
... |
# veri = bytearray("ş")
veri = bytearray("abcd",encoding="utf-8")
print(veri)
print(veri[1])
print(veri[0])
with open("veri.bin", 'wb') as dosya:
dosya.write(veri)
veri2 = bytearray("diğer veri", encoding="utf-8")
with open("veri.bin", "rb") as dosya1:
data = dosya1.readinto(veri2)
print("Ve... |
'''
Steven Kyritsis CS100
2021F Section 031 HW 08,
November 5, 2021
'''
#1
def two_words(length, first_letter):
while True:
word1 = input("Please enter a " + str(length) + "-letter word please: ")
if len(word1) == length:
break
while True:
word2 = input("Please enter a word ... |
X, Y, A, B = map(int, input().split())
ans = 0
while True:
if X*A < B and X*A < Y:
X *= A
ans += 1
else:
break
ans += (Y-X-1)//B
print(ans)
|
"""Guarde en lista `naturales` los primeros 100 números naturales (desde el 1)
usando el bucle while
"""
naturales=[]
i=1
while i <=100:
naturales.append(i)
i+=1
#print(i)
#print(naturales)
"""Guarde en `acumulado` una lista con el siguiente patrón:
['1','1 2','1 2 3','1 2 3 4','1 2 3 4 5',...,'...47 48 4... |
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "Private Program"
description = """
User with authorization to peform administrative tasks such as associating
users to roles within the scope of of a program.<br/><br/>When a person
creates a ... |
"""
link: https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
problem: 给小写字母字符串 s, p,求s中所有子串中,p的字母异位词,即组成字符串的字符集一致
solution: 滑动窗口。维护长度为len(p)的窗口内每个字符出现的次数
"""
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
c1, c2, res = [0] * 26, [0] * 26, []
for x in p:
... |
"""Exceptions raised by this NApp."""
class DeviceException(Exception):
"""Device related exception."""
def __init__(self, message, device=None):
"""Take the parameter to inform the user about the error.
Args:
device (str, :class:`Device`): The device that was looked for.
... |
"""A function for testing approximate equality of two numbers.
Same as math.isclose in Python v3.5 (and newer)
https://www.python.org/dev/peps/pep-0485
"""
def almost_equal(a, b, rel_tol=1e-09, abs_tol=0.0):
"""A function for testing approximate equality of two numbers.
Same as math.isclose in Python v3.5 (an... |
old_file = open('city.txt', 'r')
new_file = open('city_with_format.txt', 'w')
all_cities = old_file.readlines()
# print all_cities
for i in all_cities:
city, country = i.strip().split()
new_file.write('%-25s%-25s\n' % (city, country))
old_file.close()
new_file.close()
|
{
'targets': [
{
'configurations': {
'Debug': { },
'Release': { }
},
'target_name': 'appels',
'type': 'executable',
'dependencies': [
'third_party/skia/skia.gyp:alltargets',
'third_party/skia/gyp/sdl.gyp:sdl',
],
'include_dirs': [
'... |
def pattern(n):
if n <= 1:
return ""
res = ""
for i in range(1, n//2+1):
res += str(i*2)*(i*2)+"\n"
return res[:-1] |
TOTAL_CHARACTERS = 'SELECT COUNT(character_id) FROM charactercreator_character;'
TOTAL_SUBCLASS = '''
SELECT COUNT(*) FROM (SELECT *
FROM charactercreator_character cc_c
INNER JOIN charactercreator_necromancer cc_n
ON cc_c.character_id = cc... |
response.title = settings.title
response.subtitle = settings.subtitle
response.meta.author = '%(author)s <%(author_email)s>' % settings
response.meta.keywords = settings.keywords
response.meta.description = settings.description
response.menu = [
(T('Home'),URL('default','index')==URL(),URL('default','index'),[]),
(T('C... |
class Solution:
def split(self, spaces: int, sets: int) -> Iterable[int]:
if (spaces % sets == 0):
rem = spaces // sets
return (rem for i in range(sets))
else:
rem, bigRem = sets - (spaces % sets), spaces//sets
return (bigRem + 1 if (i >= rem) else big... |
#dicionario suporta um par de chave e um valor
d1 = dict(chave1 = "valor da chave", chave2 = "chave 2")
d1["nova_chave"] = "chave nova"
print(d1["nova_chave"])
print(d1)
d2 = {"chave": "esse é outro jeito de declarar chaves"}
print(d2)
d3 = {
"string" : "valor",
123: "outro valor",
(1,2,3,4) : "tupla",
}
pr... |
#
# PySNMP MIB module FMS100-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FMS100-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:14:07 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, 09:... |
"""
Write program, that will count the sum of all numbers from 1 to
number that was entered by user.
1,2,3,4,5,... 100
(1 + 100) / 2 * 100
For 5:
1+2+3+4+5
the result is gonna be:
15
(1 + 5) / 2 * 5 = 15
range(1, 6)
1,2,3,4,5
"""
def sum_up_to(end):
sum = 0 # 15
for number in rang... |
{
"targets": [
{
"target_name": "cpp-netlib",
"type": "static_library", # unlike boost-asio which is header-only
"include_dirs": [
"0.11.1-final/cpp-netlib-cpp-netlib-0.11.1-final"
],
"defines": [
"BOOST_NETWORK_ENAB... |
def chdir():
pass
def getcwd():
pass
def listdir():
pass
def mkdir():
pass
def remove():
pass
def rename():
pass
def rmdir():
pass
sep = "/"
def stat():
pass
def statvfs():
pass
def sync():
pass
def uname():
pass
def unlink():
pass
def urandom():... |
#!/usr/bin/env python
"""Contains the Data Model Descripts for the REST Resources.
Contains the Data Model Configuration settings for each
REST Resource provided by the Python Eve Server. Data
validation object typing is also included.
"""
__author__ = "Sanjay Joshi"
__copyright__ = "IBM Copyright 2015"
__credits__ =... |
# Given a linked list, rotate the list to the right by k places, where k is non-negative.
#
# Example 1:
#
# Input: 1->2->3->4->5->NULL, k = 2
# Output: 4->5->1->2->3->NULL
# Explanation:
# rotate 1 steps to the right: 5->1->2->3->4->NULL
# rotate 2 steps to the right: 4->5->1->2->3->NULL
# Example 2:
#
# Input: 0->1->... |
# 28 Wind Chill
#Asking for air temperature and wind speed.
T = float(input('Enter the air temperature in celsius= '))
v = float(input('Enter the velocity of windin km/h = '))
x = round(13.12 * 0.6215 * T - 11.37 * v ** 0.16 + 0.3965 * T * v ** 0.16)
print('Wind chill index = ',x)
|
"""
Class that represents a single linked
list node that holds a single value
and a reference to the next node in the list
"""
class Node:
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def get_value(self):
return self.value
def get_... |
##Read the dictionary
fh = open('C:\\english-dict.txt')
dict = []
while True:
line = fh.readline()
dict.append(line.strip())
if not line:
break
fh.close()
#Enter letters to use when compile a list of words
letters = input("Please enter your letters: ")
letters_set=set(letters)
mini = input("Minimu... |
class Collector:
def __init__(self, name, have_task=True):
self.name = name
self.have_task = have_task
self.data_dict = None
self.last_collect = 0
def run_task(self):
pass
def get_data(self):
pass
|
class ControlPoint(object):
'''undirected unweighted graph'''
def __init__(self):
self.num = int(0)
self.name = ""
self.X = 0.0
self.Y = 0.0
self.Z = 0.0
self.N = 0.0
self.E = 0.0
self.H = 0.0
def init_controlpoint(self,line):
line = ... |
#
# Copyright (c) 2009 Voltaire
# $COPYRIGHT$
#
# Additional copyrights may follow
#
# $HEADER$
#
"""
Configuration settings for application
"""
# Debug mode
DEBUG = True
# Authorisation key
AUTH = "" |
def digit_powers():
res = []
for i in range(1, 10):
j = 0
while True:
j += 1
num = i ** j
num_digits = len(str(num))
if num_digits != j:
break
res += [num]
return res |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def preProcess(s):
if not s:
return ['^', '$']
T = ['^']
for c in s:
T += ['#', c]
T += ['#', '$']
... |
print((type(None)))
print(type(True))
print(type(5))
print(type(5.5))
print(type('hi'))
print(type([]))
print(type(()))
print(type({})) |
#!/usr/bin/env python
#pylint: skip-file
# This source code is licensed under the Apache license found in the
# LICENSE file in the root directory of this project.
class ProtectionDomain(object):
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the... |
a=1
b=2
print('a=',a,'b=',b)
x=3
y=3
z=3
print(x,y,z) |
res = 0
n = 0
print("S= ", end="")
for n2 in range(1, 51):
if n2 == 1:
n += 1
print(f"{n}/{n}", end="")
else:
n += 2
res += (n / n2)
print(f" + {n}/{n2}", end="")
print(f"\nResultado = {res}")
|
"""A single Node in the graph of the art."""
class ArtNode:
def __init__(self, x: int, y: int, thickness: int) -> None:
self.x = x
self.y = y
self.thickness: int = thickness
def xy(self, factor: int = 1):
"""
Gets the xy position of this node, but also allow for
... |
lanche = 'Hambúrguer', 'Suco', 'Pizza', 'Pudim'
for comida in lanche:
print(f'Eu vou comer {comida}')
for cont in range(0, len(lanche)):
print(f'Eu vou comer {lanche[cont]} na posição {cont}')
for pos, comida in enumerate(lanche):
print(f'Eu vou comer {comida} na posição {pos + 1}')
print('Comi pra caramb... |
"""
By starting at the top of the triangle below and moving to adjacent
numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03... |
"""
PyNullWeb - a web server that returns minimal content.
:copyright: (c) 2017 by Detlef Kreuz
:license: Apache 2.0, see LICENSE
"""
|
def alphabeta(node, is_max=True, alpha=float('-inf'), beta=float('inf')):
if node and not node.children:
return (node.val, [node])
elif is_max:
# Can always fall back on alpha. This is the lower bound score
for child in node.children:
score, path = minimax(child, False, alpha... |
#desenvolva um programa que leia o primeiro
#termo e a razao de uma PA. No final, Mostre
#os 10 primeiro termos dessa progressao.
#OBS: PA= (1,100,10) o primeiro n=1 a razao=10
primeiroTermo=int(input("Digite o primeiro termo da sua PA: "))
razao=int(input("Digite a razao da sua PA: "))
pa=int(input("Qual a posiçao v... |
# -*- coding: utf-8 -*-
class ErrorResponse(Exception):
def __init__(self, error=None, errorcode=None, errormessage=None,
errordetails=None):
self.error = error
self.errorcode = errorcode
self.errormessage = errormessage
self.errordetails = errordetails
def _... |
#!/usr/bin/env python3
"""
This module contains forms used by the app.
"""
|
"""
construir uma classe carro que vai possuir dois atributos compostos por outras duas classes:
1) Motor
2) Direção
1 - Motor resposavel de controlar a velocidade
1- atributo de velocidade
2- acelerar, incremetar de 1 unidade a 1
3- frear que decremeta em 2 unidades
2 - Direção responsavel por controlar... |
# -*- coding: utf-8 -*-
'''
File name: code\sum_of_squares\sol_273.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #273 :: Sum of Squares
#
# For more information see:
# https://projecteuler.net/problem=273
# Problem Statement
'''
Consi... |
def primes(n):
for i, prime in enumerate(prime_generator()):
if i == n:
return prime
def prime_generator():
n = 2
primes = set()
while True:
for p in primes:
if n % p == 0:
break
else:
primes.add(n)
yield n
... |
#-*-coding=utf-8-*-
class Node(object):
def __init__(self, elem=-1,lchild=None, rchild=None):
self.elem=elem
self.lchild=lchild
self.rchild=rchild
class Tree(object):
def __init__(self):
self.root=Node()
self.nodequeue=[]
def addnode(self, elem):
node =Node(e... |
def f(n:Int)->Int:
return (n * (n+1)) // 2
def get_numbers(how_many:Int)->List(Int):
nums = []
for i in range(1, 1 + how_many):
nums.append(f)
return nums
print(get_numbers(4))
def apply_first(funs, n):
return funs[0](n)
print(apply_first(get_numbers(4), 10))
|
"""
异常的自定义和抛出:
class ****Exception(Exception):
pass
定义一个学生类,私有属性gender,提供对应的设置值及访问值的方法
"""
# 异常类定义
class GenderException(Exception):
def __init__(self):
super().__init__()
self.err_msg = "性别只能设置为男、女、male、female、man、woman"
class Student:
def __init__(self, name, gender):
self.nam... |
'''
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
'''
class Solution:
def isValid(self, s: str) -> ... |
"""
Codemonk link: https://www.hackerearth.com/problem/algorithm/monk-and-palindromes-52299611/
Monk loves maths and is always curious to learn new things. Recently, he learned about palindromes. Now, he decided to
give his students a problem which uses maths and the concept of palindromes. So, he wants the students t... |
def contador(* num): # O asterisco no contador significa que pode receber diversos valores e vai colocar dentro de uma tupla
for valor in num:
print(f' {valor} ', end='')
print(f'Recebi os valores {num} e sao ao todo {len(num)}')
print('Fim')
contador(2, 1, 7)
contador(4, 0, 4, 6, 9, 8)
def so... |
# -*- coding: utf-8 -*-
"""Main module."""
def ascii_deco(vector):
cadena = vector.split(',')
suma = " "
for i in range(len(cadena)):
ascci = int(cadena[i])
caracter = chr(ascci)
suma = suma + caracter
print (suma)
|
#
# This file contains the Python code from Program 11.22 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm11_22.txt
#
class Simulation(... |
NETWORKS = {
3: {
"name": "test",
"http_provider": "https://ropsten.infura.io",
"ws_provider": "wss://ropsten.infura.io/ws",
"db": {
"DB_DRIVER": "mysql+pymysql",
"DB_HOST": "localhost",
"DB_USER": "unittest_root",
"DB_PASSWORD": "unitt... |
# Declares an initial list with 5 values
List1 = [1,2,3,4,5]
# Unpacks this list into 5 separate variables
a,b,c,d,e = List1
# Prints both the list and one of the unpacking variables
print(List1)
print(a)
# Changes the value of a to 6
a = 6
# Prints both the list and a, and we can see that changing a d... |
def sum_of_multiples(limit, multiples):
multiples_set = set()
for multiple in multiples:
if multiple != 0:
quotient, rest = divmod(limit, multiple)
if rest == 0:
quotient -=1
multiples_set = multiples_set.union(set(multiple * i for i in range(1,quotie... |
# Size of the window
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
# Default friction used for sprites, unless otherwise specified
DEFAULT_FRICTION = 0.2
# Default mass used for sprites
DEFAULT_MASS = 1
# Gravity
GRAVITY = (0.0, -900.0)
# Player forces
PLAYER_MOVE_FORCE = 700
PLAYER_JUMP_IMPULSE = 600
PLAYER_PUNCH_IMPULS... |
# Write a program that outputs the string representation of numbers from 1 to n.
#
# But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
#
# Example:
#
# n = 15,
#
# Return:
#... |
class Solution:
"""
Time Complexity: O(N)
Space Complexity: O(1)
"""
def balanced_string_split(self, s: str) -> int:
# initialize variables
L_count, R_count = 0, 0
balanced_substring_count = 0
# parse the string
for char in s:
# update the numbe... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 BigML
#
# 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 ... |
"""
Introduction
============
The ``ox_profile`` package provides a python framework for statistical
profiling. If you are using ``Flask``, then ``ox_profile`` provides a
flask blueprint so that you can start/stop/analyze profiling from within
your application. You can also run the profiler stand-alone without
``Flask... |
def opcodeI() -> int:
with open("/home/thelichking/Desktop/adventOfCode/Day2/Opcodes",'r' ) as file:
lines = list(map(int,file.readline().replace("\n","").split(",")))
lines[1],lines[2] = 1,0
idx = 0
while idx < len(lines):
cur_opcode = lines[idx]
if cur_op... |
class Solution:
def findLUSlength(self, a, b):
"""
:type a: str
:type b: str
:rtype: int
"""
if a == b:
return -1
return max(len(a), len(b))
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def inOrder(self, root, bstArr):
if not root:
return
if root.left:
self.inOrder(r... |
# Advent Of Code 2016, day 3, part 2
# http://adventofcode.com/2016/day/3
# solution by ByteCommander, 2016-12-03
data = open("inputs/aoc2016_3.txt").read()
# parse input to vertical groups of 3 numbers
rows = [[int(x) for x in line.split()] for line in data.splitlines()]
vertically = [item for inner in zip(*rows) fo... |
__title__ = "pyls-isort"
__version__ = "0.1.1"
__summary__ = "Isort plugin for python-language-server"
__uri__ = "https://github.com/paradoxxxzero/pyls-isort"
__author__ = "Florian Mounier"
__email__ = "paradoxxx.zero@gmail.com"
__license__ = "MIT"
__copyright__ = "Copyright 2017 %s" % __author__
|
class Solutions(object):
def singleNumber(self, nums):
res = 0
for i in range(32):
bit_i_sum = 0
for num in nums:
bit_i_sum += (num >> i) & 1
res += (bit_i_sum % 3) << i
return res
if __name__ == '__main__':
print(Solutions().single... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.