text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Nov 8 10:27:14 2018 @author: MariusD """ #%% def bubble(lst): for j in range(0, len(lst) - 1): for i in range(0, len(lst) - j - 1): if lst[i] > lst[i + 1]: temp = lst[i] lst[i] = lst[i + 1] ...
import unicode import board from game_state import GameState # Initialize GameState to key track if the game has ended. game_state = GameState() print(" Welcome to WeThinkCode (Group 26) MineSweeper.\n\n" "-----------------------------------------------------------\n" "| Rules:" + (" " * 50) + "|\n" ...
def jogar(): import random print("*********************************") print("Bem-vindo no jogo de Adivinhação!") print("*********************************") numero_secreto = random.randrange(1,101) total_de_tentativas = 0 pontos = 1000 print("""Qual nível de dificuldade? (1) Fáci...
class Calc(object): display = "" curnumber = None numbers = None operations = None def __init__(self): self.operations = [] self.numbers = [] self.curnumber = "" def add_number(self): self.numbers.append(int(self.curnumber)) self.curnumber = "" def...
def max_list_recursive(lst): """ recursive method to find maximum in a list :param: lst - list with > operator defined :return: max value """ pass # @todo -fix this def sum_list_recursive(lst): """ recursive method to find sum of a list :param lst: :return: sum of list, 0 if emp...
import math """ Methods used to generate data files, provided here to allow for testing after reading files """ def make_csv_data(nsteps): iv=[] x=[] y=[] for i in range(0,nsteps): iv.append(i) x.append(2.0*math.pi*i/nsteps) y.append(math.cos(x[i])) return iv,x,y def ...
""" Demo the cost of recursion for Fibonacci sequences """ class FibonacciDemo: def __init__(self): self.loop_count = 0; self.rec_count = 0; def fib_loop(self, n): a = 0 b = 1 while (n > 0): oldA = a a = b b = oldA + b n-=...
""" EXCEPTION Program 3 module tries to catch various exceptions. As is written, the main block raises three exceptions. Rewrite three functions so that they handle specific exceptions. Catch the exception and print the error message. Each shall also have catch all exception handler with the generic error message. I...
total = 1000 def IsPythagorean(a, b, c): return (a**2 + b**2) == c**2 def AddsToTotal(a, b, c): return a + b + c == total def Find(): for i in range(1, total): for j in range(i, total): for k in range(j, total): # print '{} {} {}'.format(i,j,k) if ...
maximum = 20 divisors = range(1, maximum)[::-1] answer = maximum nope = False while(True): for divisor in divisors: if (answer % divisor != 0): nope = True break else: nope = False if (nope): answer += 1 else: break print answer
import os path = input("What is the path you would like to go to: ") while True: os.chdir(path) os.makedirs(input("What directory would you like to make")) if input("Would you like to make another directory (yes/no): ") == "yes": if input("Would you like to change the path (yes/no): ") == "y...
#1 for x in range(0,100,2): print(x + 1, end=" ") #2 kaboom_string = "KABOOM" for x in kaboom_string: print((x + " ") * 3, end="") #3 string_3 = "askaliceithinkshe'llknow" for x in range(0, len(string_3), 2): print(string_3[x:x+1], end=" ") #4 # ? #5 listoflists = [['mn', 'pa', 'ut'], ['b', 'p',...
# Factorials ''' def factorial(number): if number == 1: print(number, " = ", end=" ") return 1 else: print(number, " * ", end=" ") return number * factorial(number-1) print(factorial(int(input('Which number would you like the factorial of? ')))) ''' # Pascal's Triangle def p...
# This is a guess the number game # You have 5 tries or you'll lose the game # The game tracks wins/loses ratio __author__ = 'jaime.alv.fdz@gmail.com' import random win_global = 0 lose_global = 0 name_global = '' def greetings(): global name_global print('Hi. What is your name?') name = input() whil...
#this comment will be in GitHub Repository #a=10 input simple assign data,Keyboard entered data, data from file or DB #b=20 # Variable - Container which contains data for Processing (temp) its logical name for memory address a=int(input("Please enter the first number : ")) b=int(input("Please enter the second nu...
def take(count, iterable): counter = 0 for item in iterable: if counter == count: return counter += 1 yield item def run_take(): items = range(50) for item in take(40, items): print(item) if __name__ == '__main__': run_take()
X = str(input('')) if 'H' in X: print('YES') elif 'Q' in X: print('YES') elif '9' in X: print('YES') else: print('NO')
class Course: def __init__(self, grade, credits, name = "N/A"): self.grade = score[grade] self.letter = grade self.credits = credits self.name = name score = { 'A' : 4.000, 'A-': 3.667, 'B+': 3.333, 'B' : 3.000, 'B-': 2.667, 'C+': 2.333, 'C' : 2.000, 'C-': 1.667, ...
import csv import codecs # def write_to_csv(datalist, header): # pass def write_data(datalist, header, file_name='data.csv'): # 指定编码为 utf-8, 避免写 csv 文件出现中文乱码 with codecs.open(file_name, 'w+', 'utf-8') as csvfile: # filednames = ['书名', '页面地址', '图片地址'] writer = csv.DictWriter(csvfile, fieldn...
import numpy as np def GrahamEvaluate(point_list, point): """ evaluate the addition of a point to a point_list for a Graham Scan if point_list doesn't contain at least 2 values, then add the point and return otherwise, evaluate if the point, together with theh last 2 points makes a clockwise, counter-c...
import numpy as np import pandas as pd from Modules import file_navigation """ This is a python module for reading in the raw and embedded data values This is here to ensure that all other modules and notebooks only call the functions here, instead of writing their own """ def read_embedding_data(dataset, age_cutoff...
L = [4,6,5,1,3,2,7,11,9,10,8] def bubbleSort(L): for i in range(len(L)): j = i + 1 for j in range(i, len(L)): if L[i] > L[j]: L[i], L[j] = L[j], L[i] return L print(bubbleSort(L))
""" Let’s say we have some customer records in a text file (customers.txt, see below) – one customer per line, JSON-encoded. We want to invite any customer within 100km of our Dublin office (GPS coordinates 53.3381985, -6.2592576) for some food and drinks on us. Write a program that will read the full list of custo...
# coding:utf-8 # Possibilitats: PE, PA, TI # Total 9: 3 empat, 6 guanyador # jugador1 humà # jugador2 machine from random import randint #Jugador humà jugador1=raw_input("SR Possi la jugada (PE/PA/TI): ") #Jugador machine aleatori=randint(1,3) if (aleatori==1): jugador2="PE" if (aleatori==2): jugador2="PA" if (ale...
#Carol Castro #88710391 import json import wof_computer import random import time NUM_HUMAN = 1 NUM_PLAYERS = 3 VOWEL_COST = 250 VOWELS = ['A', 'E', 'I', 'O', 'U'] # Load the wheel wheelFile = open('wheel.json', 'r') wheel = json.loads(wheelFile.read()) wheelFile.close() # Load the phrase set phraseFile = open('...
''' The Fibonacci sequence is the integer sequence defined by the recurrence relation: F(n) = F(n-1) + F(n-2), where F(0) = 0 and F(1) = 1. In other words, the nth Fibonacci number is the sum of the prior two Fibonacci numbers. Below are the first few values of the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 14...
''' An IP Address is in the format of A.B.C.D, where A, B, C, D are all integers between 0 to 255. Given a string of numbers, return the possible IP addresses you can make with that string by splitting into 4 parts of A, B, C, D. Keep in mind that integers can't start with a 0! (Except for 0) Example: Input: 1592551...
#You are given a singly linked list and an integer k. Return the linked list, removing the k-th last element from the list. #Try to do it in a single pass and using constant space. #Here's a starting point: class Node: def __init__(self, val, next=None): self.val = val self.next = next def __str__(self):...
#Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. #An input string is valid if: #- Open brackets are closed by the same type of brackets. #- Open brackets are closed in the correct order. #- Note that an empty string is also considered valid. #Examp...
''' You are given an array of integers. Find the maximum sum of all possible contiguous subarrays of the array. Example: [34, -50, 42, 14, -5, 86] Given this input array, the output should be 137. The contiguous subarray with the largest sum is [42, 14, -5, 86]. Your solution should run in linear time. Here's a st...
def fib_set(k): fib = [0] * (k + 2) fib[1] = 1 i = 2 while fib[i - 1] <= k: fib[i] = (fib[i - 1] + fib[i - 2]) i += 1 return set(fib) print(fib_set(20))
''' You are given an array. Each element represents the price of a stock on that particular day. Calculate and return the maximum profit you can make from buying and selling that stock only once. For example: [9, 11, 8, 5, 7, 10] Here, the optimal trade is to buy when the price is 5, and sell when it is 10, so the re...
''' You are given the root of a binary tree. Find and return the largest subtree of that tree, which is a valid binary search tree. Here's a starting point: ''' class TreeNode: def __init__(self, key): self.left = None self.right = None self.key = key def __str__(self): # preo...
''' The h-index is a metric that attempts to measure the productivity and citation impact of the publication of a scholar. The definition of the h-index is if a scholar has at least h of their papers cited h times. Given a list of publications of the number of citations a scholar has, find their h-index. Example: I...
''' Return the longest run of 1s for a given integer n's binary representation. Example: Input: 242 Output: 4 242 in binary is 0b11110010, so the longest run of 1 is 4. ''' def longest_run(n): longest = 0 tmp_longest = 0 while n > 0: if n & 1 == 1: tmp_longest += 1 longest...
#!/usr/bin/env python3 # # IndyCar Preternship Project # University of Notre Dame - CSE 20312 # Creators: Emma Fredin, Aidan Gordon, Jonathon Vasilak, and Mark Schermerhorn # # This program gathers race results in real-time and compiles statistics in a convenient way, particularly concerning the use of Push to Pass and...
n=int(input("enter the number")) i=0 temp=n while n>0: r=n%10 i=i+(r**3) n=n//10 if temp==i: print('it is armstrong number') else: print('not a armstrong number')
import math, random class Solver(): def __init__(self, puzzle): self.num_grid = puzzle.num_grid self.cell_map = puzzle.cell_map self.board = self.start_search(puzzle.board) def start_search(self, board): board = self.constraint_propagation(board) if board == False: ...
def getadd(): # addr = 12345 # addr = 12346 addr = 12347 # addr = 12348 return addr # if state == 0 and len(tmp) > 11 or (len(tmp) > 10 and not tmp.endswith("\a")): # wrong = 1 # if state == 1 and len(tmp) > 6 or (len(tmp) > 5 and not tmp.endswith("\a")): # wrong = 1 #...
import unittest class Node(object): def __init__(self): self.root_node = {} def add_word(self, word): current_node = self.root_node is_new_word = False for character in word: if character not in current_node: is_new_word = True ...
#Sort the given array A = [] n = int(input('Enter number of elements : ')) print('Enter elements : ') for i in range(n): A.append(int(input())) A.sort(reverse= True) print('Sorted array is :', A)
# Union of two sorted arrays with handling of duplication def unionSort(a, b , n ,m): ''' a= Sorted array 1 n= Size of aaray 1 (a) b= Sorted array 2 m= Size of aaray 2 (b) ''' c= list() #a list or array for storing the result i, j =0, 0 while i<n and j<m : while i+1<n and a[...
#Search the element in array by using Binary Search #*Binary search only works on sorted array* def bianrySearch(arr, n, x): l=0 r= n-1 while(l<=r): mid = (l+r)//2 if (arr[mid]==x): return mid if (arr[mid]<x): l=mid+1 else: r=mid-1 retu...
arr=[1, 2, 3, 4] res=[1]*len(arr) left=[1]*len(arr) right=[1]*len(arr) for i in range(len(arr)): left[i]= arr[i-1]*left[i-1] for i in range(len(arr)-2, -1, -1): right[i]= arr[i+1]*right[i+1] for i in range(len(arr)): res[i]=(right[i]*left[i])//len(arr) print (res)
import numpy as np global N N=int(input("Enter N for the size of board : ")) def printSolution(board): for i in range(N): for j in range(N): print (board[i][j], end = " ") print() def isSafe(board, row, col): # Check this row on left side for i in range(col): if board[...
from collections import namedtuple import pygame from .constants import Color Move = namedtuple("Move", "column_delta, row_delta") def is_jump(move_tuple): return abs(move_tuple.column_delta) == 2 def get_jumped_move(move_tuple): """Take a move tuple (e.g. 2, 2) and return the jumped equivalent for that mov...
#!/usr/bin/env python import RPi.GPIO as gpio import time gpio.setmode(gpio.BOARD) gpio.setup(11, gpio.IN) state = 0 while True: input = gpio.input(11) if input == state: continue state = input if state == 0: print('Button Pressed Off') else: print('Button Pressed On') time.sleep(0.2)
#!/usr/bin/env python import RPi.GPIO as gpio def loop(): raw_input() state = 0 def btn_press(pin): global state input = gpio.input(11) if state == input: return else: state = input if state == 1: print("button turned on") else: print("button turned off") gpio.setmode(gpio.BOARD) gpi...
#!/usr/bin/env python ''' ------------------------------------------------------------------------------- Function to replace specific colours in a raster figure. Often you need to change the colour of a raster graphic for some reason, e.g. to increase contrast. Recreating these images can be time consuming. To ...
# name = input('tell me your name, punk: ') # age = input('...and your age: ') # print(name, ' your are ', age) # Calc the area of the circle radius = input('Enter the radius of your circle (m): ') area = 3.142*int(radius)**2 print('The area of your circle is: ', area)
import string def tokenize(main_string, delimeters={" "}, special_tokens={"\\newline"}): """ Returns a list of tokens delimeted by the strings contained in the delimeters set. Punctuation and whitespace characters are treated as individual tokens. Delimeters are no...
#!/usr/bin/env python # Copyright (c) 2018 Intel Labs. # authors: German Ros (german.ros@intel.com) # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ Module with auxiliary functions. """ import math from typing import List, Optional, Tuple imp...
import sys """this is the straight function.""" rank_list = ['x', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] playerlist1 = ['QS', 'JD', '8H', '10C', '9S'] playerlist2 = ['AS', '5D', '6C', '8H', '7S'] print(playerlist1, "this is the players hand") # PART 1 index_list = [] for i in playerlist1: ...
import unittest from .models import movie Movie = movie.Movie class MovieTest(unittestst.TestCase): def setUp(self): self.new_movie = Movie(1234, "Python must be crazy","Ancient pythoneers", "https://image.tmdb.org/t/p/w500/khsjha27hbs",8.5,129993) def test_inctance(self): self.assertT...
class Retangle(): def __init__(self,length=1,width=1): self.length=length self.width=width def __setattr__(self,name,value): if name=='square': self.length=value self.width=value else: super().__setattr__(name,value) def mianji...
while True: num_1 = input('Digite um número: ') num_2 = input('Digite outro número: ') if not num_1.isdigit() or not num_2.isdigit(): print('Digite um número válido.') continue else: num_1 = float(num_1) num_2 = float(num_2) operador = input('Digite a operadoração...
""" https://rszalski.github.io/magicmethods/ """ ## OLHAR O LINK ACIMA ## class A: def __init__(self): # método mágico iniciador print(f'Eu sou o INIT') a = A()
""" Combinations, Permutations e Product - Itertools Combinação - Ordem não importa Permutação - Ordem importa Ambos não repetem valores únicos. Produto - Ordem importa e repete valores únicos """ import itertools pessoa = ['Luiz', 'André', 'Eduardo', 'Letícia', 'Fabrício', 'Rose'] for grupo in itertools.combinations(...
print() print('TEXTO EXPLICATIVO:') perguntas = { 'Pergunta 1': { 'pergunta': 'Quanto é 2+2? ', 'respostas': {'a': '1', 'b': '4', 'c': '5'}, 'resposta_certa': 'b' }, 'Pergunta 2': { 'pergunta': 'Quanto é 2*3? ', 'respostas': {'a': '7', 'b': '9', 'c': '6'}, 'r...
def func(arg, arg2): return f'{arg} * {arg2} =', arg * arg2 var = func(2,4) print(var) variavel = lambda x, y: x * y print(variavel(2, 8))
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] ex1 = [variavel for variavel in l1] # cria uma cópia idêntica a l1 print(ex1) ex2 = [v * 2 for v in l1] # multiplica o valor de v por 2 print(ex2) ex3 = [(v, v2) for v in l1 for v2 in range(3)] # cria uma lista de coordenadas (0, 1), (0, 2)... print(ex3) l2 = ['Luiz', 'Mauro', 'Mar...
import itertools alunos = [ {'nome': 'Derick', 'nota': 'A'}, {'nome': 'Luiz', 'nota': 'B'}, {'nome': 'Karla', 'nota': 'A'}, {'nome': 'Clara', 'nota': 'C'}, {'nome': 'Stheffany', 'nota': 'B'}, {'nome': 'Filipe', 'nota': 'D'}, {'nome': 'Pedro', 'nota': 'C'}, {'nome': 'Maria', 'nota': 'D'},...
class Produto: def __init__(self, nome, preco): self.nome = nome self.preco = preco def desconto(self, percentual): self.preco = self.preco - (self.preco * percentual / 100) @property def nome(self): return self._nome @nome.setter def nome(self, valor): ...
# ESSE CÓDIGO É RESPONSAVEL APENAS PELA DESCRIPTAÇÃO DA MENSAGEM JÁ CRIPTOGRAFADA ## CRIAÇÃO DA TABELA PARA INSERÇÃO DOS VALORES tabela=[] for i in range(26): linha=[] cont=65+i for j in range(26): if cont>90: cont-=26 linha.append(chr(cont)) cont+=1 tabela...
def fact(n): if n == 0: return 1 p = 1 for i in range(1, n+1): p *= i return p def calc_binom(n, k): return int(fact(n)/(fact(k)*fact(n-k))) lines = 10 #lines = int(input("Number of lines: ")) pascal_triangle = [] for i in range(lines): nums = [] for j in range(i+1): ...
import turtle from turtle import Screen import random caspar = turtle.Turtle() turtle.colormode(255) def random_color(): r = random.randint(0, 256) g = random.randint(0, 256) b = random.randint(0, 256) return r, g, b # colors = ["red", "green", "blue", "orange", "purple", "pink", "...
import re def isValidEmail(email): regex = "^[A-Z0-9._+-]+@[A-Z0-9]+.[A-Z]{2,}$" if len(email) > 7: if re.match(regex, email, re.IGNORECASE) is not None: return True if isValidEmail("netsetos@gmail.com"): print("Valid Email Address") else: print("Invalid Email A...
import pandas as pd from objects.subjects import Subjects from objects.students import Students from objects.teachers import Teachers #name_tch = input('Write your name: ') #name_tch = name_tch.capitalize() #print(name_tch) def populate_data(): # all the data with which we will work is entered # --------------...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'equalStacks' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY h1 # 2. INTEGER_ARRAY h2 # 3. INTEGER_ARRAY h3 # #計算stack的總共高度...
nomor = int(input("Nomor Berapa: ")) def dot(): global nomor global num if len(nomor) > 3: num.insert(-3,".") if len(nomor) > 6: num.insert(-7,".") if len(nomor) > 9: num.insert(-11,".") def dot2(): global kali global kal i...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re,sys regex_input = raw_input('Enter regex > ') regexp = re.compile(regex_input, re.IGNORECASE) test_email_addresses = ['abc@gmail.com', 'xyz123@hotmail.com', 'blahblah09@gmail.com'] matched_address = [] for email_address in test_email_addresses: if rege...
#NOMBRES: #Reto 1 #Entradas: Cadena #Salidas: Cantidad de cada caracter #Restricciones: Se debe dar una cadena, la cadena no puede ser vacia def contarCaracteres(cadena): if(type(cadena)!=str): return "Debe indicar una cadena" elif(cadena==""): return "Cadena no valida" else: ...
import random # imports the library named random def rps(): """ this plays a game of rock-paper-scissors (or a variant of that game) arguments: no arguments (prompted text doesn't count as an argument) results: no results (printing doesn't count as a result) ""...
def factorial(n): ans=1 for i in range(1,n+1): ans = ans * i print(f"multiply {i}") return ans # test it print(factorial(9))
def isPrime(n): if n > 2 and n%2 == 0: return 0 i = 3 while i*i <= n: if n % i == 0: return 0 i += 2 return 1 if __name__ == '__main__': l = (input()[1:-1]).split(',') for n in reversed(sorted(l, key=lambda k: int(k))): if isPrime(int(n)): ...
# # @lc app=leetcode id=124 lang=python3 # # [124] Binary Tree Maximum Path Sum # # https://leetcode.com/problems/binary-tree-maximum-path-sum/description/ # # algorithms # Hard (30.60%) # Likes: 1981 # Dislikes: 149 # Total Accepted: 221.9K # Total Submissions: 717.6K # Testcase Example: '[1,2,3]' # # Given a n...
# # @lc app=leetcode id=968 lang=python3 # # [968] Binary Tree Cameras # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minCameraCover(self, root: TreeNode) -> int: # Set c...
#!/usr/bin/python import hashlib import sys m = hashlib.md5() eHarmonyOtptFile = open("eHarmonyOutput.txt", 'w') #Open output file to store matched passwords passwordFile = open("eHarmony.txt", "r+") #Open the given list of hashed passwords passwordList = passwordFile.readlines() for i in range(0,len(passwordLis...
# Team Nintentoads (Stella Oh, Helena Williams, Jason Chan) # SoftDev # K06 -- Amalgate the KREWES # 2020-09-26 # A program that will print the name of a randomly-selected student # from team (orpheus, rex, or endymion) import random # Dictionary of team (str) and names in each team (list) KREWES = { 'orpheus': ...
while True: w=input("檢測的字串(end結束):") if w=="end": print("檢測結束") break else: s=input("檢測的單一字元:") t=w.count(s) print("字元%s出現次數為:%d" % (s,t))
M=int(input("請輸入階層值M:")) i=n=1 while (M>=i): ##True往下執行 i=i*n n+=1 print("超過M為"+str(M)+"的最小階層N值為:"+str(n-1))
# Математическая программа викторины. # # Напишите программу, которая запрашивает ответ для математического выражения, проверяет # , прав ли пользователь или нет, а затем отвечает соответствующим образом сообщением def numb(): num = int(input("Решите пример 35 + 24 - 18 = ")) num1 = int(input("128 - 69 + 17 ...
# BeautifulSoup is used to obtain the html document and for parsing from bs4 import BeautifulSoup # urllib.request for Python 3, urllib for Python 2 from urllib.request import urlopen # xlwt is used to port the data to an excel sheet import xlwt url = "https://www.cadth.ca/about-cadth/what-we-do/products-and-services/...
from time import sleep # used to clear the terminal window from os import name, system # Verifies if the email has at least a basic resemblance to an email def get_email(): while True: email = input("Please enter your email for alert notifications: ") if '@' not in email or '.' not in email or le...
import string def compareItems((w1,c1), (w2,c2)): if c1 > c2: return - 1 elif c1 == c2: return cmp(w1, w2) else: return 1 def main(): print "Word Frequency Analyzer" print "This prints a report on the n most frequent words.\n" fname = raw_input("File to analyze: ") text = open(fname,'r').read() text = ...
""" https://leetcode.com/problems/find-all-anagrams-in-a-string/ https://app.glider.ai/practice/problem/algorithms/anagram-substring/problem Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s...
def binay_search_itr(arr, x): """ https://www.geeksforgeeks.org/floor-in-a-sorted-array/ :param arr: :param x: :return: """ l = 0 h = len(arr) - 1 res = -1 while l <= h: m = l + (h - l // 2) if arr[m] == x: return arr[m] elif arr[m] > x: ...
def divide(arr): """ https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1# https://app.glider.ai/practice/problem/algorithms/inversion-of-array/problem :param arr: :return: """ n = len(arr) // 2 if len(arr) == 1: return arr, 0 left = arr[:n] right ...
res = [] def solve(open, closed, op): """ https://www.interviewbit.com/problems/generate-all-parentheses-ii/ :param open: :param closed: :param op: :return: """ if open == closed == 0: res.append(op) return if open != 0: op1 = op op1 += '(' sol...
from collections import defaultdict class Solution(object): def canFinish(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ self.courseDict = defaultdict(list) for pair in prerequisites: ...
""" https://leetcode.com/problems/coin-change/ You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may a...
def isPalindrome(string): """ :param string: :return: """ return string == string[::-1] def solve(n, string): """ https://app.glider.ai/practice/problem/algorithms/rotation-of-a-palindrom/problem https://www.geeksforgeeks.org/check-given-string-rotation-palindrome/ You are given a...
""" https://www.interviewbit.com/problems/repeat-and-missing-number-array/ You are given a read only array of n integers from 1 to n. Each integer appears exactly once except A which appears twice and B which is missing. Return A and B. Note: Your algorithm should have a linear runtime complexity. Could you impleme...
def fill_water(water, glasses, row, column): """ https://app.glider.ai/practice/problem/algorithms/water-fill-glasses/problem There is a stack of water glasses in a form of pascal triangle and a person wants to pour the water only at the topmost glass, but the capacity of each glass is 1 unit . Overflo...
""" https://app.glider.ai/practice/problem/algorithms/paint/problem In Paint, when we take a Shape Filler and click on a pixel, the color of the region is replaced with a selected color. For a given screen as a 2D array (size of N x M) of colored pixels, S{X, Y} pixel and new color C, replace the color of the given pi...
""" https://www.interviewbit.com/problems/min-steps-in-infinite-grid/ You are given a few points on the coordinate plane and are asked to go through (or visit) all of the given points in the same order as they are given in the input. You can move from a point to any one of its eight adjacent points and it will be cou...
def countNonDecreasing(n): """ https://app.glider.ai/practice/problem/algorithms/nondecreasing-numbers/problem https://www.geeksforgeeks.org/total-number-of-non-decreasing-numbers-with-n-digits/ You have given with a count of digits N. Print the count of total non-decreasing numbers having N digits. ...
def solve(arr): """ https://www.geeksforgeeks.org/find-rotation-count-rotated-sorted-array/ :param arr: :return: """ l = 0 n = len(arr) h = n - 1 if arr[l] < arr[h]: return -1 while l <= h: m = (l + h) // 2 nxt = (m + 1) % n # rotate index of the array fr...
def binay_search_itr(arr, x): """ Given a sorted array, find the element in the array which has minimum difference with the given number. :param arr: :param x: :return: """ l = 0 h = len(arr) - 1 while l <= h: m = l + (h - l // 2) if arr[m] == x: return ar...
def divide(arr): n = len(arr) // 2 if len(arr) == 1: return arr left = arr[:n] right = arr[n:] return merge(divide(left), divide(right)) def merge(left, right): arr = [] i = j = 0 while i < len(left) and j < len(right): if left[i] > right[j]: arr.append(righ...