text stringlengths 37 1.41M |
|---|
def finding_diff_bw_two_sets(*args):
a,b=args
print(f"finding difference a with b: {a.difference(b)}")
print(f"finding difference b with a: {b.difference(a)}")
if __name__ == "__main__":
a,b = {1,2,3,4,5},{2,3,5,7,8}
finding_diff_bw_two_sets(a,b)
c,d = {'a',True,(1,2)},{'b',False,True,(1,2)}
... |
from webtask import website
def webdata(url):
# sending url to website to create file with that website html code
website(url)
# filename from url dynamically
filename = url.split(".")[1]+".html"
# reading data from file
with open(filename,'r') as filedata:
# readline return data into li... |
"""7. Write a program to find the sum of squares of only the even numbers in the given list. (Hint: Use the methods filter, map, reduce.)
Example:
Input:
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
Sum of squares of even numbers = 120"""
from functools import reduce
lst = [1,2,3,4,5,6,7,8,9]
res = reduce(lambda a,b: a+... |
import heapq
import sys
list1 = []
inputter = int(input("enter the number of elements to be inserted in list: "))
for i in range(inputter):
inputter1 = int(input("enter elements: "))
list1.append(inputter1)
while(1):
z = int(input("1.push\n 2.pop\n 3.pushpop\n 4.replace\n 5.print\n"))
if z == 1:
... |
#Diceware roller
import random
#choose a number of die
number_of_die = int(input("How many die do you wish to roll?: "))
#chose the number of sides
number_of_sides = int(input("How many sides should the die have?: "))
def dice(n):
print (random.randrange(1,n))
for i in range (0, number_of_die):
dice(numb... |
#Reading and writing to file
my_file = open('data.txt','r')
file_content = my_file.read()
my_file.close()
print(file_content)
username = input('Enter your name: ')
my_file_writing = open('data.txt','w')
my_file_writing.write(username)
my_file_writing.close()
|
import time
from multiprocessing import Process
#When you need processes to run at the same time (not for waiting)
def ask_user():
start = time.time()
user_input = input('Enter your name: ')
greet = f'Hello, {user_input}'
print(greet)
print(f'ask_user, {time.time() - start}')
def complex_calc():
... |
import random
# import random is a simple library that implements the random number generator behavior
# Please read into the variables below the correct numbers. Use try and except to catch error.
# a simple example would be:
# hero_hp = int(input("how many hp does the hero have?"))
while True:
try:
hero... |
lugares_favoritos = {'Davy': ['Caldas Novas', 'Cinema'], 'Duda': ['Volei', 'Safari'], 'Jose': 'Igreja'}
for name, lugar_favorito in lugares_favoritos.items():
print('Os lugares favoritos do ' + name + ' são: {}'.format(lugar_favorito.title()))
|
prompt = 'Quais sabores o senhor(a) deseja: \n'
sabores = ''
while sabores != 'quit':
print(prompt)
sabores = input()
print('O sabor ' + sabores.title() + ' foi adicionado com sucesso!!!\n')
|
from practica3 import *
def seleccionador (argument):
if argument == 1:
while True:
try:
entrada = input('Introduce una matriz de la forma [[1,2],[2,3]]\n')
print(mas_repetido(entrada))
break
except:
print('Error, se deb... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def indexreshape(n, m):
"""
separates n indexes in m equal disjoint parts, trims edges equally
returns tuple ((1_start_idx, 1_end_idx),...,(m_start_idx, m_end_idx))
"""
if n < m:
raise ValueError('m must be lower or equal to n')
delta = (... |
output_list = []
while(True):
input_str = input("please input")
if(input_str=="0:00"):
break
split_list = input_str.split(":")
single_h = float(360/12)*int(split_list[0])
single_m = 360/60*int(split_list[1])
n1 = abs(single_h-single_m)
n2 = 360-single_h+single_m
if(n1>n2):
... |
import tkinter as tk
from tkinter import *
import random
import time
import numpy as np
import keyboard
from pynput.mouse import Listener
import pyautogui
import cv2
#this demo code saves a template which student needs to replicate...
#NOTE: here I am only taking a screenshot ONCE, when the program starts, so if t... |
from cv2 import *
from imutils import *
#resizing the image
img=imread("sample2.jpg")
resizeImg=resize(img, width=200) #resizes the given image
imwrite("resizedimage.jpg", resizeImg) #creates the above image in the folder
imshow("resizedimage.jpg", resizeImg) #displays the mentioned image on the screen when we ru... |
def open_file(file_name):
try:
return open(file_name, "r")
except FileNotFoundError:
return None
def read_matrix(file_object):
matrix = []
for line in file_object:
line = line.strip().split()
matrix.append([int(element) for element in line])
return matrix
def ... |
#This program accepts two integers from user input and compares the to see which one is greater
int_1 = int(input("Enter the first number: "))
int_2 = int(input("Enter the second number: "))
if int_1 > int_2:
print(int_1,"is greater than",int_2)
elif int_2 > int_1:
print(int_2,"is greater than",int_1)
else:
... |
"""
This program allows the user to input a number that represents the length of a list, input that many elements, and then enter one value to
determine if it exists within the list
"""
def populate_list(int_object):
new_list = []
while len(new_list) != int_object:
list_element = input("Enter an elemen... |
def remove_evens(list_object):
for element in reversed(list_object):
if element % 2 == 0:
list_object.remove(element)
return list_object
def remove_evens2(list_object):
new_list = []
for element in list_object:
if element % 2 != 0:
new_list.append(element)
re... |
#This program takes in two numbers from user input and prints all integers between them
lower_int = int(input("Enter the lower number: "))
higher_int = int(input("Enter the higher number: "))
if lower_int >= higher_int:
print("The lower number must be lower than the higher one!")
else:
for i in range(lower_in... |
"""
This program takes two words from user input and checks if they are anagrams of each other
"""
def main_func():
words_list = input("Enter two words seperated with a space: ").split()
word1 = words_list[0]
word2 = words_list[1]
word1_sorted = sort_string(word1)
word2_sorted = sort_string(word2... |
"""
This program reads documents from a file into a list, populates a dictionary with the words from the list of documents as the keys and the set
of document numbers as the value for each word. The program then enables the user to search for specific words and find out in which documents
they occur, as well as enablin... |
def createPrime():
n = 10**6
sieve = [True] * n
for x in range(2, int(n**0.5)+1):
if sieve[x]:
for y in range(2*x,n,x):
sieve[y] = False
return sieve
def eulerfunction(a,b,prime):
n = 1
while True:
if not prime[n**2+a*n+b]:
return a*b, n
... |
import time
def main():
start = time.time()
n = 2**1000
sum = 0
while n > 0:
sum += (n%10)
n = n/10
print sum
print time.time() - start
if __name__ == "__main__":
main()
|
"""Homework 2 for CSE-41273"""
# Adam Vickter
# Function 1
def combine_lists(one, two):
"""Take 2 lists as input and return a new list consisting of the elements
of the first list followed by the elements of the second list."""
combine_lists = one + two
return(combine_lists)
... |
import argparse
import random
base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("mode", help="Either 'encrypt' or 'decrypt' the given fiel")
parser.add_argument("text", help="the input file to be encrypted")
parser.add_argument("algorithm", help="ca... |
class Node(object):
def __init__(self, value):
self.left = None
self.right = None
self.value = value
self.height = 1
def getBalance(self):
leftHeight = self.left.height if self.left else 0
rightHeight = self.right.height if self.right else 0
return leftHe... |
class Node(object):
def __init__(self, value, next = None):
self.value = value
self.next = next
def __str__(self):
if self.next:
return '%s -> %s' % (self.value, self.next)
else:
return str(self.value)
def reverse(head):
if head is None or head.next... |
def expendStr(arr):
alist = ['|', '|']
alist[1:-1] = [item for item in '|'.join(arr)]
return alist
def manacher(arr):
if not arr:
return 0
expendArr = expendStr(arr)
length = len(expendArr)
lps = [0] * length
lps[1] = 1
for i in range(2, len(expendArr)):
lps[i] = max... |
import math
import random
import vector
'''
this program randomly creates vectors, tells you what the vectors are
then shows how simple vector calculations work. The random vectors produced are non integer to ensure the program works for all possible inputs.
It also tests the following
identitie... |
coins = [200,100,50,20,10,5,2,1]
def print_coins(change):
if change == 0: print "Nothing"
else:
for (n, c) in change:
if n != 0: print "{}*{} + ".format(n,c),
total = sum(map(lambda (n, c): n*c, change))
print " = " + str(total)
def make_change(n, usable_coins, coins_used):
if len(usable_co... |
from PIL import Image
userInputImage = input("Choose an image to alter .jpg.")
im = Image.open(userInputImage)
data = list(im.getdata()) #gets the the RGB values of each pixel
def addTuples(tuple):
return tuple[0] + tuple[1] + tuple[2]
red = (140, 35, 24)
blue = (94, 140, 106)
green = (136, 166, 94)
yello... |
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
quit('File does not exist!')
lst = list()
for line in fh:
words = line.rstrip().split()
for word in words:
if word not in lst:
lst.append(word)
lst.sort()
print(lst)
|
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# # define GPIO pins with variables a_pin and b_pin
# a_pin = 18
# b_pin = 23
# create discharge function for reading capacitor data
def discharge(a_pin,b_pin):
GPIO.setup(a_pin, GPIO.IN)
GPIO.setup(b_pin, GPIO.OUT)
GPIO.output(b_pin, False)
... |
import psycopg2 as pg
choice = int(input("Enter Your choice:\n"
"1. Find\n"
"2. insert\n"
"3. delete\n"
"4. Quit\n"))
def Conneciton():
connection = ""
# use postgres
try:
connection = pg.connect(user="postgres",
... |
import collections
dic = dict()
n = int(input())
for i in range(n):
survey = input().split(" ")
dic[survey[0]] = survey[1]
listOfElems = list(dic.values())
# Create a dictionary of elements & their frequency count
dictOfElems = dict(collections.Counter(listOfElems))
# Remove elements from dictionary whose va... |
class Node(object):
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def traverse_pre_order_recursive(root, action=print):
if root:
action(root.data, end=" ")
traverse_pre_order_recursive(root.left, action)
... |
import time
A= [99,55,4,66,28,31,36,52,38,72]
for i in range(len(A)):
min_index = i
for j in range(i+1, len(A)):
if A[min_index] > A[j]:
min_index = j
A[i], A[min_index] = A[min_index], A[i]
print("sorted array")
# t = time.time()
# print("time complexity",t)
for i in range(len(A)):
... |
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
self.prevval = None
class Dlinkedlist:
def __init__(self):
self.headval=None
def push(self, NewVal):
if (self.headval is None):
self.headval = Node... |
from Actividades.Actividad3.Sobre import Sobre
from datetime import date, datetime
class Caja:
# Atributes
__id = -1
__date = date
__time = datetime
__desc = ""
__sobres = list()
# Constructor
def __init__(self, sobres, d):
self.__id = self.__id + 2
self.__date = date.... |
import unittest
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.table = [None for i in range(10)]
self.load = 0
def rebuild(self):
# print("rebuild")
old_table = self.table
self.load = 0
self.table... |
import string
n=input()
alphabets=string.ascii_lowercase[:27]
if n in alphabets: print('Alphabet')
else: print("No")
|
class A:
def truth(self):
return 'All numbers are even'
class B(A):
pass
class C(A):
def truth(self):
return 'Some numbers are even'
class D(B,C):
def truth(self,num):
if num%2 == 0:
return A.truth(self)
else:
return super().truth()
d = D()
d.t... |
import unittest
class Hantu:
def __init__(self,name,legs):
self.name = name
self.legs = legs
class Jin(Hantu):
def __init__(self,name,legs=1,booing='yes'):
Hantu.__init__(self,name,legs)
self.booing = booing
Tomang = Jin('Tomang')
#print(Tomang.name)
#print(Tomang.legs)
#pr... |
def perm(arr):
result = list([[]])
for i in range(len(arr)):
t = list()
for y_lst in result:
for j in arr:
if j not in y_lst:
new_lst = list(y_lst)
new_lst.append(j)
t.append(list(new_lst))
result = t... |
from card_game import *
from setup import *
# Ask for the number of players joining the game
n_players = int(input("How many players will join? "))
# Run the function and save it as players_list
players_list = ask_names(n_players)
# Create a player instances
for p in range(n_players):
players_list[p] = Player(pl... |
def solution(a_list):
m1,m2 = float('inf'), float('inf')
for x in a_list:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2
print solution([1, 2, -8, -2, 0])
|
my_name = 'Zed .A .Shaw'
my_age = 23
my_height = 75
my_weight = 170
my_eyes = 'blue'
my_teeth = 'white'
my_hair = 'black'
print "Let's talk about %s." %my_name
print "He is %s lbs in weight." %my_weight
print "He is %s inches tall. "%my_height
print "He has %s coloured eyes."%my_eyes
print "He has %s teeth."%my_teeth
p... |
#Rohan Rao
import random
import time
name = input("What is your name? ")
print("Good Luck ! ", name)
# Word bank
# Words to guess from
words = ['banana','strawberry','mango','blueberry',
'pineapple','apple','raspberry','blackberry','orange','pear',
'grape','peach','kiwi']
#Chooses randomn word
word = random.choice... |
# Rohan Rao
# Help from Dad
# This is my final project for Game Design
# This game is popular and is known as "Flappy Bird"
# It has 3 difficulties (Easy, Medium, and Hard)
# which changes the scrolling speed to make it harder
# I don't have a leaderboard because
# Flappy Bird doesn't usually have a leaderboard
# This ... |
#Rohan Rao
#This program contains ForLoops Program, Prime Numbers, and the Fibonacci sequence
#Forloops
for line in range(5):
print()
for number in range(5-line,0,-1):
print(number, end =' ')
#Prime Numbers Program
start = 25 #First Value of finding prime number
end = 50 #Last Value of finding p... |
from tkinter import *
root = Tk()
myLabel = Label(root, text = "hello world!")
myLabel.pack()
root.mainloop()
|
from ortools.graph import pywrapgraph
import time
import random
from copy import copy,deepcopy
def main():
print("What kind of assignment problem are you trying to solve?\nEnter:")
problem = int(input("1: Balanced Minimization\n2: Unbalanced Minimization\n3: Balanced Maximization\n4: Unbalanced Maximization"))
if p... |
quieres_sabritas_input = input ( "quieres sabrtias de limon? (si/no): ")
if quieres_sabritas_input == "si":
quieres_sabritas = True
elif quieres_sabritas_input == "no":
quieres_sabritas = False
else:
print("tienes que decir que si on no sucio mortal")
quieres_sabritas = False
tienes_dinero_input = inpu... |
import re
def remove_special_char(text):
text = re.sub('[áàãâ]', 'a', text)
text = re.sub('[óòõô]', 'o', text)
text = re.sub('[éèê]', 'e', text)
text = re.sub('[íì]', 'i', text)
text = re.sub('[úù]', 'u', text)
text = re.sub('ç', 'c', text)
return text
|
class Pizzeria:
def __init__(self, pizzas: dict, num_ingredients: int) -> None:
self.pizzas = pizzas
self.num_ingredients = num_ingredients
self._ingredients_reverse_index()
def __eq__(self, other):
return isinstance(other, Pizzeria) and \
self.pizzas == other.piz... |
string1 = "Cisco Router"
#se puede acceder a los indices de un string, cada caracter representa un indice
#el ultimo caracter de puede acceder con -1
#para leer un string del reves se comineza con -1 y va decrenciendo en negativo
string1[1]
string1[-1]
#para saber el lenght de un caracter usar la funcion len
len(stri... |
'''
Implement a function is_prime(x) that returns True if x is prime, False
otherwise. (1 Point)
>>> is_prime(7)
True
>>> is_prime(15)
False
'''
# ... your code ...
def is_prime(num):
if (num == 1):
return False
isPrime = True
for y in range(2, num - 1):
if (isPrime):
if (num... |
######################################
# Introduction to Python Programming #
# WS 2013/2014 #
# Iterators & Generators #
######################################
'''
Implement an iterator that iterates over a file by paragraph.
By "paragraph" we mean all lines in the file which are no... |
#########################################
# Introduction to Python Programming #
# Exercise Sheet 13 #
# List Comprehensions #
#########################################
# Exercise 2
''' (2 Points) Write function "count" that takes a list of words as argument
and returns a list... |
''' 1. POS-Tagged text (3 Points)
The file "example.xml" containing POS-tagged text, where words are
represented as follows:
<W TYPE="part of speech" ...>word</W>
Write a function that reads the file and ** returns ** a list of word-POS
pairs (see example below).
Example:
read_file("example.xml")
should re... |
'''
Implement a function that recognizes palindromes (2 Points).
>>> is_palindrome("level")
True
>>> is_palindrome("levels")
False
Hints:
string[i] gives you the ith character from left (starting from 0)
string[-i] gives you ith character from right (starting from 1)
# >>> s = "abcd"
# >>> s[0]
a
# >>> s[-1]
d
In... |
#create a dictionary for base64
#iterate through each binary value and sum up each 6 bit to the corresponding base64 value
def hexToBase64(string):
binary = bin(int(string,16)) #convert string -> integer -> binary
print(binary)
base = 6
mask = '111111'
rv = ""
while (binary != 0):
bit =... |
word = input("Give me a word\n")
i = 0
l = len(word)
while i <= l:
print(word[i])
i = i+1
|
mystr = str(input('Enter a string:'))
letter = str(input('What letter do you want to check for?'))
mylist = []
for i in mystr:
mylist.append(i)
if mylist.count(letter)!=0:
print('Yes')
else:
print('No')
|
# Importation du module <<TURTLE>>
import turtle
def se_positionner(o,x,y,z=0):
'''
OBJECTIF : Cette fonction permet de positionner la tortue, sans tracer, à un point de coordonnees(x et y) connus dans le repère
METHODE : utilisation des méthodes "penup()", "goto()" "right()" et "pendown()"
... |
def coder(word, key):
new_word = []
a = ''
alfabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for each_chr in word:
index = (alfabet.index(each_chr) + key) % 26
new_word.append(alfabet[index])
a... |
from q2.l2_distance import l2_distance
from q2.utils import *
import matplotlib.pyplot as plt
import numpy as np
def knn(k, train_data, train_labels, valid_data):
""" Uses the supplied training inputs and labels to make
predictions for validation data using the K-nearest neighbours
algorithm.
Note: ... |
# The super() builtin returns a proxy object
# (temporary object of the superclass) that allows us
# to access methods of the base class. In Python, super()
# has two major use cases: allows us to avoid using
# the base class name explicitly and
# working with Multiple Inheritance
# super is used to call the construc... |
print("Salom. Siz bilan Mad_Lib o'yinini o'ynaymiz.")
print("Izohdagi kerakli turdagi so'zlarni kiriting!\n")
while True:
adj1 = input("adjective: ")
noun1 = input("noun: ")
pl_noun1 = input("plural noun: ")
name = input("woman's name: ")
adj2 = input("adjective again: ")
noun2 = input("noun again: ")
name2 = i... |
#function practice assignment
#1
def factorial(n):
result=[]
import math
result=math.factorial(n)
return result
factorial(5)
#2 - prime number is not divisible by anything
def is_prime(x):
n = 2
if x < n:
return 'Is not a prime number'
else:
while n < x:
... |
'''
functions used to "deal" cards into the players hand
by copying the correct card pictures into a folder (static)
from which the browser loads them
'''
import os, shutil, re
def deal(hand):
# deal an entire hand of white cards, takes a list of card indices
'''
for pic in os.scandir('static'): #clear th... |
a = dict()
a[1] = 1
def calculateCollatzSequenceLength(num):
if (int(num) in a):
return a[int(num)]
if (num%2 ==0):
return 1 + calculateCollatzSequenceLength(num/2)
return 1 + calculateCollatzSequenceLength(3 * num + 1)
maxer = 0
indOfMax = 0
for i in range(2,1000000):
col_length = cal... |
#############################################################################
# Ejemplos extraidos del libro Python 3 Text Processing with NLTK 3 Cookbook.
# Referidos al capitulo 7.
#############################################################################
from nltk.corpus import movie_reviews
from nltk.clas... |
#Password Generator (Weak or strong)
import random
n=input('What type of password do you want? Weak or Strong ',) #User Input
list1=['grapedwine','downsyndrome', 'celestialbodies','goodwills','badnames','loyalbunnies']
#random names for weak password
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRS... |
from abc import ABC, abstractmethod
from model import Model
class ModelExample(Model):
def __init__(self, model_file):
super().__init__(model_file)
self.reset()
relative_path = 'gym_maze/envs/maze_samples/'
self._load_model(relative_path + model_file)
def _load_model(self, ful... |
class PriorityQueue():
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str(i) for i in self.queue])
def is_empty(self):
return len(self.queue) == 0
def push(self, data, cost):
for i in range(len(self.queue)):
if cost <= s... |
class MergeSort:
def mergeSort(self, arr):
if len(arr) > 1:
middle = len(arr) // 2
left = arr[:middle]
right = arr[middle:]
# Sort the first half
self.mergeSort(left)
# Sort the second half
self.mergeSort(right)
... |
def victory():
vararray = ['Hello World!', 'Learning how to program.', 'It is always fun.','One step at a time.','This is our song.']
return vararray
def initseq():
sequence = [0,1,9,0,2,3,4,0,1,9,0,2,3,4,0,1,9,0,1] #9 is a bookmark for skip a line
return sequence
def sing_fight_song ():
myarray ... |
from random import randint
doctors-prueba = dict({423: {'first_name': 'emanuel', 'last_name': 'rolon'}})
def get_keys():
for item in my_dict:
print(item, "tiene el valor:", my_dict[item])
def prueba():
return [{doc[0]: {"first_name": doc[1].first_name, "last_name": doc[1].last_name}} for doc in
... |
#Write a Python program that simulates a handheld calculator. Your program should process input from the Python console
# representing buttons that are “pushed,” and then output the contents ofthe screenafter each operation isperformed.
# Minimally, your calculator should beable toprocess the basic arithmetic operati... |
#Demonstrate how to use Python’s list comprehension syntax to produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].
def progression():
return list(x*(x+1) for x in range(0,10))
print(progression()) |
#Write a Python program that repeatedly reads lines from standard input until an EOFError is raised,
# and then outputs those lines in reverse order (a user can indicate end of input by typing ctrl-D)
def line_reader_and_reverser():
lines=[]
while True:
x= input()
if x == '':
break
... |
# Write a set of Python classes that can simulate an Internet application in which one party, Alice, is periodically
# creating a set of packets that she wants to send to Bob. An Internet process is continually checking if Alice has
# any packets to send, and if so, it delivers them to Bob’s computer, and Bob is peri... |
#Demonstrate how to use Python’s list comprehension syntax to produce the list [ a , b , c , ..., z ],
# but without having to type all 26 such characters literally.
print(list(chr(97+a) for a in range(0,26)))
|
#Write a short Python function that takes a sequence of integer values and determines if there is a distinct pair
# of numbers in the sequence whose product is odd.
def odd_product_pair(data):
data = set(data)
for i in data:
for j in data:
if i == j :
continue
if i... |
"""
map built-in function applies a function to items in a sequence and collects all
the results in a new list.
list(map(abs,[-1,2,0,1,2]))
"""
if __name__ == '__main__':
n = int(input())
input_line = input()
integer_list = map(int, input_line.split())
t = tuple(integer_list)
print(hash(t))
|
a = int(input('how many students in the class:'))
list_score = []
name = []
for i in range(a):
name_input = input('insert your name:')
score =int(input('insert test score:'))
if score not in list_score:
list_score.append(score)
name.append(name_input)
highest = 0
for score in range... |
# ADD IMPORTS HERE
def calculate_distance(x1, x2):
"""Returns the distance between m-dimensional
points x1 and x2.
"""
# ADD IMPLEMENTATION HERE
def find_neighbor_indices(X, query):
"""Returns 1-dimensional numpy array of shape (m,)
where each value is the argsort of the distance.
See nu... |
import json
# as requested in comment
tester = {"one": 1, "two": 2}
with open('file.txt', 'w') as file1:
file1.write(json.dumps(tester)) # use `json.loads` to do the reverse
with open('file.txt', 'r') as file2:
test1 = json.loads(file2.readline())
# test1 = json.loads('file.txt')
print(test1)
print(test1[... |
a = [['yellow_hat', 'headgear'], ['blue_sunglasses', 'eyewear'], ['green_turban', 'headgear']]
# should return 5
b = [['crow_mask', 'face'], ['blue_sunglasses', 'face'], ['smoky_makeup', 'face']]
def solution(clothes):
total_per_kind = {}
# keep track of counts per each kind of clothes
for kind in clothes:... |
'''
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common... |
import heapq
def solution(scoville, K):
answer = 0
# k is target scoville
# the goal is to make every scoviile list above K by mixing them
# new_scoville = old_scoville(lower one) + (old_scoville(higher one) * 2)
heapq.heapify(scoville)
while len(scoville) > 1 and scoville[0] < K:
a = ... |
"""
An Upper triangular matrix is a square matrix (where the number of rows and columns are equal) where all the elements below the diagonal are zero.
For example, the following is an upper triangular matrix with the number of rows and columns equal to 3.
1 2 3
0 5 6
0 0 9
Write a program to convert a square mat... |
"""
Arun is working in an office which is N blocks away from his house. He wants to minimize the time it takes him to go from his house to the office.
He can either take the office cab or he can walk to the office.
Arun's velocity is V1 m/s when he is walking. The cab moves with velocity V2 m/s but whenever he calls... |
"""
In this assignment, you will have to take two numbers as input and print the difference.
Input Format:
The first line of the input contains two numbers separated by a space.
Output Format:
Print the difference in single line
Example:
Input:
4 2
Output:
2
Explanation:
Since the difference of numbers 4 an... |
# -*- coding: utf-8 -*-
"""implement a polynomial basis function."""
import numpy as np
def build_poly(x, degree):
"""polynomial basis functions for input data x, for j=0 up to j=degree."""
# ***************************************************
expand=np.ones((x.shape[0],1))
for i in range(1,degr... |
#
#
def countBreakpoints(sequence):
""" stepik.org/lesson/43282/step/1?unit=21346
rosalind.info/problems/ba6b/#
"""
length = len(sequence)
assert length > 0
pairs = [None] * (length + 1)
pairs[0] = (0, sequence[0])
pairs[-1] = (sequence[-1], length + 1)
for i in range(length - ... |
import random
# Generating numbers for sorting
def data_set(count):
tab_u = [] # unsorted tab
for i in range(count):
tab_u.append(random.randint(0, 1000))
return tab_u
# Bubble
def bubble_sort(tab):
for i in range(len(tab) - 1):
for j in range(len(tab) - 1):
if tab[j] ... |
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
m = 0
res = -9999999999
for num in nums:
m = num + m if res > 0 else num + 0
res = max(res, m, num)
if res > 0 >= m:
m = num if num > 0 else 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.