content stringlengths 7 1.05M |
|---|
print('hello, world !')
print('---------------')
for v in range(0, 5+1):
if v % 2 == 0:
print('hello, world !')
else:
print(v, " is odd") |
def barplot(x_data, y_data, error_data, x_label="", y_label="", title=""):
_, ax = plt.subplots()
# Draw bars, position them in the center of the tick mark on the x-axis
ax.bar(x_data, y_data, color = '#539caf', align = 'center')
# Draw error bars to show standard deviation, set ls to 'none'
# to re... |
nom = input("Bonjour ! Quel est votre prénom \n")
if(nom == "Jonnhy" ):
print("Hello my love! ");
else:
print(" Salut " + nom + ", James, James bond" );
|
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
if not intervals:
return []
... |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __eq__(self, other):
if isinstance(other, ListNode):
m = self
n = other
while m and n:
if m.val != n.val:
return False
m = m.n... |
def func(a, word='hello', *para, **kwords):
print(type(para))
print(para)
for i in para:
print(i)
def func1(**kwords):
print(type(kwords))
print(kwords)
for k,v in kwords.items():
print(k,':', v)
# 任意函数(装饰器会用到)
def func3(*params, **kwords):
pass
|
del_items(0x80121AA0)
SetType(0x80121AA0, "struct THEME_LOC themeLoc[50]")
del_items(0x801221E8)
SetType(0x801221E8, "int OldBlock[4]")
del_items(0x801221F8)
SetType(0x801221F8, "unsigned char L5dungeon[80][80]")
del_items(0x80121E88)
SetType(0x80121E88, "struct ShadowStruct SPATS[37]")
del_items(0x80121F8C)
SetType(0x... |
# BST implementation - insertion, finding, traversals, deletion
# Author - rudrajit1729
# Utility class represents individual nodes in BST
class Node:
def __init__(self, key = 0):
self.left = None
self.right = None
self.value = key
# Utility function to insert node in BST
def i... |
### Defined thai letters and numbers
thaiAlpha = [' ', 'า', 'บ', 'ซ', 'ด', 'แ', 'ฟ', 'ก', 'ห', 'ิ', 'จ', 'ฅ', 'ล', 'ม',
'น', 'อ', 'ภ', 'ข', 'ร', 'ส', 'ต', 'ึ', 'ฟ', 'ว', 'x', 'ย', 'ฉ'] # th
thaiNumber = ['๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙', '๐'] # th
### Defined lating letters and numbers
latinAlpha = [' ', 'a... |
def lengthOfLongestSubstring(s: str) -> int:
arr = list(s)
res = len(arr)
res_l = res
if res == 0:
return res
res = 0
for i in range(res_l):
tmp = [arr[i]]
if i > (res_l/2) and i< res:
return res
for j in range(1,res_l - i):
if arr[i+j] in tmp:
if len(tmp) > res:
res = len(tmp)
break
... |
'''
This file contains exceptions that can be thrown by the model, which
will in turn be caught by the endpoint resource and converted into an
appropriate status code
'''
class ConsistencyError(Exception):
"""ConsistencyError is raised when there is disagreement
between the metadata and storage layer on th... |
annovar_to_ncbi = {}
annovar_to_ncbi['EnterAnnovarGene']='CorrectNCBIGene'
annovar_to_ncbi['KIAA1804']='MAP3K21'
annovar_to_ncbi['FLJ33360']='LINC02145'
annovar_to_ncbi['FLJ33581']='LINC01721'
annovar_to_ncbi['FLJ46066']='LINC01994'
annovar_to_ncbi['FLJ26245']='LINC02167'
annovar_to_ncbi['LINC00273']='' # Reported as ... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def get_height(self, root):
node = root
height = 0
while node is not None:
... |
# Bubble Sort
def bubbleSort(list):
endIndex = len(list) - 1
while True:
shouldContinue = False
for i in range(endIndex):
if list[i] > list[i + 1]:
temp = list[i + 1]
list[i + 1] = list[i]
list[i] = temp
shouldContinue = True
if not shouldContinue:
break
e... |
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"instance": {
"1": {
"router_id": "10.4.1.1",
"base_topology_mtid": {
"0": {... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
## What is a Decorator ?
# A decorator is the name used for a software design pattern. Decorators dynamically alter the
# functionality of a function, method, or class without having to directly use subclasses or change
# the source code of the function being decorated.
de... |
"""172. Factorial Trailing Zeroes"""
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
## all trailing 0 is from factors 5 * 2.
## But sometimes one number may have several 5 factors,
## for example, 25 have two 5 factors, ... |
URL_PATH = 'http://127.0.0.1:8000/api/v1/'
TEST_USER_1 = {
'email': 'spongebob@krusty.com',
'password': 'SquarePants',
}
TEST_USER_2 = {
'email': 'patric_star@krusty.com',
'password': 'Star22',
}
TEST_URL_1 = {
'entered_url': 'https://github.com',
'short_code': 'spongecc',
}
TEST_URL_2 = {
... |
ls = [8, 4, 12, 2, 12, 4, 9, 1, 3, 5, 13, 3]
ls1 = []
ls2 = []
ls.sort(reverse = -1)
print(ls)
total = sum(ls)
half = total/2
print("Half = ", half)
if total % 2 == 0:
for i in ls:
if sum(ls1) < sum(ls2):
ls1.append(i)
else:
ls2.append(i)
if sum(ls1) != sum(ls2):
... |
"""
Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same.
Examples:
arr[] = {1, 5, 11, 5}
Output: true
The array can be partitioned as {1, 5, 5} and {11}
"""
def partition_equal_subset_sum(arr):
target, n = sum(arr), len(a... |
def count_substring(string, sub_string):
count = 0
for i in range(len(string)):
if string[i:].startswith(sub_string):
count += 1
return count
if __name__ == '__main__':
print("Enter a string: ", end = ' ')
string = input().strip()
print("Enter substring: ", end = ' ')
... |
#! /usr/bin/env python3
def applyRule(rule, s):
a, b = rule[0], rule[1]
if a == s[0]:
return b + s[1:]
return None
def applyRules(rules, ss):
ret = [applyRule(r, s) for r in rules for s in ss]
return [i for i in ret if i is not None]
def search(rules, m):
"""
search from 'a', ext... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 21:49:37 2019
@author: jercas
"""
"""
leetcode-53: 最大子序和 EASY
'数组' '动态规划' '分治算法'
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),
返回其最大和。
"""
"""
Thinking:
1.动态规划法:定义最大子序和 与 当前累积和,遍历列表当前数为正值时累加,否则清空累积和设置为当前值,每次按是否大于最大子序和进行更新。
2.分治算法: 遍历数... |
def f():
try:
f()
finally:
g()
|
# there is no guarantee of find the secret word in 10 guesses
# for example ['aaaaaa', 'bbbbbb', ..., 'zzzzzz']
# the strategy really depends on the distribution of chars
class Solution(object):
def findSecretWord(self, wordlist, master):
"""
:type wordlist: List[Str]
:type master: Master
... |
#-*- coding: utf-8 -*-
config = {
"code": {
"exit": {
"0001": "NETWORK \ubb38\uc7ac\ub85c \uc778\ud55c \uac15\uc81c\uc885\ub8cc"
}
},
"db": {
"redis_db_bta": 1,
"redis_db_common": 0,
"redis_host": "gAAAAABYuEUdvRKvSL8P8LANdYsHkNPsN1VBL1P-jBD7XAf6Sr_Pd30pU-... |
a = 0
b = 1
while a != b:
senha = 2002
x = int(input())
if x == senha:
print("Acesso Permitido")
break
else:
print("Senha Invalida")
|
#
# PySNMP MIB module Unisphere-Data-SLEP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-SLEP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:32:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
with open("5letterscrabble.txt", 'r') as f:
allwords = f.read()
allletters = list(allwords)
print(len(allletters))
allletters.sort()
alphabet = "abcdefghijklmnopqrstuvwxyz"
counts = {}
for each in list(alphabet):
#print(allletters.count(each))
counts[each] = allletters.count(each)
counts2 = dict(sorted(co... |
def sum_n_natural_numbers(n: int) -> int:
""":returns 1 + 2 + 3 + 4 + ... + n"""
result = 0
for i in range(n + 1):
result = result + i
return result
# print(sum_n_natural_numbers(0))
# print(sum_n_natural_numbers(1))
# print(sum_n_natural_numbers(2))
# print(sum_n_natural_numbers(3))
# print(s... |
def get_server_url(http_method, server_root, username, password):
if username and password:
return '%(http_method)s://%(user)s:%(pass)s@%(server)s' % {
'http_method': http_method,
'user': username,
'pass': password,
'server': server_root,
}
else:
... |
#
# PySNMP MIB module L2L3-VPN-MCAST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/L2L3-VPN-MCAST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:04:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
#map from dna to rna
'''
Blood Group: A B AB O
DNA: A T C G combination
RNA: U,A, G, C combination respectively to DNA
input: ATTCG
output:UAAGC
'''
rna_map={'A':'U','T':'A','C':'G','G':'C'}
#dna=input('Enter DNA: ')
dna="ATTCG"
op=""
for l in dna:
op+=rna_map.get(l)
print(op) |
# Settings
# Access credentials:
CONSUMER_KEY = ''
CONSUMER_SEC = ''
ACCESS_TOK = ''
ACCESS_SEC = ''
USERLLIST = 'userlist.txt'
OUTDIR = u'Output'
OUTFILE = 'tweetdata.' # output filename prefix
|
'''
+ soma
- subtração
* multiplicação
/ divisão
// divisão inteira
** exponenciação
% resto da divisão
() parenteses - alterar a precedência nas contas
'''
print('adição', 10 + 10)
print('subtração', 10 - 10)
print('multiplicação', 10 * 10)
print('divisão', 10 / 10)
print('divisão inteira', 20.5 // 5)
print('elevação... |
"""Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S."""
class Solution(object):
def numMatchingSubseq(self, S, words):
"""
:type S: str
:type words: List[str]
:rtype: int
"""
count = 0
for word in words:
... |
bot_instance = None
global_config = None
reference_market = None
default_time_frame = None
def __init__(bot, config):
global bot_instance
bot_instance = bot
global global_config
global_config = config
def get_bot():
return bot_instance
def get_global_config():
return global_config
def s... |
class Animal (object):
pass
class Dog(Animal):
def __init__(self,name):
self.name=name
class Cat(Animal):
def __init__(self,name):
self.name=name
class Person(object):
def __init__(self,name):
self.name=name
class Employee(Person):
def __init__(self,name,salary):
supe... |
"""The experimental package provides some analysis functions for
aggregating darshan log data. The functions are not well
tested.
"""
|
def sumTo(aBound):
""" Return the sum of 1+2+3 ... n """
theSum = 0
aNumber = 1
while aNumber <= aBound:
theSum = theSum + aNumber
aNumber = aNumber + 1
return theSum
print(sumTo(4))
print(sumTo(1000))
# Ex1 : Write a while loop that is initialized at 0 and stops at 15.
# ... |
# -*- coding: utf-8 -*-
"""
Document Library
"""
module = "doc"
#==============================================================================
# Settings
resource = "setting"
tablename = "%s_%s" % (module, resource)
table = db.define_table(tablename,
Field("audit_read", "boolean"),
... |
"""
Model Config for YOLO v1
"""
class YoloConfig:
def __init__(self, in_channels=3, split_size=7, num_boxes=2, num_classes=20):
# * Define the model aechitecture.
# * Each conv layer is a tuple (kernel_size, out_ch, stride, padding.)
# * each conv block is a list [(conv1_params), ... , (co... |
available_parts = ["computer",
"monitor",
"keyboard",
"mouse",
"mouse mat",
"hdmi cable"]
current_choice = "-"
computer_parts = [] # create an empty list
while current_choice != "0":
if current_choice in "12345":
... |
class PrecisionConfig(object):
def __init__(self):
self.BASE = 10
self.PRECISION_INTEGRAL = 8
self.PRECISION_FRACTIONAL = 8
self.Q = 293973345475167247070445277780365744413
self.PRECISION = self.PRECISION_INTEGRAL + self.PRECISION_FRACTIONAL
assert(self.Q > self.... |
# -*- coding: utf-8 -*-
# @Author: chandan
# @Date: 2017-07-08 00:49:31
# @Last Modified by: chandan
# @Last Modified time: 2017-07-08 10:24:41
DATA_DIR = '/home/chandan/Documents/datasets/uah'
MODEL_DIR = '/home/chandan/Dropbox/gridlock/models'
SCORE_COLUMNS = 2, 10, 11, 12, 13
|
class Calc:
def add(self, number1, number2):
return float(number1) + float(number2)
def sub(self, number1, number2):
return float(number1) - float(number2)
def mul(self, number1, number2):
return float(number1) * float(number2)
def div(self, number1, number2):
return float(number1) / float(n... |
# Problem name: Transform the equation
# What it basically does is transform infix to postfix
# PASSED
def priority(a):
if a=='^':
return 3
elif a=='*' or a=='/':
return 2
elif a=='+' or a=='-':
return 1
else: #signifies brackets
return 0
t=int(input())
while t:
sta... |
# class used to parse card request in CSV format
# throws validation errors if fields have errors
class LineParser:
# parses a comma seperated string into each field
# expected line format is
# <merc ref>,<amount>,<card>,<expiry month>,<expiry year>,<first name>,<last name>,<email>,<postal code>
def parse( sel... |
sea=input("enter season")
if sea=='spring':
print("its time to plant")
elif sea=='summer':
print("its time to water")
elif sea=='winter':
print("its time to stay in")
else:
print("its time to harvest")
|
def is_orphan_dataset(datasets, pvc):
if not datasets:
return False
for d in datasets:
if 'dataset-' + d == pvc:
return False
return True
def is_orphan_group(groups, pvc):
if not groups:
return False
for d in groups:
if 'project-' + d.get('name') == pvc:
... |
class Solution:
def numDecodings(self, s: str) -> int:
def is_letter(idx):
c1 = s[idx - 1]
c2 = s[idx]
if c1 == "1":
return c2 >= "0" and c2 <= "9"
elif c1 == "2":
return c2 >= "0" and c2 <= "6"
return False
... |
var1 = "Hello World"
for character in var1:
if character == ' ':
print("There was a space, oh no")
break
print(character)
for character in var1:
if character == ' ':
print("There was a space, lets skip this iteration")
continue
print(character)
for charact... |
"""
Descricao rapida e simples.
asdfljkhasdflkjhsdflkjhasdfkjh, asdfasdf, asdf,,,asdfasdfasdf
qwerqwerqwerqwerqwerqwerwerwer
qwerqw
erqwer
werqwerqwerqwerdfgs
dfg
sgh
asdfasdfçlkhi,qalfglka.lfahsgiohoa asdoifgufsjh
"""""
class MinhaClasse:
"""Documentacao normal
Conforme qualquer outra documentacao que vc ... |
n = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
c = 10
s = n
p = 1
soma = 0
while p > 0:
soma += c
while c > 0:
print('{}'.format(s), end = '')
print(' >>' if c > 1 else '...', end = ' ')
c -= 1
s += r
p = c = int(input('\nDigite qua... |
#gefunden = False
anzeige1 = "Wir haben eine Haushaltsauflösung"
anzeige2 = "Wir verkaufen Staubsauger"
anzeige3 = "Kaufe Schmuck"
anzeigenliste = [anzeige1,anzeige2,anzeige3]
begriff1= "Haushaltsauflösung"
begriff2= "Staubsauger"
begriff3= "Schmuck"
begriffsliste = [begriff1,begriff2,begriff3]
#print(begriffslist... |
cuts = []
def find_max_value(rod_size, prices, total_value):
if rod_size < 0:
return 0
elif rod_size == 0:
return total_value
else:
max_val = 0
for cut, value in enumerate(prices, 1):
max_val = max(max_val, find_max_value(rod_size - cut, prices, total_value + va... |
"""
--- Day 15: Dueling Generators ---
Here, you encounter a pair of dueling generators. The generators, called generator A and generator B, are trying to
agree on a sequence of numbers. However, one of them is malfunctioning, and so the sequences don't always match.
As they do this, a judge waits for each of them to... |
class quickFind:
_id = []
_count = 0
def __init__(self, N):
self._id = list(range(0,N))
self._count = N
#Quick-find
def find(self, p):
return self._id[p]
def union(self,p, q):
self._pID = self.find(p)
self._qID = self.find(q)
if (self._pID == sel... |
def number(g):
if not g or len(g) < 4 or any(len(r) != len(g[0]) for r in g):
raise ValueError('Ill-formed grid')
if g == [" _ ", "| |", "|_|", " "]:
return '0'
elif g == [" ", " |", " |", " "]:
return '1'
else:
return '?'
def grid(n):
if n == '0':
r... |
# py-data-structures <http://github.com/gwtw/py-data-structures>
# Copyright 2016 Daniel Imms <http://www.growingwiththeweb.com>
# Released under the MIT license <http://github.com/gwtw/py-data-structures/blob/master/LICENSE>
def default_compare(a, b):
if a < b:
return -1
elif a > b:
return 1
return 0
|
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 16:56:36 2020
@author: kshit
"""
'''
Pythagorean Triplets can be generated by the formula.
Given any positive integers m and n where m > n > 0, the integers
a = m^2 - n^2
b = 2*m*n
c = m^2 + n^2
'''
def dicksinson_pythagorus():
for m in range(1,32):
... |
class AbstractExecutor(object):
def __init__(self, config, model):
raise NotImplementedError("Executor not implemented")
def train(self, train_dataloader, eval_dataloader):
"""
use data to train model with config
Args:
train_dataloader(torch.Dataloader): Dataloader... |
#DICTONARIES FOR VARIOUS POSSIBILITIES
ones = {
0 : 'zero ',
1 : 'one ',
2 : 'two ',
3 : 'three ',
4 : 'four ',
5 : 'five ',
6 : 'six ',
7 : 'seven ',
8 : 'eight ',
9 : 'nine '
}
prefix = {
2 : 'twen', # for -ty and -teen
3 : 'thir',
4 : 'four',
5 : '... |
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if not numbers or len(numbers) == 0:
return []
i, j = 0, len(numbers) - 1
while i < j:
if numbers[i] + numbers[j] ... |
m = []
with open('input', 'r') as f:
for line in f:
m.append(list(line.rstrip()))
rows = len(m)
cols = len(m[0])
def go(r, d):
num_trees = 0
i, j = 0, 0
while i < rows:
if m[i][j % cols] == '#':
num_trees += 1
i += d
j += r
return num_trees
total = 1
... |
def assert_is_in_range(x, constraint):
minimum = constraint['min']
maximum = constraint['max']
assert minimum <= x , f'min:{minimum}, got:{x}'
assert x <= maximum, f'max:{maximum}, got:{x}'
|
# -*- coding: utf-8 -*-
# noinspection PyClassHasNoInit
class PlayerStates:
AVAILABLE = 0x0
AFK = 0x1
PLAYING = 0x2
QUIT = 0xff # my own, not GGPO server's
@staticmethod
def codeToString(code):
if code == 0:
return 'AVAILABLE'
elif code == 1:
return 'A... |
"""
Mostly constants related to consensus, or p2p connection that are not suitable to be in config
"""
# blocks bearing a timestamp that is slightly larger than current epoch will be broadcasted
ALLOWED_FUTURE_BLOCKS_TIME_BROADCAST = 15
# blocks bearing a timestamp that is slightly larger than current epoch will be c... |
#!usr/bin/python
# -*- coding:utf8 -*-
'''
传统的生产者-消费者模型是一个线程写消息,一个线程取消息,通过锁
机制控制队列和等待,但一不小心就可能死锁.
如果改用协程,生产者生产消息后,直接通过yeild跳转到消费者开始执行, 待消费者执行
完毕后,切换回生产者继续生产,效率极高
'''
def consumer():
r = 'hh'
while True:
print("first start")
n = yield r
print('v',n)
if not n:
return
... |
# Created by MechAviv
# Intense Damage Skin | (2436645)
if sm.addDamageSkin(2436645):
sm.chat("'Intense Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# Ray-autopilot
def autopilot_on_ray():
"""
Speed up the dataset collection by running simulation and autopilot in Ray.
1. Port oatomobile on Carla latest (0.9.12+) version and Python 3.7.
2. Solve the problem of Ray supporting ABC.
3. Use Ray actor and task to make autopilot simulation parrallel an... |
# Asking name
name = input("What's your name? ")
# Say Hello
print(f"Hello, {name}!")
print("I'm Moqi. Nice to meet you.") |
def test_remote_channel():
pass
|
class BinaryTreeNode:
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __lt__(self, other):
if other == None:
return self
return self.value < other.value
def __str__(self):
... |
class Solution:
def compress(self, chars: List[str]) -> int:
truncate=0
p=0
q=0
count=0
while p< len(chars):
while q < len(chars):
if chars[p] == chars[q]:
count=count+1
else:
break
... |
projects = dict()
employees = dict()
tasks = dict()
|
'''
Problem Statement : Turbo Sort
Link : https://www.codechef.com/problems/TSORT
score : accepted
'''
numbers = []
for _ in range(int(input())):
numbers.append(int(input()))
numbers.sort()
print(*numbers,sep='\n') |
{
"targets": [
{
"target_name": "ogg",
"type": "static_library",
"include_dirs": [
"1.3.2/libogg-1.3.2/include"
],
"sources": [
"1.3.2/libogg-1.3.2/src/*.c"
],
"direct_dependent_settings": {
... |
def isCharValue(c: str):
return c.isalnum() or c == '_' or c == "."
def get_tokens(line):
"""
获取一行中的所有token,把一个标点符号单算一个token
"""
tokens = []
s = ''
for c in line:
if isCharValue(c):
s = s + c
else:
if len(s) > 0:
tokens.append(s)
... |
# Reference:
# https://www.tellusxdp.com/ja/api-reference/
class APIException(Exception):
"""General unexpected response."""
pass
class BadRequest(APIException):
"""Invalid request parameter, HTTP 400."""
pass
class Unauthorized(APIException):
"""Authentication failed, HTTP 401."""
pas... |
# RadixSort.py
'''
기수정렬(RadixSort)
O(n)
'''
def CountingSort(list, exp1) :
n = len(list)
output = [0] * (n)
count = [0] * (10)
for i in range(0, n) :
index = list[i] // exp1
count[index % 10] += 1
for i in range(1, 10) :
count[i] += count[i - 1]
i = n - 1
while ... |
class Settings(object):
def __init__(self):
self.show_status_messages = True
self.show_view_status = True
self.auto_show_diagnostics_panel = True
self.show_diagnostics_phantoms = False
self.show_diagnostics_count_in_view_status = False
self.show_diagnostics_in_view_s... |
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def find(self, item):
if self.head is None:
return None
return self.head.find(item)
def find_by(self, fn):
if self.head is None:
return None
... |
l = []
n = 'y'
while n == 'y':
l.append(input('Введите значение в список: '))
n = input('Для ввода еще одного элемента в список, нажмите Y: ').lower()
print(f'Введен список: {l}')
result = []
for i in range(0, len(l), 2):
tmp = l[i:i+2]
result += tmp[::-1]
print(result)
|
arr = [11, 22, 33, 44, 55]
print("Array is :",arr)
res = arr[::-1]
print("New array:",res)
arr.reverse()
print("After reversing Array using method reverse():",arr) |
CLEAN_BOARD = [
['0', '0', '0'] + ['0', '0', '0'] + ['0', '0', '0'],
['0', '0', '0'] + ['0', '0', '0'] + ['0', '0', '0'],
['0', '0', '0'] + ['0', '0', '0'] + ['0', '0', '0'],
# -------------------------------------------------
['0', '0', '0'] + ['0', '0', '0'] + ['0', '0', '0'],
['0', '0', '0'] ... |
# Functions for sorting exercise
def cmp(a, b):
return (a > b) - (a < b)
def mySort(numbers):
numbers = bubbleSort(numbers)
return numbers
def bubbleSort(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
#################################
# Selection Sort
n = len(nums)
... |
def check_all(array_all, expected):
if len(array_all) < len(expected):
print("Error: Output is too short to match expected results")
return False
item_i = 0
while item_i < len(array_all):
if check_line(array_all[item_i], expected[0]):
break
item_i += 1
print... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
def scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores):
height, width, numKeypoints = scores.shape
localMaximum = True
yStart = max(heatmapY - localMaximumRadius, 0)
yEnd = min(heatmapY + localMaximumRadius + 1, heig... |
# dataset settings
dataset_type = 'CocoDataset'
data_root = '/content/drive/MyDrive/Neu-Det_Dataset/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
classes = ('letters', 'crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches')
train_p... |
# coding=utf-8
"""Hamiltonian Cycle Backtracking finding algorithm Python implementation."""
V = 5 # vertices count
def is_safe(v, graph, path, pos):
if not graph[path[pos - 1]][v]:
return False
for i in range(pos):
if path[i] == v:
return False
return True
def hc_util(grap... |
test = {
'name': 'Lambda Trivia',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> x = 5
>>> x = lambda x: lambda x: lambda y: 3+x
>>> x(3)(5)(7)
8
>>> you = 'fly'
>>> yo, da = lambda do: you, lambda can: True
... |
class VideoStream:
def __init__(self, filename):
self.filename = filename
try:
self.file = open(filename, 'rb')
except:
raise IOError
self.frameNum = 0
def nextFrame(self):
"""Get next frame."""
data = self.file.read(5) # Get the framelength from the first 5 bits
if data:
frame... |
class Solution:
def findContentChildren(self, g, s):
g.sort(reverse = True); s.sort(reverse = True); res = 0
while s and g:
if g[-1] <= s[-1]: res += 1; g.pop(); s.pop()
else: s.pop()
return res |
class node:
def __init__(self, data = None):
self.data = data
self.next = self
self.prev = self
class Circular_linked_list:
def __init__(self):
self.head = None
def append(self, data):
new_node = node(data)
if self.head == None:
self.head = ne... |
#max rows = 45 for Bellman-Ford (very slow algorithm)
rows = 40
size = 800
button_size = (11/80) * size, (5/80) * size
spacing = size // rows
white = 255, 255, 255
black = 0, 0, 0
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
yellow = 255, 255, 0
purple = 128, 0, 128
orange = 255, 165, 0
grey = 128, 128, 128
pink ... |
n=int(input("enter factorial number"))
s=1
for i in range(n,0,-1):
s*=i
print (s)
|
animal_class = str(input())
if animal_class == "dog":
print("mammal")
elif animal_class == "crocodile" or animal_class == "tortoise" or animal_class == "snake":
print("reptile")
else:
print("unknown")
|
searched_word = input().split(", ")
txt = input().split(", ")
b = []
[b.append(i) for i in searched_word for word in txt if i in word if i not in b]
print(b)
|
# django oauth toolkit has serious issues with extending the application model.
# this is a fix for that...
migration_path = './oauth2/migrations/0001_initial.py'
s = ''
s += ' '*4 + 'run_before = [\n'
s += ' '*8 + "('oauth2_provider', '0001_initial'),\n"
s += ' '*4 + ']\n'
# after this line we want to add the above c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.