content stringlengths 7 1.05M |
|---|
MONTHS = ["january", "february", "march", "april", "may", "june","july", "august", "september","october","november", "december"]
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
def getDate():
alvin.speak('Today is monday jun 14')
def get_date(text):
text = text.lower()... |
#
# Copyright 2019 XEBIALABS
#
# 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 rights to use, copy, modify, merge, publish, distribute, su... |
num_cases = int(input())
# Graph is small (less than 27 nodes), and we can represent the disjoint set using an array.
for c in range(num_cases):
forest = [-1] * 26
partition_id = 0
while True:
line = input().strip()
if line[0] == "*":
line = input().strip().split(",")
# Report here
n... |
# r_to_d converts from radius as an integer or float to diameter.
def r_to_d ( radius ):
if radius < 0:
radius = -radius
print ( "in function radius= ->{}<-".format(radius) )
diameter = radius * 2
print ( "in function diameter= ->{}<-".format(diameter) )
return (diameter)
# Automated Tes... |
class TransferControl:
def __init__(self, req):
self.req = req
async def check_balance(self):
"""
:return:
"""
endpoint = 'balance'
return await self.req.get(endpoint=endpoint)
async def check_balance_ledger(self):
"""
:return:
""... |
set_name(0x80122CDC, "PresOnlyTestRoutine__Fv", SN_NOWARN)
set_name(0x80122D04, "FeInitBuffer__Fv", SN_NOWARN)
set_name(0x80122D2C, "FeAddEntry__Fii8TXT_JUSTiP7FeTableP5CFont", SN_NOWARN)
set_name(0x80122D9C, "FeAddTable__FP11FeMenuTablei", SN_NOWARN)
set_name(0x80122E1C, "FeDrawBuffer__Fv", SN_NOWARN)
set_name(0x80123... |
#Получение размера
a = {0, 1, 2, 3}
print(len(a))
#4
#Добавление элемента
a = {0, 1, 2, 3}
a.add(4)
print(a)
#{0, 1, 2, 3, 4}
#Удаление элемента
a = {0, 1, 2, 3}
a.remove(3)
print(a)
#{0, 1, 2}
#Полная очистка
a = {0, 1, 2, 3}
a.clear()
print(a)
#set()
|
cards = {}
for card in input().split():
cards.setdefault(card[0], 0)
cards[card[0]] += 1
print(max(cards.values()))
|
"""
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
Each child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the co... |
def change_var(a):
global x
x=a
return x
def change_var2(b):
x=b
return x
change_var(3)
print(x)
|
# 3. uzdevums
# my_text = input("Ievadiet savu tekstu: ")
# text_1 = "nav"
# text_2 = "slikts"
# if my_text.find(text_1) != -1 and my_text.find(text_2) != -1:
# new_text=my_text.replace(text_1, "ir" )
# new_text=new_text.replace(text_2, "labs" )
# print(new_text)
# else:
# print(my_text)
# 3. Uzrak... |
# SERASSI É PAR ?/
n = int(input('Kants que você quer? _ '))
for i in range(0, n + 1, 2):
print(i, end=' ')
print('\n\nJeito alternativo:')
# consome mais processamento pq tem mais laços
for j in range(0, n + 1):
if j % 2 == 0:
print(j, end=' ')
|
'''
Örnek 3.5:
İki farklı kompleks sayının toplamını hesaplayan programı kodlayalım.
'''
a = 2.5 + 3j #a sayısı
r = 6; i = -4
b = complex(r, i) #b sayısı
print ("a=",a)
print ("b=",b)
print ("a+b=",a+b) #a+b değeri |
FONT_NAME = "Verdana"
FONT_SIZE1 = "10"
FONT_SIZE2 = "11"
FONT_SIZE3 = "7"
FONT_SIZE4 = "8"
COLORS_ABBREVIATED_AUTHOR_NAME = ("#1565C0", "#6A1B9A", "#1A237E", "#311B92", "#4527A0",
"#5E35B1", "#4A148C", "#01579B", "#3949AB", "#7B1FA2",
"#283593")
DEF... |
class Config(object):
DEBUG = False
TESTING = False
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/<YOUR-DEVELOPMENT-DATABASE>'
SQLALCHEMY_TRACK_MODIFICATIONS = True
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'post... |
# This script changes the maximum metal layer to use during PnR
def replace_line_at_pattern(filename, pattern, text_insert):
read_file = open(filename, 'r').readlines()
with open(filename,'w') as write_file:
for line in read_file:
if pattern in line:
write_file.write(text_i... |
def LSB(n):
return n & -n
class FenwickTree:
def __init__(self, array):
self.len = len(array)+1
self.arr = [0] * self.len
for i in range(0, self.len - 1):
self.update(i, array[i])
def update(self, index, val):
j = index+1
while j < self.len:
... |
mylist=[1,2,3,4,5]
for i in range(len(mylist)):
print(i,len(mylist),range(len(mylist)))
mylist.pop()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'fancyears'
__mtime__ = '2020/2/7'
# code is far away from bugs with the god animal protecting
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ... |
'''
This is literally ONLY a few functions, but a great example
of a file that I might want to fill up with function definitons
and import to use at some point. I don't want to run it as a
script, I am just going to keep some functions that do things
I need...thee is NO main() either and no need to check to see
if __n... |
def mode(nums):
"""Return most-common number in list.
For this function, there will always be a single-most-common value;
you do not need to worry about handling cases where more than one item
occurs the same number of times.
>>> mode([1, 2, 1])
1
>>> mode([2, 2, 3, 3, 2])
... |
# 2.5.1, Woche 2, Block 5, Aufgabe 1
# Liste
schloss = ["rot","grün"]
# Elemente hinzufügen
schloss += ["gelb"]
# Elemente ausgeben
for i in range(len(schloss)):
print(schloss[i]) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = """73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
6222989342... |
print('Vou somar todos os números que forem pares pra você :)\nSe você digitar um número ímpar irei desconsiderá-lo')
s = 0
for c in range(0, 6):
n = int(input('Digite um número: '))
if n % 2 == 0:
s = n + s
print('A soma total é de {}'.format(s))
|
# Uses python3
memo = {}
def calc_fib(n):
if n <= 1:
return n
if n in memo:
return memo[n]
else:
f = calc_fib(n - 1) + calc_fib(n - 2)
memo[n] = f
return f
n = int(input())
print(calc_fib(n))
|
"""
the Constant Variables.
"""
class ConstantSet(object):
"""
The class of constant number.
It doesn't follow the Pascal format since its speciality.
"""
class ConstError(TypeError):
pass
class ConstCaseError(ConstError):
pass
def __setattr__(self, key, value):
i... |
def main(_, rooms, single, multiple):
for room in rooms:
single.add(room) if room not in single else multiple.add(room)
return single.difference(multiple).pop()
if __name__ == "__main__":
k, rooms, single, multiple = input(), input().split(), set(), set()
print(main(k, rooms, single, multip... |
def to_tweets(filename):
with open(filename, 'r') as raw_file:
with open(filename.split('.')[0]+'_tweets.txt', 'w') as output:
is_title = False
char_count = 0 # Max = 140
current_tweet = []
for line in raw_file.readlines():
line = line.strip()... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
val = dict()
for i in range(len(nums)):
if (target-nums[i]) in val.keys():
return [val[target-nums[i]],i]
val[nums[i]] = i
|
class ChapterError(Exception):
pass
class VerseError(Exception):
pass
|
def fibWord(n):
Sn_1 = "0"
Sn = "01"
tmp = ""
for i in range(2, n + 1):
tmp = Sn
Sn += Sn_1
Sn_1 = tmp
return Sn
# driver program
n = 6
print (fibWord(n))
|
"""
The functionality of bio_embeddings is split into 5 different modules
.. autosummary::
:toctree: modules
bio_embeddings.embed
bio_embeddings.extract
bio_embeddings.project
bio_embeddings.utilities
bio_embeddings.visualize
"""
|
code_word = "priya"
guess=""
guess_count = 0
guess_limit = 3
out_of_guess = False
while guess !=code_word and not out_of_guess :
if guess_count < guess_limit :
guess=input("enter your guess : ")
guess_count += 1
else :
out_of_guess = True
if out_of_guess:
print("out of... |
"""
Named projection classes that can be created or parsed.
"""
def find(projname, crstype, strict=False):
"""
Search for a projection name located in this module.
Arguments:
- **projname**: The projection name to search for.
- **crstype**: Which CRS naming convention to search (different
... |
#
# PySNMP MIB module CISCO-UNIFIED-COMPUTING-LICENSE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UNIFIED-COMPUTING-LICENSE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:00:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Usi... |
class NegativeNumberError(Exception):
def __init__(self, message):
super().__init__(message)
def get_inverse(n):
number = int(n)
if number == 0:
raise ZeroDivisionError('n is 0')
elif number < 0:
raise NegativeNumberError('n is less than 0')
elif type(number) is not int:
... |
def add_native_methods(clazz):
def initWriterIDs__java_lang_Class__java_lang_Class__(a0, a1, a2):
raise NotImplementedError()
def initJPEGImageWriter____(a0):
raise NotImplementedError()
def setDest__long__(a0, a1):
raise NotImplementedError()
def writeImage__long__byte____int... |
#!/usr/bin/env python
"""Tests for `beaker` package."""
def test_something():
pass
|
class Solution:
def entityParser(self, text):
ps = [[6, """, '"'],
[6, "'", "'"],
[5, "&", '&'],
[4, ">", '>'],
[4, "<", '<'],
[7, "⁄", '/']]
ans = ""
idx = 0
while idx < len(text):
... |
# Fatiamento de caracteres é usado para selecionar APENAS os caracteres especificados. A sequência começa no 0, excluindo o último caracter.
frase=str("Curso em vídeo")
print("Curso" in frase) # Exibe se existe a palavra na frase com True/False
print(frase[0]) # Exibe o primeiro caracter
print(frase[:14]) # Exibe do p... |
#!/usr/bin/python3
__author__ = "yang.dd"
"""
example 075
"""
if __name__ == '__main__':
for i in range(5):
n = 0
if i != 1:
n += 1
if i == 3:
n += 1
if i == 4:
n += 1
if i != 4:
n += 1
if n == ... |
vel = int(input('A qual velocidade você passou no radar? '))
valor = (vel - 80) * 7
if vel > 80:
print(f'Você foi multado! \nValor da multa: R${valor}')
else:
print('Velocidade permitida!') |
#Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos Dólares ela pode comprar
# Cotação do dia 25/11/2021 $5.56.
real = float(input('Informe a quantidade de dinheiro que você tem na carteira:'))
conversaoDolar: float = real / 5.56
print(f'O valor de R${real:.2f} convertido em dólar é ... |
name1 = 'Fito'
name2 = 'Ben'
name3 = 'Ruby'
name4 = 'Nish'
name5 = 'Nito'
name = input("Enter your name: ")
if name == name1 or name == name2 or name == name3 or name == name4 or name == name5:
print("I know you!")
else:
print("Sorry, ", name, "I don't know who you are :(")
|
"""
Datasets should all have the same format so they can be easily used together.
In particular, they should be exported from the submodule:
- as a xarray DataArray or saved asnetcdf file format
- with 'lon' as the longitude variable name in °E (float)
- with 'lat' as the latitude variable name in °N (float)
- with 't... |
target = int(input())
now = 0
for i in range(0, target // 5 + 1):
count_5k = target // 5 - i
count_3k = 0
if count_5k * 5 == target:
print(count_5k + count_3k)
break
else:
if (target - count_5k * 5) % 3 == 0:
count_3k = (target - count_5k * 5) // 3
print(... |
def transmit_order_to_erp(erp_order_process):
# FIXME - submit order to erp
erp_order_process.erp_order_id = '1337'
erp_order_process.save()
def update_campaign_step(campaign_process):
# FIXME get campaign participation for the organisation/person and update to target values
pass
def create_ev... |
#
# _midi_file_event.py
# crest-python
#
# Copyright (C) 2017 Rue Yokaze
# Distributed under the MIT License.
#
class MidiFileEvent(object):
def __init__(self, tick, message):
self.__tick = int(tick)
self.__message = message
def __GetTick(self):
return self.__tick
def __G... |
def sanitize_for_shell(string):
"""
Return `string` with double quotes escaped for use in a Windows shell command.
"""
return string.replace('"', r'\"')
def sanitize_username(name):
"""
This applies only to Windows usernames (logons).
"""
return name.translate(None, r'"/[]:;|=,+*?<>' +... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/1291/A
def f(s):
i = len(s)-1
l = []
while i>=0 and len(l)<2:
if int(s[i])%2==1:
l.append(s[i])
i -= 1
if len(l)<2:
return -1
l.reverse()
return ''.join(l)
t = int(input())
for _ in range(t... |
def convert_textgen_noun_json_to_utg(textgen_data, aninality):
# this code used in migrations, so, it MUSTN'T be changed
properties = {1: 0 if aninality else 1}
if 'мр' in textgen_data['properties']:
properties[3] = 0
if 'ср' in textgen_data['properties']:
properties[3] = 1
if 'ж... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Income, obj[9]: Bar, obj[10]: Coffeehouse, obj[11]: Restaurant20to50, obj[12]: Direction_same, obj[13]: Distance
# {"feature": "Coffeehouse", "instances... |
def binarySearch(array, target):
start = 0
end = len(array) - 1
while start <= end:
midIndex = (end - start) // 2
indexValue = array[midIndex]
if indexValue == target: return midIndex
elif indexValue < target: start = midIndex + 1
else: end = midIndex - 1
print(midIndex, indexValue)
... |
class Tablero:
def __init__(self):
self.vida_nave = None
self.puntos_nave = None
def modifica_vida(self, vida):
self.vida_nave = vida
return self.vida_nave
def modifica_puntos(self, puntos):
self.puntos_nave = puntos
return self.puntos_nave |
# Obratenie vety
# Napíšte funkciu veta_naopak, ktorá berie ako argument vetu a vráti túto vetu s všetkými slovami pospiatky. K tomu si napíšte pomocnú funkciu slovo_odzadu, ktorá berie iba jedno slovo a to vráti pospiatky. (Veľkosť písmen a interpunkciu neriešte.)
# Sample Input:
# veta_naopak('toto je tajná správa'... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module that includes classes and functions used by fuzzers."""
def FillInParameter(parameter, func, template):
"""Replaces occurrences of a paramete... |
def f(n):
if n==0:
return 1
return n-m(f(n-1))
def m(n):
if n==0:
return 0
return n-f(m(n-1)) |
# Mad Libs Story Maker
# Create a Mad Libs style game, where the program asks the user for
# certain types of words, and then prints out a story with the
# words that the user inputted.
# The story doesn't have to be too long, but it should have some sort of story line.
# Subgoals:
# If the user has to put... |
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print(line)
happy_bday = Song(["생일 축하 합니다",
"고소당하기는 싫으니까",
"여기서 이만 할게요"])
bulls_on_parade = Song(["조개 껍질 한가득 차고",
... |
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single q... |
class Config(object):
def __init__(self, db_type, ip, port, db, user, passwd):
"""
:param db_type:
* mysql
* oracle
* postgresql
:param ip:
:param port:
:param db:
:param user:
:param passwd:
"""
self.__db_t... |
def report_status(scheduled_time, estimated_time):
'''(number, number) -> str
Report status of flight(on time, early, delayed)
which has to arrive at scheduled time but now will
arrive at estimated time.
Pre-condition: 0.0 <= scheduled_time < 24 and
0.0 <= estimated_time < 24
>>> report_status(14.0, 14... |
__import__('setuptools').setup(
name="aye",
version="0.0.1",
author="Tony Fast", author_email="tony.fast@gmail.com",
description="Interactive Notebook Modules.",
license="BSD-3-Clause",
setup_requires=['pytest-runner'],
tests_require=['pytest', 'pytest-ipynb'],
install_requires=['ipytho... |
with open("input.txt", "rt") as file:
text = file.read().splitlines()
size = len(text[0])
length = len(text)
ones = [0 for _ in range(size)]
for s in text:
for i, c in enumerate(s):
if c == '1':
ones[i] += 1
gamma = ""
epsilon = ""
for i in ones:
if i > (length/2):
gamma += ... |
# -*- coding: UTF-8 -*-
strings = {
u"P1AA01" : u"La Cabane des Robinson",
u"P1AA02" : u"Indiana Jones and the Temple of Peril",
u"P1AA04" : u"Pirates of the Caribbean",
u"P1DA03" : u"Autopia",
u"P1DA04" : u"Buzz Lightyear Laser Blast",
u"P1DA06" : u"Les Mystères du Nauti... |
{
"id": "",
"name": "",
"symbol": "",
"rank": 0,
"circulating_supply": 0,
"total_supply": 0,
"max_supply": 0,
"last_updated": None,
"market_cap": 0,
"market_cap_change_24h": 0,
"volume": 0,
"ath": 0,
"ath_date": None,
"ath_change_percentage": 0.0,
"percent_cha... |
num = [[], []]
for c in range(1,8):
n = int(input(f'Digite o {c}º numero:'))
if n % 2 == 0:
num[1].append(n)
else:
num[0].append(n)
num[1].sort()
num[0].sort()
print(f'Os valores pares digitados são {num[1]}')
print(f'Os valores impares digitados são {num[0]}')
|
def _carp(*args,skip=1):
"""Warn with no backtrace"""
if TRACEBACK:
print(_longmess(*args, skip=skip), end='', file=sys.stderr)
else:
print(_shortmess(*args, skip=skip), end='', file=sys.stderr)
|
# -*- coding: utf-8 -*-
"""
Dan Scullin
DAT-129
Icon Programming
Goal is to create an icon of my creation, and manipulate it using functions. Rad!
This is a temporary script file.
"""
lists = [['0', '0', '0', '0', '1', '0', '0', '0', '0', '0'],
['0', '0', '0', '0', '1', '0', '0', '0', '0', '0'],
['0', '0', ... |
#
# PySNMP MIB module RADLAN-BONJOUR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADLAN-BONJOUR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:36:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# `!(A || B) || ( (A || C) && !(B || !C) )`
def truthy(a, b, c):
answer = ((not (a or b)) or ((a or c) and not(b or not c)))
return answer
def truthTable():
print( # A B C
truthy(0, 0, 0), # 0 0 0
truthy(0, 0, 1), # 0 0 1
truthy(0, 1, 0), # 0 ... |
"""
Write a program to find the node at which the intersection of two singly linked lists begins.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note tha... |
def solve(arr):
prefix = [0] * len(arr)
for i in range(1, len(arr)):
prefix[i] = arr[i - 1] + prefix[i - 1]
suffix = [0] * len(arr)
for i in range(len(arr) - 2, -1, -1):
suffix[i] = suffix[i + 1] + arr[i + 1]
for i in range(len(arr)):
if suffix[i] == prefix[i]:
... |
class Solution:
def minSwaps(self, data: List[int]) -> int:
countOnes = 0
for num in data:
if num == 1:
countOnes += 1
if countOnes == 0:
return 0
start = 0
countZ = 0
minCount = 99999999
for end, num in en... |
expected_output = {
"cdp": {
"index": {
1: {
"capability": "R",
"device_id": "device2",
"hold_time": 152,
"local_interface": "Ethernet0",
"platform": "AS5200",
"port_id": "Ethernet0",
},
... |
numero = int(input('Digite um número para calcular seu fatorial: '))
fatorial = 1
item = numero
while item > 0:
fatorial = fatorial * item
item += -1
print('O valor da fatorial {}! é {}.'.format(numero, fatorial)) |
Frameworks = [
"MobileWiFi.framework",
"IMTranscoding.framework",
"CarPlaySupport.framework",
"Spotlight.framework",
"TeaCharts.framework",
"SafariCore.framework",
"AppSSOKerberos.framework",
"RemindersUI.framework",
"AirTrafficDevice.framework",
"InertiaCam.framework",
"Conf... |
valores = []
continuar = ''
numeros_digitados = 0
verificador_cinco = 0
while True:
n = int(input('DIGITE UM NUMERO: '))
if n == 5:
verificador_cinco += 1
valores.append(n)
numeros_digitados += 1
print('VALOR ADICIONADO')
continuar = input('QUER CONTINUAR [S] [N] ').upper()
if contin... |
# -*- coding: utf-8 -*-
"""
Transliterating Thai text with ISO 11940
:See Also:
* `Wikipedia \
<https://en.wikipedia.org/wiki/ISO_11940>`_
"""
_consonants = {
"ก": "k",
"ข": "k̄h",
"ฃ": "ḳ̄h",
"ค": "kh",
"ฅ": "k̛h",
"ฆ": "ḳh",
"ง": "ng",
"จ": "c",
"ฉ": "c̄h",
"ช": "c... |
def convert_number(value):
# função que irá converter um número
try:
# 1º tenta converter para um tipo inteiro
value = int(value)
# Se bem sucedido retorna o valor convertido
return value
# se não:
except ValueError:
try:
# 2º tenta converter para tipo... |
listanum = []
maior = 0
men = 0
for c in range(0, 5):
listanum.append(int(input(f'Digite um numero para a posição {c}: ')))
if c== 0:
mai = men = listanum[c]
else:
if listanum[c] > mai:
mai = listanum[c]
if listanum[c] < men:
men = listanum[c]
print('=-' * 30)... |
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... |
def f(x):
x = str(x)
x = list(map(int, x))
return sum(x)
a, b = map(int, input().split())
print(max(f(a), f(b))) |
with open("../inputs/day2.txt","r") as f:
data=f.read()
data=data.split("\n")
data.pop()
while data !=[]:
word1=data.pop()
for word2 in data:
different=0
matching=''
for i in range(word1.__len__()):
if word1[i] != word2[i]:
different+=1
... |
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
temp = []
a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
count = 0
while num and count < 8:
cc = a[num & 0xf]
temp.append(cc)
... |
def split_name(name):
if '.' in name:
return tuple(name.split('.'))
else:
return (name,)
def get_via_name_list(src, name_parts):
"""
Util to get name sequence from a dict. For instance, `("location","query")`
would return src["location"]["query"].
"""
if len(name_parts) > ... |
g=(x*x for x in range(10))
print(list(range(10)))
next(g)
next(g)
for n in g:
print(n)
# 求斐波那契数列
def fib(num):
n,a,b=0,0,1
while n<num:
print(b,end=" ")
a,b=b,a+b
n=n+1
return 'done'
print(fib(6))
# 使用生成器(generator)求斐波那契数列
def fib_g(num):
n,a,b=0,0,1
while n<num:
... |
v = float(input('Qual o comprimento da parede em metro?'))
c = v*100
m = v*1000
print('O comprimento da parede em cm é {} e em mm é {}'.format(c,m))
|
# Welcome.
#
# In this kata you are required to, given a string, replace every letter with its position in the alphabet.
#
# If anything in the text isn't a letter, ignore it and don't return it.
#
# "a" = 1, "b" = 2, etc.
#
# Example
# alphabet_position("The sunset sets at twelve o' clock.")
# Should return "20 8 5 19... |
"""Response data for the GetProductExportUpdate request."""
GET_PRODUCT_EXPORT_UPDATE_RESPONSE = {
"pseudoExports": [
{
"ID": 20217,
"Channel": "All Channels",
"CopyImages": False,
"ProductCount": 2,
"ProductsExported": 0,
"Status": "C... |
class Solution:
# @param {character[][]} board
# @param {string[]} words
# @return {string[]}
def findWords(self, board, words):
trie = {}
for word in words:
t = trie
for c in word:
if c not in t:
t[c] = {}
t = t... |
class Options:
def __init__(self, cfg):
self.cutting_speed = cfg['cutting_speed']
self.travel_speed = cfg['travel_speed']
self.travel_height = cfg['travel_height']
self.first_cutting_height = cfg['first_cutting_height']
self.cutting_layer_size = cfg['cutting_layer_size']
... |
'''
https://leetcode.com/contest/weekly-contest-152/problems/can-make-palindrome-from-substring/
'''
class Solution:
def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
n = len(s)
s = [ord(c) - ord('a') for c in s]
cs = []
for i, c in enumerate(s):
... |
class Solution(object):
def medianSlidingWindow(self, nums, k):
medians, window = [], []
for i in xrange(len(nums)):
# Find position where outgoing element should be removed from
if i >= k:
# window.remove(nums[i-k]) # this works too
... |
def foo(x, y, z):
if x:
return x + 2
elif y:
return y + 2
else:
if z:
return z + 2
else:
return 2
def bar():
a = 1
b = 2
c = 3
if a:
result = a + 2
elif b:
result = b + 2
else:
if c:
result ... |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
res = nums[0]
count = 1
for i in nums[1:]:
if res == i:
count += 1
else:
count -= 1
if count == 0:
res = i
count... |
''' Custom email validation =>
A valid email address meets the following criteria:
It's composed of a username, domain name, and extension assembled in this format: username@domain.extension
The username starts with an English alphabetical character, and any subsequent characters consist of one or more
of ... |
# create variable cars to contain integer 100
cars = 100
# create variable space_in_a_car to contain float 4.0
space_in_a_car = 4.0
# create variable drivers to contain int 30
drivers = 30
# create variable passengers to contain int 90
passengers = 90
# subtract drivers from cars to set int variable cars_not_driven
car... |
SHORT_NAME = 'myscreen'
FULL_NAME = 'My Screen'
default_app_config = 'addons.{}.apps.AddonAppConfig'.format(SHORT_NAME)
|
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class Solution:
def insert(self, head: 'Node', insertVal: int) -> 'Node'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.