content stringlengths 7 1.05M |
|---|
class InMemoryKVAdapter:
""" Dummy in-memory key-value store to be used as mock for KVAdapter"""
def __init__(self):
self._data = {}
def get_key(self, key):
root, key = self._navigate(key)
return root.get(key, None)
def get_keys(self, key):
root, key = self._navigate(k... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 15:59:53 2020
@author: Pablo
"""
class Term:
string = ''
lang = ''
score=0
corpus=''
synonyms=[]
iateURL=''
translations = {}
def __init__(self, term, code):
self.strin... |
# Basic - Print all integers from 0 to 150.
y = 0
while y <= 150:
print(y)
y = y + 1
# Multiples of Five - Print all the multiples of 5 from 5 to 1,000
x = 5
while x < 1001:
print(x)
x = x + 5
# Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible ... |
##write a function that takes a nested list as an argument
##and returns a normal list
##show that the result is equal to flattened_list
nested_list = ['a', [2, 3], [4, 'b', [0, -2, ['c', 'e', '0f']]]]
flattened_list = ['a', 2, 3, 4, 'b', 0, -2, 'c', 'e', '0f']
def flat_list(nest_list):
flat = list()
... |
''' Program to count each character's frequency
Example:
Input: banana
Output: a3b1n2
'''
def frequency(input1):
l = list(input1)
x= list(set(l))
x.sort()
result=""
for i in range(0,len(x)):
count=0
for j in range(0,len(l)):
if x[i]==l[j]:
count +=1
... |
# coding=utf-8
# i=10
# print(i)
# i = True
# if i:
# print("True")
# else:
# print("False")
#
# total = 'tem_one' + \
# 'tem_two' + \
# 'item_three'
# print(total)
# money = 99.9
# count = 5
# person = '小明'
# print(money, type(money))
# money = '9.9哈'
# print(money, type(money))
# money = 11... |
class VarDecl:
def __init__(self, name: str, type: str):
self._name = name
self._type = type
def name(self) -> str:
return self._name
def type(self) -> str:
return self._type
|
# DROP TABLES
# The following CQL queries drop all the tables from sparkifydb.
song_in_session_table_drop = "DROP TABLE IF EXISTS song_in_session"
artist_in_session_table_drop = "DROP TABLE IF EXISTS artist_in_session"
user_and_song_table_drop = "DROP TABLE IF EXISTS user_and_song"
# CREATE TABLES
# The following CQL ... |
class DataGridViewCell(DataGridViewElement,ICloneable,IDisposable):
""" Represents an individual cell in a System.Windows.Forms.DataGridView control. """
def AdjustCellBorderStyle(self,dataGridViewAdvancedBorderStyleInput,dataGridViewAdvancedBorderStylePlaceholder,singleVerticalBorderAdded,singleHorizontalBorderAdd... |
# Exercise 01.2
# Author: Leonardo Ferreira Santos
arguments = input('Say something: ')
print('Number of characters: ', arguments.__sizeof__() - 25) # "-25" is necessary because this function always implements "25".
print('Reversed: ', arguments[::-1])
|
class Matrix:
def __init__(self, *rows):
self.matrix = [row for row in rows]
def __repr__(self):
matrix_repr = ""
for i, row in enumerate(self.matrix):
row_repr = " ".join(f"{n:6.2f}" for n in row[:-1])
row_repr = f"{i}: {row_repr} | {row[-1]:6.2f}"
... |
'''
This program implements merge sort to sort an array of length n
Author: Juan Ríos
'''
def read_file(path):
File = open(path,'r')
content = File.read()
array = content.split('\n')
tmp = []
for i in array:
tmp.append(int(i))
return tmp
def merge(b_array, c_array):
... |
# C++ | General
multiple_files = True
no_spaces = False
type_name = "Pixel"
# C++ | Names
name_camelCase = True
name_lower = False
# Other
out_filename = "Out.cpp" # Only works when multiple_files is on
multiple_files_extension = ".h" |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_content(pluginname, "shopex")
|
#
# PySNMP MIB module CISCO-UNIFIED-COMPUTING-DOMAIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UNIFIED-COMPUTING-DOMAIN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:15:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... |
def test_e1():
a: list[i32]
a = [1, 2, 3]
b: list[str]
b = ['1', '2']
a = b
|
# TODO(kailys): Doc and create examples
class ConfigOption(object):
"A class representing options for ``Config``."
def __init__(self, name, value_map):
self.name = name
self.value_to_code_map = value_map
self.code_to_value_map = {v: k for k, v in value_map.iteritems()}
self.va... |
"""
Module: 'crypto' on GPy v1.11
"""
# MCU: (sysname='GPy', nodename='GPy', release='1.20.2.rc7', version='v1.11-6d01270 on 2020-05-04', machine='GPy with ESP32', pybytes='1.4.0')
# Stubber: 1.3.2
class AES:
''
MODE_CBC = 2
MODE_CFB = 3
MODE_CTR = 6
MODE_ECB = 1
SEGMENT_128 = 128
SEGMENT_8... |
# -*- coding: utf-8 -*-
{
'name': "Product Minimum Order Quantity",
'summary': """
Specify the minimum order quantity of an item""",
'description': """
This module adds the functionality to control the minimum order quantity in a sales order line. The default number is set to 0. You can change this ... |
"""
goose : honk pig : 0.05 frog : -8 horse : 1 2 foo 3 duck : "quack quack"
"""
def pydict_to_mxdict(d):
res = []
for k,v in d.items():
res.append(k)
res.append(':')
if type(v) in [list, set, tuple]:
for i in v:
res.append(i)
else:
res.ap... |
def main():
myList = []
choice = 'a'
while choice != 'x':
if choice == 'a' or choice == 'A':
option1(myList)
elif choice == 'b' or choice == 'B':
option2(myList)
elif choice == 'c' or choice == 'C':
option3(myList)
elif choice == ... |
reslist = [
-3251,
-1625,
0,
1625,
3251,
4876,
6502,
8127,
9752,
11378,
13003,
] # 1625/1626 increments
def fromcomp(val, bits):
if val >> (bits - 1) == 1:
return 0 - (val ^ (2 ** bits - 1)) - 1
else:
return val
filepath = "out.log"
with open(fil... |
# fun from StackOverflow :)
def toFixed(numObj, digits=0):
return f"{numObj:.{digits}f}"
# init
a = int(input("Enter a> "))
b = int(input("Enter b> "))
c = int(input("Enter c> "))
d = int(input("Enter d> "))
# calc
f = toFixed((a+b) / (c+d), 2)
# output
print("(a + b) / (c + d) = ", f)
|
#20 se 100 takk vo print kro jo 2 se devied ho
num=20
while num<=100:
a=num-20
if num%2==0:
print(num)
num+=1 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "HW5_FFT.py",
"provenance": [],
"collapsed_sections": [],
"authorship_tag": "ABX9TyOW+hfid580c7DvA724SrbG",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": ... |
def area_of_rectangle(a,b):
return a * b
a = int(input())
b = int(input())
print(area_of_rectangle(a,b)) |
print('='*5 + 'CASTRO BUY' + '='*5)
preco = float(input('Preço das compras: R$'))
print('FORMAS DE PAGAMENTO:')
op = int(input('[ 1 ] à vista dinheiro/cheque\n'
'[ 2 ] à vista cartão\n'
'[ 3 ] 2x no cartão\n'
'[ 4 ] 3x ou mais no cartão\n'
'Qual a opção?: '))
... |
t = int(input())
for _ in range(t):
a, b = map(int, input().split())
diff = abs(b-a)
if diff == 0:
print(0)
continue
if diff % 10 == 0:
print(diff//10)
else:
print(diff//10 + 1) |
def sortMolKeys(my_molecules):
if ' and ' not in list(my_molecules.keys())[0]:
my_sort = ['' for i in range(len(my_molecules))]
nums = [int(i.split()[0]) for i in my_molecules]
nums_sorted = ['%i'%i for i in sorted(nums)]
for key in my_molecules:
index = nums_sorted.index... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# No difference between single and double quotes
x = '''
seven
'''.capitalize()
print('x is {}'.format(x))
print(type(x))
|
x = int(input())
y = int(input())
# the variables `x` and `y` are defined, so just print their sum
print(sum([x, y]))
|
layers_single_good_simulated_response = """{"id": 1474, "url": "https://koordinates.com/services/api/v1/layers/1474/", "type": "layer", "name": "Wellington City Building Footprints", "first_published_at": "2010-06-21T05:05:05.953", "published_at": "2012-05-09T02:11:27.020Z", "description": "Polygons representing buildi... |
hash_table = [0] * 8
def get_key(data):
return hash(data)
def get_address(key):
return key % 8
def save_data(data, value):
key = get_key(data)
addr = get_address(key)
if not hash_table[addr]:
hash_table[addr] = [[key, value]]
else:
for i in range(len(hash_table[addr])):
... |
print('Quantidade de tinta nescessario.')
lar = float(input('Largura da parede: '))
alt = float(input('Altura da Parede: '))
area = lar * alt
tinta = area / 2
print('Sua parede é de {:.2f}m²:'.format(area))
print('Precisa de aprocimadamente {:.3f}l de tinta.'.format(tinta)) |
set_name(0x8012427C, "PresOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x801242A4, "FeInitBuffer__Fv", SN_NOWARN)
set_name(0x801242CC, "FeAddEntry__Fii8TXT_JUSTiP7FeTableP5CFont", SN_NOWARN)
set_name(0x8012433C, "FeAddTable__FP11FeMenuTablei", SN_NOWARN)
set_name(0x801243BC, "FeDrawBuffer__Fv", SN_NOWARN)
set_name(0x80124... |
src='2018-5540'
region='box[[181pix,79pix], [681pix,816pix]]'
directory='/Volumes/NARNIA/pilot_cutouts/leakage_corrected/2018-5540/'
imsubimage(imagename='FDF_peakRM_fitted_corrected.fits',outfile='pkrm_smol_temp',region=region,overwrite=True,dropdeg=True)
exportfits(imagename='pkrm_smol_temp',fitsimage='2018-5540_p... |
# coding=utf-8
BASE_ENDPOINT = "http://sskj.si/?s={}"
MAX_DEFINITIONS = 50
MAX_CACHE_AGE = 43200
class SpecialChars:
TERMINOLOGY = u"\u25CF"
SLANG = u"\u2666"
REPLACEMENTS = {
# no-break space replacement with normal space
"\xa0": " "
}
def remove_num(d):
for n in range(1, MAX_DEFINITIONS):
... |
#### Regulation Z
IGNORE_DEFINITIONS_IN_PART_1026 = [
'credit report',
'credit-report',
'Consumer Price Index',
'credit counseling',
'and credit the',
'credit reporting agencies',
'credit history',
'Credit the amount',
'credit to a deposit account',
'Consumer Price level',
'... |
class Solution:
def bitwiseComplement(self, N: int) -> int:
X = 1
while N > X: X = X * 2 + 1
return X - N
|
class Constants:
HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) '
'Gecko/20100101 Firefox/70.0'
}
HEADERS = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:70.0) '
'Gecko/20100101 Firefox/70.0',
"Connection": ... |
# https://programmers.co.kr/learn/courses/30/lessons/77484
# 로또의 최고 순위와 최저 순위
def count_to_rank(count):
return min(6, 7 - count)
def solution(lottos, win_nums):
base = 0
num_joker = 0
for num in lottos:
if num == 0:
num_joker += 1
elif num in win_nums:
base += ... |
# You are developing an online booking portal for a bus tour company. On the website, tourists can book in
# groups to come on your company's city bus tour. The company has various buses with different capacities.
# You want to determine, from the list of available bookings, if you can completely fill up a particular b... |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py 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 3 of the License, or
(at your option) any late... |
# ex02 Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número].
numero = int(input('Digite um número: '))
print(f'O numero informado foi {numero}')
|
#
# PySNMP MIB module SIEMENS-HP4KHIM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SIEMENS-HP4KHIM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:04:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
def _list_of_n(lst, n):
"""For assignment to (list, ...) - make this list the right size"""
if lst is None or (hasattr(lst, 'isHash') and lst.isHash) or not (isinstance(lst, collections.abc.Sequence) and not isinstance(lst, str)):
lst = [lst]
la = len(lst)
if la == n:
return lst
... |
'''
/profissional-de-saude/{idprofissional}/gerar-consulta/{dateTime}{
blueprint:paciente
template:profissionalDesSaudeGerarConsulta.html
dados:{
consulta{
nomeProfissional,
especialidade,
dateTime,
valor
}
}
*******pagseguro
}
''' |
# -*- coding: utf-8 -*-
"""
Created on Sat May 2 17:07:59 2020
@author: teja
"""
# Stack
l = [1, 2, 3, 4]
l.append(10)
print(l.pop())
print(l)
#Queue
l = [1, 2, 3, 4]
l.append(20)
l.pop(0)
print(l) |
# https://easily-champion-frog.dataos.io:7432/depot/collection
connection_regex = r"^(http|https):\/\/([\w.-]+(?:\:\d+)?(?:,[\w.-]+(?:\:\d+)?)*)(\/\w+)?(\/\w+)?(\?[\w.-]+=[\w.-]+(?:&[\w.-]+=[\w.-]+)*)?$"
apikey_regex = "\\w+"
|
"""A simple example for how to replace the provided artifact macro"""
load("@mabel//rules/maven_deps:mabel.bzl", "artifact")
def g_artifact(coordinate, type = "auto"):
return artifact(coordinate, repositories = ["https://maven.google.com/"], type = type)
|
# -*- coding: utf-8 -*-
# 商户信用分服务
class ShopcreditscoreService:
__client = None
def __init__(self, client):
self.__client = client
def batch_query_shop_credit_scores(self, shop_ids):
"""
连锁店根据商户ID集合批量查询商户信用分信息
:param shopIds:商户ID集合
"""
return self.__clien... |
'''
94. Binary Tree Inorder Traversal
Medium
1231
51
Favorite
Share
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
'''
# Definition for a bi... |
class Inventory:
def add(item, slot, stat, bag):
bag = {
"slot": str(slot),
"stat": int(stat)
}
return bag; |
BASE_URL = "https://www.booking.com/"
HEADERS = [
"Hotel Name",
"Type",
"Location",
"Date Range",
"adults",
"rooms",
"Score",
"price",
]
|
# This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
CONTEXT_KEYS = ['reset', 'error', 'badinfo',
'in_browser', 'in_statusbar', 'in_titlebar', 'in_console',
'in_pager', 'in_taskview',
'active_pane', 'inactive_pane',
'... |
class UnauthorizedEvalError(ValueError):
pass
class UnauthorizedNameAccess(UnauthorizedEvalError, NameError):
pass
class UnauthorizedCall(UnauthorizedEvalError):
pass
class UnauthorizedAttributeAccess(UnauthorizedEvalError):
pass
class UnauthorizedSubscript(UnauthorizedEvalError):
pass
|
class Macro:
def __init__(self, actions, check_sticky):
self.actions = actions
self.check_sticky = check_sticky
def step(self, current_sticky_actions):
while len(self.actions) > 0:
action = self.actions.pop(0)
if self.check_sticky and action not in current_sticky... |
n1 = int(input('digite um número:'))
n2 = n1 + 1
n3 = n1 - 1
print('O número que você digitou é {} o seu sucesor é {} e o seu antecessor é {}.'.format(n1, n2, n3))
t1 = int(input('digite outro número:'))
print('O número que você digitou é {} o seu antecessor é {} e o seu sucessor é {}'.format(t1, t1 - 1, t1 + 1))
|
# 两个链表的公共节点
# 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),
# 请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
class Solution:
# 第一个参数给比较短的链表,第二个参数给长链表的值
# def findEqual(self,):
def FindFirstCommonNode(self, pHead1, pHead2):
# 假设输入的两个链表,是同一个链表
if pHead1 == pHead2:
... |
# this program caluclate the sum from 1 to a given number
target_number = int(input("Enter a number up to which you wan to calculate the sum from 1: "))
sum_of_numbers = target_number
for n in range(1,target_number):
sum_of_numbers += n
print(f"The total sum of 1 to {target_number} is {sum_of_numbers}")
|
class Solution:
def solve(self, s):
last_char = ""
cur_streak_length = 0
best_ans = 0
for i in range(len(s)):
cur_char = s[i]
if cur_char == last_char:
cur_streak_length += 1
else:
cur_streak_length = 1
last_char = c... |
"""
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise
return 0.
You may assume that the version strings are non-empty and contain only digits
and the . character.
The . character does not represent a decimal point and is used to separate
num... |
n, q = map(int, input().split())
root = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().split())
root[a].append(b)
root[b].append(a)
d = [10**8] * (n + 1)
d[1] = 0
seen = [0] * (n + 1)
ind = [0] * (n + 1)
# record=[[] for i in range(n+1)] # 変数の情報記録
def tree_search(n, G, s, func... |
#
# PySNMP MIB module STN-POLICY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STN-POLICY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:11:31 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 main():
# input
N, M = map(int, input().split())
scs = [list(map(int, input().split())) for _ in range(M)]
# compute
if N == 1:
numbers = range(0, 10)
elif N == 2:
numbers = range(10, 100)
else:
numbers = range(100, 1000)
for i in numbers:
flag = True... |
#Crie um programa que diga 'Hello World'
msg = 'Hello World!'
print( msg )
|
class car:
def __init__(self):
self.__fuelling()
def drive(self):
print("Driving..!!")
def __fuelling(self):
print("Refilling Gas")
volvo=car()
volvo.drive()
volvo._car__fuelling() |
s = 0
t = 0
while True:
n = int(input('Número: '))
if n == 999:
break
s += n
t += 1
print(f'Soma: {s}')
print(f'Total: {t}')
|
def dump_vector(x):
return ",".join(map(str, x))
def dump_matrix(xs):
vs = map(dump_vector, xs)
return "{0}#{1}#{2}".format(xs.shape[0], xs.shape[1], "|".join(vs))
def dump_pca(pca):
return "{0}\n{1}".format(dump_matrix(pca.components_.T), dump_vector(pca.mean_))
def dump_mlp(mlp):
activation = m... |
galera = list()
dados = list()
maior = list()
menor = list()
contador = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso: ')))
galera.append(dados[:])
dados.clear()
continuar = str(input('Deseja continuar? [S/N]')).strip().upper()[0]
if continuar in 'N': break
pr... |
def meets_criteria(number):
num_str = str(number)
# check to see if two number are the same next to each other
i = 1
previous = num_str[0]
while i < 6 :
if previous == num_str[i]:
break
previous = num_str[i]
i+=1
if i == 6:
return 0
# no more ... |
___assertEqual(+False, 0)
___assertIsNot(+False, False)
___assertEqual(-False, 0)
___assertIsNot(-False, False)
___assertEqual(abs(False), 0)
___assertIsNot(abs(False), False)
___assertEqual(+True, 1)
___assertIsNot(+True, True)
___assertEqual(-True, -1)
___assertEqual(abs(True), 1)
___assertIsNot(abs(True), True)
___a... |
# Will keep track of all the variables and their values
class SymbolTable:
def __init__(self):
self.symbols = {}
def get(self, name):
value = self.symbols.get(name, None)
return value
def set(self, name, value):
self.symbols[name] = value
def remove(self, name):
... |
class BoidRuleAvoid:
fear_factor = None
object = None
use_predict = None
|
#!/usr/bin/env python
# Whites/Pastels
snow = (255, 250, 250)
snow2 = (238, 233, 233)
snow3 = (205, 201, 201)
snow4 = (139, 137, 137)
ghost_white = (248, 248, 255)
white_smoke = (245, 245, 245)
gainsboro = (220, 220, 220)
white = (255, 255, 255)
# Grays
black = (0, 0, 0)
dark_slate_black = (49, 79, 79)
dim_gray = (105... |
"""
This is the core of deep learning: (1) Take an input and desired output, (2) Search for their correlation
"""
def compute_error(b, m, coordinates):
"""
m is the coefficient and b is the constant for prediction
The goal is to find a combination of m and b where the error is as small as possible
coor... |
hashicorp_base_url = "https://releases.hashicorp.com"
def _terraform_download_impl(ctx):
platform = _detect_platform(ctx)
version = ctx.attr.version
# First get SHA256SUMS file so we can get all of the individual zip SHAs
ctx.report_progress("Downloading and extracting SHA256SUMS file")
sha256sums... |
# Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements; and to You under the Apache License, Version 2.0.
"""OpenWhisk "Hello world" in Python.
// Licensed to the Apache Software Foundation (ASF) under one or more contributor
// license agreements; and to You under the A... |
# -*- coding: utf-8 -*-
# @ Time : 2020/9/8 14:56
# @ Author : Redtree
# @ File : config.py
# @ Desc :
VERSION = 'V0.1'
'''
database_setting
'''
DIALCT = "mysql"
DRIVER = "pymysql"
USERNAME = "mysql-username"
PASSWORD = "123456"
HOST = "数据库连接地址"
PORT = "数据库服务端口"
DATABASE = "testdb"
DB_URI = "{}+{}://{}:{}@{}:{}... |
# OSEK Builder Global Variables (OB Globals)
# ------------------------------------------
# list of column titles in TASK tab of OSEX-Builder.xlsx
TaskParams = ["Task Name", "PRIORITY", "SCHEDULE", "ACTIVATION", "AUTOSTART",
"RESOURCE", "EVENT", "MESSAGE", "STACK_SIZE"]
TNMI = 0
PRII = 1
SCHI = 2
ACTI = 3
ATSI = 4... |
# -*- coding: utf-8 -*-
{
'name': 'Chapter 14 code for the mail template recipe',
'depends': ['mail', 'report_py3o'],
'data': [
'views/library_book.xml',
'views/library_member.xml',
'data/py3o_server.xml',
'reports/book_loan_report.xml'
],
'demo': ['demo/demo.xml'],
}... |
#Write a Python program to remove duplicates from a list.
sample_list = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40]
duplicate_items =set()
unique_list = []
for num in sample_list:
if num not in duplicate_items:
unique_list.append(num)
duplicate_items.add(num)
print(unique_list) |
"""
Utils for URLs (to avoid circular imports)
"""
DASHBOARD_URL = '/dashboard/'
PROFILE_URL = '/profile/'
PROFILE_PERSONAL_URL = '{}personal/?'.format(PROFILE_URL)
PROFILE_EDUCATION_URL = '{}education/?'.format(PROFILE_URL)
PROFILE_EMPLOYMENT_URL = '{}professional/?'.format(PROFILE_URL)
SETTINGS_URL = "/settings/"
SE... |
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
res=""
strs.sort()
for i in xrange(len(strs[0])):
if strs[0][i]==strs[-1][i]:
... |
# coding: utf-8
class CartesianProduct:
def extract(self,val,row):
if isinstance(val, list):
for v in val:
row.append(v)
else:
row.append(val)
def combi(self,x, y, result):
#print("combi before",x,y,result)
row = []
for i in x:
... |
def keywordMatching(amazonTitle,wallmartTitles,wallmartPrices,wallmartIds):
#whitelist of letters
whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')
amazonTitle = ''.join(filter(whitelist.__contains__, amazonTitle))
titles = []
commonalities = []
for i in wallmartTitles:... |
# -*- coding: utf-8 -*-
'''
File name: code\gozinta_chains\sol_548.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #548 :: Gozinta Chains
#
# For more information see:
# https://projecteuler.net/problem=548
# Problem Statement
'''
A goz... |
class RandomVariable:
def __init__(self):
self._parametrization = None
def sample(self):
pass
def as_tensor(self):
pass
def make_parametrization(self):
pass
class Parametrization:
def __init__(self):
self._free_vars = []
self._trainable_params = [... |
lines = [l.strip() for l in open('input.txt', 'r').readlines()]
p1, p2, first_player = [], [], True
for line in lines:
if 'Player 2' in line:
first_player = False
if not line or 'Player' in line:
continue
if first_player:
p1.append(int(line))
else:
p2.append(int(line))
def determine_winner(p1, p2):
memo... |
# -*- coding: utf-8 -*-
{
'name': 'Slovak - Accounting',
'version': '1.0',
'author': '26HOUSE',
'website': 'http://www.26house.com',
'category': 'Accounting/Localizations/Account Charts',
'description': """
Slovakia accounting chart and localization: Chart of Accounts 2020, basic VAT rates +
f... |
"""
Prácticas de Redes de comunicaciones 2
Autores:
Miguel Arconada Manteca
Mario García Pascual
credenciales:
Este fichero contiene los credenciales que utilizamos para usar
SecureBox.
"""
my_token = '7E4DA9B6a2C0beF3'
my_nia = '361902'
|
# fibonacci: int -> int
# calcula el n-esimo numero de la sucesion de fibonacci
# ejemplo: fibonacci(7) debe dar 13
def fibonacci(n):
assert type(n) == int and n>=0
if n<2:
# caso base
return n
else:
# caso recursivo
return fibonacci(n-1) + fibonacci(n-2)
# test:
assert fib... |
# Given a non-empty string, encode the string such that its encoded length is the shortest.
# The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets
# is being repeated exactly k times.
# Note:
# k will be a positive integer and encoded string will not be empty or have extra space... |
def get_gnn_config(parser):
parser.add_argument('--ggnn_keep_prob', type=float, default=0.8)
parser.add_argument('--t_step', type=int, default=3)
parser.add_argument('--embed_layer', type=int, default=1)
parser.add_argument('--embed_neuron', type=int, default=256)
parser.add_argument('--prop_lay... |
X = int(input())
Y = float(input())
consumoMédio = X / Y
print('{:.3f} km/l'.format(consumoMédio))
|
"""Package management"""
# Copy paste this at the top of a file to have it work with with both modulare
# imports and running as a direct script
# import os
# import sys
#
# sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../') |
BLACK = 0x000000
WHITE = 0xFFFFFF
GRAY = 0x888888
DARKGRAY = 0x484848
ORANGE = 0xFF8800
DARKORANGE = 0xF18701
LIGHTBLUE = 0x5C92D1
BLUE = 0x0000C0
GREEN = 0x00FF00
PASTEL_GREEN = 0x19DF82
SMOKY_GREEN = 0x03876D
PINK = 0xD643BB
PURPLE = 0x952489
DEEP_PURPLE = 0x890C32
YELLOW = 0xF4ED06
# RED = 0xC80A24
RED = 0xDE0A07
BR... |
# pytools/recursion/subsets.py
#
# Author: Daniel Clark, 2016
'''
This module contains functions to return all of the subsets of a given
set
'''
def subsets_reduce(input_set):
'''
Reduce function method for returning all subsets of a set
'''
return reduce(lambda z, x: z + [y + [x] for y in z],
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
##f1(node) be the value of maximum money we can rob from the subtree with node as root ( we can rob node if necessary).
##f2(node) be the value of maximum m... |
number_grid = [ [1, 2, 4],
[2, 5, 6],
[3, 4, 6] ]
print(number_grid[0][0])
print(number_grid[2][2])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.