content stringlengths 7 1.05M |
|---|
"""Crie um programa que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas;
- O nome com todas as letras minúsculas;
Quantas letras ao todo, sem considerar espaços;
Quantas letras tem o primeiro nome:"""
n = str(input('Digite seu nome completo: ')).strip()
#div = n.split()
print(n.up... |
bot_fav_color = "blue"
# Creating a parent class to use for various games
class Player:
def __init__(self, name, fav_color):
self.name = name
self.fav_color = fav_color
def __str__(self):
if self.fav_color == "blue":
return f"Hi {self.name} 😉! My favorite color... |
'''011 - PINTANDO PAREDES.
PROGRAMA QUE LEIA LARGURA E ALTURA DE UMA ÁREA E MOSTRE A QUANTIDADE DE TINTA QUE SERÁ NECESSÁRIO
TINTA = 4.5m'''
L = float(input('Qual a Largura da parede: '))
A = float(input('Qual a Altura da parede: '))
AT = L * A
T = AT / 4.5
print('Sua parede tem a dimensão de {} x {}, então sua área é... |
""" if
print('programa de notas')
def evaluacion(nota):
valoracion="aprovado"
if nota < 5:
valoracion='suspendido'
else:
valoracion='aprovo'
return valoracion
dato = input('ingrese la nota: ')
print(evaluacion(int(dato))) """
""" for
# recorro una lista
for i in... |
#Task 4: Login functionality
# In its parameter list, define three parameters: database, username, and password.
def login(database, username, password):
if username in dict.keys(database) and database[username] == password:
print("Welcome back: ", username)
elif username in dict.keys(database) or pass... |
H, W = map(int, input().split())
N = 0
a_map = []
for i in range(H):
a = list(map(int, input().split()))
a_map.append(a)
result = []
for i in range(H):
for j in range(W):
if a_map[i][j]%2==1:
if j < W - 1:
N += 1
result.append([i + 1, j + 1, i + 1, j + 2])... |
class Stairs:
def designs(self, maxHeight, minWidth, totalHeight, totalWidth):
c = 0
for r in xrange(1, maxHeight + 1):
if totalHeight % r == 0:
n = totalHeight / r
if (
n > 1
and totalWidth % (n - 1) == 0
... |
# Solve the Equation
class Solution(object):
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
left, right = equation.split('=')
a1, b1 = self.get_coefficients(left)
a2, b2 = self.get_coefficients(right)
a, b = a1 - a2, b2 - b... |
# 邮箱验证链接有效时间:s
VERIF_EMAIL_TOKEN_EXPIRES = 7200
# 登录用户收货地址最大数量
USER_ADDRESS_COUNTS_LIMIT = 20
# 登录用户浏览记录保存最大数量
USER_BROWSING_HISTORY_COUNTS_LIMIT = 5
|
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... |
length = int(raw_input())
s = raw_input()
n = length / 4
A = T = G = C = 0
for i in s:
if i == 'A':
A += 1
elif i == 'T':
T += 1
elif i == 'G':
G += 1
else:
C += 1
res = 0
if A != n or C != n or G != n or T != n:
res = length
l = 0
for r in xrange(length):
... |
class JellyBean:
def __init__( self, mass = 0 ):
self.mass = mass
def __add__( self, other ):
other_mass = other.mass
other.mass = 0
return JellyBean( self.mass + other_mass )
def __sub__( self, other ):
self_mass = self.mass
self.mass -= other.mass
def... |
def fatorial(a,b=0):
"""
Uma função que calcula o fatorial de um número
:param a: Número a ser calculado
:param b: Variável de escolha que define a visualização dos cálculos
:return: Sem retorno
"""
f = a
if b == 1:
for c in range(a-1,1,-1):
f = f * c
print(f... |
class PlayerAlreadyHasItemError(Exception):
pass
class PlayerNotInitializedError(Exception):
pass
|
valorProduto = float(input('Insira o valor do produto: R$'))
porcentagem = int(input('Insira a % de desconto deste produto: '))
valorDesconto = porcentagem*valorProduto/100
print(f'O valor final é de: R${valorProduto-valorDesconto:.2f} ')
|
# Preferences defaults
PREFERENCES_PATH = "./config/preferences.json"
PREFERENCES_DEFAULTS = {
'on_time': 1200,
'off_time': 300
}
# Bot configureation
DISCORD_TOKEN = "from https://discord.com/developers"
ADMIN_ID = 420
USER_ID = 999
DEV_MODE = True
PREFIX = '!!'
PREFIXES = ('johnsmith ', 'john smith ')
COGS_L... |
# สร้าง list
def detail(data): # data รับมาเป็น list
for i in data:
print("{}".format(i))
score = []
print("{}".format(score))
print("{}".format(type(score)))
for i in range(5):
x = int(input('Enter Score : '))
score.append(x)
print("{}".format(score))
detail(score)
# List Com... |
# has_good_credit = True
# has_criminal_record = True
#
# if has_good_credit and not has_criminal_record:
# print("Eligible for loan")
# temperature = 35
#
# if temperature > 30:
# print("It's a hot day")
# else:
# print("It's not a hot day")
name = "ddddddddddddddddddddddddddddddddddddddddddddddddddddddd... |
x = ''
while True:
x = input()
print(x)
if x == 'end':
break
print('end') |
# -*- coding: utf-8 -*-
def main():
s = sorted([input() for _ in range(15)])
print(s[6])
if __name__ == '__main__':
main()
|
#prctice8-14
#汽车
def make_car(name, brand, **other):
car = {}
car['name'] = name
car['brand']=brand
for key, value in other.items():
car[key]=value
return car
car = make_car('subaru', 'outback',
color= 'blue',
tow_package=True)
print(car)
|
class Calculadora(object):
"""docstring for Calculadora"""
memoria = 10
def suma(a, b):
return a + b
def resta(a, b):
return a - b
def multiplicacion(a, b):
return a * b
def division(a, b):
return a / b
@classmethod
def numerosPrimos(cls, limite):
rango = range(2, limite)
return [primo for prim... |
# Perulangan pada set dan dictionary
print('\n==========Perulangan Pada Set==========')
set_integer = {10, 20, 30, 40, 50}
# Cara pertama
for item in set_integer:
print(item, end=' ')
print('')
# Cara kedua
for i in range(len(set_integer)):
print(list(set_integer)[i], end=' ')
print('')
# Cara ketiga
i = 0... |
# -*- coding: utf-8 -*-
minha_string = "O rato roeu a roupa do rei de Roma"
busca = minha_string.find("rei") #recebe como parametro a busca
print(busca) #mostra a posição da busca
print(minha_string[busca:]) #mostra tudo que vem após a busca
busca = minha_string.find("Rainha")
print(busca) #caso não encontre o resul... |
# -*- coding: utf-8 -*-
# @Author: zengjq
# @Date: 2020-10-21 14:04:31
# @Last Modified by: zengjq
# @Last Modified time: 2020-10-21 14:45:03
class Solution:
# 90 mem 100
# 把大数往nums1的末尾移动
def merge(self, nums1, m, nums2, n):
while m and n:
if nums1[m-1] > nums2[n-1]:
... |
def word_time(word, elapsed_time):
return [word, elapsed_time]
p0 = [word_time('START', 0), word_time('What', 0.2), word_time('great', 0.4), word_time('luck', 0.8)]
p1 = [word_time('START', 0), word_time('What', 0.6), word_time('great', 0.8), word_time('luck', 1.19)]
p0
p1 |
# Definition for singly-linked list.
# class LinkedListNode:
# def __init__(self, value = 0, next = None):
# self.value = value
# self.next = next
class Solution:
def containsCycle(self, head):
if not head or not head.next:
return False
current = head
... |
def inf():
while True:
yield
for _ in inf():
input('>')
|
def grep(pattern):
print("Searching for", pattern)
while True:
line = (yield)
if pattern in line:
print(line)
search = grep('coroutine')
next(search)
search.send("I love you")
search.send("Don't you love me")
search.send("I love coroutines")
|
# -*- coding: utf-8 -*-
def extraNumber(A, B, C):
if A == B: return C
elif A == C: return B
else: return A
extraNumber = lambda A, B, C: C if (A == B) else B if (A == C) else A
"""
Given three integers, two of them are guaranteed to be equal, find the third one.
Example
For A = 2, B = 4 and C = 2, the ... |
def conf():
return {
"id":"discord",
"description":"this is the discord c360 component",
"enabled":False,
} |
"""Custom errors and exceptions."""
class MusicAssistantError(Exception):
"""Custom Exception for all errors."""
class ProviderUnavailableError(MusicAssistantError):
"""Error raised when trying to access mediaitem of unavailable provider."""
class MediaNotFoundError(MusicAssistantError):
"""Error rais... |
S = input()
l = len(S)
nhug = 0
for i in range(l//2):
if S[i] != S[l-1-i]:
nhug += 1
print(nhug)
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hi there! I'm {}, {} years old!".format(self.name, self.age))
maria = Person("Maria Popova", 25)
pesho = Person("Pesho", 27)
print(maria)
# name = Maria Popova
# age = 25 |
class Solution:
def maxNumber(self, nums1, nums2, k):
def merge(arr1, arr2):
res, i, j = [], 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i:] >= arr2[j:]:
res.append(arr1[i])
i += 1
else:
... |
def sudoku2(grid):
seen = set()
# Iterate through grid
for i in range(len(grid)):
for j in range(len(grid[i])):
current_value = grid[i][j]
if current_value != ".":
if (
(current_value + " found in row " + str(i)) in seen
... |
"""Constants for the tankerkoenig integration."""
DOMAIN = "tankerkoenig"
NAME = "tankerkoenig"
CONF_FUEL_TYPES = "fuel_types"
CONF_STATIONS = "stations"
FUEL_TYPES = ["e5", "e10", "diesel"]
|
FEATURES = 'FEATURES'
AUTH_GITHUB = 'AUTH_GITHUB'
AUTH_GITLAB = 'AUTH_GITLAB'
AUTH_BITBUCKET = 'AUTH_BITBUCKET'
AUTH_AZURE = 'AUTH_AZURE'
AFFINITIES = 'AFFINITIES'
ARCHIVES_ROOT = 'ARCHIVES_ROOT'
DOWNLOADS_ROOT = 'DOWNLOADS_ROOT'
ADMIN = 'ADMIN'
NODE_SELECTORS = 'NODE_SELECTORS'
TOLERATIONS = 'TOLERATIONS'
ANNOTATIONS ... |
# Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of j... |
def aumentar(v=0, t=0, per=False):
res = v + (v*t/100)
return res if per is False else f'{moeda(res)}'
def diminuir(v=0, t=0, per=False):
res = v - (v*t/100)
return res if per == False else f'{moeda(res)}'
def dobro(v=0, per=False):
res = v*2
return res if not per else f'{moeda(res)}'
def ... |
def func(*args):
print(args)
print(*args)
a = [1, 2, 3]
# here "a" is passed as tuple of list: ([1, 2, 3],)
func(a)
# print(args) -> ([1, 2, 3],)
# print(*args) -> [1, 2, 3]
# here "a" is passed as tuple of integers: (1, 2, 3)
func(*a)
# print(args) -> (1, 2, 3)
# print(*args) -> 1 2 3
|
def main():
while True:
n,m = map(int, input().split())
if n==0 and m==0:
break
D = [9] * n
H = [0] * m
for d in range(n):
D[d] = int(input())
for k in range(m):
H[k] = int(input())
D.sort() #... |
# Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '[' ']’. These brackets must be close in the correct order. for example "()" and "()[]{}" are valid but "[)", "({[)]" and "{{{" are invalid.
class validity:
def f(str):
a= ['()', '{}', '[]']
while any(i in str... |
# Default Configurations
DEFAULT_PYTHON_PATH = '/usr/bin/python'
DEFAULT_STD_OUT_LOG_LOC = '/usr/local/bin/log/env_var_manager.log'
DEFAULT_STSD_ERR_LOG_LOC = '/usr/local/bin/log/env_var_manager.log'
DEFAULT_START_INTERVAL = 120
|
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = input(prompt)
# in 关键字。它测定序列中是否包含某个确定的值。
if ok in ('y', 'yes', 'ye'):
return True
if ok in ('n', 'no', 'nop', 'nope '):
return False
retries = retries -1
if retries < 0:
raise OSError('uncooperati... |
n=int(input())
students={}
for k in range(0,n):
name = input()
grade=float(input())
if not name in students:
students[name]=[grade]
else:
students[name].append(grade)
for j in students:
gradesCount=len(students[j]); gradesSum=0
for k in range(0,len(students[j])):
... |
def problem_2():
"By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
sequence = [1]
total, sequence_next = 0, 0
# While the next term in the Fibonacci sequence is under 4000000...
while(sequence_next < 4000000):
... |
"""
创建函数,计算IQ等级
ma = int(input("请输入你的心里年龄:"))
ca = int(input("请输入你的实际年龄:"))
iq = ma / ca * 100
if 140 <= iq:
print("天才")
elif 120 <= iq:
print("超常")
elif 110 <= iq:
print("聪慧")
elif 90 <= iq:
print("正常")
elif 80 <= iq:
print("迟钝")
else:
print("低能")
"""
def get_iq(ma,ca):
iq = ma / ca * 100
... |
#
# PySNMP MIB module HUAWEI-VPLS-TNL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-VPLS-TNL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:49:40 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
nome = 'Luiz Otávio'
idade = 32
altura = 1.80
e_maior = idade > 18
peso = 80
imc = peso / (altura**2)
print(nome, 'tem', idade, 'anos de idade e seu imc é', imc)
#
print(f'{nome} tem {idade} anos de idade e seu imc é {imc:.2f}')
print('{} tem {} anos de idade e seu imc é {:.2f}'.format(nome, idade, imc))
# No exempl... |
print('a sequence from 0 to 2')
for i in range(3):
print(i)
print('----------------------')
print('a sequence from 2 to 4')
for i in range(2, 5):
print(i)
print('----------------------')
print('a sequence from 2 to 8 with a step of 2')
for i in range(2, 9, 2):
print(i)
'''
Output:
a seque... |
class MockResponse:
def __init__(self, status_code, data):
self.status_code = status_code
self.data = data
def json(self):
return self.data
class AuthenticationMock:
def get_token(self):
pass
def get_headers(self):
return {"Authorization": "Bearer token"}... |
#Creating a Tuple
newtuple = 'a','b','c','d'
print(newtuple)
# Tuple with 1 element
tupple = 'a',
print(tupple)
newtuple1 = tuple('abcd')
print(newtuple1)
print("------------------")
#Accessing Tuples
newtuple = 'a','b','c','d'
print(newtuple[1])
print(newtuple[-1])
#Traversing a Tuple
for i in newtuple:
print(... |
my_favorite_things = {'food': ['burgers', 'pho', 'mangoes'], 'basketball': ['dribbling', 'passing', 'shooting']}
# A list uses square brackets while a dictionary uses curly braces.
my_favorite_things['movies'] = ['Avengers', 'Star Wars']
# my_favorite_things of movies is value
# A square bracket after a variable allows... |
#
# @lc app=leetcode id=2 lang=python
#
# [2] Add Two Numbers
#
# @lc code=start
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type... |
def get_words_indexes(words_indexes_dictionary, review):
words = review.split(' ')
words_indexes = set()
for word in words:
if word in words_indexes_dictionary:
word_index = words_indexes_dictionary[word]
words_indexes.add(word_index)
return words_indexe... |
bool_expected_methods = [
'__abs__',
'__add__',
'__and__',
'__bool__',
'__ceil__',
'__class__',
'__delattr__',
'__dir__',
'__divmod__',
'__doc__',
'__eq__',
'__float__',
'__floor__',
'__floordiv__',
'__format__',
'__ge__',
'__getattribute__',
'__ge... |
#the program calculates the average of numbers whose input is in the form of a string
def average():
numbers = str(input("Enter a string of numbers: "))
numbers = numbers.split()
numbers2 = []
total = 0
for number in numbers:
number = int(number)
total += number
... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_dict = {}
for i, num in enumerate(nums):
n = target - num
if n not in num_dict:
num_dict[num] = i
else:
return [num_dict[n], i]
|
def pick_arr(arr, b):
nums = arr[:b]
idxsum = sum(nums)
maxsum = idxsum
for i in range(b):
remove = nums.pop()
add = arr.pop()
idxsum = idxsum - remove + add
maxsum = max(maxsum, idxsum)
return maxsum
print(pick_arr([5,-2,3,1,2], 3))
|
#!/usr/bin/env python
# encoding: utf-8
class HashInterface(object):
@staticmethod
def hash(*arg):
pass
|
class Solution:
def solve(self, nums):
ans = [-1]*len(nums)
unmatched = []
for i in range(len(nums)):
while unmatched and unmatched[0][0] < nums[i]:
ans[heappop(unmatched)[1]] = nums[i]
heappush(unmatched, [nums[i], i])
for i in range(len(nu... |
# This is a sample Python script.
# Press shift+⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press ⌘F8 t... |
'''
Created on Aug 30, 2012
@author: philipkershaw
'''
|
SETTINGS = {
'gee': {
'service_account': None,
'privatekey_file': None,
}
}
|
grid = [
[0,0,0,0,7,0,0,8,4],
[0,0,0,8,0,0,9,7,0],
[0,1,0,0,0,0,2,0,0],
[0,0,3,0,0,0,8,9,0],
[8,2,0,4,9,0,0,3,6],
[9,0,0,0,0,8,0,0,0],
[0,7,0,0,0,0,0,0,0],
[0,0,4,0,0,0,0,6,0],
[1,0,6,0,0,7,3,0,2],
]
def print_matriz():
for y in range(0,9):
for x in range(0,9):
... |
def fibonacci(n):
"""
Def: In mathematics, the Fibonacci numbers are the numbers in the following
integer sequence, called the Fibonacci sequence, and characterized by the
fact that every number after the first two is the sum of the two preceding
ones: `0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,... |
# Fried Chicken Damage Skin
success = sm.addDamageSkin(2435960)
if success:
sm.chat("The Fried Chicken Damage Skin has been added to your account's damage skin collection.")
# sm.consumeItem(2435960)
|
# -*- coding: utf-8 -*-
# Tests for the different contrib/localflavor/ form fields.
localflavor_tests = r"""
# USZipCodeField ##############################################################
USZipCodeField validates that the data is either a five-digit U.S. zip code or
a zip+4.
>>> from django.contrib.localflavor.us.fo... |
class Solution(object):
def decompressRLElist(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
new = []
for i in range(len(nums)/2):
new += nums[2*i] * [nums[2*i+1]]
return new |
# -*- coding: utf-8 -*-
BADREQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
GONE = 410
TOOMANYREQUESTS = 412
class DnsdbException(Exception):
def __init__(self, message, errcode=500, detail=None, msg_ch=u''):
self.message = message
self.errcode = errcode
self.detail = detail
self.... |
#create class
class Event:
#create class variables
def __init__(self , eventId , eventType , themeColor , location):
self.eventId = eventId
self.eventType = eventType
self.themeColor = themeColor
self.location = location
#define class functions
def displayEventDetails(se... |
"""
1. Основы циклов.
a. Напишите цикл for, который выводит ASCII-коды всех символов в стро-
ке с именем S. Для преобразования символов в целочисленные ASCII-
коды используйте встроенную функцию ord(character). (Поэксперимен-
тируйте с ней в интерактивной оболочке, чтобы понять, как она рабо-
тает.)
b. Затем изм... |
class Piece:
def __init__(self, row, col):
self.clicked = False
self.numAround = -1
self.flagged = False
self.row, self.col = row, col
def setNeighbors(self, neighbors):
self.neighbors = neighbors
def getNumFlaggedAround(self):
num = 0
for n in self... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:del.py
@TIME:2020/4/29 19:57
@DES:
'''
dict = {'shuxue':99,'yuwen':99,'yingyu':99}
print('shuxue:',dict['shuxue'])
print('yuwen:',dict['yuwen'])
print('yingyu:',dict['yin... |
# Input is square matrix A whose rows are sorted lists.
# Returns a list B by merging all rows into a single list.
#
# Goal: O(n^2 log n)
# Actually O(n^2 log(n^2)) but since log(n^2) == 2log(n) and constant factors can be ignored => O(2log(n)) can be relaxed to O(log(n))
def mergesort(Sublists):
sublists_count=l... |
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# Author: Flyaway - flyaway1217@gmail.com
# Blog: zhouyichu.com
#
# Python release: 3.4.5
#
# Date: 2017-02-28 13:43:07
# Last modified: 2017-03-01 17:02:35
"""
Database for DIRT
"""
class Path:
"""Path is the real data structure that store in the database.
""... |
def non_contiguous_motif(str1, dna_list):
index = -1
num = 0
for i in str1:
for j in dna_list:
index+= 1
if i == j:
num = index
return num
|
#!/usr/bin/env python
NAME = 'Microsoft ISA Server'
def is_waf(self):
detected = False
r = self.invalid_host()
if r is None:
return
if r.reason in self.isaservermatch:
detected = True
return detected
|
#
# PySNMP MIB module Unisphere-Data-L2F-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-L2F-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:24:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
# -*- coding: utf-8 -*-
# Docstring
"""Run the Full create_MW_potential_2014 set of scripts."""
__author__ = "Nathaniel Starkman"
__all__ = [
"main",
]
###############################################################################
# IMPORTS
###################################################################... |
enu = 3
zenn = 0
for ai in range(enu, -1, -1):
zenn += ai*ai*ai
print(zenn)
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
File for Message object and associated functions.
The Message object's key function is to prevent users from editing... |
deck = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
value = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
deck_values = dict(zip(deck, value))
hand = [input() for _ in range(6)]
hand_values = [deck_values.get(card) for card in hand]
print(sum(hand_values) / 6)
|
def validate(opciones, eleccion): #recibe las opciones en una lista y lo que introdujo el usuario
# Definir validación de eleccion
##########################################################################
#pass
while eleccion not in opciones: #mientras la eleccion no este en la lista de opciones
... |
"""Codon to amino acid dictionary"""
codon_to_aa = {
"TTT": "F",
"TTC": "F",
"TTA": "L",
"TTG": "L",
"TCT": "S",
"TCC": "S",
"TCA": "S",
"TCG": "S",
"TAT": "Y",
"TAC": "Y",
"TAA": "*",
"TAG": "*",
"TGT": "C",
"TGC": "C",
"TGA": "*",
"TGG": "W",
"CTT": ... |
# -*- coding: utf-8 -*-
class RedirectError(Exception):
def __init__(self, response):
self.response = response
class NotLoggedInError(Exception):
pass
class SessionNotFreshError(Exception):
pass |
class Cell(object):
def __init__(self):
self.neighbours = [None for _ in range(8)]
self.current_state = False
self.next_state = False
self.fixed = False
def count_neighbours(self) -> int:
count = 0
for n in self.neighbours:
if n.current_state:
... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: aghast_generated
class DimensionOrder(object):
c_order = 0
fortran_order = 1
|
def specialPolynomial(x, n):
s = 1
k = 0
while s <= n:
k += 1
s += x**k
return k-1
if __name__ == '__main__':
input0 = [2, 10, 1, 3]
input1 = [5, 111111110, 100, 140]
expectedOutput = [1, 7, 99, 4]
assert len(input0) == len(expectedOutput), '# input0 = {}, # expectedOutput = {}'.format(len(input0), len(exp... |
class TermGroupScope:
"""Specifies the values different group types can take within the termStore."""
global_ = 0
system = 1
siteCollection = 2
unknownFutureValue = 3
|
arphabet_to_ipa = {
'aa': 'ɑ',
'ae': 'æ',
'ah':'ʌ',
'ao':'ɔ',
'aw':'W',
'ax':'ə',
'axr':'ɚ',
'ay':'Y',
'eh':'ɛ',
'er':'ɝ',
'ey':'e',
'ih':'ɪ',
'ix':'ɨ',
'iy':'i',
'ow':'o',
'oy':'O',
'uh':'ʊ',
'uw':'u',
'ux':'ʉ',
'b':'b',
'ch':'C',
... |
def render_q(world, q_learner):
qvalues_list = []
for h in range(world.height):
row = []
qvalues_row = []
for w in range(world.width):
loc = torch.LongTensor([h, w])
c = world.get_at(loc)
# print('c', c)
if c == '' or c == 'A':
... |
__all__ = [
"deployment_pb2",
"repository_pb2",
"status_pb2",
"yatai_service_pb2_grpc",
"yatai_service_pb2",
]
|
class UnresolvedChild(Exception):
"""
Exception raised when children should be lazyloaded first
"""
pass
class TimeConstraintError(Exception):
"""
Exception raised when it is not possble to satisfy timing constraints
"""
pass
|
def solve():
N = int(input())
V = list(map(int, input().split()))
V1 = sorted(V[::2])
V2 = sorted(V[1::2])
flag = -1
for i in range(1, N):
i_ = i // 2
# if i&1: print('Check {} {}'.format(V1[i_], V2[i_]))
# if i&1==0: print('Check {} {}'.format(V2[i_-1], V1[i_]))
... |
"""
This file contains mappings:
parameters_names_mapping - Mapping of Tcl/Tk command attributes
to methods of Qt/own objects.
Own objects are included because
of implementation details such as
menu problem (see ... |
def module4():
print(123 == '123') #______
print(123 == int('123')) #______
print('ABC' == 'abc') #______
print(True == 1) #______
print(False == "") #______
print(False == bool("")) #______ |
def target(x0, sink):
print(f'input: {x0}')
while True:
task = yield
x0 = task(x0)
sink.send(x0)
def sink():
try:
while True:
x = yield
except GeneratorExit:
print(f'final output: {x}')
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.