content stringlengths 7 1.05M |
|---|
"""
Strings & Frets
Write a function that gets a string number and a fret of a 6-string guitar in 'standard tuning' and return the corresponding note. For this challenge we use a 24 fret model.
The notes are:
C, C#/Db, D, D#/Eb, E, F, F#/Gb, G, G#/Ab, A, A#/Bb, B
Try not to use a 2 dimensional list. Look at the image... |
'''
Класс нужен для избежания опечаток при написании названий команд.
Добавлять все новые команды сюда.
'''
class bot_command:
add = 'add'
all = 'all'
chatid = 'chatid'
delete = 'delete'
get = 'get'
help = 'help'
linal = 'linal'
mark_formulas = 'mark_formulas'
marks = 'marks'
oak... |
# Solution to Project Euler Problem 2
def sol():
ans = 0
x = 1
y = 2
while x <= 4000000:
if x % 2 == 0:
ans += x
x, y = y, x + y
return str(ans)
if __name__ == "__main__":
print(sol())
|
class GameState(object):
def __init__(self, player, action, card_name):
self.action = action
self.player = player
self.card_name = card_name
|
#!flask/bin/python
# Copyright 2020 Luis Blazquez Miñambres (@luisblazquezm), Miguel Cabezas Puerto (@MiguelCabezasPuerto), Óscar Sánchez Juanes (@oscarsanchezj) and Francisco Pinto-Santos (@gandalfran)
# See LICENSE for details.
def handle400error(ns, message):
"""
Function to handle a 400 (bad arguments co... |
"""
面试题37:两个链表的第一个公共结点
题目:输入两个链表,找出它们的第一个公共结点。链表结点定义如下:
https://leetcode.com/problems/intersection-of-two-linked-lists/
思路:
两个链表连接以后,之后的节点都是一样的了。
1. 使用两个栈push 所有节点,然后比较栈顶元素,如果一样就 都 pop继续比较。如果栈顶不一样,结果就是上一次 pop 的值。
2. 先分别遍历两个链表,找到各自长度,然后让一个链表先走 diff(len1-len2)步骤,之后一起往前走,找到的第一个就是。
"""
# Definition for singly-linked... |
try:
trigger_ver += 1
except:
trigger_ver = 1
print(f"dep file version {trigger_ver}: Even if you save this file, this script won't re-execute. Instead, create the trigger file.") |
#2개 이하로 다른 비트
def solution(numbers):
answer = []
for number in numbers:
if number%2 == 0:
answer.append(number+1)
else:
bin_num = '0'+bin(number)[2:]
for i in range(len(bin_num)-1,-1,-1):
if bin_num[i] == '0':
answer.append(... |
class Solution:
# @param A a list of integers
# @param elem an integer, value need to be removed
# @return an integer
def removeElement(self, A, elem):
if not A:
return 0
lens = 0
for i in xrange(0, len(A)):
p = A.pop(0)
... |
# Pay calculator from exercise 02.03 rewritten to give the employee 1.5 times
# the hourly rate for hours worked above 40 hours.
# Define constants
MAX_NORMAL_HOURS = 40
OVERTIME_RATE_MULTIPLIER = 1.5
# Prompt user for hours worked and hourly rate of pay.
hours = input('Enter Hours: ')
rate = input('Enter rate: ')
#... |
def chunker(iterable, size):
"""Return a piece of the specified size of the iterable at a time."""
for i in range(0, len(iterable), size):
yield iterable[i:i+size]
for chunk in chunker(range(25), 4):
print(list(chunk))
|
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... |
for i in range(2):
for j in range(4):
if i == 0 and j == 1: break;
print(i, j)
|
class FinalValue(Exception):
"Force a value and break the handler chain"
def __init__(self, value):
self.value = value
|
# ann, rets = self.anns[0], []
# for entID, ent, stim in ents:
# annID = hash(entID) % self.nANN
# unpacked = unpackStim(ent, stim)
# self.anns[annID].recv(unpacked, ent, stim, entID)
#
# #Ret order matters
# for logits, val, ent, stim, atn, entID in ann.... |
nome = input('Nome: ')
print('Nome digitado: ', nome)
print('Primeiro caractere: ', nome[0])
print('Ultimo caractere: ', nome[-1])
print('Tres primeiros caracteres: ', nome[0:3])
print('Quarto caractere: ', nome[3])
print('Todos menos o primeiro: ', nome[1:])
print('Os dois ultimos: ', nome[-2:]) |
a = [[3,5]]
a[0] = [7]
a[1] = [0]
a[2] = null
|
"""Module containing exceptions raised by ."""
# Copyleft 2021 Sidon Duarte
class GetRmqApiException(Exception):
"""Base class for all exceptions raised by twine."""
pass
|
# Copyright (c) 2018-2022 curoky(cccuroky@gmail.com).
#
# This file is part of my-own-x.
# See https://github.com/curoky/my-own-x for further info.
#
# 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 Licens... |
# Leo colorizer control file for pseudoplain mode.
# This file is in the public domain.
# import leo.core.leoGlobals as g
# Properties for plain mode.
properties = {}
# Attributes dict for pseudoplain_main ruleset.
pseudoplain_main_attributes_dict = {
"default": "null",
"digit_re": "",
"escap... |
"""
some specific bubble sort
"""
def bubble_sort(arr):
times = 0
for i_index in range(len(arr)-1):
j = 0
changed = False
while j < len(arr)-1:
if arr[j] > arr[j + 1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
changed, times = True, times+1
... |
champName = ["Aatrox","Ahri","Akali","Alistar","Amumu","Anivia",
"Annie","Ashe","AurelionSol","Azir","Bard","Blitzcrank",
"Brand","Braum","Caitlyn","Camille","Cassiopeia","ChoGath",
"Corki","Darius","Diana","DrMundo","Draven","Ekko",
"Elise","Evelynn","Ezreal","Fiddle... |
def xml_body_p_parse(soup, abstract, keep_abstract):
# we'll save each paragraph to a holding list then join at the end
p_text = []
# keeping the abstract at the begining depending on the input
if keep_abstract == True:
if abstract != '' and abstract != None and abstract == abstract:
... |
num_pl = int(input())
pl_list = input()
gift_list = []
mius_list = []
i = 0
times = 0
while True:
if(not(pl_list[i]==' ')):
times += 1
if (times > num_pl):
pl_list += pl_list[times-num_pl-1]
if (i == 0 and times <= num_pl):
gift_list.append(1)
... |
# Create variable a
_____
# Create variable b
_____
# Print out the sum of a and b
_____________ |
class Thumbnails():
"""This is the Factory Client Object that will call an instance of a text reader"""
def __init__(self, imgSourcePath, thumbnailList, saveDir, resize_height=None, resize_width=None, tf_model_path=None, ocr_confidence=None, padding=None):
'''The last 5 parameters resize_height, resize... |
# coding=utf-8
"""
Filename: whetting_your_appetite
Author: Tanyee
Date: 2020/3/26
Original: https://docs.python.org/3.7/tutorial/index.html
Description: Whet your appetite is a phrase meaning to "sharpen one's desire for food" whereas
the food here means Python.
"""
"""
If you do much w... |
coreimage = ximport("coreimage")
canvas = coreimage.canvas(150, 150)
def fractal(x, y, depth=64):
z = complex(x, y)
o = complex(0, 0)
for i in range(depth):
if abs(o) <= 2: o = o*o + z
else:
return i
return 0 #default, black
pixels = []
w = h = 150
for i in range(w):
... |
# Heaviside step function
x = 3
theta = None
if x < 0:
theta = 0.
elif x == 0:
theta = 0.5
else:
theta = 1.
print("Theta(" + str(x) + ") = " + str(theta))
|
#
# PySNMP MIB module COLUBRIS-DEVICE-WDS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/COLUBRIS-DEVICE-WDS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
age = int(input())
def drinks(drink):
print(f"drink {drink}")
if age <= 14:
drinks("toddy")
elif age <= 18:
drinks("coke")
elif age <= 21:
drinks("beer")
else:
drinks("whisky")
|
# from https://stackoverflow.com/questions/1151658/python-hashable-dicts
class HashableDict(dict):
""" A hashable version of a dictionary, useful for when a function needs to be cached but uses a dict as an
argument """
def __key(self):
return tuple((k, self[k]) for k in sorted(self))
def __ha... |
SECTION_SEPARATOR = "%" * 30
def get_required_node_edges(qualified_node_id, required_node_ids):
node_requires = [
f"{required_node_id}-->{qualified_node_id}"
for required_node_id in required_node_ids
]
return "\n".join(node_requires)
def get_icon(dict_value):
icon = ""
if "icon" i... |
total_food = int(input())
total_food_grams = total_food * 1000
is_food_over = False
command = input()
while command != 'Adopted':
eaten_food = int(command)
total_food_grams -= eaten_food
if total_food_grams < 0:
is_food_over = True
command = input()
if is_food_over:
print(f'Food is not ... |
class Solution:
def isInterleave(self, s1, s2, s3):
"""
:type s1: str
:type s2: str
:type s3: str
:rtype: bool
"""
if len(s3) != len(s1) + len(s2):
return False
if len(s3) == 0 and len(s1) == 0 and len(s2) == 0:
return True
... |
# to get a string like this run:
# openssl rand -hex 32
SECRET_KEY = "de45991397da83e674149beb168b17fde74ebd4a8d6ca65310aedc7a082d5309"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
# @Title: 矩阵置零 (Set Matrix Zeroes)
# @Author: 18015528893
# @Date: 2021-02-24 14:33:15
# @Runtime: 52 ms
# @Memory: 15.1 MB
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
... |
#!/usr/bin/env python3
#ccpc20qhda
gcd = lambda a,b: b if a==0 else gcd(b%a,a)
t = int(input())
for i in range(t):
m,n = list(map(int,input().split()))
aa = m*(m-1)
bb = (m+n)*(m+n-1)
c = gcd(aa,bb)
print('Case #%d: %d/%d'%(i+1,aa//c,bb//c))
|
class Room:
def __init__(self, lw, rw, name=""):
self.id = id(self)
self.name = name
self.leftWall = lw
self.rightWall = rw
self.P = 0
self.S = 0
self.W = 0
self.C = 0
self.parseFinish = False
def getId(self):
return self.id
d... |
"""Docstring for the card.py module
This module contains the Card class which can be used for creating
multiple cards in a deck.
"""
class Card:
"""
A class to represent cards.
Parameters
----------
suit : str
The suit of the card
rank : str
The rank of the card
Attribu... |
"""
Erros mais comuns em Pyhton
# ATENÇÃO
É importante estar atento e apreender a ler as síadas de erros geradas pela execução do
nosso código.
Os erros mais comuns:
1 - SyntaxError -> Ocorre quando o Puthon encontra um erro de sintaxe. Ou seja, foi escrito algo
que o Python reconhece como parte da l... |
"""
找一个临界点
分成2个部分 一部分大于临界点 一部分小于临界点
递归
"""
def quickSort(arr):
quickSort1(arr, 0, len(arr) - 1)
return arr
def quickSort1(arr, left, right):
if left < right:
pivot = partition(arr, left, right)
quickSort1(arr, left, pivot - 1)
quickSort1(arr, pivot + 1, right)
def partition(arr,... |
#!/usr/bin/python3
""" Reference: https://edabit.com/challenge/HTaZiWnsCGgehpgdr
This challenge is as follows:
Travelling through Europe one needs to pay
attention to how the license plate in the
given country is displayed. When crossing the
border you need to park on the shoulder,
unscrew the p... |
'''
@description: Some training parameters
@author: liutaiting
@lastEditors: liutaiting
@Date: 2020-04-01 23:49:35
@LastEditTime: 2020-04-04 23:41:21
'''
EPOCHS = 5
BATCH_SIZE = 32
NUM_CLASSES = 7
image_width = 48
image_height = 48
channels = 1
model_dir = "image_classification_model.h5"
train_dir = "dataset/train"
va... |
nome = str(input('Digite seu nome:')).strip()
serardor = nome.split()
print('Analisando seu nome...')
print('Seu nome em maiusculas é', nome.upper())
print('Seu nome em minusculas é', nome.lower())
print('seu nome tem ao todo', len(nome),'lertras')
print('Seu primeiro nome é', )
print('seu nome primeiro é {} e t... |
class Generator():
"""Virtual class for Generators."""
def generate_char(self, char):
self.generate_basic_info(char)
self.generate_characteristics(char)
self.generate_status(char)
self.generate_combact_stat(char)
self.generate_skills(char)
self.generate_weapons(ch... |
# Node 'Class'
#
# written by John C. Lusth, copyright 2012
#
# not really an object, a node is an abstraction of
# a two-element array the first slot holds the value
# the second slot holds the next pointer
#
# VERSION 1.0
def NodeCreate(value,next): return [value,next]
def NodeValue(n): return n[0]
def NodeNext(n): ... |
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[31mERRO: por favor, digite um número inteiro válido.\033[m')
continue
except (KeyboardInterrupt):
print('\033[31m de dados interrompida pelo usuá... |
# 01234567890123456789012345
letters = "abcdefghijklmnopqrstuvwxyz"
backwards = letters[25:0:-1]
# if I want to print z...a then in line 4 I should write : backwards = letters[25::-1], so the slicing starts printing from 25 backwards to the start INCLUDING the start
# create a slice that produces the charact... |
"""
This file is a part of My-PyChess application.
In this file, we define heuristic constants required for the python chess
engine.
"""
pawnEvalWhite = (
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0),
(2.0, 2.0, 3.0, 5.0, 5.0, 3.0, 2.0, 2.0),
(0.5, 0.5, 1... |
# order is important
SPECIAL_BUTTONS = {
'CONTROL_RIGHT': 'MOD_CONTROL_RIGHT',
'CONTROL_LEFT': 'MOD_CONTROL_LEFT',
'CONTROL': 'MOD_CONTROL_LEFT',
'CTRL_RIGHT': 'MOD_CONTROL_RIGHT',
'CTRL_LEFT': 'MOD_CONTROL_LEFT',
'CTRL': 'MOD_CONTROL_LEFT',
'SHIFT_RIGHT': 'MOD_SHIFT_RIGHT',
'SHIFT_LEFT'... |
# There are two sorted arrays nums1 and nums2 of size m and n respectively.
# Find the median of the two sorted arrays.
# The overall run time complexity should be O(log (m+n)).
# You may assume nums1 and nums2 cannot be both empty.
# Example 1:
# nums1 = [1, 3]
# nums2 = [2]
# The median is 2.0
# Example 2:
# nums1... |
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
def dfs(course,prerequisite,used):
used.add(course)
if prerequisites[1] not in used:
dfs(prerequisites,prerequisites[1],used)
used = set()
used_1 = s... |
class Plugin(object):
name = "base"
description = "base plugin"
def add_arguments(self, parser):
pass
|
v, n = [int(x) for x in input().split()]
total = v*n
for i in range(1, 10):
if i>=2:
print(" ", end="")
print((total*i+9)// 10, end="")
print()
|
numero = int(input('Insira um número para ver a tabuada: '))
for i in range(1,11):
print('{} x {} = {}'.format(numero, i, numero*i))
|
'''write a simple function to add two integers,
demonstrate how to call the function with various
inputs'''
# call the function add, 2 and 3, print the result to the terminal
# call the function add, 2 and 3, save the result as a variable |
# -*- coding: utf-8 -*-
"""
1431. Kids With the Greatest Number of Candies
Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that
the ith kid has.
For each kid check if there is a way to distribute extraCandies among the kids such that
he or she can have the great... |
l1= []
l2 = []
i = int(input())
for a in range (0,i):
a = input()
if (a[0]=='1'):
l1.append(a[-1])
elif (a[0]=='2'):
l2.append(a[-1])
elif (a[0] == '5'):
for b in range (0,len(l1)):
print (l1[b], end = " ")
print()
elif (a[0] == '6'):
for b in rang... |
# Write a function to rotate an array. You are given the array arr,
# n, the size of an array, and d, the number of elements to pivot on
# [1,2,3,4,5,6,7], n = 7, d = 2
# [3,4,5,6,7,1,2]
def rotate_array(arr, n, d):
if n == 0:
return None
elif n == 1:
return arr
return arr[d:] + arr[:d... |
class Solution:
def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
graph = collections.defaultdict(list)
innodes = collections.defaultdict(list)
indegrees = [0] * n
for u, v in prerequisites:
indegrees[v] += 1
... |
# author: delta1037
# Date: 2022/01/08
# mail:geniusrabbit@qq.com
# 将数据库表转换成md和CSV文件
class SQL2Notion:
def __init__(self, db_connect):
self.db_connect = db_connect
|
class APIError(Exception):
"""Represents an error returned in a response to a fleet API call
This exception will be raised any time a response code >= 400 is returned
Attributes:
code (int): The response code
message(str): The message included with the error response
http_error(goo... |
"""Base vocabulary map & EOS & UNK (PAD) token"""
# Author: Ziqi Yuan <1564123490@qq.com>
class Vocab:
def __init__(self, pretrain_embedding_path):
self.vocab = []
self.dict = []
with open(pretrain_embedding_path) as file:
for index, line in enumerate(file):
wo... |
# Rotting Oranges
# https://leetcode.com/problems/rotting-oranges/
# In a given grid, each cell can have one of three values:
# the value 0 representing an empty cell;
# the value 1 representing a fresh orange;
# the value 2 representing a rotten orange.
# Every minute, any fresh orange that is adjacent (4-direction... |
def travel(n,I,O):
l1=[]
#print(I,O)
for i in range(n):
l4=[]
for j in range(n):
if i==j:
l4.append(1)
else:
l4.append(0)
l1.append(l4)
#print(l1)
#print(l1[0].index(1))
for out in range(n):
incoming=out
... |
class UriTemplates:
"""Entities uri templates."""
ENTITY = '/entities/{0}'
ENTITIES = '/entities'
|
# Here 'n' is the number of rows and columns
def pattern(n):
for a in range(n):
print("* "*n,end="\n")
pattern(5)
'''
this will return
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
|
# ... client initialization left out
data_client = client.data
file_path = "characterizations/CdTe1.json"
dataset_id = 1
data_client.upload(dataset_id, file_path) |
"""
BASICS
Ensures the existance and correct location of keys
"""
# Ensures the existance of the main keys
# COMPLETE (large dict): Complete JSON directory with all tags and subtags
def ensure_main_keys(COMPLETE):
K = COMPLETE.keys()
if {"user", "password", "Solver", "Variables", "Equation", "Initial Condi... |
num = [5,9,3,4,6]
num[2] = 8
num.append(10)
num.sort(reverse=True)
num.insert(1,0)
num.pop()
num.remove(9)
if 4 in num:
num.remove(4)
else:
print('Não achei o número 4 na lista.')
print(num)
print(f'Essa lista tem {len(num)} elementos.')
|
# Python Loops
# for [iterator] in [sequence]
# [sequence] = range(start, end, step)
print ("\nLoop with range")
evenodd = lambda n : "even" if n % 2 == 0 else "odd"
for i in range(1, 11):
print (i, "is " + str(evenodd(i)))
print ("\nLoop in range with step")
for i in range(1, 11, 2):
print (i, "is " + str(ev... |
path = "input.txt"
file = open(path)
input = file.readlines()
file.close()
all_fish = [[int(x) for x in line.split(",")] for line in input][0]
for i in range(80):
new = 0
for idx in range(len(all_fish)):
if all_fish[idx] == 0:
all_fish[idx] = 6
new += 1
else:
... |
# -*- coding: utf-8 -*-
"""
Script para ejercicios con funciones en python
"""
def es_par(numero):
if numero == 0:
return True
else:
if numero % 2 == 0:
return True
else:
return False
numero = int(input("Ingresa un valor entero: "))
if es_par(numero):
... |
def test1_3():
n = 1
while True:
time1 = 100*n**2
time2 = 2**n
if time1 >= time2:
n += 1
else:
break
print(n, time1, time2)
test1_3()
|
def numDepthIncreases():
'''
Problem: https://adventofcode.com/2021/day/1/
'''
with open("data.txt") as f:
data = f.readlines()
num_depth_increases = 0
for i, line in enumerate(data):
if i > 0 and i <= len(data):
if int(line.strip('\n')) > int(data[i-1].str... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
FileName: 344. Reverse String.py
Description:
Author: Kimberly Gao
Date: 2021/07/13 11:21 AM
Version: 0.1
Runtime: 412 ms (5.16%)
Memory Usage: 18.5 MB (64.61%)
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Two pointers: he... |
"""
RENDER
"""
render_camera = 'cam1'
render_lights = 'light1'
"""
MATERIAL
"""
mat = 'phong1'
mat_color = ''
"""
INSTANCES
"""
inst_state = 1
inst_tra = 'viz6/null_tra'
inst_tx = 'r'
inst_ty = 'g'
inst_tz = 'b'
inst_rot = 'viz6/null_rot'
inst_rx = 'r'
inst_ry = 'g'
inst_rz = 'b'
inst_sca = 'viz6/null_sca'
ins... |
class ServiceReviewHistory:
def __init__(self, org_uuid, service_uuid, service_metadata, state, reviewed_by, reviewed_on, created_on,
updated_on):
self._org_uuid = org_uuid
self._service_uuid = service_uuid
self._service_metadata = service_metadata
self._state = stat... |
class Solution:
def XXX(self, n: int) -> str:
dp = '1'
for i in range(n-1):
s, cur_char, cnt, dp = dp, dp[0], 0, ''
for index in range(len(s)):
if s[index] == cur_char: cnt += 1
else:
dp += str(cnt) + cur_char
... |
def starts_with_vowel(word: str) -> bool:
return word[0].lower() in "aeiou"
def translate_word(word: str) -> str:
if starts_with_vowel(word):
return word + "yay"
vowel_index = 0
for index, letter in enumerate(word):
if starts_with_vowel(letter):
vowel_index = index
... |
BuildSettingInfo = provider()
def _string_imp(ctx):
value = ctx.build_setting_value
label = ctx.label.name
print("evaluated value for " + label + ": " + value)
return BuildSettingInfo(value = value)
string_flag = rule(
implementation = _string_imp,
# https://docs.bazel.build/versions/main/skyl... |
for _ in range(int(input())):
tot = 0
lst = list(map(int, input().split()))
for i in range(1, len(lst)):
if lst[i] > lst[i - 1] * 2:
tot += (lst[i] - 2 * lst[i - 1])
print(tot)
|
BASE_URL = 'http://www.travelpayouts.com'
API_DATA_URL = 'http://api.travelpayouts.com/data'
def whereami(client, ip, locale='en', callback=None):
locale = locale if locale in ['en', 'ru', 'de', 'fr', 'it', 'pl', 'th'] else 'en'
params = {
'ip': ip,
'locale': locale
}
if callback:
... |
class ModuleAggregator:
def __init__(self, registry_name) -> None:
self.registry_name = registry_name
self._registry = {}
def __getitem__(self, key):
if isinstance(key, str):
return self._registry[key]
return key
def register(self, name=None):
def wrappe... |
parrot = 'NORWEGIAN BLUE'
print(parrot)
print(parrot[3])
print(parrot[4])
print()
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-4:])
print()
number = '9,243;365:248 978;269'
separators = number[1::4]
print(separators) |
class User:
'''
class that generates new instances of users
'''
user_list = [] #empty user list
def __init__(self,username,password):
self.username = username
self.password = password
def registration(self):
'''
registration method adds users to the system
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# class Solution(object):
# def swapPairs(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
class Solution(object):
# de... |
app_name = 'price_analysis'
urlpatterns = []
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/3/7 12:04 上午
# @Author : xinming
# @File : 28_strstr.py
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = len(haystack)
n = len(needle)
if n==0:
return 0
if m<n:
return... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : yException.py
# Author : yang <mightyang@hotmail.com>
# Date : 02.11.2019
# Last Modified Date: 03.11.2019
# Last Modified By : yang <mightyang@hotmail.com>
class yException(Exception):
'''
基本异常
'''
def __ini... |
# -*- coding: utf-8 -*-
class Model(object):
pass
class NullModel(Model):
def __init__(self):
pass
@property
def name(self):
return ''
|
#
# PySNMP MIB module HUAWEI-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-PWE3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:45:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
""" Copyright 2017 Akamai Technologies, Inc. All Rights Reserved.
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 ... |
#**kwagrs use for complex agrument like dictionary store string values
def func(**kwargs):
for key, value in kwargs.items():
print("{} : {} ".format(key,value))
dict = {"Manish":"Male","Rashmi":"Female"}
func(**dict)
|
nome1 = 'Felipe'
nome2 = 'Schmaedecke'
for n in nome1:
if n not in nome2:
print(n, end=' ')
for n in nome2:
if n not in nome1:
print(n, end=' ')
|
#The code is to take in numbers which are even and odd in the provided set
even_numbers = []
odd_numbers = []
for number in range(0,1001):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)
print(even_numbers)
print("\n")
print("\n")
print(odd_numbers) |
#
# PySNMP MIB module AC-ANALOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AC-ANALOG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:54:29 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... |
#!/usr/bin/env python
def get_help_data_12575():
"""
Sensor Inventory help.
Data store of information to be presented when a help request is made for port 12576.
Returns a list of dictionaries associated with various requests supported on that port.
"""
help_data = [
{
... |
# -*- coding: utf-8 -*-
"""
File processing
@author: Dazhuang
"""
def insert_line(lines):
lines.insert(0, "Blowin' in the wind\n")
lines.insert(1, "Bob Dylan\n\n")
lines.append("\n\n1962 by Warner Bros. Inc.")
return ''.join(lines)
with open('Blowing in the wind.txt', 'r+') as f:
lines = f.readlin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.