content stringlengths 7 1.05M |
|---|
#!/usr/local/bin/python3
def resultado_f1(**kwargs):
for posicao, piloto in kwargs.items():
print(f'{posicao} -> {piloto}')
if __name__ == '__main__':
resultado_f1(primeiro='Hamilton', segundo='Massa')
podium = {'primeiro': 'Hamilton', 'segundo': 'Massa'}
resultado_f1(**podium)
|
"""
sspanel.urls
This module contains static URLs (and one incomplete URL)
"""
USER_LOGIN_URL = "https://www.survivalservers.com/sspanel/includes/ajax/validate_login.php"
SUBUSER_LOGIN_URL = "https://www.survivalservers.com/sspanel/includes/ajax/validate_subuser_login.php"
LOGOUT_URL = "https://www.survivalservers.co... |
county_names = [
'Autauga County, Alabama',
'Baldwin County, Alabama',
'Barbour County, Alabama',
'Bibb County, Alabama',
'Blount County, Alabama',
'Bullock County, Alabama',
'Butler County, Alabama',
'Calhoun County, Alabama',
'Chambers County, Alabama',
'Cherokee County, Alabama',
'Chilton County, Alabama'... |
#Write a class complex to represent complex numbers,
#along with overloaded operators + and * which adds and multiplies them.
#Formula --> (a+bi)(c+di) = (ac-bd) + (ad+bc)i
class Complex:
def __init__(self, r, i):
self.real = r
self.imaginary = i
def __add__(self, c):
return Complex(s... |
guess = None
value = 5
trial = 5
print("WELCOME TO OUR GUESS GAME")
while trial > 0:
print('Your remaining trial is {}'.format(trial))
guess = int(input('enter a number: '))
if guess == value:
print('You win')
break
else:
trial = trial-1
else:
print('You loss')
|
class IllegalArgumentException(Exception):
pass
class LinkedList:
class _Node:
def __init__(self, val=None, next_node=None):
self.val = val
self.next = next_node
# def __str__(self):
# return str(self.val)
# def __repr__(self):
# return... |
line_num = 0
total = 0
visited = {}
with open("day8.txt") as f:
data = f.readlines()
def nop(num):
global line_num
line_num += 1
def jmp(num):
global line_num
line_num += num
def acc(num):
global total
global line_num
total += num
line_num += 1
cmds ... |
# Divyanshu Lohani: https://github.com/DivyanshuLohani
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
n = 5
pypart(n) |
built_modules = list(name for name in
"Core;Gui;Widgets;PrintSupport;Sql;Network;Test;Concurrent;Xml;Help;OpenGL;OpenGLFunctions;OpenGLWidgets;Qml;Quick;QuickControls2;QuickWidgets;Svg;SvgWidgets;UiTools"
.split(";"))
shiboken_library_soversion = str(6.0)
pyside_library_soversion = str(6.0)
version = "6.0.0"
... |
'''
Pattern
Enter number of rows: 5
5
54
543
5432
54321
'''
print('Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(number_rows,0,-1):
for column in range(number_rows,row-1,-1):
if column < 10:
print(f'0{column}',end=' ')
else:
print(column,end=' ')
print()
|
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# statsRetention : Stats retention
def get_all_stats_retention(self) -> dict:
"""Get all statistics retention configuration
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpo... |
line = input().split()
n = int(line[0])
m = int(line[1])
ans = min(n,m)
if(ans%2==0):
print("Malvika")
else:
print("Akshat")
|
data = open("day15.txt").read().replace("\n", "").split(",")
data = [int(x) for x in data]
def find_last_number(data, stop):
previous = data[-1]
turn = len(data)
last_spoken = {value: key + 1 for key, value in enumerate(data[:-1])}
while turn < stop:
new_number = turn - \
last_spok... |
class BasePagination(object):
"""
Class that make queryset paginated
"""
model = None
def __init__(self, cursor, items_per_page, model):
"""
:param cursor: field that would be direction for pagination
:param items_per_page: items per each page
:param model: model cla... |
# Approach 2 - Left-to-Right Pass Improved
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
"IV": 4,
"IX": 9,
"XL": 40,
"XC": 90,
"CD": 400,
"CM": 900
}
class Solution:
def romanToInt(self, s: str) -> int:
total = 0
i ... |
class TreeNode:
def __init__(self, data):
self._data = data
self._children = []
def __repr__(self, level=0):
res = "\t" * level + repr(self._data) + "\n"
for child in self._children:
res += child.__repr__(level + 1)
return res
class BSTNode:
def __init_... |
#
# PySNMP MIB module CTRON-SSR-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SSR-TRAP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:31:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
remote = ("example.com", 80)
page = "/response"
auth = ""
reqthreads = 4
|
class Queue:
def __init__(self):
self.__items = []
def enqueue(self, item):
self.__items.append(item)
def dequeue(self):
if not self.length():
raise QueueEmptyException()
item = self.__items[0]
self.__items = self.__items[1:]
return item
def... |
# 从头到尾打印链表
# 输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
# 链表结构
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 打印链表
def printChain(head):
node = head
while node:
print(node.val)
node = node.next
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFr... |
"""Aula 06: Linux - MariaDB Server + MySQL Workbench
[comandos]
sudo apt-get update
sudo apt-get install mariadb-server
sudo mysql -u root
USE mysql;
UPDATE user SET plugin='' WHERE User='root';
FLUSH PRIVILEGES;
exit
sudo apt-get install mysql-workbench
"""
|
def solve(data, part_two=False):
max_found = -1
seat_ids = []
for l in data:
row_max = 127
row_min = 0
seat_max = 7
seat_min = 0
for c in l:
if c == 'F':
row_max = ((row_max-row_min) // 2) + row_min
elif c == 'B':
... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-12-04 09:48:17
# Description:
class Solution:
def longestWord(self, words: List[str]) -> str:
valid = set([""])
for word in sorted(words, key=lambda x: len(x)):
if word[:-1] in valid:
v... |
class Bipartite(object):
def __init__(self, graph):
self.is_bipartite = True
self.color = [False for _ in range(graph.v)]
self.marked = [False for _ in range(graph.v)]
self.edge_to = [0 for _ in range(graph.v)]
self.odd_length_cycle = []
for v in range(graph.v):
... |
# The objective is to find the summation of the odd elements in the array
# Define a simple array
sample =[12,33,54,89,776,3]
# Get length of the array
l= len(sample)
s=0
# Looping on the array up to max length to sum up the odd elements
for i in range(l):
if (i%2!=0):
s = s + int(sample[i])
#print the sum... |
"""
Module: 'os' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1
SDMODE_1LINE = 2
SDMODE_4LINE = 3
SDMODE_SPI = 1
def chdir():
pass
def dupterm():
pass
def dupterm_notify... |
class SmokeTestFail(Exception):
pass
class SmokeTestRegistry(object):
def __init__(self):
self.tests = {}
def register(self, sequence, name):
def decorator(fn):
self.tests[name] = {
'sequence': sequence,
'test': fn
}
ret... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 字典
# 查找和插入的速度极快,不会随着key的增加而变慢
# 需要占用大量的内存
dic = {'name':'hong', 'age':29}
print(dic)
print(dic['age'])
# 修改
dic['age'] = 30
dic['gender'] = 'male'
print(dic)
# 删除
del dic['gender']
print(dic)
# dic.clear()
# print(dic)
# 方法
print(str(dic))
|
# Stores JSON schema version, incrementing major/minor number = incompatible
CDOT_JSON_VERSION_KEY = "cdot_version"
# Keys used in dictionary (serialized to JSON)
CONTIG = "contig"
CHROM = "chrom"
START = "start"
END = "stop"
STRAND = "strand"
BEST_REGION_TYPE_ORDER = ["coding", "5PUTR", "3PUTR", "non coding", "intr... |
def int_from_rgb(r, g, b):
return (r << 16) + (g << 8) + b
def rgb_from_int(color):
return ((color >> 16) & 255), ((color >> 8) & 255), (color & 255)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Misc.py: Just a sample file with a function.
This material is part of this post:
http://raccoon.ninja/pt/dev-pt/python-importando-todos-os-arquivos-de-um-diretorio/
"""
def hey_ho():
return "Let's go!" |
# Runtime: 68 ms, faster than 87.39% of Python3 online submissions for Design Circular Queue.
# Memory Usage: 14.5 MB, less than 5.26% of Python3 online submissions for Design Circular Queue.
class MyCircularQueue:
class Node:
def __init__(self, val, prev=None, next=None):
self.val = val
... |
version = "2020.04.26内测版"
marker = "=================================="
center = "\t\t\t\t "
splitter = '=================================================================================================='
mapHeader = '________________________________________________________________________________________________'
m... |
questions = ['''A 2m long stick, when it is at rest, moves past an observer on the ground with a speed of 0.5c.
(a) What is the length measured by the observer ?
(b) If the same stick moves with the velocity of 0.05c what would be its length measured by the observer ''',''' A small lantern of mass 100 gm is hanged fro... |
# Copyright 2014-2017 Insight Software Consortium.
# Copyright 2004-2009 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
class byte_info(object):
"""
This class stores information about the byte size and byte align
values from a dec... |
#calculo da media
n1 = int (input('Digite a primeira nota: '))
n2 = int (input('Digite a segunda nota: '))
m= (n1+n2)/2
print('As notas foram {} e {}, então a média do aluno é {}\n'.format(n1, n2, m))
# 1 ()
# 2 ** potenciação
# 3 // * / %
# 4 + - |
pkg_dnf = {}
actions = {
'dnf_makecache': {
'command': 'dnf makecache',
'triggered': True,
},
}
files = {
'/etc/dnf/dnf.conf': {
'source': 'dnf.conf',
'mode': '0644',
},
}
if node.metadata.get('dnf', {}).get('auto_downloads', False):
pkg_dnf['yum-cron'] = {}
s... |
#https://stackabuse.com/parallel-processing-in-python/
def load_deck(deck_loc):
deck_list = open('vintage_cube.txt', 'r')
deck = Queue()
for card in deck_list:
deck.put(card)
deck_list.close()
return deck
|
n=[int(x) for x in input("Enter the numbers with space: ").split()]
x=[ ]
s=0
for i in range(len(n)):
for j in range(i+1,len(n)):
x.append((n[i],n[j]))
for i in range(int(len(x))):
a = min(x[i])+min(x[len(x)-i-1])
if(a>s):
s=a
print("OUTPUT: ",s)
|
valores = []
while True:
valores.append(int(input('Digite um número: ')))
continuar = str(input('Deseja continuar? [S/N] ')).upper().strip()[0]
while continuar not in 'SN':
continuar = str(input('Tente novamente! Deseja continuar? [S/N] ')).upper().strip()[0]
if continuar in 'N':
... |
class Params ():
def __init__(self):
print('HotpotQA')
self.name = "HotpotQA"
################################
# dataset
################################
data_path = ''
DATA_TRAIN = 'train.pkl'
DATA_DEV = 'dev.pkl'
DATA_TEST = 'dev.pkl'
... |
"""
Call ECMWF eccodes tools for manipulate grib files.
https://software.ecmwf.int/wiki/display/ECC/GRIB+tools
"""
__author__ = "The R & D Center for Weather Forecasting Technology in NMC, CMA"
__version__ = '0.1.0'
|
METHOD = "twoSum"
TESTCASES = [
([2,7,11,15],9),
([-1,-2,-3,-4,-5],-8)
]
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
mem = {}
for i in range(len(nums)):
x = nums[i]
... |
pkgname = "duktape"
pkgver = "2.7.0"
pkgrel = 0
build_style = "makefile"
make_cmd = "gmake"
make_build_args = ["-f", "Makefile.sharedlibrary"]
make_install_args = ["-f", "Makefile.sharedlibrary", "INSTALL_PREFIX=/usr"]
hostmakedepends = ["gmake", "pkgconf"]
pkgdesc = "Embeddeable JavaScript engine"
maintainer = "q66 <q... |
class Solution:
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
power = n-1
result = 0
for i in range(n):
value = ord(s[i])-64
result = result + (value * pow(26, power))
power = power - 1
... |
config = {
'row_data_path': './data/rel_data.txt',
'triplet_data_path': './data/triplet_data.txt',
'kg_data_path': './output/kg_data.json',
'template_path': './output/template.xlsx',
'url': "http://localhost:7474",
'user': "neo4j",
'password': "123456"
}
|
class Villager:
def __init__(self, number, books):
self.number = number
self.books = books
self.goodTrades = []
def getNumber(self):
return self.number
def getBooks(self):
return self.books
def addGoodTrade(self, book):
self.goodTrades.append(bo... |
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
result = []
self.backtrack(result, '', digits)
return result
def backtrack(self, result, combination, d... |
#!/usr/bin/env python3
def lookandsay(n):
acc = [(1,n[0])]
for c in n[1:]:
count, num = acc[-1]
if num == c:
acc[-1] = (count+1, num)
else:
acc += [(1, c)]
return "".join(["".join((str(x),y)) for (x,y) in acc])
seed = "3113322113"
for i in range(50):
see... |
class ControllerToWorkerMessage(object):
"""
Class defines the message sent from the controller to the workers. It takes
a task as defined by the user and then sends it. This class assumes that the
generated tasks are PICKLEABLE although it does not explicitly check.
"""
TASK_KEY = "task"
... |
# encoding: utf-8
"""
Package with various simple non-GUI utilities.
The modules and objects defined in this package have no dependencies on
other parts of madgui and are neither subscribers nor submitters of any
events. They should also have little to no dependencies on non-standard
3rd party modules.
"""
|
class RBI:
def __init__(self, fmeca):
self.fmeca = fmeca
self._generate_rbi()
def _generate_rbi(self):
# TODO: Add rbi logic (from risk_calculator but modified to take a
# fmeca argument and loop through each inspection type)
if self._total_risk is None:
... |
def parse(it):
result = []
while True:
try:
tk = next(it)
except StopIteration:
break
if tk == '}':
break
val = next(it)
if val == '{':
result.append((tk,parse(it)))
else:
result.append((tk, val))
r... |
kminicial = float(input('Insira a km inicial: '))
kmatual = float(input('insira a km atual: '))
dias = int(input('Quantos dias ficou alugado? '))
kmpercorrido = kmatual - kminicial
rkm = kmpercorrido * 0.15
rdias = dias * 60
total = rkm+rdias
print ('O total de km percorrido foi: {}. A quantidade de dias utilizado foi... |
attribute_filter_parameter_schema = [
{
'name': 'search',
'in': 'query',
'required': False,
'description': 'Lucene query syntax string for use with Elasticsearch. '
'See <a href=https://www.elastic.co/guide/en/elasticsearch/'
'reference/7... |
def get_max_profit(prices, fee, reserve=0, buyable=True):
if not prices:
return reserve
price_offset = -prices[0] - fee if buyable else prices[0]
return max(
get_max_profit(prices[1:], fee, reserve, buyable),
get_max_profit(prices[1:], fee, reserve + price_offset, not buyable)
)... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 11056.py
# Description: UVa Online Judge - 11056
# =============================================================================
while True:
... |
"""
Ex 48 - Create a multiplication table
"""
# Enter the number
t = int(input('Enter the number to be calculated on the multiplication table: '))
print('-=' * 8)
# Loop and Calculation
for c in range(1, 11):
print(f'||{c} x {t:2} =\t{t * c}||')
print('-=' * 8)
input('Enter to exit')
|
class ModbusException(Exception):
@staticmethod
def fromExceptionCode(exception_code: int):
if exception_code == 1:
return IllegalFunctionError
elif exception_code == 2:
return IllegalDataAddressError
elif exception_code == 3:
return IllegalDataValueError
elif exception_code == 4:
... |
"""Contants for Hitachi Smart App integration"""
DOMAIN = "Hitachi_smart_app"
#PLATFORMS = ["humidifier", "sensor", "number", "climate","fan"]
PLATFORMS = ["humidifier","sensor","number","fan","climate","switch"]
MANUFACTURER = "Hitachi"
DEFAULT_NAME = "Hitachi Smart Application"
DEVICE_TYPE_AC = 0x01
DEVICE_TYPE_DEH... |
# aoc 2020 day 9
def two_sum(val, lst):
for x in lst:
for y in lst:
if x + y == val:
return True
return False
prelude_len = 25
with open("aoc_2020_9.in") as f:
data = f.readlines()
data = list(map(int, data))
part_one_answer = 0
for idx in range(prelude_len, len(dat... |
#
# PySNMP MIB module A3COM-SWITCHING-SYSTEMS-FDDI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-SWITCHING-SYSTEMS-FDDI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:08:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
# 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 __init__(self):
self.result = []
def rightSideView(self, root):
"""
:type root: TreeNode... |
N = int(input())
with open('applicant_list.txt', 'r') as f:
data = f.readlines()
data = [d.split() for d in data]
for d in data:
for i in range(2, 7):
d[i] = float(d[i])
def sorting(data, count_b, count_c, count_e, count_m, count_p, pref, exam):
"""
exam = 2 --> phy --> phy + math
exam = ... |
# Huu Hung Nguyen
# 12/07/2021
# Nguyen_HuuHung_freq_distribution.py
# The program takes a numbers list and creates a frequency distribution table.
# It then display the frequency distribution table.
def get_max(data_list):
''' Take a data list and return its maximum data. '''
# Determine the num... |
n = int(input())
data = list(map(int,input().split()))
one , two , three = [] , [] , []
for i in range(len(data)):
if data[i] == 1:
one.append(i+1)
elif data[i] == 2:
two.append(i+1)
else:
three.append(i+1)
teams = min(len(one),len(two),len(three))
print(teams)
for i in range(teams):... |
one_char = ["!", "#", "%", "&", "\\", "'", "(", ")", "*", "+", "-", ".", "/",
":", ";", "<", "=", ">", "?", "[", "]", "^", "{", "|", "}", "~", ","]
# they must be ordered by length decreasing
multi_char = ["...", "::", ">>=", "<<=", ">>>", "<<<", "===", "!=", "==", "===", "<=", ">=", "*=", "&&", "-=", "+=",... |
class MachopCommand(object):
def shutdown(self):
pass
def cleanup(self):
pass
|
INPUT_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Deriva Demo Input",
"description": ("Input schema for the demo DERIVA ingest Action Provider. This Action "
"Provider can restore a DERIVA backup to a new or existing catalog, "
"or creat... |
#Ler duas notas e calcular a média
nota1 = float(input("Digite a primeira nota: "));
nota2 = float(input("Digite a segunda nota: "));
#Importante usar float aqui, em notas é comum haver, por exemplo "0.5";
media = (nota1+nota2) / 2;
print(f"A média entre as notas \033[0:33m{nota1:.2f}\033[m e \033[35m{nota2:.2... |
class TestClassConverter:
@classmethod
def setup_class(cls):
print("\nsetup_class: setup any state specific to the execution of the given class\n")
@classmethod
def teardown_class(cls):
print("\nteardown_class: teardown any state that was previously setup with a call to setup_class.... |
# model settings
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
model = dict(
type='TDN',
pretrained='modelzoo://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
style='pytorch'),
ne... |
# convert a decimal number to bukiyip.
def decimal_to_bukiyip(a):
bukiyip = ''
quotient = 2000000
while quotient > 0:
quotient = a // 3
remainder = a % 3
bukiyip += str(remainder)
a = quotient
return bukiyip[::-1]
# convert a bukiyip number to decimal
def bukiyip_to_d... |
msg1 = 'Digite seu nome: '
nome = input(msg1)
msg2 = 'É um prazer te conhecer, ' + '\033[1:30m' + nome + '\033[m' + '!'
print(msg2)
|
# -*- coding: utf-8 -*-
# Authors: Y. Jia <ytjia.zju@gmail.com>
"""
Sort a linked list in O(n log n) time using constant space complexity.
https://leetcode.com/problems/sort-list/description/
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
s... |
expected_output = {
'type': {
'IP route': {
'address': '10.21.12.0',
'mask': '255.255.255.0',
'state': 'Down',
'state_description': 'no ip route',
'delayed': {
'delayed_state': 'Up',
'secs_remaining': 1.0,
... |
# Open terminal > python3 condition.py
# Start typing below commands and see the output
x = int(input('Please enter an integer: '))
if x < 0:
print(str(x) + ' is a negative number')
elif x == 0:
print(str(x) + ' is zero')
else:
print(str(x) + ' is a positive number') |
"""
Calculator library containing basic math operations.
"""
class Calculator:
def add(self, first_term, second_term):
return first_term + second_term
def subtract(self, first_term, second_term):
return first_term - second_term
def divide(self, first_term, second_term):
return fi... |
class Stopwatch(object):
"""
Provides a set of methods and properties that you can use to accurately measure elapsed time.
Stopwatch()
"""
@staticmethod
def GetTimestamp():
"""
GetTimestamp() -> Int64
Gets the current number of ticks in the timer mechanism.
Re... |
name0_0_1_1_0_0_0 = None
name0_0_1_1_0_0_1 = None
name0_0_1_1_0_0_2 = None
name0_0_1_1_0_0_3 = None
name0_0_1_1_0_0_4 = None |
"""
<<>> __enter__() <<>>
-> Called on a context manager just before entering the with-block
-> The return value is bound the as-variable.
-> May return any value it wants, including None.
-> Commonly returns the context manager itself.
<<>> __exit__() <<>>
-> Executed after the with-block terminates
-> Handles except... |
# Zaimplementować funkcję power(number: int, n: int) -> int, której zadaniem jest zwrócenie wyniku działania
# n
# u
# m
# b
# e
# r
# n
# NIE UŻYWAĆ OPERATORA **
def power(number: int, n: int):
if n==0:
return 1
else:
return power(number,n-1)*number
print(power(2,3)) |
if float(input()) < 16 :
print('Master' if input() == 'm' else 'Miss')
else:
print('Mr.' if input() == 'm' else 'Ms.')
|
class IllegalKeyException(Exception):
pass
class Vigenere:
""" Implementation of the Vigenère cipher.
The Vigenère cipherbelongs to the polyalphabetic ciphers. It uses not
only one cipher alphabet, but multiple to encode a message making
the cipher much harder to break. On the other hand the effo... |
"""
Module to demonstrate how to modify a list in a for-loop.
This function does not use the accumulator pattern, because we are
not trying to make a new list. Instead, we wish to modify the
original list. Note that you should never modify the list you are
looping over (this is bad practice). So we loop over the ran... |
fruit = {"orange":"a sweet, orange, citrus fruit",
"apple": " good for making cider",
"lemon":"a sour, yellow citrus fruit",
"grape":"a small, sweet fruit growing in bunches",
"lime": "a sour, green citrus fruit",
"lime":"its yellow"}
print(fruit)
# .items will pr... |
def isPalindrome(s):
s = s.lower()
holdit = ""
for charac in s:
if charac.isalpha():
holdit+=charac
i=0
j=len(holdit)-1
while i<=j:
if holdit[i]!=holdit[j]:
return False
i+=1
j-=1
return True
s = "0P"
print(isPalindrome(s)) |
##############################################################################
#
# Copyright (c) 2003-2020 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development unt... |
def trace_get_attributes(cls: type):
class Wrapper:
def __init__(self, *args, **kwargs):
self.wrapped = cls(*args, **kwargs)
def __getattr__(self, item):
result = getattr(self.wrapped, item)
print(f"-- getting attribute '{item}' = {result}")
return res... |
class Controller:
def __init__(self, cfg):
self.internal = 0
# self.update_period = cfg.policy.params.period
self.last_action = None
def reset(self):
raise NotImplementedError("Subclass must implement this function")
def get_action(self, state):
raise NotImplement... |
"""
Exception classes for subway.
"""
# TODO: more organized and hierachical exceptions.
class SubwayException(Exception):
def __init__(self, message, code=10):
"""
:param message: str.
:param code: int. 10 general, 11 jobid unmatch, 12 only valid for general without id
13 no ... |
#!usr/bin/python
# -*- coding:utf8 -*-
class Cat(object):
def say(self):
print("I am a cat")
class Dog(object):
def say(self):
print("I am a dog")
def __getitem__(self, item):
return "bobby"
class Duck(object):
def say(self):
print("I am a duck")
# animal = Cat
# ani... |
# coding=utf-8
# /usr/bin/env python
'''
Author: wenqiangw
Email: wenqiangw@opera.com
Date: 2020-07-30 11:05
Desc:
''' |
name = 'tinymce4'
authors = 'Joost Cassee, Aljosa Mohorovic'
version = '3.0.2'
release = version
|
#!/usr/bin/python3
def solution(A):
if not A:
return 0
max_profit = 0
min_value = A[0]
for a in A:
max_profit = max(max_profit, a - min_value)
min_value = min(min_value, a)
return max_profit |
#-*- coding : utf-8 -*-
class Distribute(object):
def __init__(self):
self.__layout = 0
self.__funcs = {list:self._list, dict:self._dict}
@property
def funcs(self):
return self.__funcs
def _drowTab( self, tab, add=' |' ):
add = add * tab
return " {add}".format(**locals())
def _dict( self, data, tab ):... |
"""TensorFlow project."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def deps(prefix = ""):
http_archive(
name = "com_google_farmhash",
build_file = prefix + "//third_party/farmhash:farmhash.BUILD",
strip_prefix = "farmhash-master",
# Does not have any rel... |
s = input().lower()
search = input().lower().strip()
str_list = []
# Tokenize
token = ""
for c in s:
if c not in [' ','\'','"','.',',']:
token += c
else:
if len(token) > 0:
str_list.append(token)
token = ""
if len(token) > 0:
str_list.append(token)
# Search
print('Fou... |
def multiply(a, b):
return a * b
result = multiply(2,3)
print(result)
|
'''https://leetcode.com/problems/decode-string/'''
class Solution:
def decodeString(self, s: str) -> str:
stack = []
curNum = 0
curStr = ''
for i in s:
if i=='[':
stack.append(curStr)
stack.append(curNum)
curNum = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.