content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 12 17:16:30 2021
@author: Marchiano
Sudoku solver using backtraking algorithm
Steps followed:
1) Find empty position on grid
2) Check if value on specified grid position is admissible
3) If valid, solve recursively the puzzle by repeating steps 1 and 2 for th... |
# game model
# - holds global game properties
class Game():
def __init__(self, config):
self.config = config
self.pygame = config.pygame
self.screen = self.pygame.display.set_mode(
(
self.config.SCREEN_PX_WIDTH,
self.config.SCREEN_PX_HEIGHT
)
)
self.clock = self.pygame.time.Clock()
self.... |
lexicon_dataset = {
'direction': 'north south east west down up left right back',
'verb': 'go stop kill eat',
'stop': 'the in of from at it',
'noun': 'door bear princess cabinet'
}
def scan(sentence):
result = []
words = sentence.split(' ')
for word in words:
if word.isnumeric():
... |
EN_US_CHARSET = (
"`1234567890-=\\"
"qwertyuiop[]"
"asdfghjkl;'"
"zxcvbnm,./"
"~!@#$%^&*()_+|"
"QWERTYUIOP{}"
"ASDFGHJKL:\""
"ZXCVBNM<>?"
" \n"
)
UK_UA_CHARSET = (
"'1234567890-=ґ"
"йцукенгшщзхї"
"фівапролджє"
"ячсмитьбю."
"ʼ!\"№;%:?*()_+Ґ"
"ЙЦУКЕНГШЩЗХЇ"
... |
#
# PHASE: unused deps checker
#
# DOCUMENT THIS
#
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
"get_unused_dependency_checker_mode",
)
def phase_unused_deps_checker(ctx, p):
return get_unused_dependency_checker_mode(ctx)
|
# MÉDIA ESCOLAR
n1 = float(input('Primeira nota: _ '))
n2 = float(input('Segunda nota: _ '))
m = (n1 + n2) / 2
if m < 5:
print('Infelizmente você foi REPROVADO, pois sua média é {:.1f}' .format(m))
elif m >= 5 and m < 7: #elif 5 <= m < 7: _também funcionaria!! mlk
print('Sua média é {} e você está de RECUPERA... |
def merge_sorted_arr(left, right):
i = 0
j = 0
new_arr = []
while j < len(right) and i < len(left):
if left[i] < right[j]:
new_arr.append(left[i])
i += 1
elif right[j] <= left[i]:
new_arr.append(right[j])
j += 1
while i < len(left):
... |
"""
Security = chave
5ecur1ty = senha
"""
"""hexadecimal:
1= 1
2=2
3=3
até 9=9
10 = A
11 = B
12 = C
13 = D
14 = E
15 = F
"""
chave = input("Digite a base da sua senha: ")
senha = ""
for letra in chave:
if letra in "Aa": senha = senha + "1"
elif letra in "Bb": senha = senha + "@"
elif letra in "Cc": senha =... |
{
"targets": [
{
"target_name" : "libtracer",
"type" : "static_library",
"sources" : [
"./libtracer/basic.observer.cpp",
"./libtracer/simple.tracer/simple.tracer.cpp",
"./libtracer/annotated.tracer/TrackingExecutor.cpp",
"./libtracer/annotated.tracer/BitMap.cpp",
"./libtracer... |
pet1 = {'name': 'mr.bubbles', "type":'dog', "owner" : 'joe'}
pet2 = {'name': 'spot', "type":'cat', "owner" : 'bob'}
pet3 = {'name': 'chester', "type":'horse', "owner" : 'chloe'}
pets = [pet1, pet2, pet3]
for pet in pets:
print(pet['name'], pet['type'], pet['owner'])
|
'''
Author: ZHAO Zinan
Created: 10. March 2019
1005. Maximize Sum Of Array After K Negations
'''
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A.sort()
for index, a in enumerate(A):
if a <= 0:
if K > 0:
... |
def main():
N, M = map(int, input().split())
a = list(map(int, input().split()))
A = a[-1]
def is_ok(mid):
last = a[0]
count = 1
for i in range(1,N):
if a[i] - last >= mid:
count += 1
last = a[i]
if count >= M... |
class AddOperation:
def soma(self, number1, number2):
return number1 + number2
|
GOOGLE_SHEET_URL = (
"https://sheets.googleapis.com/v4/spreadsheets/{sheet_id}/values/{table_name}"
)
LOGGING_DICT = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {"standard": {"format": "%(message)s"}},
"handlers": {
"file": {
"level": "INFO",
"cl... |
N = int(input())
A = [int(x) for x in input().split()]
for i in range(N):
for j in range(i, N):
A[i], A[j] = A[j], A[i]
if sorted(A) == A:
print("YES")
quit()
A[i], A[j] = A[j], A[i]
print("NO")
|
"""Top-level package for pycorrel."""
__author__ = """Maxime Godin"""
__email__ = 'maxime.godin@polytechnique.org'
__version__ = '0.1.1'
|
def add_time(start, duration, start_day = ""):
new_time = ""
#24h_hours = 0
# If a user added a starting day, correct the input to be lower
if start_day:
start_day = start_day.lower()
if start_day == 'monday':
start_day_num = 0
elif start_day == 'tuesday':
start_day_num = 1
elif start_day... |
n1 = 36
n2 = 14
m = max(n1, n2)
lcm = n1 * n2
rng = range(m, n1*n2+1)
for i in rng:
if i % n1 == 0 and i % n2 == 0:
print("The lcm is " + str(i))
break
|
test_text="Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz Zhzh Chch Shsh Yoyo Yaya "
replace_table=[
["by","бай"],
["By","Бай"],
["The","Дзе"],
["the","дзе"],
["t'h","дз"],
["T'h","Дз"],
["too","ту"],
["Too","Ту"],
["to","ту"],
["To","Ту"],
["ss... |
def add_bias(v):
"""
Inclui bias no vetor de entrada
:param v: vetor de entrada
:return: matriz do vetor de entrada com bias
"""
v_bias = []
if dataset == "Books_attend_grade":
v_bias = [[1] + x for x in v]
else:
for i in v:
v_bias.append([1, i])
... |
# take linear julia list of lists and convert to julia array format
execfile('../pyprgs/in_out_line.py')
execfile('../pyprgs/in_out_csv.py')
dat1 = lin.reader("../poets/results_poets/cross_validation/EC1.dat")
dat2 = lin.reader("../poets/results_poets/cross_validation/EC2.dat")
dat3 = lin.reader("../poets/results_poe... |
#!/usr/bin/env python3
#coding: utf-8
### 1st line allows to execute this script by typing only its name in terminal, with no need to precede it with the python command
### 2nd line declaring source code charset should be not necessary but for exemple pydoc request it
__doc__ = "3D obj file loader"#information descr... |
# Quick Sort
# Randomize Pivot to avoid worst case, currently pivot is last element
def quickSort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quickSort(A, si, pi-1)
quickSort(A, pi+1, ei)
# Partition
# Utility function for partitioning the array(used in quick sort)
def partition(A, s... |
# -*- coding:utf-8 -*-
"""
@file name: __init__.py.py
Created on 2019/5/14
@author: kyy_b
@desc:
"""
if __name__ == "__main__":
pass |
class Proxy():
proxies = [] # Will contain proxies [ip, port]
#### adding proxy information so as not to get blocked so fast
def getProxyList(self):
# Retrieve latest proxies
url = 'https://www.sslproxies.org/'
header = {'User-Agent': str(ua.random)}
response = requests.get(ur... |
input = """
mysum(X) :- #sum{P: c(P)} = X, dom(X).
mycount(X) :- #count{P: c(P)} = X, dom(X).
dom(0). dom(1).
c(X) | d(X) :- dom(X).
:- not c(0).
:- not c(1).
"""
output = """
mysum(X) :- #sum{P: c(P)} = X, dom(X).
mycount(X) :- #count{P: c(P)} = X, dom(X).
dom(0). dom(1).
c(X) | d(X) :- dom(X).
:- not c(0).
:- not... |
file = open("nomes.txt", "r")
lines = file.readlines()
title = lines[0]
names = title.strip().split(",")
print(names)
for i in lines[1:]:
aux = i.strip().split(",")
print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2])) |
x = 50
def funk():
global x
print("x je ", x)
x = 2
print("Promjena globalne vrijednost promjeljive x na ", x)
funk()
print("Vrijednost promjeljive x sada je ", x)
|
# https://leetcode.com/contest/weekly-contest-132/problems/maximum-difference-between-node-and-ancestor/
# 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... |
def main():
lista = []
while True:
a = int(input(f'Digite o primeiro número: '))
if a == 0:
break
lista.append(a)
print(lista)
lista_a = comprimento(lista)
print(lista_a)
lista_b = inverter(lista)
print(lista_b)
lista_c = minimo(lista)
print(l... |
"""
project_month01/game_2048_core.py
2048 游戏核心算法
"""
# 1. 定义零元素后移函数
# [2,0,0,2] --> [2,2,0,0]
# [2,0,4,2] --> [2,4,2,0]
# 14:10
list_merge =[2,16,0,4]
def zero_to_end():
# 思想:从后向前,如果是零元素,删除后末尾追加零.
for i in range(len(list_merge) - 1, -1, -1):
if list_merge[i] == 0:
del list_merge[... |
# 列表 list
L1 = []
L2 = [1, 2, 3, 4]
L3 = ['1', 2, '3', 'hello']
L4 = [L1, L2, L3]
L4[2][3] = 'world'
# 通过迭代创建list
L5 = list(range(1, 11))
print(L4)
print(L5)
# 可加
print(L2 + L3)
# 可乘
print(L2 * 2)
|
# Each new term in the Fibonacci sequence is generated by adding
# the previous two terms. By starting with 1 and 2, the first 10
# terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values
# do not exceed four million, find the sum of the even-valu... |
def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'},
{'abbr': 1, 'code': 1, 'title': '360-day'},
{'abbr': 2, 'code': 2, 'title': '365-day'},
{'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
|
#
# PySNMP MIB module ZXR10-VSWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXR10-VSWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:42:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
del_items(0x80122A40)
SetType(0x80122A40, "struct Creds CreditsTitle[6]")
del_items(0x80122BE8)
SetType(0x80122BE8, "struct Creds CreditsSubTitle[28]")
del_items(0x80123084)
SetType(0x80123084, "struct Creds CreditsText[35]")
del_items(0x8012319C)
SetType(0x8012319C, "int CreditsTable[224]")
del_items(0x801243BC)
SetTy... |
# -*- coding: utf-8 -*-
class RegisterException(Exception):
"""Exception raised on a registration error."""
|
has_high_income = True
has_good_credit = True
has_criminal_record = False
if has_high_income and has_good_credit:
print("Eligible for loan")
if has_high_income or has_good_credit:
print("Eligible for consultation")
if has_good_credit and not has_criminal_record:
print("Eligible for credit card") |
#1
def print_factors(n):
#2
for i in range(1, n+1):
#3
if n % i == 0:
print(i)
#4
number = int(input("Enter a number : "))
#5
print("The factors for {} are : ".format(number))
print_factors(number)
|
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# Viikkotehtävä 6, videovuokraamon käyttöliittymän kontrolleri
# date: 9.11.2016
# authot: Toni Pikkarainen
# -------------------------------------------------------------------------
@auth.requires_login()
def index(... |
print('\033[34m-='*20)
print(' DETECTOR DE PALÍDROMO')
print('-='*20, '\033[m')
fr = str(input('Qual frase deseja verificar: ')).strip().upper()
palavra = fr.split()
junto = ''.join(palavra)
inverso = ''
for letra in range(len(junto) -1, -1, -1):
inverso += junto[letra]
print('O inverso de {} é {}'.format(ju... |
# Min Heap implementation
def swap(h, i, j):
h[i], h[j] = h[j], h[i]
def _min_heap_sift_up(h, k):
while k//2 >= 0:
if h[k] < h[k//2]:
swap(h, k, k//2)
k = k//2
else:
break
def _min_heap_sift_down(h, k):
last = len(h)-1
while (2*k+1) < last:
... |
{
"targets": [
{
"target_name": "node-cursor",
"sources": [ "node-cursor.cc" ]
}
]
} |
"""
A stub module to house pyrolite extensions,
where they are installed.
"""
|
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = []
common = [res.append(list(set(a))[0]) for a in itertools.takewhile(lambda x: len(set(x)) == 1, [x for x in zip(*strs)])]
return "".join(res)
# Enumeration soln
# def longestCommonPrefix(s... |
def solution(coins, amount):
coins = sorted(coins)
minCoins = [0] * (amount + 1)
for k in range(1, amount+1):
minCoins[k] = amount + 1
i = 0
while i < len(coins) and coins[i] <= k:
minCoins[k] = min(minCoins[k], minCoins[k - coins[i]] + 1)
i += 1
... |
amount = int(input('''Copyright © 2021 Ashfaaq Rifath
CURRENCY CONVERTER.lk
---------------------
Please enter amount(LKR): '''))
con_currency = input("Please enter convert currency: ")
if con_currency.upper() == "USD":
converted = amount * 200
print(f"🛑🛑🛑 {amount} LKR is {converted} 💲")
if con_curr... |
class Node:
def __init__(self, value, _next=None):
self._value = value
self._next = _next
def __str__(self):
return f'{self._value}'
def __repr__(self):
return f'<Node | Val: {self._value} | Next: {self._next}>'
|
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
# click to show follow up.
# Follow up:
# Did you use extra space?
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best solution.
# Coul... |
x=input('enter str1')
y=input('enter str2')
a=[]
b=[];c=[];max=-1
for i in range(len(x)+1):
for j in range(i+1,len(x)+1):
a.append(x[i:j])
for i in range(len(y)+1):
for j in range(i+1,len(y)+1):
b.append(y[i:j])
for i in range(len(a)):
for j in range(len(b)):
if a[i]==b[j... |
altitude = int(input("CURRENT ALTITUDE:"))
if altitude <=1000:
print("You can land the plan")
elif altitude > 1000 and altitude < 5000:
print("Come down to 1000")
else:
print("Turn around")
|
class Solution:
def myPow(self, x: float, n: int) -> float:
'''
x^n = x^2 ^ (n//2) if n is even
x^n = x * x^2 ^ (n//2) is n is odd
'''
if n == 0: return 1
result = self.myPow(x*x, abs(n) //2)
if n % 2:
result *= x
... |
# Python snippets
#################################
class MetaClass(type):
"""Return a class object with the __class__ attribute equal to the class object.
This allows interesting things within the class, such as __class__.__name__,
which are otherwise not available.
This class is used as a metaclass... |
# -*- coding: utf-8 -*-
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:]
if __name__ == '__main__':
solution = Solution()
assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd')
assert 'zxyxxe... |
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
start, end = 0, len(nums)- 1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] < target:
start =... |
class GameRules:
"""
A list of gamerules used by the world.
Contains all gamerules for Java edition as of 1.16.5.
"""
def __init__(self):
"""
Creates the rules of the class.
"""
self.rules = []
self.create_game_rules()
def create_game_rules(self):
"""
Saves every gamerule to the self.rules arra... |
#!/usr/bin/env python3
def mysteryAlgorithm(lst):
for i in range(1,len(lst)):
while i > 0 and lst[i-1] > lst[i]:
lst[i], lst[i-1] = lst[i-1], lst[i]
i -= 1
return lst
print(mysteryAlgorithm([6, 4, 3, 8, 5])) |
'''
practice qusestion from chapter 1 Module 5 of IBM Digital Nation Courses
by Aashik J Krishnan/Aash Gates
'''
x = 10
y ="ten"
#step 1
temp = x
#temp variable now holds the value of x
#step 2
x = y
#the variable x now holds the value of y
#step 3
y = temp
# y now holds the value of temp which is the orginal value... |
#
# @lc app=leetcode id=541 lang=python3
#
# [541] Reverse String II
#
# https://leetcode.com/problems/reverse-string-ii/description/
#
# algorithms
# Easy (49.66%)
# Total Accepted: 117.1K
# Total Submissions: 235.8K
# Testcase Example: '"abcdefg"\n2'
#
# Given a string s and an integer k, reverse the first k char... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
'''
Url: https://www.hackerrank.com/challenges/write-a-function/problem
Name: Write a function
'''
def is_leap(year):
'''
For this reason, not every four years is a leap year. The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for ex... |
class Solution(object):
# O(Nlog(N))
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
for i in range(len(citations)):
if citations[i] < i + 1:
return i
return len(citation... |
class Solution:
def findJudge(self, N: int, trust: List[List[int]]) -> int:
E = len(trust)
if E < N - 1:
return -1
trustScore = [0] * N
for a, b in trust:
trustScore[a - 1] -= 1
trustScore[b - 1] += 1
for index, t in enumerate(trustScore, 1... |
line = '-'*39
bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|'
blankNum1 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*4 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
blankNum2 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}... |
"""
A feature-based chart parser.
"""
|
def dfs(u, graph, visited):
visited.add(u)
for v in graph[u]:
if v not in visited:
dfs(v, graph, visited)
def count_dfs(u, graph, visited=None, depth=0):
if visited is None:
visited = set()
visited.add(u)
res = 1
for v, count in graph[u]:
if v not in visite... |
# -*- coding: utf-8 -*-
def seconds_to_human(seconds):
"""Convert seconds to a human readable format.
Args:
seconds (int): Seconds.
Returns:
str: Return seconds into human readable format.
"""
units = (
('week', 60 * 60 * 24 * 7),
('day', 60 * 60 * 24),
('h... |
def selection_sort(arr):
for num in range(0, len(arr)):
min_position = num
for i in range(num, len(arr)):
if arr[i] < arr[min_position]:
min_position = i
temp = arr[num]
arr[num] = arr[min_position]
arr[min_position] = temp
arr = [6, 3, 8, 5, 2, 7, 4, 1]
print(f'Unordered: {arr}')
selection_sort(a... |
def queens(board):
"""
Doesn't work because the solution is not recursive. It constraints to only
checking the possible solutions of plaicng the queen in a given spot.
Another thing, no need to store the whole board, it's just enough to have a
one dimensional array of the columns.
One more thing, the diago... |
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO NO URI>')
print('<AMO FAZER EXERCICIO NO URI >')
print('<AMO FAZER EXERCICIO NO URI>')
print('< AMO FAZER EXERCICIO >')
print('<AMO FAZER EXERCICIO >')
|
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for idx in range(len(image)):
image[idx] = list(reversed(image[idx]))
image[idx] = [1 if b == 0 else 0 for b in image[idx]]
return image
|
# Leia nome e peso de várias pessoas, em uma lista composta só
# Diga:
# 1) quantas pessoas foram cadastradas
# 2) a lista das pessoas que têm o maior peso
# 3) a lista das pessoas que têm o menor peso
pessoas = []
maiorPeso = 0
menorPeso = 0
print("PARA PARAR, DEIXE EM BRANCO!\n-------")
while True:
try:
pes... |
WINSTRIDE = (8, 8)
PADDING = (8, 8)
SCALE = 1.15
MIN_NEIGHBORS = 5
OVERLAP_NMS = 0.9
|
index_definition = {
"name": "id",
"field_type": "int",
"index_type": "hash",
"is_pk": True,
"is_array": False,
"is_dense": False,
"is_sparse": False,
"collate_mode": "none",
"sort_order_letters": "",
"expire_after": 0,
"config": {
},
"json_paths": [
"id"
]
}
updated_in... |
def fac(n):
if n==1 or n==0:
return 1
else:
return n*fac(n-1)
print(fac(10))
|
#-------------------------------------------------------------------#
# Returns the value of the given card
#-------------------------------------------------------------------#
def get_value(card):
value = card[0:len(card)-1]
return int(value)
#-----------------------------------------------------------------... |
# we prompt the user for the code.
# enters beginning meter reading
# Enters ending meter reading.
# we compute the gallons of water as a 10th of the gotten gallons.
# we print out the bill meant to be paid the user
def bill_calculator(code, gallons):
if code == "r":
bill = 5.00 + (gallons * 0.0005)
... |
class VoetbalClub:
"""
VoetbalClub is een simpele class.
Gemaakt om het aantal punten van de clubs bij te kunnen houden.
"""
def __init__(self, naam):
self.naam = naam
self.punten = 0
|
'''
exceptions.py: exceptions defined by textform
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2020 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more ... |
"""
画出下列代码内存图,说出终端显示结果
"""
# insert 键:切换插入或者改写模式
name_of_beijing, region = "北京", "市"
name_of_beijing_region = name_of_beijing + region
region = "省"
print(name_of_beijing_region) # 北京市
del name_of_beijing
print(name_of_beijing_region) # 北京市
|
def default_pipe(data, config):
subjects = config.get("subjects")
mutated_data = []
for row in data:
# Nest the subjects defined in config into a single dict
# and add it to mutated_row with the key "Subjects".
row_subjects = {k: int(v) for k, v in row.items() if k in subjects and bo... |
expected_normal_output = """Title Release Year Estimated Budget
Shawshank Redemption 1994 $25 000 000
The Godfather 1972 $6 000 000
The Godfather: Part II 1974 $13 000 000
The Dark Knight 2008 $185 000 000
12 Angry Men 1957 ... |
#Written for Python 3.4.2
data = [line.rstrip('\n') for line in open("input.txt")]
blacklist = ["ab", "cd", "pq", "xy"]
vowels = ['a', 'e', 'i', 'o', 'u']
def contains(string, samples):
for sample in samples:
if string.find(sample) > -1:
return True
return False
def isNicePart1(string):
... |
class MyStr(str):
def __format__(self, *args, **kwargs):
print("my format")
return str.__format__(self, *args, **kwargs)
def __mod__(self, *args, **kwargs):
print("mod")
return str.__mod__(self, *args, **kwargs)
if __name__ == "__main__":
ms = MyStr("- %s - {} -")
prin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
树:是由结点与节点之间的链接关系组成
树的特征:
1、存在唯一的起始点,树根
2、树根外的其他结点都有且只有一个前驱结点;但每个结点可以有0-n个后继
树可以有多个尾结点
3、树根可以到达任意结点(有限跳)
4、任意两个不同结点向下出发,无交叉
二叉树:
树中每个结点最多关联到两个后继结点
后继结点明确分左右
左右子树必须明确说明
几个基本概念:(都是对于二叉树而言)
空树:不包含任何结点
单点树:只包含一个结点
父结点和子节点是相... |
#
# AGENT
# Sanjin
#
# STRATEGY
# This agent always defects, if the opponent defected too often. Otherwise it cooperates.
#
def getGameLength(history):
return history.shape[1]
def getChoice(snitch):
return "tell truth" if snitch else "stay silent"
def strategy(history, memory):
if getGameLength(history... |
#! /usr/bin/env python
#-----------------------------------------------------------------------
# COPYRIGHT_BEGIN
# Copyright (C) 2017, FixFlyer, LLC.
# All rights reserved.
# COPYRIGHT_END
#-----------------------------------------------------------------------
class Event(object):
"""Base class for API events.""... |
VERSION = (0, 1)
YFANTASY_MAIN = 'yfantasy'
def get_package_version():
return '%s.%s' % (VERSION[0], VERSION[1])
|
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
class Solution:
def maxProfit_as_many_transactions(self, prices):
if not prices:
return 0
profit, prev = 0, prices[0]
for i in range(1, len(prices)):
if prices[i]... |
# -*- coding: utf-8 -*-
"""Dashboard routes that lead to JSONs without providing parameters."""
routes = {
'netwide': {
'client_list': '/usage/client_list_json',
'topology': '/l3_topology/show',
'event_types': '/dashboard/event_autocomplete_types',
'alerts': '/alerts/show',
'... |
nums = []
with open("day1_input", "r") as f:
for line in f:
nums.append(int(line))
# part 1
# for numA in nums:
# for numB in nums:
# # find two entries that sum to 2020:
# if (numA + numB == 2020):
# print(numA, numB)
# # their product is:
# print(... |
text = input("Enter A sentence: ")
bad_words = [BADWORDSHERE]
for words in bad_words:
if words in text:
text_length = len(words)
hide_word = "*" * text_length
text = text.replace(words, hide_word)
print(text)
|
Clock.clear()
# controll #######################################################
Clock.bpm = 120
Scale.default = Scale.chromatic
Root.default = 0
p1 >> keys(
[4,6,11,13,16,18,23,25]
,dur=[0.25]
,oct=4
,vibdepth=0.3 ,vib=0.01
)
p2 >> blip(
[4,6,11,13,15,16,18,23,25]
,dur=[0.25]
,oct=... |
"""
Faça um programa que peça para o usuário que digite 10 valores e some-os.
qtd = int(input('Quantas vezes esse loop deve rodar? ')) # montando a estrutura do loop
soma = 0
for n in range(1, qtd+1): # loop vai rodar quantas vezes informar acima
num=int(input(f'Informe o {n}/{qtd} valor: '))
soma=soma+num
p... |
"""
funcs
Descript:
File name: funcs.py
Maintainer: Kyle Gortych
created: 03-22-2022
"""
def skip(s,n):
"""
Returns a copy of s, only including positions that are multiples of n
A position is a multiple of n if pos % n == 0.
Examples:
skip('hello world',1) returns 'hello world'
s... |
numero1 = int(input('Digite um numero: '))
numero2 = int(input('Digite um numero: '))
numero3 = int(input('Digite um numero: '))
if numero1 <= numero2 and numero1 < numero3 and numero2 <= numero3:
print('crescente')
else:
print('não está em ordem crescente')
|
# How to merge two dicts
x = {'a': 1, 'b': 2}
y = {'c': 3, 'd': 4}
z = {**x, **y}
print(z) |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include".split(';') if "/xavier_ssd/TrekBot/TrekBot2_WS/src/navigation/nav_core/include" != "" else []
PROJECT_CATKIN_DEPENDS = "std_msgs;geometr... |
# Copyright (c) 2008, Michael Lunnay <mlunnay@gmail.com.au>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND T... |
#!/usr/bin/env python
# coding: utf-8
# In[9]:
for i in range(int(input())) :
print('Distances: ', end='')
X,Y = input().split()
Z = zip(X, Y)
for S in Z :
x = ord(S[0]) - ord('A') + 1
y = ord(S[1]) - ord('A') + 1
if x <= y :
print(y-x, end= ' ')
else :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.