text
stringlengths
37
1.41M
# 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив, # заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный # и отсортированный массивы. Сортировка должна быть реализована в виде функции. # По возможности доработайте алгоритм (сделайте его умнее). import r...
from cipher import Cipher MENU = """0: exit 1: my info 2: list users 3: get user's public cube 4: get user's ciphercubes 5: go to cipher """ class DataManager: def __init__(self, db, cipher_manager): self.db = db self.cipher_manager = cipher_manager def list_users(self): users = self....
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com #Mostrar la cantidad de numeros pares desde 1 hasta 100 numero=1 cantidad=0 while numero <= 100: #print("Los numeros pares son: ",numero) numero= numero+2 cantidad=cantidad+1 print("La cantidad de numero pares son: ",cantidad)
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com #Mostrar la cantidad de numeros multiplos de 3 desde 1 hasta el numero ingresado por teclado num=int(input("Ingrese un numero: ")) i=3 cant=0 while i<=num: if i%3==0: print(i) cant+=1 i+=1 print("La cantidad de multiplos de 3 es: ...
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com # Un alumno desea saber cual será su calificación final en la materia de Matemáticas, dicha calificación se compone por 3 porcentajes , a su vez cada porcentaje tiene cierta cantidad de notas, primero diremos los siguiente: #parciales 55% examen final 30% trabaj...
##Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com # De acuerdo a tres números , indicar cual es el menor y cual es el mayor. Numero1=float(input("Ingrese un numero: ")) Numero2=float(input("Ingrese un numero: ")) Numero3=float(input("Ingrese un numero: ")) if Numero1 > Numero2 and Numero1 > Numero3: ...
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com # Diseñar un algoritmo que lea por consola el valor de una factura, en este caso aplicaremos un IGV 18% (Perú factura=float(input("Por favor ingrese el valor de su factura: ")) gravamen=factura*0.18500 print("Su valor de IGV es: ",gravamen)
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com #Diseñar un algoritmo que al momento de ingresar tres números, indicar si hay números iguales y números diferentes, # de ser así verificar si están ordenados ascendentemente, descendentemente o desordenados. Numero1=float(input("Ingrese un numero: ")) Numer...
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com # Diseñar un algoritmo que permita aplicar un descuento en el supermercado de tal forma permita visualizar el monto a pagar después de aplicar dicho procedimiento descuento=float(input("Por favor ingrese el valor de descuento: ")) costo=float(input("Por favor...
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com #Mostrar la suma de 2 numeros ingresados por teclado numero1=float(input("Ingrese numero: ")) numero2=float(input("Ingrese numero: ")) suma=numero1+numero2 if suma>0: print("Los numeros ingresados fueron: ",numero1, numero2, "y su suma es: ",suma) else:...
#Nombre: Alejandro Cadena #Correo: Dobleaduo@gmail.com #Muestra de resto y cociente mediante restas resto = 0 co = 0 num=int(input("Ingrese el numerador ")) den=int(input("Ingrese el denominador ")) while num > den: num = num-den resto = num co+=1 print("El residuo es: ",resto) print("El cociente es: ",c...
import unittest from exercises.tree import BinarySearchTree class TreeNodeTests(unittest.TestCase): pass class TreeTests(unittest.TestCase): def test_left_insert(self): #test insert right tree = BinarySearchTree(3) tree.insert(5) tree.insert(3) tree.insert(6) self.assertEqual(tree...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Sympy example: How to solve a differential equation using sympy @author: a.perez """ import sympy as sy sy.init_printing() # Define a generic function u and its variable, t u = sy.Function('u') t = sy.symbols('t') # We want to solve the differential equation u''(t)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 26 21:55:23 2019 @author: telu """ # %% 1) def liste_puissance(p, n): return [i**p for i in range(n)] print('Question 1)') print(liste_puissance(1, 5), liste_puissance(2, 10)) # %% 2) def dernier_chiffre(i): i_str = str(i) # Transf...
"""Utility file to seed system database from sample data in seed_data/""" import datetime from sqlalchemy import func from model import Teacher, TeacherClass, Class, StudentClass, Student, StudentMeasure, Response, Measure, Subject, Objective, Question, QuestionAnswerChoice, AnswerChoice, connect_to_db, db from se...
"""This module define the functions for preprocessing the signal data""" import numpy as np def bandPassFilter(data, sampleRate=None, highpass=None, lowpass=None): """ Return the signal filtered between highpass and lowpass. Note that neither highpass or lowpass should be above sampleRate/2. Paramet...
""" This script generate time series of tweet volumes per hour or per day. Author: Sofiane Abbar Run: python volume.py tweets.txt daily """ import time from datetime import datetime import json from collections import defaultdict import sys try: fname = sys.argv[1] granularity = sys.argv[2] except: pri...
def getHeight(self,root): #Write your code here left, right = 0, 0 if root.left != None: left = self.getHeight(root.left) + 1 if root.right != None: right = self.getHeight(root.right) + 1 return max(left, right)
#!/usr/bin/env python '''''''' #Requesting the YUE cis-linked gene webpage to find cis-regulatory element genomic coordinates that are linked to down- and up-regulated genes '''''''' '''''''' #To find an API, right click a webpage in chrome and inspect element. #You will see the html format for the website. If you ha...
# print("Hey World 😎"[1:2]) my_name = "Stephen" # print(my_name) name_legnth = len(my_name) print(f"{my_name} is {name_legnth} letters long") print(my_name.center(20, "*")) print(type(3/4)) print(int(10)) print(float(10)) print(str(10)) print(chr(97)) print(round(2.34567, 2)) print(type(True)) print(chr(0...
#!/usr/bin/env python3 def getLifeDigit(num, final = False): r = 0 for i in num: r += int(i) if final: return r else: return getLifeDigit(str(r), True) print(getLifeDigit(input("Date of Birth: ")))
# -*- coding: cp1250 -*- __author__ = 'Piotr' import doctest import unittest class recursive_calculate_list_of_number(): def suma(self,tab): if len(tab) ==1: return tab[0] else: return tab[0]+self.suma(tab[1:]) convString = "abcd" def anagramik(a,b): if(len(a)...
"""Generate N random points inside a given Box""" import random import rhinoscriptsyntax as rs def main(box, n): if not box or not n: raise ValueError('Box or Length undefined') points = [] for _ in range(0, n): x = random.uniform(box[0][0], box[6][0]) y = random.uniform(box[0][1], box[6][1]) z ...
#------------------------------------------------------------------------------- # INTPROG Python Coursework # James Taylor # 368574 # Autumn Teaching Block 2014 #------------------------------------------------------------------------------- from graphics import * def main(): print("Patchwork Drawing Program up3...
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class ABCDataset(object): """Abstract base class for a dataset. """ __metaclass__ = ABCMeta @abstractmethod def add(self, iterable): # pragma: no cover """Adds a set of objects from the provided iterable to the datas...
"""he function object in question remembers values in enclosing scopes regardless of whether those scopes are still present in memory. In effect, they have attached packets of memory (a.k.a. state re- tention), which are local to each copy of the nested function created, and often provide a simple alternative to classe...
for x in [1,2,3,4]:print x **2 import os f = open('script2.py') """print f.next() print f.next() l = [1,2,3] i = iter(l) while True: try: X = next(i) except StopIteration: break print X **2""" for line in f: print line
def bonAppetit(bill, k, b): #print bill bill.pop(k) #print bill total_bill = sum(bill) #print total_bill anns_share = total_bill/2 if anns_share < b: return b-anns_share elif anns_share == b: return " Bon Appetit " print bonAppetit([3,10,2,9],1,12)
def sumpairs(arr,s): count = 0 for i in range(len(arr)): for j in range(i+1,len(arr)): if arr[i]+arr[j] == s: count += 1 return count print sumpairs([1,2,3,4,5],5)
#__str__ to return the card name as a string, and __gt__ and __lt__ to allow the cards to be compared against each other. class Card: def __init__(self,value,suit): self.value = value self.suit = suit def __str__(self) -> str: value_conv = {"A": "Ace",2: "Two", 3: "Three", 4: ...
with open(file= "new.txt", mode= "r+") as file_Obj: #brand_new = file_Obj.write(str(58)) file_Obj.write(input(print("Nhao 1 chuoi vao file: "))) file_Obj.seek(0) brand_new1 = file_Obj.read() #file_Obj.close() print(brand_new1)
""" A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known. He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66). His mother looks out of a window 1.5 meters from the ground. How many times will t...
import random import collections import time import matplotlib.pyplot as plt numbers = [] results = [] for i in range(1000): numbers.append(random.randint(1, 10)) choice = int(input('Выберите метод(1 или 2)')) start_time = time.time() if choice == 1: result = collections.Counter(numbers) print...
#Load file FILENAME = "eventLocations.csv" with open(FILENAME) as f: lines = f.readlines() def isPreTrail(date): #LemmingTrail happened August 2013 if date[:4] == '2014': return False elif date[:4] == '2013' and int(date[5:7]) > 8: return False else: return True dates = [l.split()[-1][:10] for l...
""" =================== TASK 1 ==================== * Name: Power to the Number * * Write a function `numpower()` that will for the * passed based number `num` and exponent `expo` * return the value of the number `num` raised to * the power of `expo`. * * Note: Please describe in details possible cases * in which y...
"""Important to point out that nearly all hidden payroll is paid to cops. Quantify that here""" import pandas as pd import sys sys.path.insert(0, "../../Final_Results") df = pd.read_csv("../../Final_Results/Final_by_Agency_Type_SP.csv", index_col=0) yr = list(range(2016,2020)) df.rename(columns = {str(x):x for x in y...
#-*- encoding=utf-8 -*- from askmath.models import Lesson class LessonSorting(): """ Class for ordering the lessons using topological sorting. """ def __init__(self, initial_lessons): """ This function takes as a parameter a list of lessons that do not have prerequisites. """ self.__lessons = list(initial...
from tkinter import * class SimpleAddCal: def __init__(self, win): # Labels self.lbl1 = Label(win, text = "First Number") self.lbl1.place(x = 100, y = 50) self.lbl2 = Label(win, text = "Second Number") self.lbl2.place(x = 100, y = 100) self.lbl3 = Label(win, text = "...
from tkinter import * from tkinter import ttk import sqlite3 class ProductDB : # Will hold database connection db_conn = 0 # A cursor is used to traverse the records of a result theCursor = 0 # Will store the current student selected curr_student = 0 def setup_db(self): # Open o...
# Given a square matrix, calculate the absolute difference between the sums of its diagonals. # https://www.hackerrank.com/challenges/diagonal-difference/problem def diagonalDifference(arr): diagonalSum = 0 for i in range(n): diagonalSum = diagonalSum + (arr[i][i] - arr[i][n-i-1]) return ab...
# Lily has a chocolate bar that she wants to share it with Ron for his birthday. # Each of the squares has an integer on it. She decides to share a contiguous segment # of the bar selected such that the length of the segment matches Ron's birth month and # the sum of the integers on the squares is equal to his birt...
# A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # Find the largest palindrome made from the product of two 3-digit numbers. # https://projecteuler.net/problem=4 def p(x): z=x y=0 while int(x) > 0: y=...
#build a block of code that will excute whenever we tell it to execute def my_function_name(name): print("Hello, {}!".format(name)) my_function_name("Jen") #we mainly want functions to do only ONE thing but do ONE thing WELL #if you need the funciton to do more things, then make more functions #and have them cal...
#anytime you're thinking about returning a list from a function #you can return a generator #the output items are calculated as needed #range is the mathematical promise of integers, that's really #a generator #this calculates it only when we need it #it's better on memory def gen_odd_num(less_than): for x in rang...
import person class Customer(person): def __init__(self, name, address, telNumber, customerNumber, mailingList): Person.__init__(self, name, address, telNumber) self.__customerNumber = customerNumber self.__mailingList = mailingList def customerMailingChoice(self): cust...
#tyrell.brantley001@albright.edu #ask the user for 2 integers def getNumber(): try: numberOne = int(input('Enter the first number: ')) except ValueError: print('This is not an interger! Try again.') numberOne = int(input('Enter the first number: ')) else: return numberOne ...
# An animal shelter, # which holds only dogs and cats, operates on a strictly" # first in, first out" basis. People must adopt either the"oldest" # (based on arrival time) of all animals at the shelter, # or they can select whether they would prefer a dog or a cat # (and will receive the oldest animal of that type). # ...
# Given string inputString: # Find if the the string contains only unique characters # Naive # Runtime O(n^2) def naiveFind(inputString) -> bool: for index, character in enumerate(inputString): for otherCharacter in inputString[index+1:]: if character == otherCharacter: return F...
# Rotate a matrix 90 degrees def rotate(matrix): return list(zip(*matrix[::-1])) matrix = [[1, 2], [3, 4]] print(rotate(matrix))
#! /usr/bin/env python2.7 def array_merger(array_list): """ This function can be used to sort and merge k sorted arrays , where k is the number of arrays """ new_array = [] length_array = len(array_list) range_array = range(length_array) array_tmp = [array_list[array_index].pop(0) for array...
class Vehicle(): def __init__(self,brand_name, color): self.brand_name = brand_name self.color = color def getBrandName(self): return self.brand_name class Car(Vehicle): def __init__(self,brand_name, model, color): super().__init__(brand_name,color) self.model = m...
for x in xrange(100,1000): print x square = False for i in xrange(10, x): if i*i == x: print "perfect square" square = True break elif i*i > x: print "not a perfect square" break if square == False: prime = True for i in xrange(2, x/2): if x &i ==0: prime = False break if prime...
class A(object): def __init__(self, a, b): self.a = a self.b = b def change_first(first): first.a = 6 first.b = 7 first = A(4,5) change_first(first) print(first.a, first.b)
def divide_by_zero_with_generic_exception(dividend): try: result = dividend / 0 except Exception as e: print("Exception occurred!") def divide_by_zero_with_exception(dividend): try: result = dividend / 0 except ZeroDivisionError as e: print("Illegal operation: Division...
def solve(): simple_pirates = 1 coins = 119 found = False while simple_pirates < 100: simple_reward = 0 while simple_reward < 100: simple_reward = simple_reward + 1 deputy_reward = 2 * simple_reward chief_reward = 5 * simple_reward resul...
def use_map(list): print("\nDemo of map function") doubles = map(lambda num: num * 2, list) for number in doubles: print(number) def use_filter(list): print("\nDemo of filter function") uneven = filter(lambda n: n % 2 != 0, list) for number in uneven: print(number) def use_li...
#!/usr/bin/python print("Demo of some basic list operations") print("") print("") def print_list(names): for name in names: print("%s" % (name)) print("-----END OF LIST------") names = [] names.append("Martin") print_list(names) print("list content after insert") names.insert(0, "Kalle") print_list(names) ...
class Login: case = None print("Press 0 to Login") print("Press 1 to Create Account") try: case = int(input("Enter Your Choice ==> ")) if case == 0: print("=============LOGIN===============") userName = str(input("Enter Your Name : ")) password = input...
from datetime import datetime as dt def isPrime(x): for divisor in range(2,x): if x%divisor == 0: # X is non-prime return False return True def factorize(x): primeFactors = [] divisor = 2 while x > 1: if isPrime(divisor): if x % divisor == 0: x = x / divisor primeFactors....
""" Reverse a linked list head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def Reverse(head): ...
""" Delete Node at a given position in a linked list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method. """ def Delete(head, position): pos...
''' What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? ''' from functools import reduce from math import gcd def lcm(a,b): ''' Returns least common multiple of a and b ''' return a*b // gcd(a,b) def smallest_multiple(l): ''' Returns the smallest positive num...
class People(object): role = "students" def __init__(self,name,age): self.name = name self.age = age def eat(self): print("%s is eating..."% self.name) def get_age(self): print("%s is %s years old..."% self.name,self.age) def sleep(self): print("%s is sleeping...
"""binarize.py """ import cv2 import numpy as np from .utils import separate_lab, separate_luv def binary_threshold_lab_luv(image_rgb, b_thresh, l_thresh): """ Returns a binarized version of image_rgb computed by thresholding the blue-yellow channel (b) of LAB representation and the l channel of LUV represent...
"""utils.py """ from matplotlib import pyplot as plt from matplotlib import gridspec as gridspec def generate_4_2_layout(): """ Returns a 4x2 standard layout """ fig = plt.figure(figsize=(10, 10), constrained_layout=True) gs = fig.add_gridspec(4, 2) return fig, gs def generate_6_2_layout(): "...
from wycash import Money, Bank import unittest class TestWyCash(unittest.TestCase): def test_multiplication(self): five = Money.dollar(5) self.assertEqual(Money.dollar(10), five.times(2)) self.assertEqual(Money.dollar(15), five.times(3)) def test_equality(self): # refactoring...
import random def scores_grades(): print "Scores and Grades" for i in range (10): score = random.randint(60, 100) if score >= 60 and score <=69: print "Score:", score, ";", "Your grade is D" elif score >= 70 and score <=79: print "Score:", score, ";", "Your grade ...
x = ['magical unicorns',19,'hello',98.98,'world'] y = [2,3,1,7,4,12] z = ['magical','unicorns'] def typeList(arr): sum = 0 string_list = [] for i in range(len(arr)): if isinstance(arr, int) or isinstance(arr, float): sum+=arr[i] #sums items in the list if they are numbers elif t...
words = "It's thanksgiving day. It's my birthday,too!" print "position of day:", words.find("day") print "new words:", words.replace("day", "month") x = [2,54,-2,7,12,98] def minmax(x): print "min", min(x) print "max", max(x) minmax(x) x = ["hello",2,54,-2,7,12,98,"world"] def firstlast(x): print "first",...
"""Leia 3 valores reais (A, B e C) e verifique se eles formam ou não um triângulo. Em caso negativo, calcule a área do trapézio que tem A e B como base e C como altura. """ A,B,C = input().split() A = float(A) B = float(B) C = float(C) perimetro = A+B+C area_trapezio = C*(A+B)/2 Condicao_1 = (B-C...
"""Faça um programa que calcule e mostre o volume de uma esfera sendo fornecido o valor de seu raio (R). A fórmula para calcular o volume é: (4/3) * pi * R3. Considere (atribua) para pi o valor 3.14159.""" Raio = float(input()) PI = 3.14159 Volume = (4/3.0)*PI*(Raio**3) print("VOLUME = {:.3f}".format(Volume))...
''' Implement an algorithm to determine if a string has all unique characters. ''' unique_str = "AbCDefG" non_unique_str = "non Unique STR" def normalize_str(input_str): # function that removes spaces from string and converts all characters to lower input_str = input_str.replace(" ", "") retu...
''' Given an array of size N-1 and given there are numbers from 1 to N with one element missing, the missing number is to be found. ''' def find_missing_number_in_array(arr): ''' Time complexity: O(n) Space complexity: O(1) arr - array: int ''' # sum all numbers in size N target_sum = sum(i for i ...
# # Lesson 2 # # Lists and Loops # # Lightning Review # # Variables # # Variables are names that you can assign values to # # Variables can contain numbers, strings, lists, True/False # # Variable names can contain letters and underscores and should be descriptive # # Strings # # Strings can contain anything that ...
# -*- coding: utf-8 -*- """ Created on Tue May 14 18:57:50 2019 @author: Stephanie """ answer=("Ахахах, о еде. $$удивление $$улыбка В корпусе на первом этаже есть столовая и автомат с кофе, $$улыбка также прямо на остановке факультета есть киоск, выше по склону слата, и в библиотеке, где ты можешь ещё и почитать, ес...
#生成单个机器人的路径 import random from path import solve_maze_with_queue def generate_cmd(start_pos, obj_pos): current_direction = "S" # 生成一个任务 print(start_pos, obj_pos) # 生成一个路径 path = solve_maze_with_queue(start_pos[0], start_pos[1], obj_pos[0], obj_pos[1]) #print(path) cmd_ary = [] for ...
import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # instance = MyClass(argument1, argument2...) port_number = 65432 server_socket.bind(("0.0.0.0", port_number)) server_socket.listen() print(f"Listening for incoming connection on port {port_number}...") connection, address = server_socke...
from random import shuffle, randint def getHash(length): hash_arr = [] hash = "" for x in range(48, 58): hash_arr.append(chr(x)) shuffle(hash_arr) for x in range(65, 91): hash_arr.append(chr(x)) shuffle(hash_arr) for x in range(97, 122): hash_arr.append(chr(x)) shuffle(hash_arr) for x in range(le...
s=int(input()) if s<1 or s>31: exit(0) s=s%7 if s==1: print("Monday") elif s==2: print("Tuesday") elif s==3: print("Wednesday") elif s==4: print("Thrusday") elif s==5: print("Friday") elif s==5: print("Saturday") else: print("Sunday")
t=float(input("Enter the temp")) f=int(input("Enter 1 to convert celcius to farenhiet or press 2 to convert farenheit celcius")) if f==1: print(t*1.8 +32) elif f==2: print(((t-32)*5)/9)
a=float(input("Enters 1st no")) b=float(input("Enters 2nd no")) c=float(input("Enters 3rd no")) if a>b: if a>c: print("1st no is greatest") else: print("3rd no is greatest") else: if(b>c): print("2nd no is greatest") else: print("3rd no is greatest")
class FizzBuzz: def return_fizz_buzz(self, number): if int(number) % 3 == 0: if int(number) % 5 != 0: output = 'fizz' else: output = 'fizz-buzz' else: if int(number) % 5 != 0: output = number else: ...
from random import choice from nltk.corpus import brown from nltk.corpus import stopwords difficulty = raw_input("Set the difficulty to either easy, medium, or hard:") difficulty = difficulty.lower() while difficulty != "hard" and difficulty != "medium" and difficulty != "easy": difficulty = raw_input("Please enter...
#문자열 포맷 # print("a" + "b") # print("a", "b") #방법 1 print("나는 %d살입니다." % 20) # d 는 정수값만 넣을 수 있음 print("나는 %s을 좋아해요." % "파이썬") # s 는 문자열 String 값을 넣겠다 print("Apple 은 %c로 시작해요." % "A") # c는 캐릭터라서 한 글자만 받겠단 # %s 로만 쓰면 정수건 문자건 상관없이 출력 가능 print("나는 %s살입니다." % 20) # d 는 정수값만 넣을 수 있음 print("나는 %s색과 %s색을 좋아해요." % ("파란", "빨간")...
""" generate nth fibonacci term """ from duration import duration from multiprocessing import Process def fib_recursion(n): # using recursion if n == 0: return 0 if n == 1: return 1 return fib_recursion(n-1) + fib_recursion(n-2) def cache_fib(n, r): # memoization if r[n] >= 0: return ...
""" You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Exp...
def median(list_num): s = sorted(list_num) if len(s)%2 == 0: return (s[len(s)/2] + s[(len(s)/2) - 1]) / 2.0 else: return s[(len(s)-1)/2]
# -*- coding: utf-8 -*- """ Created on Tue Dec 6 23:33:08 2016 Final project intended to be able to schedule courses for students given a list of classes. Initial prioritization is by listing order. @author: clifp """ #from courseClass import* from courseClass import* import sys BARRIER_TEXT = "===================...
class BSTMap: # empty map instance def __init__(self): self._root = None self._size = 0 # return the number of entries in the map def __len__ (self): return self._size # Returns an iterator for traversing the skeys in the map def __iter__(self): return _BSTMapITe...
""" Inspired by: https://www.hackerrank.com/challenges/validating-postalcode/problem (removed regex criteria) Validate postcodes A valid postal code P have to fulfil both below requirements: P must be a number in the range from 100000 to 999999 inclusive. P must not contain more than one alternating repetitive digit...
# Q4: Write a recursive function that checks whether a string # is a palindrome (a palindrome is a string that's the same when # reads forwards and backwards.) def is_palindrome(cs): if len(cs) == 0 or len(cs) == 1: return True if not cs[0] == cs[-1]: return False r...
""" hackerrank: https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem Davis has a number of staircases in his house and he likes to climb each staircase 1, 2 or 3 steps at a time. Being a very precocious child, he wonders how many ways there are to reach the top of the staircase. Given the respective h...
""" Hackerrank: https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-lite For this question, you will write a program that generates values from the Fibonacci sequence. The Fibonnaci sequence is recursively defined by: Fn = Fn - 1 + Fn - 2 Using the following seed values: F0 = 0, F1 ...
""" From my interviewcake.com question of the week email: Write an algorithm that determines if two rectangles overlap on an xy grid. A rectangle is defined as a dictionary like the below: rectangle_one = { 'left_x' : 1, 'bottom_y' : 1, 'width' : 6, 'length' : 3 } rectangle_two = { 'left_x' : 5, ...
""" From: Cracking the Coding Interview Pattern Matching You are given two strings, pattern and value. The pattern can only be a and b where as values can be for example catcatcatgocatgo which matches with aaabab. Write a function which tests to see if the value matches the pattern. """ def find_pattern(cs): if le...
""" FROM CTCI: Pond Size: You have an integer matrix representing a plot of land, where the value at that location represents the height above sea level. A value of zero indicates water. A pond is a region of water connected vertically or horizontally. The size of the pond is the total number of connected water cells....
# Write a function that is passed a linked list of integers and a “target” number # and that returns the number of occurrences of the target in the linked list. class Node: def __init__(self, val, next_node=None): self.val = val self.next_node = next_node class LinkedList: def __init__(self,...
""" From: Cracking the Coding Interview Assuming that we have a method isSubstring, that returns true or false depending on whether or not string1 is a substring of string2, use isSubstring to determine whether or not string2 is a rotation of string1. Eg "waterbottle" is a rotation of "erbottlewat" """ def is_substrin...
from TrieNode import TrieNode class Trie: def __init__(self): self.root = TrieNode() def char_to_index(self, c): return ord(c) - ord('a') def insert(self, cs): # ctn -> current trie node ctn = self.root cs = cs.lower() for c in cs: c_asc...
import alphabet Nodes = [] class Node(object): def __init__(self, name, num): self.name = name self.higher_nodes = [] self.lower_nodes = [] if(num == 1): self.tentative = 0 else: self.tentative = 1000 self.distances = {} self.num_lower = 0 self.num_higher = 0 def add(self, node, dis):...