text
stringlengths
5
121k
def two_sum(arr, key): left = 0 right = len(arr) - 1 while left < right: if arr[left] + arr[right] == key: return [left+1, right+1] elif arr[left] + arr[right] > key: right -= 1 elif arr[left] + arr[right] < key: ...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def Intersect(self, headA, headB): c1 = headA c2 = headB len1, len2 = 0 while c1: len1 = len1 + 1 c1 = c1.next while c2: len2 = l...
def reverse_alpha(string): newList = list(string) rightptr = len(newList)-1 leftptr = 0 while leftptr < rightptr: if not newList[leftptr].isalpha(): leftptr +=1 elif not newList[rightptr].isalpha(): rightptr -=1 else: newList[lef...
def anagram(str1, str2): if(len(str1) != len(str2)): return False count = 0 for i in str1: count += ord(i) for i in str2: count -= ord(i) return (count==0) input1, input2, *rest = [word for word in input('Enter the strings to compare: ').split()] print(inp...
import nltk from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) file = open("vocab-1", "rb") output = open("vocab", "w") for i in file: word = i.strip() if word not in stop_words: output.write(word+"\n") output.close() file.close()
def describe(): desc = """ Problem : Given a non-empty binary tree root, return the maximum path sum. Note that for this problem, a path goes from one node to another by traversing edges. The path must have at least one edge and it does not have to pass by the root. NOTE : When we say that the ...
class TreeNode(): def __init__(self, val): self.value = val self.left = None self.right = None def describe(): desc = """ Problem : Given a binary tree and a number S, find all paths from root-to-leaf such that the sum of all the node values of each path equals S -------------- """...
def waysToClimb01(n, possibleSteps): if n == 0: return 1 noWays = 0 for steps in possibleSteps: if n-steps > 0: noWays += waysToClimb01(n-steps, possibleSteps) return noWays def waysToClimb02(n, possibleSteps): arr = [0] * (n+1) a...
def describe(): desc = """ Problem : Given a sorted array of numbers, find if a given number 'key' is present in the array. Though we know that the array is sorted, we don't know if it's sorted in ascending or descending order. You should assume that the array can have duplicates. Write a function to return the ind...
def longestSubstringWithoutRepeating01(str): if len(str) <= 1: return len(str) def hasNoRepeatingChars(str): charCount = [0] * 128 for char in str: charCount[ord(char)] = charCount[ord(char)] + 1 if charCount[ord(char)] > 1: return False...
from __future__ import print_function class Node(): def __init__(self, value, node=None): self.value = value self.next = node def print_list(self): node = self while node is not None: print(node.value, end='->') node = node.next print('null') ...
def describe(): desc = """ Problem : Given a set of elements find all it's distinct subsets. Example: Input : [1,3] Output : [], [1], [3], [1,3] ---------------- """ print(desc) def find_subsets(nums): subsets = [] if len(nums) == 0: return subsets subsets.append([]) ...
def describe(): desc = """ Problem : Given an array, find the average of all subarrays of K contiguous elements in it. Ex : Given Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5 Output: [2.2, 2.8, 2.4, 3.6, 2.8] """ print(desc) def brute_force_find_averages_of_subarrays(K, arr): result = [] pri...
def removeDuplicates01(arr): res = [] for elm in arr: if elm not in res: res.append(elm) return res def removeDuplicates02(arr): arr.sort() res = [] for i in range(len(arr)): if len(res) == 0 or res[len(res)-1] != arr[i]: res.append(arr[i]) r...
def describe(): desc = """ Problem : Find the number of ways possible to place n queens on a n x n chess board such that no 2 queens can attack each other. The queens attack each other when they are placed on the same row, same column or placed diagonal to each other. Example : Input : n = 4 Outp...
def bubbleSort(arr): if len(arr) <= 1: return arr i = 0 while i < len(arr): j = 1 while j < len(arr): if arr[j-1] > arr[j]: arr[j-1], arr[j] = arr[j], arr[j-1] j += 1 i += 1 return arr def mergeSort(arr): if...
def productExceptSelf(arr): if len(arr) == 0: return [] if len(arr) == 1: return [1] leftCumulativeProduct = [1] * len(arr) leftCumulativeProduct[0] = arr[0] for i in range(1, len(arr)): leftCumulativeProduct[i] = leftCumulativeProduct[i-1] * arr[i] rightCumulat...
import heapq def describe(): desc = """ Problem : Given an unsorted array find the K largest numbers in it. Example : Input : [3, 1, 5, 12, 2, 11], K = 3 Output : [5, 12, 11] --------------- """ print(desc) def unoptimized_find_k_largest_numbers(nums, k): res = [] maxheap = [] for ...
from tkinter import * import sqlite3 from Vagtplan2.Editor import * class Submit: def delete(self): conn = sqlite3.connect('vagt_plan_app.db') c = conn.cursor() c.execute("DELETE from users WHERE oid= " + self.delete_box.get()) ...
import os a = 10 print(type(a)) b = 20 print(type(b)) if a == 10 and b == 20: print(a, end=" ")
import socket import select HEADER= 1 IP = "127.0.0.1" PORT = 8888 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((IP, PORT)) server_socket.listen() sockets_list = [server_socket] clients = {} print(f'Me...
""" Insper - Engenharia 1B Design de Software EP3: Jogo da Velha Vitória Rocha e Isabella Oliveira """ import tkinter as tk import tkinter.messagebox as tkm from Jogo import Jogo class Tabuleiro: def __init__(self): self.meu_jogo = Jogo() self.window = tk.Tk() self.window.titl...
teams = [ { 'astros': { '2B': 'Altuve', 'SS': 'Correa', '3B': 'Bregman', } }, { 'angels': { 'OF': 'Trout', 'DH': 'Pujols', } } ] angels = teams[1].get('angels', 'Team not found') print(list(angels.values())[1])
var_range = int(input("Enter a Number to set the upper range: ")) def fizzbuzz(upper): for num in range(1, upper): if num != upper: if num % 3 == 0 and num % 5 == 0: print('FizzBuzz') elif num % 3 == 0: print('Fizz') elif num % 5 == 0: print('Buzz') else: ...
def full_name(first, last): print(f'{first} {last}') full_name(first = 'Kristine', last = 'Hudgens') full_name(last = 'Hudgens', first = 'Kristine')
full_name = lambda first, last: f'{first} {last}' def greeting(name): print(f'Hi there {name}') greeting(full_name('kristine', 'hudgens'))
tags = ['python', 'development', 'tutorials', 'code'] number_of_tags = len(tags) last_item = tags[-1] index_of_last_item = tags.index(last_item) print(number_of_tags) print(last_item) print(index_of_last_item) print(tags) tags.sort() print(tags) tags.sort(reverse=True) print(tags) totals = [234, 1, 5...
from random import choice questions = ["Why was Prince Hans mean?", "Why Anna punch him?", "Why did Elsa run away?"] question = choice(questions) answer = input(question).strip().lower while answer !="just because": answer = input("but.. why? ").strip().lower() print("Oh.. Okay")
num1 = 10 num2 = 5 if num1 > num2: print("num1 is bigger than num2") elif num1 == num2: print("num1 is equal to num2") elif num1 < num2: print("num2 is bigger than num1")
import urllib.request, urllib.parse, urllib.error from urllib.request import urlopen g = [] from bs4 import BeautifulSoup import ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input ("enter: ") x = urlopen(url,context=ctx).read() s = BeautifulSoup(x,'...
''' 3. Recursive Lines Write a recursive function that accepts an integer argument, n. The function should display n lines of asterisks on the screen, with the first line showing 1 asterisk, the second line showing 2 asterisks, up to the nth line which shows n asterisks. ''' def main(): num_lines ...
prices = [72.51, 9.27, 153.74, 30.23, 53.00] names = ["CAT", 'GE', 'MSFT', 'AA', 'IBM'] for name, price in zip(names, prices): print(name, '=', price)
def isPrime(x): for n in range(2, x): if x % n == 0: return False return True filterObject = filter(isPrime, range(10)) print('Prime numbers between 1-10: ', list(filterObject)) filterObject2 = filter(lambda x: x % 2 == 0, range(10)) print(list(filterObject2)) randomlist = [1, 'a',...
import pickle import csv from random import randint def main(): with open('Trivia_v2.csv', 'r') as csv_file: csv_read = csv.reader(csv_file) csv_list = [] for line in csv_read: csv_list.append(line) questions = [] answers = [] correct = [] for line in csv_list:...
def forever_recursion(times): annoying_message(times) def annoying_message(times): if times > 0: print('Nudge Nudge, Wink Wink, Say No More Say No More') annoying_message(times -1) forever_recursion(995)
''' Demonstrate the CashRegister class in a program that allows the user to select several items for purchase. When the user is ready to check out, the program should display a list of all the items he or she has selected for purchase, as well as the total price. ''' import CashRegisterClass import RetailItemClass as...
''' 8. Trivia Game In this programming exercise you will create a simple trivia game for two players. The program will work like this: • Starting with player 1, each player gets a turn at answering 5 trivia questions. (There should be a total of 10 questions.) When a question is displayed, 4 po...
""" Wireless Solutions, Inc. is a business that sells cell phones and wireless service. You are a programmer in the company’s IT department, and your team is designing a program to manage all of the cell phones that are in inventory. You have been asked to design a class that represents a cell phone. The data that sh...
''' 1. Recursive Printing Design a recursive function that accepts an integer argument, n, and prints the numbers 1 up through n. ''' def main(): stop_num = int(input('At what number do you want this program to stop at: ')) recursive_print(1, stop_num) def recursive_print(p_start, p_stop): ...
''' Binary Tree is a tree data structure in which each node has at most two children which are left child and right child - top node is root Complete binary tree - every level, except possibly the last, is completely filled and all nodes in the last level are as far left as possible Full binary tree - A full bi...
''' 6. Sum of Numbers Design a function that accepts an integer argument and returns the sum of all the integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1, 2, 3, 4, . . . 50. Use recursion to calculate the sum. ''' de...
import sqlite3 from sqlite3 import Error sql_create_sensors_table = """ CREATE TABLE IF NOT EXISTS sensor ( id integer PRIMARY KEY, name text NOT NULL ); """ sql_create_data_table = """ CREATE TABLE IF NOT EXISTS d...
class Cake(): def __init__(self,flavor): self.flavor = flavor def eat(self): print("Yummy!!! Eating a " + self.flavor + " cake :)") cake = Cake("chocolate") cake.eat()
number = int(input("Enter a number : ")) for r in range (number): print("#", end="",sep="") for c in range (r): print(" ", end="",sep="") print("#",sep="")
number = int(input("enter a number : ")) if number >= 0 and number <= 36: print("number is in range") else: print("out of range") if number == 0: print("green") if number >= 1 and number < 10: if number % 2 == 0 : print("odd-numbered pockets are red") else: print("even...
count = 0 file = str(input("enter file name :")) print("file name is :", file) content = open(file, 'r') for i in range(0, 10): i += count + 1 print(f"{i} :",i)
size = 0 Starting_number_of_organisms = int(input("Starting_number_of_organisms : ")) daily_increase = int(input("daily increase : ")) Average_daily_increase = daily_increase / 100 print("Average daily increase :",Average_daily_increase) number_of_days_to_multiply = int(input("number_of_days_to_mult...
days_number = int(input("Enter a number : ")) if days_number == 1 : print("monday") elif days_number == 2 : print("tuesday") elif days_number == 3 : print("wednesday") elif days_number == 4 : print("thursday") elif days_number == 5 : print("friday") elif days_number == 6 : print("saturday")...
from secrets import choice from tkinter.messagebox import YES from sqlalchemy import true from sympy import And def customer(): user = str(input("What type of food you requried : ")) if user == 'burgers': print("Food item is available") else: print("You've entered unavailable it...
names = ['Jane','John','Alena'] names_1 = ['John','Jane','Adeev'] text = 'Welcome to the party' names.extend(names_1) for name in range(1): names.append(input("enter name :")) for name in names: print(name,text)
total_no_of_cookies = 48 cups_of_sugar = 1.5 cups_of_butter = 1 cups_of_flour = 2.75 no_of_cookies_req = round(int(input("cookies required :"))) print("no of cookies required in roundup : {0:2f} ".format(no_of_cookies_req)) req_sugar = (no_of_cookies_req / total_no_of_cookies) * cups_of_sugar print("no of cups of suga...
shares_purchased = 2000 print("Number of shares purchased :",shares_purchased) amount_paid_per_share = 40.00 print("Amount paid for each share :",amount_paid_per_share) stockbroker_commission = 3 / 100 print("Commission paid to stockbroker :",stockbroker_commission) shares_sold = 2000 print(...
first_name = str(input("Enter First Name : ")) middle_name = str(input("Enter Middle Name : ")) last_name = str(input("Enter Last Name : ")) print("Initials of persons names : ", '\n',first_name[0],'\n', middle_name[0],'\n', last_name[0])
rising_oceans_levels_per_year = 1.6 years = 0 for i in range (1,26): years = rising_oceans_levels_per_year * i print(f"rising levels per {i} year : {years}")
Celsius = float(input("enter the celsius : ")) far = 9 * ( Celsius / 5 ) + 32 print(Celsius) print(far)
def value_1(): number_1 = int(input("enter value 1 : ")) return number_1 def value_2(): number_2 = int(input("enter value 2 : ")) return number_2 def max(value_1,value_2): if value_1 > value_2 : return value_1 else: return value_2 def main(): number_1 = value_1() ...
def fat(): fat_grams = float(input("Enter fat grams :")) calories_from_fat = fat_grams * 9 return calories_from_fat def carbohydrates(): carb_grams = float(input("Enter Carbohydrates :")) calories_from_carbs = carb_grams * 4 return calories_from_carbs def calculations(): C_fat = ...
from math import sqrt as s for i in range(int(input())): l,r=[int(x) for x in input().split(" ")] def sumOfPrimes(l,r): primes=['',''] for i in range(2,r+1): primes.append(True) for j in range(2,int(s(r))+1): if primes[j]==True: for k in r...
DAY_NUM = 2 def input(): f = open("input/day" + str(DAY_NUM) + ".txt") inp = [l.rstrip('\n') for l in f] f.close() return inp def checkPasswords(inp): res1, res2 = 0, 0 for line in inp: x = line.split(" ") fir = int(x[0].split("-")[0]) sec = int(x[0].split("-")[1]) ...
""" Concrete sudoku solver classes which use various algorithms to solve sudoku puzzles. """ from .errors import Catastrophic, NoNextMoveError from .solver import (BasicSolver, Solver, Elimination, HiddenSingles, NakedPairs, NakedTriples, NakedQuads, HiddenPairs, HiddenTriples...
mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "lion" , "zebra","duck" ,"bull", "sheep", "cat", "cow", "fox", "lion") frequency = {} for item in mytuple: if item.lower() not in frequency: frequency[item.lower()] = 1 else: frequency[item.lower()] = frequency[item.lower()] + 1 for key,va...
from datetime import datetime now = datetime.now() timestamp = datetime.timestamp(now) print(timestamp)
from datetime import date t1 = date(year = 2018, month = 7, day = 12) t2 = date(year = 2017, month = 12, day = 23) t3 = t1 - t2 print("t3 =", t3)
import re expression = r'[0-9]+' numberslist = [] number1 = number2 = number3 = "" while re.search(expression, number1) is None: number1 = input('Please input first number: \n') while re.search(expression, number2) is None: number2 = input('Please input second number: \n') while re.search(expression,...
word = input("Please input a word : \n") newword = "" i = len(word) while i > 0: newword = newword + word[i-1] i = i - 1 print(newword)
txt = input('Please insert a string : \n') dictionary = {} for letter in txt: if letter not in dictionary.keys(): dictionary[letter] = 1 else: dictionary[letter] = dictionary[letter] + 1 print(dictionary)
from datetime import datetime, date, time today = datetime.today() print("Today is " , today) yesterday = today.timestamp() - 60*60*24 yesterday = date.fromtimestamp(yesterday) print( "Yesterday is " , yesterday) tomorrow = today.timestamp() + 60*60*24 tomorrow = date.fromtimestamp(tomorrow) print...
set1 = {"apple", "banana", "cherry" , "strawberry"} set2 = {"cherry", "ananas", "strawberry", "cocoa"} set3 = set1.intersection(set2) print(set3)
mytuple = ("dog", "cat", "cow", "fox", "hen", "cock", "duck" ,"bull", "sheep") myliste = [] txt = input("Please input a text : \n") for element in mytuple: if element != txt: myliste.append(element) myliste=tuple(myliste) print(myliste)
liste = [1,2,3,4,5] def sumliste(liste): sum = 0 for item in liste: sum = sum + item print("The sum of the numbers in the list is {}".format(sum)) sumliste(liste)
def ret_3(): return 1, 2, 3 def main(): a, b, c = ret_3() print("a = {0}, b = {1}, c = {2}".format(a, b, c)) print("a = %d, b = %d, c = %d" % (a, b, c)) if __name__ == "__main__": main()
def is_palindrome(n): return str(n) == str(n)[::-1] my_list = [] for n_1 in range(100, 1000): for n_2 in range(100, 1000): result = n_1 * n_2 if is_palindrome(result): my_list.append(result) print(max(my_list))
from sklearn import datasets from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from app import two_model_feature_importance_app dict_ = datasets.load_iris() X_train, X_test, y_train, y_test = train_test_split(d...
number_test_cases = int(input("Enter the number of test cases: ")) for idx in range(number_test_cases): test_case = input("Test case #{} ".format(idx+1)) suppression = 0 for i, c in enumerate(test_case): if i < 1: continue if c == test_case[i-1]: suppression += 1 ...
""" There are three types of edits that can be performed on strings: - insert a charachter - remove a charachter - replace a charachter Given two strings, wrtie a function to check if they are one edit (or zero) edits away Ex: pale, ple -> True // {'a':1} pales, pale -> True // {'s':1} pale, bale -> True // {'...
import os import urllib.parse as urlparse import urllib.request def image_downloader(file): """ This Function Downloads all images from a Text File including urls. Args: file: the path of the text file. On Execution: Downloads the images from URLs provided on the text file an...
import sys def foo(a, b): return a // b def bar(a, b): return foo(a, b) if __name__ == "__main__": if len(sys.argv) != 3: print("USAGE: runtime-error.py NUM1 NUM2") sys.exit(1) a = int(sys.argv[1]) b = int(sys.argv[2]) x = bar(a, b) print("a / b = {}".format(x))
def multiply(num, power_of_ten): num = str(num) if num.find('.') == -1: num = num + '.' point_index = num.find('.') while len(num[point_index + 1:len(num)]) < power_of_ten: num = num + '0' point_index = num.find('.') num = num.replace('.', '') num = num[0:point_index + power_...
import pyperclip, re phoneRegex = re.compile(r'''((\s|\+|\.)?(\d{2}|\(\d{2}\))?(\s|-|\.)?(\d{10}))''', re.VERBOSE) emailRegex = re.compile(r'''([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))''', re.VERBOSE) matches = [] file = open('sample_text_file.txt', 'r') for each in file: for groups in pho...
from tkinter import * def MulTable(): print("\n") print("Table") for x in range(1,11): m = int(EnterTable.get()) print((x), 'once the', (m), '=', (x*m)) win = Tk() win.geometry('200x200') win.title('Multiplication Table') EnterTable = StringVar() label = Label(win, t...
import unittest from Deck import * from Card import * class TestDeck(unittest.TestCase): def test_init(self): assumeResult = \ "Y1 Y1 Y1 Y2 Y2 Y3 Y3 Y4 Y4 Y5 " + \ "G1 G1 G1 G2 G2 G3 G3 G4 G4 G5 " + \ "W1 W1 W1 W2 W2 W3 W3 W4 W4 W5 " + \ "R1 R1 R1 R...
a = 0 b = 0 r = 0 print('Donner 2 entiers positif A et B') print('A : ') a = int(input()) print('B : ') b = int(input()) r = a while r > 0: r = r - b if r == 0: print('A est Divisible par B') else: print('A n\'est pas divisible par B')
'''def somar(a=0, b=0, c=0): s = a + b + c print(f'A soma vale {s}') somar(3, 2, 5) somar(2, 2) somar(7) ''' def somar(a=0, b=0, c=0): s = a + b + c return s r1 = somar(3, 4, 1) r2 = somar(1, 9) r3 = somar(2, 4) print(f'{r1}, {r2}, {r3}') print(somar(3, 2, 8)) def fatorial(num=1):...
cedulas = 50 saque = int(input('Digite o valor a ser sacado: ')) totced = 0 total = saque while True: if total >= cedulas: total -= cedulas totced += 1 else: if totced > 0: print(f'total de {totced} cédulas de R$ {cedulas}') if cedulas == 50: c...
nome = 'Amanda' idade = 28 salario = 987.35 print(f'A {nome:10} tem {idade} anos e ganha R$ {salario}') print(f'A {nome:^10} tem {idade} anos e ganha R$ {salario}') print(f'A {nome:-^10} tem {idade} anos e ganha R$ {salario}') print(f'A {nome:->10} tem {idade} anos e ganha R$ {salario}') print(f'A {nome:-<10} ...
l1 = [1, 2, 3, 4] l1_iter = iter(l1) print(next(l1_iter)) print(next(l1_iter)) print(next(l1_iter)) print(next(l1_iter)) l1_iter = iter(l1) for _ in l1_iter: print(_, end=" ") print() class MyNumbers: def __iter__(self): self.a = 10 return self def __next__(self): if self.a<=30: x ...
import cv2 import numpy as np img1=cv2.imread('/home/ramraj/Downloads/messi.jpg',0) img=cv2.imread('/home/ramraj/Downloads/mainlogo.png',0) rows,columns=img.shape roi=img1[0:rows,0:columns] ret,img_thres=cv2.threshold(img,220,255,cv2.THRESH_BINARY_INV) img_thres_inv=cv2.bitwise_not(img_thres) img_3=cv2.bitwise_and(roi...
panjang=eval(input("Masukkan panjang persegi panjang = ")) lebar=eval(input("Masukkan lebar persegi panjang = ")) luas=panjang * lebar print("\nLuas Persegi Panjang adalah = %d"%(luas)) keliling=2*(panjang + lebar) print("nkeliling Persegi Panjang adalah = %d"%(keliling))
class Location: def __init__(self, y, x): self.y = y self.x = x def get_x(self): return self.x def get_y(self): return self.y def set_coords(self, y, x): self.y = y self.x = x def set_x(self, x): self.x =...
from manual_queue.QueueElem import MyQueueElement class MyQueue: def __init__(self): self.head = None self.tail = None self.is_empty = True def enqueue(self, elem): tmp = MyQueueElement(elem) if self.head is None: self.head = tmp if self.tail is not...
class BankAccount: def __init__(self, bank_account_number, balance, int_rate, month_fee, customer): self.bank_account_number = bank_account_number self.balance = balance self.int_rate = int_rate self.month_fee = month_fee self.customer = customer def finish_month(sel...
def block(code): opened = [] blocks = {} for i in range(len(code)): if code[i] == '[': opened.append(i) elif code[i] == ']': blocks[i] = opened[-1] blocks[opened.pop()] = i return blocks def parse(code): return ''.join(c for c in code ...
def main(): arr = [7, 7, 7] print("arr[2] = {}".format(arr[2])) for i in range(3): arr[i] = i; print("arr[2] = {}".format(arr[2])) arr.append(5) print("arr[3] = {}".format(arr[3])) main()
class Solution: def merge1(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ for i in range(m,len(nums1)): nums1[i] = nums2[i-m] nums1.sort() ...
class Solution: def getRow(self, rowIndex, pas = [1]): '''hint: only O(N) extra space, meaning storing from 0th to nth lists is not allowed.''' if len(pas)-1 == rowIndex: return pas next_pas = [1] for i in range(0, len(pas)): if i == len(pas)-1: ...
import Tkinter as tk class Observable: """class Observable defines the infrastructure of model/view register and notification""" def __init__(self, InitialValue = 0): self.data = InitialValue self.observer_list = [] def RegisterObserver(self, observer): self.observer_list.append(observer) def ObserverNot...
class Solution: def merge(self, A, m, B, n): '''Note: A is actually [1, 3, 6, placeholder, placeholder], m = 3 B is [2, 5], n = 2 So avoid using len(A) and len(B), use m and n with incre/decre. And avoid using append() and extend()''' if n == 0: return pa = 0 pb = 0 ...
''' 1. Write a Python program to count the number of arguments in a given function. Sample Output: 0 1 2 3 4 1 2. Write a Python program to compute cumulative sum of numbers of a given list. Note: Cumulative sum = sum of itself + all previous numbers in the said list. Sample Output: [10, 30, 60, 100, 150, 210, 217] [1...
''' 1. Write a Python program to check whether two given circles (given center (x,y) and radius) are intersecting. Return true for intersecting otherwise false. Sample Output: True False 2. Write a Python program to compute the digit distance between two integers. The digit distance between two numbers is the absolute...
def slopes(tree_map, right, down): index, row, tree_counter = 0, 0, 0 text_length = len(tree_map[0]) while row != len(tree_map) - 1: index += right row += down if index >= text_length: index = index - text_length position = tree_map[row][index] if positio...