content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
__all__=['glottal', 'phonation', 'articulation', 'prosody', 'replearning'] |
# creating a function to calculate the density.
def calc_density(mass, volume):
# arithmetic calculation to determine the density.
density = mass / volume
density = round(density, 2)
# returning the value of the density.
return density
# receiving input from the user regarding the mass ... |
class documentmodel:
def getDocuments(self):
document_tokens1 = "China has a strong economy that is growing at a rapid pace. However politically it differs greatly from the US Economy."
document_tokens2 = "At last, China seems serious about confronting an endemic problem: domestic violence and corr... |
# For internal use. Please do not modify this file.
def setup():
return
def extra_make_option():
return ""
|
def collatz(number):
if number%2==0:
number=number//2
else:
number=3*number+1
print(number)
return number
print('enter an integer')
num=int(input())
a=0
a=collatz(num)
while a!=1:
a=collatz(a)
|
# CONVERSION OF UNITS
# Python 3
# Using Jupyter Notebook
# If using Visual Studio then change .ipynb to .py
# This program aims to convert units from miles to km and from km to ft.
# 1 inch = 2.54 cm, 1 km = 1000m, 1 m = 100 cm, 12 inches = 1 ft, 1 mile = 5280 ft
# ------- Start -------
# Known Standard Units of Co... |
# 🚨 Don't change the code below 👇
age = input("What is your current age?")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
age = int(age)
days_left = (90*365) - (age*365)
weeks_left = (90*52) - (age*52)
months_left = (90*12) - (age*12)
print(f"You have {days_left} days, {weeks_left} weeks le... |
'''constants.py
Various constants that are utilized in different modules across the whole program'''
#Unicode characters for suits
SUITS = [
'\u2660',
'\u2663',
'\u2665',
'\u2666'
]
#A calculation value and a face value for the cards
VALUE_PAIRS = [
(1, 'A'),
(2, '2'),
(3, '3'),
(4, '4... |
def is_overlap(arr1, arr2):
if arr2[0] <= arr1[0] <= arr2[1]:
return True
if arr2[0] <= arr1[1] <= arr2[1]:
return True
if arr1[0] <= arr2[0] <= arr1[1]:
return True
if arr1[0] <= arr2[1] <= arr1[1]:
return True
return False
def merge_2_arrays(arr1, arr2):
l = ... |
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
def fib3(n):
if n == 1 or n == 2 or n == 3:
return 1
else:
return fib3(n - 1) + fib3(n - 2) + fib3(n - 3)
def fib_mult(n):
if n == 1:
return 1
if n == 2:
return 2
... |
"""Given a linked list of co-ordinates where adjacent points either form a vertical line or a horizontal line.
Delete points from the linked list which are in the middle of a horizontal or vertical line."""
"""Input: (0,10)->(1,10)->(5,10)->(7,10)
|
(7,... |
__author__ = 'JPaschoal'
__version__ = '1.0.1'
__email__ = 'jonfisik@hotmail.com'
__date__ = '08/05/2021'
'''
Qualquer número natural de quatro algarismos pode ser dividido
em duas dezenas formadas pelos seus dois primeiros e dois
últimos dígitos.
Exemplos:
1297: 12 e 97
5314: 53 e 14
Escreva um programa que i... |
"""
==========
Exceptions
==========
Module containing framework-wide exception definitions. Exceptions for
particular subsystems are defined in their respective modules.
"""
class VivariumError(Exception):
"""Generic exception raised for errors in ``vivarium`` simulations."""
pass
|
"""
Python program to find the n'th number in the tribonacci series
Tribonacci series is a generalization of the Fibonacci sequence, in which the current term
is the sum of the previous three terms.
"""
def find_tribonacci(n):
dp = [0] * n
dp[0] = 0
dp[1] = 0
dp[2] = 1
# Compute the sum of the pre... |
__author__ = 'Dmitriy Korsakov'
def main():
pass
|
# Python - 3.4.3
def problem(a):
try:
return float(a) * 50 + 6
except:
return 'Error'
|
"""
bluew.daemon
~~~~~~~~~~~~~~~~~
This module provides a Daemon object that tries its best to keep connections
alive, and has the ability to reproduce certain steps when a reconnection is
needed.
:copyright: (c) 2017 by Ahmed Alsharif.
:license: MIT, see LICENSE for more details.
"""
def daemonize(func):
"""
... |
class TransportModesProvider(object):
TRANSPORT_MODES = {
'0': None,
# High speed train
'1': {
'node': [('railway','station'),('train','yes')],
'way': ('railway','rail'),
'relation': ('route','train')
},
# Intercity train
'2': {... |
# current = -4.036304473876953
def convert(time):
pos = True if time >= 0 else False
time = abs(time)
time_hours = time/3600
time_h = int(time_hours)
time_remaining = time_hours - time_h
time_m = int(time_remaining*60)
time_sec = time_remaining - time_m/60
time_s = int(time_se... |
"""
Define redistricting.management as a Python package.
This file serves the purpose of defining a Python package for
this folder. It is intentionally left empty.
This file is part of The Public Mapping Project
https://github.com/PublicMapping/
License:
Copyright 2010-2012 Micah Altman, Michael McDonald
Li... |
def composite_value(value):
if ';' in value:
items = []
first = True
for tmp in value.split(';'):
if not first and tmp.startswith(' '):
tmp = tmp[1:]
items.append(tmp)
first = False
else:
items = [value]
return items
|
# MIT License
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP.
#
# actionLog : Get Action/Audit Logs
def get_audit_log(
self,
start_time: int,
end_time: int,
limit: int,
log_level: int = 1,
ne_pk: str = None,
username: str = None,
) -> list:
"""Get audit log details filt... |
#!/usr/bin/env python
# iGoBot - a GO game playing robot
#
# ##############################
# # GO stone board coordinates #
# ##############################
#
# Project website: http://www.springwald.de/hi/igobot
#
# Licensed under MIT License (MIT)
#
# Copyright (c) 2018 Daniel Springwald... |
def compare(a: int, b: int):
printNums(a, b)
if a > b:
msg = "a > b"
a += 1
elif a < b:
msg = "a < b"
b += 1
else:
msg = "a == b"
a += 1
b += 1
print(msg)
printNums(a, b)
print()
def printNums(a, b):
print(f"{a = }, {b = }")
def main():
for a in range(1, 4):
for b in range(1, 4):
compare... |
#!/usr/bin/env python
"""quicksort.py: Program to implement quicksort"""
__author__ = 'Rohit Sinha'
def quick_sort(alist):
quick_sort_helper(alist, 0, len(alist) - 1)
def quick_sort_helper(alist, start, end):
if start < end:
pivot = partition(alist, start, end)
quick_sort_helper(alist, sta... |
latest_block_redis_key = "latest_block_from_chain"
latest_block_hash_redis_key = "latest_blockhash_from_chain"
most_recent_indexed_block_redis_key = "most_recently_indexed_block_from_db"
most_recent_indexed_block_hash_redis_key = "most_recently_indexed_block_hash_from_db"
most_recent_indexed_ipld_block_redis_key = "mos... |
class CountryExclude(object):
@staticmethod
def validate(data: str) -> None:
"""
Check is country should be excluded
:param data: string to validate
:return: None
:raise: ValueError on failure
"""
# Exclude these countries/islands
if data in [
... |
a = 'abcdefghijklmnopqrstuvwxyz'
b = 'pvwdgazxubqfsnrhocitlkeymj'
trans = str.maketrans(b, a)
src = 'Wxgcg txgcg ui p ixgff, txgcg ui p epm. I gyhgwt mrl lig txg ixgff wrsspnd tr irfkg txui hcrvfgs, nre, hfgpig tcm liunz txg crt13 ra "ixgff" tr gntgc ngyt fgkgf.'
print(src.translate(trans))
|
def get_level_1_news():
news1 = 'Stars Wars movie filming is canceled due to high electrical energy used. Turns out' \
'those lasers don\'t power themselves'
news2 = 'Pink Floyd Tour canceled after first show used up the whole energy city had for' \
'the whole month. The band says they\... |
user_num = int(input("which number would you like to check?"))
def devisible_by_both():
if user_num %3 == 0 and user_num %5 == 0:
print("your number is divisible by both")
else:
print("your number is not divisible by both") |
class PyQtSociusError(Exception):
pass
class WrongInputFileTypeError(PyQtSociusError):
__module__ = 'pyqtsocius'
def __init__(self, input_file: str, expected_file_extension: str, extra_message: str = None):
self.file = input_file
self.file_ext = '.' + input_file.split('.')[-1]
s... |
base_rf.fit(X_train, y_train)
under_rf.fit(X_train, y_train)
over_rf.fit(X_train, y_train)
plot_roc_and_precision_recall_curves([
("original", base_rf),
("undersampling", under_rf),
("oversampling", over_rf),
]) |
# The view that is shown for normal use of this app
# Button name for front page
SUPERUSER_SETTINGS_VIEW = 'twitterapp.views.site_setup'
|
# Stwórz zmienną my_family zawierającą drzewo genealogiczne twojej rodziny.
# Zacznij od siebie - opisując imię, nazwisko, datę urodzenia
# każdej osoby oraz jej rodziców.
# Podpowiedź: rodzice będą listami, zawierającymi w sobie kolejne słowniki.
my_family = {
"first_name": "Mikołaj",
"last_name": "Lewandows... |
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
self.word = str
class Trie:
def __init__(self):
self.root = TrieNode()
def add_word(self, word):
node = self.root
for c in word:
if c not in node.children:
... |
class MoonBoard():
"""
Class that encapsulates Moonboard layout info for a specific year.
:param year_layout: Year in which this board layout was published
:type year_layout: int
:param image: Path to the image file for this board layout
:type image: str
:param rows: Number of rows of the... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 19:42:35 2020
@author: Administrator
"""
"""
给定一个矩阵序列,找到最有效的方式将这些矩阵相乘在一起.给定表示矩阵链的数组p,使得第i个矩阵Ai的维数为p[i-1]*p[i].
编写一个函数MatrixChainOrder(),该函数应该返回乘法运算所需的最小乘法数.
输入:p=(40,20,30,10,30)
输出:26000
有四个大小为40*20,20*30,30*10和10*30的矩阵.假设这四个矩阵为A,B,C和D,该函数的执行方法可以执行乘法运算的次数... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
############################
# File Name: calc.py
# Author: One Zero
# Mail: zeroonegit@gmail.com
# Created Time: 2015-12-28 00:22:01
############################
# 定义函数
def add(x, y):
'''相加'''
return x + y
def subtract(x, y):
'''相减'''
return x - y
def... |
'''Write a Python program to empty a variable without destroying it.
Sample data: n=20
d = {"x":200}
Expected Output : 0
{}'''
n = 20
d = {"x":200}
print(type(n)())
print(type(d)()) |
{
"name": "Module Wordpess Mysql",
"author": "Tedezed",
"version": "0.1",
"frontend": "wordpress",
"backend": "mysql",
"check_app": True,
"update_app_password": True,
"update_secret": True,
"executable": False,
}
|
"""
@author : udisinghania
@date : 24/12/2018
"""
string1 = input()
string2 = input()
a = 0
if len(string1)!=len(string2):
print("Strings are of different length")
else:
for i in range (len(string1)):
if string1[i]!=string2[i]:
a+=1
print(a)
|
AGENDA = {}
def exibir_contatos():
if len(AGENDA) > 0:
for contato in AGENDA:
buscar_contato(contato)
print('-' * 30)
else:
print('\nA sua agenda está vazia. Adicione alguns contatos!\n')
def buscar_contato(contato):
try:
print(f'Nome: {contato}')
pr... |
"""Minimize_sum_Of_array!!!, CodeWars Kata, level 7."""
def minimize_sum(arr):
"""Minimize sum of array.
Find pairs of to multiply then add the product of those multiples
to find the minimum possible sum
input = integers, in a list
output = integer, the minimum sum of those products
ex: minS... |
# Copyright (c) 2011-2020 Eric Froemling
#
# 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,... |
#!/usr/bin/python
# -*- utf-8 -*-
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
copy = [e for e in nums]
l = len(nums)
k = l - k % l
for i in range(l):
... |
# Enter your code for "camelCase" here.
def to_camel(ident):
def a(x):
return x
def b(x):
return x[0].upper() + x[1::]
def c():
yield a
while True:
yield b
d = c()
return "".join(d.__next__()(x) for x in ident.split("_"))
|
# Write a program that asks the user to input any positive integer
# and outputs the successive values of the following calculation.
# At each step calculate the next value by taking the current value and,
# if it is even, divide it by two, but if it is odd, multiply it by three and add one.
# Have the program end if t... |
class ModelPermissionsMixin(object):
"""
Defines the permissions methods that most models need,
:raises NotImplementedError: if they have not been overridden.
"""
@classmethod
def can_create(cls, user_obj):
"""
CreateView needs permissions at class (table) level.
We'll... |
class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
index = int(sorted(hero)[0])
return {'B':'Batman: ','R':'Robin: ','J':'Joker: '}[hero[0]] + quotes[index]
|
class Node:
starting = True
ending = False
name = ""
weight = [1, 20]
active = True
edge_length = 0
nodes = []
def __init__(self, name, grid, posX, posY, active):
self.name = name # Name of the node
self.grid = grid # Which grid the node will be placed
self.posX = posX # Position X on the grid
s... |
#!/usr/bin/env python3
dna = "ATGCAGGGGAAACATGATTCAGGAC"
#Make all lowercase
lowerDNA = dna.lower()
#Replace the complementary ones
complA = lowerDNA.replace('a','T')
complAT = complA.replace('t','A')
complATG = complAT.replace('g','C')
complATGC = complATG.replace('c','G')
#reverse the complement
revDNA = complATG... |
# with open("ReadMe.txt",'r') as file:
# print(file.read()) # Hello from Python 201
# # Running after adding the second line to the .txt file
# with open("ReadMe.txt",'r') as file:
# print(file.read()) # Hello from Python 201
# # This is a new line
# # Running after adding the se... |
OCTICON_LAW = """
<svg class="octicon octicon-law" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M8.75.75a.75.75 0 00-1.5 0V2h-.984c-.305 0-.604.08-.869.23l-1.288.737A.25.25 0 013.984 3H1.75a.75.75 0 000 1.5h.428L.066 9.192a.75.75 0 00.154.838l.53-.53-.53.53... |
__all__ = ['__author__', '__license__', '__version__', '__credits__', '__maintainer__']
__author__ = 'Henrik Nyman'
__license__ = 'MIT'
__version__ = '0.1'
__credits__ = ['Henrik Nyman']
__maintainer__ = 'Henrik Nyman'
|
print("Primeira e Última String\n")
frase = str(input("Digite a frase: ")).strip().upper()
print("A letra A aparece {} vezes na frase\n".format(frase.count('A')))
print(f"A primeira letra A aparece na posição: {frase.find('A')+1}\n")
print(f"A última letra A aparece na posição: {frase.rfind('A')+1}\n") |
def projectData(X, U, K):
"""computes the projection of
the normalized inputs X into the reduced dimensional space spanned by
the first K columns of U. It returns the projected examples in Z.
"""
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the projecti... |
def ssort(array):
for i in range(len(array)):
indxMin = i
for j in range(i+1, len(array)):
if array[j] < array[indxMin]:
indxMin = j
tmp = array[indxMin]
array[indxMin] = array[i]
array[i] = tmp
return array
|
# _*_ conding:utf8-
'''
# 如果要有默认参数,那么一定统一塞到最后面
def test(name1,name2='Joker',name3='Joker2'):
print(name1,name2,name3)
test('h','h','j')
# * 强制命名,*后面的所有参数,在传参过程中必须要带上
# 参数名防止传参错误
def NB(name1,*,name2='Joker',name3='Joker2'):
print(name1,name2,name3)
# 1. 位置参数,可以不带参数名
# 2. 带参数名的传参方式
NB('Joker3',name2='hahah',... |
depl_user = 'darulez'
depl_group = 'docker'
# defaults file for ansible-docker-apps-generator
assembly_path = 'apps-assembly'
apps_path = './apps-universe'
stacks_path = './stacks-universe'
default_docker_network = 'hoa_network'
docker_main_sections = ['docker_from', 'docker_init', 'docker_reqs', 'docker_core', 'docker... |
class Solution:
def widthOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# bfs
# corner case
if root is None:
return 0
queue = list()
queue.append((root, 0))
level = 1
while len(queue) > 0:
... |
class TrieNode(object):
__slots__ = ('children', 'isWord')
def __init__(self):
self.children = {}
self.isWord = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word:... |
nomemv = ''
media = m20 = mv = 0
for i in range(4):
nome = input('Digite o nome da pessoa {}: '.format(i))
idade = int(input('Digite a idade do(a) {}: '.format(nome)))
sexo = input('Digite o sexo do(a) {}: '.format(nome))
media = media + idade
if(sexo=='f'):
if(idade<20):
m20 = m... |
class FastLabelException(Exception):
def __init__(self, message, errcode):
super(FastLabelException, self).__init__(
"<Response [{}]> {}".format(errcode, message)
)
self.code = errcode
class FastLabelInvalidException(FastLabelException, ValueError):
pass
|
'''ALUMNA: HUAMANI TACOMA ANDY
EJERCICIO : PAINT DASH GRIDS-DFS-RECURSIVE'''
# DESCRIPCION: IMPLEMENTACION DE DFS-RECURSIVE PARA PINTAR LOS DASH GRIDS DE UNA MATRIZ
def dfs_recursive(matrix, startX, startY, simbVisited, simbPared):
# TABLERO, POSICION INICIALX, POSICION INICIALY, SIMBOLO VISITADO, SIMBOLO PA... |
__all__ = ["PACK_HEADER_MAX"]
# max scanned length of packet header
PACK_HEADER_MAX = 60
|
'''We sort a large sublist of a given list and go on reducing the size of the list until all elements are sorted.'''
def shellSort(input_list):
mid = len(input_list) // 2
while mid > 0:
for i in range(mid, len(input_list)):
temp = input_list[i]
j = i
# Sort t... |
# some basic settings
ph = 350 # pageheight
pw = ph * 2 # pagewidth
steps = 180 # how many pages / steps to draw
dot_s = 8 # size of the dots at the end of the radius
radius = ph/2 * .75
angle = 2*pi/steps
gap = radius / (steps - 1) * 2 # used to draw the dots of the sine wave
sin_vals = [sin(i*angle) for i in r... |
"""
PASSENGERS
"""
numPassengers = 2341
passenger_arriving = (
(3, 12, 4, 1, 1, 0, 2, 7, 5, 7, 0, 0), # 0
(4, 12, 2, 2, 4, 0, 2, 5, 3, 3, 2, 0), # 1
(3, 2, 3, 2, 2, 0, 6, 7, 5, 5, 2, 0), # 2
(1, 10, 4, 2, 1, 0, 6, 5, 1, 4, 1, 0), # 3
(3, 3, 2, 5, 4, 0, 9, 6, 7, 3, 5, 0), # 4
(5, 7, 4, 2, 3, 0, 5, 7, 4, 5,... |
"""
Project Euler Problem 12: Highly divisible triangular number
"""
# What is the value of the first triangle number to have over five hundred divisors?
# A simple solution is to not worry about generating primes, and just test odd numbers for divisors
# Since we have to test a lot of numbers, it probably is worth g... |
#
"""Make a function map that works the same way as the built-in map function:"""
def square(n):
return n * n
def map(square, list1):
return [ square(num) for num in list1 ] |
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def check(s, t):
word_map = {}
for i, v in enumerate(s):
tmp = word_map.get(t[i])
if tmp is None:
w... |
num = [[], []]
for c in range(0, 7):
n = (int(input(f'Digite o {c + 1}° valor: ')))
if n % 2 == 0:
num[0].append(n)
else:
num[1].append(n)
print('-=' * 24)
num[0].sort()
num[1].sort()
print(f'Os valores pares digitados foram: {num[0]}')
print(f'Os valores ímpares digitados foram: {num[1]}')... |
class Docs:
helps = """
:shrimp:새우 봇의 명령어 입니다!
새우야 도움말 <명령어>로 상세히 볼 수 있습니다!
**새우야**
새우 봇이 온라인인지 확인합니다!
**도움말**
새우 봇의 명령어를 알려줍니다!
**밥**
GSM의 급식을 알려줍니다!
**초대**
새우 봇을 초대할 수 있는 링크를 줍니다!
**커스텀**
새우 봇에게 새로운 명령어를 추가합니다!
**통계**
이 서버 내에서 새우 봇에게 내렸던 명령들의 횟수를 보여줍니다!
"""
ping = """
새우 봇이 온라인인지 확인합니다!
그리고 반갑게 인사:wav... |
# -*- coding: utf-8 -*-
# see LICENSE.rst
# ----------------------------------------------------------------------------
#
# TITLE : data
# PROJECT : astronat
#
# ----------------------------------------------------------------------------
"""Data Management.
Often data is packaged poorly and it can be difficult t... |
def constrict(maxc,minc,dell):
# Garante que as coordenadas de dell estão dentro dos limites
#
# next = constrict(maxc,minc,dell)
#
# next: vetor avaliado (com coordenadas dentro dos limites)
# maxc: valor máximo das coordenadas
# minc: valor mímimo das coordenadas
# dell... |
#Esta es la respuesta del control
def sumarLista(lista, largo):
if (largo == 0):
return 0
else:
return lista[largo - 1] + sumarLista(lista, largo - 1)
def Desglosar(numero:int,lista=[]):
def rev(l):
if len(l) == 0: return []
return [l[-1]] + rev(l[:-1])
if numero==0:
... |
# Utility functions for incrementing counts in dictionaries or appending to a list of values
def add_to_dict_num(D, k, v=1):
if k in D:
D[k] += v
else:
D[k] = v
def add_to_dict_list(D, k, v):
if k in D:
D[k].append(v)
else:
D[k] = [v]
def report(min_verbosity, *args):
... |
s = input()
sort_s = sorted(s)
print(sort_s)
# str型の文字列を直接sorted()に入れると
# str型の文字列を1文字ずつに分割したlist型として認識して
# それをソートしたlist型を取得できる。 |
# coding=utf-8
#
# @lc app=leetcode id=821 lang=python
#
# [821] Shortest Distance to a Character
#
# https://leetcode.com/problems/shortest-distance-to-a-character/description/
#
# algorithms
# Easy (62.75%)
# Likes: 658
# Dislikes: 57
# Total Accepted: 42K
# Total Submissions: 65.7K
# Testcase Example: '"lovel... |
'''
Created on Mar 19, 2022
@author: mballance
'''
class ActivityBlockMetaT(type):
def __init__(self, name, bases, dct):
pass
def __enter__(self):
print("ActivityBlockMetaT.__enter__")
def __exit__(self, t, v, tb):
pass
|
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2020-01-14 00:47
# @Author : Fabrice LI
# @File : 20200113_667_longest_palindromic_subsequence.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given a string s, find the longest palindromic subsequence's l... |
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
if len(s)==0:
return s
s = list(s)
def flip(s,start,end):
for i in range(start,(start+end)//2 + 1):
s[i],s[end-i+start] = s[end - i+start],s[i]
... |
list1=[1,2,3,5,7,12,19] #数字列表
list2=['strawberry','watermelon','mango'] #字符串列表
student=['55122005100','李明','男',19] #学生列表
print(student)
list4=[i for i in range(1,20,2)] #list4是1到19的奇数
print(list4)
#向列表中添加元素
list3=list1+list2 #列表合并(连接)
print(list3)
list1.append(31) #在list1中朝最后一个位置添加元素
print(list1)
list1.insert(1,2) #在li... |
'''
question link- https://leetcode.com/problems/sum-of-all-subset-xor-totals/
Sum of All Subset XOR Totals
Question statement:
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.
For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.
'''
def subse... |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
ans = [1]*n
for i in range(1,m):
for j in range(1,n):
ans[j] = ans[j-1] + ans[j]
return ans[-1] if m and n else 0 |
'''
Write a Python program to compute the sum of all items of a
given array of integers where each integer is multiplied by its
index. Return 0 if there is no number.
Sample Input:
[1,2,3,4]
[-1,-2,-3,-4]
[]
Sample Output:
20
-20
0
'''
def sum_index_multiplier(nums):
# use enumerate to return count and value
... |
# ## Leap Year
# # 💪This is a Difficult Challenge 💪
# # Instructions
# Write a program that works out whether if a given year is a leap year. A normal year has 365 days, leap years have 366, with an extra day in February. The reason why we have leap years is really fascinating, this video does it more justice:
# ... |
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = Node(root)
def display(self, start, traversal=""):
if start != None:
traversal += (str(... |
class Solution:
def expandFromMiddle(self, s:str, l:int, r:int):
while (l >= 0 and r < len(s) and s[l] == s[r]):
l -= 1
r += 1
return (r - l - 1)
def longestPalindrome(self, s: str) -> str:
if len(s) < 1: return 0
start = 0
end = 0
... |
class Paddle():
def __init__(self, x1, x2 , y1, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
#private method
def __setPaddleRight(self):
self.x1 = 4
self.x2 = 4
self.y1 = 0
self.y2 = 1
display.set_pixel(self.x1, self.y1, 9)... |
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
minBuy = 999999 # probably should use sys.maxint
maxProfits = 0
for i in xrange(len(prices)):
minBuy = min(minBuy, prices[i])
maxP... |
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def log(message, log_class, log_level):
"""Log information to the console.
If you are angry about having to use Enums instead of typing the classes and levels in, look up how any logg... |
class Solution:
def findContestMatch(self, n):
"""
:type n: int
:rtype: str
"""
ans = list(range(1, n + 1))
while len(ans) > 1:
ans = ["({},{})".format(ans[i], ans[~i]) for i in range(len(ans) // 2)]
return ans[0] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Создайте класс с именем _Person_, содержащий три поля для хранения имени, фамилии и отчества.
# В классе создайте функцию _show_data()_, выводящую на экран имя, фамилию и отчество.
# Далее от класса _Person_ с помощью наследования создайте два класса: _Student_, _Professor_.... |
N, C, S, *l = map(int, open(0).read().split())
c = 0
S -= 1
ans = 0
for i in l:
ans += c == S
c = (c+i+N)%N
ans += c == S
print(ans) |
"""Question: https://leetcode.com/problems/palindrome-number/
"""
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
copy, reverse = x, 0
while copy:
reverse *= 10
reverse += copy % 10
copy = copy // 10
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Sandip Dutta
"""
# To implement simple tree algorithms
# DFS on Binary Tree,
# Problem Stateent : sum of all leaf nodes
#number of nodes of tree
n = 10
'''we take starting node to be 0th node'''
''' tree is a directed graph here'''
tree = [[1, 2],#0
... |
def mensagem(cor='', msg='', firula='', tamanho=0):
if '\n' in msg:
linha = msg.find('\n')
else:
linha = len(msg)
limpa = '\033[m'
if tamanho == 0:
tamanho = firula * (linha + 4)
if firula == '':
print(f'{cor} {msg} {limpa}')
else:
print(f'{cor}{tamanho}... |
n1 = int(input('Digite o 1° número: '))
n2 = int(input('Digite o 2° número: '))
s = n1 + n2
print('{} + {} = {}'.format(n1, n2, s))
|
'''
Leetcode Problem number 687.
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
'''
class Solution:
def longestUn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.