text
stringlengths
37
1.41M
import unittest from employee import Employee, Person from parameterized import parameterized class TestPerson(unittest.TestCase): @parameterized.expand([ ("Federico", "Davara", 19, 2612427136, {"name":"Federico", "surname":"Davara", "age":19, "phone":2612427136}) ]) def test_get_person(self, name...
from employee import Employee, Person class Administration: listEmployee={} def add_employee(self,employee): legajo=len(self.listEmployee) self.listEmployee[legajo]=employee return if __name__ == '__main__': adm=Administration() adm.add_employee({'name':"Celina",'surnam...
class Punto(): def __init__(self, a=0, b=0): self.a= a self.b= b def __str__(self): return "(%d, %d)" % (self.a, self.b) class PuntoMejorado(Punto): def cuadrante(self): print(a) if a > 0 and b > 0: print("cuadrante 1") elif a < 0 and b ...
class Person: def __init__(self, name=None, surname=None, age=None): self._name = name self._surname = surname self._age = age def get_person(self): # upper() pone a los atributos en mayusculas. return {'_name': self._name.upper(), '_surname': self._surname.upper(), ...
#106482904 Feb/04/2021 23:45UTC+5.5 shamanthmuroor 1A - Theatre Square Python 3 Accepted 61 ms 0 KB """ Question 1a: Theatre Square Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with...
def subArraySum(arr, n, s): for i in range(n): sum = 0 for j in range(i, n): sum += arr[j] if sum >= s: if sum == s: return [i+1, j+1] break return [-1] arr = [1,2,3,4,5,6,7,8,9,10] n = 10 s = 15 ans = subArray...
""" Count the frequency of all the characters in given string """ def hashFunc(c): return (ord(c) - ord('a')) #ord: gets ascii value of integer def countFreq(S): for i in range(len(S)): index = hashFunc(S[i]) Frequency[index] += 1 print("Enter String to count character frequency: ") S...
""" 102951: USACO Gym Problem: A. Maximum Distance You are given N (3≤N≤5000) integer points on the coordinate plane. Find the square of the maximum Euclidean distance (aka length of the straight line) between any two of the points. Input The first line contains an integer N. The second line contains N integers, th...
#!/usr/bin/env python3 # ## BASIC WEB SCRAPPER # these are the packages to install with pip package_names = ['requests', 'beautifulsoup4'] import requests import bs4 # to print the data list def print_list(list_data, list_type): print("\nHere is the listing of {}:".format(list_type)) for item in list_data: ...
#import necessary libraries import numpy as np import matplotlib.pyplot as plt import ROOT ROOT.gROOT.SetBatch(True) import math as mt import time ##create constants dimesions for the scintillators !global variables!## start = time.time() def main(): ## get the relevant values from the user ## # give scintill...
''' Created on Dec 20, 2017 @author: venturf2 --- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the in...
''' Created on Dec 20, 2017 @author: venturf2 --- Day 12: Digital Plumber --- Walking along the memory banks of the stream, you find a small village that is experiencing a little confusion: some programs can't communicate with each other. Programs in this village communicate using a fixed system of pipes. Messages a...
''' Created on Dec 2, 2016 @author: venturf2 --- Day 3: Squares With Three Sides --- Now that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up this part of Easter Bunny HQ. This must be a graphic design department; the walls are covered in specifications for tr...
#Напишите выражение (задание на самопроверку). #Дано n-значное целое число N. Определите, входят ли в него цифры 3 и 7. Number = list(str(input("Print any number: "))) print(Number) Search = list(map(int, Number)) print(Search) print(3 in Search and 5 in Search)
#Задача #В первый день спортсмен пробежал х километров, а затем он каждый день увеличивал пробег на 10% от предыдущего #значения. По данному числу у определите номер дня, на который пробег спортсмена составит не менее у километров. #Входные данные #Программа получает на вход действительные числа х и у #Выходные данные ...
#!/usr/bin/env python3 num = int(input("Enter number: ")) num_list = [0, 1, 1] n0 = 0 n1 = 1 n2 = 1 for n in range(2, num): n3 = n2 + n1 num_list.append(n3) n1 = n2 n2 = n3 print(num_list) print(num_list[-1])
# By submitting this assignment, I agree to the following: # By submitting this assignment, I agree to the following: # Aggies do not lie, cheat, or steal, or tolerate those who do� # I have not given or received any unauthorized aid on this assignment� # # Name: Anthony Matl, Luca Maddaleni, Landon Charles, ...
print "Guess the mystery number - it's between 1 and 100!" guess = input("Type in your first guess: ") while guess != number: if guess > number: print "Too high! Guess lower!" else: print "Too low! Guess higher!" guess = input("Type in your guess:") print "Well done. You are right!...
#increase the prices by 20% for i in range(4): priceIncrease = priceOf[i] * 20/100.0 priceOf[i] = priceOf[i] + priceIncrease # display the new prices print print "%15s%15s%20s" %("Item No", "Item", "Item Price") for i in range(4): print "%15d%15s%20.2f" %(i+1,food[i],priceOf[i])
students = [] #function1 def get_students_titlecase(): students_titlecase = [] for student in students: #students_titlecase = student["name"].title() #We removed the above because as we read the file when it has more than one name it only prints one #The reason for that is the above co...
cars = ["BMW", "Honda", "Mercedes", "Daihatsu"] emptylist = [] #We can print the content of said lists print(cars) print(emptylist) #We can print specific items in the list by using the item's index print(cars[2]) print(cars[0]) #We can replace an item in a list by setting its new value using its index. cars[0] =...
#Collect the user's input word urword = input("Please enter a word that is a palindrome:") #Spell the collected word backwards bckword = urword[::-1] #Check if the user's word and the same word spelled backwards are the same if urword == bckword: print("%s spelled backwords also spells %s" %(urword, bckword)) els...
student_names = ['Yves-Martin', "ronald","Sherly", "Wladimir", "Reginald", 'Maxime', "Sandra", "Tamara", "Sylvain", "Fabiola"] for name in student_names: if name == "Maxime": continue print("Found her current man!" + name) #break print("Our friend’s names are "+ name)
# -*- coding: utf-8 -*- """ Created on Wed Aug 29 22:15:33 2018 @author: Urchaug """ #python program to check if the input year is a leap year or not year = int(input("enter a year:")) if (year%4)==0: if (year%100)==0: if (year%400)==0: print("{0} is a leap year".format(year)) ...
# -*- coding: utf-8 -*- """ Created on Thu Mar 29 20:50:58 2018 @author: Urchaug """ MAX=18 MAX=eval(input("please enter a number: ")) print(end=" ") for column in range (1, MAX + 1): print(end= "%2i " % column) print() print(end=" +") for column in range( 1, MAX + 1 ): ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 26 20:37:49 2018 @author: Urchaug """ #list the factors of the integers 1.......MAX MAX=20 n=1 #starts with 1 while n<=MAX: factor = 1 print (end=str(n) + ': ') while factor <= n: if n % factor == 0: print(factor,end= ' ') ...
# -*- coding: utf-8 -*- """ Created on Tue May 1 20:59:24 2018 @author: Urchaug """ # Factorial(n) # computes n! # returns the factorial of n def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) def main(): # try out the factorial function ...
# -*- coding: utf-8 -*- """ Created on Thu Aug 30 14:17:20 2018 @author: Urchaug """ #python program to find the multiplication table(from 1 to 10)c of a number input by the user #take input from the user num = int(input("Display multiplication table of?")) #use for loop to iterate 10 times for i in range(...
# -*- coding: utf-8 -*- """ Created on Fri Mar 30 22:21:58 2018 @author: Urchaug """ num=int(input("display multiplication table of? ")) for i in range(1,11): print(num,"x",i,'=',num*i)
# -*- coding: utf-8 -*- """ Created on Tue Apr 10 12:19:55 2018 @author: Urchaug """ # use some functions and values from the math package from math import sqrt, sin, cos, pi # location of orbiting point is (x,y) # location of fixed point is always (100, 0) # AKA (P_X, P_Y). change these as necessary. p...
# nearest_neighbor.py import numpy as np import sys sys.path.insert(1,"./Trees") from trees import BST from trees import BSTNode from scipy.spatial import KDTree from sklearn import neighbors def metric(x, y): """Return the Euclidean distance between the 1-D arrays 'x' and 'y'. Raises: ValueError: if ...
# image_segmentation.py import numpy as np from scipy import linalg as la from scipy.misc import imread as ir from scipy import sparse as sp from matplotlib import pyplot as plt def laplacian(A): """Compute the Laplacian matrix of the graph G that has adjacency matrix A. Parameters: A ((N,N) ndarray):...
# iPyParallel.py - Intro to Parallel Programming from ipyparallel import Client import numpy as np import time from matplotlib import pyplot as plt def initialize(): """ Write a function that initializes a Client object, creates a Direct View with all available engines, and imports scipy.sparse as spar on...
num = '' while type(num) is str: num = input("Dwse arithmo: ") try : num = float(num) #an einai ari8mos ola kala except ValueError : #ValuError einai to sfalma poy 8a dwsei an pame na kanoyme metatroph px string se dekadiko print("Den edwses ari8mo! - Ksanaprospa8hse!") #typwne...
targetStr=[ "alpha","alloha","allright", "basic","batch", "mark","marval" ] class TrieTree(object): def __init__(self,targets=None): if targets is None: targets = [] self.targets=targets self.tree = {} self.build() self.END="-1" def build(sel...
# -*- coding: utf-8 -*- """ Created on Fri May 17 11:20:36 2019 @author: zding5 """ import matplotlib.pyplot as plt import numpy as np def plotJHistory(J_history, iteration): num_iter = np.arange(1, iteration+1) fig, ax = plt.subplots(figsize = (6,4)) ax.plot(num_iter,J_history,'o-') ax.s...
import time import datetime class Timer: def __init__(self): self.start_time = 0 def start(self): self.start_time = time.time() def stop(self): self.start_time = self.current_time def elapsed(self): self.current_time = time.time() print('time {} elaps...
import random import sys def find_rand_edge(G1): temp = random.randint(1, (num - len(G1))) # Generate a rand among all edges in the 2d array G1 row = 0 for x in [len(y) - 1 for y in G1]: # run down rows of G1 (expect the first entry of each row (thus -1)) to find which vertices the chosen edge connects to temp -...
score = input("Enter Score: ") fscore = float(score) try : if fscore > 1.0 : print("Error") quit() elif fscore < 0 : print("Error") quit() except : print("Error") quit() if fscore >= 0.9 : print("A") elif fscore >= 0.8 : print("B") elif fscore >= 0.7 : ...
x= int(input("Enter the number to find the factorial:")) f=1 for i in range (1, x+1): f=f*i print(f)
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ...
# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: # 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... # Let us list the factors of the first seven triangle numbers: # 1: 1 # 3: 1,3 # 6: 1,2,3...
#Botones Tkinter from Tkinter import * def cambio(): # r g b 0-f 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f ventana.config(bg="#006") boton1.config(bg="#22d") boton1.config(fg="#fff") ventana.iconify() def calcular(): print("El cuadrado de 5 es: " + str(5*5)) ventana = Tk() ventana.geometry("400x300") boton1 = Butto...
nombre = "Jesus" num = 5.4 b = True c = 5 + 4j d = 'a' # type es para mostrar el tipo de dato ''' Este comentario se va a terminar aquí ''' print(type(nombre)) print(type(num)) print(type(b)) print(type(c)) print(type(d)) print(nombre) print(num) print(b) print(c) print(d) input()
# Traditional Decorator pattern: noticeably verbose class WriteLoggingFile1(object): def __init__(self, file, logger): self._file = file self._logger = logger # We need to implement every file method, # and in the truly general case would need # a getter, setter, and deleter for every ...
""" Due to fermat's little theorem, since p is prime, then: x ^ (p - 1) = 1 (mod p) Now by raising the left-hand side to any exponent, we can get multiples of (p - 1) i.e. x ^ (p - 1) = x ^ 2(p - 1) = x ^ 3(p - 1) = 1 (mod p) Therefore for any arbitrary exponent a, we can keep decreasing (p - 1)...
################################################# # Helper functions ################################################# def almostEqual(d1, d2, epsilon=10**-7): # note: use math.isclose() outside 15-112 with Python version 3.5 or later return (abs(d2 - d1) < epsilon) import decimal def roundHalfUp(d):...
from Comparison.Algorithm import Algorithm import networkx """@package Comparison This module manages the graph comparison for the connectomes. """ class SymmetricDifference(Algorithm): """ Class for the the symmetric difference algorithm, it creates a graph composed of the edges present in one graph but not the ...
from collections import deque class Queue : def __init__(self,items = None): if items == None : self.items = deque() else : self.items = deque(items,len(items)) def enQueue(self,i) : self.items.append(i) def deQueue(self) : return self.items.popleft() ...
#Basic Functions import cv2 import numpy as np #read the image img = cv2.imread('resources\doraemon.png') kernel=np.ones((5,5),np.uint8) imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #turn a colored image into gray scale imgBlur = cv2.GaussianBlur(imgGray,(7,7),0) # Blur the image imgCanny = cv2.Canny(im...
# This program exercises bags: # Replace any "<your code>" comments with your own code statement(s) # to accomplish the specified task. # Do not change any other code. # The following files must be in the same folder: # abstractcollection.py # abstractbag.py # arraybag.py # arrays.py # ball.py ...
# Ball class class Ball: # Class variable DEFAULT_RADIUS = 1 # Constructor: def __init__(self, color, radius = DEFAULT_RADIUS): self.color = color; self.radius = radius; # Special methods: def __eq__(self, other): if self is other: return Tr...
#! /usr/bin/env python3 import numpy as np def cost_(y, y_hat): if type(y_hat) != np.ndarray or type(y) != np.ndarray or y.ndim != 1\ or y_hat.ndim != 1 or len(y_hat) != len(y): return None else: return(np.dot((1 / (2 * len(y)))*(y_hat - y) ,(y_hat - y))) if __name__ == "__main__...
#!/usr/bin/python def set_matrix_zero(matrix): """ >>> set_matrix_zero([[1, 0, 1, 1], [1, 1, 0, 1], [1, 1, 1, 1]]) [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 1]] """ n = len(matrix) assert(n >= 1) m = len(matrix[0]) x = set() y = set() for i in xrange(0, n): for j in xrange(...
from libro import Libro from controlador import Controlador con = Controlador() while True: print("---------- COLECCION DE LIBROS ------------") print("El numero de libros registrados es ",con.getNumLibros()) print("1.- Anyadir libros") print("2.- Eliminar libros") print("3.- Listar libros") p...
import string import random as ran def passwordgen(text,maxlength): #length of text will also be 0 as it hold no data yet # will recurise picking new charcter until >maxlength if len(text) < maxlength: randomChar = get_random_char() return passwordgen(text+randomChar,maxlength) else: ...
# Complete the reverseArray function below. def reverseArray(a): # using two pointers left = 0 right = len(a)-1 while left < right: # swap a[left], a[right] = a[right], a[left] left+=1 right-=1 return a
## Example 0 ## print('\n## Example 0 ##\n') # scope = variable life expectancy # the parts of a program where you can access a variable def f(): p = 2 q = 3 print(p+q) def g(): f() print(p) # this won't work, why? # to make it visible to the caller, return it def f2(): p = 2 q = 3 print(p+q) ret...
import turtle turtle.bgcolor("black") turtle.color("green") turtle.speed(50) def square(sidelength): for i in range(4): turtle.forward(sidelength) turtle.right(90) for i in range(60): square(100) turtle.right(5) turtle.exitonclick()
import sys c = float(input('Informe o valor total do consumo: R$')) if c <= 0: print('Valor Inválido!') sys.exit() f = int(input('Informe o total de pessoas: ')) if f <= 0: print('Valor inválido!') sys.exit('Número inválido de pessoas!') p = float(input('Informe o percentual da taxa de serviço:...
word = input("Введіть слово: ") res = ""; for x in word: res += x*2; print(res)
#EXERCISE NO 3.20 lst= ['january','february','march'] for char in lst: print(char[:3])
def avg(): a=eval(input("the marks of student splitted by comma(,): ")) b=eval(input("the marks of student splitted by comma(,): ")) c=eval(input("the marks of student splitted by comma(,): ")) d=eval(input("the marks of student splitted by comma(,): ")) lst=[] lst.append(a) lst.appen...
#!/usr/bin/python3 """ Class Student that defines a student by: (based on 11-student.py) """ class Student: """Class Student that defines a student by: (based on 11-student.py)""" def __init__(self, first_name, last_name, age): """Initializes the data Args: first_name (str): fir...
#!/usr/bin/python3 def divisible_by_2(my_list=[]): return([True if num % 2 == 0 else False for num in my_list])
# -*- coding: utf-8 -*- """ Created on Mon Feb 15 17:03:34 2021 @author: admin """ import json import pandas as pd import requests from datetime import date, timedelta import numpy as np import os import sys def daterange(date1, date2): ''' Parameters ---------- date1 : date.datetime ...
def plot_importance(importance_df, figsize=(8, 8)): """Plot feature importance Parameters ---------- importance_df : pandas dataframe Output dataframe from LOFO/FLOFO get_importance figsize : tuple """ importance_df = importance_df.copy() importance_df["color"] = (importance_df[...
import re print("**********WELCOME TO ROT__**********") print("----Here u can give any shift number to ROT__----") alphabet="abcdefghijklmnopqrstuvwxyz" #al=list(alphabet) out='' shift=int(input("Enter the shift number=")) print("Shift=",shift) empty=[] print("*Select your function: ") print("\t1.ROT13_Enco...
from typing import List class Solution: def checkIfExist(self, arr: List[int]) -> bool: doubleList = [] arrSize = len(arr) zeroCnt = 0 for i in arr: doubleList.append(i * 2) for i in arr: if i == 0: zeroCnt += 1 for j in...
# # @lc app=leetcode.cn id=42 lang=python3 # # [42] 接雨水 # # https://leetcode-cn.com/problems/trapping-rain-water/description/ # # algorithms # Hard (48.39%) # Likes: 840 # Dislikes: 0 # Total Accepted: 51.6K # Total Submissions: 106.6K # Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]' # # 给定 n 个非负整数表示每个宽度为 1 的柱子的高...
tree = {'Adam':[0,930],'Seth':[1,912],'Enosh':[2,905],'Kenan':[3,910],\ 'Mahalalel':[4,895],'Jared':[5,962],'Enoch':[6,365],'Methuselah':[7,969],\ 'Lamech':[8,777],'Noah':[9,0],'Shem':[10,0],'Ham':[10,0],'Japheth':[10,0]} while True: name1,name2=input().split( ) if name1 in tree and name2 in tree:...
import matplotlib.pyplot as plt from matplotlib import style import numpy as np style.use('ggplot') # Riiight we need 1 for the unique case between 2 and 3. freqObject = {1: 0} freqs = [] freqsOfFreqs = [] primes = [] differences = []; def isPrime(n): # Range goes from bottom to one less than top: for i i...
#!/usr/bin/env python def calculate(up_to): print("Calculating up to {}".format(up_to)) total = 0 for i in range(1, up_to): if (i % 3 == 0) or (i % 5 == 0): total += i return total print("Total sum is {}".format(calculate(1000)))
# -*- coding: utf-8 -*- """ The while loop is similar to an if statement: it executes the code inside of it if some condition is true. The difference is that the while loop will continue to execute as long as the condition is true. In other words, instead of executing if something is true, it executes while that thing ...
# -*- coding: utf-8 -*- # An integer is just a number without a decimal part (for instance, -17, 0, and 42 are all integers, but 98.6 is not). # For the purpose of this lesson, we'll also say that a number with a decimal part that is all 0s is also an integer, such as 7.0. # Define a function is_int that takes a number...
def cube(number): return number * number * number def by_three(number): if number % 3 == 0: return cube(number) else: return False print cube(9) print by_three(15) print by_three(7) print def shut_down(s): if s == "yes": return "Shutting down" elif s == "no": retu...
# DNN 구성 # keras23 보다 loss 더 좋게 만들 것 import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.callbacks import EarlyStopping from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler x=np.array([[1,2,3...
import numpy as np x=np.array([1.,2.,3.,4.,5.]) print(np.where(x>=3)) # (array([2,3,4]), dtype=int64) - 특정 값의 위치와 타입을 반환 print(x[np.where(x>=3)]) # [3. 4. 5.] - 특정 값을 반환 print(np.where(x>=3, 3, 0)) # [0 0 3 3 3] - 특정 값을 명시 된 값으로 변환 후 반환 # x 가 3 이상인 경우엔 3, 아닌 경우엔 0으로 변환 후 반환
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, Dense, Flatten, MaxPooling2D # convolution 2D layer model=Sequential() model.add(Conv2D(filters=10, kernel_size=(2,2), strides=1, padding='same', input_shape=(10,10,1))) # padding = 'same' -> Conv2D 를 지나면서 줄어드는 s...
import unittest from General.Self_Assess_Question_Generation.QuestionFormation import QuestionFormation class TestQuestionGeneration(unittest.TestCase): # def test_something(self): # self.assertEqual(True, False) def test_yes_questions(self): questionGeneration = QuestionFormation() ...
import turtle from PIL import Image def goto(x,y): turtle.penup() turtle.goto(x,y) turtle.pendown() def yuan(): turtle.color('#FFFFFF',"#FF9933") goto(0,-200) turtle.begin_fill() turtle.circle(200) turtle.end_fill() def huabian(): goto(0,0) turtle.color('#FF9933') for _ i...
import time class ListNode: def __inti__(self, x): self.val = x self.next = None def addTwoNumbers(L1, L2): node = ListNode() res = node carry = 0 endL1 = False endL2 = False while True: if not endL1: num1 = L1.val try: L1 = ...
#VISUAL DEFINE from visual import * #allows the program to run and create visual actions from visual.graph import * #allows the program to create graphs based on the code from random import random scene = display (title = 'Sistema solar', width = 800, height = 800, \ range = (25000,25000,2500...
from itertools import combinations def solution(numbers): answer = set() #set으로 같은 요소가 존재하는 경우 배제 가능 for i in list(combinations(numbers,2)): answer.add(sum(i)) answer = sorted(answer) return answer # from itertools import combinations # def solution(numbers): # answer = s...
import string def solution(s): answer = '' index = 0 for i in s: if i.isalpha(): index += 1 if index % 2 != 0: answer += i.upper() else : answer += i.lower() else: answer+= ' ' index = 0 c...
import turtle turtle.shape('turtle') def circle(flag): if flag == 'l': for i in range(360): turtle.forward(1) turtle.left(1) else: for i in range(360): turtle.forward(1) turtle.right(1) for i in range(3): circle('l') circle('r') tu...
import turtle turtle.shape('turtle') def spider(n): for i in range(n): turtle.right(360 / n) turtle.forward(90) turtle.stamp() turtle.left(180) turtle.forward(90) turtle.right(180) spider(12)
# https://leetcode.com/problems/can-place-flowers/ # Step1: Solved 2019-1-8 # Step2: 在速度上做提升 class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ # 3空插1个,开头和结尾是2空 i,count = 0, 0 ...
def reorder(arr): i = -1 for j in range(len(arr)): print(i,j,arr) if arr[j]%2 == 0: arr[i+1], arr[j] = arr[j], arr[i+1] i += 1 arr = [1,2,3,4,5,6,7,8,9] reorder( arr ) print(arr)
from typing import List class Heap: """This is a max heap""" def __init__(self, a: List[int]): self.a = a self.build_max_heap() def max_heapify(self, i: int): left = (i+1)*2 - 1 right = left + 1 if left < self.size and self.a[i] < self.a[left]: largest = left else: largest = i if right < self...
import math class Graph: no_of_vertices: int nodes = list() def __init__(self, no_of_vertices: int): self.no_of_vertices = no_of_vertices for x in range(no_of_vertices): self.nodes.append({"adj_nodes": list(), "color": "white", "d": math.inf, "p": math.nan}) def add_edge(...
# https://www.hackerrank.com/contests/w3/challenges/half def dlog(n): result = 0 while n > 1: n = n / 2 result += 1 return result def solve(n): # If number of stacks is odd, xor is always 1. # Let's remove the single stone from first stack and call it done. if n & 1 == 1: ...
"""Program that outputs one of at least four random, good fortunes.""" __author__ = "730439074" # The randint function is imported from the random library so that # you are able to generate integers at random. # # Documentation: https://docs.python.org/3/library/random.html#random.randint # # For example, consider t...
""" Problem: Given a 32-bit signed integer, reverse digits of an integer. Test Case 1: Input: 123 Output: 321 Test Case 2: Input: -123 Output: -321 Test Case 3: Input: 120 Output: 21 """ from stack import LinkedStack def reverse(nums): #declare your stack Stack = LinkedStack() #ini...
# A permutation is an ordered arrangement of objects. # For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. # If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. # The lexicographic permutations of 0, 1 and 2 are: # 012 021 102 120 201 ...
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. # For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. # # A number n is called deficient if the sum of its proper divisors is less than n and i...
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. import time def get_sum_of_multiple(multiple: int, below_number: int): if multiple >= below_number: return 0 ...
# The number 3797 has an interesting property. # Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. # Similarly we can work from right to left: 3797, 379, 37, and 3. # # Find the sum of the only 11 primes that are both truncatable f...
# n! means n × (n − 1) × ... × 3 × 2 × 1 # # For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800 # The sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. # # Find the sum of the digits in the number 100! def get_factorial(num): if num == 1: return num return num * get_factorial(...
# Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). # If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. # # For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 1...