text stringlengths 37 1.41M |
|---|
#
#
## Tom
#
#
## Use the linked list class
from linkedlist import *
MyList = linkedList()
MyList.insert(Node("Lars"))
MyList.insert(Node("Alex"))
print(MyList.getSize())
MyList.insert(Node("Tom"))
MyList.insert(Node("Mike"))
print(MyList.getSize())
# Use the print method
MyList.printLL()
|
import sys
args=sys.argv[1]
count=0
file=open("iphorizontal.txt","r")
f=file.readline()
file_list=f.split(" ")
print("list of IP's is:",file_list)
for line in file_list:
if(args==line):
#print("ip found in list:",line)
count=count+1;
if(count>0):
print("Ip found")
print("number of times ip found is:",count)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
# TODO(mzc) 将 level = 2 对应 book set URL 记录 到 csv 中
def read_record(cls_id=None, clsname=None, baseUrl=None, max_page_num=None):
with open('./level2url.csv', 'rb+') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
... |
# Command-line program that takes a file containing a maze representation
# and finds the shortest path from the starting point to the endpoint,
# if it exists
class Node:
def __init__(self, state, parent, action):
self.state = state
self.parent = parent
self.action = action
class StackFr... |
def replace_number(number, value, replace_by):
if number == 0:
return 0
digit = number % 10
if digit == value:
digit = replace_by
return digit + 10 * replace_number(number/10, value, replace_by)
print 12120234212, replace_number(12120234212, 2, 5)
print 12129294292, replace_number(12129294292, 9, 3)
|
# Return index, value and a string if value found else return -1
def binary_search(alist, value, left, right):
if right >= left:
mid = left + (right - left) / 2
if alist[mid] == value:
return mid, alist[mid], "found"
if value < alist[mid]:
right = mid -1
if value > alist[mid]:
left = mid + 1
ret... |
class Queue(object):
def __init__(self):
self.data = []
super(Queue, self).__init__()
def enqueue(self, value):
self.data.append(value)
return self.data
def dequeue(self):
if self.data:
return self.data.pop()
return None
def is_empty(self):
if not len(self.data):
return True
return False
... |
num1= float(input("Enter first number:"))
operator= input("Enter operator:")
num2= float(input("Enter second number:"))
if operator=="+":
print(num1+num2)
elif operator=="-":
print(num1-num2)
elif operator=="*":
print(num1*num2)
elif operator=="/":
print(num1/num2)
|
tries=0
secret_word="giraffe"
guess=0
while guess!=secret_word:
guess=input("Choose and animal in all lowercase letters:")
tries=tries+1
if tries==1:
print("The animal is yellow")
if tries==2:
print("The animal is yellow and has spots")
if tries==3:
print("The ani... |
matrix = [[int(num) for num in input().split(", ")] for _ in range(int(input()))]
first_diagonal = [matrix[n][n] for n in range(len(matrix))]
second_diagonal = [matrix[n][len(matrix) - 1 - n] for n in range(len(matrix))]
print(f"First diagonal: {', '.join([str(x) for x in first_diagonal])}. Sum: {sum(first_diagonal)}"... |
from collections import deque
commands = deque()
cars = deque()
passed_cars = 0
green_time = int(input())
window_time = int(input())
crash_flag = False
def crash(car, hit):
global crash_flag
print("A crash happened!")
print(f"{car} was hit at {hit}.")
crash_flag = True
def move_cars(time):
globa... |
def first_triangle(size):
for row in range(1, size + 2):
nums = [x for x in range(1, row)]
if nums:
print(" ".join(map(str, nums)))
def second_triangle(size):
for row in range(size, 0, -1):
nums = [x for x in range(1, row)]
if nums:
print(" ".join(map(st... |
lists = list(reversed([[n for n in peace.split()] for peace in input().split("|")]))
flatten_list = [el for sublist in lists for el in sublist]
print(*flatten_list, sep=" ")
|
def num_of_player(turn):
if turn % 2:
return 1
return 2
def get_turn(turn, free_r_in_c):
player = num_of_player(turn)
while True:
print(f"Player {player}, please choose a column.")
number_of_column = input()
if number_of_column.isnumeric():
number_of_column ... |
import os
def create(f_name):
with open(f_name, "w") as file:
pass
def add(f_name, content):
with open(f_name, 'a') as file:
file.write(f"{content}\n")
def replace(f_name, old_str, new_str):
if os.path.exists(f_name):
with open(f_name, 'r') as file:
text = file.read... |
# numbers_list = [int(x) for x in input().split(', ')]
# result = 1
#
# for number in numbers_list:
# if number <= 5:
# result *= number
# elif number > 5:
# result /= number
#
# print(result)
from errors import ValueCannotBeNegative
for _ in range(5):
num = int(input())
if num < 0:
... |
from checks import num_of_player
def push_mark(i, j, num, game_board):
game_board[i][j] = num
def get_turn(turn, free_r_in_c, rows):
player = num_of_player(turn)
while True:
print(f"Player {player}, please choose a column.")
number_of_column = input()
if number_of_column.isnumeri... |
# def entry_list(n):
# lines = []
# for _ in range(n):
# lines.append(input())
# return lines
#
#
# count = int(input())
# names = entry_list(count)
#
# unique_names = set(names)
# for n in unique_names:
# print(n)
n = int(input())
names = set()
for _ in range(n):
names.add(input())
for n i... |
nums = [int(n) for n in input().split(', ')]
result = {'Positive:': [el for el in nums if el >= 0], 'Negative:': [el for el in nums if el < 0], 'Even:': [el for el in nums if el % 2 == 0], 'Odd:': [el for el in nums if el % 2 != 0]}
for k, v in result.items():
n = ", ".join([str(x) for x in v])
print(f"{k} {n}"... |
contacts = {}
command = input()
while not command.isnumeric():
name, phone = command.split("-")
contacts[name] = phone
command = input()
for _ in range(int(command)):
n = input()
if n not in contacts:
print(f"Contact {n} does not exist.")
else:
print(f"{n} -> {contacts[n]}")
|
# define list
lst = [7, 8, 9, 2, 3, 1, 4, 10, 5, 6]
# sort list in ascending order without modify the list
l1 = sorted(lst)
# print sorted list in ascending order
print(l1)
# sort in descending order without modify the list
l1.reverse()
# print list
print(l1)
# print the even numbers in a ... |
import random
def guessNumber():
attempts = 1
player = input(f"Let's play Number Guessing Game! \nWhat's your name? ")
print(f"Hello {player}! Let the fun begin! Just keep it in mind, you have 5 chances only!")
number = int(input("Guess A Number between 1 - 10!: "))
randomNumber = random.randint(1, 10)
if ... |
from fractions import Fraction
import math
class Calculator:
#odd se usa como fracc,pero no es igual,tener cuidado
def oddToProb(self,odd):
num,den=odd
return float(num)/(num+den)
def probToOdd(self,prob):
if prob==1:
return(1,0)
fracc=Fraction(prob)
haps=fracc.numerator
nothaps=fracc.denominator-fra... |
# from math import gcd
# Usage:
# ans = gcd(100, 54)
# Euclid's algorithm
def gcd(a, b):
tmp = 0
while b > 0:
tmp = a
a = b
b = tmp % b
return a
|
import math
def prime_factors(n):
factors = []
while n % 2 == 0:
factors.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
factors.append(i)
n = n // i
if n > 2:
factors.append(n)
return factors
# Time Compl... |
from math import sqrt
def divisors(number: int) -> List[int]:
solutions = []
number = int(number)
for i in range(1, int(sqrt(number)) + 1):
if number % i == 0:
if number // i == i:
solutions.append(i)
else:
solutions.append(i)
s... |
char = str(input("please input a word:"))
vowels = "aeiou"
found = False
vowel = 0
cons = 0
for letter in char:
for vow in vowels:
if letter == vow:
found = True
break
if found == True:
vowel += 1
else: cons += 1
found = False
print("Your wor... |
roman = str(input("Plese input a simplified roman numeral number:"))
numeral = "MDCLXVI"
total = 0
for letter in roman:
print(letter)
if letter == "M":
total += 1000
elif letter == "D":
total += 500
elif letter == "C":
total += 100
elif letter == "L":
total += 50
... |
weight = int(input("Please in put your weight in kilograms:"))
height = float(input("Now please input you height in meters:"))
bmi = weight/height**2
print("Your Body Mass Index is:", bmi)
|
phrase = str(input("Please type out a phase that has an odd amount of characters, spaces count too."))
print("This is the middle chracter:", phrase[len(phrase)//2:len(phrase)//2+1])
print("This is the first half:", phrase[:len(phrase)//2])
print("This is the latter half:", phrase[len(phrase)//2+1:])
|
import datetime
year = 2018
month = 2
day = 10
x = datetime.date(year,month,day)
print("This is today's date:", x)
|
# count the no. of duplicates word and print the count.
dict={}
#loop for taking the input words.
for i in range(int(input())):
#If input not in the dictionary, then add it
#else increment the counter
key = input()
if not key in dict.keys(): #keys() returns keys used in the dictionary.
dict.upda... |
#here compute the minimum price from given list of items
#here you have to select K items and l[J] must be purchased
#return the minimum price to purchase K items given l[J] must be included.
price=0
N,K,J=[int(i) for i in input().split()]
l = [int(i) for i in input().split()][:N]
price=price+l[J-1]
l.remove(l[J-1]
... |
number=int(input("Enter a number N: "))
for x in range(1,6):
print(number*x)
|
n=input("Enter a number to find factorial: ")
r=1
if n>0:
for x in range(1,n+1):
r=r*x
print (r)
else:
print ("Enter a positive number")
|
print("hello")
a=int(input("enter the value"))
b = int (input("enter the second value"))
c=a+b
print("the vale is ",c)
print("welcome")
#hello |
''' Assumptions made : All laptops have Manufacturer name .
Gaming are expensive than'''
class Laptop(object):
def __init__(self,name):
self.name = name
class Gaminglaptop(Laptop):
def BuyLaptop(self, amount):
if amount < 0:
return "invalid amount"
if ... |
"""
helper methods/globals for pgn_writer and pgn_reader
"""
#rows are 1-8
#assumed 8x8 2d array
#flipped means display w/ black pieces on bottom
COL_HEADS = {chr(i+97): i for i in range(8)} #ltrs a-h
def display(board, flipped=False):
if flipped:
board = board[::-1]
left_margin = " "*3
output = "\... |
x = int(input("enter a number"))
if x%2 ==0 :
print("x is even")
else:
print("x is odd")
|
#Copy the contents from http://arcade.academy/examples/move_keyboard.html#move-keyboard and see if you can figure out what is going on. Add comments to any uncommented lines
"""
This simple animation example shows how to move an item with the keyboard.
If Python and Arcade are installed, this example can be run from t... |
# Uses python3
import sys
def fibonacci_partial_sum_naive(n):
if n <= 2:
return n
#The pisano period of modulo by 10 is 60
num = n%60
if num == 0:
sum = 0
else:
sum = 1
div = int(n/60)
ar = [0,1]
for i in range (2,num+1):
ar.append((ar[i-1]+ar[i-2])%10)
sum = sum + ar[i]
return sum%10
from... |
# Uses python3
def calc_fib(n):
ar = [0,1]
for i in range (2,n+1):
ar.append(ar[i-1]+ar[i-2])
return ar[n]
n = int(input())
print(calc_fib(n))
|
"""
Problem Statement:
Design the class structure for a keyword-based document search engine.
Requirements
- A document consists of an integer ID, a title, and a body.
- A keyword search consists of a short set of tokens (<= ~10) and should return
the documents which contain the highest number of occurrences
of th... |
#
# @lc app=leetcode id=23 lang=python3
#
# [23] Merge k Sorted Lists
#
# https://leetcode.com/problems/merge-k-sorted-lists/description/
#
# algorithms
# Hard (33.24%)
# Total Accepted: 356.4K
# Total Submissions: 1.1M
# Testcase Example: '[[1,4,5],[1,3,4],[2,6]]'
#
# Merge k sorted linked lists and return it as o... |
#
# @lc app=leetcode id=50 lang=python3
#
# [50] Pow(x, n)
#
# https://leetcode.com/problems/powx-n/description/
#
# algorithms
# Medium (27.58%)
# Total Accepted: 293.7K
# Total Submissions: 1.1M
# Testcase Example: '2.00000\n10'
#
# Implement pow(x, n), which calculates x raised to the power n (x^n).
#
# Example... |
#
# @lc app=leetcode id=1006 lang=python3
#
# [1006] Clumsy Factorial
#
# https://leetcode.com/problems/clumsy-factorial/description/
#
# algorithms
# Medium (55.22%)
# Total Accepted: 4.8K
# Total Submissions: 8.6K
# Testcase Example: '4'
#
# Normally, the factorial of a positive integer n is the product of all
# ... |
#
# @lc app=leetcode id=61 lang=python3
#
# [61] Rotate List
#
# https://leetcode.com/problems/rotate-list/description/
#
# algorithms
# Medium (26.55%)
# Total Accepted: 179.7K
# Total Submissions: 676K
# Testcase Example: '[1,2,3,4,5]\n2'
#
# Given a linked list, rotate the list to the right by k places, where k ... |
import traceback
from datetime import datetime
class Player():
def __init__(self, data):
"""Takes a dict converted from the JSON response by the API and wraps
the player data within an object.
:param data: The player data from the API's response.
:type data: dict
"""
... |
class Three_Vecter:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __add__(self, n):
r = Three_Vecter()
r.x = self.x + n.x
r.y = self.y + n.y
r.z = self.z + n.z
return r
def __sub__(self, n):
r = Three_Vecter(... |
import random
class Card:
"""The responisibility of this class:
--draw the card
--validate the user's guess
--determine if correct
--put a score to the round
Attributes:
--last card: interger of last card drawn
--current card: interger of current card drawn
--current ... |
a = 2
b = 3
print(a * b)
print(a ** b)
print(a // b)
print(a / b)
print(a - b)
print(a + b)
|
def triangleArea():
height = int(input("Enter triangle height : "))
base = int(input("Enter triangle base : "))
area = (height * base) / 2
print("Area of triangle is {}". format(area))
triangleArea() |
def strReverse():
fname = input("Enter your first name : ")
lname = input("Enter your last name : ")
rev_fname = fname[::-1]
rev_lname = lname[::-1]
print(rev_fname+" "+rev_lname)
strReverse() |
import sqlite3 as lite
class DatabaseManage(object):
def __init__(self):
global con
try:
con = lite.connect("course.db")
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS course(Id INTEGER PRIMARY KEY AUTOINCREMENT, name TE... |
import re
string = "Hello my name is gaurav sanas, I am 27 years old"
match = re.search("27", string)
if match:
print("match found at position : ", match.start())
else:
print("not found")
# case sensitive if we used small h it will not match
# ^ start with
match2 = re.search("^Hello", string)
if match2:
... |
from datetime import date, time, datetime
from math import floor
DAYS_PER_YEAR = 365
class Decalander:
MONTHS_PER_YEAR = 10
DAYS_PER_MONTH = floor(DAYS_PER_YEAR / MONTHS_PER_YEAR)
def __init__(self, year: int, ordinal: int):
self.year = year
self.ordinal = ordinal
def __str__(self... |
# Python program to find largest number in a list
# List of numbers
list = [13, 10, 25, 31, 56, 80, 95, 110, 250, -2, -7]
# Sorting the list
list.sort()
# Printing numbers in the list
print("The Numbers from the list is: ", list)
# Printing the first largest number in the list
print("The first largest number is:", ... |
import helper
import authorization
import alexa_device
__author__ = "NJC"
__license__ = "MIT"
__version__ = "0.2"
def user_input_loop(alexa_device):
""" This thread initializes a voice recognition event based on user input. This function uses command line
input for interacting with the use... |
a = [3, 4, 5]
b = a
# assign the variable "a" to a new list without changing "b"
a = [i + 3 for i in a]
b = a[:] # even better way to copy a list
print (a)
print(b)
|
# Elaborar um programa que apresente o valor da conversão em dólar lido em real.
real = float(input('Quantos reais deseja converter? '))
price = float(input('Qual o valor da cotação do dolar? '))
print(f'R${real} convertido em dolares é igual a R${real / price}')
|
"""
Elaboar um programa que faça a leitura de 4 valores inteiros. Ao final, apresentar o resultado do produto do
primeiro com o terceiro e a soma do segundo com o quarto
"""
a = int(input('Digite o primeiro valor: '))
b = int(input('Digite o segundo valor: '))
c = int(input('Digite o terceiro valor: '))
d = int(inp... |
"""
Ler uma temperatura em Fahrenheit e apresentá-la convertida em Celsius.
C = (F - 32) * (5 / 9)
"""
F = float(input('Entre com uma temperatura em Fahrenheit: '))
C = (F - 32) * (5 / 9)
print('%s graus Fahrenheit são %.2f graus Celsius' % (F, C))
|
from random import * # So that we can have random numbers.
def main():
mum = "Eileen"
dad = "Sydney"
wife = "Laura"
place = "Sydney"
print(id(mum))
print("Hi, Mom")
print(id(dad))
print(id(place))
main()
# Note that the ids of dad and place are identical.
# This is an example of... |
class Queue:
def __init__(self):
self.items = []
def enqueue(self, value):
self.items.insert(0, value)
def deq(self):
return self.items.pop()
def isEmpty(self):
return (len(self.items) == 0)
def size(self):
return (len(self.items))
if __name__ == '__main_... |
def gcd(m,n):
while m %n != 0 :
oldm = m
oldn = n
m = oldn
n = oldm%oldn
return n
m = int(input("Enter 1st int: "))
n = int(input("Enter 2nd int: "))
print(gcd(m,n))
|
from math import log10
from tkinter import IntVar, Spinbox
class SDTShowSpinbox(Spinbox):
def __init__(self, master=None, sdt=None, show_cnt=1, command=None):
self.sdt = sdt
# Initialize Variables
self.curr_show = IntVar()
self.curr_show.set(1)
self.show_cnt = show_cnt
... |
vegetables = [
{"name": "eggplant"},
{"name": "tomato"},
{"name": "corn"},
]
print(vegetables)
import csv
with open('veggies.csv', 'w') as f:
writer= csv.writer(f)
writer.writerow(['name','length'])
for veggie in vegetables:
#i want the name of the veg
vegetable_name = veggie['name']
veggie_name_leng... |
#加 +
print(1+1)
# 减 -
print(1-1)
#乘 *
print(2*2)
#除 /
print(9/3)
#取余%
print(2%3)
a = 10
b = 30
print(a+b-a)
# 字符串 列表 元组
#字符串
s = '1111'
d = '2222'
print(s+d )
# 列表
l = [1,2,3,4]
k = [5,6,7,8]
print(l+k)
# 元组
t = (1,2,3,4,)
y = (3,5,8,)
print(t+y)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__title__ = ''
#__author__ = 'tiangy'
#__mtime__ = '2019/9/5'
'''
i =1
while(判断条件):
循环体
i =i+1
'''
for i in range(1,101,1):
print (i)
i = 1
while(i < 101):
print (i)
i = i +1
# for 循环
'''
range(0,10,1) = [1,2,3,4,5,6,7,8,9]
range(0,10,2) = [1,3,... |
import sys
'''
This module is print function package to decoration for string
'''
class ZeroIndexError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class OverIndexError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(se... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 00:42:38 2020
@author: RogelioTESI
"""
class Reversa:
"""Iterador para recorrer una secuencia de atrás para adelante."""
def __init__(self,datos):
self.datos = datos
self.indice = len(datos)
def __iter__(self):
return self
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 01:03:21 2020
Multiplicacion
@author: RogelioTESI
"""
a = input("Ingresa un numero: ")
b = input("Ingresa otro numero: ")
a = int(a)
b = int(b)
c = a*b
print("El resultado es: ", c)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 7 00:25:32 2018
@author: Liv d'Aliberti
"""
#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#Find the sum of all the primes below two million.
#In solving this problem, I learned about this thing called
#the Sieve of Eratosthenes which is ... |
""" Определим слова в хэштеге.
Дана строка, начинается с # и содержит набор слов соединенных в одну строку без пробелов.
Срока описана в стиле camelCase, то есть первое слово начинается с прописной буквы, а каждое следующее с заглавной.
Например: #приветКакДела, #меняЗовутЕгорМнеМногоЛет и тд.
Необходимо посчитать ... |
""" Реализовать функцию map, принимающей два аргумента:
список и произвольную арифметическую функцию.
Функция map должна возвращать новый список,
элементы которого являются результатом функции func.
Пусть будет функция, возводящая число в куб (в 3-ю степень числа)
"""
def func3s(x):
return x**3
def map(x: lis... |
""" Дан файл с расписанием занятий на неделю.
Помимо названия предмета в нем также указано лекция это,
или практическое занятие, или лабораторная работа.
В одной строке может быть указаны только один предмет с информацией о нем.
Посчитать, сколько за неделю проходит практических занятий,
лекций и лабораторных рабо... |
import os
def manualInput(question):
answer = input(question + "(y/n): ").lower().strip()
print("")
while not(answer == "y" or answer == "yes" or \
answer == "n" or answer == "no"):
print("Введите y или n")
answer = input(question + "(y/n):").lower().strip()
print("")
if ans... |
#Backtracking-2
#Problem1 : https://leetcode.com/problems/subsets/
#All test cases passed on Leetcode
#Time Complexity: O(2^n) -Exponential
#Space Complexity: O(n) for Backtracking
class Solution:
def __init__(self):
self.result=[]
#Approach used :backtracking
#Update the same list we call ba... |
import numpy as np
import matplotlib.pyplot as plt
# calculate Euclidean distance
def euclidean_distance(x1, x2):
scale_x1 = x1 * 100
scale_x2 = x2 * 100
return np.sqrt(np.sum(np.power(scale_x1 - scale_x2, 2)))
# Initial centroids with random samples
def init_centroids(data, k):
num_samples, dim = d... |
#************************** CS421: Assignment 7 **************
#
# Most of the implementation for the cryptoquote algorithm is done
#
# You only need to implement section 5.
#
# Lines from 28 and 35 reflect different test cases.
# Start with simple test cases and progress to the bigger test cases
#
# Use... |
from turtle import *
speed(-1)
def draw_square(l,colour):
for i in range(4):
color(str(colour))
forward(l)
left(90)
for i in range(30):
draw_square(i*5,"red")
left(17)
penup()
forward(i * 2)
pendown()
|
def numero_to_letras(numero):
indicador = [("", ""), ("MIL", "MIL"), ("MILLON", "MILLONES"), ("MIL", "MIL"), ("BILLON", "BILLONES")]
entero = int(numero)
decimal = int(round((numero - entero) * 100))
# print 'decimal : ',decimal
contador = 0
numero_letras = ""
while entero > 0:
... |
# Task_1. Написати скрипт, який з двох введених чисел визначить, яке з них більше, а яке менше.
a = int(input("Введіть число "))
b = int(input("Введіть число "))
if a == b:
print("Числа {0} і {1} рівні".format(a, b))
elif a <= b:
мін_зн, макс_зн = a, b
print("Число {0} - мінімальне число , а число {1} - ... |
#Task
#Given an integer, , perform the following conditional actions:
#If is odd, print Weird
#If is even and in the inclusive range of to , print Not Weird
#If is even and in the inclusive range of to , print Weird
#If is even and greater than , print Not Weird
#Complete the stub code provided in your ... |
#!/usr/bin/env python3
#sheinkhant
def prime_checker(number):
is_prime = True
for i in range(2, number - 1):
if number % i == 0:
is_prime = False
if is_prime:
print("It's a prime number.")
else:
print("It's not a prime number.")
n = int(input("Check this number: "))
prime_checker(number=n) |
#!/usr/bin/env python3
#sheinkhant
for i in range(1,101):
if i % 3 == 0 and i % 5 == 0:
print("FuzzBuzz")
elif i % 3 == 0:
print("Fuzz")
elif i % 5 == 0:
print("Buzz")
else:
print(i) |
def move(_1,_2):
_2.append(_1.pop(-1))
print(a,b,c)
def toh(disks,source,dest,aux):
if disks==1:
move(source,dest)
else:
toh(disks-1,source,aux,dest)
move(source,dest)
toh(disks-1,aux,dest,source)
# def tower(disks,source,dest,aux):
# if disks==1:
# ... |
from graph import Graph,Edge
from dijkstra import dijkstra_target
g=Graph([1,2,3,4,5,6,7,8,9,10]) # Create graph with 10 houses
g.add_edge(Edge(1,2,cost=3))
g.add_edge(Edge(2,3,cost=4))
g.add_edge(Edge(3,4,cost=2))
g.add_edge(Edge(4,5,cost=3))
g.add_edge(Edge(5,6,cost=5))
g.add_edge(Edge(6,7,cost=4))
g.add_e... |
def quick_sort(l):
if len(l) in [0, 1]:
return l
p = l[0]
smaller = []
larger = []
for e in l[1:]:
if e < p:
smaller.append(e)
else:
larger.append(e)
return quicksort(smaller) + [p] + quicksort(larger)
def count_quick_sort(l):
... |
class Scientist():
def __init__(self, born, died):
self.born = born
self.died = died
def simultaneously_alive(A, B):
if A.died <= B.born or B.died <= A.born:
return False
return True
def max_alive(S):
most_living = 0
currently_living = []
scientists = sorte... |
import os
from abc import ABCMeta
from abc import abstractmethod
class base_data(object):
def __init__(self, is_training):
__metaclass__=ABCMeta
print("base_data init")
self._is_training = is_training
@abstractmethod
def __call__(self, *args, **kwargs):
print("base_data ca... |
# coding: utf-8
"""
Reverse Complement
Autor:
Colaborador:
Guido Luz Percú (guidopercu@gmail.com)
Tipo:
bioinformatics
Descrição:
Converte uma sequência de DNA em seu complemento, isto é, inverte a string e troca A por T, T por A, C por G e G por C.
Complexidade:
?
Dificuldade:
facil
Licenca:
MI... |
# -*- coding: utf-8 -*-
"""
Algoritmo de Aho-Corasick.
Autor:
Alfred Aho and Margaret Corasick (1975)
Colaborador:
Pedro Arthur Duarte (JEdi)
pedroarthur.jedi@gmail.com
Tipo:
multi pattern string matching
finite automate-based
Descrição:
Dado um conjunto de padrões, esse algoritmo constrói uma máquina de est... |
# -*- encoding: utf-8 -*-
"""
Cálculo da raíz quadrada através do método de Newton-Raphson
Autor:
Isaac Newton e Joseph Raphson
Colaborador:
Alysson Oliveira (lssn.oliveira@gmail.com)
Tipo:
math
Descrição:
Método interativo para estimar as raízes de funções e pode ser aplicado
a para o cálculo de r... |
# -*- encoding: utf-8 -*-
"""
Binary Heap
Autor:
M. D. ATKINSON, J. R. SACK, N. SANTORO, and T. STROTHOTT
Colaborador:
Juan Lopes (me@juanlopes.net)
Tipo:
data-structures
Descrição:
Implementação de priority queue usando uma binary min-heap.
Complexidade:
Inserção: O(log n)
Remoção: O(lo... |
# -*- coding: utf-8 -*-
"""
Algoritmo de Bellman-Ford.
Autor:
Richard Bellman & Lester R. Ford Jr. (1958)
Colaborador:
Pedro Arthur Duarte (JEdi)
pedroarthur.jedi@gmail.com
Tipo:
graph
shortest path on directed graphs with negative weighted edges
Descrição:
O algoritmo de Bellman-Ford determina o caminho mai... |
# -*- encoding: utf-8 -*-
"""
* Sequência de Fibonacci
*
* Autor:
* Felipe Djinn <felipe@felipedjinn.com.br>
* Colaborador:
* Bruno Lara Tavares <bruno.exz@gmail.com>
* Dilan Nery <dnerylopes@gmail.com>
* Tipo:
* math
* Descrição:
* Na matemática, os Números de Fibonacci são uma sequência definida ... |
# encoding: utf-8
"""
Permutation
Autor:
Fabian Stedma
Colaborador:
Bruno Gabriel dos Santos (bruno.gsantos89@gmail.com)
Tipo:
math
Descrição:
Calcula o número de combinações distintas que são possíveis de serem formadas por um array numérico.
Complexidade:
O(n!)
Dificuldade:
medio
Referência... |
# coding: utf-8
'''
Array Sum
Autor:
?
Colaborador:
Dayvid Victor (victor.dvro@gmail.com)
Descricao:
Esse programa recebe como parametro uma lista
e retorna a soma dos elementos desta lista.
Complexidade:
O(n)
Dificuldade:
facil
Licenca:
GPL
'''
def arraysum(l, key = lambda a, b: a + b):
s... |
from typing import List
from unittest import TestCase
class TestFilterOddNumbers(TestCase):
""" This test case filters odd numbers from a given sequence """
def test_with_basic_algorithm(self) -> None:
""" Test checks if odd numbers are filtered with basic algorithm """
odds: List[...] = lis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.