content
stringlengths 7
1.05M
|
---|
"""
Faça um programa que leia um numero inteiro positivo ímpar N
e imprima todos os numeros impares de 1 ate N em ordem decrescente.
"""
n = int(input('Digiete um valor positivo impar para iniciar o programa: '))
while n % 2 == 0 or n < 0:
print('Valor invalido.')
n = int(input('Digiete um valor positivo impar para iniciar o programa: '))
for i in range(n, 0, -1):
print(f'{i}', end=' ')
|
#Tipos Primitivos e Saída de Dados#
n1 = int(input('Digite um numero: '))
n2 = int(input('Digite mais um numero: '))
s = n1+n2
print('A soma vale ',s)
#print('A soma vale {}'.format(s))
|
"""Timedelta formatter.
This script allows to format a given timedelta to a specific look.
This file can also be imported as a module and contains the following functions:
* format_timedelta - formats timedelta to hours:minutes:seconds
"""
def format_timedelta(td):
"""Format timedelta to hours:minutes:seconds.
Args:
td (datetime.timedelta): Seconds in timedelta format
Returns:
str: Formatted string
"""
minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
return "{:d}:{:02d}:{:02d}".format(hours, minutes, seconds)
|
def euler():
d = True
x = 1
while d == True:
x += 1
x_1 = str(x)
x_2 = f"{2 * x}"
x_3 = f"{3 * x}"
x_4 = f"{4 * x}"
x_5 = f"{5 * x}"
x_6 = f"{6 * x}"
if len(x_1) != len(x_6):
continue
sez1 = []
sez2 = []
sez3 = []
sez4 = []
sez5 = []
sez6 = []
for t in range(len(x_1)):
sez1.append( x_1[t])
sez2.append(x_2[t])
sez3.append(x_3[t])
sez4.append(x_4[t])
sez5.append(x_5[t])
sez6.append(x_6[t])
sez1.sort()
sez2.sort()
sez3.sort()
sez4.sort()
sez5.sort()
sez6.sort()
if sez1 == sez2 == sez3 == sez4 == sez5 == sez6:
return x
return False
euler()
|
# Given a string s, return the longest palindromic substring in s.
#
# Example 1:
# Input: s = "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# lets first check if s a palindrome
def palindrome(s):
mid = len(s) // 2
if len(s) % 2 != 0:
if s[:mid] == s[:mid:-1]:
return s
else:
if s[:mid] == s[:mid - 1:-1]:
return s
return ""
def longest_palindrome(s):
if palindrome(s) == s:
return s
longest = s[0]
for i in range(0, len(s)):
for j in range(1, len(s)+1):
current = palindrome(s[i:j])
if len(current) > len(longest):
longest = current
return longest
if __name__ == "__main__":
input_string0 = "babad"
input_string1 = "cbbd"
input_string2 = "a"
input_string3 = "ac"
input_string4 = "bb"
print(longest_palindrome(input_string4))
|
def algo(load, plants):
row = 0
produced = 0
names = []
p = []
for i in range(len(plants)):
if row < len(plants):
battery = plants.iloc[row, :]
names.append(battery["name"])
if load > produced:
temp = load - produced
if battery["pmax"] >= temp >= battery["pmin"]:
used = temp
elif battery["pmax"] < temp:
used = battery["pmax"]
elif battery["pmin"] > temp:
used = battery["pmin"]
produced += used
p.append(used)
elif load <= produced:
used = 0
p.append(used)
row += 1
response = dict(zip(names, p))
return response
|
# note the looping - we set the initial value for x =10 and when the first for loop is
# executed, it is evaluated at that time, so changing the variable x in the loop
# does not effect that loop. Now the next time that for loop is executed at that
# time the new value of x is used!
x = 10
for i in range(0,x):
print(i)
x = 5
for i in range(0,x):
print(i)
# another example
x = 5
# outer loop
for i in range (0, x):
# inner loop
for j in range(0, x):
print(i, j)
x = 3 # next time the inner loop is evaluted it will use this value
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 10:05:43 2019
@author: Parikshith.H
"""
L = [10,20,30,40,50]
n = len(L)
print("number of elements =",n)
for i in range(n):
print(L[i])
# =============================================================================
# #output:
# number of elements = 5
# 10
# 20
# 30
# 40
# 50
# =============================================================================
for elem in L:
print(elem)
# =============================================================================
# #output:
# 10
# 20
# 30
# 40
# 50
# =============================================================================
#program to add the contents of two lists and store in another list
A = [10,20,30]
B = [1,2,3]
for i in range(len(A)):
print(A[i] + B[i])
# =============================================================================
# #output:
# 11
# 22
# 33
# =============================================================================
list = [1, 3, 5, 7, 9]
for i, val in enumerate(list):
print (i, ",",val)
# =============================================================================
# #output:
# 0 , 1
# 1 , 3
# 2 , 5
# 3 , 7
# 4 , 9
# =============================================================================
|
# This is a variable concept
'''
a = 10
print(a)
print(type(a))
a = 10.33
print(a)
print(type(a))
a = "New Jersey"
print(a)
print(type(a))
'''
#a = input()
#print(a)
name = input("Please enter your name : ")
print("Your name is ",name)
print(type(name))
number = int(input("Enter your number : ")) #Explicit type conversion
print("Your number is ",number)
print(type(number))
|
def vowels(word):
if (word[0] in 'AEIOU' or word[0] in 'aeiou'):
if (word[len(word) - 1] in 'AEIOU' or word[len(word) - 1] in 'aeiou'):
return 'First and last letter of ' + word + ' is vowel'
else:
return 'First letter of ' + word + ' is vowel'
else:
return 'Not a vowel'
print(vowels('ankara'))
|
"""
Author: Andreas Finkler
Created: 23.12.2020
"""
|
dist = []
for num in range(1, 1000):
if (num % 3 == 0) or (num % 5 == 0):
dist.append(num)
print(sum(dist))
|
seg1 = float(input('Segmento 1: '))
seg2 = float(input('Segmento 2: '))
seg3 = float(input('Segmento 3: '))
if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg1 + seg2:
if seg1 == seg2 == seg3:
print('Este triângulo é um triângulo equilátero!')
elif seg1 == seg2 or seg1 == seg3 or seg2 == seg3:
print('Este triângulo é um triângulo isósceles!')
elif seg1 != seg2 != seg3 != seg1:
print('Este triângulo é um triângulo escaleno!')
else:
print('Os segmentos informados NÃO PODEM forma um triângulo.')
|
add_init_container = [
{
'op': 'add',
'path': '/some/new/path',
'value': 'some-value',
},
]
|
def get_persistent_id(node_unicode_proxy, *args, **kwargs):
return node_unicode_proxy
def get_type(node, *args, **kwargs):
return type(node)
def is_exact_type(node, typename, *args, **kwargs):
return isinstance(node, typename)
def is_type(node, typename, *args, **kwargs):
return typename in ['Transform', 'Curve', 'Joint', 'Shape', 'UnicodeDelegate', 'DagNode']
def rename(node_dag, name, *args, **kwargs):
return name
def duplicate(node_dag, parent_only=True, *args, **kwargs):
return node_dag + '_duplicate'
def list_relatives(node_dag, *args, **kwargs):
return node_dag
def parent(node, new_parent, *args, **kwargs):
return new_parent
def delete(nodes, *args, **kwargs):
del (nodes)
def get_scene_tree():
return {'standalone': None}
def list_scene(object_type='transform', *args, **kwargs):
return []
def list_scene_nodes(object_type='transform', has_shape=False):
return ['standalone']
def exists(node, *args, **kwargs):
return True
def safe_delete(node_or_nodes):
return True
|
age = 20
if age >= 20 and age == 30:
print('age == 30')
elif age >= 20 or age == 30:
print(' age >= 20 or age == 30')
else:
print('...')
|
"""Default configuration settings"""
DEBUG = True
TESTING = False
# Logging
LOGGER_NAME = 'api-server'
LOG_FILENAME = 'api-server.log'
# PostgreSQL
USE_POSTGRESQL = True
POSTGRESQL_DATABASE = 'my_resume'
POSTGRESQL_USER = 'learn'
POSTGRESQL_PASSWORD = 'pass.word'
POSTGRESQL_HOST = 'localhost'
POSTGRESQL_PORT = '5432'
|
# coding: utf-8
userdetails = {'nickname': 'Glycos Shadow',
'password': 'pokem9nb2',
'avatar': '119'}
rooms = ['botdevelopment'] # Add rooms here
devs = ['pokem9n'] # Keep the usernames in id format, users here can access all commands.
server = 'sim3.psim.us' # Socket Address of the server you're trying to connect to. By default the bot expects it to support secure connections
comchar = ['+','.'] # List of command characters separated by commas.
ranks = " +%@★*#&~"
|
class Solution(object):
def lastStoneWeight(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
#helper function
def remove_largest():
#locate the index of the element with max value
heaviest_1_idx = stones.index(max(stones))
#swap the highest value element with the last element
stones[heaviest_1_idx], stones[-1] = stones[-1], stones[heaviest_1_idx]
#pop the element at the last index
return stones.pop()
#special case handler
#list is empty
if not stones:
return 0
#list has only 1 element
elif len(stones) == 1:
return stones[0]
else:
#loop as long as list has no more than 1 element
while len(stones) > 1:
#pop the heaviest element in the list
heaviest_1 = remove_largest()
#pop the heaviest element in the list
heaviest_2 = remove_largest()
#if the weights of two heaviest elements are not the same
if heaviest_1 - heaviest_2 != 0:
#append the new element into the list after the different weight is subtract
stones.append(heaviest_1 - heaviest_2)
#return the only element in the list if the list is not empty; otherwise, return 0
return stones[0] if stones else 0
|
def namta(p=1):
for i in range(1, 11):
print(p, "x", i, "=", p*i)
namta(5)
namta()
|
num_waves = 2
num_eqn = 2
# Conserved quantities
pressure = 0
velocity = 1
|
#Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos
#dígitos separados.
num = str(input("Digite um número de 0 a 9999: "))
print('Analisando o número!')
x = 0
tam = len(num)
while(x<tam):
print("O {}° número é: {}".format(x+1,num[x]))
x+=1
|
# Defining our main object of interation
game = [[0,0,0],
[0,0,0],
[0,0,0]]
#printing a column index, printing a row index, now #we have a coordinate to make a move, like c2
def game_board(player=0, row=1, column=1, just_display=False):
print(' 1 2 3')
if not just_display:
game[row][column] = player
for count, row in enumerate(game, 1):
print(count, row)
game_board(just_display=True)
game_board(player=1, row=2, column=1)
# game[0][1] = 1
# game_board()
|
def function_2(x):
return x[0]**2 + x[1]**2
def numerical_diff(f, x):
h = 1e-4
return (f(x+h) - f(x-h)) / (2*h)
def function_tmp1(x0):
return x0*x0 + 4.0**2
def function_tmp2(x1):
return 3.0**2.0 + x1*x1
print(numerical_diff(function_tmp1, 3.0))
print(numerical_diff(function_tmp2, 4.0))
|
def preencherinventario(lista):
resp = 'S'
while resp == 'S':
equipamento = [input('Equipamento: '),
float(input('Valor? ')),
int(input('Digite o sérial: ')),
input('Departamento: ')]
lista.append(equipamento)
resp = input('Digite "S" para inserir mais itens, e enter para finalizar: ').upper()
def exibirinventario(lista):
for elemento in lista:
print(f'Nome..........:{elemento[0]}')
print(f'Valor.........:{elemento[1]}')
print(f'serial........:{elemento[2]}')
print(f'Departamento..:{elemento[3]}')
def localizarpornome(lista):
busca = input('Digite o nome do equipamento que deseja buscar: ')
for elemento in lista:
if busca == elemento[0]:
print(f'Valor..:{elemento[1]}')
print(f'Serial..{elemento[2]}')
def depreciarpornome(lista, porc):
depreciacao = input('Digite o nome do equipamento que deseja depreciar: ')
for elemento in lista:
if depreciacao == elemento[0]:
print(f'Valor antigo: {elemento[1]}')
elemento[1] = elemento[1] * (1 - porc / 100)
print(f'Novo valor: {elemento[1]}')
def excluirporserial(lista):
serial = int(input('Digite o serial do equipamento que será excluido:'))
for elemento in lista:
if elemento[2] == serial:
lista.remove(elemento)
return 'Itens Excluídos. '
def resumivalores(lista):
valores = []
for elemento in lista:
valores.append(elemento[1])
if len(valores) > 0:
print(f'O equipamento mais caro custa: R${max(valores)}')
print(f'O equipamento mais barato custa: R${min(valores)}')
print(f'valor totalé de : R${sum(valores)}')
|
"""
>>> motor = Motor()
>>> motor.acelerar()
>>> motor.velocidade
1
"""
# TODO: ajustar o doctest
class Carro:
def __init__(self, motor, direcao):
self.motor = motor
self.direcao = direcao
def calcular_velocidade(self):
return self.motor.velocidade
def acelerar(self):
self.motor.acelerar()
def frear(self):
self.motor.frear()
def calcular_direcao(self):
return self.direcao.valor
def girar_a_direita(self):
return self.direcao.girar_a_direita()
def girar_a_esquerda(self):
return self.direcao.girar_a_esquerda()
class Motor:
def __init__(self, velocidade=0):
self.velocidade = velocidade
def acelerar(self):
self.velocidade += 1
def frear(self):
if self.velocidade >= 2:
self.velocidade -= 2
else:
self.velocidade = 0
NORTE = 'Norte'
SUL = 'Sul'
LESTE = 'Leste'
OESTE = 'Oeste'
class Direcao:
rotacao_direita_dct = {NORTE: LESTE, LESTE: SUL, SUL: OESTE, OESTE: NORTE}
rotacao_esquerda_dct = {NORTE: OESTE, LESTE: NORTE, SUL: LESTE, OESTE: SUL}
def __init__(self, valor=NORTE):
self.valor = valor
def girar_a_direita(self):
self.valor = self.rotacao_direita_dct[self]
def girar_a_esquerda(self):
self.valor = self.rotacao_esquerda_dct[self]
|
JOBS_RAW = {
0: {
"Name": "Farmer"
},
1: {
"Name": "Baker"
},
2: {
"Name": "Lumberjack"
},
3: {
"Name": "Carpenter"
}
}
|
class ApiException(Exception):
"""
Generic Catch-all for API Exceptions.
"""
status_code = None
def __init__(self, status_code=None, msg=None, *args, **kwargs):
self.status_code = status_code
super(ApiException, self).__init__(msg, *args, **kwargs)
|
class AutowiringError(Exception):
"""
Error indicating autowiring of a function failed.
"""
...
|
def work(x):
x = x.split("cat ") #"cat " is a delimiter for the whole command dividing the line on two parts
f = open(x[1], "r") #the second part is a filename or path (in the future)
print(f.read()) #outputs the content of the specified file
|
#calculodeSalario
salario= int(input('Digite o valor do seu salário : '))
if salario < 1250:
salario = salario *1.15
print ('Seu novo sálario passa a ser de R${:.2f}'.format(salario))
else:
salario > 1250
salario =salario *1.10
print('Seu novo salário passa a ser de R${:.2f}'.format(salario))
|
def un_avg_pool(name, l_input, k, images_placeholder, test_images):
"""
the input is an 5-D array: batch_size length width height channels
"""
input_shape = l_input.get_shape().as_list()
batch_size = input_shape[0]
length = input_shape[1]
width = input_shape[2]
height = input_shape[3]
channels = input_shape[4]
output_shape = [batch_size,k*length,2*width,2*height,channels]
sess.run(tf.global_variables_initializer())
input_array = np.zeros(input_shape,dtype = np.float32)
output_array = np.zeros(output_shape,dtype = np.float32)
input_array = l_input.eval(session = sess,feed_dict={images_placeholder:test_images})
#input_array = np.array(l_input.as_list())
for n in range(batch_size):
for l in range(k*length):
for w in range(2*width):
for h in range(2*height):
for c in range(channels):
output_array[n,l,w,h,c] = input_array[n,int(l/k),int(w/2),int(h/2),c]
output = tf.convert_to_tensor(output_array)
return output
def un_max_pool(name, l_input, l_output, k, images_placeholder, test_images):
'''
parameters:
l_input is the input of pool
l_output is the output of pool
according to input,we can get the max index
according to output and max_index, unpool and reconstruct the input
return:
the reconstructed input
'''
input_shape = l_input.get_shape().as_list()
output_shape = l_output.get_shape().as_list()
batch_size = output_shape[0]
length = output_shape[1]
rows = output_shape[2]
cols = output_shape[3]
channels = output_shape[4]
input_array = l_input.eval(session = sess,feed_dict={images_placeholder:test_images})
output_array = l_output.eval(session = sess,feed_dict = {images_placeholder:test_images})
unpool_array = np.zeros(input_shape,dtype = np.float32)
for n in range(batch_size):
for l in range(length):
for r in range(rows):
for c in range(cols):
for ch in range(channels):
l_in, r_in, c_in = k*l, 2*r, 2*c
sub_square = input_array[ n, l_in:l_in+k, r_in:r_in+2, c_in:c_in+2, ch ]
max_pos_l, max_pos_r, max_pos_c = np.unravel_index(np.nanargmax(sub_square), (k, 2, 2))
array_pixel = output_array[ n, l, r, c, ch ]
unpool_array[n, l_in + max_pos_l, r_in + max_pos_r, c_in + max_pos_c, ch] = array_pixel
unpool = tf.convert_to_tensor(unpool_array)
return unpool
def un_max_pool_approximate(name,l_input,output_shape,k):
# out = tf.concat([l_input,tf.zeros_like(l_input)], 4) #concat along the channel axis
# out = tf.concat([out,tf.zeros_like(out)], 3) #concat along the no.-2 axis
# if k == 2:
# out = tf.concat([out,tf.zeros_like(out)], 2) #concat along the no.-3 axis
# out = tf.reshape(out,output_shape)
out = tf.concat([l_input,l_input], 4) #concat along the channel axis
out = tf.concat([out,out], 3) #concat along the no.-2 axis
if k == 2:
out = tf.concat([out,out], 2) #concat along the no.-3 axis
out = tf.reshape(out,output_shape)
return out
|
num = int(input('Enter a number:'))
count = 0
while num != 0:
num //= 10
count += 1
print("Total digits are: ", count)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Answer(object):
def __init__(self, p_id, username, datetime_from, content):
self.p_id = p_id
self.username = username
self.datetime_from = datetime_from
self.content = content
"""docstring for Answer"""
# def __init__(self, arg):
# super(Answer, self).__init__()
# self.arg = arg
|
class MetodoDeNewton(object):
def __init__(self, f, f_derivada, x0, precisao=0.001, max_interacoes=15):
self.__X = [x0]
self.__interacoes = 0
while self.interacoes < max_interacoes:
self.__X.append(self.X[-1] - f(self.X[-1]) / f_derivada(self.X[-1]))
self.__interacoes += 1
if abs(self.X[-2] - self.X[-1]) <= precisao:
break
@property
def X(self):
return self.__X
@property
def x(self):
return self.__X[-1]
@property
def interacoes(self):
return self.__interacoes
|
S = input()
t = ''.join(c if c in 'ACGT' else ' ' for c in S)
print(max(map(len, t.split(' '))))
|
# Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que
# conterão apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três
# listas geradas.
list = []
odd = []
pair = []
while True:
num = int(input('Digite um número: '))
cont = str(input('Deseja continuar [S/N]: '))
if num in list:
print('Valor duplicado! Não vou adicionar...')
else:
list.append(num)
print('Valor adicionado com sucesso!!')
# Principal situation: Pair or odd
if num % 2 == 0:
pair.append(num)
else:
odd.append(num)
if cont in 'Nn':
break
print('=*'*30)
print(f'Sua lista é {list}')
print(f'Os valores pares digitados foram: {pair}'if pair.count(num % 2 == 0) > 1
else f'O valor par digitado foi: {pair}')
print(f'E os valores ímpares digitados foram: {odd}'if odd.count(num % 2 == 1) > 1
else f'E o valor ímpar digitado foi: {odd} ')
print('=*'*30)
|
"""
Helper functions for both simulator and solver.
"""
__author__ = "Z Feng"
def pattern_to_similarity(pattern: str) -> int:
"""
Convert a pattern of string consisting of '0', '1' and '2' to a similarity rating.
'2': right letter in right place
'1': right letter in wrong place
'0': wrong letter
:param pattern: string of pattern
:return: similarity
"""
return int(pattern[::-1], 3)
def similarity_to_pattern(similarity: int) -> str:
"""
Inverse of pattern_to_similarity for 5 digit in base 3.
:param similarity: str
:return: pattern
"""
pattern = ''
for i in range(5):
pattern += str(similarity % (3 ** (i + 1)) // 3 ** i)
return pattern
def gen_similarity_LUT(legal_guesses: list = None, potential_answers: list = None) -> dict:
"""
Generate the lookup table (LUT) of similarities for any guess and answer in the dictionary.
LUT returned as a nested dictionary: lut[guess][target] == similarity.
:param legal_guesses: list of legal guesses
:param potential_answers: list of potential answers
:return: LUT nested dictionary
"""
if legal_guesses is None:
legal_guesses = get_guess_dictionary()
if potential_answers is None:
potential_answers = get_answer_dictionary()
lut = {guess: {answer: compare(guess, answer) for answer in potential_answers} for guess in legal_guesses}
return lut
def compare(guess: str, target: str, lut: dict = None) -> int:
"""
Compare a guess string to a target string. Return the similarity as an integer in the range of [0, 3^N-1], where
N is the length of both guess and target strings.
"""
assert len(guess) == len(target)
if not lut is None:
if guess in lut:
if target in lut[guess]:
return lut[guess][target]
N = len(guess)
similarity = 0
used_target = [False for i in range(N)]
used_guess = [False for i in range(N)]
for i in range(N):
if guess[i] == target[i]:
similarity += 2 * 3 ** i
used_target[i] = True
used_guess[i] = True
for i in range(N):
if used_guess[i]:
continue
for j in range(N):
if not used_target[j] and guess[i] == target[j]:
similarity += 3 ** i
used_target[j] = True
break
assert 0 <= similarity < 3 ** N
return similarity
def get_guess_dictionary() -> list:
with open('words_wordle.txt', 'r') as f:
dictionary = f.readlines()
for i in range(len(dictionary)):
# print(len(word))
assert len(dictionary[i]) == 6
dictionary[i] = dictionary[i][:5]
return dictionary
def get_answer_dictionary() -> list:
with open('words_wordle_solutions.txt', 'r') as f:
dictionary = f.readlines()
for i in range(len(dictionary)):
# print(len(word))
assert len(dictionary[i]) == 6
dictionary[i] = dictionary[i][:5]
return dictionary
if __name__ == "__main__":
guess = 'speed'
target = 'crepe'
similarity = compare(guess, target)
print(similarity)
print(similarity_to_pattern(similarity))
#EOF
|
# Criar um programa onde o usuário irá escrever uma expressão qualquer que use parênteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
expressao = input('Digite a expressão: ')
lista = []
for elementos in expressao:
if elementos =='(':
lista.append('(')
elif elementos == ')':
if len(lista) > 0:
lista.pop()
else:
lista.append(')')
break
if len(lista) == 0:
print('Sua expressão está valida!')
else:
print('Sua expressão está invalida!')
|
# coding=utf-8
def point_inside(p, bounds):
return bounds[3] <= p[0] <= bounds[1] and bounds[0] <= p[1] <= bounds[2]
|
#Python Operators
x = 9
y = 3
#Arithmetic operators
print(x+y) #Addition
print(x-y) #Subtraction
print(x*y) #Multiplication
print(x/y) #Division
print(x%y) #Modulus
print(x**y) #Exponentiation
x = 9.191823
print(x//y) #Floor division
#Assignment operators
x = 9
x += 3
print(x)
x = 9
x -= 3
print(x)
x *= 3
print(x)
x /= 3
print(x)
x **= 3
print(x)
#Comparison operators
x = 9
y = 3
print(x==y) #True if x equals y, False otherwise
print(x != y) #True if x does not equal y, False otherwise
print(x > y) #True if x is greater than y, False otherwise
print(x < y) #True if x is less than y, False otherwise
print(x >= y) #True if x is greater than or equal to y, False otherwise
print(x <= y) #True if x is less than or equal to y, False otherwise
|
test = {
'name': 'lab1_p1a',
'suites': [
{
'cases': [
{
'code': r"""
>>> # It looks like your variable is not named correctly.
>>> # Remember, we want to save the value of pi as a variable.
>>> # What type should the variable be?
>>> # Start the variable name with pi_
>>> 'pi_flt' in vars()
True
"""
},
{
'code': r"""
>>> # The variable name is good but the value is off.
>>> # Seems like a typo.
>>> pi_flt == 3.1416
True
"""
}
]
}
]
}
|
"""This problem was asked by Google.
You're given a string consisting solely of (, ), and *. * can represent either a (, ), or an empty string.
Determine whether the parentheses are balanced.
For example, (()* and (*) are balanced. )*( is not balanced.
"""
|
# 2020.04.27
# https://leetcode.com/problems/add-two-numbers/submissions/
# works
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# Part 1: turn the linked lists into listspart
# get values into list:
list1 = []
list1.append(l1.val)
mask = l1
while mask.next:
if mask.next:
list1.append(mask.next.val)
if mask.next.next:
mask = mask.next
else:
break
print(list1)
# get values into list:
list2 = []
list2.append(l2.val)
mask = l2
while mask.next:
if mask.next:
list2.append(mask.next.val)
if mask.next.next:
mask = mask.next
else:
break
print(list2)
# part 2: reverse the numbers
l1 = list1
l2 = list2
# convert list 1
l1 = l1[::-1] # reverse the order
strL = ""
l1 = int("".join(map(str, l1))) # convert to a single number
print(l1)
# convert list 2
l2 = l2[::-1] # reverse the order
strL = ""
l2 = int("".join(map(str, l2))) # convert to a single number
print(l2)
# add and make a new backwards list
# add list 1 and list 2
l3 = l1 + l2 # add the numbers
l3 = list(str(l3)) # convert to list of digits (string form)
l3 = list(map(int, l3)) # convert to a list of digits
l3 = l3[::-1] # reverse the order
print(l3)
# turn back into a linked list
# swap names
list3 = l3
# start the linked list
l3 = ListNode(list3[0])
# remove first item
list3.pop(0)
mask = l3
for i in list3: # now one digit shorter
mask.next = ListNode(i) # create node for each item in list
# print(mask.next.val)
mask = mask.next
print(l3.val)
print(l3.next.val)
print(l3.next.next.val)
return l3
xx = Solution()
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
xx.addTwoNumbers(l1, l2)
|
KNOWN_PATHS = [
"/etc/systemd/*",
"/etc/systemd/**/*",
"/lib/systemd/*",
"/lib/systemd/**/*",
"/run/systemd/*",
"/run/systemd/**/*",
"/usr/lib/systemd/*",
"/usr/lib/systemd/**/*",
]
KNOWN_DROPIN_PATHS = {
"user.conf": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
"system.conf": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".service": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".target": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".mount": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".automount": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".device": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".swap": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".path": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".timer": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".scope": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".slice": [
"/etc/systemd/system/%unit%.d/*.conf", "/run/systemd/system/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".network": [
"/etc/systemd/network/%unit%.d/*.conf", "/run/systemd/network/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
".netdev": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
"timesyncd.conf": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
"journald.conf": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
"journal-upload.conf": [
"/etc/systemd/%unit%.d/*.conf", "/run/systemd/%unit%.d/*.conf", "/usr/lib/systemd/%unit%.d/*.conf", "/lib/systemd/%unit%.d/*.conf"
],
}
|
"""Top-level package for NewlineCharacterConv."""
__author__ = """NewlineCharacterConv"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
# -*- coding: UTF-8 -*-
"""
@Project :Random_Choose_Play
@File :config.py
@Author :ChengXiaozhao
@Date :2021/7/27 下午8:38
@Desc :
"""
ALL_TASKS = {
"学习": {
"看书": ["《计算机系统》", "《C++ Primer》", "《机器学习》"],
"看课程视频": ["李宏毅-强化学习课程", "机器学习课程", "Web前端开发"],
},
"娱乐": {
"逛B站": ["欣赏舞蹈视频", "看音乐视频", "看搞笑视频"],
"逛知乎": ["知乎推荐页-随机刷", "知乎热榜", "整理知乎收藏夹", "知乎搜索开心内容"],
},
"放松": {
"闭目养神": ["躺着休息", "靠着休息"],
"远眺": ["轻声哼歌", "发呆瞎想"]
}
}
TASK_LINK = {
"看课程视频": "https://www.icourse163.org/",
"李宏毅-强化学习课程":
"https://www.bilibili.com/video/BV1UE411G78S?from=search&seid=14424175449318245082&spm_id_from=333.337.0.0",
"机器学习课程": "https://www.bilibili.com/video/BV18D4y127f1",
"Web前端开发":
"https://www.icourse163.org/learn/BFU-1003382003?tid=1461899443#/learn/content?type=detail&id=1238840217&cid"
"=1259664510 ",
"逛B站": "https://www.bilibili.com/?spm_id_from=333.788.b_696e7465726e6174696f6e616c486561646572.1",
"欣赏舞蹈视频": "https://www.bilibili.com/video/BV1Uo4y1k77b",
"看音乐视频": "https://www.bilibili.com/video/BV1HJ411F7cB",
"看搞笑视频": "https://www.bilibili.com/video/BV1za411w7ui",
"逛知乎": "https://www.zhihu.com/hot",
"知乎推荐页-随机刷": "https://www.zhihu.com/",
"知乎热榜": "https://www.zhihu.com/hot",
"整理知乎收藏夹": "https://www.zhihu.com/people/cheng-xiao-zhao-24/collections",
"知乎搜索开心内容": "https://www.zhihu.com/search?type=content&q=%E6%90%9E%E7%AC%91"
}
# 第一级范围的内容文案
grade_1_text = {"学习": "学习吧,少年", "娱乐": "emmm...玩会儿吧", "放松": "休息一下咯"}
|
# Created by MechAviv
# ID :: [101000010]
# Ellinia : Magic Library
sm.warp(101000000, 4)
|
class scrimp(object):
DOWNLOAD_START = "Give Me Some Time..."
UPLOAD_START = "Starting to upload..."
AFTER_SUCCESSFUL_UPLOAD_MSG = "**Thank you for Using Me > © @KitaxRobot **"
SAVED_RECVD_DOC_FILE = "File Downloaded Successfully 😎"
CUSTOM_CAPTION_UL_FILE = " "
|
def format_change_kind(kind):
return {
('new'): '已上架',
('notice'): '可预定',
}[kind]
|
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle = rectangle
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.row1, self.col1, self.row2, self.col2, self.newValue = row1, col1, row2, col2, newValue
for i in range(self.row1, self.row2 + 1) :
for j in range(self.col1, self.col2 + 1):
self.rectangle[i][j] = self.newValue
def getValue(self, row: int, col: int) -> int:
self.row = row
self.col = col
return self.rectangle[self.row][self.col]
# Your SubrectangleQueries object will be instantiated and called as such:
# obj = SubrectangleQueries(rectangle)
# obj.updateSubrectangle(row1,col1,row2,col2,newValue)
# param_2 = obj.getValue(row,col)
|
#UTF-8
salario = int(input('Digite seu salário: '))
idade = int(input('Digite sua idade: '))
imposto = 'você deve pagar os impostos'if salario >= 1200 and idade >= 20 else 'você não paga os impostos'
print(f'resultado {imposto}')
|
# 2nd Solution
i = 4
d = 4.0
s = 'HackerRank '
a = int(input())
b = float(input())
c = input()
print(i+a)
print(d+b)
print(s+c)
|
{
'includes': [
'common.gyp',
'amo.gypi',
],
'targets': [
{
'target_name': 'amo',
'product_name': 'amo',
'type': 'none',
'sources': [
'<@(source_code_amo)',
],
'dependencies': [
]
},
]
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MATH6005 Lecture 6. Functions Revision.
# =============================================================================
# Example: Scope of a variable
#
# The code below attempts to double the value of the 'my_salary' variable
# but FAILS. This is because within double_value() the argument 'to_double'
# is called a 'local variable' with 'local scope'. Changes to 'to_double'
# only happen within the function. You can think of to_double as a copy
# of my_salary when it is passed in.
# =============================================================================
"""
def double_value(to_double):
print('double_value() has been called')
to_double = to_double * 2
print('Inside double_value() to_double now = {}'.format(to_double))
def main():
my_salary = 25000
print('value of my_salary BEFORE calling function {}'.format(my_salary))
#call the function and pass in keyword argument
double_value(to_double=my_salary)
print('value of my_salary AFTER calling function {}'.format(my_salary))
if __name__ == '__main__':
main()
|
def imprime_quadro(numeros):
print('.' * (len(numeros) + 2))
maior_numero = max(numeros)
numeros_traduzidos = []
for numero in numeros:
numeros_traduzidos.append(['|' if n < numero else ' ' for n in range(maior_numero)][::-1])
for linha in zip(*numeros_traduzidos):
print('.' + ''.join(linha) + '.')
print('.' * (len(numeros) + 2))
def bubble_sort(numeros):
while numeros != sorted(numeros):
for index in range(len(numeros) - 1):
if numeros[index] > numeros[index + 1]:
numeros[index], numeros[index + 1] = numeros[index + 1], numeros[index]
imprime_quadro(numeros)
def selection_sort(numeros):
index = 0
while numeros != sorted(numeros):
menor_numero = min(numeros[index:])
index_menor_numero = numeros[index:].index(menor_numero) + index
if numeros[index] > menor_numero:
numeros[index], numeros[index_menor_numero] = menor_numero, numeros[index]
index += 1
imprime_quadro(numeros)
def insertion_sort(numeros):
index_main = 1
while numeros != sorted(numeros):
index = index_main
while index > 0 and numeros[index] < numeros[index - 1]:
numeros[index], numeros[index - 1] = numeros[index - 1], numeros[index]
index -= 1
index_main += 1
imprime_quadro(numeros)
algoritmos = {'bubble':bubble_sort, 'selection':selection_sort, 'insertion':insertion_sort}
algoritmo_escolhido = input()
numeros = [int(n) for n in input().split()]
imprime_quadro(numeros)
algoritmos[algoritmo_escolhido](numeros)
|
### Task 5.6
#Implement a Pagination class helpful to arrange text on pages and list content on given page.
#The class should take in a text and a positive integer which indicate how many symbols will be allowed per each page (take spaces into account as well).
#You need to be able to get the amount of whole symbols in text, get a number of pages that came out and method that accepts the page number and return quantity of symbols on this page.
#If the provided page’s number is missing print the warning message "Invalid index. Page is missing". If you're familiar with Exceptions using in Python display the error message in this way.
#Pages indexing starts with 0.
#Example:
#```python
#>>> pages = Pagination('Your beautiful text', 5)
#>>> pages.page_count
#4
#>>> pages.item_count
#19
#>>> pages.count_items_on_page(0)
#5
#>>> pages.count_items_on_page(3)
#4
#>>> pages.count_items_on_page(4)
#Exception: Invalid index. Page is missing.
#```
#Optional: implement querying pages by symbols/words and displaying pages with all the symbols on it.
#If you're querying by symbol that appears on many pages or if your are querying by the word that is divided in two return an array of all the occurrences.
#Example:
#```python
#>>> pages.find_page('Your')
#[0]
#>>> pages.find_page('e')
#[1, 3]
#>>> pages.find_page('beautiful')
#[1, 2]
#>>> pages.find_page('great')
#Exception: 'Great' is missing on the pages
#>>> pages.display_page(0)
#'Your '
#>>> pages.count\_items\_on_page(4)
#Exception: Invalid index. Page is missing.
#```
class Paginator:
def __init__(self, content, page_sz):
self.page_sz = page_sz if page_sz > 0 else 0
self.content = content
self.__split_content()
def get_sz_content(self):
return len(self.content)
def __split_content(self):
self.pages = []
page_all_sz = self.get_sz_content()
begin = 0
if not self.page_sz:
self.pages.append((begin, page_all_sz - 1))
else:
while page_all_sz > 0:
cur_page_sz = min(self.page_sz, page_all_sz)
cur_page_end = begin + cur_page_sz
self.pages.append((begin, cur_page_end))
begin = cur_page_end
page_all_sz -= cur_page_sz
def get_pages_cnt(self):
return len(self.pages)
def __if_page_exists(self, page_num):
if page_num >= self.get_pages_cnt():
raise Exception('Invalid index. Page is missing.')
def count_items_on_page(self, page_num):
self.__if_page_exists(page_num)
page = self.pages[page_num]
return page[1] - page[0]
def display_page(self, page_num):
self.__if_page_exists(page_num)
page = self.pages[page_num]
begin, end = page[0], page[1]
return self.content[begin:end]
def find_page(self, text):
res_pages = []
for i, page in enumerate(self.pages):
begin, end = page[0], page[1]
if text in self.content[begin:end]:
res_pages.append(i)
return res_pages
if __name__=='__main__':
txt = '''Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt,
explicabo. nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur
magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia
dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et
dolore magnam aliquam quaerat voluptatem. ut enim ad minima veniam, quis nostrum exercitationem ullam corporis
suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? quis autem vel eum iure reprehenderit, qui in
ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur?'''
p = Paginator(txt, 50)
print(p.pages)
print('Pages count:', p.get_pages_cnt())
print(p.count_items_on_page(0))
print(p.display_page(0))
print(p.find_page('ut'))
#[0, 27, 28, 52, 57, 67, 71]
print(p.display_page(15))
|
"""
This function converts given hexadecimal number to decimal number
"""
def hexa_decimal_to_decimal(number: str) -> int:
# check if the number is a hexa decimal number
if not is_hexa_decimal(number):
raise ValueError("Invalid Hexa Decimal Number")
# convert hexa decimal number to decimal
decimal = 0
for i in range(len(number)):
decimal += int(number[i], 16) * (16 ** (len(number) - i - 1))
return decimal
def is_hexa_decimal(number: str) -> bool:
# check if the number is a hexa decimal number
if len(number) == 0:
return False
for i in range(len(number)):
if number[i] not in "0123456789ABCDEF":
return False
return True
|
#
a, b = 10, 10
print(a == b)
print(a is b)
print(id(a), id(b))
a1 = [1, 2, 3, 4]
b1 = [1, 2, 3, 4]
print(a1 == b1)
print(a1 is b1)
print(id(a1), id(b1))
|
print ("Moi je m\'appelle \'Lolita\'")
print ("Lo ou bien Lola, du pareil au même")
print ("je m\'appelle \'lolita\'")
print ("Quand je rêve aux loups, c\'est Lola qui saigne")
print ("[...]")
print ("C\'est pas ma faute")
print ("Et quand je donne ma langues aux chats je vois les autres ")
print ("Tout prêts à se jeter sur moi, c\'est pas ma faute à moi")
print ("Si j\'entends tout autour de moi'")
print ("L.O.L.I.T.A, moi \'Lolita\'")
|
total = 0
media = 0.0
for i in range(6):
num = float(input())
if num > 0.0:
total += 1
media += num
print('{} valores positivos'.format(total))
print('{:.1f}'.format(media/total))
|
"""This file contains a function that returns the int that apears an odd number of times in a list of integers, the best practice solution was:
def find_it(seq):
for i in seq:
if seq.count(i)%2!=0:
return i
"""
def find_it(seq):
"""This function returns the integer that is in the list an odd number of times"""
for i in seq:
y = seq.count(i)
if y % 2 != 0:
return i
break
#6kyu
|
# http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/JIS0201.TXT
JIS0201_map = {
'20' : 0x0020, # SPACE
'21' : 0x0021, # EXCLAMATION MARK
'22' : 0x0022, # QUOTATION MARK
'23' : 0x0023, # NUMBER SIGN
'24' : 0x0024, # DOLLAR SIGN
'25' : 0x0025, # PERCENT SIGN
'26' : 0x0026, # AMPERSAND
'27' : 0x0027, # APOSTROPHE
'28' : 0x0028, # LEFT PARENTHESIS
'29' : 0x0029, # RIGHT PARENTHESIS
'2A' : 0x002A, # ASTERISK
'2B' : 0x002B, # PLUS SIGN
'2C' : 0x002C, # COMMA
'2D' : 0x002D, # HYPHEN-MINUS
'2E' : 0x002E, # FULL STOP
'2F' : 0x002F, # SOLIDUS
'30' : 0x0030, # DIGIT ZERO
'31' : 0x0031, # DIGIT ONE
'32' : 0x0032, # DIGIT TWO
'33' : 0x0033, # DIGIT THREE
'34' : 0x0034, # DIGIT FOUR
'35' : 0x0035, # DIGIT FIVE
'36' : 0x0036, # DIGIT SIX
'37' : 0x0037, # DIGIT SEVEN
'38' : 0x0038, # DIGIT EIGHT
'39' : 0x0039, # DIGIT NINE
'3A' : 0x003A, # COLON
'3B' : 0x003B, # SEMICOLON
'3C' : 0x003C, # LESS-THAN SIGN
'3D' : 0x003D, # EQUALS SIGN
'3E' : 0x003E, # GREATER-THAN SIGN
'3F' : 0x003F, # QUESTION MARK
'40' : 0x0040, # COMMERCIAL AT
'41' : 0x0041, # LATIN CAPITAL LETTER A
'42' : 0x0042, # LATIN CAPITAL LETTER B
'43' : 0x0043, # LATIN CAPITAL LETTER C
'44' : 0x0044, # LATIN CAPITAL LETTER D
'45' : 0x0045, # LATIN CAPITAL LETTER E
'46' : 0x0046, # LATIN CAPITAL LETTER F
'47' : 0x0047, # LATIN CAPITAL LETTER G
'48' : 0x0048, # LATIN CAPITAL LETTER H
'49' : 0x0049, # LATIN CAPITAL LETTER I
'4A' : 0x004A, # LATIN CAPITAL LETTER J
'4B' : 0x004B, # LATIN CAPITAL LETTER K
'4C' : 0x004C, # LATIN CAPITAL LETTER L
'4D' : 0x004D, # LATIN CAPITAL LETTER M
'4E' : 0x004E, # LATIN CAPITAL LETTER N
'4F' : 0x004F, # LATIN CAPITAL LETTER O
'50' : 0x0050, # LATIN CAPITAL LETTER P
'51' : 0x0051, # LATIN CAPITAL LETTER Q
'52' : 0x0052, # LATIN CAPITAL LETTER R
'53' : 0x0053, # LATIN CAPITAL LETTER S
'54' : 0x0054, # LATIN CAPITAL LETTER T
'55' : 0x0055, # LATIN CAPITAL LETTER U
'56' : 0x0056, # LATIN CAPITAL LETTER V
'57' : 0x0057, # LATIN CAPITAL LETTER W
'58' : 0x0058, # LATIN CAPITAL LETTER X
'59' : 0x0059, # LATIN CAPITAL LETTER Y
'5A' : 0x005A, # LATIN CAPITAL LETTER Z
'5B' : 0x005B, # LEFT SQUARE BRACKET
'5C' : 0x00A5, # YEN SIGN
'5D' : 0x005D, # RIGHT SQUARE BRACKET
'5E' : 0x005E, # CIRCUMFLEX ACCENT
'5F' : 0x005F, # LOW LINE
'60' : 0x0060, # GRAVE ACCENT
'61' : 0x0061, # LATIN SMALL LETTER A
'62' : 0x0062, # LATIN SMALL LETTER B
'63' : 0x0063, # LATIN SMALL LETTER C
'64' : 0x0064, # LATIN SMALL LETTER D
'65' : 0x0065, # LATIN SMALL LETTER E
'66' : 0x0066, # LATIN SMALL LETTER F
'67' : 0x0067, # LATIN SMALL LETTER G
'68' : 0x0068, # LATIN SMALL LETTER H
'69' : 0x0069, # LATIN SMALL LETTER I
'6A' : 0x006A, # LATIN SMALL LETTER J
'6B' : 0x006B, # LATIN SMALL LETTER K
'6C' : 0x006C, # LATIN SMALL LETTER L
'6D' : 0x006D, # LATIN SMALL LETTER M
'6E' : 0x006E, # LATIN SMALL LETTER N
'6F' : 0x006F, # LATIN SMALL LETTER O
'70' : 0x0070, # LATIN SMALL LETTER P
'71' : 0x0071, # LATIN SMALL LETTER Q
'72' : 0x0072, # LATIN SMALL LETTER R
'73' : 0x0073, # LATIN SMALL LETTER S
'74' : 0x0074, # LATIN SMALL LETTER T
'75' : 0x0075, # LATIN SMALL LETTER U
'76' : 0x0076, # LATIN SMALL LETTER V
'77' : 0x0077, # LATIN SMALL LETTER W
'78' : 0x0078, # LATIN SMALL LETTER X
'79' : 0x0079, # LATIN SMALL LETTER Y
'7A' : 0x007A, # LATIN SMALL LETTER Z
'7B' : 0x007B, # LEFT CURLY BRACKET
'7C' : 0x007C, # VERTICAL LINE
'7D' : 0x007D, # RIGHT CURLY BRACKET
'7E' : 0x203E, # OVERLINE
'A1' : 0xFF61, # HALFWIDTH IDEOGRAPHIC FULL STOP
'A2' : 0xFF62, # HALFWIDTH LEFT CORNER BRACKET
'A3' : 0xFF63, # HALFWIDTH RIGHT CORNER BRACKET
'A4' : 0xFF64, # HALFWIDTH IDEOGRAPHIC COMMA
'A5' : 0xFF65, # HALFWIDTH KATAKANA MIDDLE DOT
'A6' : 0xFF66, # HALFWIDTH KATAKANA LETTER WO
'A7' : 0xFF67, # HALFWIDTH KATAKANA LETTER SMALL A
'A8' : 0xFF68, # HALFWIDTH KATAKANA LETTER SMALL I
'A9' : 0xFF69, # HALFWIDTH KATAKANA LETTER SMALL U
'AA' : 0xFF6A, # HALFWIDTH KATAKANA LETTER SMALL E
'AB' : 0xFF6B, # HALFWIDTH KATAKANA LETTER SMALL O
'AC' : 0xFF6C, # HALFWIDTH KATAKANA LETTER SMALL YA
'AD' : 0xFF6D, # HALFWIDTH KATAKANA LETTER SMALL YU
'AE' : 0xFF6E, # HALFWIDTH KATAKANA LETTER SMALL YO
'AF' : 0xFF6F, # HALFWIDTH KATAKANA LETTER SMALL TU
'B0' : 0xFF70, # HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK
'B1' : 0xFF71, # HALFWIDTH KATAKANA LETTER A
'B2' : 0xFF72, # HALFWIDTH KATAKANA LETTER I
'B3' : 0xFF73, # HALFWIDTH KATAKANA LETTER U
'B4' : 0xFF74, # HALFWIDTH KATAKANA LETTER E
'B5' : 0xFF75, # HALFWIDTH KATAKANA LETTER O
'B6' : 0xFF76, # HALFWIDTH KATAKANA LETTER KA
'B7' : 0xFF77, # HALFWIDTH KATAKANA LETTER KI
'B8' : 0xFF78, # HALFWIDTH KATAKANA LETTER KU
'B9' : 0xFF79, # HALFWIDTH KATAKANA LETTER KE
'BA' : 0xFF7A, # HALFWIDTH KATAKANA LETTER KO
'BB' : 0xFF7B, # HALFWIDTH KATAKANA LETTER SA
'BC' : 0xFF7C, # HALFWIDTH KATAKANA LETTER SI
'BD' : 0xFF7D, # HALFWIDTH KATAKANA LETTER SU
'BE' : 0xFF7E, # HALFWIDTH KATAKANA LETTER SE
'BF' : 0xFF7F, # HALFWIDTH KATAKANA LETTER SO
'C0' : 0xFF80, # HALFWIDTH KATAKANA LETTER TA
'C1' : 0xFF81, # HALFWIDTH KATAKANA LETTER TI
'C2' : 0xFF82, # HALFWIDTH KATAKANA LETTER TU
'C3' : 0xFF83, # HALFWIDTH KATAKANA LETTER TE
'C4' : 0xFF84, # HALFWIDTH KATAKANA LETTER TO
'C5' : 0xFF85, # HALFWIDTH KATAKANA LETTER NA
'C6' : 0xFF86, # HALFWIDTH KATAKANA LETTER NI
'C7' : 0xFF87, # HALFWIDTH KATAKANA LETTER NU
'C8' : 0xFF88, # HALFWIDTH KATAKANA LETTER NE
'C9' : 0xFF89, # HALFWIDTH KATAKANA LETTER NO
'CA' : 0xFF8A, # HALFWIDTH KATAKANA LETTER HA
'CB' : 0xFF8B, # HALFWIDTH KATAKANA LETTER HI
'CC' : 0xFF8C, # HALFWIDTH KATAKANA LETTER HU
'CD' : 0xFF8D, # HALFWIDTH KATAKANA LETTER HE
'CE' : 0xFF8E, # HALFWIDTH KATAKANA LETTER HO
'CF' : 0xFF8F, # HALFWIDTH KATAKANA LETTER MA
'D0' : 0xFF90, # HALFWIDTH KATAKANA LETTER MI
'D1' : 0xFF91, # HALFWIDTH KATAKANA LETTER MU
'D2' : 0xFF92, # HALFWIDTH KATAKANA LETTER ME
'D3' : 0xFF93, # HALFWIDTH KATAKANA LETTER MO
'D4' : 0xFF94, # HALFWIDTH KATAKANA LETTER YA
'D5' : 0xFF95, # HALFWIDTH KATAKANA LETTER YU
'D6' : 0xFF96, # HALFWIDTH KATAKANA LETTER YO
'D7' : 0xFF97, # HALFWIDTH KATAKANA LETTER RA
'D8' : 0xFF98, # HALFWIDTH KATAKANA LETTER RI
'D9' : 0xFF99, # HALFWIDTH KATAKANA LETTER RU
'DA' : 0xFF9A, # HALFWIDTH KATAKANA LETTER RE
'DB' : 0xFF9B, # HALFWIDTH KATAKANA LETTER RO
'DC' : 0xFF9C, # HALFWIDTH KATAKANA LETTER WA
'DD' : 0xFF9D, # HALFWIDTH KATAKANA LETTER N
'DE' : 0xFF9E, # HALFWIDTH KATAKANA VOICED SOUND MARK
'DF' : 0xFF9F, # HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK
}
|
#it is collection of data and methods.
class gohul:
a=100
b=200
def func(self):
print("Inside function")
print(gohul.func(1))
object=gohul()
print(object.a)
print(object.b)
print(object.func())
object1=gohul()
print(object1.a)
|
# Description: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。
# 如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
#
# 你可以假设数组中无重复元素。
#
# Examples: 输入: [1,3,5,6], 5, 输出: 2
# 输入: [1,3,5,6], 2, 输出: 1
# 输入: [1,3,5,6], 7, 输出: 4
# 输入: [1,3,5,6], 0, 输出: 0
#
# Difficulty: Simple
# Author: zlchen
# Date: 4/30/2019
# Performance: 56 ms, surpass 61.69%'s python3 submissions
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
try:
index = nums.index(target)
except:
nums.append(target)
index = sorted(nums).index(target)
return index
|
# Array
# An array is monotonic if it is either monotone increasing or monotone decreasing.
#
# An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
#
# Return true if and only if the given array A is monotonic.
#
#
#
# Example 1:
#
# Input: [1,2,2,3]
# Output: true
# Example 2:
#
# Input: [6,5,4,4]
# Output: true
# Example 3:
#
# Input: [1,3,2]
# Output: false
# Example 4:
#
# Input: [1,2,4,5]
# Output: true
# Example 5:
#
# Input: [1,1,1]
# Output: true
#
#
# Note:
#
# 1 <= A.length <= 50000
# -100000 <= A[i] <= 100000
class Solution:
def isMonotonic(self, A):
"""
:type A: List[int]
:rtype: bool
"""
if A[0] < A[-1]:
isIncrease = True
else:
isIncrease = False
if isIncrease:
for i in range(1,len(A)):
if A[i] < A[i-1]:
return False
else:
for i in range(1,len(A)):
if A[i] > A[i-1]:
return False
return True
|
class Solution:
"""
@param matrix: an integer matrix
@return: the length of the longest increasing path
"""
def longestIncreasingPath(self, matrix):
if not matrix or len(matrix) == 0 or len(matrix[0]) == 0:
return 0
n = len(matrix)
m = len(matrix[0])
longest = 0
memory = {}
for i in range(n):
for j in range(m):
longest = max(longest, self.dfs(matrix, n, m, i, j, True, memory))
longest = max(longest, self.dfs(matrix, n, m, i, j, False, memory))
return longest
def dfs(self, matrix, n, m, i, j, ascending, memory):
memKey = str(i) + "_" + str(j) + "_" + str(ascending)
if memKey in memory:
return memory[memKey]
longest = 0
for adj in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
x = i + adj[0]
y = j + adj[1]
if x < 0 or x >= n or y < 0 or y >= m:
continue
if ascending and matrix[x][y] <= matrix[i][j]:
continue
if not ascending and matrix[x][y] >= matrix[i][j]:
continue
longest = max(longest, self.dfs(matrix, n, m, x, y, ascending, memory))
memory[memKey] = longest + 1
return memory[memKey]
|
# -*- coding: utf-8 -*-
"""Top-level package for NeuroVault Collection Downloader."""
__author__ = """Chris Gorgolewski"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
class LandingPage:
@staticmethod
def get():
return 'Beautiful UI'
|
class Peptide:
def __init__(self, sequence, proteinID, modification, mass, isNterm):
self.sequence = sequence
self.length = len(self.sequence)
self.proteinID = [proteinID]
self.modification = modification
self.massArray = self.getMassArray(mass)
self.totalResidueMass = self.getTotalResidueMass()
self.pm = self.getPrecursorMass(mass)
self.isNterm = isNterm
def getMassArray(self, mass):
massArray = []
sequence = self.sequence
position = self.modification['position']
deltaMass = self.modification['deltaMass']
for i in range(self.length):
massArray.append(mass[sequence[i].upper()])
for i in range(len(position)):
massArray[position[i]] += deltaMass[i]
return massArray
def getTotalResidueMass(self):
totalResidueMass = sum(self.massArray)
return totalResidueMass
def getPrecursorMass(self, mass):
pm = self.totalResidueMass
pm = pm + mass['Hatom'] * 2 + mass['Oatom']
return pm
def getMassList(self, mass, param):
massList = []
fwdMass = 0
massArray = self.massArray
totalResidueMass = self.totalResidueMass
useAIon = param['useAIon']
for i in range(self.length - 1):
fragment = dict()
fwdMass += massArray[i]
revMass = totalResidueMass - fwdMass
fragment['b'] = fwdMass + mass['BIonRes']
fragment['y'] = revMass + mass['YIonRes']
if useAIon:
fragment['a'] = fwdMass + mass['AIonRes']
massList.append(fragment)
return massList
|
def fatorial(n):
if n==1:
return n
return fatorial(n-1) * n
print(fatorial(5))
"""n = 5 --> ret = 1*2*3*4*5
n = 4 --> fatorial(4) = 1*2*3*4
n = 3 --> fatorial(3) = 1*2*3
n = 2 --> fatorial(2) = 1*2
n = 1 --> fatorial(1) = 1"""
print(fatorial(4))
|
#CMPUT 410 Lab1 by Chongyang Ye
#This program allows add courses and
#corresponding marks for a student
#and count the average score
class Student:
courseMarks={}
name= ""
def __init__(self,name,family):
self.name = name
self.family = family
def addCourseMark(self, course, mark):
self.courseMarks[course] = mark
def average(self):
grade= []
grade= self.courseMarks.values()
averageGrade= sum(grade)/float(len(grade))
print("The course average for %s is %.2f" %(self.name, averageGrade))
if __name__ == "__main__":
student = Student("Jeff", "Hub")
student.addCourseMark("CMPUT410", 90)
student.addCourseMark("CMPUT379", 95)
student.addCourseMark("CMPUT466", 80)
student.average()
|
def super_reduced_string(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/reduced-string/problem
Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest
length by doing a series of operations. In each operation he selects a pair of adjacent lowercase letters that
match, and he deletes them. For instance, the string aab could be shortened to b in one operation.
Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the
final string is empty, print Empty String
Args:
s (str): String to reduce
Returns:
str: the reduced string, or "Empty String" if it's empty
"""
cur_string = s
while True:
found = False
for i in range(1, len(cur_string)):
if cur_string[i-1] == cur_string[i]:
found = True
cur_string = cur_string.replace(cur_string[i]*2, "", 1)
break
if not found:
break
if not cur_string:
cur_string = "Empty String"
return cur_string
if __name__ == "__main__":
assert super_reduced_string("aaabccddd") == "abd"
assert super_reduced_string("baab") == "Empty String"
|
{
"targets": [{
"target_name": "defaults",
"sources": [ ],
"conditions": [
['OS=="mac"', {
"sources": [
"src/defaults.mm",
"src/json_formatter.h",
"src/json_formatter.cc"
],
}]
],
'include_dirs': [
"<!@(node -p \"require('node-addon-api').include\")"
],
'libraries': [],
'dependencies': [
"<!(node -p \"require('node-addon-api').gyp\")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
"xcode_settings": {
"OTHER_CPLUSPLUSFLAGS": ["-std=c++17", "-stdlib=libc++", "-Wextra"],
"OTHER_LDFLAGS": ["-framework CoreFoundation -framework Cocoa -framework Carbon"],
"MACOSX_DEPLOYMENT_TARGET": "10.12"
}
}]
}
|
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
register_rule("agents/" + _("Agent Plugins"),
"agent_config:nvidia_gpu",
DropdownChoice(
title = _("Nvidia GPU (Linux)"),
help = _("This will deploy the agent plugin <tt>nvidia_gpu</tt> to collect GPU utilization values."),
choices = [
( True, _("Deploy plugin for GPU Monitoring") ),
( None, _("Do not deploy plugin for GPU Monitoring") ),
]
)
)
|
# -*- coding: utf-8 -*-
"""
Taken from Data Structures and Algorithms using Python
"""
def matrix_chain(d):
n = len(d) - 1
N =[[0]*n for i in range(n)]
for b in range(1,n):
for i in range(n-b):
j = i+b
N[i][j] = min(N[i][j]+N[k+1][j]+d[i]*d[k+1]*d[j+1] for k in range(i,j))
return N
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 :data_constant.py
@说明 :
@时间 :2020/07/30 15:36:45
@作者 :Riven
@版本 :1.0.0
'''
DATA_DB_PATH = '/app_server/data/data_base.db'
ACCOUNT_DB_TABLE_NAME = 'account_table'
ACCOUNT_DB_TABLE_KEYS = ['phone', 'password', 'name', 'token']
|
#Nicolas Andrade de Freitas - Turma 2190
#Exercicio 10
km = float(input("Digite um velocidade em km/h: "))
ms = km / 3.6
print("{}KM/H são {:.2f} M/S".format(km, ms))
|
#!/usr/bin/env python
types = [
("bool", "Bool", "strconv.FormatBool(bool(*%s))", "*%s == false"),
("uint8", "Uint8", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("uint16", "Uint16", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("uint32", "Uint32", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("uint64", "Uint64", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("int8", "Int8", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"),
("int16", "Int16", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"),
("int32", "Int32", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"),
("int64", "Int64", "strconv.FormatInt(int64(*%s), 10)", "*%s == 0"),
("float32", "Float32", "strconv.FormatFloat(float64(*%s), 'g', -1, 32)", "*%s == 0.0"),
("float64", "Float64", "strconv.FormatFloat(float64(*%s), 'g', -1, 64)", "*%s == 0.0"),
("string", "String", "string(*%s)", "*%s == \"\""),
("int", "Int", "strconv.Itoa(int(*%s))", "*%s == 0"),
("uint", "Uint", "strconv.FormatUint(uint64(*%s), 10)", "*%s == 0"),
("time.Duration", "Duration", "(*time.Duration)(%s).String()", "*%s == 0"),
# TODO: Func
]
imports = [
"time"
]
imports_stringer = [
"strconv"
]
|
"""# `//ll:driver.bzl`
Convenience function to select the C or C++ driver for compilation.
"""
def compiler_driver(ctx, toolchain_type):
driver = ctx.toolchains[toolchain_type].c_driver
for src in ctx.files.srcs:
if src.extension in ["cpp", "hpp", "ipp", "cl", "cc"]:
driver = ctx.toolchains[toolchain_type].cpp_driver
break
return driver
|
#!/usr/bin/env python
counts = dict()
mails = list()
fname = input("Enter file name:")
fh = open(fname)
for line in fh:
if not line.startswith("From "):
continue
# if line.startswith('From:'):
# continue
id = line.split()
mail = id[1]
mails.append(mail)
freq_mail = max(mails, key=mails.count) # To find frequent mail
print(freq_mail, mails.count(freq_mail)) # To find countof frequent mail
"""
for x in mails:
counts[x]=counts.get(x,0)+1
bigmail=None
bigvalue=None
for key,value in counts.items():
if bigvalue==None or bigvalue<value:
bigmail=key
bigvalue=value
print(bigmail, bigvalue)
"""
|
class OriginEPG():
def __init__(self, fhdhr):
self.fhdhr = fhdhr
def update_epg(self, fhdhr_channels):
programguide = {}
for fhdhr_id in list(fhdhr_channels.list.keys()):
chan_obj = fhdhr_channels.list[fhdhr_id]
if str(chan_obj.number) not in list(programguide.keys()):
programguide[str(chan_obj.number)] = chan_obj.epgdict
return programguide
|
class TrieNode:
def __init__(self):
self.children = {}
self.endOfString = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
currNode = self.root
for char in word:
if char not in currNode.children:
currNode.children[char] = TrieNode()
currNode = currNode.children[char]
currNode.endOfString = True
def search(self, word):
currNode = self.root
replace = ""
for char in word:
if char not in currNode.children:
return word
replace += char
currNode = currNode.children[char]
if currNode.endOfString == True:
return replace
return word
class Solution:
def replaceWords(self, dictionary: list[str], sentence: str) -> str:
trie = Trie()
wordsList = sentence.split()
for rootWord in dictionary:
trie.insert(rootWord)
processed_wordList = []
for word in wordsList:
processed_wordList.append(trie.search(word))
return " ".join(processed_wordList)
|
def get_capabilities():
return [
"bogus_capability"
]
def should_ignore_response():
return True
|
#Desenvolva um programa que leia o primeiro termo de uma PA. No final mostre os 10 primeiros termos dessa progressão.
p = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão: '))
d = p + (10 - 1) * r
for c in range(p, d + r, r):
print('{}'. format(c), end= ' -> ')
print('ACABOU')
|
class ExportModuleToFile(object):
def __init__(self, **kargs):
self.moduleId = kargs["moduleId"] if "moduleId" in kargs else None
self.exportType = kargs["exportType"] if "exportType" in kargs else None
|
años = int(input())
planet = str(input())
planetas = dict([('Mercury', 88), ('Venus', 225), ('Earth', 365), (
'Mars', 687), ('Jupiter', 4333), ('Saturn', 10759), ('Uranus', 30689), ('Neptune', 60182)])
print(años*planetas[planet]//365)
|
class Preprocessor:
def __init__(self, title):
self.title = title
def evaluate(self, value):
return value
|
s=input()
li=list(map(int,s.split(' ')))
while(li!=sorted(li)):
n=(len(li)//2)
for i in range(n):
li.pop()
print(li)
|
#!/usr/bin/env python3
#Take a list, say for example this one: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.
#Extras:
#Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
#Write this in one line of Python.
#Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.
#list = input("Input few numbers (comma separated): ").split(",")
list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
num = int(input("Enter a number for comparison: "))
print ("numbers less than %d are: " %num)
print([element for element in list if element < num])
#2. new_list = []
#for element in list:
# if int(element) < 5:
# new_list.append(element)
#print (new_list)
|
# Прикуп + Выигрышные номера тиража + предыдущий тираж к примеру 58570
def test_prikup_winning_draw_numbers_for_previous_draw(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_prikup()
app.ResultAndPrizes.click_winning_draw_numbers()
app.ResultAndPrizes.select_draw_58570_in_draw_numbers()
app.ResultAndPrizes.click_ok_in_winning_draw_numbers_modal_window()
app.ResultAndPrizes.button_get_report_winners()
app.ResultAndPrizes.parser_report_text_winners()
assert "ВЫИГРЫШНЫЕ НОМЕРА" in app.ResultAndPrizes.parser_report_text_winners()
assert "ПРИКУП - Тираж 58570 :" in app.ResultAndPrizes.parser_report_text_winners()
assert "15/06/2018, 18:10:00 ЛОК" in app.ResultAndPrizes.parser_report_text_winners()
assert "35 21 20 01 23 32 41 49 27 07 48 08 09 24 10" in app.ResultAndPrizes.parser_report_text_winners()
app.ResultAndPrizes.comeback_main_page()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 11:53:23 2020
@author: chris
"""
__version__ = "0.3.2"
__status__ = "Alpha"
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 01:38:54 2020
@author: abhi0
"""
class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
tempLight=sorted(light)
cnt=0
sum1=0
sum2=0
for i in range(len(light)):
sum1=sum1+light[i]
sum2=sum2+tempLight[i]
if sum1==sum2:
cnt+=1
return cnt
|
#! /usr/bin/python3
# p76
print("Let's preatice everything.")
print("You\'d need to know \'about escapes with \\ that do \n newlines and \t tabs.")
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("--------------")
print(poem)
print("--------------")
five = 10 - 2 + 3 - 6
print("This should be five:%s" % five)
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print("With a starting point of:%d" % start_point)
print("We'd have %d beans, %d jars, and %d crates." % (beans,jars,crates))
start_point = start_point / 10
print("We can alse do that this way:")
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
|
FI_MUNICIPALITIES = [
'Alajärvi',
'Alavieska',
'Alavus',
'Asikkala',
'Askola',
'Aura',
'Akaa',
'Brändö',
'Eckerö',
'Enonkoski',
'Enontekiö',
'Espoo',
'Eura',
'Eurajoki',
'Evijärvi',
'Finström',
'Forssa',
'Föglö',
'Geta',
'Haapajärvi',
'Haapavesi',
'Hailuoto',
'Halsua',
'Hamina',
'Hammarland',
'Hankasalmi',
'Hanko',
'Harjavalta',
'Hartola',
'Hattula',
'Hausjärvi',
'Heinävesi',
'Helsinki',
'Vantaa',
'Hirvensalmi',
'Hollola',
'Huittinen',
'Humppila',
'Hyrynsalmi',
'Hyvinkää',
'Hämeenkyrö',
'Hämeenlinna',
'Heinola',
'Ii',
'Iisalmi',
'Iitti',
'Ikaalinen',
'Ilmajoki',
'Ilomantsi',
'Inari',
'Inkoo',
'Isojoki',
'Isokyrö',
'Imatra',
'Janakkala',
'Joensuu',
'Jokioinen',
'Jomala',
'Joroinen',
'Joutsa',
'Juuka',
'Juupajoki',
'Juva',
'Jyväskylä',
'Jämijärvi',
'Jämsä',
'Järvenpää',
'Kaarina',
'Kaavi',
'Kajaani',
'Kalajoki',
'Kangasala',
'Kangasniemi',
'Kankaanpää',
'Kannonkoski',
'Kannus',
'Karijoki',
'Karkkila',
'Karstula',
'Karvia',
'Kaskinen',
'Kauhajoki',
'Kauhava',
'Kauniainen',
'Kaustinen',
'Keitele',
'Kemi',
'Keminmaa',
'Kempele',
'Kerava',
'Keuruu',
'Kihniö',
'Kinnula',
'Kirkkonummi',
'Kitee',
'Kittilä',
'Kiuruvesi',
'Kivijärvi',
'Kokemäki',
'Kokkola',
'Kolari',
'Konnevesi',
'Kontiolahti',
'Korsnäs',
'Koski Tl',
'Kotka',
'Kouvola',
'Kristiinankaupunki',
'Kruunupyy',
'Kuhmo',
'Kuhmoinen',
'Kumlinge',
'Kuopio',
'Kuortane',
'Kurikka',
'Kustavi',
'Kuusamo',
'Outokumpu',
'Kyyjärvi',
'Kärkölä',
'Kärsämäki',
'Kökar',
'Kemijärvi',
'Kemiönsaari',
'Lahti',
'Laihia',
'Laitila',
'Lapinlahti',
'Lappajärvi',
'Lappeenranta',
'Lapinjärvi',
'Lapua',
'Laukaa',
'Lemi',
'Lemland',
'Lempäälä',
'Leppävirta',
'Lestijärvi',
'Lieksa',
'Lieto',
'Liminka',
'Liperi',
'Loimaa',
'Loppi',
'Loviisa',
'Luhanka',
'Lumijoki',
'Lumparland',
'Luoto',
'Luumäki',
'Lohja',
'Parainen',
'Maalahti',
'Maarianhamina',
'Marttila',
'Masku',
'Merijärvi',
'Merikarvia',
'Miehikkälä',
'Mikkeli',
'Muhos',
'Multia',
'Muonio',
'Mustasaari',
'Muurame',
'Mynämäki',
'Myrskylä',
'Mäntsälä',
'Mäntyharju',
'Mänttä-Vilppula',
'Naantali',
'Nakkila',
'Nivala',
'Nokia',
'Nousiainen',
'Nurmes',
'Nurmijärvi',
'Närpiö',
'Orimattila',
'Oripää',
'Orivesi',
'Oulainen',
'Oulu',
'Padasjoki',
'Paimio',
'Paltamo',
'Parikkala',
'Parkano',
'Pelkosenniemi',
'Perho',
'Pertunmaa',
'Petäjävesi',
'Pieksämäki',
'Pielavesi',
'Pietarsaari',
'Pedersören kunta',
'Pihtipudas',
'Pirkkala',
'Polvijärvi',
'Pomarkku',
'Pori',
'Pornainen',
'Posio',
'Pudasjärvi',
'Pukkila',
'Punkalaidun',
'Puolanka',
'Puumala',
'Pyhtää',
'Pyhäjoki',
'Pyhäjärvi',
'Pyhäntä',
'Pyhäranta',
'Pälkäne',
'Pöytyä',
'Porvoo',
'Raahe',
'Raisio',
'Rantasalmi',
'Ranua',
'Rauma',
'Rautalampi',
'Rautavaara',
'Rautjärvi',
'Reisjärvi',
'Riihimäki',
'Ristijärvi',
'Rovaniemi',
'Ruokolahti',
'Ruovesi',
'Rusko',
'Rääkkylä',
'Raasepori',
'Saarijärvi',
'Salla',
'Salo',
'Saltvik',
'Sauvo',
'Savitaipale',
'Savonlinna',
'Savukoski',
'Seinäjoki',
'Sievi',
'Siikainen',
'Siikajoki',
'Siilinjärvi',
'Simo',
'Sipoo',
'Siuntio',
'Sodankylä',
'Soini',
'Somero',
'Sonkajärvi',
'Sotkamo',
'Sottunga',
'Sulkava',
'Sund',
'Suomussalmi',
'Suonenjoki',
'Sysmä',
'Säkylä',
'Vaala',
'Sastamala',
'Siikalatva',
'Taipalsaari',
'Taivalkoski',
'Taivassalo',
'Tammela',
'Tampere',
'Tervo',
'Tervola',
'Teuva',
'Tohmajärvi',
'Toholampi',
'Toivakka',
'Tornio',
'Turku',
'Pello',
'Tuusniemi',
'Tuusula',
'Tyrnävä',
'Ulvila',
'Urjala',
'Utajärvi',
'Utsjoki',
'Uurainen',
'Uusikaarlepyy',
'Uusikaupunki',
'Vaasa',
'Valkeakoski',
'Varkaus',
'Vehmaa',
'Vesanto',
'Vesilahti',
'Veteli',
'Vieremä',
'Vihti',
'Viitasaari',
'Vimpeli',
'Virolahti',
'Virrat',
'Vårdö',
'Vöyri',
'Ylitornio',
'Ylivieska',
'Ylöjärvi',
'Ypäjä',
'Ähtäri',
'Äänekoski',
]
SV_MUNICIPALITIES = [
'Alajärvi',
'Alavieska',
'Alavo',
'Asikkala',
'Askola',
'Aura',
'Akas',
'Brändö',
'Eckerö',
'Enonkoski',
'Enontekis',
'Esbo',
'Eura',
'Euraåminne',
'Evijärvi',
'Finström',
'Forssa',
'Föglö',
'Geta',
'Haapajärvi',
'Haapavesi',
'Karlö',
'Halso',
'Fredrikshamn',
'Hammarland',
'Hankasalmi',
'Hangö',
'Harjavalta',
'Gustav Adolfs',
'Hattula',
'Hausjärvi',
'Heinävesi',
'Helsingfors',
'Vanda',
'Hirvensalmi',
'Hollola',
'Vittis',
'Humppila',
'Hyrynsalmi',
'Hyvinge',
'Tavastkyro',
'Tavastehus',
'Heinola',
'Ijo',
'Idensalmi',
'Itis',
'Ikalis',
'Ilmola',
'Ilomants',
'Enare',
'Ingå',
'Storå',
'Storkyro',
'Imatra',
'Janakkala',
'Joensuu',
'Jockis',
'Jomala',
'Jorois',
'Joutsa',
'Juga',
'Juupajoki',
'Juva',
'Jyväskylä',
'Jämijärvi',
'Jämsä',
'Träskända',
'S:t Karins',
'Kaavi',
'Kajana',
'Kalajoki',
'Kangasala',
'Kangasniemi',
'Kankaanpää',
'Kannonkoski',
'Kannus',
'Bötom',
'Högfors',
'Karstula',
'Karvia',
'Kaskö',
'Kauhajoki',
'Kauhava',
'Grankulla',
'Kaustby',
'Keitele',
'Kemi',
'Keminmaa',
'Kempele',
'Kervo',
'Keuru',
'Kihniö',
'Kinnula',
'Kyrkslätt',
'Kides',
'Kittilä',
'Kiuruvesi',
'Kivijärvi',
'Kumo',
'Karleby',
'Kolari',
'Konnevesi',
'Kontiolax',
'Korsnäs',
'Koskis',
'Kotka',
'Kouvola',
'Kristinestad',
'Kronoby',
'Kuhmo',
'Kuhmois',
'Kumlinge',
'Kuopio',
'Kuortane',
'Kurikka',
'Gustavs',
'Kuusamo',
'Outokumpu',
'Kyyjärvi',
'Kärkölä',
'Kärsämäki',
'Kökar',
'Kemijärvi',
'Kimitoön',
'Lahtis',
'Laihela',
'Letala',
'Lapinlahti',
'Lappajärvi',
'Villmanstrand',
'Lappträsk',
'Lappo',
'Laukas',
'Lemi',
'Lemland',
'Lempäälä',
'Leppävirta',
'Lestijärvi',
'Lieksa',
'Lundo',
'Limingo',
'Libelits',
'Loimaa',
'Loppi',
'Lovisa',
'Luhanka',
'Lumijoki',
'Lumparland',
'Larsmo',
'Luumäki',
'Lojo',
'Pargas',
'Malax',
'Mariehamn',
'S:t Mårtens',
'Masku',
'Merijärvi',
'Sastmola',
'Miehikkälä',
'S:t Michel',
'Muhos',
'Multia',
'Muonio',
'Korsholm',
'Muurame',
'Virmo',
'Mörskom',
'Mäntsälä',
'Mäntyharju',
'Mänttä-Vilppula',
'Nådendal',
'Nakkila',
'Nivala',
'Nokia',
'Nousis',
'Nurmes',
'Nurmijärvi',
'Närpes',
'Orimattila',
'Oripää',
'Orivesi',
'Oulainen',
'Uleåborg',
'Padasjoki',
'Pemar',
'Paltamo',
'Parikkala',
'Parkano',
'Pelkosenniemi',
'Perho',
'Pertunmaa',
'Petäjävesi',
'Pieksämäki',
'Pielavesi',
'Jakobstad',
'Pedersöre',
'Pihtipudas',
'Birkala',
'Polvijärvi',
'Påmark',
'Björneborg',
'Borgnäs',
'Posio',
'Pudasjärvi',
'Pukkila',
'Punkalaidun',
'Puolanka',
'Puumala',
'Pyttis',
'Pyhäjoki',
'Pyhäjärvi',
'Pyhäntä',
'Pyhäranta',
'Pälkäne',
'Pöytyä',
'Borgå',
'Brahestad',
'Reso',
'Rantasalmi',
'Ranua',
'Raumo',
'Rautalampi',
'Rautavaara',
'Rautjärvi',
'Reisjärvi',
'Riihimäki',
'Ristijärvi',
'Rovaniemi',
'Ruokolax',
'Ruovesi',
'Rusko',
'Rääkkylä',
'Raseborg',
'Saarijärvi',
'Salla',
'Salo',
'Saltvik',
'Sagu',
'Savitaipale',
'Nyslott',
'Savukoski',
'Seinäjoki',
'Sievi',
'Siikais',
'Siikajoki',
'Siilinjärvi',
'Simo',
'Sibbo',
'Sjundeå',
'Sodankylä',
'Soini',
'Somero',
'Sonkajärvi',
'Sotkamo',
'Sottunga',
'Sulkava',
'Sund',
'Suomussalmi',
'Suonenjoki',
'Sysmä',
'Säkylä',
'Vaala',
'Sastamala',
'Siikalatva',
'Taipalsaari',
'Taivalkoski',
'Tövsala',
'Tammela',
'Tammerfors',
'Tervo',
'Tervola',
'Östermark',
'Tohmajärvi',
'Toholampi',
'Toivakka',
'Torneå',
'Åbo',
'Pello',
'Tuusniemi',
'Tusby',
'Tyrnävä',
'Ulvsby',
'Urjala',
'Utajärvi',
'Utsjoki',
'Uurainen',
'Nykarleby',
'Nystad',
'Vasa',
'Valkeakoski',
'Varkaus',
'Vemo',
'Vesanto',
'Vesilahti',
'Vetil',
'Vieremä',
'Vichtis',
'Viitasaari',
'Vindala',
'Vederlax',
'Virdois',
'Vårdö',
'Vörå',
'Övertorneå',
'Ylivieska',
'Ylöjärvi',
'Ypäjä',
'Etseri',
'Äänekoski',
]
|
# Given a date, return the corresponding day of the week for that date.
# The input is given as three integers representing the day, month and year respectively.
# Return the answer as one of the following values
# {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.
# Example 1:
# Input: day = 31, month = 8, year = 2019
# Output: "Saturday"
# Example 2:
# Input: day = 18, month = 7, year = 1999
# Output: "Sunday"
# Example 3:
# Input: day = 15, month = 8, year = 1993
# Output: "Sunday"
# Constraints:
# The given dates are valid dates between the years 1971 and 2100.
# Hints:
# Sum up the number of days for the years before the given year.
# Handle the case of a leap year.
# Find the number of days for each month of the given year.
class Solution(object):
def dayOfTheWeek(self, day, month, year):
"""
:type day: int
:type month: int
:type year: int
:rtype: str
"""
# 从最初开始累计到今日 查表返回
week = [0, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
# 注意形参同名问题,大坑
months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
y, m, d, w = 1971, 1, 1, 5
while y != year or m != month or d != day:
d += 1
w += 1
if w > 7:
w = 1
flag = False
if y % 4 == 0 and y % 100 != 0 or y % 400 == 0:
flag = True
if flag and m == 2:
if d > 29:
m += 1
d = 1
else:
if d > months[m]:
m += 1
d = 1
if m > 12:
m = 1
y += 1
return week[w]
|
#
# Example file for working with loops
#
def main():
x = 0
# define a while loop
while (x<5):
print(x)
x+=1
# define a for loop
for i in range(5):
x -= 1
print(x)
# use a for loop over a collection
days = ["Mon","Tue","Wed",\
"Thurs","Fri","Sat","Sun"]
for day in days:
print(day)
# use the break and continue statements
for day in days:
if day == "Wed":
continue
if day == "Fri":
break
print(day)
#using the enumerate() function to get index
for index,day in enumerate(days):
print("Day #{} = {}".format(index,day))
if __name__ == "__main__":
main()
|
def solution(S):
hash1 = dict()
count = 0
ans = -0
ans_final = 0
if(len(S)==1):
print("0")
pass
else:
for i in range(len(S)):
#print(S[i])
if(S[i] in hash1):
#print("T")
value = hash1[S[i]]
hash1[S[i]] = i
if(value > i):
ans = value - i
count = 0
else:
ans = i - value
if(ans>ans_final):
ans_final = ans
count = 0
#print(ans_final)
else:
hash1[S[i]] = i
count = count + 1
if(count >= ans_final):
if(count==1):
count= count + 1
#print(count)
return(count)
#print(count)
return(count)
else:
#print(ans_final)
if(ans_final==1):
ans_final= ans_final + 1
#print(ans_final)
return(ans_final)
return(ans_final)
S = "cdd"
#print(len(S))
solution(S)
|
# 022: Crie um programa que leia o nome completo de uma pessoa e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras no total (sem considerar os espaços).
# - Quantas letras tem o primeiro nome.
nome = str(input('Digite o seu nome: ')).strip()
print(f'maiusculas: {nome.upper()}')
print(f'minusculas: {nome.lower()}')
print(f'letras ao todo: {len(nome) - nome.count(" ")}')
print(f'letras no primeiro nome: {len(nome.split()[0])}') # print(f'letras no primeiro nome: {nome.find(" ")}'
|
Size = (400, 400)
Position = (0, 0)
ScaleFactor = 1.0
ZoomLevel = 50.0
Orientation = 0
Mirror = 0
NominalPixelSize = 0.12237
filename = ''
ImageWindow.Center = None
ImageWindow.ViewportCenter = (1.4121498000000001, 1.2090156)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [[-0.5212962, -0.0758694], [-0.073422, -0.0073422]]
ImageWindow.show_scale = True
ImageWindow.scale_color = (128, 128, 255)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (0, 0, 255)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.2, -0.2], [0.2, 0.2]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = 'xy'
ImageWindow.grid_color = (0, 0, 255)
ImageWindow.grid_x_spacing = 1.0
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
camera.use_multicast = True
camera.IP_addr = 'pico14.niddk.nih.gov'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.