content
stringlengths
7
1.05M
arr1 = [-12, 11, -13, -5, 6, -7, 5, -3, -6] arr2 = [1, 2, -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2, 1] def moveNegativeInt(arr): for i in arr: if i < 0: temp = i arr.remove(i) arr.insert(0, temp) return arr print(moveNegativeInt(arr1)) print(moveNegativeInt(arr2))
el_mundo_es_plano = True if el_mundo_es_plano: print ("Tené cuidado de no caerte") # este es el primer comentario spam = 1 # y este es el segundo comentario # ... y ahora un tercero! text = "# Este no es un comentario, es un String" print (spam) print (te...
s = input() l = len(s) r = 'AWH' # just repeat Os bc valid, ignore other rules print(r + 'O' * l)
# By manish.17, contest: ITMO Academy. Двоичный поиск - 2, problem: (G) Student Councils # https://codeforces.com/profile/manish.17 k = int(input()) n = int(input()) a = [] for i in range(n): a += [int(input())] alpha, omega = 1, 10**18 while alpha < omega: mid = (alpha + omega + 1) // 2 total = k*mid ...
WOQL_CONCAT_JSON = { "@type": "Concatenate", "list": {"@type" : "DataValue", "list" : [ {"@type": "DataValue", "variable": "Duration"}, { "@type": "DataValue", "data": {"@type": "xsd:string", "@value": " yo "}, ...
class GeneralizationSet: name = "" id = "" attributes = [] def __init__(self, name, gs_id, attributes): self.name = name self.id = gs_id self.attributes = attributes def __str__(self): return f'id:{self.id} name: {self.name} attributes: {self.attributes}'
"""igcommit - The main module Copyright (c) 2021 InnoGames GmbH Portions Copyright (c) 2021 Emre Hasegeli """ VERSION = (3, 1)
# # @lc app=leetcode id=32 lang=python3 # # [32] Longest Valid Parentheses # # @lc code=start class Solution: def longestValidParentheses(self, s: str) -> int: max_length = 0 left_count = right_count = 0 for i in range(len(s)): # left to right scan if s[i] == '(': ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumNumbers(self, root: TreeNode) -> int: if root == None: return 0 else: ...
########################################################################### # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/...
# Problem 1: Two Sum class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ # Given an array of integers, return indices of the two numbers such that they add up to a specific target. # You ...
a = 1.123456 b = 10 c = -30 d = 34 e = 123.456 f = 19892122 # form 0 s = "b=%i" % b print(s) # form 1 s = "b,c,d=%i+%i+%i" % (b,c,d) print(s) # form 2 s = "b=%(b)i and c=%(c)i and d=%(d)i" % { 'b':b,'c':c,'d':d } print(s) # width,flags s = "e=%020i e=%+i e=%20i e=%-20i (e=%- 20i)" % (e,e,e,e,e) print(s)
#!/usr/bin/Anaconda3/python # -*- coding: utf-8 -*- class Board(object): """ Board 黑白棋棋盘,规格是8*8,黑棋用 X 表示,白棋用 O 表示,未落子时用 . 表示。 """ def __init__(self): """ 初始化棋盘状态 """ self.empty = '.' # 未落子状态 self._board = [[self.empty for _ in range(8)] for _ in range(8)] # 规格...
registry = [] def register(cls, bench_type=None, bench_params=None): registry.append((cls, bench_type, bench_params)) return cls
__author__ = "Bilal El Uneis and Jieshu Wang" __since__ = "Nov 2018" __email__ = "bilaleluneis@gmail.com" """ Meta Classes are the blue print for classes just like classes are blue print for types instantiated from them. they allow to set class capabilities. bellow is example: Meta Class To prevent inheritance of Clas...
# # PySNMP MIB module ASCEND-MIBUDS3NET-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBUDS3NET-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:12:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
vermelho = '\033[31m' verde = '\033[32m' azul = '\033[34m' #----------------------------- ciano = '\033[36m' magenta = '\033[35m' amarelo = '\033[33m' preto = '\033[30m' branco = '\033[37m' #----------------------------- original = '\033[0;0m' negrito = '\033[1m' reverso = '\033[2m' #----------------------------- fu...
class AppCredentials(object): def __init__(self, client_id, client_secret, redirect_uri): self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri
# * T<=11, n<=10, c_i<=10 # * มีชุดทดสอบ 10 ชุด ชุดละ 10 คะแนน # * 10 คะแนน: f(x) = ax^2 + c # * 10 คะแนน: f(x) = ax^2 + bx + c # * 30 คะแนน: T<=4, n<=3 # * 50 คะแนน: ไม่มีเงื่อนไขเพิ่มเติม def useGenerator(gen): gen("s1", "sample1", 2, 2) gen("s2", "ssss", 3, 2) gen(1, "deg 2 pls", 2, 2) gen(2, "seed...
s=str(input()) n1,n2=[int(e) for e in input().split()] count=0 count2=1 for i in range(n1): print(s[i],end="") for i in range(n2-n1+1): print(s[n2-count],end="") count+=1 for i in range(len(s)-n2-1): print(s[n2+count2],end="") count2+=1
# 28. Implement strStr() class Solution(object): # brute-force 1 def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ lh , ln = len(haystack), len(needle) if ln == 0: return 0 for i in range(lh - ln + 1): ...
# # PySNMP MIB module DLGHWINF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLGHWINF-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:47:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
primeiraNota = float(input('Informe a primeira nota: ')) segundaNota = float(input('Informe a segunda nota: ')) media = (primeiraNota + segundaNota) / 2 if 9 <= media <= 10: conceito = 'A' situacao = 'APROVADO' elif 7.5 <= media <= 9: conceito = 'B' situacao = 'APROVADO' elif 6 <= media <= 7.5: ...
class Pricing(object): def __init__(self, location, event): self.location = location self.event = event def setlocation(self, location): self.location = location def getprice(self): return self.location.getprice() def getquantity(self): return self.location.getqua...
class Solution(object): def sub_two(self, a, b): if a is None or b is None: raise TypeError('a or b cannot be None') result = a ^ b borrow = (~a & b) << 1 if borrow != 0: return self.sub_two(result, borrow) return result
class Plan(): """ This is a class for the plans. """ def __init__(self, name, price, limit): """ The constructor for the Subscription class. Parameters: name (str): The plan name. price (int): The plan price. limit (int): Allowed nuber of websi...
# write a function that accepts a name as input and # prints out "Hello {name}!" def greeting(name): print("Hello " + name + "!") greeting("Alfred")
class MetaGetter: def __init__(self, context): self.__context = context def render_width_px(self): original_width = self.__context.scene.render.resolution_x return int(original_width * self.__render_size_fraction()) def render_height_px(self): original_height = self.__context.scene.render.resolution_y r...
# 024 - Write a Python program to test whether a passed letter is a vowel or not. def vowelLetter(pLetter): return pLetter.upper() in 'AEIOU' print(vowelLetter('A')) print(vowelLetter('B'))
def extractTandQ(item): """ T&Q """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None bad = [ '#K-drama', 'fashion', 'C-Drama', '#Trending', 'Feature', '#Trailer', '#Eng Sub', 'M...
class IntervalStats: def __init__(self) -> None: self.interval_duration = 0.0 self.rtt_ratio = 0.0 self.marked_lost_bytes = 0 self.loss_rate = 0 self.actual_sending_rate_mbps = 0 self.ack_rate_mbps = 0 self.avg_rtt = 0.0 self.rtt_dev = 0.0 sel...
nome = str(input('Digite seu nome completo: ')) nome = nome.strip() print('Seu nome é {}'.format(nome)) print('O seu nome com todas as letras maiúsculas é: {}'.format(nome.upper())) print('O seu nome com todas as letras minúsculas é: {}'.format(nome.lower())) n1 = nome.split() print('Seu nome completo tem {} letras!'.f...
velhomasc = '' listmasc = [] media = 0 mulheres = 0 for c in range(1, 5): print('-' * 5, f'{c}º PESSOA', '-' * 5) nome = str(input('Nome: ')) idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')).upper().strip() media += idade if sexo == 'M': listmasc += [idade] velhoma...
# Python3 Total Ways to arrange coins {1, 3, 5} to Sum Upto N # Using Recursion def Arrangement(N): if N < 0: return 0 if N == 0: return 1 return Arrangement(N-1) + Arrangement(N-3) + Arrangement(N-5) # Using DP dp = [None for _ in range(10001)] def Arrangement_DP(n): if n < 0: return 0 if n == 0: retur...
def ex2(): rs = np.random.RandomState(112) x=np.linspace(0,10,11) y=np.linspace(0,10,11) X,Y = np.meshgrid(x,y) X=X.flatten() Y=Y.flatten() weights=np.random.random(len(X)) plt.hist2d(X,Y,weights=weights); #The semicolon here avoids that Jupyter shows the resulting arrays
"""Module with util funcs for testing.""" def assert_raises(exception, func, *args, **kwargs) -> None: """Check whether calling func(*args, **kwargs) raises exeption. Parameters ---------- exception : Exception Exception type. func : callable Method to be run. """ try:...
def change_data(x): if x < 0 or x >255: return None elif 200 <= x <=255: return int(round((x - 200) * 3 / 11.0 + 85, 0)) elif 0 <= x <=130: return int(round(x * 6 / 13.0, 0)) else: return int(round((x - 131) * 23 / 68.0 + 61, 0)) if __name__ == '__main__': print('-1...
n, x = map(int, input().split()) s = str(input()) for e in s: if e == "o": x += 1 else: x -= 1 if x < 0: x = 0 print(x)
cont = soma = 0 while True: nota = float(input()) if nota < 0 or nota > 10: print('nota invalida') else: soma += nota cont += 1 if cont == 2: break print('media = {}'.format(soma / cont))
template = """ /**************************************************************************** * ${name}.sv ****************************************************************************/ module ${name}( ${ports} ); ${wires} ${port_wire_assignments} ${interconnects} endmodule """
src = Split(''' awss.c enrollee.c sha256.c zconfig_utils.c zconfig_ieee80211.c wifimgr.c ywss_utils.c zconfig_ut_test.c registrar.c zconfig_protocol.c zconfig_vendor_common.c ''') component = aos_component('ywss', src) component.add_macros('DEBUG') ...
numeros = [] while True: x = int(input('Digite um valor:')) if x not in numeros: numeros.append(x) else: print(f'O Numero digitado {x} já esta na lista e não será incluido!') stop = str(input('Deseja continuar? [S/N]')).upper().strip()[0] while stop not in 'SN': stop = str(i...
#!/usr/bin/env python # coding: utf-8 # # **Estruturas de controle condicionais** # # > São estruturas para controlar o fluxo do programa # # Vamos utilizar os famosos SE e SENÃO. # # Em Python a estrutura é bem simples, comparado a outras linguagens, mas antes considere esse fluxograma: # # ![untitled.png](data:i...
class Settings: base_url = "https://compass.scouts.org.uk" date_format = "%d %B %Y" # dd Month YYYY org_number = 10000001 total_requests = 0 wcf_json_endpoint = "/JSon.svc" # Windows communication foundation JSON service endpoint web_service_path = base_url + wcf_json_endpoint
def say_hello(): return "hello"
def searchRange(nums, target): start, end = -1, -1 lo, hi = 0, len(nums)-1 while lo <= hi: mid = (lo+hi)//2 if nums[mid] == target and (mid == 0 or nums[mid-1] != target): start = mid break elif nums[mid] < target: lo = mid+1 ...
start,end=input().split() edges=[("ab",1),("ac",1),("be",3),("cd",1),("de",1),("df",2),("eg",1),("fg",1),("ba",1),("ca",1),("eb",3),("dc",1),("ed",1),("fd",2),("ge",1),("gf",1)] paths=[(start,0)] while True: new_paths=paths for (path,T) in paths: for (edge,t) in edges: if path[-1]==edge[0] a...
# OpenWeatherMap API Key weather_api_key = "972fc242a771ca44611f48d634a9e967" # Google API Key g_key = "AIzaSyCWD-Z7WINc53d-5orJ46Zg3qVZN1UK0ho"
class ListNode: def __init__(self,x): self.val = x self.next = None class Solution: def hasCycle(self,head): # type head: ListNode # rtype: bool fast, slow = head, head while fast and fast.next: fast = fast.next.next slow = slow.next ...
#Exercicio 50 s = 0 for c in range(1, 7): n = int(input(f'Escolha o {c}° número: ')) if n % 2 == 0: s = s + n print(f'A soma entre os números pares entre esses números escolhidos vai ser igual a {s}')
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): num = A[0] for number in A[ 1 : ]: num = num ^ number return num
def count_3_in_time(n): # 00:00:00 ~ n:59:59 count = 0 for hrs in range(0, n + 1): for min in range(0, 60): for sec in range(0, 60): if -1 != str(hrs).find('3') or -1 != str(min).find('3') or -1 != str(sec).find('3'): count += 1 return count de...
# Given a binary tree, return all root-to-leaf paths. # Note: A leaf is a node with no children. # Example: # Input: # 1 # / \ # 2 3 # \ # 5 # Output: ["1->2->5", "1->3"] # Explanation: All root-to-leaf paths are: 1->2->5, 1->3 # Definition for a binary tree node. # class TreeNode(object): # def...
def last_index(pattern): wave_list = pattern.wave_list number_of_elements = len(wave_list) return number_of_elements
def code(st, syntax = ""): return f"```{syntax}\n{st}```" def md(st): return code(st, "md") def diff(st): return code(st, "diff")
class AuthStatusError(Exception): """ Auth status error """ pass
def IDW(Z, b): """ Inverse distance weighted interpolation. Input Z: a list of lists where each element list contains four values: X, Y, Value, and Distance to target point. Z can also be a NumPy 2-D array. b: power of distance Output Estimated value at the target l...
""" Query ===== This is the query package. """
def maxSum(a, b, k, n): a.sort() b.sort() i = 0 j = n - 1 while i < k: if (a[i] < b[j]): a[i], b[j] = b[j], a[i] else: break i += 1 j -= 1 sum = 0 for i in range (n): sum += a[i] return(sum) ...
def aumentar(n=0, porc=0): """ -> Calcula o aumento de um valor, utilizando porcentagem pré-determinada :param n: (opcional) Número a ser aumentado :param porc: (opcional) Porcentagem a ser utilizada :return: (opcional) Retorna 'n' mais 'porc' porcento, ex: 10 + 20% """ return n * (1 + porc/...
def fib(n): first=0 second=1 overall=0 if n==0: return 0 elif n==1: return 1 else: for i in range(1,n): overall=second+first first=second second=overall return overall def productFib(num): n=1 append_array=[] while T...
number = 600851475143 def isPrime(n): for i in range(2, n): if n % i == 0 and i != n: return False return True def LargestPrimeFactor(n): _n, lpf = n, 0 for i in range(2, n): if isPrime(i) and n % i == 0: _n, lpf = _n/i, i print(i, end=', ') ...
""" This file provides all error codes for the program. """ ERR_OK = 0 WARN_OK = 0 ERR_MISSING_ARGUMENT = 100 ERR_MISMATCHED_FORMAT = 101 ERR_MISMATCHED_PLATFORM = 102 ERR_UNKNOWN_PLATFORM = 103 ERR_MISMATCHED_ARGUMENT = 104 ERR_UNKNOWN_ARGUMENT = 105 WARN_IMPLICIT_FORMAT = 200 WARN_MODULE_NOT_FOUND = 201 WARN_MOD_...
# Title : TODO # Objective : TODO # Created by: Wenzurk # Created on: 2018/2/5 # for value in range(1,5): # print(value) # for value in range(1,6): # print(value) numbers = list(range(1,6)) print(numbers)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Решите задачу: создайте словарь, связав его с переменной school , и наполните данными, # которые бы отражали количество учащихся в разных классах (1а, 1б, 2б, 6а, 7в и т. п.). # Внесите изменения в словарь согласно следующему: а) в одном из классов изменилось # коли...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Jinyuan Sun # @Time : 2022/3/31 6:17 PM # @File : aa_index.py # @annotation : define properties of amino acids ALPHABET = "QWERTYIPASDFGHKLCVNM" hydrophobic_index = { 'R': -0.9, 'K': -0.889, 'D': -0.767, 'E': -0.696, 'N': -0....
class DefaultTokenizer: def __init__(self, prefixes, suffixes, infixes, exceptions): self.prefixes = prefixes self.suffixes = suffixes self.infixes = infixes self.exceptions = exceptions def __call__(self, text: str): return text.split(" ")
for i in range(1, 21): if i % 3 == 0: print("Fizz") else: print(i)
cutoff = 20 decision_cutoff = .25 model_path = 'ml/overwatch_messages.model' vectorizer_path = 'ml/overwatch_messages.vectorizer'
#!/usr/bin/env python # __author__ = "Ronie Martinez" # __copyright__ = "Copyright 2019-2020, Ronie Martinez" # __credits__ = ["Ronie Martinez"] # __maintainer__ = "Ronie Martinez" # __email__ = "ronmarti18@gmail.com" def calculate_amortization_amount(principal, interest_rate, period): """ Calculates Amortiza...
def clean_xml_indentation(element, level=0, spaces_per_level=2): """ copy and paste from http://effbot.org/zone/elementent-lib.htm#prettyprint it basically walks your tree and adds spaces and newlines so the tree is printed in a nice way """ i = "\n" + level*spaces_per_level*" " if len(ele...
# -*- coding: utf-8 -*- """Top-level package for dsn_3000.""" __author__ = """Shannon-li""" __email__ = 'lishengchen@mingvale.com' __version__ = '0.1.0'
# # PySNMP MIB module Juniper-SUBSCRIBER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-SUBSCRIBER-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:01:13 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
#input # 69 237 245 22 97 105 68 243 232 209 177 72 161 199 237 218 206 122 209 100 79 226 195 202 160 238 106 99 118 57 68 68 53 65 240 230 160 99 208 64 118 210 232 244 119 178 69 224 146 87 104 237 232 204 227 75 65 162 90 75 64 133 75 225 238 160 204 54 14 196 121 78 72 240 89 237 145 108 244 179 102 54 32 160 53 8...
def trapes_areal(sideEn=float, sideTo=float, høyde=float): """ Returnerer arealet til et trapes """ return abs(( ( sideEn+sideTo ) * høyde ) / 2) def array(array): ''' Returnerer arealet til array ''' A = 0 bredde = 1 for i in range(0, len(array)-1): A += trapes_areal( a...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: # root and current node cur = ro...
def proc(command, message): return { "data": { "text": "Your command was not recognised. Type 'help' to read the list of all available commands." }, "response_required": True }
A, B, C = input().split() A = int(A) B = int(B) C = int(C) if(A < B and A < C and B < C): a = C b = B c = A elif(A < B and A < C and C < B): a = B b = C c = A elif(B < A and B < C and A < C): a = C b = A c = B elif(B < A and B < C and C < A): a = A b = C c = B e...
"""Ordered List impelementation.""" class Node(object): """Node class.""" def __init__(self, initdata=None): """Initialization.""" self.data = initdata self.next = None def getData(self): """Get node's data.""" return self.data def setData(self, data): ...
print('******* Bem vindo a aula 13 *********') n = int(input('Informe um número')) for c in range(0, n): print(c) print('Fim') for c in range (0, 6, 2): print(c) print('Fim')
for _ in range(int(input())): s = input() f,l,r = 0,0,0 for i in range(len(s) - 1): if(s[i] == s[i + 1]): f = 1 l = i break for i in range(len(s) - 1,0,-1): if(s[i] == s[i - 1]): # print(i) f = 1 r = i break if s[0] == s[len(s) - 1]: f = 1 if f == 0:print('yes') elif(len(s) % 2 != 0): pr...
""" tells the bot to join the [params] channel """ class Command: owner_command = True def run(self): self.response = f"attempting to join {self.params}" self.raw_send = "JOIN " + self.params
def solution(n, delivery): answer = '' ans_list = [] for i in range(n): ans_list.append('?') for de in delivery: if(de[2] == 1): ans_list[de[0] -1] = 'O' ans_list[de[1] -1] = 'O' for de in delivery: if(de[2] == 0): if(ans_list[de[0] -1 ] =...
# def summation(num): # pos = 0 # while (num > 0): # pos += num # print(pos) # num -= 1 # print(num) # return pos # # Code here def summation(num): pos = 0 for num in range(1,num + 1): pos += num print(num) return p...
def somar(a=0,b=0,c=0): s=a+b+c return s def main(): #print(somar(3,4,5)) r1 = somar(3,4,5) r2 = somar(1,7) r3 = somar(4) print('RESULTADOS: ',r1,r2,r3) main()
def tf_io_copts(): return ( [ "-std=c++11", "-DNDEBUG", ] + select({ "@bazel_tools//src/conditions:darwin": [], "//conditions:default": ["-pthread"] }) )
def nb_post_fix(rtl_log_f,rtl_log,nb_log): ''' Replaces non-blocking load results in rd of trace log. Sees time/CycleCnt at which non-block load is written back to gpr, checks from that time/CycleCnt backwards, where this gpr was written in trace log, replaces the result in rd (also load) at that instru...
# a place to hold event type constants used among many data models, rules, or policies ADMIN_ROLE_ASSIGNED = "admin_role_assigned" FAILED_LOGIN = "failed_login" MFA_DISABLED = "mfa_disabled" SUCCESSFUL_LOGIN = "successful_login" SUCCESSFUL_LOGOUT = "successful_logout" USER_ACCOUNT_CREATED = "user_account_created" # ACC...
# # PySNMP MIB module WebGraph-AnalogIO-57662-US-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WebGraph-AnalogIO-57662-US-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:32:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
#!/usr/bin/env python PART1SOL = 388611 PART2SOL = 27763113 # Right on the first try! def part1(x): count = 0 loc = 0 while True: try: dat = x[loc] except IndexError: return count count += 1 x[loc] += 1 loc += dat # 137 too low # 169 too ...
''' This problem was recently asked by AirBNB: Given a sorted array, A, with possibly duplicated elements, find the indices of the first and last occurrences of a target element, x. Return -1 if the target is not found. Example: Input: A = [1,3,3,5,7,8,9,9,9,15], target = 9 Output: [6,8] Input: A = [100, 150, 150, 1...
#!/usr/bin/env python # encoding: utf-8 ''' @author: Jason Lee @license: (C) Copyright @ Jason Lee @contact: jiansenll@163.com @file: jianzhi_offer_28.py @time: 2019/3/26 18:26 @desc: 字符串的排列: 输入一个字符串,按字典序打印出该字符串中字符的所有排列。 例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 ''' def Permutation(str): ...
# -*- coding: utf-8 -*- """ Created on Tue Mar 31 08:21:14 2020 @author: Shivadhar SIngh """ def sum_odd_digits(number): dsum = 0 # only count odd digits while number > 0: # add the last digit to the sum digit = number % 10 if digit % 2 != 0 : dsum = dsum + digit # ...
def foo(a, b): return a * b foo(1, 2) ## OK foo(1) ## error: wrong number of arguments
""" Questão #4 Vale 20 Enunciado Faça uma função que receba uma lista que contém números inteiros positivos e textos. Retorne uma lista em que os primeiros elementos são os números pares ordenados em ordem crescente, seguidos pelos textos sem ordenação específica e depois pelos ímpares ordenados em ordem decrescente....
# 7. Sa se scrie o functie care primeste ca parametri un numar x default egal cu 1, # un numar variabil de siruri de caractere # si un flag boolean setat default pe True. # Pentru fiecare sir de caractere, sa se genereze o lista care sa contina caracterele care au codul ASCII divizibil cu x # in caz ca flag-ul este...
#!/usr/bin/python # ENVIRONMENT / WORLD DEFINITIONS class world(object): def __init__(self): return def get_outcome(self): print("Abstract method, not implemented") return def get_all_outcomes(self): outcomes = {} for state in xrange(self.n_states): fo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __project__ = 'leetcode' __file__ = '__init__.py' __author__ = 'king' __time__ = '2020/1/9 13:28' _ooOoo_ o8888888o 88" . "88 (| -_- |) ...
def common_code(tipoInt, txt): """ Função usada para tipos numéricos inteiros ou flutuantes. :param tipoInt: padrão para tipo inteiro :param txt: mensagem a ser utilizada no input de 'n' :return: retorna n """ while True: try: if tipoInt: n = int(input(tx...
"""Status Messeges string formats.""" FLIGHT_RECORD_NOT_FOUND = "File: {filename} not found" # TODO: Add a link to upload new files once endpoint to upload files implemented. FLIGHT_RECORDS_EXISTING = """ Available flight records:\n{flight_records} """