content
stringlengths
7
1.05M
print('first') print('second') if True: x = 1 y = 2 print('hi')
''' sekarang kita menghitung bunganya! ooh ya, apakah anda tahu bahwa kita bisa merantai perhitungan seperti ini jawaban = 2000 * /100 kita buat hal serupa di sini ''' ''' ciptakan variabel suku_bunga dan berikan nilai antara 5 hingga 30 -ciptakan juga varibel jumlah_bunga yang merupakan hasil perkalian sisa_cicilan d...
# Title : Insert new element before each element # Author : Kiran raj R. # Date : 23:10:2020 def insert_b4(list_in, str_elem): out = [elem for list_elem in list_in for elem in (str_elem, list_elem)] print(f"After inserting element: {out}") def insert_after(list_in, str_elem): out = [elem for list_el...
NOP = 0 RD = 1 WR = 2 class mmiodev(object): def __init__(self): self.regmap = {} self.regidx = {} def addReg(self, name, addr, length, readonly=0, default=0): # make sure it doesn't overlap with anything. for (a0,a1) in self.regmap: assert addr < a0 or addr >= a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Author: Jorge Mauricio # Email: jorge.ernesto.mauricio@gmail.com # Date: 2018-02-01 # Version: 1.0 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Objetivo: Define una función en la cual se ...
def of(n, acc1=0, acc2=1): if n < 0: raise ValueError if n == 0: return 0 elif n <= 1: return acc2 else: return of(n - 1, acc2, acc1 + acc2)
#!/usr/bin/python3 # Create a file and call it lyrics.txt (it does not need to have any content) # Create a new file and call it songs.docx and in this file write 3 lines # of text to it. # Open and read the content and write it to your terminal # window. * you should use the read(), readline(), and readlines() # ...
class Star: def __init__(self): self.x = random(-width/2, width/2) self.y = random(-height/2, height/2) self.z = random(width/2) self.pz = self.z def update(self, speed): self.z = self.z - speed if self.z < 1: self.z = width/2 ...
login_schema = { 'type': 'object', 'properties': { 'login': {'type': 'string', 'pattern': '^[0-9A-z-_]+$'}, 'password': {'type': 'string', 'pattern': '^[0-9A-z-_]+$'} }, 'required': ['login', 'password'] } register_schema = { 'type': 'object', 'properties': { 'login': {...
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class ValueTypeEnum(object): """Implementation of the 'ValueType' enum. Specifies the type of the value contained here. All values are returned as pointers to strings, but they can be casted to the type indicated here. 'kInt64' indicates that...
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @file : hooks.py @Time : 2021/3/31 15:32 @Author: Tao.Xu @Email : tao.xu2008@outlook.com """ def pytest_smtp_report_title(report): """ Called before adding the title to the report """ def pytest_smtp_results_summary(prefix, summary, postfix): """ Called before...
DATABASE_AUTO_CREATE_INDEX = True DATABASES = { 'default': { 'db': 'billing', 'host': 'localhost', 'port': 27017, 'username': '', 'password': '' } } CACHES = { 'default': {}, 'local': { 'backend': 'spaceone.core.cache.local_cache.LocalCache', 'max...
# We're trying to find the sum of the even fibonacci numbers # from 1 to `max_num` class Solution: # We're going to do fibonacci iteratively def solution(self, max_num: int) -> int: # `minus1` and `minus2` keep track of the last two values # starting with 0 and 1, `num` keeps track of the curren...
class Solution: def maxDistance(self, position: List[int], m: int) -> int: position=sorted(position) dis=position[-1]-position[0] if m==2: return position[-1]-position[0] low=1 high=dis def validInterval(interval): n=m-1 ...
project = 'django-sms' copyright = '2021, Roald Nefs' author = 'Roald Nefs' release = '0.4.0' extensions = ['m2r2'] templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] source_suffix = ['.rst', '.md'] html_theme = 'alabaster' html_theme_options = { "description": "A Django app f...
def main(): f = [int(i) for i in [line.rstrip("\n") for line in open("Data.txt")][0].split(",")] f[1] = 12 f[2] = 2 i = 0 while True: if f[i] == 99: break elif f[i] == 1: f[f[i + 3]] = f[f[i + 1]] + f[f[i + 2]] elif f[i] == 2: f[f[i + 3]] =...
def pivotedBinarySearch(arr, n, key): pivot = findPivot(arr, 0, n-1) if pivot == -1: return binarySearch(arr, 0, n-1, key) if arr[pivot] == key: return pivot if arr[0] <= key: return binarySearch(arr, 0, pivot-1, key) return binarySearch(arr, pivot + 1, n-1, key) def findPi...
def register(mf): mf.register_event("main", lambda: print("tests"), unique=False) register_parents = False
# https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ # 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 buildTree(se...
''' Exercício Python 26: Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”, em que posição ela aparecea primeira vez e em que posição ela aparece a última vez. ''' frase = str(input('Digite uma frase: ')).upper().strip() print(f'A letra "A" aparece {frase.count("A")} vezes na f...
DATABASE = { 'host': None, 'port': None, 'username': None, # 'data' 'password': None, # 'cafl-2021' 'db': None, 'uri': None, } BROWSER = { # broswer settings 'options': [ "--no-sandbox", "--dns-prefetch-disable", "--disable-browser-side-navigation", "--...
# Copyright 2021 The Bazel Authors. All rights reserved. # # 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 la...
# compose tree to describe object dictionary # assume all instrument readings are four-byte floats theTree = { 0x1000: { 0x00: {0x40: 0, 'size': 4} }, 0x6001: { 0x00: {0x40: 5}, 0x01: {0x40: 'INST:SEL CH1;:SOUR:VOLT?', 0x23: 'INST:SEL CH1;:SOUR:VOLT'}, 0x02: {0x40: 'INST:SEL CH1;:SOUR:CURR?', 0x23: 'INST:SEL...
api_key = "" api_secret = "" access_token_key = "" access_token_secret = ""
USERS = {} def update_user(user): if user not in USERS: USERS[user] = 0 USERS[user] += 1 return {'name': user, 'access': USERS[user]}
N, A, B = map(int, input().split()) if B >= A*N: print(A*N) else: print(B)
class Network: def __init__(self): self.layer_list = [] self.num_layer = 0 def add(self, layer): self.num_layer = self.num_layer + 1 self.layer_list.append(layer) def forward(self, x): for i in range(self.num_layer): x = self.layer_list[i].forward(x) ...
""" define in here e.g. the number of class, box scale, ... meaning constants class date: 9/30 author: arabian9ts """ # the number of classified class classes = 21 # the number of boxes per feature map boxes = [4, 6, 6, 6, 6, 6,] # default box ratios # each length should be matches boxes[index] box_ratios = [ [...
_base_ = [ '../../_base_/models/detr.py', '../../_base_/datasets/mot15.py', '../../_base_/default_runtime.py' #'../../_base_/datasets/mot_challenge.py', ] custom_imports = dict(imports=['mmtrack.models.mot.kf'], allow_failed_imports=False) link = 'https://download.openmmlab.com/mmdetection/v2.0/detr...
_base_ = [ '../_base_/default_runtime.py' ] model = dict( type='opera.InsPose', backbone=dict( type='mmdet.ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_eval=False, style='pytorch', init_cfg=dict(type='Pretrai...
# -*- coding: utf-8 -*- """ meraki This file was automatically generated for meraki by APIMATIC v2.0 ( https://apimatic.io ). """ class ObjectTypeEnum(object): """Implementation of the 'objectType' enum. TODO: type enum description here. Attributes: PERSON: TODO: type de...
# Задача 1. Вариант 38. # Напишите программу, которая будет сообщать род деятельности и псевдоним под которым скрывается Аврора Жюпен. После вывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода. # Kucheryavenko A. I. # 17.03.2016 print("Жорж Санд более известна, как французская писа...
""" Define multi-algoritmic simulation errors. :Author: Arthur Goldberg <Arthur.Goldberg@mssm.edu> :Date: 2016-12-12 :Copyright: 2016-2018, Karr Lab :License: MIT """ class Error(Exception): """ Base class for exceptions involving multi-algoritmic simulation Attributes: message (:obj:`str`): the exc...
class Employee(): def __init__(self, first_name, last_name, money): self.first_name = first_name self.last_name = last_name self.money = money def give_raise(self, add_money=5000): self.money += add_money return self.money
#Shape of capital B: def for_B(): """printing capital 'B' using for loop""" for row in range(7): for col in range(5): if col==0 or row==0 and col!=4 or row==3 and col!=4 or row==6 and col!=4 or col==4 and row%3!=0: print("*",end=" ") else: ...
def add(x,y): return x + y def multiply(x,y): return x * y def subtract(x,y): return x - y def divide(x,y): return y/x def power(x,y): return x**y
""" https://leetcode.com/problems/longest-increasing-subsequence/ Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may be more...
''' Created on 1.12.2016 @author: Darren '''''' Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. For example, Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6. The above elevation map is ...
## -*- coding: utf-8 -*- ## ## Sage Doctest File ## #**************************************# #* Generated from PreTeXt source *# #* on 2017-08-24T11:43:34-07:00 *# #* *# #* http://mathbook.pugetsound.edu *# #* ...
# EclipseCon Europe Che Challenge # # This program prints the numbers from 1 to 100, with every multiple of 3 # replaced by "Fizz", and every multiple of 5 replaced by "Buzz". Numbers # divisible by both are replaced by "FizzBuzz". Otherwise, the program # prints the number. # # Your mission, if you choose to accept it...
class DataPacker: #list data type will only write out the values without the key @staticmethod def dataTypeList(): return "list" @staticmethod def dataTypeObject(): return "object" def __init__(self, type): self.type = type self.data = [] def add_pair(...
#! /usr/bin/python # Filename: object_init # Description: the constructor in python class Persion: def __init__(self, name): self.name = name def sayHi(self): print(self.name) test = Persion("Hello,world") test.sayHi()
arr = [-3, 4, 8, -2, -1, 5, 4, 8] for i in range(0, len(arr)-1): if(arr[i] > 0): #num is positive temp = arr[i] arr[i] = arr[i+1] arr[i+1] = temp print(arr)
class Rememberer: def __init__(self): self.funcs = [] def register(self, fn): self.funcs.append(fn) fn.__conform__ = lambda new: self.recode(fn, new) return self def recode(self, fn, new): if new is None: self.funcs.remove(fn) else: ...
# coding=utf-8 """ 백준 16953번 : A -> B """ A, B = map(int, input().split()) count = 0 while A < B: string = str(B) if str(B)[-1] == '1': B = int(string[:len(string)-1]) count += 1 else: if B % 2 == 0: B = B // 2 count += 1 else: break if ...
# Fibonacci maxi = int(input("Insira até que numero deve ser calculado a sequencia de Fibonacci: ")) a = 0 b = 1 c = 0 while c < maxi: c = a + b print(c) a = b b = c
""" categories: Core,Functions description: Assign instance variable to function cause: Unknown workaround: Unknown """ def f(): pass f.x = 0 print(f.x)
# СОРТИРОВКА ПУЗЫРЬКОМ nums = [2,5,1,8,7,3,4,6,9] print(nums) for i in range(len(nums)): for j in range(len(nums)-i-1): if nums[j] > nums[j+1]: nums[j], nums[j+1] = nums[j+1], nums[j] print(nums)
# Create a program that reads an integer and shows on the screen whether it is even or odd n = int(input('Type a integer: ')) if n % 2 == 0: print('The number {} is {} EVEN {}'.format(n, '\033[1;31;40m', '\033[m')) else: print('The number {} is {} ODD {}'.format(n, '\033[7;30m', '\033[m'))
# @Time : 2019/4/24 23:22 # @Author : shakespere # @FileName: 3Sum.py ''' 15. 3Sum Medium Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate tr...
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 CEA # Pierre Raybaut # Licensed under the terms of the CECILL License # (see guiqwt/__init__.py for details) """ guiqwt.signals -------------- In `guiqwt` version 2, the `signals` module used to contain constants defining the custom Qt SIGNAL objects used by `guiqwt`...
# 5. Ваканция # Напишете програма, която спрямо даден бюджет и сезон да пресмята цената, локацията и мястото на настаняване за ваканция. # Сезоните са лято и зима – "Summer" и "Winter". Локациите са – "Alaska" и "Morocco". Възможните места за настаняване # – "Hotel", "Hut" или "Camp". # • При бюджет по-малък или равен ...
# Handshake # Count the number of Handshakes in a board meeting. # # https://www.hackerrank.com/challenges/handshake/problem # T = int(input()) for a0 in range(T): N = int(input()) print(N * (N - 1) // 2)
inicial = int(input('Qual o numero inicial?')) final = int(input('Qual o numero final?')) x = inicial while( x <= final): if(x % 2 == 0): print(x) x = x + 1
#!/usr/bin/env python3 # Everything in Python are objects. # This means that everything that's created is an # instance on a pre-defined class, or a self-defined class. # These instances are in memory (hence named objects), and # has access to the functions defined in the original classes # and is called methods. # 1...
def print_header(cadena_texto): print("Hola ", cadena_texto) nombre = input("¿Cuál es tu nombre? ") print_header(nombre)
def main_screen(calendar): while True: print("What would you like to do? ") print("\ta) Add event") print("\tb) Delete event") print("\tc) Print events") print("\td) Exit") answer = input(" $ ") if "a" in answer: add_event(calendar) elif "...
def levenshtein_Distance(word1,word2): word1="#"+word1 wordTmp="#"+word2 letters1 = list(word1) letters2 = list(wordTmp) # Initializing table table = [ [0 for i in range(len(word1))] for j in range(len(wordTmp))] for i in range (len(word1)): table[0][i] = i fo...
# # PySNMP MIB module ACMEPACKET-PRODUCTS (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ACMEPACKET-PRODUCTS # Produced by pysmi-0.3.4 at Mon Apr 29 16:57:56 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
# Feature flag to raise an exception in case of a non existing device feature. # The flag should be fully removed in a later release. # It allows dependend libraries to gracefully migrate to the new behaviour raise_exception_on_not_supported_device_feature = True # Feature flag to raise exception if rate limit of the ...
class Solution: def countOdds(self, low: int, high: int) -> int: c = high - low + 1 if c % 2 == 1 and low % 2 == 1: r = 1 else: r = 0 return r + c // 2
class Solution: def reverseWords(self, s: str) -> str: res, blank = '', False for _ in s[::-1]: res += _ return ' '.join(res.split()[::-1])
# ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache #...
def N(): for row in range(7): for col in range(7): if (col==0 or col==6) or row-col==0: print("*",end=" ") else: print(end=" ") print()
# 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 addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type ...
a=list(map(int,input().split(',')))[:4] x,y,p,q=a[0],a[1],a[2],a[3] b1,b2,b3=1,1,1 print(b1,'C',x,b2,'H',y,',',b3,',C',p,'H',q) print((b1*x+b2*y),(b3*(p*q))) while (b1*x+b2*y)!=(b3*(p*q)): while b1*x!=b3*p: print('l1') if b1*x!=p: b1+=1 elif x!=b3*p: b3+=1 ...
league_schema_name = None def tn(tablename: str) -> str: if league_schema_name is not None: return '`{0}`.`{1}`'.format(league_schema_name, tablename) else: return '`{0}`'.format(tablename)
A = [1, 2, 3] for i, x in enumerate(A): A[i] += x B = A[0] C = A[0] D: int = 3 while C < A[2]: C += 1 if C == A[2]: print('True') def main(): print("Main started") print(A) print(B) print(C) print(D) if __name__ == '__main__': main()
# Folders FOLDER_SCHEMA = "graphql" # Packages PACKAGE_RESOLVERS = "resolvers" # Modules MODULE_MODELS = "models" MODULE_DIRECTIVES = "directives" MODULE_SETTINGS = "settings" MODULE_PYDANTIC = "pyd_models"
""" The ``covertutils`` module provides ready plug-n-play tools for `Remote Code Execution Agent` programming. Features like `chunking`, `encryption`, `data identification` are all handled transparently by its classes. The :class:`SimpleOrchestrator` handles all data manipulation, and the :class:`Handlers.BaseHandler` ...
# 2. Matching Parentheses # You are given an algebraic expression with parentheses. Scan through the string and extract each set of parentheses. # Print the result back on the console. string = list(input()) stack_index = [] for index in range(len(string)): if string[index] == "(": stack_index.append(in...
# # PySNMP MIB module JUNIPER-FABRIC-CHASSIS (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-FABRIC-CHASSIS # Produced by pysmi-0.3.4 at Wed May 1 13:59:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
"""Rules for simple testing without dependencies by parsing output logs.""" def tflite_micro_cc_test( name, expected_in_logs = "~~~ALL TESTS PASSED~~~", srcs = [], includes = [], defines = [], copts = [], nocopts = "", linkopts = [], deps = [], ...
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: rows=len(grid) columns=len(grid[0]) for i in range(1,columns): grid[0][i]+=grid[0][i-1] for j in range(1,rows): grid[j][0]+=grid[j-1][0] for k in range(1,rows): for l in ra...
''' Take two sorted linked lists L, R and return the merge of L and R Notes: * when declaring a python class, inherit from object if not otherwise specified * in the python class __init__ function, self is a required first argument * next is a reserved name (iterator method) in python. use the variable name next_node ...
# -*- coding: utf-8 -*- """Top-level package for mvstats.""" __author__ = """Hrishikesh A. Chandanpurkar""" __email__ = 'hrishikeshac@gmail.com' __version__ = '0.1.0'
global_transform = 0 # TODO: add types / proper data structures to variables def find_attitude_data(timestamp): """ Find corresponding attitude data by time stamp. :param timestamp: The timestamp. :return: ? """ pass def find_displacement_data(timestamp): """ Find corresponding d...
PRED_TYPE = 'Basic' TTA_PRED_TYPE = 'TTA' ENS_TYPE = 'Ens' MEGA_ENS_TYPE = 'MegaEns'
# -*- coding: UTF-8 -*- """ Copyright 2021 Tianshu AI Platform. All Rights Reserved. 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 ...
# Copyright (c) 2017 Dustin Doloff # Licensed under Apache License v2.0 load( ":internal.bzl", "assert_files_equal_rule", "assert_label_struct_rule", ) def assert_equal(v1, v2): """ Asserts that two values are equal. If not, fails the build """ if v1 != v2: fail("Values were not eq...
class Application: def __init__(self, owner, raw): self.id = raw['app_id'] self.owner_id = raw['owner_id'] self._update(owner, raw) def _update(self, owner, raw): self._raw = raw self.owner = owner self.name = raw['name'] self.type = raw['type'] ...
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT...
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified). __all__ = ['a'] # Cell def a(b): "qgerhwtejyrkafher arerhtrw" return 10
print ("Hello there welcome to Medieval Village.") print ("You have a village that you need to take care of. Choose one of the options to keep the village in good shape 1) Plant and harvest the crops 2) Use resources from the forest near the village 3) Get your defenses up") user_choice = input() user_choice = int(user...
def solution(board, moves): # At first, make stack of each columns boardStack = [[] for _ in range(len(board[0]))] for row in board[::-1]: # Watch out, column index is subtracted by -1 for column, element in enumerate(row): if element != 0: boardStack[column].appe...
repeat = int(input()) for x in range(repeat): inlist = list(map( int, input().split())) inlen = inlist.pop(0) avg = sum(inlist)//inlen inlist.sort() for i in range(inlen): if inlist[i] > avg: result = (inlen-i)/inlen *100 break result = 0 print("%.3f"%resu...
""" CCC Problem J2 Randy Zhu """ infection_limit = int(input()) patient_zeroes = int(input()) infection_rate = int(input()) infected = 0 # newly_infected = 0 # infected = 0 currently_infected = patient_zeroes # infected = 0 days = 0 while infected < infection_limit: infected += (currently_infected...
#!/usr/bin/env python # # Copyright 2009-2020 NTESS. Under the terms # of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # # Copyright (c) 2009-2020, NTESS # All rights reserved. # # Portions are copyright of other developers: # See the file CONTRIBUTORS.TXT in the top ...
""" Given the capacity of the knapsack and items specified by weights and values, return the maximum summarized value of the items that can be fit in the knapsack. Example: capacity = 5, items(value, weight) = [(60, 5), (50, 3), (70, 4), (30, 2)] result = 80 (items valued 50 and 30 can both be fit in the knapsack) Th...
class TBikeTruck: def __init__(self, id, capacity, init_location): self.id = id self.capacity = capacity self.location = init_location self.bikes_count = 0 self.distance = 0 def to_json(self): return { 'id': self.id, 'location_id': self.lo...
class Stack: topIndex = 0 items = [None] * 64 def push(self, item): self.topIndex += 1 self.items[self.topIndex] = item def pop(self): if self.topIndex == 0: return None else: itemToReturn = self.items[self.topIndex] self.topIndex -= 1 ...
# Cheering Expression (6510) rinz = 2012007 scissorhands = 1162003 sweetness = 5160021 sm.setSpeakerID(rinz) sm.sendNext("Welcome! What can I do for you today? ...A gift? For me? " "Wow, a customer's never given me a gift before!") sm.giveItem(sweetness) sm.completeQuest(parentID) sm.consumeItem(scissorhands) sm.s...
''' Faça um progroma que leia nome e média de um aluno, guardando também a situação[aprovado or nao em um dicionário. No final, mostre o conteúdo da estrutura na tela. ''' turma = dict() turma['nome'] = str(input('Nome: ')) turma['media'] = float(input('Média: ')) if turma['media'] > 6.9: turma['situacao'] = 'Apro...
# Copyright 2019 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. config_type='sweetberry' inas = [ ('sweetberry', '0x40:3', 'pp1050_a', 1.05, 0.010, 'j2', True), # R462, SOC ('sweetberry', '0x40:1', '...
def selectionSort(A): for i in range(len(A) - 1): index_min = i value_min = A[i] for j in range(i + 1, len(A)): if A[j] < value_min: index_min = j value_min = A[j] A[index_min] = A[i] A[i] = value_min return A def insertionS...
# # LeetCode # # Problem - 386 # URL - https://leetcode.com/problems/lexicographical-numbers/ # class Solution: def lexicalOrder(self, n: int) -> List[int]: ans = [] for i in range(1, n+1): ans.insert(bisect.bisect_left(ans, str(i)), str(i)) return ans
def _method(f): return lambda *l, **d: f(i, *l, **d) class o: def __init__(i, **d): i.__dict__.update(**d) def __repr__(i): return str( {k: (v.__name__ + "()" if callable(v) else v) for k, v in sorted(i.__dict__.items()) if k[0] != "_"}) def of(i, **methods): for k, f in methods.items(): i.__di...
class Solution(object): def minCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ if not costs: return 0 dp = [0] * (len(costs[0])) dp[:] = costs[0] for i in xrange(1, len(costs)): d0 = d1 = d2 = 0 ...
class Solution: def romanToInt(self, s: str) -> int: romanMap = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} result = 0 prev = 1000 for c in s: curr = romanMap[c] if curr > prev: result += curr - prev*2 else: ...
''' Design a calculator which will solve all the problems correctly except for 1. 45*3 = 555 2. 56+9 = 77 3. 56/6 = 4 Your program should take two numbers, operator as input and show the output. ''' def add(n1,n2): ''' To add the given numbers ''' result = n1+n2 return result def sub(n1,n2): ''' To ...