text
stringlengths
37
1.41M
import datetime def timestamp(): now = datetime.datetime.now() return now.strftime("%d.%m.%Y %H:%M:%S") def elapsed_time(start_time, end_time): seconds = end_time - start_time minutes = seconds // 60 seconds %= 60 print("Elapsed time: {0:.0f} minutes {1:.0f} seconds".format(minutes, seconds)...
def find_nearest_repetition(paragraph): word_latest_index = {} nearest_dist = float('inf') for idx, word in enumerate(paragraph): if word in word_latest_index: diff = idx - word_latest_index[word] word_latest_index[word] = idx if diff < nearest_dist: ...
def binary_search(arr, x): left, right = 0, len(arr)-1 while left <= right : mid = left + (right - left)/2 if arr[mid] == x : return mid if arr[mid] < x : left = mid+1 else: right = mid-1 return -1 if __name__=="__main__": arr = [-14, ...
import random class Stack: class MaxWithCount: def __init__(self, max, count): self.max = max self.count = count def __init__(self): self._element = [] self._cache_max_count = [] def is_empty(self): return len(self._element)==0 def push(sel...
def compute_h_index(arr): l = len(arr) arr.sort() for idx, val in enumerate(arr): if val >= l - idx: return l-idx return 0 if __name__ == "__main__": arr = [6,9,5,8,1] print "Array -", arr print "h-index =", compute_h_index(arr)
class MinHeap: def __init__(self): self.current_size = 0 self.heap = [0] def insert(self, x): self.current_size += 1 self.heap.append(x) self.perc_up(self.current_size) def perc_up(self, idx): while idx // 2: if self.heap[idx] < self.heap...
## Followup question of 3.3 from stack import * class SetOfStacks: def __init__(self, stack_size): self.stacks = [] self.max_size = stack_size def get_last_stack(self): if self.stacks: return self.stacks[-1] return None def push(self, x): last = se...
from linked_list import * def has_cycle(head): slow = fast = head while fast and fast.next and fast.next.next: slow, fast = slow.next, fast.next.next if slow is fast: slow = head while slow is not fast: slow, fast = slow.next, fast.next return...
from binary_tree import * def preorder(root): s, result = [root], [] while s: x = s.pop() if x: result.append(x.val) s.append(x.right) s.append(x.left) return result if __name__ == "__main__": root = get_sample_binary_tree() tree_traversal(root) ...
# -*- coding: utf-8 -*- import math # 这种写法就是Python特有的列表生成式。利用列表生成式,可以以非常简洁的代码生成 list。 L = [x * x for x in range(1, 11)] print [x*(x+1) for x in range(1, 100, 2)] # range(1, 100, 2) 可以生成list [1, 3, 5, 7, 9,...] d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } tds = ['<tr><td>%s</td><td>%s</td></tr>' % (name, score) for nam...
from random import randint player = 0 comp = 0 turn = 0 crimenum = 1 print "Welcome to the Prisoner's Dilemma" print "You and your partner have been caught on a bank robbing spree. You are sequestered in separate interogation rooms. You will each be given the chance to confess to or deny each individual robbery on your...
def addition(a,b): c=a+b print(c) def subtract(a,b): c=a-b print(c) import time print("This is python programming") time.sleep(3) print("Thank you")
"""from collections import Counter def common_permutation(a, b): return ''.join(k * v for k, v in sorted((Counter(a) & Counter(b)).items())) print( common_permutation('pretty', 'women')) print( common_permutation('walking', 'down')) print(common_permutation('the', 'street')) #print common_permutation('aaa...
import random class Card(): suits = ['Spades',"Hearts","Clubs","Diamonds"] ranks = ['None','Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King'] def __init__(self,suit,rank): self.suit = suit self.rank = rank def show(self): print '{} of {}'.format(Card....
class Node: def __init__(self,val): self.val = val self.next = None def add(self,node): self.next = node def x(M,l): n = 1 root = Node(l.pop(0)) prev = root while(l): n += 1 curr = Node(l.pop(0)) prev.next = curr prev = cu...
from collections import deque,defaultdict class Table: capacity = 0 availability = True occupancy = 0 def __init__(self,number): self.number = number def addOccupant(self): self.occupancy += 1 self.availability = False def setCapacity(self,capacity): self.capacity = capacity de...
''' Create a class that represents a deck of playing cards. The data for this object will be the cards themselves. The methods this class will have are the following deal - a method that returns the value of the card on top of the deck. Once a card is dealt it cannot be dealt again until the deck is shuffled. shuffle...
#Given a string of numbers, retrun tru/false if the string is valid if seen from the opposite side #Eg: "0169", opposite side view is "6910", "234" opposite side view is invalid #Simple dictionary to store the numbers as indices, and their valid upside down views as values numberRef = {'0':'0', '1':'1', '6':'9', '8':'...
#Pascal's Triangle: ''' [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] ''' class Solution: # @param A : integer # @return a list of list of integers def generate(self, A): answer = [] if A == 0: return answer row0 = [1] if A == 1: ...
def sudoku2(grid): # check 3*3 grids: uniques = [] #check rows first for i in range(len(grid)): for j in range(len(grid)): if grid[i][j] == '.': pass elif grid[i][j] not in uniques: uniques.append(grid[i][j]) else: ...
g={1: [2, 3,6], 2: [4, 5], 3: [6, 7],4:[8,9,13]} def BFS(G,root): queue = [] #The queue visited = [] #The path of visited nodes ht = [(0,root)] #Starting: queue.append(root) level = 1 members = 1 neighbors = 0 ht = [(0,root)] while queue != []: v = queue.pop(...
def sortarr(given): l = [] for i in range(0,131): l.append(0) #list of 130 items initialized for each in given: # each will represent the index in l l[each]=l[each]+1 #print l #sorting the input list: i=j=0 while i<=130: #traversing the list l if l[i]!...
def sorted_insert(iterable, *, key=lambda x:x, reverse:bool=False): iterable = list(iterable) for i in range(1,len(iterable)): poz = i-1 elem = iterable[i] while poz >= 0 and key(elem) <= key(iterable[poz]): iterable[poz+1] = iterable[poz] poz = poz-1 ite...
def main(): verbo=raw_input("Verbo: ") verbo= verbo.lower() print verbo verbo_f(verbo) def verbo_f(verbo): novo_verbo= verbo[0:len(verbo)-2] novo_verbo = novo_verbo+"o" print novo_verbo if __name__== "__main__": main()
# -*- coding: cp1252 -*- def main(): data=raw_input("Digite a data( / / )") data = data.split("/") data_mes(data) def data_mes(data): meses = ['Janeiro','Fevereiro','Maro','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'] print data[0],"de %s de "%(meses[in...
#string is made of characters - letters[a-z,A-Z], digits[0-9], special characters like comma, period, semicolon # characters are stored in ASCII format or Unicode format (UTF-8,56 UTF-16,UTF-32) str1 , str2 = "Hello", " World " num = 10 # Basic operations on string print(f"Concatenation of {str1} and {str2} = {st...
import math import numpy as np import matplotlib.pyplot as plt class Bezier: """ Bezier curve interpolation around points Attributes: n: The number of points around which it will be interpolated points: The coordinate of the points around which it will be interpolated ...
nil = 0 num = 0 max = 1 cap = "A" low = "a" print("Equality :\t" , nil , "==" , num , nil == num) print("Equality:\t" , cap , "==" , low , cap == low) print("Inequality:\t" , nil, "!=" , max , nil!= max) print("Greater:\t" , nil ,">" , max, nil > max) print("Lesser:\t" , nil , "<" , max , nil < max) pr...
'''he greeting program. Make a program that has your name and the current day of the week stored as separate variables and then prints a message like this: “Good day <name>! <day> is a perfect day to learn some python.” Note that <name> and <day> are predefined variables in source code. An additional bonus will...
from tkinter import * import math #Creating GUI: #Initiating window. window = Tk() window.geometry('1920x1080') #Putting title. window.title("Quadratic Calculator") #Defining function to handle "clicked event": def calculate(): enterButton.configure(text="Calculate") a = int(aEntry.get()) b = int(bEntry....
# -*- coding: utf-8 -*- """ Created on Sun Aug 30 17:23:33 2020 @author: Shanu """ from random import randint num=str(randint(100, 999)) print("Welcome to the 3 digit number guessing game \nType \"quit\" to forfeit the game ") def guess(): usr=str(input("Input your guess\n")) if(len(usr)<3): ...
i = 0 #define integer while (i<119): #wile i is less than 119, do the following print(i) #print current value of i i += 10 #add 10 to i
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ start=0 last=len(nums)-1 i=0 while i<=last: if nums[i]==0 and i!=start: nums[i],nums[start]=nums[start],num...
#!/usr/bin/env python # Basic Data Types import json my_int = 1; my_float = 1.4; my_float2 = 2.64e-9; myList = [ my_int , my_float , my_float2 ] myDict = {'obj1':myList} jsonObj = json.dumps(myList, myDict) FileName = "./Ex1_DumpNLoad_Json.Db" FilePtr = open ( FileName, "w") print "Writing the File - " , File...
#!/usr/bin/env python import urllib2 #import json import simplejson url = "https://www.youtube.com/results?search_query=json+tutorial+for+beginners&oq=json+&gs_l=youtube.1.0.0l10.6363.7333.0.12650.5.4.0.1.1.0.183.638.0j4.4.0...0.0...1ac.1.11.youtube.mKBgnjiljyw" req = urllib2.Request(url) opener = urllib2.build_open...
#ORIGINAL POEM # Author : Pawn # Title : Stars in your eyes # License : None print "You are : "; print "1.A man "; print "2.A woman "; answer=input() gender="person"; char="She"; if answer==1: gender="man"; if answer==2: gender="woman"; char="He"; try : lookLikeCoolAndFunny(me); except: ...
from random import randint import csv #import math #import copy mainmenu = ["1:Add a new item ", "2:Move an item", "3:search an item", "4:view the inventory of a warehouse", "0: exit the system"] warehouseA = [] warehouseATV = 0 def addNewItem(): global warehouseA globa...
matrix1 = [] matrix2 = [] matrix3 = [] a = input("Введите операцию (+ или *): ") print("Введите первую матрицу") for x in range(3): s = [] for y in range(3): s.append(int(input())) matrix1.append(s) for x in range(3): # Вид 1-ой матрицы for y in range(3): print(matrix1[x][y]...
#!/usr/bin/env python # -*- coding: utf-8 -*- from model import * import sys import unittest MS_2_KMH = 3.6 class TestSimpleSpeedControl(unittest.TestCase): def test_that_simple_pid_speedcontrol_reaches_desired_speed(self): car = Car() controller = SpeedController(car) car.set_control...
import random import math random.seed(0) class Point: x = -1.0 y = -1.0 def __init__(self, x = -1, y = -1): self.x = x self.y = y def __str__(self): return '({:-f}; {:-f})'.format(self.x, self.y) def __repr__(self): return str(self) def __hash__(self): ...
from run_raindrops import * # This will run the app allowing user to decide what number to use and print the factorials n = '' while n != 'exit': n = int(input("Enter a number: ")) print_all_factors(n) print(pling_plang_plong(n))
def sift_down(lst, elem): result = [] while True: left = 2 * elem + 1 if 2 * elem + 1 < len(lst) else elem right = 2 * elem + 2 if 2 * elem + 2 < len(lst) else elem min_elem = elem if lst[elem] < lst[left] else left min_elem = min_elem if lst[min_elem] < lst[right] else right ...
def suma(num1, num2): return num1 +num2 def resta(num1, num2): if(num1<num2): return num2-num1 else: return num1-num2 def potencia(num1, pot): return num1**pot def division(num1, num2): if(num2 != 0): return num1/num2; else: return 'indefinido'
import random import os many = int(input("How many numbers: ")) file = str(input("What file name: ")) folder="D:\\Coding\\Coding-Projects\\python\\homework\\" os.chdir(folder) fopen = open(file, 'a') where=os.getcwd() print(where) for x in range (1,many+1): randomnumber=random.randint(0,999) result=str(random...
#homework_3 #Programmer James Bishop #Date August 28, 2013 #Assignment: Write a complete python program that inputs 3 integers and outputs YES if all three of the integers are positive otherwise it outputs NO. #Get the 3 inputs one = input("What is the first integer? > ") two = input("What is the second integer? >...
#homework_3 #Programmer James Bishop #Date August 28, 2013 #Assignment: Write a complete python program that inputs 3 integers and outputs YES if any of the three of the integers is positive otherwise it outputs NO. #Get the 3 inputs a=input("Enter the first integer: ") b=input("Enter the second integer: ") c=input("E...
def equal(a, b, c): if int(a) == int(b) and int(b) == int(c) and int(c) == int(a): return True elif int(a) == int(b) or int(b) == int(c) or int(c) == int(a): return True else: return False print(equal("5", "5", "5"))
import argparse def main(): """ Function to create argparse object to get CLI arguments and invoke relevant functions based on these :return: none """ pass if __name__ == '__main__': try: main() except KeyboardInterrupt as ex: print(ex) exit(1) exit(0)
import sqlite3 conn = sqlite3.connect('tutorial1.db') c = conn.cursor() def read_from_db(): c.execute("SELECT datestamp, value FROM stuffToPlot WHERE value=4 AND keyword='Python'") # data = c.fetchall() # print(data) for row in c.fetchall(): print(row) read_from_db() c.close() conn.close()
#!/usr/local/bin/python def new_list(): list=[2,45] print list[0] for i in range(5): if i < len(list): list[i] = i else : list.append(i) for i in range(5): print list[i] #new_list() def del_list(): list = range(10) print list del list[2] ...
# Last amended: 15th March, 2019 # My folder: /home/ashok/Documents/10.higgsBoson # Ref: # https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60 # Objective: # Learning basics of PCA # 1.0 Reset memory and call libraries %reset -f import pandas as pd import numpy as np # 1.1 For scaling data fr...
# Last amended: 24th June, 2019 # Ref: # http://cs231n.github.io/neural-networks-2/ # https://machinelearningmastery.com/image-augmentation-deep-learning-keras/ # # Objective: # How Image augmentation is performed. # Image augmentation basics # # # $ cd ~ # $ source activate tensorflow # On Wi...
#Imports Pandas package #Saves the excel file to a variable named xl #Saves formatting to variable named lines #Stores the sales data from the Excel sheet in variable named SalesData import pandas as pd xl = pd.ExcelFile("OSSalesData.xlsx") lines = "=" * 25 SalesData = xl.parse("Orders") #Defines the main menu functi...
import random import time ##Compares the selected user play and selected robot play from users perspective for victory def player_plays(selected_user_play, selected_robot_play): if selected_user_play == 'Rock' and selected_robot_play == 'Scissors': return 'Player wins!' elif selected_user_play == 'Scissors' and se...
import pygame #This is adapted from Python Crash Course class Ship(): def __init__(self, screen): self.screen = screen #This will load the ship sprite and get its rect (or rectangle) self.image = pygame.image.load() self.rect = self.image.get_rect("finalProject/Shup.gif") ...
@@ -0,0 +1,149 @@ # def binarify(num): # """convert positive integer to base 2""" # powers=[] # for i in range(0,20): # powers.append(2**i) # for i in range(0, len(powers)-1): # if number > powers[i] and number <powers[i+1]: # myindex=i # digits=[] # for i in range (0, myindex+1)[::-1] # digit=...
print("Hej TE19C") # skapar en variabel och tilldelar det värdet "Linus" name = "Linus" #print (name) print(f"Ditt namn är {name}") # float typomvandlar strängen till ett flyttal för att kunna räkna med det side = float(input("Ange kvadratens sida: ")) area = side**2 print(f"Arean av kvadraten är {area} a.e.")
# tail recursive fib, with the help of http://stackoverflow.com/questions/22111252/tail-recursion-fibonacci def perfFib(a, b, n): if n == 1: return a else: return perfFib(b, a+b, n-1) def fib(n): return perfFib(1, 2, n) # solution a, b, sum = 1, 2, 0 while a < 4000000: a,b = b, a+b ...
import numpy as np import matplotlib.pyplot as plt import imblearn from imblearn.over_sampling import SMOTE from imblearn.under_sampling import RandomUnderSampler from imblearn.pipeline import Pipeline # A function that takes in the target column, and prints the frequencies for each class. # If you set the plot parame...
#!/usr/bin/env python f = open("data/input.txt","rb+") changes = [] for i in f: changes.append(int(i)) frequency = 0 for change in changes: frequency = frequency + change print frequency
import csv from utils import * ''' Form of raw event: date, name, type, time, category The point of this module is to take the provided raw data and correctly parse it. Each row will have the following columns. Headers to implement: Important: [x] participant_id [x] gender [x] age [x] number_of_total_even...
#!/usr/bin/env python3 # # Created by Austin de Mora # Created on May 2021 # This function displays ever RGB value using nested # loops def main(): # This function displays ever RGB value using nested # loops print("This program displays all RGB values from " "(0,0,0) to (255,255,255...
import random from colorama import Fore,Back,Style class Numbers: """ Create and generate random code. Takes in a guess and compares. Stereotype: Information Holder """ def __init__(self): self.code = random.randint(1000, 9999) self.output = '****' def get_hint(self, guess): "...
class Payroll: # private personal_relief = 2400 def __init__(self, basic_salary, benefits): self.basic_salary = basic_salary self.benefits = benefits def calculate_gross_salary(self): """ Gross salary is the salary that you get after adding all the benefits and allowa...
#def int_func(a): # b = a[0].lower() + a[1:] # return b #print(int_func(input("Type a word: "))) def upcase(): while True: words = input('Enter list of words or * to exit: ').split(" ") output = [] for i in words: try: if i == '*': ...
class DoubleLinkedListNode: #for interviewer reference def __init__(self, data, next=None, prev=None): self._data = data self._next = next self._prev = prev class DoubleLinkedList: #for interviewer reference def __init__(self, head=None): self._head = head se...
# def print_list(sample,count): # for i in sample: # if type(i) == list: print_list(i,count + 1) # else: print("---" * count + "+" + str(i)) # sample = [7,[3,2,[1,4]],[5,[6,[2], 3]]] # print_list(sample,1) sample = [7,[3,2,[1,4]],[5,[6,[2], 3]]] answer = 0 # def sum_list(sample): # for i in sample:...
"""This module generates all permutation of numbers starting from 1 up to and including n""" def helper_all_perms(numbers): """Recursive function to actually generate the permutations""" if len(numbers) <= 1: yield numbers else: # Generate all permutation for numbers excluding the fi...
"""This module contain a memoized decorator, and two memoized functions (fib, n_choose_r)""" import functools class Memoized: """Decorator adding memoization to a function""" def __init__(self, func): functools.update_wrapper(self, func) # Will make e.g. fib.__name__ = "fib" self.func = ...
def twice(func): def loop_twice(*args): func(*args) func(*args) return loop_twice @twice def say_hello(name): print(f'Hello, {name}') say_hello('MUIC') def repeat(n): def get_function(func): def do_something(*args): for _ in range(n): func(*args) return do_something return get...
""" python script that generates timeseries plot - line and circle using bokeh library. line : gap between the two dates circle : repersenting every node and its count """ from bokeh.plotting import figure, show, output_file from datetime import datetime import pandas as pd import numpy as np # Utility function to...
import pandas as pd import clipboard import math import argparse parser = argparse.ArgumentParser() parser.add_argument("csv", help="Name of the CSV file", type=str) parser.add_argument("column", help="Name of the column you want to copy", type=str) parser.add_argument("copy_count", help="Number of entries to copy in ...
sum=0 for i in range(3,1000): if (i%3==0 or i%5==0): sum+=i print(sum)
#Author : Avinash Kumar 2018 #This Program is designed to convert the given numerical to Words print("\n*********************** Numericals To Words ***************************\n\n") n=int(input("Enter a Number you want to convert to Words : Minimum =0 Maximum = 9900009999999.\n\n This Program can help you within t...
#bottom up mergesort adapted from sedgewick wayne def mergesort_bottom(L): n = len(L) length = 1 while(length < n): low = 0 while(low < n - length): merge_bottom(L, low, low + length - 1, \ min(low + 2 * length - 1, n - 1)) low += 2*length length...
import urllib2 import re print "" while True: try: tofind = raw_input("Enter a valid URL: ") complet = "http://" + str(tofind) urlrequest = urllib2.urlopen(str(complet)) reading = urlrequest.read() urlrequest.close() print " *Done!" break except: ...
""" Funciones con listas Aquí van algunas funciones útiles cuando trabajamos con listas. remove(x) - remueve el primer valor X de la lista pop([i]) - remueve el valor en la posición i. pop() remueve el último valor de la lista len(x) - permite calcular el tamaño de una lista """ def ejemplo1(): nombre...
def get_city_country(city_name, country_name, population=None): """Slightly formatted city name and country.""" result_string = f"{city_name}, {country_name}".title() if population: result_string += f" – population: {population}." return result_string
def show_messages(messages): for message in messages: print(f"{message.title()}") # Write a function, that prints each message and # Moves each message to a new list called sent_messages as it’s printed. def send_messages(messages, sent_messages): while messages: popped_message = messages.pop...
rivers = {'nile': 'egypt', 'amazon': 'brasil', 'yangtze': 'china', 'mekong': 'laos, cambodia, vietnam', 'volga': 'russia', 'ganges': 'india', 'mississipi': 'united states', 'danube': 'austria, hungary' } for key, value in rivers.items(): print(f"The {k...
# Places to visit places = ['japan','australia','norway', 'belarus'] print(places) print(sorted(places)) print(places) # you can add arguments to the function using a comma # Used sorted() to print in reverse alphabetical order without changing the original list. print(sorted(places,reverse=True)) print(places) print(...
class Restaurant: """A class representing a restaurant.""" # Store two attributes: a restaurant_name and a cuisine_type def __init__(self, restaurant_name, cuisine_type): """Initialize name and type attributes.""" self.name = restaurant_name self.type = cuisine_type def descri...
# Movie theater charges different ticket prices depending on a person’s age. age = input("\nPlease enter your age and I say how much ticket will cost for you: ") age = int(age) if age <= 3: print("Ticket is free!") elif age > 3 and age <= 12: print("The ticket is $10.") else: print("The ticket is $15.")
# My wish list for cars with messages cars = ['tesla', 'toyota prius', 'nissan', 'mini cooper', 'honda accord'] message1 = f"I would like to own {cars[0].title()}." message2 = f"But {cars[1].title()} is cheaper." message3 = f"Artsiom and Verona own {cars[-1].title()} in California." print(message1) print(message2) prin...
# Write a program that creates a list of items and uses each function introduced in this chapter at least once. languages = ['russian','belarusian','english','french'] print(languages) languages.append('japanese') print(languages) #if i use -1 instead of 4, then 'german' goes before 'japanese', #it means insert() fun...
''' Function that prints one sentence telling what you are learning in this chapter. Call the function, and make sure the message displays correctly.''' def display_message(): print("In chapter 8 you’ll learn about functions!") display_message()
# Think of five simple foods, and store them in a tuple. # Use a for loop to print each food the restaurant offers. buffet_food = ('noodles', 'potato', 'vegetables', 'meat', 'fish') print('Original menu: ') for food in buffet_food: print(food.title()) # Try to modify one of the items, and make sure that Python reje...
import unittest from city_functions_11_2 import get_city_country class NamesTestCase(unittest.TestCase): """Test for 'city_functions.py'.""" def test_city_country_name(self): """Do Tokyo, Japan works?""" full_name = get_city_country('tokyo', 'japan') self.assertEqual(full_name, 'Tokyo,...
""" In this exercise, you'll be playing around with the sys module, which allows you to access many system specific variables and methods, and the os module, which gives you access to lower- level operating system functionality. """ # See the docs for the OS module: https://docs.python.org/3.7/library/os.html import o...
x = input('Ведите число ') y = int(x+x) z =int(x+x+x) x= int(x) f = x + y +z print(f'{x}+{y}+{z}={f}')
# https://www.hackerrank.com/challenges/nested-list/problem marksheet = [[raw_input(), float(raw_input())] for _ in range(int(raw_input()))] second_lowest = sorted(list(set([score for name, score in marksheet])))[1] names = sorted([name for name, score in marksheet if score == second_lowest]) for name in names: p...
# https://leetcode.com/problems/same-tree/description/ def is_same_tree(p, q): if (p and not q) or (not p and q): return False if not p and not q: return True return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right) def is_same_tree(p, q): if p and q:...
def print_pairs(array): for i in array: for j in array: print("%d, %d" %(i, j)) print_pairs([1, 2, 3, 4, 5]) # The complexity of the print_pairs function is: O(N^2) # We do a nested loop = length(array) ^ 2 = N * 2 # There are O(N^2) pairs # Conclusion: O(N^2)
# https://www.hackerrank.com/challenges/palindrome-index import sys def is_palindrome(s): return s == s[::-1] def palindrome_index(s): for i in range(len(s)): if is_palindrome(s[i+1:len(s)-i]): return i if is_palindrome(s[i:len(s)-i-1]): return len(s)-i-1 q = int(raw...
def reverse(array): for i in range(len(array) / 2): index = len(array) - i - 1 temporary_num = array[index] array[index] = array[i] array[i] = temporary_num return array new_array = reverse(list(range(1, 6)) for i in new_array: print(i) # The complexity of the reverse fun...
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def is_empty(self): return self.head == None def push_front(self, data): new_node = Node(data) new_node.next = self.head ...
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ ''' - Examples: [1, 1, 2] # => 2 [] # => 0 [1, 1, 1] # => 1 [1, 2, 3, 3, 4, 5] # => 5 ''' def remove_duplicates(nums): if not nums: return 0 total_result = 1 num = nums[0] for index in range(1, len(nums)): ...
def sequential_search(list, item): for element in list: if element == item: return True return False list = [1, 2, 32, 8, 17, 19, 42, 13, 0] print(sequential_search(list, 3)) print(sequential_search(list, 13))
''' https://leetcode.com/problems/self-dividing-numbers/description/ Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] ''' def self_dividing_numbers(left, right): output = [number for number in range(left, right + 1) if dividing(number, number)] return output def dividing(number...
from linked_list import * print('--- Instantiate Linked List ---') linked_list = LinkedList() print(linked_list) print('--- Push Front & Size ---') linked_list.push_front(10) linked_list.push_front(9) linked_list.push_front(8) print("Current size: %i" %(linked_list.size())) print('--- Push Back ---') linked_list.pus...