content stringlengths 7 1.05M |
|---|
#Task https://adventofcode.com/2020/day/2
inputExample = [['2-3','r','rrnr'],
['5-10','n','ltnnnknnvcnnn'],
['7-9','p','jtpptpllpj'],
['2-5','s','slssssszssssssss'],
['16-17','d','dddddddddddddddlp'],
['2-5','q','bbwqqbkmdhqmjhn'],
['7-10','m','qmpgmmsmmmmkmmkj'],
['1-3','a','abcde'],
['4-7','g','vczggdgbgxg... |
# -*- coding: utf-8 -*-
DESC = "live-2018-08-01"
INFO = {
"DropLiveStream": {
"params": [
{
"name": "StreamName",
"desc": "流名称。"
},
{
"name": "DomainName",
"desc": "您的加速域名。"
},
{
"name": "AppName",
"desc": "应用名称。"
}
],
"de... |
#!/usr/bin/env python
# coding: utf-8
class tokenargs(object):
'''Wraps builtin list with checks for illegal characters in token arguments.'''
# Disallow these characters inside token arguments
illegal = '[]:'
# Replace simple inputs with illegal characters with their legal equivalents
re... |
#
# PySNMP MIB module SAF-IPRADIO (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SAF-IPRADIO
# Produced by pysmi-0.3.4 at Wed May 1 14:59:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
This module is designed to analysis data
"""
|
gopen = open('namecheck.txt' , 'w')
for i in range(1,54):
fopen = open('%d' % i, 'r')
for z in range(100):
rline = fopen.readline()
if rline:
rlist = rline.split('$')
name = rlist[0].strip()
clg = rlist[1].strip()
nlist = name.split(' ')
if len(nlist)==1:
gopen.write('%s, %s \n' % (name,clg))
... |
class RectCoordinates:
def __init__(self, x, y, w, h):
self.startX = int(x)
self.startY = int(y)
self.w = int(w)
self.h = int(h)
self.endY = int(y + h)
self.endX = int(x + w)
def get_frame(self, frame):
return frame[self.startY:self.endY, self.startX:self... |
# Reading lines from file and putting from a list to a dict
dna = dict()
contents = []
for line in open('rosalind_gc.txt', 'r').readlines():
contents.append(line.strip('\n'))
if line[0] == '>':
header = line[1:].rstrip()
dna[header] = ''
else:
dna[header] = dna.get(header) + line.rst... |
class ExpiredInstrument(Exception):
def __init__(self, instrument):
expire_message = f"El instrumento expiró: {instrument.maturity_date}"
super().__init__(expire_message)
|
#!/usr/bin/python
# Filename: func_default.py
def say(message='3',times=1):
print (message * times)
say();
say(times=11)
say('Hello')
say('World',5)
say(2,4)
|
"""
Project Euler Problem 45
========================
Triangle, pentagonal, and hexagonal numbers are generated by the following
formulae:
Triangle T[n]=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal P[n]=n(3n-1)/2 1, 5, 12, 22, 35, ...
Hexagonal H[n]=n(2n-1) 1, 6, 15, 28, 45, ...
It can be verified that T[... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 8 12:01:02 2021
@author: Easin
"""
in1 = input()
#print(in1)
count = 0
list1 = []
list2 = []
for values in range(len(in1)):
if in1[values] >= 'a' and in1[values] <= 'z':
list1.append(in1[values])
flag = True
for elem in range(len(li... |
def negate_condition(condition: callable):
def _f(context):
return not condition(context)
return _f
def dummy(context: dict) -> dict:
return context
class Transition:
def __init__(self, next_state: object, condition: callable, callback: callable = dummy):
self.next_state = next_stat... |
# python3
def compute_min_number_of_refills(d, m, stops):
assert 1 <= d <= 10 ** 5
assert 1 <= m <= 400
assert 1 <= len(stops) <= 300
assert 0 < stops[0] and all(stops[i] < stops[i + 1] for i in range(len(stops) - 1)) and stops[-1] < d
count = 0
curr = 0
stops.insert(0, 0)
stops.appen... |
"""Decode ASCII-encoded messages"""
def decode(coded):
"""Decode a string of ASCII codes"""
return ''.join(map(chr, map(int, coded.split())))
if __name__ == '__main__':
print(decode('''
67 111 109 101 32 105
110 32 97 32 78 101
119 32 89 101 97 114
39 115 32 99 97 112
... |
def applicant_selector(gpa,ps_score,ec_count):
message = "This applicant should be rejected."
if (gpa >= 3):
if (ps_score >= 90):
if (ec_count >= 3):
message = "This applicant should be accepted."
else:
message = "This applicant should be given an in-person interview."
return messag... |
# lc551.py
# LeetCode 551. Student Attendance Record I `E`
# acc | 91% | 13'
# A~0f27
class Solution:
def checkRecord(self, s: str) -> bool:
a = 0
l = 0
for c in s:
if c == "L":
l += 1
if l > 2:
return False
else:... |
inp = input()
def palin(inp):
if len(inp)==1: return True
elif len(inp)==2: return inp[0]==inp[1]
else: return inp[0]==inp[-1] and palin(inp[1:-1])
if palin(inp): print('PALINDROME')
else: print('NOT PALINDROME') |
def bazel_toolchains_repositories():
org_chromium_clang_mac()
org_chromium_clang_linux_x64()
org_chromium_sysroot_linux_x64()
org_chromium_binutils_linux_x64()
org_chromium_libcxx()
org_chromium_libcxxabi()
def org_chromium_clang_mac():
native.new_http_archive(
name = 'org_chromium_... |
# This file contains the set of rules of basic
# defining the constants
DIGITS = '0123456789'
# defining the token types
TOKEN_INT = 'INT'
TOKEN_FLOAT = 'FLOAT'
TOKEN_PLUS = 'PLUS'
TOKEN_MULTI = 'MUL'
TOKEN_MINUS = 'MINUS'
TOKEN_DIVIDE = 'DIV'
TOKEN_LPAREN = 'LPAREN' # left parenthesis
TOKEN_RPAREN = 'RP... |
""" Constants for the Desktop Processes integration. """
NAME = "Desktop Processes"
DOMAIN = "desktop_processes"
IGNORE = "ignore"
PRIORITY = "priority"
ATTR_CONFIG = "config"
VERSION = "0.1.0"
STARTUP_MESSAGE = f"""
-------------------------------------------------------------------
{NAME}
Version: {VERSION}
This is... |
{
"targets": [{
"target_name": "ui",
"include_dirs": ["<(module_root_dir)/src/includes", "<(module_root_dir)"],
"sources": [
'<!@(node tools/list-sources.js)'
],
"conditions": [
["OS=='win'", {
"libraries": [
"<(module_root_dir)/libui.lib"
]
}],
["OS=='linux'", {
"cflags": ["-fvi... |
# programmers L4 : 도둑질
# solved by JY
# DATE : 2021.03.12
# DP 사용
# dp[i] = 집 i번 째까지 털었을 때 최대 금액
# dp[0][] = 1번 집부터 털기
# dp[1][] = 2번 집부터 털기
# dp[][i] = max(dp[][i-2] + m[i-1], dp[][i-1])
def solution(money):
dp = [[0]*(len(money) + 1) for _ in range(2)]
dp[0][0], dp[0][1], dp[0][2] = 0, money[0], money[0] ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 25 13:53:05 2017
@author: venusgrape
In this problem, you'll create a program that guesses a secret number!
The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive).
The computer makes guesse... |
"""
Code From:
https://github.com/laurentluce/python-algorithms/
The MIT License (MIT)
Copyright (c) 2015 Laurent Luce
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, includi... |
class Solution:
# Sorting key function (Accepted), O(n log n) time, O(n) space
def sortByBits(self, arr: List[int]) -> List[int]:
def tup(n):
return (bin(n).count('1'), n)
return sorted(arr, key=tup)
# One Liner (Top Voted), O(n log n) time, O(n) space
def sortByBits(self, A... |
#
# PySNMP MIB module STN-CHASSIS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STN-CHASSIS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:03:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# Python returning values
def withdraw_money(current_bal, amount):
if(current_bal >= amount):
current_bal -= amount
return current_bal
balance = withdraw_money(100, 20)
if (balance >= 50):
print(f"The balance is {balance}.")
else:
print("You need to make a deposit.")
|
class Queue:
"""An implementation of the Queue data strucutre."""
def __init__(self):
self._items = []
def __repr__(self):
return "pyDS.queue.Queue({})".format(self._items)
def __str__(self):
return str(self._items)
def __len__(self):
return len(self._items)
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 16 09:31:26 2016
@author: andre
# edX MITx 6.00.1x
# Introduction to Computer Science and Programming Using Python
# Problem Set 2, problem 3
# Use bisection search to make the program faster
# The following variables contain values as described below:
# balance - the ... |
print('=' * 12 + 'Desafio 43' + '=' * 12)
peso = float(input('Informe sua massa (em kg): '))
altura = float(input('Digite sua altura (em m): '))
imc = peso / (altura ** 2)
print(f'IMC: {imc:.1f}')
if imc < 18.5:
print('Categoria: ABAIXO DO PESO')
elif imc < 25.0:
print('Categoria: PESO IDEAL')
elif imc < 30.0:
... |
while True:
n = int(input("Height: "))
width = n
if n > 0 and n <= 8:
break
for num_of_hashes in range(1, n + 1):
num_of_spaces = n - num_of_hashes
print(" " * num_of_spaces, end="")
print("#" * num_of_hashes, end="")
print(" ", end="")
print("#" * num_of_hashes)
|
class Events:
# REPL to USER EVENTS
INP = 'inp'
OUT = 'out'
ERR = 'err'
HTML = 'html'
EXC = 'exc'
PONG = 'pong'
PATH = 'path'
DONE = 'ended'
STARTED = 'started'
FORKED = 'forked'
# REPL <-> USER EVENTS
NOINT = 'noint'
# USER to REPL EVENTS
WRT = 'wrt'
RU... |
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... |
# Runtime Average-case: Theta(n^2)
# Runtime Best-case (already sorted): O(n)
# Runtime Worst-case (reserve sorted): Theta(n^2)
# In Place: Yes
# Stable: Yes
def insertion_sort(a):
for j in range(1, len(a)):
key = a[j]
# start with element before and keep going back
i = j - 1
whil... |
nums = list()
for i in range(0, 5):
nums.append(int(input(f'Digite o valor da posição {i}: ')))
maior = max(nums)
menor = (min(nums))
print('-=-'*15)
print(f'Você digitou os valores {nums}')
print(f'O maior valor digitado foi {maior} nas posições ', end='')
for i, v in enumerate(nums):
if v == maior:
pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The module contains a collection of useful algorithms written in python."""
__author__ = 'Md. Imrul Hassan'
__email__ = 'mihassan@gmail.com'
__version__ = '0.2.1'
|
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
if not node: return None
... |
squares = [1, 4, 9, 16, 25]
print(squares)
print(squares[0]) #Get first value; remember index offset
print(squares[-1]) #Get last value in sequence
print(squares[2:4]) #Return slice of list
squares.append(54) #Add new value
print(squares)
squares[3] = 88 #Insert new value
print(squares)
|
numeros=[[], []]
valor = 0
for c in range(1,8):
valor= int(input(f' Digite o {c}º valor: '))
if valor % 2 == 0:
numeros[0].append(valor)
if valor % 2 == 1:
numeros[1].append(valor)
print(numeros)
numeros[0].sort()
numeros[1].sort()
print(f' Os valores pares digitados foram {numeros[0]}... |
# ### Problem 3
# Given 2 lists of claim numbers, write the code to merge the 2 lists provided to produce a new list by alternating values between the 2 lists. Once the merge has been completed, print the new list of claim numbers (DO NOT just print the array variable!)
# ```
# # Start with these lists
# list_of_claim_... |
class OffsetMissingInIndex(Exception):
pass
class CouldNotFindOffset(Exception):
pass
class LogSizeExceeded(Exception):
pass
|
# Copyright 2017 The Forseti Security Authors. 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 ap... |
print("Welcome to the F.A.T C.A.T program, this program encrypts messages using the reverse cipher method") #Prints whats in the parenteses
sentence = input("What do you want to encrypt? ") #Declares a varible and stores what the user inputs
final = ""
i = len(sentence) -1
while(i != -1):
final+= sentence[i];
i... |
def sum_series(generator, n):
return sum(generator(i) for i in range(n))
def series(generator, n):
return [generator(i) for i in range(n)]
def search_bordered_sum_series(generator_fabric, n, left_x, right_x, border, epsilon=0.01**5):
left_y = sum_series(generator_fabric(left_x), n)
right_y = sum_s... |
computation_config = {
'Variable': 'GV1',
'From': ['WB API'],
'files': ['GV1_WB.csv'],
'function': lambda df, var: df.groupby(['ISO']).transform(lambda x: x.rolling(5, 1).mean()),#.mean(axis=1),
'sub_variables': [
'Adjusted net savings, including particulate emission damage (% of GNI)',
... |
# DomirScire
class Animal:
def __init__(self, color, number_of_legs):
self.species = self.__class__.__name__
self.color = color
self.number_of_legs = number_of_legs
def __repr__(self):
return f'{self.color} {self.species}, {self.number_of_legs} legs'
class Wolf(Animal):
de... |
TRAIN = False
USERS = {
'yuncam':'aBc1to3'
}
|
##function 'return_list' goes here
def return_list(the_string):
new_list = []
the_string = the_string.replace(" ",",")
the_string = the_string.split(",")
if len(the_string) == 1:
return the_string[0]
else:
for x in range(len(the_string)):
new_list.append(the_string[x... |
"""
[E] Given an array, find the average of all contiguous subarrays of size 'K 'in it.
Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5
Output: [2.2, 2.8, 2.4, 3.6, 2.8]
"""
# Brute Force Approach: Time: O(n * k) space: O(1)
def find_averages_of_subarrays(K, arr):
result = []
for i in range(len(arr)-K+1):
# find ... |
# Maximum Vacation Days
# Rules:
# 1. You can only travel among N cities, represented by indexes from 0 to N-1.
# Initially, you are in the city indexed 0 on Monday.
# 2. The cities are connected by flights. The flights are represented as a N*N matrix (not necessary symmetrical),
# called flights representing the... |
class Option:
OPTION_ENABLE = 256
OPTION_TX_ABORT = 1024
OPTION_HIGH_PRIORITY = 2048
|
#BFS or Breadth First Search is a traversal algorithm for a tree or graph, where we start from the root node(for a tree)
#And visit all the nodes level by level from left to right. It requires us to keep track of the chiildren of each node we visit
#In a queue, so that after traversal through a level is complete, our a... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
curr_level = [cloned]
while... |
def add(x, y):
"""add two numbers"""
return x + y
def subtract(x, y):
"""subtrct one number from another"""
return y - x
def mult(x, y):
"""multiply two numbers"""
return x * y
|
# Demo Python Tuples
'''
Create Tuple With One Item
To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
'''
# One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(t... |
# Copyright 2017 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
DEPS = [
'properties',
'step',
'url',
]
def RunSteps(api):
api.url.validate_url(api.properties['url_to_validate'])
def GenTests(api):
... |
lista = ()
lista1 = list()
tuplas = []
tuplas1 = tuple()
dicionario = {}
dicionario1 = dict()
dados = {'nome': 'Pedro', 'idade': 25}
print(dados['nome'])
print(dados['idade'])
print(f'O {dados["nome"]} tem {dados["idade"]} anos')
dados['nome'] = 'Leandro' #altera o elemento
print(dados)
dados['sexo'] = 'M... |
'''
@Date : 2017-12-07 11:18
@Author: yangyang Deng
@Email : yangydeng@163.com
@Describe:
将使用在 align 中的参数封装到一个类里。
'''
class argvs:
# 输入图片的位置
image_path = ''
output_dir = ''
# 人名
class_name = 'dyy'
image_size = 182
margin = 44
gpu_memory_fraction = 1
detect_multiple_faces = Fa... |
class Option(object):
"""A Class implementing some sort of field interface"""
def __init__(self,
name, label, type,
description=None, category='general', required=False,
choices=None, default=None, field_options=None):
kwargs = locals()
kwargs.pop('self')
... |
#!/usr/bin/env python
def plain_merge(array_a: list, array_b: list) -> list:
pointer_a, pointer_b = 0, 0
length_a, length_b = len(array_a), len(array_b)
result = []
while pointer_a < length_a and pointer_b < length_b:
if array_a[pointer_a] <= array_b[pointer_b]:
result.append(arr... |
sexo = str(input('Digite o sexo [M/F]: ')).strip().upper()[0]
while sexo.upper() not in 'MF':
sexo = str(input('Valor inválido. Digite novamente: ')).upper()
print('sexo {} registrado com sucesso.'.format(sexo))
|
# does this even work?
class InvalidToken(Exception, object):
"""Raise an invalid token """
def __init__(self, message, payload):
super(InvalidToken, self).__init__(message, payload)
self.message = message
self.payload = payload |
""" Stat objects make life a little easier """
class CoreStat():
""" Core stats are what go up and down to modify the character """
def __init__(self, points=0):
points = int(points)
if points < 0:
points = 0
self._points = points
self._current = self.base
s... |
"""
weather.exceptions
------------------
Exceptions for weather django app
"""
class CityDoesNotExistsException(Exception):
def __init__(self, message: str = None, *args, **kwargs):
if message is None:
message = "The queried city object doesn exists"
Exception.__init__(self, message,... |
x={"a","b","c"}
y=(1,2,3)
z=[4,5,2]
print(type(x));
print(type(y));
print(type(z));
x.add("d")
print(x)
z.append(5)
print(y)
print(z)
for i in x:
print (i)
if 5 in z:
print("yes")
x.remove("b")
print(x)
z.remove(4)
print(z)
z.insert(1,7)
print(z)
z.extend(y)
print(z)
print(z.count(2))
del... |
#mostra o valor de uma compra em uma loja de acordo com a quantidade de itens
print("Lojas quase dois Tabela de preços")
for x in range(1,51):
valor=x*1.99
print(str(x)+" Itens = R$ "+str(valor)) |
'''The Caesar cipher is a type of substitution cipher in which each alphabet in the plaintext or messages is shifted by a number of places down the alphabet.
For example,with a shift of 1, P would be replaced by Q, Q would become R, and so on.
To pass an encrypted message from one person to another, it is first necess... |
first = ord('A')
last = ord('Z')
for i in range(first, last + 1):
for j in range(last, first - 1, -1):
if j <= i:
print(chr(i), end=' ')
else:
print('', end=' ')
print()
|
coordinates_01EE00 = ((123, 116),
(123, 124), (123, 127), (123, 128), (123, 136), (123, 137), (124, 115), (124, 117), (124, 119), (124, 120), (124, 121), (124, 122), (124, 130), (124, 134), (124, 135), (124, 138), (125, 114), (125, 116), (125, 124), (125, 125), (125, 126), (125, 127), (125, 128), (125, 131), (125, 13... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 19 17:46:22 2021
@author: rezanmoustafa
"""
# Endret fra 8b til 9
class Sporsmaal:
def __init__(self, sporsmaal, svar, valg=[]):
self.sporsmaal=sporsmaal
self.svar=svar
self.valg=valg
def HentSporsmaal(self):
... |
# -*- coding: utf-8 -*-
Consent_form_Out = { # From Operator_CR to UI
"source": {
"service_id": "String",
"rs_id": "String",
"dataset": [
{
"dataset_id": "String",
"title": "String",
"description": "String",
"keywor... |
class Ionic:
"""Ionic radius class. Stores: charge, spin, coordination"""
def __init__(self, charge=0, coordination="", radius=0.0):
self.charge = charge
self.coordination = coordination
self.radius = radius
def set_radius(self, value: float):
self.radius = value
cl... |
class Adapter(object):
def __init__(self):
self.interfaces = []
|
with open("10.in") as file:
lines = file.readlines()
lines = [line.rstrip() for line in lines]
# Part 1
luc = {"(": ")", ")": "(", "[": "]", "]": "[",
"{": "}", "}": "{", "<": ">", ">": "<"}
lup = {")": 3, "]": 57, "}": 1197, ">": 25137}
score = 0
for line in lines:
stack = []
for i in range(0,... |
__all__ = [
'config_enums',
'feed_enums',
'file_enums'
]
|
#Flag
#Use a flag that stores on the nodes to know if we visited or not.
#time: O(N).
#space: O(N), for each node we use O(1) and there are N nodes.
class Solution(object):
def detectCycle(self, head):
curr = head
while curr:
if hasattr(curr, 'visited') and curr.visited: return curr
... |
class Solution:
def binarySearchableNumbers(self, nums: List[int]) -> int:
maximums = [nums[0]] # from the left
minimums = [0] * len(nums) # from the right
min_n = nums[-1]
result = 0
for n in nums[1::]:
maximums.append(max(maximums[-1], n))
... |
'''
快速排序
'''
# 1、描述
'''
快速排序是由东尼·霍尔所发展的一种排序算法。
快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists),其是一种分而治之思想在排序算法上的典型应用。
通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,
然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据标出有序数列。
'''
# 2、算法步骤
'''
(1)从数列中挑出一个元素,称为 “基准”(pivot);
(2)重新排序数列,所有元素比基准值小的摆放在基准... |
# def candies(s): # worst case = three passes of 's', len, max, sum
# length = len(s)
# if length <= 1:
# return -1
# return max(s) * length - sum(s)
def candies(seq):
length = 0
maximum = 0
total = 0
for i, a in enumerate(seq):
try:
current = int(a)
ex... |
def convert2meter(s, input_unit="in"):
'''
Function to convert inches, feet and cubic feet to meters and cubic meters
'''
if input_unit == "in":
return s*0.0254
elif input_unit == "ft":
return s*0.3048
elif input_unit == "cft":
return s*0.0283168
else:
print(... |
# reference : https://wikidocs.net/16074
class Language:
default_language = "English"
def __init__(self):
self.show = '나의 언어는 ' + self.default_language
@classmethod
def class_my_language(cls):
return cls()
@staticmethod
def static_my_language():
return Language()
... |
# [Stone Colusses] It Ain't Natural
CHIEF_TATOMO = 2081000
sm.setSpeakerID(CHIEF_TATOMO)
sm.sendNext("Well, you don't look like you just spoke to an ancient nature spirit, but I suppose we'll know soon enough. "
"Are you ready for a little adventure?\r\n\r\n"
"#bYou know it! How do I get to th... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ======================================================================
#
# gensbo - a GENeral Simulation Based Optimizer
#
# 一个基于仿真的优化器
#
# ======================================================================
#
# author : Mingtao Li
# date ... |
# a = [1,2,2,3,4,5]
# # print(list(set(a)))
# def correct_list(a):
# return(list(set(a)))
# print(correct_list(a))
a = [1,2,2,3,4,5]
def correct_list(a):
s = []
for i in a:
if i not in s:
s.append(i)
return(s)
print(correct_list(a)) |
# coding: UTF-8
print(r'''
【程序19】题目:打印出如下图案(菱形)
7 * 8:
*
***
******
********
******
***
*
* 4s 1
*** 3s 3
****** 1s 5
******** 0s 8
****** 1s 5
*** 2s 3
* 3s 1
7 * 9:
*
***
*******
*********
*******
***
*
程序分析:先把图形分成两部分来看待,前四行一个规律,后三... |
'''
Title: %s
Given: %s
Return %s
Sample Dataset: %s
Sample Output: %s
'''
def compute():
pass
if __name__ == "__main__":
pass
|
def read_color(input_func):
"""
Reads input color and lower cases it
"""
user_supplied_color = input_func()
return user_supplied_color.casefold()
def is_quit(user_supplied_color):
return 'quit' == user_supplied_color
def print_colors():
"""
In the while loop ask the user to enter a c... |
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
ret = [];
wl = len(words[0])
wordsused = []
for i in range (0, len(s) - len(words) * wl + 1):
test = s[i:i+wl]
... |
# encoding: utf-8
##################################################
# This script shows an example of a header section. This sections is a group of commented lines (lines starting with
# the "#" character) that describes general features of the script such as the type of licence (defined by the
# developer), authors,... |
string = input('Digite a palavra:')
stringSemEspacos = string.replace(' ', '')
stringTodaMinuscula = stringSemEspacos.lower()
stringInvertida = stringTodaMinuscula[::-1]
if stringInvertida == stringTodaMinuscula:
print("É um palíndromo.")
else:
print("Não é um palíndromo.")
|
#经典的约瑟夫环问题,不容错过
#by leetcode.cn/u/ak-bot
#2022-5-4
def josephsring_recursive(n,k):
'''
约瑟夫环(递归解法)
时间复杂度:O(n)
n个人围成一圈,从0开始编码。
从第一个人(0号)开始计数,杀死第k个人,然后从下一个人开始计数,问谁能活到最后?
输入:
n:人数
k:杀死第k个人
返回:
ans:活到最后的那个人
'''
#分析:
#如果只有一个人,那直接返回0就可以了
#如果是两个人,如果k是奇数,那0号先挂;如果是偶数,1号先挂
... |
# función que verifica la elección del usuario con respecto
# al menú principal
def get_choice(text = None):
""" gets users choice from a numbered list """
try:
choice = int(input(text if text else "Choose something...\n"))
return choice
except Exception as error:
print("Please don'... |
#
# Note.
#
# Root directory: Visual studio code workspace root.
#
block_input_file = "./ascii-floor-map-to-csv/data/block-map.txt"
table_input_file = "./ascii-floor-map-to-csv/data/table-number-map.txt"
output_file_name = "./ascii-floor-map-to-csv/auto-generated/floor-map.csv"
try:
bl_file = open(block_input_file... |
def result(text):
count=0
for i in range(len(metin)):
if(ord(metin[i])>=65 and ord(metin[i])<=90):
count=count+1
return count
|
#Pegando o nome completo
nome = input('Digite seu nome completo: ')
#transformando
nomeUp = nome.upper()
nomeLow = nome.lower()
#Nome sem espaços
#Dividindo
divNome = nome.split()
#print(divNome)
#Pegando primeiro nome
firstNome = divNome[0]
tamFirstNome = len(firstNome)
#print(firstNome)
#Juntando
nomeJunt = ''.jo... |
def genTest():
print('Block of code before first yield statement')
yield 1
print('Block of code after first yield statement and before second yield statement')
yield 2
print('Block of code after all yield statements')
# foo = genTest returns <function gen at 0x101faf400>
foo = genTest() # retu... |
class PropertyReference:
def __init__(self, var_name, property_name):
self.var_name = var_name
self.property_name = property_name
def __str__(self):
return f'{self.var_name}.{self.property_name}'
def code_gen_string(self):
return str(self)
class FunctionCallArgument:
... |
##Retrieve region of sequences delimited by a forward and reverse pattern
#v0.0.1
f = [ [x.split('\n')[0], ''.join(x.split('\n')[1:])] for x in open('gg-13-8-99.fasta', 'r').read().rstrip('\n').split('>') ][1:]
fw = ['AGAGTTTGATCMTGGCTCAG']
rv = ['GWATTACCGCGGCKGCTG']
mtol = 1
endstr = 3
w = open('ggmb.fa', 'w')
nl = ... |
def say(message, times = 1):
print(message * times)
say('Hello', 4)
say('World', 4)
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3)
func(3, c=13)
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.