content
stringlengths
7
1.05M
data = { "nouns" : #['nouns'][0] {"example" : #['nouns'][0][0] ["plural form", #['nouns'][0][1] ["tags"], #['nouns'][0][2] ["synonyms"], #['nouns'][0][3] "usage ranking"], "cat" : ["ca...
def balance(): i01.setHeadSpeed(0.95,0.95) i01.setArmSpeed("left",1.0,0.85,0.95,0.95) i01.setArmSpeed("right",0.65,0.85,0.65,0.85) i01.setHandSpeed("left",0.85,0.85,0.85,0.85,0.85,0.85) i01.setHandSpeed("right",0.85,0.85,0.85,0.85,0.85,0.85) i01.setTorsoSpeed(0.95,0.85,1.0) i01.moveHead(79,1...
# Curso Python 13 # ---Desafio 49--- # Refaça o Desafio 009, mostrando a tabuada de um número # que o usuário escolher, só que agora utilizando um laço for. n = int(input('Deseja ver a tabuada de qual número? ')) for c in range(0, 11): print(f'{n} x {c} = {n*c}')
"""Day 1 Part Two. Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on. For example: ) causes him to enter the basement at character posi...
def openfile_returnlist(csvfilename): with open(csvfilename) as f: x=[] for line in f: # last character is a \n x.append(line[:-1].split("\t")) return x if __name__ == "__main__": mylist = openfile_returnlist("data/brands_filtered.txt") print(mylist[0:2])
sigfox_hexa = 0x21134464D0A00500C01C8C01 lenght = 96 bin_host, bin_network = '', '' def bin_format(sigfox_hexa, lenght): return f'{sigfox_hexa:0>{lenght}b}' # def bin_protocol('sigfox_bin'): # for i in range(96): # if i <= 3: # bin_host = bin_host + sigfox_bin[i] # elif i <= 7: # ...
def main(): X = int(input()) if X<40: print(40-X) elif X<70: print(70-X) elif X<90: print(90-X) else: print("expert") if __name__ == '__main__': main()
# solution to a kata on codewars # https://www.codewars.com/kata/exes-and-ohs/python # idea is to determine whether there is an # equal number of "x" and "o" in a string # (count the total of both upper and lower case) def xo(s): return s.lower().count('x') == s.lower().count('o')
student_grades = { 'Joe': [90, 95, 87, 99], 'Sally': [97, 92, 90, 100], 'Mark': [80, 83, 72, 89] } student_grades_avg = {} def calc_avg(scores): avg = sum(scores) / len(scores) return avg for student, scores in student_grades.items(): student_grades_avg[student] = calc_avg(scores) prin...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def convertBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ # Input:...
class Position: def __init__(self, x, y): self.x = int(x) self.y = int(y) def move(self, x, y): self.x += x self.y += y def __str__(self): return "X: " + str(self.x) + ", Y: " + str(self.y) def count_trees_for_movement_pattern(field, step_x, step_y): ...
''' We can also store a number of objects inside a list or a dictionary. The below example, we have a list of mobile objects and we are iterating over the list and printing the values ''' class Mobile: def __init__(self, brand, price): self.brand = brand self.price = price mob1=Mobile("Apple", 10...
# Copyright (C) 2018 DataArt # # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
fruits = ['grape', 'raspberry', 'apple', 'banana'] # sorted并不会改变原来对象 print(sorted(fruits)) print(fruits) # reverse sorted print(sorted(fruits, reverse=True)) # key sorted print(sorted(fruits, key=len)) # key and reverse sorted print(sorted(fruits, key=len, reverse=True)) # list.sort(),会改变对象原本顺序 print(fruits.sort()...
def Miladi_to_Shamsi(y, m, d): g_d_m = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] if (m > 2): y2 = y + 1 else: y2 = y days = 355666 + (365 * y) + ((y2 + 3) // 4) - ((y2 + 99) // 100) + ((y2 + 399) // 400) + d + g_d_m[m - 1...
X = int(input()) if X%2 == 0: X += 1 for k in range(X,X+12,2): print(k)
# Time: O(n) # Space: O(1) class Solution(object): def minSwaps(self, s): """ :type s: str :rtype: int """ def cost(s, x): diff = 0 for c in s: diff += int(c) != x x ^= 1 return diff//2 ones ...
def tag(name, *content, cls=None, **attrs): """Generate one or more HTML tags, from Fluent Python, page 155""" if cls is not None: attrs['class'] = cls if attrs: attr_str = ''.join(f' {attr}="{value}"' for attr, value in sorted(attrs.item...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ ret =...
# Rename settings_sample.py to settings.py # Generate jss_credentials with: # printf "username:password" | iconv -t ISO-8859-1 | base64 -i - jss_server = "YOUR_JAMF_PRO_URL" jss_credential = "YOUR_CREDENTIALS" attributes = { "extension_attributes": [ { "id": 32, # Extenss...
class Person: def __init__(self): self.fname = 'Alex' self.lname = 'Prodan' self.age = 25 def __repr__(self): return f'Person(fname={self.fname}, lname={self.lname}, age={self.age})' def __str__(self): return f'{self.fname} {self.lname} {self.age}' def __byte...
test = { 'name': 'lab1_p2a', 'suites': [ { 'cases': [ { 'code': r""" >>> # It looks like your variable is not named correctly. >>> # Remember, we want a boolian variable that starts with somenum_ >>> 'somenum_bool' in vars() True """ ...
# Task 1 class StatePool: def __init__(self): self.__states = {} def get_instance(self, cls): if cls not in self.__states: self.__states[cls] = cls() return self.__states[cls] # Task 2 class HeroState: __state_pool = StatePool() @classmethod def get_instance...
for _ in range(int(input())): a=input() r=input() for i in a: if ord('A') <= ord(i) <= ord('Z'): print(r[ord(i)-ord('A')],end="") else: print(i,end="") print()
"""Dummy class that does not have MotionDetection class.""" class motiondetection: """Dummy class that does not have MotionDetection class.""" pass
# # PySNMP MIB module CISCO-VOICE-DIAL-CONTROL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-DIAL-CONTROL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:03:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
""" entradas venta1->float->v1 venta2->float->v2 venta3->float->v3 sueldobase->float->SB salidas comision->float->c sueldototal->float->sueldototal """ #entradas v1=float(input("digite la venta 1 " )) v2=float(input("digite la venta 2 " )) v3=float(input("digite la venta 3 " )) sueldobase=float(input("digite el sueldo...
# # PySNMP MIB module SIAE-RABR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file://./sm_rabr.mib # Produced by pysmi-0.3.2 at Fri Jul 19 08:41:38 2019 # On host 0e190c6811ee platform Linux version 4.9.125-linuxkit by user root # Using Python version 3.7.3 (default, Apr 3 2019, 05:39:12) # OctetString, ObjectIdenti...
url = "bytebank.com/cambio?quantidade=100&moedaOrigem=real&moedaDestino=dolar" indice_interrogacao = url.find('?') url_base = url[:indice_interrogacao] url_parametros = url[indice_interrogacao+1:] parametro_busca = 'quantidade' indice_parametro = url_parametros.find(parametro_busca) indice_valor = indice_parametro + ...
# # 1 # # 1 2 # # 1 2 3 n = int(input("Enter value of n:")) for i in range(0, n): for j in range(0, i+1): print(j+1, end=" ") print() # # 1 # # 2 2 # # 3 3 3 n = int(input("Enter value of n:")) for i in range(1, n+1): print((str(i)+' ')*i) # # WAP print prime numbers fromm 2 to 50. c = 0 for i i...
# Copyright (c) 2018, Lehrstuhl fuer Angewandte Mechanik, Technische # Universitaet Muenchen. # # Distributed under BSD-3-Clause License. See LICENSE-File for more information # """ Module contains eigensolvers """
# see https://www.codewars.com/kata/5a262cfb8f27f217f700000b/solutions/python def solve(a,b): r1 = "".join(x for x in a if x not in b) r2 = "".join(x for x in b if x not in a) return r1+r2 print(solve("xyab","xzca") == "ybzc") print(solve("xyabb","xzca") == "ybbzc") print(solve("abcd","xyz") == "abcdxyz")...
def maximo(x, y, z): if x > y and x > z: return x if y > x and y > z: return y else: return z
# Aufgabe 2 - Übung 2 # # Erstellen Sie ein Python-Programm mit den folgenden Anforderungen: # Es soll aus einem eingegebenen Nettobetrag die 19% Mehrwertsteuer und der Bruttobetrag errechnet und angezeigt werden. # 1. Statische Variablen festlegen mwst = 0.19 # 2. Nutzereingabe erfassen und in float umwandeln netto...
#!/usr/bin/env python3 toomer_bio = """ Nathan Pinchback Tomer, who adopted the name Jean Tomer early in his literary career, was born in Washington, D.C. in 1894. Jean is the son of Nathan Tomer was a mixed-race freedman, born into slavery in 1839 in Chatham County, North Carolina. Jean Tomer is most well known for ...
class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Encountered a start tag:", tag) def handle_endtag(self, tag): print("Encountered an end tag :", tag) def handle_data(self, data): print("Encountered some data :", data)
def raw_to_libsvm(ofile, store, full_first_header=False): """Write a raw store to libsvm format :param ofile: file like object to write to :param store: the raw store :param full_first_header: Write the full first line regardless of sparseness """ for idx,data in enumerate(store): ...
#py_function_1.py # Globals namespace STAR = "Sirius" # Polaris Favorites = [ ] X = 100 def setStar(name): "Local namespace" #remove comment to map to global namespace #global STAR STAR = name Favorites.append(name) print("STAR: ", STAR) setStar("Polaris") print("STAR: ", STAR)
# -*- coding: utf-8 -*- xpath_list = [ { "name": "行政区:", 'key': "region", "expr": ["//div[@id='p1']//td/span[contains(text(),'行政区:')]/parent::td/following-sibling::td[1]/span/text()", "//span[@id='mainModuleContainer_1855_1856_ctl00_ctl00_p1_f1_r1_c2_ctrl']/text()"] }, ...
# tests transition from small to large int representation by addition # 31-bit overflow i = 0x3fffffff print(i + i) print(-i + -i) # 63-bit overflow i = 0x3fffffffffffffff print(i + i) print(-i + -i)
#!/usr/bin/env python3 class Noisy: ''' Makes noise when you get or set attributes ''' def __getattribute__(self, name): ''' Always called on attribute reads. Overidding this method properly is difficult so you should usually define __getattr__ if you want to handle ...
def resolve(): ''' code here ''' N = int(input()) D, X = [int(item) for item in input().split()] As = [int(input()) for _ in range(N)] cnt = 0 for i in range(N): day = 1 while day <= D: day +=As[i] cnt +=1 print(cnt+X) if __name__ == "__ma...
class Solution: def maxArea(self, height: List[int]) -> int: maxx = 0 l = 0 r = len(height)-1 while l<r: maxx = max(maxx,min(height[l],height[r])*(r-l)) if height[l]<height[r]:l+=1 else:r-=1 return maxx
# /usr/bin/env python3 # encoding: utf-8\ class ListNode(object): def __init__(self, item): self.val = item self.next = None class Solution: def addTwoNumbers(self, l1, l2): ''' :param l1: :param l2: :return:listNode ''' result = ListNode(0) ...
class PlantContent: def add_column(self, in_column_name: str, in_column_type: str): if in_column_name not in self.columns: self.columns[in_column_name] = in_column_type def add_foreign_key(self, in_foreign_key_name: str, in_foreign_key_entity: str): if in_foreign_key_name not in se...
number_of_students = int(input()) all_students = {} all_students_high_score = {} # adding all students + grades in dictionary for current_student in range(number_of_students): student = input() grade = float(input()) all_students.setdefault(student, []).append(grade) # calculating average grade for k, v ...
# -*- coding: utf-8 -*- __all__ = ( "Config", ) class Config(object): DEBUG = True TEMPLATES_AUTO_RELOAD = True
MALE_WORDS = ['he', 'him', 'his'] FEMALE_WORDS = ['she', 'her'] min_length = 10 def preprocess(text): return text.lower().split(' ') def predict(text): m = 0 f = 0 preprocessed = preprocess(text) for word in MALE_WORDS: if word.lower() in preprocessed: m += 1 for wor...
class Solution: def isInterleave(self, s1, s2, s3): l1 = len(s1) l2 = len(s2) l3 = len(s3) if l1 == l2 == l3 == 0: return True if l1 == 0: return s2 == s3 if l2 == 0: return s1 == s3 if l1 + l2 != l3: return F...
the_count = [1,2,3,4,5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print(f"This is count {number}") # same as above for fruit in fruits: print(f"A fruid of type: {fruit}") # ...
#!/usr/bin/python3 BOT_OAUTH = '' CLIENT_ID = '' CLIENT_SECRET = '' CHANNEL = 'botdev'
class Solution: def naive(self,root): self.count = Counter() self.nodes = {} def recur(tree): if tree==None: return (None,) left = recur(tree.left) right = recur(tree.right) branch = (tree.val,)+left+right self.count...
''' @author: Dallas Fraser @date: 2016-04-12 @organization: MLSB API @summary: The package containing all the basic methods '''
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/12/12 下午5:26 # @Title : 538. 把二叉搜索树转换为累加树 # @Link : https://leetcode-cn.com/problems/convert-bst-to-greater-tree/ QUESTION = """ 给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree) 使得每个节点的值是原来的节点值加上所有大于它的节点值之和 例如: 输入: 二叉搜索树: 5 ...
# Consonant Count # Have the function ConsonantCount(str) take the str string parameter being passed and return the number of consonants the string contains. # Examples # Input: "Hello World" # Output: 7 # Input: "Alphabets" # Output: 6 def ConsonantCount(strParam): array = ["b", "c", "d", "f", "g", "h", "j", "k",...
""" Во входном файле задана расстановка кораблей при игре в морской бой на поле 10×10 клеток в виде десяти строк символов. Пустое поле кодируется точкой, а поле, представляющее часть корабля, кодируется звёздочкой. Подсчитать количество кораблей, расставленных на поле. Замечание. Все корабли имеют форму прямоугол...
# Generated by gencrud # field role_access.RA_CREATE constants C_RA_CREATE_MAPPING = {True: 'Yes', False: 'No'} # field role_access.RA_READ constants C_RA_READ_MAPPING = {True: 'Yes', False: 'No'} # field role_access.RA_UPDATE constants C_RA_UPDATE_MAPPING = {True: 'Yes', False: 'No'} # field role_access.RA_DE...
num1 = 10 num2 = 20 num3 = 30 num4 = 40
# define x to the power of p def iterativePower(x, p): result = 1 for a in range(p): result = result * x return result
OCI_IMAGE_MANIFEST_CONTENT_TYPE = "application/vnd.oci.image.manifest.v1+json" OCI_IMAGE_INDEX_CONTENT_TYPE = "application/vnd.oci.image.index.v1+json" OCI_IMAGE_CONFIG_CONTENT_TYPE = "application/vnd.oci.image.config.v1+json" OCI_IMAGE_TAR_LAYER_CONTENT_TYPE = "application/vnd.oci.image.layer.v1.tar" OCI_IMAGE_TAR_GZ...
def binary_search(arr, tn): low = 0 high = len(arr) - 1 while low <= high: m = int((high - low) / 2) + low if arr[m] == tn: return m else: if arr[m] < tn: low = m + 1 else: high = m - 1 if low > high: r...
def Mideng(li): if(type(li)!=list): return if(len(li)==1): return [li] result=[] for i in range(0,len(li[:])): bak=li[:] head=bak.pop(i) #head of the recursive-produced value for j in Mideng(bak): j.insert(0,head) result.append(j) return result def MM(n): if(type(n)!=int or n...
#%% [markdown] ## Strings (parte 1) dir(str) nome = 'Victor Mello' nome #Acessando um caracter de uma string nome[0] # nome[0] = 'P' #Erro! Strings são imutáveis """OBS: quando se tem uma string cujo conteúdo já possui aspas simples, para evitar erro de sintaxe, tem-se 2 opções: 1) Delimitar a string com aspas du...
# Determine if String Halves Are Alike ''' You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half. Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s c...
#!/usr/bin/python # https://practice.geeksforgeeks.org/problems/count-ways-to-reach-the-nth-stair/0 def cal(): """ Trick is to calculate all in one go for the given limit of n """ dp = [0 for i in range(100001)] dp[0] = 1 dp[1] = 1 for i in range(2, 100001): dp[i] = (dp[i-1] + ...
# Your job is to find the gravitational force between two spherical objects (obj1 , obj2). # input # Two arrays are give : # arr_val (value array), consists of 3 elements # 1st element : mass of obj 1 # 2nd element : mass of obj 2 # 3rd element : distance between their centers # arr_unit (unit array), consists of 3 e...
lista = set() iloscPrzed = 0 with open('lista_zrobionych.txt', 'r', encoding='UTF-8') as plik: for nazwisko in plik: iloscPrzed += 1 lista.add(nazwisko.strip()) iloscPo = 0 with open('lista_zrobionych.txt', 'w', encoding='UTF-8') as plik: for nazwisko in lista: iloscPo += 1 plik....
# parsetab_re.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = b'\xe3\xf7\x1b^\x13\xcdAc\xfa\xaan\xef\x88\x91db' _lr_action_items = {'STAR':([3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,],[-7,...
def is_leap_year(year): return True if y % 4 != 0 or (y % 100 == 0 and y % 400 != 0) else False def correct(day, month, year): the_31_days = (1, 3, 5, 7, 8, 10, 12) if month < 13: if month in the_31_days: return True elif day > 29 and month != 2: return True ...
# -*- coding: utf-8 -*- # # This file is part of the ska-tmc-common project # # # # Distributed under the terms of the BSD-3-Clause license. # See LICENSE.txt for more info. """ ska-tmc-common """ # TODO: Work out imports and __all__ # from . import release # from tango_client import TangoClient # from tango_group_cl...
"""Tokens used by the lexer to tokenize LookML.""" class Token: """Base class for LookML tokens, lexed from LookML strings.""" id: str = "<base token>" value: str def __init__(self, line_number: int): """Initializes a Token. Args: line_number: The corresponding line in t...
house={'ling':{'chair':3,'desk':1,'pot':4}, 'jiamin':{'chair':5,'book':18,'cup':20}, 'soo':{'car':1,'chair':9,'desk':1}} def allHouse(houses,item): numItems=0 for p,i in houses.items(): numItems+=i.get(item,0) # print(p+str(i.get(item,0))) return numItems print('Number of prop...
# https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package # Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module __version__ = '1.0'
""" Multiple-method notifier :author: Matthew Farrugia-Roberts """ class MultiNotifier: def __init__(self, notifiers=None): if notifiers is not None: self.notifiers = notifiers else: self.notifiers = [] def add_notifier(self, notifier): self.notifiers.append(no...
""" Shared default parameters across the modules """ SIGNAL_TYPE = 'F/F0' # F-F0, F/F0, F-F0/F0 LINEAR_MODEL = 'ransac' # 'least_squares' or 'ransac' or 'exp_ransac' DATA_TYPE = 'ca' # one of 'ca', 'ephys' FILTER_ORDER = 1 # Order of the butterworth filter FILTER_CUTOFF = 4 # Hz cutoff for the filter MIN_STATS...
def get_api_params(): TwitterApiParams.__init__(TwitterApiParams,'x','xx','xx') return TwitterApiParams class TwitterApiParams(): def __init__( self,api_key,api_secret_key,bearer_token): self.api_key=api_key self.api_secret_key=api_secret_key self.bearer_token=bearer_token ...
class Solution: def XXX(self, root: TreeNode) -> int: # BFS,遇左右节点均为空打印退出 if not root: return 0 res = [] queque = [(1, root)] while queque: depth, first = queque.pop(0) if not first.left and not first.right: return depth ...
class Solution: def romanToInt(self, s: str) -> int: mydict = { "I":1, "IV":4, "V":5, "IX":9, "X":10, "XL":40, "L":50, "XC":90, "C":100, "CD":400, "D":500, "CM":900...
IDLE = 0 OFFLINE = 1 INGAME = 2 class User(object): def __init__(self, username, uid, point=0, status=IDLE): self.username = username self.uid = uid self.point = point self.status = status def ___str__(self): return '{} {} {} {}'.format(self.username, self.uid, self....
# Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Unit tests for L{twisted.protocols}. """
#!/usr/bin/python3 """Ultron - An EVE Online Discord Bot. Ultron is a Discord bot for EVE Online communities. Ultron is written in python, using v1.0.0 of the discord.py library.""" __version__ = "1.0.0a0" __author__ = "Sheppard" __maintainer__ = "Sheppard" __status__ = "Development"
""" Backup a DynamoDB to an Avro Container """ version = '1.0.0'
c = get_config() # noqa: F821 c.FileContentsManager.delete_to_trash = False # switch off CPU reporting c.NotebookApp.ResourceUseDisplay.track_cpu_percent = False # set a memory limit: 200MB c.NotebookApp.ResourceUseDisplay.mem_limit = 246579200 # set a disk limit: 500MB c.NotebookApp.ResourceUseDisplay.disk_limit ...
AUTHOR = 'Will Sorenson' # Location of the pelican Blog BLOG_DIR = '/Users/Will/Devel/tec_blog/' # Directory that posted notebooks should be moved to POSTED_DIR = '/Users/Will/Devel/blog_posts/posted/'
class AccuracyMetric: def __init__(self): self._good = 0 self._total = 0 def clear(self): self._good = 0 self._total = 0 def add(self, predicted_class_scores, target_classes): predicted_classes = predicted_class_scores.argmax(dim=1) self._good += (predicted...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 'args' at sumIntNumbers() is just a name (a tuple! Immutable), it can be anything else (ex: def sumIntNumbers(*numbers)) def sumIntNumbers(*args): ret = 0 #Erro #args[2] = 10 for i in args: ret += i return ret # 'kwargs' at concatenate() is just a name (a dic...
# create blank class print("creating empty class object") print() class A(object): pass # create hypothetical constructor print("defining class constructor") print("will set instance attribute \"a\"") print() def init(cls, a): print("initializing the instance") print() cls.__setattr__("a",a) # create new meth...
class AffineCipher: def __init__(self): """This is a python implementation of Affine Cipher""" pass @staticmethod def modinv(a: int, m: int): for x in range(1, m): if (((a%m) * (x%m)) % m == 1): return x return -1 @staticmethod def encryp...
""" Circle or Square Given the radius of a circle and the area of a square, return True if the circumference of the cirlce is greater than the square's perimeter and False if the square's perimeter is greater then the circumference of the circle. Examples circle_or_square(16, 625) ➞ True circle_or_square(5, 100) ➞ F...
#!/usr/bin/env python # coding=utf-8 ''' @Author: John @Email: johnjim0816@gmail.com @Date: 2020-07-21 10:26:10 @LastEditor: John @LastEditTime: 2020-07-21 10:29:03 @Discription: @Environment: python 3.7.7 ''' # Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ # Author : JohnJim0816 # Da...
def func(nums, target): length = len(nums) for i in range(length): j = i + 1 while j < length: if nums[i] + nums[j] == target: print("{}, {}".format(nums[i], nums[j])) j += 1 def find_insert(nums, target): length = len(nums) for i in range(length...
def Function(fun): def fun2(): print("start") fun() print("end") return fun2 @Function def fun3(): print("this is a arg function") fun3()
# MEDIUM # 1. count every node # 2. binary Search # class Solution: # def countNodes(self, root: TreeNode) -> int: # return self.dfs(root) # def dfs(self,root): # if not root: # return 0 # return self.dfs(root.left)+self.dfs(root.right) +1 clas...
a = [19.310344827586206, 19.597989949748744] b = [24.796747967479675, 9.0, 9.276018099547512, 6.329113924050633, 21.145374449339208, 19.615384615384617] c = a + b print(max(c)) print(min(c))
''' 29. O Sr. Manoel Joaquim possui uma grande loja de artigos de R$ 1,99, com cerca de 10 caixas. Para agilizar o cálculo de quanto cada cliente deve pagar ele desenvolveu um tabela que contém o número de itens que o cliente comprou e ao lado o valor da conta. Desta forma a atendente do caixa precisa apenas contar qua...
'''dado un numero entero, la funcion lo convierte a string luego recorre el string elemento a elemento sumando el cuadrado de este a s, al final retorna s ''' def sD(n): ns = str(n) s = 0 for i in range(len(ns)): s += int(ns[i])**2 return(s) # forma recursiva de la cadena de digitos cuadrados '''para mejorar el ...
strN = input("Please enter a number:") N = int(strN) #N = 10 total = 0 for current in range(N+1): if current % 2 == 0: total = total + current print("summation 1..",N," for even numbers is",total)
def maxj(lista): nlista = [[0 for lat in elem] for elem in lista] n = len(lista) for i in range(n): m = len(lista[i]) for j in range(m): nlista[i][j] += lista[i][j] war2 = lista[i][j] / 2 war3 = lista[i][j] /3 if i - 1 in range(n):...
def most_popular_tags(*args, **kwargs): return """SELECT tags.ROWID, tags.tag, count(tid_tag.tag) FROM tid_tag JOIN tags ON tid_tag.tag = tags.ROWID GROUP BY tags.tag ORDER BY count(tid_tag.tag) DESC LIMIT {n};""".format(**kwargs) d...
""" Faça um programa que verifique se uma letra digitada é vogal ou consoante. """ letra = str(input('Digite uma letra: ')) if letra.lower() in 'aeiou': print('Esta é uma vogal!') else: print('Esta é uma consoante!')