content stringlengths 7 1.05M |
|---|
class Carta():
CARTAS_VALORES = {
"3": 10,
"2": 9,
"1": 8,
"13": 7,
"12": 6,
"11": 5,
"7": 4,
"6": 3,
"5": 2,
"4": 1
}
NAIPES_VALORES = {
"Paus": 4,
"Copas": 3,
"Espadas": 2,
... |
def subUnsort(A):
n = len(A)
for i in range(0, n - 1):
if A[i] > A[i + 1]:
break
if i == n - 1:
return -1
start = i
for i in range(n - 1, start, -1):
if A[i] < A[start] or A[i] < A[i - 1]:
break
end = i
min = A[start]
max = A[start]
fo... |
#!/usr/bin/env python3
#pylint: disable=missing-docstring
class DeviceNotFoundException(Exception):
status_code = 404
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class UpstreamApiException(Except... |
#validation DS
server_fields = {
"match_keys": "['id', 'mac_address', 'cluster_id', 'ip_address', 'tag', 'where']",
"obj_name": "server",
"primary_keys": "['id', 'mac_address']",
"id": "",
"host_name": "",
"mac_address": "",
"ip_address": "",
"parameters": """{
'int... |
Node11 = {"ip":"10.1.3.11",
"user":"marian",
"password":"descartes"}
Node17 = {"ip":"10.1.3.17",
"user":"marian",
"password":"descartes"} |
user_name,age = input("Enter the name and age to watch the movie : ").split()
age = int(age)
conduction = user_name[0].lower()
if conduction == 'a' and age >= 10 :
print(f"Hello {user_name}!! \n You can watch the coco movie ")
else :
if age < 10:
print("Your age is smaller then limit to watch... |
class TimeoutError(Exception):
"""
Indicates a database operation timed out in some way.
"""
pass
|
def test_can_withdraw_as_alice(nft_funded, alice, bob, accounts, beneficiary):
nft_funded.withdraw({"from": alice})
init_balance = beneficiary.balance()
accounts[1].transfer(nft_funded, 10 ** 18)
nft_funded.mint({"from": bob})
nft_funded.withdraw({"from": alice})
final_balance = beneficiary.bala... |
# based on Rob Pike's talk “Lexical scanning in Go”
# http://youtu.be/HxaD_trXwRE
# http://golang.org/src/pkg/text/template/parse/lex.go
LEFT_DELIM = '{{'
RIGHT_DELIM = '}}'
PIPE = '|'
LEFT_LINK_DELIM = '[['
RIGHT_LINK_DELIM = ']]'
LEFT_COMMENT_DELIM = '<!--'
RIGHT_COMMENT_DELIM = '-->'
class Lexer:
def __init__(sel... |
class Solution:
def solve(self, nums):
numsDict = {}
for i in nums:
if i in numsDict:
numsDict[i] += 1
else:
numsDict[i] = 1
for num in numsDict:
if num == numsDict[num]:
return True
... |
# noinspection SqlNoDataSourceInspection,SqlDialectInspection
class Postgres:
"""
Provides functions to query PostgreSQL
:param str table: Param to select the right table
:param str column: Param to search duplicate or unique on
"""
def __init__(self, table: str, column: str) -> None:
... |
# Author: veelion
db_host = 'localhost'
db_db = 'crawler'
db_user = 'your-user'
db_password = 'your-password'
|
BCT_ADDRESS = '0x2f800db0fdb5223b3c3f354886d907a671414a7f'
NCT_ADDRESS = '0xd838290e877e0188a4a44700463419ed96c16107'
UBO_ADDRESS = '0x2b3ecb0991af0498ece9135bcd04013d7993110c'
NBO_ADDRESS = '0x6bca3b77c1909ce1a4ba1a20d1103bde8d222e48'
GRAY = '#232B2B'
DARK_GRAY = '#343a40'
FIGURE_BG_COLOR = '#202020'
MCO2_ADDRESS = '0... |
#!/usr/bin/env python
# encoding: utf-8
"""
permutation_ii.py
Created by Shengwei on 2014-07-15.
"""
# https://oj.leetcode.com/problems/permutations-ii/
# tags: medium / hard, numbers, permutation, dp, recursion
"""
Given a collection of numbers that might contain duplicates, return all possible unique permutations.... |
class BaseValidator:
"""
Base class for validator
"""
def is_applicable(self, schema):
raise NotImplementedError()
def validate_type(self, upstream, downstream):
raise NotImplementedError()
|
CrfSegMoodPath = 'E:\python_code\Djangotest2\cmdb\model\msr.crfsuite'
HmmDIC = 'E:\python_code\Djangotest2\cmdb\model\HMMDic.pkl'
HmmDISTRIBUTION = 'E:\python_code\Djangotest2\cmdb\model\HMMDistribution.pkl'
CrfNERMoodPath = 'E:\python_code\Djangotest2\cmdb\model\PKU.crfsuite'
BiLSTMCXPath = 'E:\python_code\Djangotest2... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class RoleCreateIpConfigParametersEnum(object):
"""Implementation of the 'Role_CreateIpConfigParameters' enum.
Specifies the interface role.
'kPrimary' indicates a primary role.
'kSecondary' indicates a secondary role.
Attributes:
KP... |
n1 = float(input("Digite sua primeira nota: "))
n2 = float(input("Digite sua segunda nota: "))
n3 = float(input("Digite sua terceira nota: "))
n4 = float(input("Digite sua quarta nota: "))
media = (n1 + n2 + n3 + n4) / 4
print("Sua média é de: ",media) |
#
# @lc app=leetcode.cn id=50 lang=python3
#
# [50] Pow(x, n)
#
n = 5
x = 6
x & 1
# @lc code=start
class Solution:
def myPow(self, x: float, n: int) -> float:
ans = 0
pow_n = x
if n > 0:
while x > 0:
if x & 1 == 1:
ans += pow_n
... |
class UnknownList(Exception):
pass
class InsufficientPermissions(Exception):
pass
class AlreadySubscribed(Exception):
pass
class NotSubscribed(Exception):
pass
class ClosedSubscription(Exception):
pass
class ClosedUnsubscription(Exception):
pass
class UnknownFlag(Exception):
pass
clas... |
# -*- coding: utf-8 -*-
"""Release data for the IPython project."""
#-----------------------------------------------------------------------------
# Copyright (c) 2008, IPython Development Team.
# Copyright (c) 2001, Fernando Perez <fernando.perez@colorado.edu>
# Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>... |
heroes_number = int(input())
heroes_list = dict()
for heroes in range(heroes_number):
hero = input().split(' ')
hero_name = hero[0]
hero_hit_points = int(hero[1])
hero_mana_points = int(hero[2])
heroes_list[hero_name] = {'HP': hero_hit_points, 'MP': hero_mana_points}
command = input()
while comm... |
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 1, 2015
# Question: 083-Remove-Duplicates-from-Sorted-List
# Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list/
# ==============================... |
class INPUT:
def __init__(self):
self.l=open(0).read().split()[::-1]
self.length=len(self.l)
return
def stream(self,k=1,f=int,f2=False):
assert(-1<k)
m=self.length
if m==0 or m<k:
raise Exception("There is no input!")
elif f!=str:
if k==0:
self.length=0
retur... |
"""
Exercício Python 7:
Desenvolva um programa que leia as duas
notas de um aluno, calcule e mostre a sua média.
"""
n1 = float(input('Digite nota AV: '))
n2 = float(input('Digite Nota AVS: '))
n3 = float(input('Digite nota VR: '))
#media = (n1+n2+n3)/3
print('A media do aluno é {:.1f}'.format((n1+n2+n3)/3))
|
#Check if NOT
txt = "Hello buddie unu!"
print("owo" not in txt)
txt = "The best things in life are free!"
if "expensive" not in txt:
print("Yes, 'expensive' is NOT present.")
'''
Terminal:
True
Yes, 'expensive' is NOT present.
'''
#https://www.w3schools.com/python/python_strings.asp |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
class FileTransform:
"""
FileTransform
"""
def __init__(self):
pass
def getSrc(self):
pass
def setSrc(self, src):
pass
def getCCCId(self):
pass
def setCCCId(self,... |
class InternalError(Exception):
pass
class InvalidAccessError(Exception):
pass
class InvalidStateError(Exception):
pass
|
{
'targets': [
{
'target_name': 'profiler',
'sources': [
'cpu_profiler.cc',
'graph_edge.cc',
'graph_node.cc',
'heap_profiler.cc',
'profile.cc',
'profile_node.cc',
'profiler.cc',
'snapshot.cc',
],
}
]
}
|
def Insertionsort(A):
for i in range(1, len(A)):
tmp = A[i]
k = i
while k > 0 and tmp < A[k - 1]:
A[k] = A[k - 1]
k -= 1
A[k] = tmp
A = [54, 26, 93, 17, 77, 31, 44, 55, 20]
Insertionsort(A)
print(A) |
class policy_name_protection():
def __init__(self,name_protection):
self.np=name_protection
def __call__(self,target):
try:
if target.policy.has_key('name_protection')==True:
if target.policy.get('name_protection')==False and self.np==True:
... |
'''
Leetcode problem No 300 Longest Increasing Subsequence
Solution written by Xuqiang Fang on 20 June, 2018
'''
class Solution(object):
########
'''
This is a classic problem and the following is a classic solution in O(nlogn)
tails is an array storing the smallest tail of all increasing subsequences ... |
#!/usr/bin/env python3
# Problem Set 4A
# Name: John L. Jones
# Collaborators:
# Time Spent: x:xx
def get_permutations(sequence):
'''
Enumerate all permutations of a given string
sequence (string): an arbitrary string to permute. Assume that it is a
non-empty string.
You MUST use recursion for ... |
def function(param, param1):
pass
def result():
pass
function(result<arg1>(), result())
|
'''
- Leetcode problem: 5
- Difficulty: Medium
- Brief problem description:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"... |
# Rescebe os valores de entrada.
P1 = float(input())
P2 = float(input())
Ml = float(input())
# Calculo da media parcial.
Mp = (2 * P1 + 3 * P2) / 5.0
# Regras para aprovação.
if Ml < 5.0 or Mp < 5.0:
M = min(Mp, 4.9)
else:
M = (3 * Mp + 2 * Ml) / 5.0
if 5.0 > M >= 2.5:
E = float(input())
F = (M + E) ... |
# https://open.kattis.com/problems/stockbroker
# init values
cash = 100
shares = 0
prices = []
#first input: num days (1-365)
num_days = int(input())
#next inputs: values on each day (1-500)
for _ in range(num_days):
prices.append(int(input()))
for i in range(len(prices)-1):
if prices[i] ... |
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = len(nums)
for i in xrange(len(nums)):
res ^= nums[i]
res ^= i
return res |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Les fonctions et les exceptions
Quelques exemples de fonctions
"""
def ask_ok(prompt, retries=3, reminder='Essayes encore!'):
while True:
ok = input(prompt).upper()
if ok in ('Y', 'YES', 'O', 'OUI'):
return True
if ok in ('N', ... |
"""coding: utf-8"""
#切片
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if x == x[::-1]:
return True
else:
return False
if __name__=='__main__':
a=Solution()
print(a.isPalindrome(12421)) |
class RequestInfo:
def __init__(self,
human_string, # human-readable string (will be printed for Human object)
action_requested, # action requested ('card' + index of card / 'opponent' / 'guess')
current_hand = [], ... |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Copyright (c) 2019, Eurecat / UPF
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
stack = []
if root is not None:
... |
__author__ = '@dominofire'
class Task:
"""
Represents a task in the workflow
"""
def __init__(self, name, cmd):
self.name = name
""" A name for the task that is unique among workflow scope """
self.command = cmd
""" A valid bash command to be executed """
# Used... |
class RawMemory(object):
'''Represents raw memory.'''
def __init__(self):
self._pointer_to_object = {}
self._object_to_pointer = {}
# address 0 won't be used
self._current_pointer = 0
def get_pointer(self, obj):
assert obj in self._object_to_pointer
return se... |
class Paginator:
def __init__(self, configuration, request):
self.configuration = configuration
self.page = request.args.get('page', 1, type=int)
self.page_size = request.args.get('page_size', configuration.per_page, type=int)
if self.page_size > configuration.max_page_size:
... |
'''
Python To-Do
A simple to-do list program using text files to hold tasks
Authored by: Bryce Buchanan
'''
# TO DO 1. Convert to class
# TO DO 2. Allow editing of tasks
# TO DO 3. Detemine and implement best data structure
# TO DO 4. File I/O
# TO DO 5. GUI
#class ToDoItem:
# def __init__(self, task):
# self.task ... |
EXECUTE_MODE_AUTO = "auto"
EXECUTE_MODE_ASYNC = "async"
EXECUTE_MODE_SYNC = "sync"
EXECUTE_MODE_OPTIONS = frozenset([
EXECUTE_MODE_AUTO,
EXECUTE_MODE_ASYNC,
EXECUTE_MODE_SYNC,
])
EXECUTE_CONTROL_OPTION_ASYNC = "async-execute"
EXECUTE_CONTROL_OPTION_SYNC = "sync-execute"
EXECUTE_CONTROL_OPTIONS = frozense... |
# -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:40 ms, 在所有 Python3 提交中击败了98.48% 的用户
内存消耗:13.7 MB, 在所有 Python3 提交中击败了6.28% 的用户
解题思路:
现将对行进行翻转,将每行第一个变为1
其次,对列进行变换,如果本列0数量较多,则翻转
"""
class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
for i in range(m): ... |
# Euler problem 90: Cube digit pairs
def solve():
# Find all possible dies with 6 digits on faces out of 10 combinations
options = []
find_options(options, [])
count = 0
# Figure out which combinations of two dies make a square
for die1 in options:
for die2 in options:
... |
class SimHash:
def __init__(self, bit=64, limit=3):
self.bit = bit
self.limit = limit
self.docs = []
def compute_bits(self, text):
word_hash = []
for word in text:
word_hash.append(hash(word))
hash_bits = []
while len(hash_bits) <... |
# Curso Introdução a Linguagem Python - MIT MISTI Brazil–Unicamp
# Ana Luísa Fogarin - 03/02/2021
# a193948@dac.unicamp.br
# SET 1 - Problema 5 - Festa da Pizza
size = 'small'
toppings = ['presunto', 'abacaxi']
if size == 'small':
base_value = 14
elif size == 'medium':
base_value = 16
else:
base_value = 1... |
# Write a function that takes a string as input and returns the string reversed.
class Solution(object):
def reverseString(self, s):
return s[::-1] |
# Curso Introdução a Linguagem Python - MIT MISTI Brazil–Unicamp
# Ana Luísa Fogarin - 11/02/2021
# a193948@dac.unicamp.br
# SET 4 - Problema 3 - Fração
class Rational:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def get_numerator(... |
# Copyright 2018, Michael DeHaan LLC
# License: Apache License Version 2.0 + Commons Clause
# ---------------------------------------------------------------------------
# workers.py - configuration related to worker setup. This file *CAN* be
# different per worker.
# ------------------------------------------------... |
#1016
#ENTRADA DE DADOS
entrada = int(input())
#SE O CARRO Y CONSEGUE SE DISTANCIAR EM CADA MINUTO 500metros = 0.5km
tempo = entrada/0.5
print(int(tempo), 'minutos')
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# coding: utf8
class ConsumerSequential():
"""`ConsumerSequential` class represents a Consumer pipeline Step.
"""
def __init__(
self, coroutine, name=None):
"""
Parameters
----------
coroutine : Cl... |
"""
0056. Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Interval... |
class InsertQueryComposer(object):
_insert_part = None
_values_part_template = None
_values_part = None
values_count = None
def __init__(self, table_name, columns):
columns_clause = ""
values_clause = ""
for column in columns:
columns_clause += "`{column_name}`, ... |
# parsetable.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'AND ARRAY ASSIGNMENT BINDIGSEQ CASE CHAR COLON COMMA COMMENT CONST DIGSEQ DIV DO DOT DOTDOT DOWNTO ELSE END EQUAL FOR FORWARD FUNCTION GE GOTO GT HEXDIGSEQ IDENTIFIER IF IN LABEL LBRAC LE LP... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
# program to display student's marks from record
student_n = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_n:
print(marks[student])
break
else:
print('No entry with that name found.') |
# COMPARANDO NÚMEROS
num1 = int(input("Primeiro valor: "))
num2 = int(input("Segundo valor: "))
print("-=" * 10)
if num1 > num2:
print("Primeiro valor MAIOR.")
elif num2 > num1:
print("Segundo valor MAIOR.")
else:
print("Os dois valores são iguais.") |
def shouldAttack(target):
return target and target.type != "burl"
while True:
enemy = hero.findNearestEnemy()
if shouldAttack(enemy):
hero.attack(enemy)
|
# Author: Chaojie Wang <xd_silly@163.com>; Jiawen Wu <wjw19960807@163.com>; Wei Zhao <13279389260@163.com>
# License: BSD-3-Claus
class Params(object):
def __init__(self):
"""
The basic class for storing the parameters in the probabilistic model
"""
super(Params, self).__init__()
... |
class AbstractPoint(object):
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = self.field()(x)
self.y = self.field()(y)
def __neg__(self):
return self.neg()
def __add__(self, other):
return self.add(other)
def __sub__(self, other):
return self.add(other.neg())
def __mul__(self, n):
retur... |
class Animal:
cat = "cat"
dog = "dog"
panda = "panda"
koala = "koala"
fox = "fox"
bird = "bird"
racoon = "racoon"
kangaroo = "kangaroo"
elephant = "elephant"
giraffe = "giraffe"
whale = "whale"
birb = "birb"
raccoon = "raccoon"
class Gif:
wink = "wink"
pat = ... |
##### Functions ################################################################
def lgis3( seq, count ):
'''
Returns reversed version of (a) longest increasing subsequence.
seq: the sequence for which (a) longest increasing subsequence is desired.
count: number of items in seq
Notes:
Uses "P... |
# Copyright 2017 John McGehee
#
# 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 or agreed to in writing... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: promotions
Description :
date: 2022/2/13
-------------------------------------------------
"""
def fidelity_promo(order):
"""为积分为1000或以上的顾客提供5%折扣"""
return order.total() * .05 if order.customer.fidelit... |
class Customer(object):
def __init__(self, match, customer, **kwargs):
self.id = kwargs.get('id', None)
self.match = match
self.customer = customer
def __repr__(self):
return 'Customer(id=%r, match=%r, customer=%r)' % (
self.id, self.match, self.customer)
@cla... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 22:24:05 2019
@author: Pooyan
"""
#this code must be checked
x=10
if x<20:
print('hello...')
else:
print('good Bye')
|
# -*- coding: utf-8 -*-
"""
322. Coin Change
You are given coins of different denominations and a total amount of money amount.
Write a function to compute the fewest number of coins that you need to make up that amount.
If that amount of money cannot be made up by any combination of the coins, return -1.
Note:
You m... |
{
'variables': {
'zmq_shared%': 'false',
'zmq_draft%': 'false',
'zmq_no_sync_resolve%': 'false',
},
'targets': [
{
'target_name': 'libzmq',
'type': 'none',
'conditions': [
["zmq_shared == 'false'", {
'actions': [{
'action_name': 'build_libzmq',
... |
#n! = 1 * 2 * 3 * 4 ..... * n
#n! = [1 * 2 * 3 * 4 ..... n-1]* n
#n! = n * (n-1)!
# n = 7
# product = 1
# for i in range(n):
# product = product * (i+1)
# print(product)
def factorial_iter(n):
product = 1
for i in range(n):
product = product * (i+1)
return product
def factorial_recursive(n):... |
def remove_whilespace_nodes(node, unlink=False):
"""Removes all of the whitespace-only text decendants of a DOM node.
When creating a DOM from an XML source, XML parsers are required to
consider several conditions when deciding whether to include
whitespace-only text nodes. This function ignores al... |
"""
16204. 카드 뽑기
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 76 ms
해결 날짜: 2020년 9월 13일
"""
def main():
N, M, K = map(int, input().split())
print(min(M, K) - max(M, K) + N)
if __name__ == '__main__':
main()
|
"""
image process detail
byte, int, float, double, rgb
""" |
n1 = int(input('Digite o valor: '))
n2 = int(input('Digite o valor: '))
s = n1+n2
print('A soma de {} e {} é {}'.format(n1, n2, s))
|
#!/usr/bin/env python2
# The MIT License (MIT)
#
# Copyright (c) 2015 Shane O'Connor
#
# 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, including without limitation the r... |
class Cell:
def __init__(self, c=' '):
self.c = c
self.highlight = {}
def __mul__(self, n):
return [Cell(self.c) for i in range(n)]
def __str__(self):
return self.c
class Highlight:
def __init__(self, line, highlight):
self.line = line
self.highlight = ... |
def parse_args(r_args):
columns = r_args.get('columns')
args = {key:value for (key,value) in r_args.items() if key not in ('columns', 'api_key')}
return columns, args |
class Solution:
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
queue = collections.deque()
for i, row in enumerate(matrix):
for j, val in enumerate(row):
if val == 0:
queue.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Config(object):
config = None
def __init__(self, config):
self.config = config
def __str__(self):
return str(self.config)
def __getitem__(self, item):
return self.config[item]
def interactive(self):
return sel... |
palavra = ('Curso', 'Video', 'Python')
qualPalavra = 0
qualLetra = 0
while True:
if palavra[qualPalavra][qualLetra] in 'AaEeIiOoUu':
print(palavra[qualPalavra]) |
# -*- coding: utf-8 -*-
"""
@project: Sorting-Algorithms
@version: v1.0.0
@file: heap_sort.py
@brief: Heap Sort
@software: PyCharm
@author: Kai Sun
@email: autosunkai@gmail.com
@date: 2021/8/4 20:42
@updated: 2021/8/4 20:42
"""
def build_heap(arr):
for i in range(len(arr) // 2... |
""" This file is create and managed by Tahir Iqbal
----------------------------------------------
It can be use only for education purpose
"""
# Printing Single and Double Quote
# single quote should print in double quotes
single = "Python's"
print(single)
# double quote should print in single quotes
doub... |
'''
Created on 2016年2月8日
@author: Darren
'''
'''
Greedy Gift Givers
A group of NP (2 ≤ NP ≤ 10) uniquely named friends has decided to exchange gifts of money. Each of these friends might or might not give some money to any or all of the other friends. Likewise, each friend might or might not receive money from any or... |
"""California county names"""
bay_area_counties = [
"alameda",
"contra_costa",
"marin",
"napa",
"san_francisco",
"san_mateo",
"santa_clara",
"sonoma",
"solano"
]
other_ca_counties = [
"amador",
"butte",
"calaveras",
"colusa",
"del_norte",
"el_dorado",
"... |
def to_batch_seq(batch):
q_seq = []
history = []
label = []
for item in batch:
q_seq.append(item['question_tokens'])
history.append(item["history"])
label.append(item["label"])
return q_seq, history, label
# CHANGED
def to_batch_tables(batch, table_type):
# col_lens = [... |
def horn(coefs, x0):
n = len(coefs)
b = coefs[0]
for index in range(1,n):
b = coefs[index] + b * x0
return b
j=horn([2,2,3,-21,8],8)
print(j) |
nome = input('Qual o seu nome?')
print('É um grande prazer te conhecer,', nome)
idade = input('Quantos anos você tem?')
print('Bacana que você tem', idade,'anos', nome,'!')
filho = input('Você tem filhos?')
print('Que bacana!')
nomeFilho = input('Qual o nome do seu filho?')
print('Então ele se chama', nomeFilho, '!') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e/train/python
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i: i + n]
# Task 1: Encode function
#
# Implem... |
class TradingDayData:
def __init__(self, pricebars, tradingday):
self.__pricebars = pricebars
self.__tradingday = tradingday
@property
def price_bars(self):
return self.__pricebars
|
# MEDIUM
# since this is looking for permutation, the Time would be O(N!)
# 1. first check if the input can form a palindrome => only <=1 odd occured char can used
# 2. only permutate the half of the input == permutation II
# eg. input = "aabb"
# only permutate ["a","b"], append reversed(input) to the end
... |
'''
Created on 15 May 2018
@author: igoroya
'''
def read_text(file_path):
my_file = open(file_path, 'r', encoding="utf-8")
text = my_file.read()
my_file.close()
return text
def print_text(text):
print(text)
def get_lines(text):
return text.split("\n")
def get_words(text):
words = []
... |
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s:
return True
m, n = 0, len(s) - 1
i, j = 0, len(t) - 1
while i <= j and m <= n:
if t[i] == s[m]:
m += 1
i += 1
else:
i += 1
... |
# Exemplo estrutura dicionário em python
contatosTelefone = {
"Joao": "11-99999-9999",
"Maria": "11-98888-8888"
}
#Exibindo chaves do dicionário
print("Keys: ",contatosTelefone.keys())
#Exibindo valores do dicioário
print("Valores: ",contatosTelefone.values())
#Exibindo chaves e valoreas através do laço for... |
"""
Copyright 2015 Rackspace
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 or agreed to in writing, software
dist... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
def add_two(a, b):
return a + b
if __name__ == "__main__":
# print(add_two.__code__)
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.