content
stringlengths
7
1.05M
''' Objektorientiert Programmierung Ein Klasse für ein bewegtes Objekt Version 1.00, 27.02.2021 Der Hobbyelektroniker https://community.hobbyelektroniker.ch https://www.youtube.com/c/HobbyelektronikerCh Der Code kann mit Quellenangabe frei verwendet werden. ''' # Bewegtes Objekt # Diese Klasse zeic...
#!/usr/bin/env python class wire(): def __init__(self, s): l = s.split() self.name = l[-1] self.known = False self.value = 0 if any([op in l for op in ["AND", "OR", "LSHIFT", "RSHIFT"]]): self.op = l[1] self.source = [l[0], l[2]] elif "NOT" i...
"""Archivist OR dictionary and list Used in filters: list of Or dictionaries Dictionaries where key is always 'or' and value is a list of strings """ def or_dict(list_): """Construct a dictionary with key 'or'""" return {"or": list_} def and_list(lists): """Construct a list of or dictionaries"""...
# # PySNMP MIB module APPACCELERATION-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPACCELERATION-TC # Produced by pysmi-0.3.4 at Wed May 1 11:23:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
name = "Alamin" age = 25 print(f"Hello, {name}. You are {age}") print(f"{5*5}") def to_lowercase(input): return input.lower() name = "Alamin Mahamud" print(f"{to_lowercase(name)} is awesome!") print(f"{name.lower()} is F*ckin awesome!") class Rockstar: def __init__(self, first_name, last_name, age): ...
# Name:Collin and Jack # Date:July 13 2017 # project05: functions and lists # Part I def divisors(num): counter = 0 lst = [] while counter != num: counter = counter + 1 if num % counter == 0: lst.append(counter) #print "divisor" """Takes a number and returns al...
class TreeNode(): def __init__(self, val = None, children=None): self.val = val if(not children): self.children = [] else: self.children def main(): print("Tree") if __name__ == "__main__": main() # Trees are a class of data structure that a similar to grap...
# Getting Started with Python (Example Word count exercise) # Author: Mohit Khedkar. thislist=input("Enter the String: ") a=thislist.split() list=[] for i in a: if i not in list: list.append(i) for i in range(0,len(list)): print(list[i],a.count(list[i]))
class ASTVisitor: """Generic base class for visitor pattern. Classes that traverse the AST inherit from this base class. """ def visit(self, node): """Call the generator for the node.""" method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self.missing) ...
""" 题目:矩阵中的路径 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。 路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。 如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。 思路分析:这是一个运用回溯法的典型题目。下面以上述例子...
nota1 = float(input('Qual a primeira nota do aluno?\n')) nota2 = float(input('Qual a segunda nota do aluno?\n')) media = (nota1 + nota2) / 2 print('Baseado na primeira nota {} e na segunda nota {} média final do aluno é {}'.format(nota1, nota2, media))
""" This is DEPRECATED. The most up-to-date logic lives in the notebooks folder, under the search_engine_results.ipynb. This will be reinstated in case there's a need to get the search engine results via a python script (which there'is not at the moment). """ # from sklearn.metrics.pairwise import cosine_similarity ...
""" Given a string s, find the length of the longest substring T that contains at most k distinct characters. Example For example, Given s = "eceba", k = 3, T is "eceb" which its length is 4. Challenge O(n), n is the size of the string s. """ __author__ = 'Daniel' class Solution: def lengthOfLongestSubstringKD...
__all__ = ['tex_table'] _tex_table_values = dict( shape = ('v', 'h', 'ver', 'hor', 'vertical', 'horizontal'), sep = ('v', 'h', 'f', 'no', 'ver', 'hor', # 'n' is also in 'horizontal' 'vertical', 'horizontal', 'full', 'none' ), fit = ('h', 'h!', 'b', 't', 'H'), loc = ('c', 'l', 'r', 'cen...
def f0() -> int: return 42 def f1(x : int) -> int: return x ^ 42 def f2(x : int, y : str) -> bool: q = int(y) return x == q r0 = f0() r1 = f1(42>>1) + 1 r2 = f2(56, "56")
""" Contains a dictionary potential SPF and DMARC issues to be used as template to populate the main module's outputs. """ ISSUES = { 'NX_DOMAIN': { 'code': 0, 'title': 'Non-existent domain', 'detail': 'The DNS resolver raised an NXDomain error for \'{domain}\'' }, 'NO_SPF': { ...
h,m=map(int,input().split(':')) while 1: m+=1 if m==60:h+=1;m=0 if h==24:h=0 a=str(h);a='0'*(2-len(a))+a b=str(m);a+=':'+'0'*(2-len(b))+b if(a==a[::-1]):print(a);exit()
#!/bin/python3 # Iterative solution # Time complexity: O(n) # Space complexity: O(1) # Note - a recursive solution won't work here (stack overflow) # The logic: # - every value that you use, the adjacent one you can't # - therefore you have to skip everything that is not required # - when you skip a val...
#!/usr/bin/env python3 def pkcs7_padding(data: bytes, cipher_block_size: int): padding_length = cipher_block_size - (len(data) % cipher_block_size) if padding_length != cipher_block_size: return data + bytes([padding_length]*padding_length) else: return data if __name__ == '__main__': ...
# # PySNMP MIB module SONUS-COMMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONUS-COMMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:01:35 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
# 0070. Climbing Stairs # # Note: # 1. We remove case "n == 0" because it is included in the other two base cases. # 2. "Solution#1 Recusion" got the error of "Time Limit Exceeded". # The reason is in this recursion, the inductive case is the combination of two sub-components which share too many redundent sub-comp...
#!/usr/bin/env python3 def primes(y): x = y // 2 while x > 1: if y % x == 0: print(y, 'has factor', x) break x -= 1 else: print(y, 'is prime.') primes(13) primes(13.0) primes(15) primes(15.0)
num_key = int(input()) max_resistance = list(map(int, input().split())) num_pressed = int(input()) key_pressed = list(map(int, input().split())) hash = {} for i in range(num_key): hash[i+1] = max_resistance[i] output = ["NO"] * num_key for key in key_pressed: hash[key] -= 1 if hash[key] < 0: output...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: r...
""" Class description goes here. """ """Generic GRPC paraver interceptor mechanisms. In general, the source of examples for making this work comes from: Heavily inspired in: https://github.com/grpc/grpc/blob/master/examples/python/interceptors/ """ HEADER_MESSAGEID = "messageid" HEADER_CLIENTPORT = "clientport"
# -*- coding:utf-8 -*- """ """ __author__ = "Andres FR" __email__ = "aferro@em.uni-frankfurt.de" __version__ = "0.3.1"
# -*- coding: utf-8 -*- def dict_equal(src_data,dst_data): assert type(src_data) == type(dst_data),"type: '{}' != '{}'".format(type(src_data), type(dst_data)) if isinstance(src_data,dict): for key in src_data: assert dst_data.has_key(key) dict_equal(src_data[...
# MIT License # # Copyright (c) [year] [fullname] # # 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,...
regs = [ #(0x3000000, "", "User Memory and User Stack (sp_usr=3007F00h)"), (0x3007f00, "", "Default Interrupt Stack (6 words/time) (sp_irq=3007FA0h)"), (0x3007fa0, "", "Default Supervisor Stack (4 words/time) (sp_svc=3007FE0h)"), (0x3007fe0, "", "Debug Exception Stack (4 words/time) (sp...
# -*- coding: utf-8 -*- """ This python package is a small collection of data about 4MOST -- e.g. its wavelength coverage and spectral resolution. """ class FourMost: def __init__(self): # Data from <https://www.4most.eu/cms/facility/> self.bands = { "LRS": {"R": 7500, ...
# -*- coding: utf-8 -*- """ Using crispy_forms with Foundation set """ INSTALLED_APPS = add_to_tuple(INSTALLED_APPS, 'crispy_forms', 'crispy_forms_foundation') CRISPY_FAIL_SILENTLY = not DEBUG # Default layout to use with "crispy_forms" CRISPY_TEMPLATE_PACK = 'foundation-5'
""" ID: duweira1 LANG: PYTHON2 TASK: milk2 """ fin = open('milk2.in','r') fout = open('milk2.out','w') dataList = [] with open('milk2.in') as f: dataList = (f.read().splitlines()) num = int(dataList[0]) tlst = [] for i in range(1,len(dataList)): firstTriggered = False first = "" second = "" for s in dataLi...
search_query = 'site:linkedin.com/in/ AND "python developer" AND "New York"' # file were scraped profile information will be stored file_name = 'results_file.csv' # login credentials linkedin_username = 'username' linkedin_password = 'PASSWORD'
# graph theory terminology & lemmas ''' degree - number of edges touching the vertex handshaking lemma - finite undirected graphs - an even number of vertices will have odd degree - consequence of the `degree sum formula` sum(deg(v el of vertices)) = 2|# edges| complete graph - vertex is conn...
MOCK_JOB_STATUS = {'value': 'test'} MOCK_JOBS_LIST = ['job1', 'job2'] class SQLMock: expected_agreement_id = None expected_job_id = None expected_owner = None stopped_jobs = [] removed_jobs = [] @staticmethod def assert_all_jobs_stopped_and_reset(): for job in MOCK_JOBS_LIST: ...
# -*- codeing = utf-8 -*- # @Time: 2022/1/15 22:32 # @Author: Coisini # @File: demo1.py # @Software: PyCharm print("hello world") # 格式化输出 age = 18 print("我的年龄是: %d岁" % age) name = 'Coisini' country = "中国" print("我的名字是: %s, 我的国籍是: %s" % (name, country)) # 分割 print("www", "baidu", "com", sep=".")
input = """ % Bug: % line 4: Aggregate conjunction is not safe. % Aborting due to parser errors. % This happened because of a faulty binding check % of the TERMS occurring inside the aggregate % w.r.t. literals q, r, and s. :- q(X), not r(X,W), s(W),#count{Y: p(Y,Z), Z >= X} < 1. """ output = """ {} """
""" Given a singly linked list, determine if it is a palindrome. """ class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def isPalindrome(self, head): reverse = [] while head: reverse.append(head.val) h...
class Agenda: def __init__(self, c): self.c = c self.events = {} self.current_time = 0 self.queue = [] def schedule(self, time, event, arguments): if time in self.events: self.events[time].append([event, arguments]) else: self.events[time]...
"""jsinterop_generator_import macro. Takes non standard input and repackages it with names that will allow the jsinterop_generator_import() target to be directly depended upon from jsinterop_generator() targets. """ load("//third_party:j2cl_library.bzl", "j2cl_library") load(":jsinterop_generator.bzl", "JS_INTEROP_RU...
ENTRY_POINT = 'fix_spaces' #[PROMPT] def fix_spaces(text): """ Given a string text, replace all spaces in it with underscores, and if a string has more than 2 consecutive spaces, then replace all consecutive spaces with - fix_spaces("Example") == "Example" fix_spaces("Example 1") == "Ex...
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Find the longest increasing subsequence. # # * [Constraints]...
count = 0 with open("tester.txt", "r") as fp: lines = fp.readlines() count = len(lines) with open("new.txt", "w") as fp: for line in lines: if(count == 3): count -= 1 continue else: fp.write(line) count-=1
##### While loop ##### #while loop for printing 1 to 100 i = 0 while i<=100: print (i) i +=1 #Print all number while are multiples of 6 within 1 to 100 i = 0 while i<=100: if i%6==0: print(i) i +=1 #How is the maturity for house i = 1 p = 2500000 while i<=30: p = p+p*.04 i +=1 print (p) ...
#!/usr/bin/env python # coding: utf-8 version = "2.0.1"
def solve(matrix): rows = len(matrix) cols = len(matrix[0]) if rows == 0 or matrix[0][0] == 1: return 0 result = [[0 for _ in range(cols)] for __ in range(rows)] result[0][0] = 1 for i in range(rows): for j in range(cols): if matrix[i][j] == 1: cont...
class Solution: def sumOddLengthSubarrays(self, arr: List[int]) -> int: """Array. Running time: O(n^2) where n is the length of arr. """ n = len(arr) res = 0 prefix = [0] * (n + 1) for i in range(1, n + 1): prefix[i] = prefix[i-1] + arr[i-1] ...
class BitFlagGenerator: def __init__(self, initial=1): self._check_is_flag(initial) self.initial = initial self.current = initial self.flags = [] def _check_is_flag(self, value): if not sum(1 for bit in bin(value) if bit == '1') == 1: raise ValueError('flag m...
# pylint: disable=protected-access,redefined-outer-name """Test constants.""" MOCK_HOST = "192.168.0.2" MOCK_USER = "user" MOCK_PASS = "pass"
# -*- coding: utf-8 -*- """ @author:XuMing @description: """ __version__ = '0.1.6'
d=0 a=int(input("Informe o valor de A\n")) while a==0: a=int(input("Informe o valor de A\n")) if a<0: print("Não existe número real para delta menor que zero") elif a>0: b=int(input("Informe o valor de B\n")) c=int(input("Informe o valor de C\n")) d=(b*b)-a*c print(d)
""" 9.4 Write a program to read through the mbox-short.txt and figure out who has sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a cou...
velocidade=float(input("Digite a velocidade do automóvel ")) if velocidade>110: if velocidade<=132: print("Você foi multado por excesso de velocidade em R$100,00") else: print("Você foi multado por excesso de velocidade em R$500,00") else: print("Pode seguir viagem com segurança")
file = open("module_scripts.py","r") lines = file.readlines() file.close() file = open("module_scripts.py","w") level = 0 for line in lines: line = line.strip() acceptableindex = line.find("#") if (acceptableindex == -1): acceptableindex = len(line) level -= line.count("try_end", 0, acceptab...
def init(bs): global batch_size batch_size = bs def get_batch_size(): return batch_size
""" Question Source:Leetcode Level: Hard Topic: Stack Solver: Tayyrov Date: 24.05.2022 """ def longestValidParentheses(s: str) -> int: stack = [] valid_indices = [] for index, par in enumerate(s): if par == ")": if stack and stack[-1][-1] == "(": vali...
#!/usr/bin/env python # coding: utf-8 #program to know if a positive number is a prime or not #picking a variable named num num = 20 #using for loop from 2 since 1 is not a prime number from knowledge of mathematics #I set the range from 2 to the number set for i in range(2,num): #An if statement to validate if t...
#João Papo-de-Pescador, homem de bem, comprou um microcomputador. # para controlar o rendimento diário de seu trabalho. # Toda vez que ele traz um peso de peixes. # maior que o estabelecido pelo regulamento de pesca do estado de São Paulo. # (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. # João prec...
if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT, _winapi.ERROR_PIPE_BUSY) or _check_timeout(t): pass class X: def get_help_text(self): return ngettext( "Your password must contain at least %(min_length)d character.", "Your password must c...
root = "/home/brian/manga_ordering" image_shape = (1654, 1170) image_shape_exception = (2960, 2164) size_title_exception = "PrayerHaNemurenai" degeneracies = [ ("Arisa", 1), ("Belmondo", 25) ] yonkoma = ["OL_Lunch"] validation = ["YoumaKourin", "MAD_STONE", "EienNoWith", "Nekodama", "SonokiDeABC"] testing = ["B...
class GameCharacter: def __init__(self, name, weapon): self.name = name self.weapon = weapon def speak(self, word): print('我是%s, %s' % (self.name, word)) class Warrior(GameCharacter): # 括号中指定父类(基类) def attack(self): print('近身肉搏') class Mage(GameCharacter): def attack(...
sum = 0 for i in range(int(input("von: ")), int(input("bis: "))): sum += i print(sum)
def convert(string): n = len(string) string = list(string) for i in range(n): if (string[i] == ' '): string[i] = '_' else: string[i] = string[i].lower() string = "".join(string) return string
#!/usr/bin/python # -*- coding: utf-8 -*- """ test_url_for ~~~~~~~~~ :copyright: (c) 2014 by geeksaga. :license: MIT LICENSE 2.0, see license for more details. """ ''' from flask import request, Response from geeksaga.archive import create_app app = create_app() with app.test_request...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: r = [] while head: r.append(head) head = head.next retur...
class MessageValidationError(Exception): def __init__(self, msg: str) -> None: super(MessageValidationError, self).__init__(msg) self.msg: str = msg
infile = open('../files/mbox.txt') outfile = open('emails.txt', mode='w') for line in infile: clean_line = line.strip() if clean_line.startswith('From '): tokens = clean_line.split() email = tokens[1] year = tokens[-1] domain = email.split('@')[1] outfile.write('domain: {...
''' Este programa muestra como inprimir en pantalla información y como realizar un salto de línea con diagonal ''' print("Mi nombre es Emilio Carcaño Bringas\nEstoy orgulloso de pertenecer a Uninaciones y estudiar en la UNAM") #Este programa fue escrito por Emilio Carcaño Bringas
params = { 'axes.labelsize': 12, 'font.size': 12, 'savefig.dpi': 1000, 'axes.spines.right': False, 'axes.spines.top': False, 'legend.fontsize': 12, 'xtick.labelsize': 12, 'ytick.labelsize': 12, 'text.usetex': False, 'legend.labelspacing': 1, 'legend.borderpad': 0.5, 'lege...
# https://leetcode.com/submissions/detail/466620736/ def merge(nums1, m, nums2, n): """ Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal...
inputfile = open('input.txt','r').readlines() for i in range(len(inputfile)): inputfile[i] = inputfile[i].strip('\n') part = 2 # 1 or 2 answer = 0 if part == 1: acc = 0 pointer = 0 run = True runned = [] while run: try: instruction = inputfile[pointer].split(" ") ex...
status_fields = { 'satp' : { 'status_fields': { 'summary': { 'Time': 'Time', 'Year': 'Year', 'Azimuth mode': 'Azimuth_mode', 'Azimuth current position': 'Azimuth_current_position', 'Azimuth current velocity': 'A...
# Cast double into string a = 2 b = str(a) print(b)
""" ONS Digital Rabbit queue handling License: MIT Copyright (c) 2017 Crown Copyright (Office for National Statistics) RabbitMQ helper function, this can probably be refactored out, but for now it maintains a handy compatibility layer for other modules. """ class ONSRabbit(object): def __init...
EMAIL_HOST ='smtp.gmail.com' EMAIL_HOST_USER = 'sedhelp@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_DEFAULT_USER = 'support@sedteam.org'
################################################### # Kısayol Ayarı ################################################### # Klavye tuş kombinasyonu kodlarına basıldığında # kısayolu aktif eder ################################################### SHORTCUT = (162, 164, 36) # CTRL + ALT + HOME ###########...
# Copyright 2021 The TF-Coder Authors. # # 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...
class BankAccount: accounts = [] def __init__(self, int_rate, balance): # Make user class later self.int_rate = int_rate self.balance = balance BankAccount.accounts.append(self) def deposit(self, amount): self.balance += amount return self def withdraw(se...
""" Sets in math: set is a group of unique elements - declare - union, intersection, symmetric_difference, difference - Examples - unique tags - users taking two actions """ a = {1, 2, 3} b = {3, 4, 5} c = {1, 2, 2, 2, 2, 3} print(c) print(a | b) d = {1, 2, 3} f = {2, 3, 4} # union print(d |...
""" token_dict 형태소 분석을 수행할 때, 거치는 전처리 과정에 필요한 여러 예외 토큰 사전 """ """ # 예외처리 특수 키워드: 해당 토큰이 셋에 존재할 경우 모든 검증 과정을 스킵하고 해당 토큰들은 예외적으로 인정 해당 단어 문서에 존재할 경우 토큰에 추가 """ valid_words = { "ai", "it", "ot", "sw", "pc", "la", "cm", "op", "ed" } # 단일 자모음 제외셋 stop_single = { "ㄱ", "ㄲ", "ㄴ", 'ㄷ', "ㄸ", "ㄹ", "ㅁ", 'ㅂ', "ㅃ", "...
""" Router for KEA models """ class Router: route_app_labels = {'django_kea'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'kea' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.ro...
#!/usr/bin/python class FunctionalList: '''A class wrapping a list with some extra functional magic, like head, tail, init, last, drop, and take.''' def __init__(self, values=None): if values is None: self.values = [] else: self.values = values def __len__(sel...
# -*- coding: utf-8 -*- acmgconfig = { "formatting": { "operators": { "$in": "=", "$gt": ">", "$lt": "<", "$not": "!=", "$range": "within", "$all": "=", "$at_least": "at least", } }, "codes": { "path...
with open('data.txt') as fp: datas = fp.read() #each testcase is seprated by '\n\n' data = datas.split('\n\n') suma = 0 for elem in data: quests = set() # different lines contain no information... answ = elem.replace('\n','').replace(' ','') for char in answ: #if this question has not answer...
"""augur_worker_github - Augur Worker that collects GitHub data""" __version__ = '0.0.1' __author__ = 'Augur Team <s@goggins.com>' __all__ = []
class Solution: def isMatch(self, s, p): dp = [[False for _ in range(len(p)+1)] for i in range(len(s)+1)] dp[0][0] = True for j in range(1, len(p)+1): if p[j-1] != '*': break dp[0][j] = True for i in range(1, len(s)+1): ...
# Everything in Python is an Object literallyAnyWordWhichBeginsWithALetterOr_IsAValidObjectName = 3 print(literallyAnyWordWhichBeginsWithALetterOr_IsAValidObjectName) # You can print something using print() something = 5 print(something) # Anything typed after '#' is a comment, it's something that is ignored by Pyth...
cities = ["서울","부산","인천", \ "대구","대전","광주","울산","수원"] print(cities[0:6]) print(cities[:]) print(cities[-50:50]) print(cities[::2], " AND ", cities[::-1])
""" Write a Python function that takes a division equation d and checks if it returns a whole number without decimals after dividing. Examples: check_division(4/2) ➞ True check_division(25/2) ➞ False """ def check_division(num): if num % 2 == 0: return num, True else: return num, False ...
#!/usr/bin/python3 # Задание 14 - Степень двойки print("14. Степень двойки") n = int(input('n: ')) p, c = 1 * 2, 1 if (n == 0): print(0) else: while (p <= n): p *= 2 c += 1 print(c)
{ 'total_returned': 1, 'host_list': [ { 'name': 'i-deadbeef', 'up': True, 'is_muted': False, 'apps': [ 'agent' ], 'tags_by_source': { 'Datadog': [ 'host:i-deadbeef' ], 'Amazon Web Services': [ 'account:staging' ] ...
class Solution: def maximumProduct(self, nums): """ :type nums: List[int] :rtype: int """ max1, max2, max3 = sorted(nums[:3])[::-1] min1, min2 = max3, max2 for num in nums[3:]: if num >= max1: max1, max2, max3 = num, max1, max2 ...
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=35): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f"Olá, meu nome é {self.nome}" @staticmethod def metodo_estatico(): return 42 @classm...
def nota(* notas, sit=False): """ ->Função para analisar notas e situação de vários aluno. :param notas: Uma ou mais notas dos alunos (aceita váriaveis) :param sit: valor opcional, indica se deve ou não adicionar a situação :return: dicionário com várias informações sobre a situação do aluno. ""...
# 2. Todo List # You will receive a todo-notes until you get the command "End". # The notes will be in the format: "{importance}-{value}". Return the list of todo-notes sorted by importance. # The maximum importance will be 10 note = input() todo_list = [0] * 10 while not note == 'End': importance, task = note.s...
n1 = float(input('fale a primeira nota: ')) n2 = float(input('fale a segunda nota: ')) media = (n1 + n2) / 2 if media < 6: print('voce foi reprovado seu burro!!') elif media < 9: print('voce foi aprovado !!') elif media <= 10: print('parabens otimo aluno !!') print('voce foi aprovado !!')
# TODO: Fill in meta tags. meta = { "title" : "", "author" : "", "description" : "", "url" : "", "icon_path" : "", "keywords" : "" } # TODO: Make additional links in nav-bar here. nav = [ { "name" : "projects", "link" : "index.html#projects" }, { "name" : "bl...
#!/usr/bin/python # # check_mk is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation in version 2. check_mk is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- # out even the i...
def pallindrom(n): a=str(n) b=a[::-1] if(a==b): return True p=0 lp=0 for i in range(100,1000): for j in range(100,1000): p=i*j if(pallindrom(p)): if(p>lp): lp=p print(lp)
# 添加数据库链接 DIALECT = 'mysql' DRIVER = 'pymysql' USERNAME = 'root' PASSWORD = 'root' HOST = '127.0.0.1' PORT = '3306' DATABASE = 'fast_api' # +{} DRIVER, SQLALCHEMY_DATABASE_URI = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format( DIALECT ,DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE ) SQLALCHEMY_COMMIT_ON_TEARDOWN =...