content
stringlengths
7
1.05M
def get_next_value(v): v *= 252533 return v % 33554393 x = 1 y = 1 val = 20151125 while True: if y == 1: y = x + 1 x = 1 else: x += 1 y -= 1 # print(x, y) val = get_next_value(val) if x == 3083 and y == 2978: print(val) break
class command_base : def __init__(self): self.talk = False self.talkNum = 0
#-*- coding:utf-8 -*- """ RSA Utils This submodule comprises of RSA utilities, and common exploit scripts. The tool also features RSA Analyser. """
class Solution: def maxScoreSightseeingPair(self, A: List[int]) -> int: maxAi, result = 0, 0 # max Ai keeps track of best encountered till now A[i]+i. # result keeps finding better results across all j's. for j in range(len(A)): result = max(maxAi+A[j]-j, result) ...
""" Author: James Ma Email stuff here: jamesmawm@gmail.com """ """ API doumentation: https://www.interactivebrokers.com/en/software/api/apiguide/java/reqhistoricaldata.htm https://www.interactivebrokers.com/en/software/api/apiguide/tables/tick_types.htm """ FIELD_BID_SIZE = 0 FIELD_BID_PRICE = 1 FIELD_ASK_PRICE = 2 F...
#!/usr/bin/env python imagedir = parent + "/oiio-images" command = rw_command (imagedir, "oiio.ico")
# -*- coding: utf-8 -*- """Config file for getting IP, email and encryption. """ # Config of getting public IP from router # You should get them from browser after logging in router ROUTER_IP_URL = 'http://192.168.0.1/userRpm/StatusRpm.htm' AUTHORIZATION_HEADERS = { 'Authorization': 'Basic YWRtaW46SklNNDgxNDg2MGpp...
triangle = '''75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 ...
"""Base class for implementing Lambda handlers as classes. Used across multiple Lambda functions (included in each zip file). Add additional features here common to all your Lambdas, like logging.""" class LambdaBase(object): @classmethod def get_handler(cls, *args, **kwargs): def handler(event, contex...
# possible cell states, bitwise-flags CELL_MINE = 1 CELL_REVEALED = 2 CELL_FLAGGED = 4 CELL_HIDDEN = 8 CELL_EMPTY = 16 # Colours for numbered cells. COLORS = { 1: 'blue', 2: 'green', 3: 'red', 4: 'dark-blue', 5: 'brown', 6: 'purple', 7: 'dark-green', 8: 'orange' } # [height, w...
n1 = "123" print(n1.isdigit()) # -- ID1 n2 = "345 2" print(n2.isdigit()) # -- ID2 n3 = "345 2b" print(n3.isdigit()) # -- ID3 n4 = "\u0035" print(n4.isdigit()) # -- ID4 n5 = "\u00BC" print(n5) print(n5.isdigit()) # -- ID5 n6 = "\u00B2343" print(n6) print(n6.isdigit()) # -- ID6 n7 = "8.9" print(n7.isdigit(...
# -*- coding: utf-8 -*- # Copyright (c) 2017-18 Richard Hull and contributors # See LICENSE.rst for details. """ Display drivers for LED Matrices & 7-segment displays (MAX7219) and RGB NeoPixels (WS2812 / APA102). """ __version__ = '1.1.1'
expected_output = { "ospf3-database-information": { "ospf3-area-header": {"ospf-area": "0.0.0.0"}, "ospf3-database": [ { "lsa-type": "Router", "lsa-id": "0.0.0.0", "advertising-router": "10.16.2.2", "sequence-number": "0x800...
names = ["Helder", "Fabia", "Linda", "Leonie", "Carina", "Ivan", "Lexy"] # print(names[0]) # print(names[1]) # print(names[2]) # print(names[3]) # print(names[4]) # print(names[5]) # print(names[6]) #print all elements with position on the left #ex: # 0: Helder # 1: Fabia ... counter = 0 while counter < len(names):...
def stopTracking(): i01.headTracking.stopTracking() i01.eyesTracking.stopTracking()
"""Exercício 17: Crie um programa que receba um texto, e que retorne esse texto invertido.""" def inverte_str(texto: str): lista = list(texto) lista.sort(reverse=True) texto = "".join(lista) return texto def inverte(texto): return texto[::-1] entrada = "amora" print(inverte(entrada)) test = ...
def isInt(x): return type(x) in (float, int) and int(x) == x class CommChannel: def __init__(self): self.outbox = [] self.inbox = [] def put(self, update): if len(update) > 0: self.outbox.append(update) def get(self): inbox = self.inbox self.inbox = [] return ...
class Solution : def canPair(self, nums, k) : n = len(nums) if n % 2 != 0 : return False # Initialization of dictionary count = [0] * k # Filling the map for i in range(n) : count[nums[i]%k] += 1 #print(count) ...
# https://sudipghimire.com.np """ Numeric Data Types in Python to run the file, we can go to the terminal and just type python 02_data_types/02_basic_data_types.py """ x: complex = -5j x = 5 # integer x = 5.5 # float x = True # Boolean # simple interest # p -> principal amount 10000 # r -> rate ...
class SingleReply: def __init__(self, inviteeId, status): self.inviteeId = inviteeId self.status = status class PartyReplyInfoBase: def __init__(self, partyId, partyReplies): self.partyId = partyId self.replies = [] for oneReply in partyReplies: self.rep...
class Solution: # @param A : list of integers # @return an integer def findMinXor(self, nums): nums.sort() x = nums[0] minimumXOR = 10**9 for i in range(1, len(nums)): y = nums[i] minimumXOR = min(minimumXOR, x^y) x = y return mi...
""" Reflection by Simon Greenwold. Vary the specular reflection component of a material with the horizontal position of the mouse. """ def setup(): size(640, 360, P3D) noStroke() colorMode(RGB, 1) fill(0.4) def draw(): background(0) translate(width / 2, height / 2) # Set the specular...
""" Name: Srinivas Jakkula CIS 41A Spring 2020 Unit E Take-Home Assignment """ # First Script – Decision Making # Write a script that can determine where different plants can be planted. # # Each plant has a name, a type (Flower, Vegetable, Tree, etc.), and a maximum height. # There are three gardens as follows: # ...
class UrlResources(object): def __init__(self, domain, sandbox, version): super(UrlResources, self).__init__() self.domain = domain self.sandbox = sandbox self.version = version def get_resource_url(self): return self.get_resource_path().format(version=self.version) ...
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: def preorderTraversal(ro...
"""Provides source code for third party libraries that we needed to adapt for use in Makahiki. Currently, Makahiki uses adapted versions of the following third party libraries: * `apps.lib.avatar`_: a library for including pictures. * `apps.lib.brabeion`_: a library for badges. * `apps.lib.django_cas`_: a libr...
class Node(object): def __init__(self, ch): self.cur_char = ch self.isEnd = False self.next = {} def get(self, ch): return self.next.get(ch, None) def put(self, ch, node): self.next[ch] = node class DictTree(object): def __init__(self): self.root = Nod...
""" 1. line notifyMKT 2. mango server 3. mango test """ line_bot_api = 'kRC4gIlLRwvJ80crtV5g5yNPq3QwqhlbSt2KEliih2VaKiwIC8ruldSn6cvmyVrWSoO0URuuEqfMs+IH9xDyMa4u6oiTm2tUJ+HNtG0414HtSEepysKxV6Y/e9h1pO/PcXlaI4BxO6aQZHfLCjsj7AdB04t89/1O/w1cDnyilFU=' handler = 'd61b703734bf899efae9c86a14365240' mango_channel = '55zHqfzX2vg...
pkgname = "xinput" pkgver = "1.6.3" pkgrel = 0 build_style = "gnu_configure" hostmakedepends = ["pkgconf"] makedepends = [ "libxext-devel", "libxi-devel", "libxrandr-devel", "libxinerama-devel" ] pkgdesc = "X input device configuration utility" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): n=target-nums[i] rest_of_nums=nums[i+1:] if n in rest_of_nums: return[i,(rest_of_nums.index(n))+i+1]
class Request: # trip: Trip # rider: User # pickup: Location id: str def __init__(self, rider, trip, pickup): self.rider = rider self.trip = trip self.pickup = pickup def accept(self): self.trip.riders.append((self.rider, self.pickup)) def un_accept(self): ...
""" 198 House Robber """ class Solution: def rob(self, nums): """ :type nums: List[int] :rtype: int """ now, last = 0, 0 for n in nums: last, now = now, max(n+last, now) return now class Solution: def rob(self, nums): ...
class MeshFace(object): """ Represents the values of the four indices of a mesh face quad. If the third and fourth values are the same,this face represents a triangle. MeshFace(a: int,b: int,c: int) MeshFace(a: int,b: int,c: int,d: int) """ def Flip(self): """ Flip(self: MeshFac...
print("""Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercício ullamco laboris nisi ut aliquip ex ea commodo consequat. velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupi...
radioData = [ "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A10_73", "HLC\Adaptive\9558L_L1024A30_230",...
fname = input('Enter a file name: ') fhand = open(fname) countAddr = dict() for line in fhand: if line.startswith('From '): words = line.split() #print(words) countAddr[words[1]] = countAddr.get(words[1],0) + 1 print(countAddr)
TOKEN = '1325729680:AAE3qwRzCXRukKJVvxM3VN_vsesEko6j4EI' HEROKU = 'https://sauce-finder.herokuapp.com/' BASE_TELEGRAM_URL = 'https://api.telegram.org/bot{}'.format(TOKEN) WEBHOOK_ENDPOINT = '{}/webhook'.format(HEROKU) TELEGRAM_INIT_WEBHOOK_URL = '{}/setWebhook?url={}'.format(BASE_TELEGRAM_URL, WEBHOOK_ENDPOINT) TELEGRA...
# Shader Uniform vs_uni = ''' uniform mat4 view_mat; uniform float Z_Bias; uniform float Z_Offset; vec4 pos_view; in vec3 pos; in vec3 nrm; void main() { pos_view = view_mat * vec4(pos+(nrm*Z_Offset), 1.0f); pos_view.z = pos_view.z - Z_Bias / pos_view.z; ...
##Looks like this piece of your code is in development, but this is a great place to think about using a for loop - for piece in range(32)... ## you'd need to have an array or other structure that holds the information that changes between iterations (i.e. piece1, piece1loc). I'd suggest using a dictionary ## as you ca...
# This code solves the Levine Sequence class LevineSequence: def __init__(self): self.start = ["2"] self.split = ["2"] self.result = "" self.len = 0 self.path = r'./Levine_Sequence/results.txt' def void(self): self.start = self.split self.split = [] ...
water_count = int(input("Write how many ml of water the coffee machine has: ")) milk_count = int(input("Write how many ml of milk the coffee machine has: ")) coffee_beans_count = int( input("Write how many grams of coffee beans the coffee machine has: ")) number_of_drinks = int(input("Write how many cups of coffee ...
#Lista de Convidados: Se pudesse convidar alguem, vivo ou morto, para o jantar, quem você convidaria? Crie uma lista que inclua pelo menos três pessoas #que você gostaria de convidar para jantar. Em seguida, utilize sua lista para exibir uma mensagem para cada pessoa, convidando-a para jantar. lista = ['Roberto Monteir...
""" Создать (не программно) текстовый файл со следующим содержимым: One — 1 Two — 2 Three — 3 Four — 4 Необходимо написать программу, открывающую файл на чтение и считывающую построчно данные. При этом английские числительные должны заменяться на русские. Новый блок строк должен записываться в новый текстовый файл. """...
# Copyright 2017 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...
# def make_hashs(word, sub_size): # ret = set() # current_hash = sum(ord(word[i]) * (i + 1) for i in range(sub_size)) # current_suma = sum(ord(word[i]) for i in range(sub_size)) # ret.add(current_hash) # for initial_pos in range(1, len(word) - sub_size + 1): # current_hash -= current_suma ...
N,S,R = map(int,input().split()) broken = list(map(int,input().split())) plus = list(map(int,input().split())) D = [1]*(N+1) for i in broken: D[i]-=1 for i in plus: D[i]+=1 ans = 0 for i in range(1,N+1): j = D[i] if j >= 1: continue if D[i-1] >1: D[i-1]-=1 elif i+1 < N + 1 an...
TELUGU_CORPORA = [ {'name':'telugu_text_wikisource', 'origin': 'https://github.com/cltk/telugu_text_wikisource.git', 'location':'remote', 'type':'text'}, ]
# Address: I2CBUS = 10 # /dev/i2c-1 EMC2301_ADDRESS = 0x2F # 8 bit version # Register CONF = 0x20 # Configuration FAN_STAT = 0x24 # Fan Status FAN_STALL = 0x25 # Fan Stall Status * FAN_SPIN = 0x26 # Fan Spin Status * DRIVE_FALL = 0x27...
def gauss(X): n = len(X) x = [0]*n for i in range(n): if X[i][i] == 0.0: return "Sorry can't excute" for j in range(i+1,n): rat = X[j][i]/X[i][i] for k in range(n+1): X[j][k] = X[j][k] - rat*X[i][k] print(X) x[n-1] = X[n-1][n]/X[n-...
"""Codewars: What is my golf score? 7 kyu URL: https://www.codewars.com/kata/59f7a0a77eb74bf96b00006a/train/python I have the par value for each hole on a golf course and my stroke score on each hole. I have them stored as strings, because I wrote them down on a sheet of paper. Right now, I'm using those strings to...
def factorial_division(num1, num2): sum = 1 sum2 = 1 for num in range(num1, 0, -1): sum = sum * num for num in range(num2, 0, -1): sum2 = sum2 * num result = sum / sum2 return result num1 = int(input()) num2 = int(input()) print(f"{factorial_division(num1, num2):.2f}")
version = "1.0" def getVersion(): return version
dyn.baseball.pos[0] = 16.0 dyn.baseball.pos[1] = 0.1 dyn.baseball.pos[2] = 2.0 dyn.baseball.vel[0] = -30.0 dyn.baseball.vel[1] = -0.1 dyn.baseball.vel[2] = 1.0 dyn.baseball.theta = trick.attach_units("degree",-90.0) dyn.baseball.phi = trick.attach_units("degree",1.0) dyn.baseball.omega0 = trick.attach_units("revoluti...
# zip(*(('white', 'small'), ('red', 'big'))) colors, sizes = zip(*(('white', 'small'), ('red', 'big'))) print(colors) print(sizes)
print(""" \033[1;37;44m 031) \033[m Crie um programa em PYTHON que:pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens até 200Km e R$0,45 para viagens mais longas. """) distancia = float(input('Qual a distancia da viagem: ')) limite = 200 curta = 0.5 longa = 0.45 ...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ This Document is Created by At 2017/11/21 """ class Rectangle: """ 矩阵面积 """ def __init__(self, width, height): self.width = width self.height = height @property def area(self): return self.width * self.height if __n...
class TestModel(object): @staticmethod def train(x): # y = np.sin(3 * x[0]) * 4 * (x[0] - 1) * (x[0] + 2) res = 0 for i in range(100000000): res += i y = sum(x * x) return y
# -*- coding: utf-8 -*- class FARule: def __init__(self, state, character, next_state): self.state = state self.character = character self.next_state = next_state def __str__(self): return "<FARule {1} --> {2} --> {3}>".format(str(self.state), self,character, ...
m = 0 def findMedian(a, b ,c): if a > b: if a < c: return a elif b > c: return b else: return c else: if a > c: return a elif b < c: return b else: return c def partition(A, l, r): p =...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2014, Trond Hindenes <trond@hindenes.com> # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # this is a windows documentation stub. actual code lives in the .ps1 # file of the ...
# x_2_5 # # 「a」「b」「c」「d」がそれぞれどんな値となるかを予想してください a = 10_000 + 4 b = 1.0 + 4 c = 3 / 3 d = 10e3 # print(a) # print(b) # print(c) # print(d)
# Approach : # Divide the linked list to two halved # First half is head and the remaining as rest # The head points to the rest in a normal linked list # In the reverse linked list , the next of current points to the prev node and the head node should point to NULL # Keep continuing this process till the last node ...
class arithmetic: def __init__(self): pass def add(self, x: int, y: int) -> int: return x + y def sub(self, x: int, y: int) -> int: return x - y def mul(self, x: int, y: int) -> int: return x * y def div(self, x: int, y: int) -> float: ...
Bag=[] #Luggage Bag Bag.append('Waterbottle') Bag.append('Milk') Bag.append('Clothes') Bag.append('Books') #Removing milk from the bag Bag.remove('Milk') print(Bag)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None ''' test case: 1. empty list 2. there is only one node in the list 3. more than one node ''' class Solution(object): def reverseList(self, head): """ :type ...
#!/usr/bin/env python def start(agent) -> None: try: next_step = next(agent) try: next_step(agent) except TypeError: msg = "Returned generator not a function, did you use yield from?" raise TypeError(msg) except StopIteration: pass
''' operadores lógicos - usado para comparações and, or, not in e not in ''' # 1 a = 2 b = 2 c = 3 # verdadeiro e falso = falso # verdadeira e verdadeira = verdadeiro # comparação1 and comparação2 # verdadeiro ou verdadeiro = verdadeiro # verdadeiro ou falso = verdadeiro # comparação1 or coparação2 resultado = a =...
# Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. time_in_seconds = int(input("Enter time in seconds: ")) hours = time_in_seconds // 3600 minutes = (time_in_seconds % 3600) // 60 sec = (time_in_seconds % 3600) % 60 print...
#inserta strings en una lista texto = input("Ingrese un string: ") no_olvidar = texto.split(",") #la coma seria el separador no_olvidar.sort() #Para ordenar la lista de menor a mayor (en orden alfabetico) print(no_olvidar)
#!/usr/bin/env python3 #encoding=utf-8 #----------------------------------------------- # Usage: python3 3-desc-computed.py # Description: computed attribute with attribute descriptor #----------------------------------------------- # Implementation 1 class DescSquare: def __init__(self, start): self.va...
def do_greet(self, args): """Greet name with welcome message: greet NAME""" self.output = 'Welcome ' + args module_directory = {'greet': do_greet} startup_script_directory = {}
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def password(string: str) -> bool: """ Your job is to create a simple password validation function, as seen on many websites. You are permitted to use any methods to validate the password. The ...
class Invoice: def __init__(self, bill_to, date): self.bill_to = bill_to self.date = date self.invoice_items = [] self.invoice_total = 0 def add_invoice_item(self, invoice_item): ''' Write the code to append an invoice_item to the self.invoice_items list ...
class paths: """ Feel free to remove this if you don't need it/add your own custom settings and use them """ class hypothesis: export_path = '/tmp/my_demo/backups/hypothesis'
class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ if not head: return None n = 0 cursor = head while cursor: cursor = cursor.next n += 1 ...
class Solution: def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ length = len(nums1) + len(nums2) res = sorted(nums1 + nums2) if length % 2: return res[int((length-1)/2)] ...
# -*- coding: utf-8 -*- DESC = "emr-2019-01-03" INFO = { "ScaleOutInstance": { "params": [ { "name": "TimeUnit", "desc": "Time unit of scale-out. Valid values:\n<li>s: seconds. When `PayMode` is 0, `TimeUnit` can only be `s`.</li>\n<li>m: month. When `PayMode` is 1, `TimeUnit` can only be `m...
print('\033[30m==='*11) print('SOMA DE VALORES ALEATÓRIOS') print('==='*11) r = int(input('Digite um número inteiro (999 para parar): ')) cont = 0 s = r while r != 999: r = int(input('Digite outro número (999 para parar): ')) cont += 1 if r != 999: s += r print('==='*10) if cont == 0 and s == 999: ...
neutral_site_fields = ['Azteca Stadium', 'Estadio Azteca', 'Tottenham Hotspur', 'Tottenham Hotspur Stadium', 'Twickenham', 'Twickenham Stadium', 'Wembley', 'Wembley Stadium'] standardized_field_names = { 'Arrowhead Stadium': 'Arrowhead Stadium', 'AT&T': 'AT&T Stadium', 'AT&T Stadium': 'AT&T Stadium', 'Ba...
""" _ _ _ _ (_) | | (_) | ___ _ _ __ ___ _ __ | | ___ _ __ ___ __ _ _| | / __| | '_ ` _ \| '_ \| |/ _ \ | '_ ` _ \ / _` | | | \__ \ | | | | | | |_) | | __/ | | | | | | (_| | | | |___/_|_| |_| |_| .__/|_|\___| |_| |_| |_|\__,_|_|_...
privKey = "" with open ('privKey.txt', 'rt') as myfile: # Open file lorem.txt for reading text for myline in myfile: # For each line, read it to a string print(myline) if myline == "Your ETH privkey derived from seed:": print(myline) #Doesnt do anything, just holds that line ...
class MinisyncError(Exception): pass class PermissionError(MinisyncError): pass
# https://leetcode.com/problems/repeated-string-match/ class Solution(object): def repeatedStringMatch(self, A, B): """ :type A: str :type B: str :rtype: int """ repeat = 0 sr = A while len(A) <= 10000: if B in A: return repeat + 1 else: A = A + sr repeat += 1 return -1
print('Digite a velocidade do seu carro:') v = int(input()) if v > 80: m = (v-80)*7 print('Você será multado por trafegar acima da velocidade em R${:.2f}.'.format(m)) else: print('Velocidade abaixo do limite permetido, BOA VIAGEM!') print(' ') print('Fim')
satis = { 'Telefon':{ 'Tuşlu': {'C1':100,'C2':200,'C3':450,'A10':350,'A20':600}, 'Akılı': {'iPhone 7':3000,'Samsung Galaxy S8':5500,'Huawei Mate X':32000,'iPhone 11':6500,'Xiaomi Mi 10':4900}, 'telsiz': ...
def result(x1, y1, x2, y2): num_list = [x1, y1, x2, y2] for _ in range(2): num_list.remove(max(num_list)) f = num_list[0] g = num_list[1] print(f"({f}, {g})") print(f"({', '.join(num_list)})") a = int(input()) b = int(input()) c = int(input()) d = int(input()) result(a, b, c, d)
class Number: def __init__(self, num): self.num = num def __add__(self, num2): print("Lets add") return self.num + num2.num def __mul__(self, num2): print("Lets multiply") return self.num * num2.num n1 = Number(4) n2 = Number(6) sum = n1 + n2 mul = n...
# Module : kilo_to_mile_converter # Description : This program program asks # the user to enter a distance in kilometers, # and then converts that distance to miles with this formula # Miles = Kilometers * 0.6214 # Programmer : William Kpabitey Kwabla # Date : 05/04/16 # Def...
# -*- coding: utf-8 -*- class ThreadSafeCreateMixin(object): """ ThreadSafeCreateMixin can be used as an inheritance of thread safe backend implementations """ @classmethod def create(cls): """ Return always a new instance of the backend class """ return cls() ...
# 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 invertTree(self, root: TreeNode) -> TreeNode: self.rec(root) return root def rec(sel...
NAMES = ['arnold SchwArzenegger', 'alEc Baldwin', 'Bob belderbos', 'julian sequeira', 'Sandra Bullock', 'keAnu reeves', 'julbob pybites', 'Bob Belderbos', 'julian sequeira', 'Al Pacino', 'brad pitt', 'matt damon', 'brad pitt'] def surname(inputStr): return inputStr.split()[1] def f...
# n ==> Size of circle # m ==> Number of items # k ==> Initial position def lastPosition(n, m, k): if (m<=n-k+1): return m+k-1 m=m-(n-k+1) if(m%n==0): return n else: return m%n # Driver code n = 5 m = 8 k = 2 ans=lastPosition(n, m, k) print(ans)
def get_yes_or_no_input(prompt): """ Prompts the user for a y/n answer returns True if yes, and False if no :param prompt: (String) prompt for input. :return: (Boolean) True for Yes False for No """ while True: value = input(prompt + " [y/n]: ") if v...
""" Main Orange Canvas Application and supporting classes. """
# Given a non-negative integer x, compute and return the square root of x. # Since the return type is an integer, the decimal digits are truncated, # and only the integer part of the result is returned. # Note: You are not allowed to use any built-in exponent function or operator, # such as pow(x, 0.5) or x ** 0.5. ...
def get_color(code): # write your answer between #start and #end #start return '' #end print('Test 1') print('Expected:Red') result = get_color ('R') print('Actual :' + result) print() print('Test 2') print('Expected:Green') result = get_color ('g') print('Actual :' + result) print() print('Test...
def game_to_genre(game_name): genres_dict = {} with open('genres_dict.txt', 'r') as file: file.seek(0) for line in file: stripped_line = line.strip() key, *value = stripped_line.split(', ') genres_dict[key] = value game_genre = None lowered_ga...
""" Given head, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is co...
# -*-coding:utf-8 -*- """ Created on 2013-4-25 @author: Danny<manyunkai@hotmail.com> DannyWork Project """ def required(wrapping_functions,patterns_rslt): """ Used to require 1..n decorators in any view returned by a url tree Usage: urlpatterns = required(func,patterns(...)) urlpatterns = re...
""" Faça um programa que receba um número inteiro maior do que 1, e verifique se o número fornecido é primo ou não. """ while True: n1 = int(input('Digite um número inteiro maior que 1: ')) n2 = 2 n3 = 0 if n1 <= 1: print('Tem que ser maior que 1!') else: if n1 % 2 == 0 or n1 % 3 =...