content stringlengths 7 1.05M |
|---|
#Input String list, write a python program to filter all the strings
#which have a similar case, either upper or lower.
#INPUT:{“Hello”,”MOM”,”Hi”,”dad”,”Python”}
#OUTPUT:{“MOM,”dad”}
def stringFilter(li):
ans = []
for i in li:
j = i.lower()
k =... |
#!/usr/bin/env python3
if __name__ == "__main__":
a = [-1, 1, 66.25, 333, 333, 1234.5]
print(a)
del a[0]
print(a)
del a[2:4]
print(a)
del a[:]
print(a)
del a
# Below causes an error since 'a' is no more available
# print(a)
|
def div(num1,num2):
assert isinstance(num1,int), '值类型不正确'
assert isinstance(num2,int), '值类型不正确'
assert num2 != 0, '除数不能为零'
return num1 / num2
if __name__ == '__main__':
print(div(100,50))
print(div(100,0))
|
fp = open("./packet.csv", "r")
vals = fp.readlines()
count = 1
pre_val = 0
current = 0
val_bins = []
for i in range(len(vals)):
pre_val = current
current = int(vals[i])
if current == pre_val:
count = count + 1
else:
count = 1
if count == 31:
print(pre_val)
val_bi... |
MANAGER_PATHS = {
'service': {
'ASSESSMENT': ('dlkit.services.assessment.AssessmentManager',
'dlkit.services.assessment.AssessmentManager'),
'REPOSITORY': ('dlkit.services.repository.RepositoryManager',
'dlkit.services.repository.RepositoryManager'),
... |
# A magic index in an array A[0...n-1] is defined to be an indexe such that
# A[i] = i. Given a sorted array of distinct integers, write a method to find a
# magic index, if one exists, in array A.
# Assumes distinct
def find(sorted_array):
i = 0
while i < len(sorted_array):
difference = sorted_array[i] - i
... |
def read_pairs():
file_name = "Data/day14.txt"
file = open(file_name, "r")
pairs = {}
for line in file:
line = line.strip("\n").split(" -> ")
pairs[(line[0][0], line[0][1])] = line[1]
return pairs, set(pairs.values())
def insertion_process(template, pairs, l... |
"""Top-level package for frontend_control."""
__author__ = """Marco Berzborn"""
__email__ = 'mbe@akustik.rwth-aachen.de'
__version__ = '0.1.0'
|
"""
Webtoon providers.
A provider is module containing functions to parse webtoons.
A provider implements:
get_image_list(src): Get image list from given source.
get_next_episode_url(src): Get next episode's url from given source.
get_episode_name(src): Get episode's name from given source.
A mapping is a... |
"""sh module. Contains classes Shape, Square and Circle"""
class Shape:
"""Shape class: has method move"""
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, deltaX, deltaY):
self.x = self.x + deltaX
self.y = self.y + deltaY
class Square(Shape):
"""Square Cla... |
class Stack:
sizeof = 0
def __init__(self,list = None):
if list == None:
self.item =[]
else :
self.item = list
def push(self,i):
self.item.append(i)
def size(self):
return len(self.item)
def isEmpty(self):
if self.size()==0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 数値読み込み
a,b,c = [int(i) for i in input().split()]
if a*b*c % 2 == 0:
print(0)
else:
d = [a,b,c]
d.sort()
print(d[0]*d[1])
|
print((1 + 3) * 5)
print((3))
tu = (3,) # 元组中如果只有一个元素. 需要在括号里写一个,
print(type(tu))
tu2 = tuple() # 空元组
print(type(tu2))
tu3 = ('人民币', '美元', '英镑', '欧元')
# tu3.append('哈哈')
# tu3[0] = '日元' # 不允许修改
# del tu3[2] # 删除也不行
print(tu3[2]) # 索引可以用
print(tu3[::2])
for el in tu3:
print(el)
# 元组的第一层是不能进行赋值的.内部元素是没有要求
tu... |
# https://adventofcode.com/2021/day/17
# SAMPLE
# target area: x=20..30, y=-10..-5
target_x = [20, 30]
target_y = [-10, -5]
# velocity ranges to probe brute force (start by big enough values then tweak it down based on the printed value range)
velocity_range_x = [0, 40]
velocity_range_y = [-30, 1000]
steps_range = 25 ... |
'''
Author: ZHAO Zinan
Created: 12/13/2018
62. Unique Paths
'''
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if not m or not n:
return 0
if n == 1:
return 1
if m... |
class Solution:
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
uglies = [1]
pq = [(prime, 0, prime) for prime in primes]
heapq.heapify(pq)
while len(uglies) < n:
val, i, factor = he... |
"""
Complete this function such that it returns True if and only if
the string passed into this function is a palindrome, that is if
it is the same string of characters forwards and in reverse.
Return False otherwise.
This solution computes the midpoint of the input_string and then
compares letters from the outside... |
class Object():
def __init__(self, pos, img):
self.pos = pos
self.img = img
self.rect = []
def fromSafe(string):
string = string.strip()
s = string.split(",")
ret = Object((int(s[2]), int(s[1])), s[0])
return ret
|
"""
author: https://github.com/alif-arrizqy
lesson: boolean logic
"""
print(20 > 8)
# output: True
print(8 > 20)
# output: False
print(9==9)
# output: True |
class MovieModel:
def __init__(self, *, id, title, year, rating):
self.id = id
self.title = title
self.year = year
self.rating = rating
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2018年4月10日 @author: encodingl
'''
def list_to_formlist(args):
list_args = args
list_tumple = []
for l in list_args:
l=str(l)
t1=(l,l)
list_tumple.append(t1)
return list_tumple
if __name__ == '__ma... |
"""
278
first bad version
easy
You are a product manager and currently leading a team to develop a new product.
Unfortunately, the latest version of your product fails the quality check. Since
each version is developed based on the previous version, all the versions after
a bad version are also bad.
Suppose you hav... |
N = int(input())
IN = OUT = 0
for _ in range(0, N):
X = int(input())
if 10 <= X <= 20:
IN += 1
else:
OUT += 1
print(f"{IN} in")
print(f"{OUT} out")
|
"""Settings for the Topology NApp."""
# Set this option to true if you need the topology with bi-directional links
# DISPLAY_FULL_DUPLEX_LINKS = True
# Time (in seconds) to wait before setting a link as up
LINK_UP_TIMER = 10
# Time (in seconds) to wait for a confirmation from storehouse
# when retrieving or updating... |
# -*- coding: utf-8 -*-
# Semana 02: Exercício adicional 01
# Escreva um programa que receba (entrada de dados através do teclado)
# o nome do cliente, o dia de vencimento, o mês de vencimento e
# o valor da fatura e imprima (saída de dados) a mensagem com
# os dados recebidos, no mesmo formato da mensagem acima.... |
# https://quera.ir/problemset/contest/9595/
n = int(input())
lines = [input() for i in range(2 * n)]
cnt = 0
for i in range(0, 2 * n, 2):
if lines[i].replace(' ', '') == lines[i + 1].replace(' ', ''):
continue
cnt += 1
print(cnt)
|
"""
Python file unde ne declaram clasa "Bicicleta" - obiect prinicipal al acestei aplicatii
"""
class Bicicleta:
def __init__(self , id , tip , pret):
self.id = id #integer number greater than 0
self.tip = tip #a basic string
self.pret = pret #float number greater than 0
def getid(sel... |
#!/usr/bin/env python3
class Piece:
def __init__(self, id, value):
self.__id = id
self.__value = value
@property
def id(self):
return self.__id
@id.setter
def id(self, id):
self.__id = id
@property
def value(self):
return self.__value
@value.... |
#!/usr/bin/env python3
def solution(n):
"""
Given a positive integer N,
returns the length of its longest binary gap.
"""
# possible states (START state is necessary to ignore trailing zeros)
START = -1
LAST_SAW_ONE = 1
LAST_SAW_ZERO = 0
current_state = START
# we move the bit mask's bit one po... |
class Person:
def __init__(self, age):
self.age = age
def drink(self):
return "drinking"
def drive(self):
return "driving"
def drink_and_drive(self):
return "driving while drunk"
class ResponsiblePerson:
def __init__(self, person):
self.person = person
... |
class A(object):
pass
class B(object):
pass
|
NAME = "eg"
DISPLAY_NAME = "달걀"
MIN_PRICE = 30000
MAX_PRICE = None
MIN_RANGE = 6000
MAX_RANGE = 10000
|
class Solution:
"""
@param image: a binary matrix with '0' and '1'
@param x: the location of one of the black pixels
@param y: the location of one of the black pixels
@return: an integer
"""
def minArea(self, image, x, y):
if image is None or len(image) == 0:
return 0
... |
"""
@author: Jessie Jiang
"""
class Style:
'''
class describing the style for the ploting and drawing
'''
def __init__(self, style_name=None,
compartment_fill_color=None,
compartment_border_color=None,
species_fill_color=None,
species_b... |
"""
16017. Telemarketer or not?
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 68 ms
해결 날짜: 2020년 9월 14일
"""
def main():
n = [int(input()) for _ in range(4)]
if n[0] > 7 < n[3] and n[1] == n[2]: print('ignore')
else: print('answer')
if __name__ == '__main__':
main()
|
"""MapReduce job that makes predictions with MLModel classes."""
# package metadata
__version_info__ = (0, 1, 0)
__version__ = '.'.join([str(i) for i in __version_info__])
|
sum=0
for i in range(5):
n=int(input())
sum+=n
print(sum) |
#
# @lc app=leetcode id=170 lang=python3
#
# [170] Two Sum III - Data structure design
#
# @lc code=start
class TwoSum:
def __init__(self):
self.vals = []
def add(self, number: int) -> None:
self.vals.append(number)
def find(self, value: int) -> bool:
s = set()
... |
def go_to_formation_2_alg(position_blue_robots):
rule_0 = [0] + go_to_point(position_blue_robots[0][0], position_blue_robots[0][1], -4500.0, 0.0)
rule_1 = [1] + go_to_point(position_blue_robots[1][0], position_blue_robots[1][1], -3600.0, -550.0)
rule_2 = [2] + go_to_point(position_blue_robots[2]... |
infile=int(open('primes.in','r').readline())
outfile=open('primes.out','w')
max1=10**infile
for i in range(infile,max1):
prime=True
for e in range(2,i//2):
if (i%e) == 0:
prime=False
break
if i==1:
answer=0
break
elif prime==True:
answer=... |
"""
__init__.py
Created by: Martin Sicho
On: 5/4/20, 10:46 AM
"""
|
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
# Insert method to create nodes
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left ... |
n, m = [int(i) for i in input().split()]
if n-m > m-1:
print(min(m+1, n))
else:
print(max(m-1, 1))
|
"""
Module containing functions for cleaning label-lists.
"""
def merge_consecutive_labels_with_same_values(label_list, threshold=0.01):
"""
If there are consecutive (end equals start) labels, those two labels are merged into one.
Args:
label_list (LabelList): The label-list to clean.
t... |
"""
Получить множество натуральных чисел, не превосходящих
1000000, каждое из которых при делении на 53 даёт в остатке 17, при
делении на 69 даёт в остатке 1, при делении на 65 даёт в остатке 5.
Результат вывести в упорядоченном по возрастанию виде.
"""
print(sorted(set(num for num in range(1, 1000001) if num % 53 ==... |
"""
link: https://leetcode.com/problems/implement-trie-prefix-tree
problem: 实现字典树
solution: 每个节点独立成树结构,递归查找
solution-fix: 直接以map形式嵌套存取,补充$为后缀符号标记字符串结束
"""
class Trie:
def __init__(self):
self.son = [None for _ in range(26)]
self.done = False
def insert(self, word: str) -> None:
if... |
#!/usr/bin/env python 3
############################################################################################
# #
# Program purpose: Count the number of substrings from a given string of lowercase #
# ... |
http = require("net/http")
def hello(w, req):
w.WriteHeader(201)
w.Write("hello world\n")
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8080", http.Handler)
|
""" Given a sorted integer array where the range of elements are in the inclusive range [lower, upper],
return its missing ranges.
For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"]. """
class Solution(object):
def findMissingRanges(self, nums, lower, upper):... |
'''
Sum of even & odd
Write a program to input an integer N and print the sum of all its even digits and sum of all its odd digits separately.
Digits mean numbers, not the places! That is, if the given integer is "13245", even digits are 2 & 4 and odd digits are 1, 3 & 5.
Input format :
Integer N
Output format :
Sum... |
# Eoin Lees
# this program creates a tuple that prints the summer months
months = ("January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December")
summer = months[4:7]
for month in summer:
print(month) |
# PERSON
SEARCH_PERSON = '''
query SearchPerson($searchTerm: String){
searchPerson(searchTerm: $searchTerm){
id
birth{
surname
}
}
}
'''
|
def is_paired(input_string):
pairs = {'[': ']', '{': '}', '(': ')'}
stack = list()
for char in input_string:
if char in pairs.keys():
stack.append(char)
elif char in pairs.values():
if not stack or pairs[stack.pop()] != char:
return False
return ... |
'''
In a balanced full binary tree,
h = ⌈ log 2 ( l ) ⌉ + 1 =
⌈ log 2 ( ( n + 1 ) / 2 ) ⌉ + 1 =
⌈ log 2 ( n + 1 ) ⌉
{\displaystyle
h=⌈ \log _{2}(l)⌉ +1=
⌈ \log _{2}((n+1)/2)⌉ +1=
⌈ \log _{2}(n+1)⌉ }
h=⌈ \log _{2}(l) ⌉ +1=
⌈ \log _{2}((n+1)/2)⌉ +1=
⌈ \log _{2}(n+1)⌉ '''
# Python program to demonstrate
... |
def missing_number(original_list=[1,2,3,4,6,7,10], num_list=[10,11,12,14,17]):
original_list = [x for x in range(num_list[0], num_list[-1] + 1)]
num_list = set(num_list)
return (list(num_list ^ set(original_list)))
print(missing_number([1,2,3,4,6,7,10]))
print(missing_number([10,11,12,14,17]))
... |
# B2054-求平均年龄
n = int(input())
s = []
for i in range(0, n):
s.append(int(input()))
a = sum(s) / len(s)
print("%.2f" % a) |
def plateau_affichage(plateau,taille,plateau_list,Htaille,plateau_lists = []) :
L=taille
H=taille
for x in range (0,L+1) :
print (str(x),(' '), end='')
for y in range (0,H+1) :
if y==0 :
print (' ')
else :
print (str(y), )
for y in range(H):
... |
# -*- coding: utf-8 -*-
""" Encapsulates Functionality for Building Web Requests. """
class RequestBuilder(object):
""" Encapsulates Functionality for Building Web Requests.
:attr _domain: The domain component of the request.
:type _domain: str
:attr _path: The path component of the request (default... |
# !/usr/bin/env python
# coding: utf-8
'''
Description:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive),
prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
1. You must not modify... |
# needed to let the vscode test discoverer find and import the tests
__all__ = [
'TestUnitCaja',
'TestUnitSplitter'
]
|
GENOMES_DIR='/media/data1/genomes'
OUT_DIR = '/media/data2/HuR_human_mouse/mouse/ribo-seq'
SRC_DIR = '/home/saket/github_projects/clip_seq_pipeline/scripts'
RAWDATA_DIR ='/media/data1/HuR_human_mouse/mouse/ribo/Penalva_L_03222017'
GENOME_BUILD = 'mm10'
GENOME_FASTA = GENOMES_DIR + '/' + GENOME_BUILD + '/fasta/'+ GENOME... |
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def partition(self, A, B):
head0 = None
tail0 = None
head1 = None
tail1 = None
ptr = A
while ptr is not None :
ptr2 = ptr.next
... |
"""
ord
"""
def hash_me(text):
hash_value = 0
for e in text:
hash_value += ord(e)
return hash_value
def print_my_chars(text):
for e in text:
print(ord(e), end=" ")
message1 = "Python is Great!"
message2 = "Python is GREAT!"
print(hash_me(message1))
print(hash_me(mes... |
# Author : SNEH DESAI
# Description : THIS IS THE CODE FOR NAIVE BAYES THEOREM
# AND IT HAD ALSO BEEN TESTED FOR ALL THE POSSIBLE RESULTS.
# DATA MINING
# Open File to read
myFile = open('Play Or Not.csv', 'r')
# Logic
ListOfLines = myFile.read().splitlines() # Reads The ... |
# https://www.codechef.com/problems/ADACRA
for T in range(int(input())):
s,u,d=input(),0,0
if(s[0]=='U'): u+=1
elif(s[0]=='D'): d+=1
for z in range(1,len(s)):
if(s[z]=='D' and s[z-1]=='U'): d+=1
elif(s[z]=='U' and s[z-1]=='D'): u+=1
print(min(d,u)) |
class Solution(object):
def verifyPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: bool
"""
if not preorder:
return True
stack = []
low = -12345678
for p in preorder:
if p < low:
return False
... |
__author__ = 'fengyuyao'
class Node(object):
pass
|
ART = {
"BANNER":
"""
::'#######::::'#####::::'#######::::'#####:::
:'##.... ##::'##.. ##::'##.... ##::'##.. ##::
:..::::: ##:'##:::: ##:..::::: ##:'##:::: ##:
::'#######:: ##:::: ##::'#######:: ##:::: ##:
:'##:::::::: ##:::: #... |
pynasqmin = ''\
'# -*- Mode: json -*-\n'\
'############################################################\n'\
'# HPC Info (Slurm Supported)\n'\
'############################################################\n'\
'# Change here whether you are working on your personal computer\n'\
'# or an HPC with SLURM\n'... |
class OrderError(Exception):
pass
class DimensionError(Exception):
pass
class IncompatibleOrder(Exception):
pass
class InvalidOperation(Exception):
pass
class OperationNotAllowed(Exception):
pass
class OutOfRange(Exception):
pass
class ImprobableError(Exception):
pass
class Un... |
def get_hostname(use_bytes=True):
if use_bytes:
return (b'test-server\n', b'')
else:
return 'test-server'
def get_xen_host_events():
return (
b"""
748dee41-c47f-4ec7-b2cd-037e51da4031 = "{"name": "keyinit"\n""",
b''
)
def get_xen_guest_events():
return (
... |
level = {
"Fresher" : list(range(20,36)),
"Junior": list(range(36,51)),
"Middle": list(range(51,76)),
"Senior": list(range(76,101))
}
keys = {
"Frontend":{
"ReactJS":{
"Component": 6,
"Redux": 6,
"Hook": 5,
"Event": 4,
"Function Co... |
#
# PySNMP MIB module ASCEND-MIBVACM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBVACM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:12:49 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
def peer(parser,logic,logging,args=0):
if args:
if "ip" in args.keys() and "p" in args.keys():
ip = args["ip"][0]
try:
port = int(args["p"][0])
except:
parser.print(args["p"][0]+": could not be cast to integer")
return
... |
nc = str(input('Digite seu nome completo:')).strip()
print('Maisculo: {}'.format(nc.upper()))
print('Minusculo: {}'.format(nc.lower()))
print('Total de letras: {}'.format(len(nc.replace(' ', ''))))
dividido = nc.split()
print('Total de letras do primeiro nome: {}'.format(len(dividido[0])))
nc2 = str(input('Digite seu ... |
nCups = int(input())
cups = {}
for i in range(nCups):
line = input().split()
if line[0].isnumeric():
cups[int(line[0])/2] = line[1]
else:
cups[int(line[1])] = line[0]
print("\n".join([cups[k] for k in sorted(cups.keys())])) |
def test_args_kwargs(*args, **kwargs):
for k in kwargs.keys():
print(k)
test_args_kwargs(fire="hot", ice="cold") |
# Template for Matrix Operations
# Created by manish.17
# https://github.com/iammanish17/CP-templates
# ----- Usage -----
#m1 = Matrix(2, 2, [[2, 4],[3, 7]])
#m2 = Matrix(2, 2, [[3, 1],[5, 2]])
#print(m1 + m2)
#print(m1 - m2)
#print(m1*m2)
#print(m1**100)
# ------------------
class Matrix(object):
def __init__(self... |
# Топ-3 + Выигрышные номера последних 4 тиражей
def test_top_3_winning_numbers_last_4_draws(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_top_3()
app.ResultAndPrizes.click_winning_numbers_of_the_last_4_draws()
app.ResultAndPrizes.button_get_report_winners()
... |
for episode in range(nb_episodes):
callbacks.on_episode_begin(episode)
episode_reward = 0.
episode_step = 0
# Obtain the initial observation by resetting the environment.
self.reset_states()
observation = deepcopy(env.reset())
if self.processor is not None:
observation = self.proces... |
# sources: http://www.atrixnet.com/bs-generator.html
# https://en.wikipedia.org/wiki/List_of_buzzwords
# http://cbsg.sourceforge.net/cgi-bin/live
BUZZWORDS = {
'en': ['as a tier 1 company', 'paving the way for', 'relative to our peers', '-free', '200%', '24/365',
'24/7', '360-degree', '360... |
"""
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if le... |
# Crie um progama que leia o nome de uma cidade se ela COMEÇA ou não com o nome "SANTO"
cid = str(input('Digite onde você nasceu: ')).strip()
print(cid[0:5].upper() == 'SANTO')
|
WALLPAPERS = [
{
"id": "E0AHdsENmDg",
"created_at": "2016-06-01T13:39:24-04:00",
"updated_at": "2021-03-16T13:00:41-04:00",
"promoted_at": "2016-06-01T13:39:24-04:00",
"width": 5005,
"height": 3417,
"color": "#0c2659",
"blur_hash": "LF7U[HofDg... |
class GLLv3:
i2c = None
__GLL_ACQ_COMMAND = 0x00
__GLL_STATUS = 0x01
__GLL_SIG_COUNT_VAL = 0x02
__GLL_ACQ_CONFIG_REG = 0x04
__GLL_VELOCITY = 0x09
__GLL_PEAK_CORR = 0x0C
__GLL_NOISE_PEAK = 0x0D
__GLL_SIGNAL_STRENGTH = 0x0E... |
"""
Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
"""
class Solution:
# @param head: A RandomListNode
# @return: A RandomListNode
def copyRandomList(self, head):
d... |
'''
06 - Using a plotting function
Defining functions allows us to reuse the same code without having to repeat all of
it. Programmers sometimes say "Don't repeat yourself".
In the previous exercise, you defined a function called plot_timeseries:
`plot_timeseries(axes, x, y, color, xlabel, ylabel)`
that takes an ... |
"""
Problem 2_3:
Write a function problem2_3() that should have a 'for' loop that steps
through the list below and prints the name of the state and the number of
letters in the state's name. You may use the len() function.
Here is the output from mine:
In [70]: problem2_3(newEngland)
Maine has 5 letters.
New Hampshire... |
class Solution:
def reachNumber(self, target: int) -> int:
target = abs(target)
step, summ = 0, 0
while summ < target or (summ - target) % 2:
step += 1
summ += step
return step
|
#Desenvolva um programa que pergunte a distancia de uma viagem em km. calcule o preço da passagem, cobrando R$0.50 por km para viagens até 200 km e R$0.45 para viagens mais longas.
print('xxxxxxxxxxxxCÁLCULO DE VIAGEMxxxxxxxxxxxx')
km = float(input('Informe a distância a ser percorrida: '))
if km <= 200:
print('Sua... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:jiayou.py
@TIME:2020/5/9 11:26
@DES: 加油,使得加油次数最少
'''
def greedy():
n = 100 # 总的储油量
k = 5
d = [50,80,39,60,40,32]
# 表示加油站之间的距离
num = 0
# 表示加油的次数... |
def camera_connected(messages):
for message in messages:
if u'Nikon D3000' in message:
yield u'add' == message[1:4]
|
__package__ = 'croprows-cli'
__author__ = "Andres Herrera"
__copyright__ = "Copyright 2018, Crop Rows Generator CLI"
__credits__ = ["Andres Herrera", "Maria Patricia Uribe", "Ivan Mauricio Cabezas"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Andres Herrera"
__email__ = "fabio.herrera@correounivalle.edu.c... |
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ASSETS_DEBUG = True
ALLOWED_HOSTS = []
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'midnight',
... |
"""
Module with color bar definitions.
"""
def _inflate_colorbar(cbar, numColors):
if len(cbar) >= numColors:
return cbar # do not reduce color bars
newBar = [None] * numColors
step = float(len(cbar) - 1) / (numColors - 1)
for i in xrange(numColors):
c_int = int(step * i)
... |
# -*- coding: utf-8 -*-
class User():
def __init__(self, username = "", password = "", email = ""):
self.username = username
self.password = password
self.email = email
def __str__(self):
return f"[{self.username}] - [pwd:{self.password} eml:{self.email}]"
|
"""Provides a decororator that automatically adds math dunder methods to a class."""
unary = "abs ceil floor neg pos round trunc".split()
binary = "add divmod floordiv mod mul pow sub truediv".split()
binary = binary + [f"r{name}" for name in binary]
dunders = tuple(f"__{name}__" for name in unary + binary)
def math... |
score = 76
grades = [
(60, 'F'),
(70, 'D'),
(80, 'C'),
(90, 'B'),
]
print(next((g for x, g in grades if score < x), 'A'))
|
# Flask settings
SERVER_NAME = None
DEBUG = True # Do not use debug mode in production
PORT = 5000
HOST = '0.0.0.0'
# Flask-Restplus settings
RESTPLUS_SWAGGER_UI_DOC_EXPANSION = 'list'
RESTPLUS_VALIDATE = True
RESTPLUS_MASK_SWAGGER = False
RESTPLUS_ERROR_404_HELP = False
# SQLAlchemy settings
SQLALCHEMY_DATABASE_URI... |
lista = list()
lista.append(0)
for i in range(5):
aux = int(input())
for j in range(len(lista)):
if aux <= lista[j]:
lista.insert(j,aux)
break
else:
if j==len(lista)-1:
lista.insert(j,aux)
lista.remove(lista[len(lista)-1])
print(lista) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.