content
stringlengths
7
1.05M
""" Test that the game controller is implemented properly. """ # Unit tests for the functions in tetris_controller require an interactive # form of testing like mock patch or event injection. We have verified that # the controller interacts with the game in an error-free manner, and that the # functions it calls run p...
def build_model(): pass def save_model(): pass def load_model(model_path): pass def load_best_model(): pass
# Databricks notebook source print("hello world") # COMMAND ---------- print("let's make some changes and commit!") # COMMAND ----------
#!/usr/bin/env python # test print('test!')
N = int(input()) V = list(map(int, input().split())) V.sort() v_sum = (V[0]+V[1]) / (2**(len(V)-1)) for i in range(2, len(V)): v_sum += V[i] / (2**(len(V)-i)) print(v_sum)
class KeyValue: def __init__(self, key: None, value: None): self.key = key self.value = value class HashMap: def __init__(self, size:int = 11): self.size: int = size self.items: list = [None] * self.size self.length: int = 0 def put(self, key, value): keyVal...
class EllysTSP: def getMax(self, places): c = places.count('C') v = len(places) - c return 2 * min(c, v) + min(abs(c-v), 1)
students = [] def get_students_titlecase(): students_titlecase = [] for student in students: students_titlecase = student.title() return students_titlecase def print_students_titlecase(): student_titlecase = get_students_titlecase() print(students_titlecase) def add_student(name, student_id=223): student...
def posicionesAdyacentes2(self,fila,columna,mapa): retorno=[] #Norte if(fila>=1 and (mapa[fila-1][columna]!="W" and mapa[fila-1][columna]!="X")): retorno.append([fila-1,columna]) #Este if(columna<=10 and (mapa[fila][columna+1]!="W" and mapa[fila][columna+1]!="X")): ...
for t in range(int(input())): a, b, threshold = map(int, input().split()) steps = 0 while a <= threshold and b <= threshold: if a < b: a += b else: b += a steps += 1 print(steps)
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def folly_deps(with_gflags = 1, with_syslibs = 0): if with_gflags: maybe( http_archive, name = "com_github_gflags_gflags", sha256 = "34af2f...
n = int(input().strip()) x = [int(i) for i in input().strip().split(' ')] w = [int(i) for i in input().strip().split(' ')] s = sum([x[i]*w[i] for i in range(0,n)]) wmean = s/sum(w) print("{:0.1f}".format(wmean))
# Solution-1 - Lisa Murray # User needs to enter integer number = input("Please enter a positive integer:") # Number needs to be converted from string format to number format, and add 1 to inclued the number chosen num2 = int(number) + 1 # Creating variable for sum sum = 0 # create loop to loop through all numbers ...
words = ('Oi', 'eu', 'aprendo', 'Python', 'pelo', 'Curso', 'em', 'video') for p in words: print(f'\nNa palavra {p.upper()} temos ', end='') for letra in p: if letra.lower() in 'aeiou': print(letra, end=' ')
# Event: LCCS Python Fundamental Skills Workshop # Date: May 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Purpose: A program to calculate the average height of 5 people # Version: 1.0 (This program contains deliberate errors) print("Average height calculator") print("====================...
class Solution: # @param word1 & word2: Two string. # @return: The minimum number of steps. def minDistance(self, word1, word2): # write your code here if word1 == word2: return 0 if len(word1) == 0: return len(word2) if len(word2) == 0: re...
def analyze(vw): for fva in vw.getFunctions(): analyzeFunction(vw, fva) def analyzeFunction(vw, fva): fakename = vw.getName(fva+1) if fakename is not None: vw.makeName(fva+1, None) vw.makeName(fva, fakename)
"""exercism bob module.""" def response(hey_bob): """ Model responses for input text. :param hey_bob string - The input provided. :return string - The respons. """ answer = 'Whatever.' hey_bob = hey_bob.strip() yelling = hey_bob.isupper() asking_question = len(hey_bob) > 0 and he...
# problem : https://leetcode.com/problems/first-missing-positive/ # time complexity : O(N) class Solution: def firstMissingPositive(self, nums: List[int]) -> int: s = set(nums) ans = 1 for num in nums: if(ans in s): ans += 1 else: brea...
M = [] Schedule = [] def maximum(a,b): if a > b : return a else: return b def calculate_predecessor(jobs,n): p = [0 for i in range(n+1)] cur_job = n chosen_job = cur_job - 1 while cur_job > 1 : if chosen_job <= 0 : p[cur_job] = 0 cur_job=cur_job-1 ...
# This file defines the board layout, as well as some other information # about the bitmaps. BaseName = '@/usr/home/srn/work/scrabble/bitmaps/' Bitmaps = { 'D':{'bitmap':BaseName + 'DW.xbm', 'background':'pink'}, 'd':{'bitmap':BaseName + 'DL.xbm', 'background':'sky blue'}, 'T':{'bitmap':BaseName + 'TW.xbm', 'backgr...
def je_prastevilo(n): if n < 2 or n % 2 == 0: return n == 2 i = 3 while i * i <= n: if n % i == 0: return False i += 2 return True def poljuben_krog(n): return ( 2 * n - 1 ) ** 2 - ( 2 * ( n - 1 ) - 1 ) ** 2 if n != 1 else 1 def je_lih_kvadrat(n): return n *...
# # PySNMP MIB module ASYNCOS-MAIL-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASYNCOS-MAIL-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:13:32 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
def bytes_to_iso(i): numbers = [(1000, 'k'), (1000000, 'M'), (1000000000, 'G'), (1000000000000, 'T')] if i < 1000: return '{} B'.format(i) for n in numbers: if i < n[0] * 1000: return '{:.1f} {}B'.format(i / n[0], n[1]) return '{:.1f} PB'.format(i) def iso_to...
""" basic box type follow: """ BOX_TYPE_FTYP="FTYP" BOX_TYPE_MDAT="MDAT" BOX_TYPE_MOOV="MOOV" BOX_TYPE_UDTA="UDTA" BOX_HEADER_SIZE =8
dataset_type = 'SUNRGBDDataset' data_root = 'data/sunrgbd/' class_names = ('bed', 'table', 'sofa', 'chair', 'toilet', 'desk', 'dresser', 'night_stand', 'bookshelf', 'bathtub') train_pipeline = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=True, lo...
n = int(input()) while n != 0: db = {} for i in range(n): name = input() color_size = input() if color_size in db: aux = db[color_size] aux.append(name) db[color_size] = aux else: db[color_size] = [name] print('') if ...
""" Contains defintions for all custom exceptions raised. """ class ConfigError(Exception): """ Indicates an error with the specified configuration file. """ def __init__(self, message, response=({"status": "Config File Error"}, 500)): super().__init__(message) self.response = response...
"""Production settings unique to the remote gradebook plugin.""" def plugin_settings(settings): """Settings for the canvas integration plugin.""" settings.CANVAS_ACCESS_TOKEN = settings.AUTH_TOKENS.get( "CANVAS_ACCESS_TOKEN", settings.CANVAS_ACCESS_TOKEN ) settings.CANVAS_BASE_URL = settings.E...
""" Design a Tic-tac-toe game that is played between two players on a n x n grid. You may assume the following rules: A move is guaranteed to be valid and is placed on an empty block. Once a winning condition is reached, no more moves is allowed. A player who succeeds in placing n of their marks in a horizontal, vert...
#intitial Variable setup List_Base = [] Image_Scale = [] Image=[] def Input(): # Gets the users input values for the image, makes sure input is exactly 100 characters and only includes 1 and 0 User_Input = str(input("Enter values here: \n")) while any(c.isalpha() for c in User_Input) is True: print("\...
def detail_samtools(Regions, Read_depth): # create a detailed list with all depth values from the same region in a sub list. From samtools depth calculations # samtools generates a depth file with: chr, position and coverage depth value # Regeions comes from the bed file with chr, start, stop, region name ...
"""Demonstrate docstrings and does nothing really.""" def myfunc(): """Simple function to demonstrate circleci.""" return 1 print(myfunc())
# 치즈 접시가 비어 있어요 cheeze = [] # 치즈 접시에 문자열 '치즈'가 무한으로 추가되고, 그때마다 '치즈 추가!'를 출력해요 while True: cheeze.append('치즈') print('치즈 추가!') # cheeze 속 치즈가 50개가 되면 추가를 멈추고 '아이~ 배불러!'를 출력해요 if len(cheeze) == 50: print('아이~ 배불러!') break
# -*- coding: utf-8 -*- """All tests for the project."""
target_prime = 10000 current_num = 2 current_denominator = current_num - 1 while True: if current_denominator == 1: # this is a prime number # print(current_num) target_prime = target_prime - 1 if target_prime == 0: print("Prime number is " + str(current_num)) break current_num = curr...
s = open('day01.txt', 'r').read() left = 0 right = 0 for i in range(len(s)): if s[i] == '(': left += 1 else: right += 1 if left - right == -1: print(i) break
N = int(input()) # input() gets the whole line, int() converts from string to int dictionary = {} # dictionaries appear to work the same as objects in javascript for i in range(0, N): inputArray = input().split() # okay this line is cool, converts indices 1->end of inputArray to floats, puts them in a list ...
# Bo Pace, Oct 2016 # Quicksort # Quicksort has a similar divide-and-conquer strategy to that # of merge sort, but has a space advantage of doing all of the # sorting in place. The worst case complexity is worse than # merge sort, however. Quicksort has a best and average case # complexity of O(nlogn), with a worst cas...
# This file is part of the pylint-ignore project # https://github.com/mbarkhau/pylint-ignore # # Copyright (c) 2020 Manuel Barkhau (mbarkhau@gmail.com) - MIT License # SPDX-License-Identifier: MIT __version__ = "2020.1017"
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: def dfs(nums,index,ans,cur=[]): ans.append(cur) for i in range(index,len(nums)):# 剪枝后树的大小有限 dfs(nums,i+1,ans,cur+[nums[i]]) ans = [] dfs(nums,0,ans) return ans
#Kunal Gautam #Codewars : @Kunalpod #Problem name: CamelCase Method #Problem level: 6 kyu def camel_case(string): return ''.join([x[0].upper()+x[1:] for x in string.lower().split()])
RUN_TEST = False TEST_SOLUTION = 26 TEST_INPUT_FILE = 'test_input_day_11.txt' INPUT_FILE = 'input_day_11.txt' MIN_NUM_SEATS_TO_MAKE_EMPTY = 5 ARGS = [MIN_NUM_SEATS_TO_MAKE_EMPTY] def main_part2(input_file, min_num_seats_to_make_empty): with open(input_file) as file: seat_occupations = list(map(lambda li...
# Problem 1: What will be the output of the following code x = 1 def f(): return x print (x) # Ans-1 print (f()) # Ans-1 #Problem 2: What will be the output of the following program? x = 1 def f(): x = 2 return x print (x) # Ans-1 print (f()) # Ans-2 print (x) # Ans-1 #Problem 3: What wi...
# Code Listing - #12 """ Module palindrome - Returns whether an input string is palindrome or not """ # Note - this is the first version of palindrome, so called palindrome1.py def is_palindrome(in_string): """ Returns True whether in_string is palindrome, False otherwise """ # Case insensitive in_stri...
# https://leetcode.com/submissions/detail/433325047/?from=explore&item_id=3577 # 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 isBalanced(self, root: TreeNode) ->...
''' Given a list of positive integers, the adjacent integers will perform the float division. For example, [2,3,4] -> 2 / 3 / 4. However, you can add any number of parenthesis at any position to change the priority of operations. You should find out how to add parenthesis to get the maximum result, and return the corr...
class constants: # username, Type: String # this email id shouldn't have 2 factor authentication username = "<enter a valid email id>" # password, Type: String password = "<enter the appropriate password>" # to email addresses => Enter a valid to email address and this email id need not disable the...
# Time: O(n) # Space: O(1) # Given two integers n and k, # you need to construct a list which contains n different positive integers ranging # from 1 to n and obeys the following requirement: # Suppose this list is [a1, a2, a3, ... , an], # then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exact...
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: sandwiches = deque(sandwiches) students = deque(students) while not (all(a!=sandwiches[0] for a in students)): if students[0] == sandwiches[0]: students.popleft() ...
class DictX(dict): def __getattr__(self, key): try: return self[key] except KeyError as k: raise AttributeError(k) def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): try: del self[key] ex...
class Model: def __init__(self, model, feature_names): self.model = model self.feature_names = feature_names self.ID = "" def get_ID(self): return self.ID def fit(self, X, y): self.model.fit(X, y) def predict(self, X): return self.model.predict(X) ...
#input={'names_raw':names_raw,'orders_raw':orders_raw,'phones_raw':phones_raw,'emails_raw':emails_raw,'start_index':0,'limit':500,'length':1251} start_index = int(float(input['start_index'])) limit = int(input['limit']) length = int(float(input['length'])) if (start_index+limit) >= length: end_index = length ...
""" Utility functions for canary tests """ CANARY_TYPES = ["cpu_noise", "fio", "iperf"] def should_run(config): """ Checks if canary tests should run. """ if "canaries" in config["bootstrap"] and config["bootstrap"]["canaries"] == "none": return False if "canaries" in config["test_control...
print(f'{"LISTA DE JOGOS DE PS4:":^38}') #O ^ serve para centralizar jogos = ('God of War', 80, 'Red Dead Redemption 2', 250, 'Dying Light', 150, 'Horizon Zera Dawn', 80, 'The Last of Us: Part 2', 280, "Marvel's Spider-Man", 130, 'Death Stranding', 146.50, 'Bloodborne', 80, 'Sekiro: Shadows Die Twice'...
''' def find( element, list): for i, j in enumerate( list): if( j == element): return i; return -1 data_path = "../data/data_uci.pgn" fd = open( data_path) ''' def find( element, list): for i, j in enumerate( list): if( j[0:2] == element): return i; return -1 data_path = "../data/data_uci.pgn" ...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
# -*- coding: utf-8 -*- """ Created on Tue Oct 2 13:17:03 2018 @author: michaelek """ ##################################### ### Misc parameters for the various functions hydro_server = 'edwprod01' hydro_database = 'hydro' crc_server = 'edwdev01' crc_database = 'ConsentsReporting' allo_table = 'reporting.CrcAlloSite...
"""Internal utilities (not exposed to the API).""" def pop(obj, *args, **kwargs): """Safe pop for list or dict. Parameters ---------- obj : list or dict Input collection. elem : default=-1 fot lists, mandatory for dicts Element to pop. default : optional Default value....
numbers = [1,3,5,4,6,2,8,9,7] prime_numbers = [] non_prime_numbers = [] i = 0 while i < len(numbers): if numbers[i] % 2 == 0: prime_numbers.append(numbers[i]) else: non_prime_numbers.append(numbers[i]) i += 1 print(f'Obshii spisok {numbers}') print(f'4etnye 4islami: {prime_numbers}') print...
# # PySNMP MIB module TRAPEZE-NETWORKS-INFO-RF-DETECT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-INFO-RF-DETECT-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:27:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Usi...
# Created by MechAviv # Kinesis Introduction # Map ID :: 331001000 # Hideout :: HQ JAY = 1531001 sm.setNpcOverrideBoxChat(JAY) if sm.sendAskYesNo("You lost your gear? Ugh, dude! Don't trash my stuff! It takes time to hack those things together. Here, I have backups of your primary and secondary, but only the basic mo...
class RealtimeException(Exception): pass class ParseFailureException(Exception): """Failure to parse a logical replication test_decoding message"""
users = [] class User(): def __init__(self, username, pin, balance=0): self.username = username self.pin = pin self.balance = balance def deposit(self, amount): self.balance += amount print(f"Deposited ${amount} into account {self.username}") self.print_balance(...
def is_it_true(anything): if anything: print('yes, it is true') else: print('no, it is false')
# -*- coding: utf-8 -*- def split_data(filename): data = {} with open(filename, 'r') as openFile: f = openFile.readlines()[1:] for line in f: line_elements = line.rstrip('\r\n').split(',') key = line_elements[1] if key in data: data[key].appen...
""" Created by Epic at 9/1/20 """ class HTTPException(Exception): """Exception that's thrown when an HTTP request operation fails.""" def __init__(self, request, data): self.request = request self.data = data super().__init__(data) class Forbidden(HTTPException): """Exception tha...
# -*- coding:utf-8 -*- sinhala_rashi=["මේෂ","වෘෂභ","මිථුන","කටක","සිංහ","කන්‍යා","තුලා","වෘශ්චික","ධනු","මකර","කුම්භ","මීන"] sinhala_rashis_short=[ "මේ","වෘෂ","මිථු", "කට","සිං","කං", "තුලා","වෘශ්","ධනු", "මක","කුම්","මීන"] sinhala_planets_short={ "Sun":"ර", "Moon":"ච", "Moon_Node":"රා", "Moon_S_Nod...
# Duolingo username and password USERNAME = 'username' PASSWORD = 'password' # Locations # Production # DB_FILE = r"db/personal.db" # LOG_DIR = 'path to logging directory' # WEB_PAGE = 'path to destination web page' # TEMPLATE_PAGE = 'path to template for web page' # Development & Test DB_FILE = r"db/personal.db" L...
print("Question 1:") ''' Use for, .split(), and if to create a Statement that will print out words that start with 's': st = 'Print only the words that start with s in this sentence' ''' st = 'Print only the words that start with s in this sentence' list_worlds = st.split(' ') for word in list_worlds: if word[0] ...
print('Digite seu nome:') nome = input() print('Digite sua idade:') idade = int(input()) podeVotar = idade>=16 print(nome,'tem',idade,'anos:',podeVotar)
# _*_ coding: utf-8 _*_ class NullURLError(Exception): '''空URL异常''' pass
OK = '+OK\r\n' def reply(v): ''' formats the value as a redis reply ''' return '$%s\r\n%s\r\n' % (len(v), v)
lost_fights = int(input()) helmet_price = float(input()) sword_price = float(input()) shield_price = float(input()) armor_price = float(input()) shield_repair_count = 0 total_cost = 0 for i in range(1, lost_fights+1): if i % 2 == 0: total_cost += helmet_price if i % 3 == 0: total_co...
# -*- coding: utf-8 -*- def get_version_info(): """Provide the package version""" VERSION = '0.0.2' return VERSION __version__ = get_version_info()
def end_other(a, b): a = a.lower() b = b.lower() if a[-(len(b)):] == b or a == b[-(len(a)):]: return True return False
""" This module contains the result sentences and intents for the German version of the Assistant information app. """ # Result sentences RESULT_ASSISTANT_APPS = "Ich habe {} apps: {}." RESULT_ASSISTANT_ID = "Meine ID ist {}." RESULT_ASSISTANT_INTENTS = "Ich kenne {} Befehle." RESULT_ASSISTANT_NAME = "Mein Name ist {}...
class ParameterTypeError(Exception): """Exception raised for errors in the input parameter. Attributes: parameter -- input parameter which caused the error message -- explanation of the error """ def __init__(self, parameter, parameter_name, parameter_type, message="The parameter can only be of type {}!"): ...
""" Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following is not: 1 / \ 2 2 \ \ 3 3 """ # Definition for a binary tree node. # class TreeNode(object): #...
#%% """ TQC+ 程式語言Python 701 串列數組轉換 請撰寫一程式,輸入數個整數並儲存至串列中, 以輸入-9999為結束點(串列中不包含-9999), 再將此串列轉換成數組,最後顯示該數組以及其長度(Length) 、最大值(Max)、最小值(Min)、總和(Sum)。 輸入說明 n個整數,直至-9999結束輸入 輸出說明 數組 數組的長度 數組中的最大值 數組中的最小值 數組內的整數總和 範例輸入 -4 0 37 19 26 -43 9 -9999 範例輸出 (-4, 0, 37, 19, 26, -43, 9) Length: 7 Max: 37 Min: -43 Sum: 44 """ ll=[] x=i...
""" The Zen of SymPy. """ s = """The Zen of SymPy Unevaluated is better than evaluated. The user interface matters. Printing matters. Pure Python can be fast enough. If it's too slow, it's (probably) your fault. Documentation matters. Correctness is more important than speed. Push it in now and improve u...
print('\033[1;4;35mGerador de PA\033[m') print('+='*15) p1 = int(input('Digite o primeiro termo: ')) raz = int(input('Digite a razão: ')) var = 0 while var != 10: print(p1, end=' - ') var = var + 1 p1 = p1 + raz print('Acabou!')
class PermissionBackend(object): supports_object_permissions = True supports_anonymous_user = True def authenticate(self, **kwargs): # always return a None user return None def has_perm(self, user, perm, obj=None): if user.is_anonymous(): return False if pe...
#Şule Nur Yılmaz - 170401058 def oku(): #asallar.txt verileri oku - diziye ata - diziyi döndür f = open("asallar.txt","r") text = f.readlines() f.close() asallar = list() for i in text: asallar.append(int(i)) return asallar #Global Veriler 3. derece polinom yakınlaştırm...
class A: def m(): pass def f(): pass
# -*- encoding: utf-8 -*- class KlotskiBoardException(Exception): def __init__(self, piece, kind_message): message = "Wrong board configuration: {} '{}'".format(kind_message, piece) super().__init__(message) class WrongPieceValue(KlotskiBoardException): def __init__(self, x): super()...
''' A curious problem that involves 'rotating' a number and solving a number of contraints Author: Daniel Haberstock Date: 05/26/2018 Sources used: https://stackoverflow.com/questions/19463556/string-contains-any-character-in-group ''' def rotate(x): # split up the integer into a list of single digit strings ...
def extractAlpenGlowTranslations(item): """ 'Alpen Glow Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None tagmap = { 'Shu Nv Minglan' : 'The Legend of t...
n1 = int(input('insira o 1 numero')) n2 = int(input('insira o 2 numero')) soma = n1 + n2 sub = n1 - n2 div = n1/n2 mul = n1 * n2 pot = n1 ** n2 divint = n1 // n2 res = n1 % n2 print('soma = ', soma) print('Sub = ', sub) print('Divisão = ', div) print('multiplicação', mul) print('potencia = ', pot) print('Divisão inteir...
S = input() ans = ( 'YES' if S.count('x') <= 7 else 'NO' ) print(ans)
{ "targets": [ { "target_name": "node-hide-console-window", "sources": [ "node-hide-console-window.cc" ] } ] }
# Escreva um programa que exiba uma lista de opções (menu): adição, subtração, divisão, multiplicação e sair # Imprima a tabuada da operação escolhida # Repita até que a opção saída seja escolhida def line(size): print('-' * size) while True: print() line(30) print('MENU' .center(30)) line(30) ...
class Node(): left = None right = None def __init__(self, element): self.element = element def __str__(self): return "\t\t{}\n{}\t\t{}".format(self.element, self.left, self.right) class BinaryTree(): head = None def __init__(self, head): self.head = Node(head...
# n=int(input()) # n2=input() # ar=str(n2) # ar=ar.split() # pair={} # total=0 # for i in ar: # if i not in pair: # pair[i]=1 # else: # pair[i]+=1 # for j in pair: # store=pair[j]//2 # total+=store # print (total) n=int(input("number of socks :")) ar=input("colors of socks :").split()...
class Solution: def trap(self, height: List[int]) -> int: lmax,rmax = 0,0 l,r = 0,len(height)-1 ans = 0 while l<r: if height[l]<height[r]: if height[l]>=lmax: ...
lanjut = 'Y' kumpulan_luas_segitiga = [] while lanjut == 'Y': alas = float(input("Masukkan panjang alas (cm) : ")) tinggi = float(input("Masukkan tinggi segitiga (cm) : ")) luas = alas * tinggi * 0.5 # / 2 print("Luas segitiganya adalah :", luas) kumpulan_luas_segitiga.append(luas) lanjut = input("\nMau...
""" Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке. """ def read_file(path): res = [] with open(path, "r") as f: res = f.readlines() return res def main(): file_name = "task2_data.txt" task2_...
class StringFormatter(object): def __init__(self): pass def justify(self, text, width=21): ''' Inserts spaces between ':' and the remaining of the text to make sure 'text' is 'width' characters in length. ''' if len(text) < width: index = text.find...
input_str = "12233221" middle_size = int(round(len(input_str) / 2) ) print(f"middle_size: {middle_size}") end_index = -1 start_index = 0 while start_index < middle_size: char_from_start = input_str[start_index] char_from_end = input_str[end_index] end_index = end_index - 1 start_index = start_index...
def main(self): def handler(message): if message["channel"] == "/service/player" and message.get("data") and message["data"].get("id") == 5: self._emit("GameReset") self.handlers["gameReset"] = handler