content
stringlengths
7
1.05M
preço = float(input('Qual é o preço do produto? R$')) novo = preço - (preço * 5 / 100) print('O produto que custava R${:.2f} agora na promoção com desconto de 5% irá custar R${:.2f}'.format(preço,novo))
# 🚨 Don't change the code below 👇 year = int(input("Which year do you want to check? ")) # 🚨 Don't change the code above 👆 #Write your code below this line 👇 if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: leapyear = True else: leapyear = False ...
def decorator_maker(): print("Я создаю декораторы! Я буду вызван только раз: когда ты попросишь " "меня создать декоратор.") def my_decorator(func): print("Я - декоратор! Я буду вызван только раз: в момент декорирования функции.") def wrapped(): print ("Я - обёртка вокруг д...
# Extra Exercise 005 """Make a program that calculates the area of a square, then show double this area to the user.""" square_base = float(input("Insert the base value: ")) square_height = float(input("Insert the height value: ")) square_area = square_base * square_height print( f"The square area is {square_area...
# The following method includes .format() methd to write in a csv file. Otherwise .join() method can be used on ',' when all the elements are string # and there is no extra comma in between a chunk of string. Follow the code below: olympians = [("John Aalberg", 31, "Cross Country Skiing"), ("Minna Maarit ...
#2) Refaça o exercício da questão anterior, imprimindo os retângulos sem preenchimento, #de forma que os caracteres que não estiverem na borda do retângulo sejam espaços. largura = int(input("Coloque a largura: ")) print("") altura = int(input("Coloque a altura: ")) print("") caractere = "#" def retângulo(largura, a...
# Copyright 2016 - Wipro Limited # # 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 writin...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- """ TODO: Helper functions for Trex traffic generators. """ def th_hello(): print("Hello from Trex helpers.")
tables = [ "title.principals.csv", "title.akas.csv", "title.ratings.csv", "title.basics.csv", "name.basics.csv" ] data_cardinality = { "3GB":{ "title.principals": 36499704, "title.akas": 19344171, "title.ratings": 993821, "title.basics": 6326545, "name.basics": 9711022 }...
list1 = [] input_str1 = input("Please input a word: ") str1 = input_str1.lower() list1 = list(str1) for item in list1: if item == 'a' or item == 'e' or item == 'i' or item == 'o' or item == 'u': while True: try: list1.remove(item) except: break output = ''.join(list1).capitalize()...
def reverse_words(s): return ' '.join(s.split(' ')[::-1]) # Best Practices def reverseWords(str): return " ".join(str.split(" ")[::-1])
def get_setup_cfg_file(params): """Get a ``setup.cfg`` file. Args: params (dict): Parameters for this project. Returns: tuple: Relative file path and string content of file. """ bdist_wheel_universal = int(params.get("bdist_wheel_universal", 1)) return "setup.cfg", _SETUP_CFG....
# encoding: utf-8 START_SERVERS = u'Start DNS Server' STOP_SERVERS = u'Stop DNS Server'
# Problem 7 100001st Prime primes = [] number = 1000000 for x in range(2, number+1): isPrime = True for y in range(2, int(x**0.5)+1): if x%y ==0: isPrime = False break if isPrime: primes.append(x) if len(primes) == 10001: print(primes[-1]) break
# Annette Chun # amc4sq # 02/22/16 # helper.py __author__ = 'Annette Chun' def greeting(msg): print(msg)
# -*- coding: utf-8 -*- # Jamdict-web - Japanese Reading Assistant # This code is a part of jamdict-web library: https://github.com/neocl/jamdict-web # :copyright: (c) 2021 Le Tuan Anh <tuananh.ke@gmail.com> # :license: MIT, see LICENSE for more details. __author__ = "Le Tuan Anh" __email__ = "tuananh.ke@gmail.com" _...
""" Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. >>> # extract 100 LDA topics, using default parameters >>> lda = LdaModel(corpus=mm, id2word=id2word, ... num_topics=100, distributed=distribution_required) Intermediate output .. code-blo...
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str >>> sln = Solution() >>> sln.reverseWords("the sky is blue") 'blue is sky the' >>> sln.reverseWords(" ") '' """ return " ".join(filter(lambda x: x != '', re...
alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") def cipher(text,key): new_text = "" for index,letter in enumerate(text): offset = key[index%len(key)] try: position = alphabet.index(letter.upper()) new_position = (position+offset)%len(alphabet) new_text+=alphabe...
#crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. #no final, mostre uma listagem de preços organizado os dados em forma tabular. print('=' * 40) print(f'{"~ LISTAGEM DE PREÇOS ~":^40}') #titulo print('=' * 40) listagem = ('Lápis', 1.75, 'Borracha', 2,...
amber99_dict = { 'NHE': [ ( 'N<0>([H]<1>)([H]<2>)', { 0: ('N' , 'N' , -0.4630, 1.8240), 1: ('HN1' , 'H' , 0.2315, 0.6000), 2: ('HN2' , 'H' , 0.2315, 0.6000), }, ), ], 'NME': [ ( 'N<0>([H]<1>)[C@]<2>([H]<3>)([H]<4>)[H]<5>', { ...
s=[] for x in range(6): s.append(input()) a=[] sizes=[] for x in s: a.append(x.split()) row=[] sum1=[] w=[] for k in range(4): for z in range(4): e=[] for x in range(3): e.append(a[x+k][z]) e.append(a[x+k][z+1]) e.append(a[x+k][z+2]) w.append(e) su...
"""Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante ‘a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico. Ex: n = leiaInt(‘Digite um n: ‘)""" def leiaint(msg): ok = False valor = 0 while True: n = str...
# TODO: Add some sort of benchmarks array_of_numbers = [4, 6, 1, 0] def merge(right, left, output=list()): """ This function merges two sorted lists. :param right: :param left: :param output: :return: """ if not right and not left: return output if left: left_min ...
def g(x): return x**2 def gp(x): return 2*x def gpp(x): return 2 def h(x): return 0.5*(x[0]**2 + x[1]**2) def H(X,Y): return 0.5*(X**2 + Y**2)
# -*- encoding: utf-8 -*- __all__ = [ 'validate_page', ] def validate_page(text: str) -> bool: result = True preps = [ text == '{"error":"Not Found"}', "<title>Группы Google</title>" in text, '<title>Git and Mercurial code management for teams</title>' in text, "- Google ...
class Solution: def reverseParentheses(self, s: str) -> str: stack = [''] for c in s: if c == '(': stack.append('') elif c == ')': add = stack.pop()[::-1] stack[-1] += add else: stack[-1] += c ...
""" Created on Jul 11, 2016 @author: ramseylab """ REGULAR_CHR_ID = set([str(x) for x in range(1, 23)] + ["X", "Y"]) # range(1,23) = 1,2,...,22 REGULAR_CHR = {("chr" + str(x)) for x in REGULAR_CHR_ID} HOMO_SAPIENS_MITO_SEQ = "chrM" HAPLOTYPE_CHR = { "chr6_apd_hap1", "chr6_cox_hap2", "chr6_dbb_hap3", ...
intro_list= [ "Hi there, sir looking forward to see you", "Greetings sir, welcome back", "Hey There, what took you so long,i was waiting for you", "How’s everything going sir? ", "Good to see you sir, you look amazeing today", "Great to see you. i hope you are having a nice day sir", "Nice to see you sir...
def print_numeric_list(number_list): print('------------------ START LIST ------------------') for number in number_list: print('{} -> {}'.format(number_list.index(number), number)) print('------------------ END LIST ------------------') numberList = [1] print_numeric_list(numberList) numberLi...
class Solution: def multiply(self, num1: str, num2: str) -> str: s = [0] * (len(num1) + len(num2)) for i in reversed(range(len(num1))): for j in reversed(range(len(num2))): mult = int(num1[i]) * int(num2[j]) summ = mult + s[i + j + 1] s[i + j] += summ // 10 s[i + j + 1] ...
# -*- coding: utf-8 -*- """ Author: Michael Markus Ackermann ================================ Metadata strings """ # For air class temp_md = ("Enverioment temperature", "Should be Celsius degrees [°C]") hum_md = ("Relative humidity", "Should be in as percentage [%]") atm_md = ("Atmospheric pressure", "Should be in Pas...
ANSI_TKL = [ {'Key': 'Key.esc', 'Pos': [0, 0], 'Size': [1, 1], }, {'Key': "SPACER", 'Pos': [0, 1], 'Size': [1, 1], }, # Spacer {'Key': 'Key.f1', 'Pos': [0, 2], 'Size': [1, 1], }, {'Key': 'Key.f2', 'Pos': [0, 3], 'Size': [1, 1], }, {'Key': 'Key.f3', 'Pos': [0, 4], 'Size': [1, 1], }, {'Key': 'Ke...
""" Simulation of Buffon's Coin Problem. """ def predict_prob(diameter=1.0, gap_width=1.0): """ Predicts the probability that the coin will hit the grid. """ d = diameter D = gap_width if d >= D: return 1.0 else: return ( 1.0 - (D - d) ** 2 / ...
# V0 # V1 # https://blog.csdn.net/qq_32424059/article/details/86998300 class MyCircularQueue(object): def __init__(self, k): """ Initialize your data structure here. Set the size of the queue to be k. :type k: int """ self.queue = [""] * k self.max_length = k ...
class DummyLogger: def debug (self, *arg): pass def info (self, *arg): pass def error (self, *arg): pass def critical (self, *arg): pass
_base_ = [ '../_base_/models/gma/gma_p-only.py', '../_base_/datasets/flyingchairs_raft_368x496.py', '../_base_/default_runtime.py' ] optimizer = dict( type='AdamW', lr=0.00025, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.0001, amsgrad=False) optimizer_config = dict(grad_clip=dict(...
class Median: def findMedianSortedArrays(self, nums1, nums2): new=sorted(nums1+nums2) x=len(new) if x%2==1: return new[int(x/2)] elif x%2==0: return (new[int(x/2)]+new[int(x/2)-1])/2 if __name__=="__main__": a=[1,2] b=[3] c=[1,283,4577,609] d=[...
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. https://leetcode.com/problems/palindrome-number/ """ class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False str_x = str(x) return st...
class TreeNode: __slots__ = ['left', 'right'] def __init__(self, value: int): self.value = value
class Cbox: """Class to hold ciphertext and implement helper functions""" def __init__(self, keylength, ciphertext): self.MAX_KEYLENGTH = 16 self.set_keylength(keylength) if ciphertext is not None: self.set_ctext(ciphertext) if not self.sanity_check(): ...
def is_palindrome(x): l = len(a) for i in range(int((l-l%2)/2)): if a[i] == a[l-i-1]: continue else: print(x," is not palindrome") return False return True a= input("Please enter the palindrome digit \n") if is_palindrome(a): l = len(a) if int(a)!=9: a = list(a) for i in range(int((l-l%2)/2),l):...
# # PySNMP MIB module CISCO-TRUSTSEC-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TRUSTSEC-TC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:57:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2013-04-22 16:15:32 class RoomManager(object): def __init__(self): self.rooms = {} def new(self, meta): if meta['hash'] in self.ro...
class Solution: def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ rootSet = set(dict) words = sentence.split() for i in range(len(words)): for j in range(min(len(words[i]), 100)): ...
""" Copyright 2018 Inmanta Contact: code@inmanta.com License: Apache 2.0 """ def test_dryrun(project): basemodel = """ import testmodule r = testmodule::Resource(agent="a", name="IT", key="k", value="write") """ project.compile(basemodel) changes = project.dryrun_resource("testmo...
with open("td9_graph_lworld.txt", "r") as f : lines = f.readlines() links =[] for line in lines : spl = line.strip("\n\r ").split(",") if len(spl) == 2 : l = { "source":spl[0],"target":spl[1],"type":"-"} links.append(l) l = { "source":spl[1],"target":spl[0],"type":"-"} l...
def func(b=None, a=None): pass func(a=1)
# -*- coding: utf-8 -*- class DiscordException(Exception): """Base exception class for discord.py Ideally speaking, this could be caught to handle any exceptions thrown from this library. """ pass class NoMoreItems(DiscordException): """Exception that is thrown when an async iteration operation h...
# Header used to check if it's an UPX file UPX_STRING = b"UPX!" # Header used to find the config offset ([ss] after unxor) CONFIG_HEADER = b"\x15\x15\x29\xD2" # Size of every element in the config space CONFIG_SIZE = 428 SIGNATURE1_SIZE = 96 SIGNATURE2_SIZE = 96 CONFIG_VERSION_SIZE = 4 CONFIG_TOTAL_SIZE = CONFIG_SIZE...
PremiumPaymentGateway = { 'id': 1, 'status_code': 200, 'payment_gateway': 'PremiumPaymentGateway' } ExpensivePaymentGateway = { 'id': 2, 'status_code': 200, 'payment_gateway': 'ExpensivePaymentGateway' } CheapPaymentGateway = { 'id': 3, 'status_code': 200, 'payment_gateway': 'Cheap...
#lists li = [45,54,56,'dtr',True,54.76] mytuple = (34,34,34,23,45,56,2,32,56,24) ''' #index print(li[4]) #negative indexing print(li[-1]) print(li[2]) #slicing print(li[2:5]) print(li[3:]) print(li[:]) print(li[:4]) ''' # integers #mutability, immutability a = 10 print(a) print(id(a)) ...
name_list = ["鈴木", "佐藤", "山田"] position = ["部長", "課長", "係長"] # 配列の要素番号を指定して値を呼び出してみよう! print(name_list[0] + position[0]) print(name_list[1] + position[1]) print(name_list[2] + position[2])
# The Python versions of list comprehensions found in Graham Hutton's # "Programming Haskell" book, chapter 5. [ x**2 for x in range(1,6) ] [ (x,y) for x in range(1,4) for y in range(4,6) ] [ (x,y) for x in range(1,4) for y in range(x,4) ] concat = lambda xss: [ x for xs in xss for x in xs ] firsts = lambda ps: [ ...
# Shift cipher # Used with the shift and ceasar option of ciphers def encrypt(message, shift): shift = int(shift) result = "" for i in range(len(message)): char = message[i] if(char.isupper()): result += chr((ord(char)+ shift-65) % 26 + 65) elif(char.islower()): result += chr((ord(char) + shift-97) % 2...
class Person: def __init__(self, name, age): self.name = name self.age = age def say_hi(self): print('Hello, my name is', self.name) person = Person('Sun Jinbo', 20) print(person) person.say_hi() class Robot: poplulation = 0 def __init__(self, name): self.name = nam...
#encoding:utf-8 subreddit = 'TikTok_Tits' t_channel = '@r_TikTok_Tits' def send_post(submission, r2t): return r2t.send_simple(submission)
""" @function: the implement of Merge Sort """ def Merge(A,B): i = 0 j = 0 result = [] for k in range(len(A)+len(B)): if i < len(A) and j < len(B): if A[i] < B[j]: result.append(A[i]) i += 1 elif B[j] < A[i]: result.app...
class Foreign: def __init__(self,nombreConstraint:str,columnas:list,nombreTablaReferencia:str, columnasOtraTabla:list): self.nombreConstraint = nombreConstraint self.columnas = columnas self.nombreTabla = nombreTablaReferencia self.columnasrefer = columnasOtraTabla
""" 总结 - 函数参数 实际参数:与形参进行对应 位置实参:根据顺序 函数名(数据1,数据2) 序列实参:拆 函数名(*序列) 关键字实参:根据名字 函数名(形参名=数据1,形参名=数据2) 字典实参:拆 函数名(**字典) 形式参数:限制实参 位置形参:必填 ...
def longest_equal_subarray2(A): longest = cnt = 0 n = len(A) for i in range(n): for j in range(i, n): cnt += 1 if A[j] else -1 if cnt == 0: longest = max(longest, j - i + 1) return longest def longest_equal_subarray(nums): d = {0: -1} ...
input = """ """ output = """ {-p(1), number(1), number(2), p(2)} """
class Settings_lvl1(): """ A class to sotre all setting for alien Invasion.""" def __init__(self): #Initialize the game's settings. self.screen_widht = 800 self.screen_height = 600 self.bg_color = (230,230,230) # Character Settings self.assasin_speed_factor...
#!/usr/bin/python class GrabzItCookie: def __init__(self, name, value, domain, path, httponly, expires, type): self.Name = name self.Value = value self.Domain = domain self.Path = path self.HttpOnly = httponly self.Expires = expires self.Type = type
# Hash Table; Stack # Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. # For example, given the list of temperatures T = [73, 74, 75,...
# -*- coding: utf-8 -*- class A: i = 5 def getI(self): print ("self.i: ", self.i) one = A() one.getI()
#!/usr/bin/env python3 # https://abc099.contest.atcoder.jp/tasks/abc099_a n = int(input()) if n < 1000: print('ABC') else: print('ABD')
if __name__ == "__main__": xt101_radio = xt101('COM9', 247) xt101_radio.send_message(0x1234, [1,2,4,5]) print("Mac:", xt101_radio.get_mac_address()) time.sleep(0.75) print("Sink:", xt101_radio.get_sink_address()) time.sleep(0.75) print("Firmware:", xt101_radio.get_...
# Exercise 1 i = 0 while i < 5: print(f'This is lap {i}') i += 1 # Exercise 2 keep_printing = True while keep_printing: v = input("Write Something:") if v == "quit": print("Bye bye!") keep_printing = False else: print(v) # Exercise 3 number = int(input("Give a number:"))...
for i in range(1,999): params = dict( pin=i ) resp=requests.get(url=url,params=params) data = resp.json() if(data["accept"] == "Yesss"): print(i, resp.json())
class ConsoleBot: def __init__(self, system): self.system = system def start(self, input_utt): # 辞書型 inputにユーザIDを設定 input = {'utt': None, 'sessionId': "myid"} # システムからの最初の発話をinitial_messageから取得し,送信 return self.system.initial_message(input) def message...
# SPDX-License-Identifier: Apache-2.0 # @version 1.0.0 rules = { "sol": {"shebang": False, "comment": ["///", "/*", "//"],}, "rs": {"shebang": False, "comment": ["//", "/*"],}, "py": {"shebang": True, "comment": ["#"],}, }
""" Select contains functions for getting keys from values, values from keys, and regex helpers for selecting a value from a list. """ class Select(): # Initialisation. def __init__(self, d): self.dict = d # Gets the key from a value in a select. def get_key(self, v): for k,val in sel...
class Solution: def reverseVowels(self, s: str) -> str: vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] new_s = [c for c in s] l, r = 0, len(s) - 1 while l < r: if s[l] not in vowels: l += 1 continue if s[r] not in v...
#palíndromo: Palavra ou frase que pode ser lida de traz pra frente idependente de espaços na frase. #Ex: "A base do teto desaba" == "abased otet od esab A" frase = input('Digite uma frase:').strip().upper() frase_quebrada = frase.split() frase_juntada = ''.join(frase_quebrada) quantidade_de_caracteres = len(frase_junta...
class Optimizer: def step(self, model): raise NotImplementedError class GD(Optimizer): def __init__(self, lr=0.001): self.lr = lr def step(self, model): for layer, name, param, grad in model.params_and_grads(): layer.params[name] = param - self.lr*grad...
########################################################################## # # Processor specific code # CPU = "Z80" # Description = "Zilog 8-bit microprocessor." # DataWidth = 8 # 8-bit data # AddressWidth = 16 # 16-bit addresses # Maximum length of an instruction (for formatting purposes) maxLength = 4 # Leadin ...
def min_platforms(arrival, departure): arrival.sort() departure.sort() platform_count = 1 output = 1 i = 1 j = 0 while i < len(arrival) and j < len(arrival): if arrival[i] < departure[j]: platform_count += 1 i += 1 if platform_count > output: ...
# -*- coding: utf-8 -*- """ Created on Mon May 30 18:27:14 2022 @author: Martin Johnson """
# Copyright 2016, Kay Hayen, mailto:kay.hayen@gmail.com # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
class Solution: def XXX(self, n: int) -> int: nums=[] nums.append(1) nums.append(2) if n>2: for i in range(2,n,1): nums.append( nums[-1] + nums[-2] ) return nums[n-1]
def foo(): def bar(): def baz(): pass # baz 1 # baz 2 # baz 3 # bar # foo
# Write a function on_all that applies a function to every element of a list. # Use it to print the first twenty perfect squares. # The perfect squares can be found by multiplying each natural number with itself. # The first few perfect squares are 1*1= 1, 2*2=4, 3*3=9, 4*4=16. # Twelve for example is not a perfect...
class Node: def __init__(self,value, next=None): self.value = value self.next = next self.read = 0 class Queue: def __init__(self, front=None, rear=None): self.front = front self.rear = rear def enqueue(self, value): node = Node(value) if not self.front: self.front = node ...
class parser_base(object): def __init__(self, file_body, **kwargs): # self.body = file_body # Include any optional key word arguments that were provided in # the instance dictionary self.__dict__.update(kwargs) # Initialize the dictionary that will receive parsed ...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': result = root while True : if p.val < result.val and q.val < re...
if __name__ == '__main__': a = int(input()) b = int(input()) int_result = int(a/b) float_result = a/b print(int_result) print(float_result)
n1 = int(input("Digite um número inteiro: ")) n2 = int(input("Digite um número inteiro: ")) n3 = int(input("Digite um número inteiro: ")) n4 = int(input("Digite um número inteiro: ")) n5 = int(input("Digite um número inteiro: ")) lista = [n1, n2, n3, n4, n5] print("A soma dos números da lista é: ", sum(lista))
#!/usr/bin/python # egyptian opentype generator data qcontrols = ['vj','hj','ts','bs','te','be','om','ss','se','cb','ce','cre','cfb','cfe','hwtb','hwte','hwttb','hwtte','hwtbb','hwtbe','hwtfb','hwtfe','dottedcircle','O33aEL','O33aER','O33aEB'] featurename = { 'abvs' : {'prefix':'ab','name':'Above-base Substitutions'...
# # Exercício 3.8 Escreva um programa que leia um valor em metros e o exiba convertido em milímetros. metros = float(input('digite um valor em metros ')) centimetros = metros*100 print ("a conversão dos metros em centimetros resultou em %4.2f centimetros" % (centimetros)) #podemos fazer varios tipos de conversores u...
# success try: 49551052 , 17 мар 2021, 15:09:45. 51ms 3.95Mb def binary_search(array, required, from_index: int, to_index: int) -> int: """ Just one more version of binary search in sorted array @param from_index: Index to search from @param to_index: Index to search to @return: Index of required e...
""" This problem was asked by Google. Given a string, return the first recurring character in it, or null if there is no recurring character. For example, given the string "acbbac", return "b". Given the string "abcdef", return null. """ def first_recurring_char(string): char_to_freq_map = {} for char in s...
y = 1 x = 0 while y <= 5: x += 1 x = 0 while False: x += 1 x = 0 while x == 2: x += 1 x = 0 while 2 <= 2: x += 1 x = 0 while True: x += 1
class Solution: def findDuplicate(self, nums: list) -> int: slow = nums[nums[0]] fast = nums[nums[nums[0]]] while fast != slow: slow = nums[slow] fast = nums[nums[fast]] start = nums[0] while start != slow: sl...
def test(): return True
#!/usr/bin/env python def extract_arguments(call): # Replace any leftover multiple whitespaces with single whitespaces call = ' '.join(call.split()) # Extract arguments part of call args_start = call.find('(') args_end = call.rfind(')') args_str = (call[args_start+1:args_end]).strip() args_...
# The API: int read4(char *buf) reads 4 characters at a time from a file. # The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file. # By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the f...
# Remove White Spaces from a string userInput = input("Enter a String: ") lists = userInput.split() newValue = "" for i in lists: newValue += str(i) print(newValue)
def extractPockysbookshelfCom(item): ''' Parser for 'pockysbookshelf.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('I Tamed a Tyrant and Ran Away', ...
map = { "U": (-3, []), "D": (+3, []), "L": (-1, [4, 7]), "R": (+1, [3, 6]), } def aoc(data): button = 5 code = "" for line in data.split("\n"): for step in line: new = button + map[step][0] if 0 < new <= 9 and not button in map[step][1]: butt...