content stringlengths 7 1.05M |
|---|
# 给定一个经过编码的字符串,返回它解码后的字符串。
#
# 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
#
# 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
#
# 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
#
# 示例:
#
# s = "3[a]2[bc]", 返回 "aaabcbc".
# s = "3[a2[c]]", 返回 "accaccacc".
# s = "2[abc]3[cd]ef", 返回... |
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.width * self.height
def get_perimeter(self):
return 2 * se... |
def demo_filter():
num_list = list( range(1, 11) )
## Example_#1:
# pick even number
result = list( filter( lambda x:x%2==0, num_list) )
# [2, 4, 6, 8, 10]
print( result )
## Example_#2:
# pick odd number
result = list( filter( lambda x:x%2==1, num_list) )
# [1, 3, 5, 7, 9... |
#35 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
primeira_reta = float(input("Digite o valor da primeira reta"))
segunda_reta = float(input("Digite o valor da segunda reta"))
terceira_reta = float(input("Digite o valor da terceira reta"))
if pr... |
courses = {
"js": "JavaScript 101",
"python": ["Python 101", "Python 201"],
"html": "HTML 101"
}
# print(courses.get("css", "CSS 101"))
if courses.get("css", None):
print("You are enrolled in CSS 101")
|
def instance_name_check(test, resource, key, value):
if test == "ISBAD":
if resource[key].startswith(value):
return True
else:
return False
else:
return False
|
'''
Given a list A of numbers (integers), you have to print those numbers which are not multiples of 5.
>>Input Format:
The first line contains the numbers of list A separated by a space.
>>Output Format:
Print the numbers in a single line separated by a space which are not multiples of 5.
>>Example:
Input:
1 2 ... |
GOOGLEAPIS_BUILD_FILE = """
filegroup(
name = "annotations_protos",
srcs = [
"google/api/annotations.proto",
"google/api/http.proto",
],
visibility = ["//visibility:public"]
)
"""
DEPS = {
"com_github_grpc_ecosystem_grpc_gateway": {
"rule": "go_repository",
"importpath": "github.co... |
class Solution:
def solve(self, nums, k):
if not nums: return 0
if nums.count(0) <= k: return len(nums)
locs = [-1]+[i for i in range(len(nums)) if nums[i] == 0]+[len(nums)]
ans = -1
for i in range(k,len(locs)-1):
ans = max(ans, locs[i+1]-locs[i-k]-1)
r... |
# Error Messages
ENTRY_ALREADY_EXISTS = 'Help entry already exists for tag "{}".'
NO_ENTRY = 'No help entry for tag "{}".'
NO_FILE_AT_PROVIDED_PATH = 'No file found at provided path: {}'
# Success Messages
ADD_SUCCESS_NO_SEED_FILE = 'Successfully added help entry "{}".'
ADD_SUCCESS_WITH_SEED_FILE = 'Successfully added... |
list = [('abc.es','HTTP/1.1 200',0,0,0,0,0),
('abcnews.go.com','HTTP/1.1 200',2,0,0,0,'/'),
('about.me','HTTP/1.1 200',5,1,1,'Lax','/'),
('abril.com.br','HTTP/1.1 301',1,1,1,0,'/'),
('alibaba.com','HTTP/1.1 200',1,0,0,0,'/'),
('ap.org','HTTP/1.1 200',0,0,0,0,0),
('biblegateway.com','HTTP/1.1 200',0,0,0,0,0),
('b... |
def super_func(*args):
total = sum(args)
print(total)
super_func(1, 2, 3, 4)
def super_func2(**kwargs):
total = 0
for value in kwargs.values():
total += value
print(total)
super_func2(num1 = 1, num2 = 2, num3 = 3, num4 = 4) |
"""Module for defining constants"""
FASTA = 'fasta'
FASTQ = 'fastq'
|
46
1280
7
800
13
3000
5000
50000
|
class PushException(Exception):
pass
class PushAuthException(PushException):
pass
class PushInvalidTokenException(PushException):
pass
class PushInvalidDataException(PushException):
pass
class PushServerException(PushException):
pass
|
#!/usr/bin/python
class RLFNodeColoring1:
"""Recursive Largest First (RLF) algorithm for node coloring."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError("the graph is directed")
self.graph = graph
self.color ... |
FONT = 'Tahoma 12'
PAUSE = 0.15
TIMES_SEPARATOR = '-'
CASE_SEPARATOR = '#'
DAY = slice(None, 2)
MONTH = slice(3, 5)
YEAR = slice(6, None)
HOUR = slice(None, 2)
MINUTE = slice(3, None) |
CHALLENGE_PERIOD = 20
PLASMA_BLOCK_INTERVAL = 10
MAX_TREE_DEPTH = 8
|
# -*- coding:utf-8 -*-
"""
db_config.py
~~~~~~~~~~~~
database config info.
"""
# my mysql config
info = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': '',
'database': 'zhihu',
'charset': 'utf8'
} |
def leia_inteiro(_texto):
while True:
numero = str(input(_texto))
if numero.isnumeric():
return numero
else:
print('Erro! Digite um número inteiro válido!')
numero = leia_inteiro('Digite um número: ')
print('Você acabou de digitar o número {}.'.format(numero))
|
"""
attr_dict.py
Implements AttrDict class for defining an attribute dictionary that allows us
to address keys as if they were attributes.
Idea taken from:
https://danijar.com/patterns-for-fast-prototyping-with-tensorflow/
Author: Sam Foreman
Date: 04/09/2019
"""
class AttrDict(dict):
"""A dict which is ac... |
r"""
Logo
----
Uses :mod:`dummy` backend.
File: `\\examples\\withDummy\\logo_xrt.py`
:mod:`xrt` logo (on the right, in two versions) created from a "flat" python
logo (on the left).
|ini_image| --------------> |logo_image| |logo_image_inv|
.. |ini_image| imagezoom:: _images/logo-python.*
:scale: 50 %
.. ... |
pensil_box = ["pen","pensil","eraser","candy","gum"]
print(pensil_box)
pensil_box.append("betmen_statue")
print(pensil_box)
|
def add(x, y):
""" Add two numbers and return their sum"""
return x+y
def subtract(x, y):
""" Subtract to numbers and return their results"""
return x-y |
l = []
s = '0123456789'
counter = 0
while counter < 1000000:
for a in s:
s0 = s.replace(a, '')
for b in s0:
s1 = s.replace(b, '')
for c in s1:
s2 = s.replace(c, '')
for d in s2:
s3 = s.replace(d, '')
... |
# CodeWars Kata/Digital Root
def digital_root(n):
if len(str(n)) == 1:
return n
else:
return digital_root(digit_sum(n))
def digit_sum(num):
return sum([int(char) for char in str(num)])
|
input = """
num(2).
node(a).
p(N) :- num(N), #count{Y:node(Y)} = N1, N<=N1.
"""
output = """
num(2).
node(a).
p(N) :- num(N), #count{Y:node(Y)} = N1, N<=N1.
"""
|
age = 37
name = 'Bob'
gender = 'male'
hobby = 'cycling'
timeofday = 'at night'
typeofbike = 'giant'
country = 'ireland'
sizeofwheels = '700'
print('{} {} {} was {} when he was {}'.format(timeofday,gender,name,hobby,age))
print('the sun is shining in the sky during the day')
print('{} flew to {} then bough... |
# Source : https://leetcode.com/problems/course-schedule-ii/
# Author : henrytine
# Date : 2020-08-09
#####################################################################################################
#
# There are a total of n courses you have to take, labeled from 0 to n-1.
#
# Some courses may have prerequisit... |
"""
The Generalized Balanced Symbols Problem.
https://bradfieldcs.com/algos/stacks/balanced-parentheses/
Given a string of opening and closing symbols, how to tell if they're balanced?
---
((({}[]))) -> true
((())) -> true
(()) -> true
() -> true
()()() -> true
()[]{} -> true
([{}]) -> true
---
()) -> false
))(( ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 28 19:45:42 2018
@author: twope
"""
'''
加入一个新feature
'''
def future_revenue(df):
period_future = df.groupby('fullVisitorId')['totals_transactionRevenue'].sum()
period_future = period_future.reset_index()
period_future.rename(columns = {'totals_tr... |
# Enter your code for "Costly cake!" here.
c1sl = input("Cake 1 side length (cm): ")
c1c = input("Cake 1 cost ($): ")
c2sl = input("Cake 2 side length (cm): ")
c2c = input("Cake 2 cost ($): ")
c1sa = float(c1sl) ** 2
c2sa = float(c2sl) ** 2
c1cp = float(c1c) / c1sa
c2cp = float(c2c) / c2sa
print ("Cake 1 costs $%.2... |
"""
Entradas
d-->int
Salidas
a-->int
b-->int
c-->int
"""
a=int(input("Digite el valor de a: "))
b=int(input("Digite el valor de b: "))
c=int(input("Digite el valor de c: "))
d=int(input("Digite el valor de d: "))
if (d==0) :
e=(a-c)**2
print("el valor de b sera de :" +str(e))
elif (d>0):
e=(a-b)**2/d
print("el v... |
class UVGridlineType(Enum, IComparable, IFormattable, IConvertible):
"""
A choice between U-gridlines or V-gridlines of a divided surface
U Gridlines
V Gridlines
enum UVGridlineType,values: U (0),V (1)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==>... |
# 上报网站的 API 的地址
LOGIN_API = 'https://app.bupt.edu.cn/uc/wap/login/check'
REPORT_PAGE = 'https://app.bupt.edu.cn/ncov/wap/default/index'
REPORT_API = 'https://app.bupt.edu.cn/ncov/wap/default/save'
DAILYUP_PAGE = 'https://app.bupt.edu.cn/xisuncov/wap/open-report/index'
DAILYUP_API = 'https://app.bupt.edu.cn/xisuncov/wap... |
# https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/
# Suppose an array of length n sorted in ascending order is rotated between 1 and
# n times. For example, the array nums = [0,1,4,4,5,6,7] might become:
# Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in
# the arra... |
# day 16 challenge 2
# actually figure things out
# can ignore everything prior to line 26 (25 when 0 indexed) when getting nearby
raw = []
with open('input.txt', mode='r') as file:
for line in file.readlines()[25:]:
raw.append([int(num) for num in line.strip().split(',')])
# grab our own ticket, too
with... |
N, a, b, c = int(input()), int(input()), int(input()), int(input())
ans = 0
if b - c < a and N >= b:
ans += (N - b) // (b - c) + 1
N = (N - b) % (b - c) + c
print(ans + N // a)
|
DISTRICTS_TO_PROVINCE = dict(s.split("\t") for s in """
DC10 EC
DC10 EC
DC10 EC
DC12 EC
DC12 EC
DC13 EC
DC13 EC
DC14 EC
DC14 EC
DC15 EC
DC15 EC
DC15 EC
DC15 EC
DC15 EC
DC44 EC
DC16 FS
DC16 FS
DC16 FS
DC18 FS
DC18 FS
DC18 FS
DC18 FS
DC18 FS
DC19 FS
DC19 FS
DC19 FS
DC19 FS
DC19 FS
DC19 FS
DC20 FS
DC20 FS
DC20 FS
DC20 FS
... |
class DBRouter:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'thirdapp':
return 'custom'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'thirdapp':
return 'custom'
return None
def allow_relation(self, obj1, obj2, **... |
# -*- coding: utf-8 -*-
#==============================================================================
# uniq
#==============================================================================
def uniq(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if x not in seen and not seen_add(x)]
|
def hanoi(pegs, start, target, n):
assert len(pegs[start]) >= n, 'not enough disks on peg'
if n == 1:
pegs[target].append(pegs[start].pop())
print ('%i -> %i: %s' % (start, target, pegs))
else:
aux = 3 - start - target # start + target + aux = 3
hanoi(pegs, start, aux, n-1)
... |
def help_(_, update):
update.message.reply_text(
'This bot can remember stickers to help you find them more easily.\n'
'\n'
'To add a sticker, just send it to me in private. To manage sticker\'s'
' tags, reply to a sticker with commands /add_tags or /delete_tag.'
) |
print("""
Exercício 25 da aula 09 de Python
Curso do Guanabara
Day 7 Code Python - 06/05/2018
""")
nome = str(input('Qual o seu nome completo: ')).strip()
print('Seu nome tem Cirino? {}'.format('cirino' in nome.lower()))
|
class Entertainment:
'''
Sources class to define Sources Objects
'''
def __init__(self,idNumber,name,description,publishedAt,source_url):
self.idNumber = idNumber
self.name = name
self.description = description
self.publishedAt = publishedAt
self.source_url = source_url |
"""
48 - Faça um programa que some os termos de valor par da sequencia de Fibonacci, cujos valores não ultrapassem quatro milhões
"""
a, b = 0, 1
while b < 3000000:
if b % 2 == 0:
print(b)
a, b = b, a+b
print(f'Soma dos valores pares da sequancia de Fibonacci que não ultrapassam quatro milhões: {b}')
|
'''
numero = input('Digite um número:')
numero = int(numero)
dobro = 2 * numero
print(dobro)
'''
n1 = input('Digite o primeiro número: ')
n2 = input('Digite o segundo número: ')
n1 = float(n1)
n2 = float(n2)
divisao = n1 / n2
resto = n1 % n2
print('Divisão igual à', divisao)
print('O resto da d... |
n = int(input())
l = []
for i in range(n):
a = list(map(int,input().split(sep=" ", maxsplit=n)))
l.append(a)
sum_1 = 0
sum_2 = 0
for i in range(n):
sum_1 = sum_1 + l[i][i]
sum_2 = sum_2 + l[i][n-1-i]
diff = sum_1 - sum_2
if diff >=0:
print(diff)
else: print(-diff)
|
with open('backup/name1.txt', 'r') as file1:
c1 = set(file1.readlines())
with open('backup/name2.txt', 'r') as file2:
c2 = set(file2.readlines())
c3 = list(c1.union(c2))
c4=[]
for i in c3:
c4.append(i.strip('\n'))
with open('backup/merge.txt', 'w') as file3:
file3.write(' '.join(c4))
|
encoding_size = 3
model = nn.Sequential(nn.Linear(input_size, int(input_size/2)),
nn.PReLU(),
nn.Linear(int(input_size/2), encoding_size*32),
nn.PReLU(),
nn.Linear(encoding_size*32, encoding_size),
nn.PReLU(),... |
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
a.sort()
for i in range(n):
if a[i] == i + 1:
continue
print("No")
return
print("Yes")
if __name__ == "__main__":
main()
|
#from . import module3a # ok but pylint makes an error: Attempted relative import beyond top-level package (relative-beyond-top-level)
def func3b():
print('3b')
#module3a.func3a()
|
# The frequently used ranges
RANGE3 = range(3)
RANGE9 = range(9)
RANGE81 = range(81)
CANDIDATES_RANGE = range(1, 10)
# This divider is printed to separate the parts
DIVIDER = "-------+-------+-------"
# These are the constants used to group "chunks" or areas in Sudoku
# These areas are the ones where the constraints ... |
# Belajar Numeric Types
# Ada 3 Jenis yaitu :
# 1. Integer
# 2. Float
# 3. Complex --> ada angka real dan angka imaginer
angka = 5
angka2 = 5.5
total = angka + angka2
print("data :", angka, type(angka))
print("data :", total, type(total))
print(10/2) # menggunakan operasi matematika pe... |
# 못 푼 문제 시간복잡도가 높음..
n = int(input())
data = list(input().split())
dx = [0, -1, 0, 1]
dy = [1, 0, -1, 0]
x = 1
y = 1
for i in data:
if x <= 0 or x >= n or y <= 0 or y >= n:
continue
if i == 'R':
x += dx[0]
y += dy[0]
if i == 'U':
x += dx[1]
y += dy[1]
if i == '... |
# * ex2 - Entrar com 15 números e escrever quantos números maiores que 30 foram digitados.
i = 1
a = 0
while i <= 15:
num = int(input('Insira o número: '))
if num > 30:
a += 1
i += 1
print(f'Foram inseridos {a} números acima 30')
|
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
curr = 0
largest = -float('inf')
for n in nums:
curr += n
if n > curr:
curr = n
largest = max((... |
"""Kata url: https://www.codewars.com/kata/597754ba62f8a19c98000030."""
def vowel_change(txt: str, vow: str) -> str:
return txt.translate(str.maketrans('aeiou', vow * 5))
|
''' A collection of html templates used by biothings APIs '''
HTML_OUT_TEMPLATE = '''
<html>
<head>
<link href="https://cdn.rawgit.com/josdejong/jsoneditor/v5.11.0/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.... |
#! /usr/bin/env python
# Módulo que define os movimentos do agente
# Objeto DELTA usado para mover o agente e alcançar seus vizinhos
DELTA = (0, -1), (1, 0), (0, 1), (-1, 0)
def neighbors(location, size=(4, 4)):
"""Retorna um gerador para os quartos vizinhos."""
x, y = location
width, height = size
... |
# -*- encoding: utf-8 -*-
# allowdebugfeatures
def breakline(line, width):
index = line.rfind(' ', 0, width + 1)
if index == -1: return
return line[:index], line[index+1:]
def breaklines(text, width, baseindentation):
if len(text) <= width or ' ' not in text:
return
lines = [... |
class IncompleteVoteError(Exception):
pass
class NoWinnerError(Exception):
pass
class InvalidVoteError(Exception):
pass
class FailedElectionError(Exception):
pass
|
"""
* Module Name: ErrorHandle
* Module Purpose: Define and handle all error messages for requests
"""
|
"""Dadata client settings"""
TIMEOUT_SEC = 3
SUGGESTION_COUNT = 10
|
s = 'hdbobbbobobobobobobooboobobobob'
count = i = 0
while True:
j = s.find('bob', i)
if j == -1 :
break
count += 1
i = j + 1
print('Number of times bob occurs is: '+str(count)) |
class ProgressSend():
def __init__(self, task):
self.task = task
self.description = ""
self.percentage = 0
self.subProgress = []
self.header = ""
def send_progress(self, percentage=None, subProgress=[], description="", header=""):
state = 'PROGRESS'
... |
x = []
for i in range(10):
if i % 2 == 0:
x.append(dask.delayed(square)(i))
else:
x.append(dask.delayed(add)(i, i))
y = dask.delayed(sum)(x)
# use `y.visualize()` to visualize the graph and `y.compute()` to execute it.
|
# Author: Sanket Dalvi
# Question Link: https://leetcode.com/problems/restore-ip-addresses/
class Solution:
def __init__(self):
super().__init__()
self.ipList = []
def getList(self, level, A, suffix):
if level > 3:
if len(suffix)-4 == len(A) and suffix[1:] not in self.ipList... |
class streaming_service_type:
netflix = "netflix"
amazon = "amazon"
youtube = "youtube"
other = "other" |
w = int(input())
n = int(input())
s = 0
for i in range(n):
a, b = map(int, input().split())
s += a * b
print(s//w) |
# -*- coding: utf-8 -*-
__title__ = "huvr_client"
__description__ = "Python Client for HUVRdata"
__url__ = "https://www.huvrdata.com"
__version__ = "0.2.8"
__build__ = 0x022200
__author__ = "HUVRdata"
__author_email__ = "api@huvrdata.com"
__license__ = "BSD 2.0"
__copyright__ = "Copyright 2019 HUVRdata LLC"
|
#!/bin/python3
class MessageHandler:
__message_type = ['Error', 'Information', 'Warning', 'Debug']
def __init__(self, date_format):
self.date_format = date_format
def new_message(message, message_code, message_type='Information'):
if message_type not in self.__message_type:
raise Exception('Un... |
#!/usr/bin/env python3
def main(msg="Hello, World!"):
print(f"\x1b[32m{msg}\x1b[0m")
if __name__ == '__main__':
args = __import__('sys').argv[1:]
if len(args) >= 1:
args = ' '.join(args)
if args:
main(args)
else:
main()
|
# bubble sort algorithm
# O(n^2) time complexity
# O(1) space complexity
def bubblesort(list, comp):
for x in range(len(list) - 1):
for y in range(len(list) - (x + 1)):
curr = list[y]
adj = list[y + 1]
if (comp(curr, adj) > 0):
list[y + 1] = curr
... |
class Employee:
def __init__(self, name, payRate):
self.name = name
self.pay = payRate
def __str__(self):
return 'EmpName: ' + self.name + 'EmpPay: ' + str(self.pay)
def grossPay(self, hoursWorked):
return self.pay * hoursWorked
class M... |
def add_values(a, b, c=0, d=0):
print(a + b + c + d)
add_values(2, 3)
add_values(2, 3, 4)
add_values(2, 3, d=7)
print("Ala ma kota", end=". \n")
print("A kotek jest bury")
|
# -*- coding: utf-8 -*-
"""
Author: Rafael R. L. Benevides
Date: 15/11/2021
"""
__version__ = '0.1.dev0'
__author__ = 'Rafael R. L. Benevides'
__email__ = 'rafaeluz821@gmail.com'
__description__ = "Math tools for engineering"
__url__ = 'https://github.com/RafaelLuz/jerimoon'
|
card, sel_sum=map(int, input().split())
card_num=list(map(int, input().split()))
max_count=0
for i in range(card):
count=card_num[i]
for j in range(i+1,card):
j_count=count+card_num[j]
for k in range(j+1,card):
if j_count+card_num[k]>sel_sum:
continue
else... |
#!/usr/bin/python
name = 'arkady'
str1 = str(input('Please add first string: '))
str2 = str(input('Please add second string: '))
num = int(input('Please add number between 1 and 3 :'))
while int(num < 0 or num > 3):
if num > 3:
print("Number is bigger then 3")
else:
print("Number is l... |
# https://www.codechef.com/problems/CHEFARRP
for T in range(int(input())):
n,c=int(input()),0
l=list(map(int,input().split()))
for i in range(1,n):
s,p=0,1
for j in range(i,-1,-1):
s,p=s+l[j],p*l[j]
if(s==p): c+=1
print(c+1) |
name = input("What is your name? ")
age = input("How old are you? ")
city = input("Where are you live? ")
print("This is {0}.".format(name))
print("It is {0}.".format(age))
print("S(he) live in {0}.".format(city))
|
class Node(object):
def __init__(self, data=None, next=None):
self.data_ = data
self.next_ = next
def get_data(self):
return self.data_
def set_data(self, data):
self.data_ = data
def get_next(self):
return self.next_
def set_next(self, next)... |
class SessionService:
SESSION_LAST_SET_DUT_COMPANY_ID = 'last_set_dut_company_id'
SESSION_LAST_SET_DUT_CATEGORY_ID = 'last_set_dut_category_id'
SESSION_LAST_SET_DUT_LOCATION_ID = 'last_set_dut_location_id'
SESSION_LAST_SET_TEMPLATE_COMPANY_ID = 'last_set_template_company_id'
SESSION_LAST_SET_TEMPLA... |
left={"w":4, "p":3, "b":2, "s":1}
right={"m":4, "q":3, "d":2, "z":1}
def alphabet_war(fight):
if len(fight)==1:
return "Left side wins!" if fight in "wpbs" else "Right side wins!" if fight in "mqdz" else "Let's fight again!"
res=""
for i,j in enumerate(fight):
if j=="*":
continue... |
"""
Author: André Bento
Date last modified: 1-04-2019
"""
def diff(list_1, list_2):
return list(set(list_1).difference(set(list_2)))
def symmetric_diff(list_1, list_2):
"""
Performs the difference between two lists. In this context the difference is what is in list_1 but not in list_2,
and w... |
#
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued ter... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: enums
class Frequency(object):
Annual = 0
Bimonthly = 1
Biweekly = 2
Daily = 3
EveryFourthMonth = 4
EveryFourthWeek = 5
Monthly = 6
NoFrequency = 7
Once = 8
OtherFrequency = 9
Quarterly = 10
... |
text = input()
result_string = []
digits = [int(i) for i in text if i.isdigit()]
non_digits = [i for i in text if not i.isdigit()]
take_list = [num for idx, num in enumerate(digits) if idx % 2 == 0]
skip_list = [num for idx, num in enumerate(digits) if idx % 2 != 0]
take_skip_list = list(zip(take_list, skip_list))
s... |
class Solution:
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
i, len1 = 2, len(s)
if len1 == 1: return False
if s == s[0] * len1: return True
while i * i < len1:
if len1 % i == 0:
flag = 1
... |
#
# PySNMP MIB module GDC-SC553-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/GDC-SC553-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:18:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
#ui class
class UI:
def welcome():
print('Welcome to the Blackjack Trainer!')
print('This program is designed to help you practice your blackjack.')
print('Enter q to quit at any time.')
def hand_display(dealer_hand, hand):
print('Dealer shows:', dealer_hand[1])
pri... |
numbers = [1,2,3,4,5]
# see contents of the array
print(numbers)
# length of the array
print(len(numbers))
#add to array
numbers.append(6)
namelist = []
#namelist = list()
# add names
namelist.append('name')
name = input("Enter your name: ")
if name in namelist:
print("I know you!")
else:
print("Sorry,... |
class Periodo:
def __init__(self, codigo, nome, disciplina_lista):
self._id = codigo
self._nome = nome
self._disciplina_lista = disciplina_lista
def get_id(self):
return self._id
def get_nome(self):
return self._nome
def get_disciplina_lista(self):
... |
pubkey = 569581432115411077780908947843367646738369018797567841
with open("flag.enc") as f:
encoded = f.read()
flag = ""
for c in encoded.split(','):
if not c: break
if int(c, 16) != 0:
flag += "0"
else:
flag += "1"
print(hex(int(flag, 2))[2:].rstrip("L").decode("hex"))
|
class test_package:
def __init__(self):
# constructor
self.f = 1
def calc_string(self, equation):
equation = equation.strip()
if equation.isdigit():
return int(equation)
if '+' in equation:
temp = equation.split('+')
total = 0
... |
def Copy(file1='Weird.txt',file2='Weirdv2.txt'):
f=open(file2,'w')
lst=open(file1,'r').readlines()
for x in lst:
f.write(x)
f.close()
Copy(file1='Weird.txt',file2='Weirdv2.txt')
|
# coding: utf-8
def array_key_exists(key, d):
return key in d
if __name__ == '__main__':
search_array = {'first': 1, 'second': 4, '': False}
print(array_key_exists('first', search_array))
|
# I'm used to create a file which holds names of tables only and to call these names in the notebooks while reading data
# so that only changing this module will be quite efficient in case of any change of data sets to be used.
# Since I create this sample project in my local computer, I don't have access to Hive an... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
class Position(list):
def __init__(self, x: int, y: int):
super().__init__((0, 0))
self.x = x
self.y = y
@property
def x(self):
return self[0]
@x.setter
def x(self, value):
if 0 <= value <= 12:
sel... |
class InvalidSignatureError(Exception):
""" """
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.