text
stringlengths 37
1.41M
|
---|
numbers = [1, 3, 4, 2, 9, 45, 32, 89]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)
|
import numpy as np
import pandas as pd
class MultilabelPredictionEvaluater(object):
"""
Class for evaluation and comparison of multi-label classifiers.
Most methods of this class take an ndarray of predictions as input and compare them (in some way) to the
correct multi-labels which the constructor method stores as self.y.
Methods:
__init__: Constructor method.
correct_predictions: Gives an ndarray indicating correctness of the predictions.
correct_predictions_per_sample: Returns an ndarray indicating the number of correct predictions per sample.
correct_predictions_per_label: Returns an ndarray indicating how many times each label was correctly predicted.
num_correct_predictions: Returns the total number of correct predictions.
strict_accuracy: Strict evaluation measure for multi-label classifiers.
false_positives: Returns an ndarray indicating the presence of false positives among the predictions.
false_positives_per_sample: Indicates the number of false positives per sample.
false_positives_per_label: Returns an ndarray indicating the number of false positives per label.
num_false_positives: Gives the total number of false positive predictions.
false_negatives: Returns an ndarray indicating presence of false negatives among the predictions.
false_negatives_per_sample: Indicates how many false negative predictions there are per sample.
false_negatives_per_label: Indicates how many false negative predictions were made for each label.
num_false_negatives: The total number of false negative predictions.
accuracy: Standard evaluation measure for multi-label classifiers.
preds_per_label: Returns the number of times each label was predicted.
comparison_table: Returns a table comparing predictions performed by different classifiers.
"""
def __init__(self, y):
"""
Constructor method.
:param y: Correct multi-labels.
:type y: ndarray, shape = (num_samples, num_labels).
"""
self.y = y
def correct_predictions(self, x):
"""
Returns an ndarray where entry i,j is True if the corresponding prediction was correct.
:param x: Predictions
:return: ndarray indicating correct predictions.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype : ndarray, shape = (num_samples, nun_labels) = self.y.shape = x.shape
"""
comparison = np.equal(x, self.y)
return comparison
def correct_predictions_per_sample(self, x):
"""
Returns an ndarray where the i'th entry is the number of correct predictions in sample i
:param x: Predictions.
:return: Array indicating the number of correct predictions per sample.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: ndarray, shape = (num_samples,)
"""
return np.sum(self.correct_predictions(x), axis=1)
def correct_predictions_per_label(self, x):
"""
Returns an ndarray where the i'th entry is the number of times the corresponding label was correctly predicted.
:param x: Predictions.
:return ndarray indicating the number of correct predictions per label.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: ndarray, shape = (num_labels)
"""
return np.sum(self.correct_predictions(x), axis=0)
def num_correct_predictions(self, x):
"""
Returns the total number of all correct predictions.
:param x: Predictions.
:return: The total number of correct predictions.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: int
"""
return int(np.sum(self.correct_predictions_per_sample(x), axis=0))
def strict_accuracy(self, x):
"""
A strict evaluation measure. Only the samples where every label was correctly predicted contribute to the score.
:param x: Predictions.
:return: The sum of all samples that were labeled correctly divided by the total number of samples.
:type x: ndarray, shape = (num_samples, num_labels)
:rtype: float
"""
comparison = self.correct_predictions(x).astype(int)
correct = np.ones(self.y.shape[0])
for i in range(self.y.shape[1]):
correct *= comparison[:, i]
return np.sum(correct, axis=0) / self.y.shape[0]
def false_positives(self, x):
"""
Returns an ndarray where the i,j'th entry is True if the corresponding prediction was a false positive.
:param x: Predictions.
:return ndarray indicating false predictions.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: ndarray, shape = (num_samples, num_labels) = x.shape = self.y.shape
"""
ones = np.ones(shape=self.y.shape)
fp = np.equal((x - self.y), ones)
return fp
def false_positives_per_sample(self, x):
"""
Returns an ndarray where the i'th entry is the number of false positives predicted for sample i.
:param x: Predictions.
:return ndarray indicating the number of false positives per sample.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: ndarray, shape = (num_samples,)
"""
return np.sum(self.false_positives(x), axis=1)
def false_positives_per_label(self, x):
"""
Returns an ndarray indicating the number of false positives per label.
The i'th entry of the returned ndarray is the number of times the corresponding label was a false positive
among the predictions.
:param x: Predictions.
:return: ndarray indicating false positives per label.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: ndarray, shape = (num_labels,)
"""
return np.sum(self.false_positives(x), axis=0)
def num_false_positives(self, x):
"""
Returns the total number of all false positive predictions.
:param x: Predictions.
:return: Total number of false positive predictions.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: int
"""
return int(np.sum(self.false_positives_per_sample(x), axis=0))
def false_negatives(self, x):
"""
Returns an ndarray where the i,j'th entry is True if the corresponding prediction was a false negative.
:param x: Predictions.
:return: ndarray indicating false negatives.
:type x: ndarray, shape = (num_samples, num_labels)
:rtype: ndarray, shape = (num_samples, num_labels) = x.shape = self.y.shape
"""
minus_ones = -1 * np.ones(shape=self.y.shape)
fn = np.equal((x - self.y), minus_ones)
return fn
def false_negatives_per_sample(self, x):
"""
Returns an ndarray where the i'th entry is the number of false negatives predicted for sample i.
:param x: Predictions.
:return: ndarray indicating false predictions per sample.
:type x: ndarray, shape = (num_samples, num_labels)
:rtype: ndarray, shape = (num_samples,)
"""
return np.sum(self.false_negatives(x), axis=1)
def false_negatives_per_label(self, x):
"""
Returns an ndarray indicating the number of false positives among the labels.
The i'th entry of the returned ndarray is the number of times the corresponding label was identified as
a false negative among the predictions.
:param x: Predictions.
:return: ndarray indicating false negatives per label.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: ndarray, shape = (num_labels,)
"""
return np.sum(self.false_negatives(x), axis=0)
def num_false_negatives(self, x):
"""
Returns the total number of false negative predictions.
:param x: Predictions.
:return The total number of false negatives among the predictions.
:type x: ndarray, shape = (num_samples, num_labels) = self.y.shape
:rtype: int
"""
return int(np.sum(self.false_negatives_per_sample(x), axis=0))
def accuracy(self, x, lenience=None):
"""
Standard evaluation measure for multi-label classification problems.
This evaluation measure can for instance be found in the paper 'Classifier chains for
multi-label classification' by Jessee Read et.al.
:param x: Predictions.
:param lenience: optional, default = None. If set to 'false positives' (resp. 'false negatives' )
we are more lenient towards false positive (resp. false negative) predictions.
:return sum of terms between 0.0 and 1/num_samples where each sample with at least one correctly predicted
label contributes to the sum.
:type x: ndarray, shape = (num_samples, num_labels)
:type lenience: str
:rtype: float
"""
correct = self.correct_predictions_per_sample(x)
num_labels_vector = self.y.shape[1]*np.ones(self.y.shape[0])
fp = self.false_positives_per_sample(x)
fn = self.false_negatives_per_sample(x)
denominator = num_labels_vector + fp + fn
if lenience == 'false positives':
denominator -= fp
elif lenience == 'false negatives':
denominator -= fn
return np.sum(correct/denominator, axis=0) / self.y.shape[0]
@staticmethod
def preds_per_label(x):
"""
Returns an ndarray where the i'th entry is the number of times the corresponding label was predicted.
:param x: Predictions.
:return: ndarray indicating predictions per label.
:type x: ndarray, shape = (num_samples, num_labels)
:rtype: ndarray, shape = (num_labels,)
"""
return np.sum(x, axis=0)
def comparison_table(self, predictions, labels):
"""
Returns a table comparing predictions performed by different classifiers.
More precisely the method creates a pandas DataFrame with columns: strict accuracy, accuracy, false positives,
false negatives, most false positives and most false negatives. The i'th row corresponds to the i'th element
in the input list of predictions.
:param predictions: List of ndarray's of shape = (num_samples, num_labels)
:param labels: List of length num_labels where every entry is a string.
:return: comparison table
:type predictions: list
:type labels: list
:rtype: pandas DataFrame
"""
columns = ['strict accuracy', 'accuracy', 'false positives ', 'false negatives',
'most false positives', 'most false negatives']
# We will fill in the values in the pandas DataFrame by applying functions to each column. Let us first
# set create a DataFrame of shape (len(predictions), len(columns)) where all entries of the i'th row
# is the integer i.
temp_list = list(np.arange(len(predictions)))
temp_list = len(columns) * [temp_list]
temp_array = np.array(temp_list).T
temp_array = temp_array.astype(int)
df = pd.DataFrame(temp_array, index=list(range(len(predictions))), columns=columns)
# We now create the functions that are to be applied to each column of our DataFrame respectively.
def f_1(x):
return self.strict_accuracy(predictions[x])
def f_2(x):
return self.accuracy(predictions[x])
def f_3(x):
return self.num_false_positives(predictions[x])
def f_4(x):
return self.num_false_negatives(predictions[x])
def f_5(x):
return labels[int(np.argmax(self.false_positives_per_label(predictions[x])))]
def f_6(x):
return labels[int(np.argmax(self.false_negatives_per_label(predictions[x])))]
functions_list = [f_1, f_2, f_3, f_4, f_5, f_6]
column_function_dict = {key: value for (key, value) in zip(columns, functions_list)}
# We iterate over the columns in df where column_series is the Series corresponding to column
# in the list columns. For each of these columns we apply the function corresponding to column and update
# the values in df.
for column, column_series in df.iteritems():
df.update(column_series.apply(column_function_dict[column]))
return df
class MaskCreater(object):
"""
Class for extracting several interesting sub-sets from a given data set.
Methods:
__init__: Constructor method.
__call__: Creates a mask that can be used to extract the sub-set where certain labels (don't) appear.
"""
def __init__(self, y):
"""
Constructor method.
:param y: Multi-labels
:type y: ndarray, shape = (num_samples, num_labels).
"""
self.y = y
def __call__(self, col_ones=None, col_zeros=None):
"""
Call method.
This method constructs a mask that can be used to extract the subset of our data set of samples labeled with
a given set of labels and not labeled with another given set of labels.
:param col_ones: List of indices corresponding to the columns corresponding to the labels that should appear.
:param col_zeros: List of indices corresponding to the columns corresponding to the labels that we do not
want to appear.
:return: Mask to extract the desired sub-data set.
:type col_ones: list
:type col_zeros: list
:rtype: ndarray, shape = (num_labels,)
"""
ones = np.ones(shape=self.y.shape)
zeros = np.zeros(shape=self. y.shape)
comp_ones = np.equal(self.y, ones)
comp_zeros = np.equal(self.y, zeros)
one_mask = np.ones(self.y.shape[0]).astype(bool)
if col_ones is None:
col_ones = []
for index in col_ones:
one_mask *= comp_ones[:, index]
zero_mask = np.ones(self.y.shape[0]).astype(bool)
if col_zeros is None:
col_zeros = []
for index in col_zeros:
zero_mask *= comp_zeros[:, index]
return one_mask * zero_mask
|
# Quiero Retruco
# El Truco es un juego de cartas muy popular en Argentina. Se suele jugar con naipes españoles de 40 cartas, las cuales tienen 4 palos (basto, oro, espada y copa) y 10 números, 1,2,3,4,5,6,7,10,11 y 12. Si bien en esta ocasión no vamos a programar un juego de truco, sí vamos a resolver uno de los problemas más usuales que surgen cuando jugamos, el cual es definir qué carta gana y qué carta pierde cuando hay un duelo entre dos cartas.
# Esquema de hierarquia de cartas para el juego truco argentino
# En la imagen podemos observar el orden de importancia de las cartas de izquierda a derecha. El 1 de espada es la más importante (y por lo tanto siempre gana) mientras que los 4s son las cartas de menor importancia (casi siempre pierden). Las cartas en la misma columna empatan si se enfrentan.
# Programar una función con dos inputs tipo string carta A y carta B que retorne la carta ganadora (tipo string), o "empate" en caso de que lo haya. Ejemplos de como debería funcionar
# dueloDeCartas("1 de espada", "1 de basto")
# >>> 1 de espada
# dueloDeCartas("7 de oro", "5 de oro")
# >>> 7 de oro
# dueloDeCartas("11 de copa", "11 de espada")
# >>> empate
palos = ["espada","basto","copa","oro"]
cartas = {}
for palo in range(4):
for numero in range(1,11):
importancia = numero - 3
if numero <= 3:
importancia += 10
if numero >= 8:
numero += 2
carta = str(numero) + " de " + palos[palo]
if palos[palo] == "espada":
if numero == 1:
importancia = 14
elif numero == 7:
importancia = 12
if palos[palo] == "oro":
if numero == 7:
importancia = 11
if palos[palo] == "basto":
if numero == 1:
importancia = 13
cartas[carta] = importancia
# def dueloDeCartas(carta1, carta2):
# if cartas[carta1] > cartas[carta2]:
# print(carta1)
# elif cartas[carta1] < cartas[carta2]:
# print(carta2)
# else:
# print("empate")
# dueloDeCartas("1 de espada", "1 de basto")
# dueloDeCartas("7 de oro", "5 de oro")
# dueloDeCartas("11 de copa", "11 de espada")
# Usar un diccionario donde la clave sea el nombre de la carta, y su contenido su importancia (un tipo int). Aprovechen la instrucción for para evitar tener que cargar todas las cartas una por una.
# A veces se suele jugar al truco con más de dos jugadores. Podría ocurrir duelos en los que participan 𝑛 cartas. Programar una función cuyo input sea una lista de strings con todas las cartas y retorne la ganadora. (En caso de empate que retorne alguna de las ganadoras, o una lista con las ganadoras). Ejemplos de como podría funcionar:
# dueloDeCartas(["7 de basto","7 de espada","12 de espada", "4 de espada"])
# >>> "7 de espada"
# dueloDeCartas(["4 de espada","7 de basto","7 de copa", "5 de copa"]) #también podría haber dado 7 de basto
# >>> "7 de copa"
def dueloDeCartas(lista):
cartas_altas = [] # Puede haber más de una
lista.sort(key = cartas.get, reverse = True)
cartas_altas.append(lista[0])
for carta in lista[1:]:
if cartas[carta] != cartas[lista[0]]:
break
cartas_altas.append(carta)
if len(cartas_altas) > 1:
print("Parda entre:")
print(*cartas_altas, sep = " - ")
dueloDeCartas(["7 de basto","7 de espada","12 de espada", "4 de espada"])
dueloDeCartas(["4 de espada","7 de basto","7 de copa", "5 de copa"])
|
# Dr. Chaos, el malevolo semiótico
# "Chaos es caos en inglés" te diría Dr. Chaos, charlando con una taza de té Chai en la mano. En verdad no es tán malo como su nombre lo hace aparentar... si es que tenés un buen manejo de los idiomas.
# Dr. Chaos esta armando un diccionario. Este diccionario tiene la particularidad de no tener definiciones; el diccionario de Dr. Chaos define una palabra como otra. Dr. Chaos quiere comenzar a traducir la literatura de todo el mundo usando el diccionario y ha venido a ti, el Number One programador de Python.
# Objetivo: Cambiar las palabras de una oración usando el diccionario de Dr. Chaos e imprimir la nueva oración en el lenguaje unificado.
# Ejemplo:
# diccionario = {"hola":"你好","como":"how","estás":"estáis"}
# oracion = "hola, como estás?"
# OUTPUT: "你好, how estáis?"
# Ejemplo 2:
# diccionario = {"ve":"regards","bien":"bom","se":"it"}
# oracion = "se ve bien!"
# Tips:
# El programa debería tratar los símbolos de interrogación, exclamación, los puntos y comas como whitespace, es decir, espacio en blanco.
# Suponer que las letras son todas minusculas.
diccionario = {"hola":"你好","como":"how","estás":"estáis","ve":"regards","bien":"bom","se":"it"}
oracion = "hola, como estás, hola?"
oracion2 = "se ve bien!"
def trad(texto):
for key in diccionario:
idx = texto.find(key)
if idx != -1:
texto = texto.replace(texto[idx:idx+len(key)],diccionario.get(key))
return texto
def traducir(texto):
word = ""
traduccion = ""
for char in texto:
if char.isalpha():
word += char
else:
traduccion += diccionario.get(word,word) + char
word = ""
if word:
traduccion += diccionario.get(word,word)
return traduccion
print(trad(oracion))
print(traducir(oracion2))
|
import math
n = int(input())
for i in range(0,n):
args = input().split(' ')
a = int(args[0])
b = int(args[1])
root_a = math.sqrt(a)
root_b = math.sqrt(b)
square_numbers = int(math.floor(root_b)) - int(math.ceil(root_a)) + 1
print(square_numbers)
|
hours_in_words = ['one', 'two', 'three','four','five','six','seven','eight','nine','ten','eleven','twelve']
minutes_in_words = ['zero','one', 'two', 'three','four','five','six','seven','eight','nine','ten','eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen','sixteen','seventeen','eighteen','nineteen',
'twenty','twenty one','twenty two','twenty three', 'twenty four', 'twenty five',
'twenty six','twenty seven', 'twenty eight', 'twenty nine','thirty']
hours = input()
minutes = input()
hours_word = ""
minutes_word = ""
if int(minutes) <= 30:
hours_word = hours_in_words[int(hours)-1]
minutes_word = minutes_in_words[int(minutes)]
else:
hours_word = hours_in_words[int(hours)]
minutes_word = minutes_in_words[len(minutes_in_words)-1-(int(minutes)-30)]
if minutes == "00":
print(hours_word + " o' clock")
elif minutes == "01":
print(minutes_word + " minute past " + hours_word)
elif minutes == "15":
print("quarter past " + hours_word)
elif int(minutes) < 30:
print(minutes_word + " minutes past " + hours_word)
elif minutes == "30":
print("half past " + hours_word)
elif minutes == "45":
print("quarter to " + hours_word)
elif int(minutes) < 59:
print(minutes_word + " minutes to " + hours_word)
elif minutes == "59":
print(minutes_word + " minute to " + hours_word)
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p=q=head
f=False
while q and q.next:
p=p.next
q=q.next.next
if p==q:
f=True
break
if f:
p=head
while p!=q:
p=p.next
q=q.next
return p
else:
return None
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# ʼ
if not l1 and not l2:
return None
elif l1 and l2:
if l1.val<=l2.val:
res=l1
p,q=l1,l2
else:
res=l2
q,p=l1,l2
elif l1 and not l2:
res=l1
p,q=l1,l2
else:
res=l2
q,p=l1,l2
# ʼ
while q:
if q.val>=p.val:
if p.next:
if q.val>=p.next.val:
p=p.next
else:
if q.next:
s=q.next
q.next=p.next
p.next=q
q=s
p=p.next
else:
q.next=p.next
p.next=q
break
else:
p.next=q
break
else:
p=p.next
return res
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
# 此题是要移动结点的值
p=node
while p.next:
p.val=p.next.val
if p.next.next:
p=p.next
else:
p.next=None
return
|
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.lst=[[] for i in range(10000)]
def add(self, key):
"""
:type key: int
:rtype: void
"""
index=key%10000
if key not in self.lst[index]:
self.lst[index].append(key)
def remove(self, key):
"""
:type key: int
:rtype: void
"""
index=key%10000
if key in self.lst[index]:
self.lst[index].remove(key)
def contains(self, key):
"""
Returns true if this set did not already contain the specified element
:type key: int
:rtype: bool
"""
index=key%10000
if key in self.lst[index]:
return True
else:
return False
|
class Stack:
def __init__(self):
self.list = []
self.top = -1
def push(self,data):
self.top += 1
self.list.insert(self.top,data)
def pop(self):
if (self.top == -1):
print("Invalid to perform Pop operation !!!")
return False
top = self.top
self.top -= 1
return self.list[top]
def printStack(self):
if (self.top == -1):
print ("Empty Stack")
return False
else:
count = 0
while(count <= self.top):
print(self.list[count])
count += 1
return True
def printStackReverse(self):
if (self.top == -1):
print ("Empty Stack")
return False
else:
dec = self.top
while True:
if (dec < 0):
break
print (self.list[dec])
dec -= 1
return True
def lengthStack(self):
return self.top+1
"""
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.printStack()
print(s.lengthStack())
print()
s.pop()
s.printStackReverse()
print(s.lengthStack())
print()
"""
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 10:53:57 2019
@author: ottil
"""
word_counter = {}
def wordcount(words):
for word in words.split():
if word not in word_counter:
word_counter[word] = 1
else:
word_counter[word] +=1
return(word_counter)
#print(wordcount(1))
|
class Queue(object):
def __init__(self):
self.queue = list()
def enqueue(self,value):
self.queue.insert(0,value)
def dequeue(self):
if self.is_empty():
return None
return self.queue.pop()
def peek(self):
if self.is_empty():
return None
return self.queue[-1]
def is_empty(self):
return not len(self.queue)
def print_queue(self):
print(self.queue)
|
"""
Logic : Do BFS traversal. At each level start with previous set as None
Then if previous, set node.next as previous
Set node as previous and continue with BFS
TimeComplexity : BFS traversal; O(N)
Space complexity : O(2^log(N)) -> O(2 to the power h where h is hte height of the tree)
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
#bfs
original_root = root
queue = [root]
while queue:
i = len(queue)
prev = None
while i:
root = queue.pop(0)
if prev!=None:
prev.next = root
if root:
queue.append(root.left)
queue.append(root.right)
prev = root
i-=1
return original_root
"""
2 pointers : Keep one pointer for going level by level and one for traversing to the right at each point
Time complexity : O(N)
Space complexity : O(1)
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
prev = root
level = root
if level == None:
return None
while level.left:
prev = level
while prev:
prev.left.next = prev.right
if prev.next:
prev.right.next = prev.next.left
prev = prev.next
level = level.left
return root
|
"""
Bruteforce: Find all indices for the first alphabet of B in A.
Then for all indexes in indices,
check if B to end matches with A[index]->A[len(A)]->A[0]->A[index-1]
Time complexity : Finding indexes O(N)
Checking for match O(N)
Space complexity : O(N)-> Storing the indexes
"""
class Solution(object):
def rotateString(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if len(A)!=len(B):
return False
if len(A) == 0:
return True
indices = [i for i, x in enumerate(A) if x == B[0]]
#iterate to see
for index in indices:
j = 0
flag = True
k = 0
for i in xrange(index,len(A)):
#print B[j],A[i],j,i
k=i
if B[j]!=A[i]:
flag = False
break
j+=1
#print flag,j,k
if flag and j!=len(B):
for i in xrange(0,k-j+1):
#print B[j],A[i],j,i
if B[j]!=A[i]:
flag = False
break
j+=1
if j==len(B):
return True
return False
|
"""
Bruteforce : For a given string, iterate over the indexes, taking the index as the middle point
of the palindrome. From the middle point, check if left and right
Time complexity : O(n^2)
Space complexity : O(1)
Other approaches:
"""
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def helper(s,i,j):
while i>=0 and j<len(s) and s[i] == s[j]:
i-=1
j+=1
return s[i+1:j]
ans = ""
for i in xrange(0,len(s)):
str_ = helper(s,i,i)
if len(str_) > len(ans):
ans = str_
str_ = helper(s,i,i+1)
if len(str_) > len(ans):
ans = str_
return ans
|
"""
Solution : Convert to binary. Store indexes of 1's.
Find maximum distance between the adjacent differences
return
Time complexity : O(N), N being the number of bytes needed to represent the number
Space complexity : O(N), depends on the number indexes stored.
"""
class Solution(object):
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
# store indexes
indexes = []
c = 0
for i in bin(N)[2:]:
if i == "1":
indexes.append(c)
c+=1
#print indexes
if len(indexes) > 1:
return max(indexes[i+1] - indexes[i] for i in xrange(0,len(indexes)-1))
else:
return 0
|
"""
Algorithm - Single stack
We use one stack only and a variable to store min element.
If the element to be inserted is less than or equal to(equal to because duplicate elements which can be same min) min element, then we push the current min element to stack, then
update the min element to new element and then push new element to stack.
If it isn't then simply push that element to stack
While popping an element, check the element is same as min, If it is, pop the element, then pop once more to retrieve
the previous minimum element as well.
Time Complexity
1. To add an element - O(1)
2. To retrieve top element - O(1)
3. To get min element - O(1)
Space complexity
1. O(n) - Worst case would be elements added in descending order which would result in 2n elements in stack
NOTE - This can also be done with 2 stacks (one regular stack and one minimum stack) but the complexities remain same.
"""
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = None
def push(self, x):
"""
:type x: int
:rtype: None
"""
if self.min == None:
self.min = x
elif x <= self.min:
self.stack.append(self.min)
self.min = x
self.stack.append(x)
def pop(self):
"""
:rtype: None
"""
if self.min == self.stack[-1]:
self.stack.pop(-1)
try:
self.min = self.stack[-1]
self.stack.pop(-1)
except IndexError:
self.min = None
else:
self.stack.pop(-1)
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
"""
With division, bruteforce soln
time complexity: O(N)
space: O(N)
"""
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
prod = 1
non_zero_prod = 1
zero_flag = False
for i in range(0,len(nums)):
if nums[i]!=0:
non_zero_prod*=nums[i]
elif zero_flag:
non_zero_prod = 0
else:
zero_flag = True
prod*=nums[i]
for i in range(0,len(nums)):
if nums[i] != 0:
ans.append(prod/nums[i])
else:
ans.append(non_zero_prod)
return ans
"""
Without division : Keep 2 arrays, one for left products and one for right products.
Answer is the product of these 2
"""
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = [0]*len(nums)
left = [0]*len(nums)
right = [0]*len(nums)
left[0] = 1
right[-1] = 1
for i in range(1,len(nums)):
left[i] = left[i-1]*nums[i-1]
for i in range(len(nums)-2, -1, -1):
right[i] = right[i+1]*nums[i+1]
for i in range(0,len(nums)):
ans[i] = left[i]*right[i]
return ans
|
"""
To find min element, do binary search on all the unsorted parts.
If there is no unsorted part, return nums[low]
When searching in second subarray, include the mid also in the search
Time complexity - O(log(N))
Space complexity - O(1)
"""
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return -1
lo = 0
hi = len(nums)-1
while lo<=hi:
mi = (lo+hi)/2
if nums[lo] <= nums[mi] <=nums[hi]:
return nums[lo]
elif nums[lo] <= nums[mi]:
lo = mi+1
else:
hi = mi
|
from Tkinter import *
class sketcheCanvas(Canvas):
"""Inherits from tk.Canvas. Additional methods for mouse click callbacks.
e.g. drawing lines, curves, etc."""
def setVals(self):
"""Sets attributes needed in sketcheGui."""
self.click = False
self.items = []
self.tool = self.drawLine
self.color = 'black'
self.ordered_pairs_final = []
self.ordered_pairs_init = []
self.coord_dict = {}
self.lines = []
self.dimensions = [36, 36]
self.bind("<Button-1>", self.draw)
self.bind("<Motion>", self.drawUpdate)
def changeColor(self, color):
"""Sets the color"""
self.color = color
def drawLine(self, coords):
"""Draws a line on the canvas if self.click is true.
If self.click is false, just stores event coordinates in self.coords.
args:
coords: list of 2 floats
"""
if self.click == False:
self.coords = coords
self.ordered_pairs_init.append(coords)
else:
self.items.append(self.create_line([self.coords, coords], fill=self.color))
self.ordered_pairs_final.append(coords)
if len(self.ordered_pairs_final) % 2 == 0:
self.coord_dict[self.items[1]] = [self.color, [self.ordered_pairs_init[0], self.ordered_pairs_final[0]]]
self.lines.append((self.color, [self.ordered_pairs_init[0],
self.ordered_pairs_final[0]]))
self.items = []
self.ordered_pairs_final = []
self.ordered_pairs_init = []
def drawRectangle(self, coords):
"""Draws a rectangle on the canvas if self.click is true.
If self.click is false, just stores event coordinates in self.coords.
args:
coords: list of 2 floats
"""
if self.click == False:
self.coords = coords
self.ordered_pairs_init.append(coords)
else:
self.items.append(self.create_rectangle([self.coords, coords], outline=self.color))
self.ordered_pairs_final.append(coords)
if len(self.ordered_pairs_final) % 2 == 0:
x1 = self.ordered_pairs_init[0][0]
y1 = self.ordered_pairs_init[0][1]
x2 = self.ordered_pairs_final[0][0]
y2 = self.ordered_pairs_final[0][1]
rect_coords = [[x1, y1],[x2, y1],[x2, y2],[x1, y2]]
self.coord_dict[self.items[1]] = [self.color, rect_coords]
self.lines.append((self.color, [x1, y1]))
self.lines.append((self.color, [x1, y2]))
self.lines.append((self.color, [x2, y2]))
self.lines.append((self.color, [x2, y1]))
self.items = []
self.ordered_pairs_final = []
self.ordered_pairs_init = []
def drawFreeHand(self, coords):
"""Draws a series of lines following the path of the mouse."""
if self.click == False:
self.coords = coords
else:
self.coord_dict[self.create_line([self.coords, coords], fill = self.color)] = [self.color, [self.coords, coords]]
self.lines.append((self.color, [self.coords, coords]))
self.coords = coords
def draw(self, event):
"""Runs the tool function stored in self.tool as a callback to
left mouse click event."""
if self.tool != None: self.tool([event.x, event.y])
self.click = not self.click
self.motionLen = 0
def drawUpdate(self, event):
"""Updates the shape being drawn as a callback to mouse motion."""
if self.click == True:
if self.motionLen > 0:
if self.tool != self.drawFreeHand:
self.delete(self.items[-1])
self.items.pop(-1)
self.ordered_pairs_final.pop(-1)
self.tool([event.x, event.y])
self.motionLen += 1
|
def to_2(num, bits):
ans=""
bits-=1
while bits>=0:
if 2**bits <= num:
num-= 2**bits
ans+='1'
else:
ans+='0'
bits-=1
return ans
palendromes = 0
nth = int(input())
nth-=1
n = 0
length = 1
while n+2**((length-1)//2) <= nth:
n += 2**((length-1)//2)
length+=1
if nth == 0:
palendrome = '1'
else:
nth-=n
palendrome = "1" + "0"*(length-2) + "1"
if length%2 == 0:
middle = to_2(nth, (length-2)//2)
palendrome = '1' + middle + middle[::-1] + '1'
else:
if nth == 0:
pass
elif nth==1:
palendrome = palendrome[:len(palendrome)//2] + '1' + palendrome[len(palendrome)//2+1:]
else:
middle = to_2(nth, (length-1)//2)
palendrome = '1' + middle + middle[::-1][1:] + '1'
print(int(palendrome, 2))
|
import heapq
class Node:
def __init__(self, idx):
self.idx = idx
self.dist = -1
self.edges = []
self.visited = False
self.pot = False
def set_dist(self, new_dist, heap):
if new_dist > self.dist:
self.dist = new_dist
def __lt__(self, other):
return self.dist > other.dist
class Edge:
def __init__(self, node1, node2, weight):
self.node1 = node1
self.node2 = node2
self.weight = weight
def get_next_node(self, node):
if self.node1 == node:
return self.node2
return self.node1
def add_data():
num_nodes, num_edges = [ int(x) for x in input().split()]
nodes = []
edges = []
for i in range(num_nodes):
nodes.append(Node(i))
for i in range(num_edges):
node1, node2, weight = input().split()
edges.append(Edge(nodes[int(node1)], nodes[int(node2)], float(weight)))
nodes[int(node1)].edges.append(edges[i])
nodes[int(node2)].edges.append(edges[i])
return (nodes, edges)
def print_order(nodes):
heap = []
for node in nodes:
heapq.heappush(heap, node)
while len(heap) != 0:
node = heapq.heappop(heap)
print(node.dist)
def dijkstra(nodes, edges):
last_node = nodes[len(nodes)-1]
cur_node = nodes[0]
cur_node.dist = 1
pot_nodes = []
pot_nodes.append(cur_node)
while len(pot_nodes) != 0 and pot_nodes[0] != last_node:
cur_node = heapq.heappop(pot_nodes)
cur_node.visited = True
for edge in cur_node.edges:
new_node = edge.get_next_node(cur_node)
if not new_node.visited:
new_node.set_dist(edge.weight * cur_node.dist, pot_nodes)
heapq.heappush(pot_nodes, new_node)
return last_node.dist
if __name__ == "__main__":
nodes, edges = add_data()
while len(nodes) != 0 and len(edges) != 0:
print("%.4f" % dijkstra(nodes, edges))
nodes, edges = add_data()
|
"""Project Euler problem 3"""
def sqrt(number):
"""Returns the square root of the specified number as an int, rounded down"""
assert number >= 0
offset = 1
while offset ** 2 <= number:
offset *= 2
count = 0
while offset > 0:
if (count + offset) ** 2 <= number:
count += offset
offset //= 2
return count
def smallest_prime_factor(number):
"""Returns the smallest prime factor of the specified number"""
assert number >= 2
for potential in range(2, sqrt(number) + 1):
if number % potential == 0:
return potential
return number
def calculate(number):
"""Returns the largest prime factor of the specified number"""
while True:
smallest = smallest_prime_factor(number)
if number > smallest:
number //= smallest
else:
answer = number
return answer
if __name__ == "__main__":
print(calculate(600851475143))
|
"""Project Euler problem 22"""
def calculate(name_list):
"""Returns the sum of the alphabetical value for each name
in the list multiplied by its position in the list"""
return sum(
(i + 1) * (ord(c) - ord("A") + 1)
for i, name in enumerate(sorted(name_list))
for c in name.strip('"')
)
with open("p022_names.txt") as f:
NAMES = f.read().split(",")
if __name__ == "__main__":
print(calculate(NAMES))
|
"""
Written by Abdullah Al-Hajjar
"""
import unittest
import pandas as pd
class test(unittest.TestCase):
@classmethod
def setUpClass(self):
try:
df3 = pd.DataFrame()
df = pd.read_csv('canadianCheeseDirectory.csv')
search_word = 'Bufflo Cow Creamy and fresh, this delicious locally-made cheese offers the traditional taste of Italy Pasteurized'
words_array = search_word.split()
for w in words_array:
for index, row in df.iterrows():
if (str(row['CheeseNameEn']).startswith(w) or str(row['CheeseNameFr']).startswith(w) or str(
row['ManufacturerNameEn']).startswith(w) or str(row['ManufacturerNameFr']).startswith(
w) or str(row['ManufacturerProvCode']).startswith(w) or
str(row['ManufacturingTypeEn']).startswith(w) or str(row['ManufacturingTypeFr']).startswith(
w) or str(row['WebSiteEn']).startswith(w) or str(row['WebSiteFr']).startswith(w) or str(
row['FatContentPercent']).startswith(w) or
str(row['MoisturePercent']).startswith(w) or str(row['ParticularitiesEn']).startswith(
w) or str(row['ParticularitiesFr']).startswith(w) or str(row['FlavourEn']).startswith(
w) or str(row['FlavourFr']).startswith(w) or
str(row['CharacteristicsEn']).startswith(w) or str(row['CharacteristicsFr']).startswith(
w) or str(row['RipeningEn']).startswith(w) or str(row['RipeningFr']).startswith(
w) or str(row['Organic']).startswith(w) or str(row['CategoryTypeEn']).startswith(w) or
str(row['CategoryTypeFr']).startswith(w) or str(row['MilkTypeEn']).startswith(w) or str(
row['MilkTypeFr']).startswith(w) or str(row['MilkTreatmentTypeEn']).startswith(
w) or str(row['MilkTreatmentTypeFr']).startswith(w) or
str(row['RindTypeEn']).startswith(w) or str(row['RindTypeFr']).startswith(w) or str(
row['LastUpdateDate']).startswith(w)):
df2 = pd.DataFrame({'CheeseId': [row['CheeseId']], 'CheeseNameEn': [row['CheeseNameEn']],
'CheeseNameFr': [row['CheeseNameFr']],
'ManufacturerNameEn': [row['ManufacturerNameEn']],
'ManufacturerNameFr': [row['ManufacturerNameFr']],
'ManufacturerProvCode': [row['ManufacturerProvCode']],
'ManufacturingTypeEn': [row['ManufacturingTypeEn']],
'ManufacturingTypeFr': [row['ManufacturingTypeFr']],
'WebSiteEn': [row['WebSiteEn']], 'WebSiteFr': [row['WebSiteFr']],
'FatContentPercent': [row['FatContentPercent']],
'MoisturePercent': [row['MoisturePercent']],
'ParticularitiesEn': [row['ParticularitiesEn']],
'ParticularitiesFr': [row['ParticularitiesFr']],
'FlavourEn': [row['FlavourEn']], 'FlavourFr': [row['FlavourFr']],
'CharacteristicsEn': [row['CharacteristicsEn']],
'CharacteristicsFr': [row['CharacteristicsFr']],
'RipeningEn': [row['RipeningEn']],
'RipeningFr': [row['RipeningFr']], 'Organic': [row['Organic']],
'CategoryTypeEn': [row['CategoryTypeEn']],
'CategoryTypeFr': [row['CategoryTypeFr']],
'MilkTypeEn': [row['MilkTypeEn']], 'MilkTypeFr': [row['MilkTypeFr']],
'MilkTreatmentTypeEn': [row['MilkTreatmentTypeEn']],
'MilkTreatmentTypeFr': [row['MilkTreatmentTypeFr']],
'RindTypeEn': [row['RindTypeEn']],
'RindTypeFr': [row['RindTypeFr']],
'LastUpdateDate': [row['LastUpdateDate']]})
df3 = df3.append(df2)
except IOError:
print('Cannot Uploadfile')
# print(df3)
self.data = str(df3)
# Setup the testing by creating a connection to the database and retrieving a record
def test(self):
print('Abdullah Al-Hajjar Student number : 040656012')
record = "1944,Mozzarina di Bufala,Mozzarina di Bufala,Saputo,Saputo,QC,Industrial,Industrielle,http://www.saputo.com/?langType=4105,http://www.saputo.com/?langType=3084,19.0,64.0,Made from 100% pasteurised buffalo milk and is rich in calcium, and low in sodium and cholesterol.,Faite à 100 % de lait de bufflonne frais, est riche en calcium et faible en sodium et en cholestérol. Savourez l'Italie grâce au goût frais et crémeux de ce somptueux fromage d'ici,Creamy and fresh, this delicious locally-made cheese offers the traditional taste of Italy.,Savourez l'Italie grâce au goût frais et crémeux de ce somptueux fromage.,,,0,Fresh Cheese,Pâte fraîche,Buffalo Cow,Bufflonne,Pasteurized,Pasteurisé,No Rind,Sans croûte,2016-02-03"
self.assertEqual(self.data, record)
# Comparing the expectation of the record with the actual retrieved object from the database
|
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
# Добавление строки в текстовый блок
def insertText(s):
textDiary.insert(INSERT, s + "\n")
textDiary.see(END)
# Расположение лошадей на экране
def horsePlaceInWindow():
horse01.place(x=int(x01), y=20)
horse02.place(x=int(x02), y=100)
horse03.place(x=int(x03), y=180)
horse04.place(x=int(x04), y=260)
# Чтение из файла оставшейся суммы
def loadMoney():
try:
f = open('money.dat', 'r')
m = int(f.readline())
f.close()
except FileNotFoundError:
print(f"Файла не существует, задано значение {defaultMoney} {valuta}")
m = defaultMoney
return m
# Запись суммы в файл
def saveMoney(moneyToSave):
try:
f = open("money.dat", "w")
f.write(str(moneyToSave))
f.close()
except:
print("Ошибка создания файла, наш Ипподром закрывается!")
quit(0)
root = Tk()
# Размеры окна программы
WIDTH = 1024
HEIGHT = 600
# Позиции лошадей
x01 = 20
x02 = 20
x03 = 20
x04 = 20
# Клички лошадей
nameHorse01 = "Ананас"
nameHorse02 = "Сталкер"
nameHorse03 = "Прожорливый"
nameHorse04 = "Копытце"
# Финансовые показатели
defaultMoney = 10000
money = 0
valuta = 'руб'
# Создаем главное окно
# Вычисляем координаты для размещения окна по центру
POS_X = root.winfo_screenwidth() // 2 - WIDTH // 2
POS_Y = root.winfo_screenheight() // 2 - HEIGHT // 2
# Устанавливаем заголовок
root.title('ИППОДРОМ')
# Запрещаем изменение размеров
root.resizable(False, False)
# Устанавливаем ширину, высоту и позицию
root.geometry(f"{WIDTH}x{HEIGHT}+{POS_X}+{POS_Y}")
road_image = PhotoImage(file="road.png") # Загружаем изображение фона
road = Label(root, image=road_image)# Устанавливаем в Label
road.place(x=0, y=17) # Выводим в окно
horse01_image = PhotoImage(file='horse01.png') # Загружаем изображение
horse01 = Label(root, image=horse01_image) # Устанавливаем в Label
horse02_image = PhotoImage(file='horse02.png')
horse02 = Label(root, image=horse02_image)
horse03_image = PhotoImage(file='horse03.png')
horse03 = Label(root, image=horse03_image)
horse04_image = PhotoImage(file='horse04.png')
horse04 = Label(root, image=horse04_image)
horsePlaceInWindow()
# Создаем кнопку и выводим ее на экран
startButton = Button(text="Старт", font='arial 20', width=61, background='#37AA37')
startButton.place(x=20, y=370)
# Создаем информационный чат виджетом Text
textDiary = Text(width=70, height=8, wrap=WORD)
textDiary.place(x=430, y=450)
# Создаем и прикрепляем к тексту полосу прокрутки
scroll = Scrollbar(command=textDiary.yview, width=20)
scroll.place(x=990, y=450, height=132)
textDiary["yscrollcommand"] = scroll.set
# Загружаем сумму средств игрока из файла
money = loadMoney()
if (money <= 0):
messagebox.showinfo("Стоп!", "На ипподром без средств заходить нельзя!")
quit(0)
# Формируем текстовую строку и выводим в нее оставшуюся сумму средств
labelAllMoney = Label(text=f'Осталось средств: {money} {valuta}.', font='Arial 12')
labelAllMoney.place(x=20, y=565)
# Выводим текстовые метки в левом нижнем углу окна
labelHorse01 = Label(text='Ставка на лошадь №1')
labelHorse01.place(x=20, y=450)
labelHorse02 = Label(text='Ставка на лошадь №2')
labelHorse02.place(x=20, y=480)
labelHorse03 = Label(text='Ставка на лошадь №3')
labelHorse03.place(x=20, y=510)
labelHorse04 = Label(text='Ставка на лошадь №4')
labelHorse04.place(x=20, y=540)
# Чекбоксы для лошадок
horse01Game = BooleanVar()
horse01Game.set(0)
horseCheck01 = Checkbutton(text=nameHorse01, variable=horse01Game, onvalue=1, offvalue=0)
horseCheck01.place(x=150, y=448)
horse02Game = BooleanVar()
horse02Game.set(0)
horseCheck02 = Checkbutton(text=nameHorse02, variable=horse02Game, onvalue=1, offvalue=0)
horseCheck02.place(x=150, y=478)
horse03Game = BooleanVar()
horse03Game.set(0)
horseCheck03 = Checkbutton(text=nameHorse03, variable=horse03Game, onvalue=1, offvalue=0)
horseCheck03.place(x=150, y=508)
horse04Game = BooleanVar()
horse04Game.set(0)
horseCheck04 = Checkbutton(text=nameHorse04, variable=horse04Game, onvalue=1, offvalue=0)
horseCheck04.place(x=150, y=538)
# Выпадающий список
stavka01 = ttk.Combobox(root)
stavka02 = ttk.Combobox(root)
stavka03 = ttk.Combobox(root)
stavka04 = ttk.Combobox(root)
# Задаем атрибут "только для чтения""
stavka01["state"] = "readonly"
stavka01.place(x=280, y=450)
stavka02["state"] = "readonly"
stavka02.place(x=280, y=480)
stavka03["state"] = "readonly"
stavka03.place(x=280, y=510)
stavka04["state"] = "readonly"
stavka04.place(x=280, y=540)
root.mainloop()
|
number_of_months = int(input("Number of months: "))
k = int(input("Number of pairs every pair produces: "))
n1,n2 = 1,1
counted = 0
while counted < number_of_months:
print(n1)
new_number = k*n1 + n2
n1 = n2
n2 = new_number
counted += 1
|
arr = []
def push(data):
arr.append(data)
def pop():
arr.pop()
def printAll():
for i in range(0,len(arr)):
print arr[i]
push(1)
push(2)
push(3)
push(4)
pop()
printAll()
|
date=input("enter the date in dd/mm/yyyy:")
day,month,year = date.split("/")
day = int(day)
month = int(month)
year = int(year)
if month==1 or month==3 or month==5 or month==7 or month==8 or month==10 or month==12:
max_days=31
elif month==4 or month==6 or month==9 or month==11:
max_days=30
elif year%4==0 and year%100!=0 or year%400==0:
max_days=29
else:
max_days=28
if month<1 or month>12:
print("entered month is invalid")
elif day<1 or day>max_days:
print("entered day is invalid")
elif year>=2020:
print("entered year is invalid")
else:
print("entered date is valid")
|
def meetsCriteria(number):
doub = False
previous = -1
st = str(number)
for i in range(len(st)):
if previous == int(st[i]):
doub = True
elif previous > int(st[i]):
return False
previous = int(st[i])
return doub
def meetsMoreCriteria(number):
previous = -1
st = str(number)
count = 1
counts = set()
for i in range(len(st)):
if previous == int(st[i]):
count += 1
elif previous > int(st[i]):
return False
else:
counts.add(count)
count = 1
previous = int(st[i])
counts.add(count)
return 2 in counts
def solve(inp):
"""
278384-824795
"""
upper, lower = 0, 0
for line in open(inp):
line = line.strip().split("-")
lower = int(line[0])
upper = int(line[1])
count = 0
count2 = 0
for i in range(lower, upper + 1):
if meetsCriteria(i):
count += 1
if meetsMoreCriteria(i):
count2 += 1
print("Part 1:", count)
print("Part 2:", count2)
if __name__ == '__main__':
print(meetsMoreCriteria(111122))
inp = "input.txt"
solve(inp)
|
fname = input("Enter file name: ")
han=open(fname)
count=0
for line in han:
line=line.rstrip()
wds=line.split()
if len(wds) < 3 or wds[0] !='From':
continue
count=count+1
print(wds[1])
print('There were',count,'lines in the file with From as the first word')
|
def are_anagrams(*words: str) -> bool:
"""
Checks whether all words passed are anagrams of each other
This will return True for the cases where less than 2 words are passed.
i.e. Nothing and a single word are considered anagrams of themselves
:param words: The words to compare against each other
:returns: True if all words are anagrams of each other; False otherwise
"""
return len({''.join(sorted(word)) for word in words}) < 2
|
from adventofcode.common import Solution
import re
class Day11(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self._s = self._load_input_as_lines()[0]
def _is_valid(self, s):
# must be 8 characters
if re.match('^[a-z]{8,8}$', s) is None:
return False
# cannot have i, o, l characters
if re.match('.*[iol]+.*', s):
return False
has_sequence = False
character_pairs = set()
for i in range(len(s)):
# sequence
if i+2 < len(s) and ord(s[i])+1 == ord(s[i+1]) and ord(s[i])+2 == ord(s[i+2]):
has_sequence = True
# character pair
if i+1 < len(s) and s[i] == s[i+1]:
character_pairs.add(s[i])
return has_sequence and len(list(character_pairs)) > 1
def _next_password(self, s):
while True:
next_s = list(s)
carry = True
for i in reversed(range(len(next_s))):
if carry:
next_char = chr(ord(next_s[i]) + 1)
if ord(next_char) > ord('z'):
next_s[i] = 'a'
carry = True
else:
next_s[i] = next_char
carry = False
s = "".join(next_s)
yield s
def part_one(self):
for s in self._next_password(self._s):
#print(s + ' is invalid')
if self._is_valid(s):
break
return s
def part_two(self):
valid_password = self.part_one()
for s in self._next_password(valid_password):
#print(s + ' is invalid')
if self._is_valid(s):
break
return s
|
from adventofcode.common import Solution
import re
class Day25(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self.input = self._load_input_as_string()
r = re.match('To continue, please consult the code grid in the manual\. Enter the code at row (\d+), column (\d+).', self.input)
if r is None:
raise Exception('Invalid input : ' + self.input)
self.row = int(r.group(1))
self.column = int(r.group(2))
def _get_code_recursive(self, row, column):
# NOTE : reaches max recursion depth for row, column values over 25,25
if row == 1 and column == 1:
return 20151125
else:
if column > 1:
# based on position of this code, its previous code is one down and one left
return ((self._get_code(row + 1, column - 1) * 252533) % 33554393)
else:
# based on position of this code, its previous code is at the previous diagonal position at upper right
return ((self._get_code(1, row - 1) * 252533) % 33554393)
def _get_code(self, target_row, target_column):
code = 20151125
row = 1
column = 1
while row != target_row or column != target_column:
print('code at ' + str(row) + ', ' + str(column) + ' is ' + str(code))
if row == 1:
# based on position of this code, the next code is the next diagonal values at the starting from lower left
row = column + 1
column = 1
else:
# based on position of this code, the next code is on the same diagonal values one up and one right of current
row -= 1
column += 1
code = ((code * 252533) % 33554393)
return code
def part_one(self):
return self._get_code(self.row, self.column)
def part_two(self):
return "ᕕ( ᐛ )ᕗ"
|
from adventofcode.common import Solution
import re
class Day19(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self._transformations = []
lines = self._load_input_as_lines()
self._final_molecule = lines[-1]
for t in lines[0:len(lines)-3]:
tmp = t.split('=>')
self._transformations.append((tmp[0].strip(), tmp[1].strip()))
def _transform(self, molecule):
possible_molecules = set()
for source, destination in self._transformations:
i = 0
while i >= 0:
i = molecule.find(source, i)
if i >= 0:
possible_molecules.add(molecule[0:i] + molecule[i:i+len(source)].replace(source, destination) + molecule[i+len(source):])
i += 1
return possible_molecules
def _molecule_closeness(self,m1, m2):
i = 0
while i < min(len(m1), len(m2)):
if m1[i] != m2[i]:
break
i += 1
return i
def part_one(self):
return len(self._transform(self._final_molecule))
def part_two(self):
# don't think this solution will always find the "shortest" steps to ANY molecule. it just happens to reverse engineer the algorithm
# the question used to generate the target molecule
starting_molecule = 'e'
target_molecule = self._final_molecule
repl_r = {destination:source for source, destination in self._transformations}
molecules = [target_molecule]
while molecules[-1] != starting_molecule:
molecules.append(re.sub('^(.*)(' + '|'.join(repl_r.keys()) + ')(.*?)$',
lambda x: x.group(1) + repl_r[x.group(2)] + x.group(3),
molecules[-1]))
return len(molecules) - 1
|
from itertools import cycle
from adventofcode.common import Solution
from typing import Set
class Day03(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self._directions = self._load_input_as_string()
def _journey(self, directions) -> Set:
x = 0
y = 0
visited_houses = {(x, y)}
for d in directions:
if d == '>':
x += 1
elif d == '<':
x -= 1
elif d == '^':
y += 1
elif d == 'v':
y -= 1
else:
assert False, f"Unrecognized direction : {d}"
visited_houses.add((x, y))
return visited_houses
def part_one(self):
return len(self._journey(self._directions))
def part_two(self):
# use cycle module to alternate between the two direction lists
direction_list = cycle([[], []])
list(map(lambda d: next(direction_list).append(d), self._directions))
return len(self._journey(next(direction_list)).union(self._journey(next(direction_list))))
|
# Faça um programa que leia o nome e peso de várias pessoas, [ X ]
# guardando tudo em uma lista. No final, mostre:
# A) Quantas pessoas foram cadastradas [ X ]
# B) Uma lista com as pessoas mais pesadas, [ X ]
# C) Uma lista com as pessoas mais leves [ X ]
temporal = list()
principal = list()
leve = pesado = 0
while True:
temporal.append(str(input('Nome: ')))
temporal.append(float(input('Peso: ')))
if len(principal) == 0:
leve = pesado = temporal[1]
else:
if temporal[1] > pesado:
pesado = temporal[1]
if temporal[1] < leve:
leve = temporal[1]
principal.append(temporal[:])
temporal.clear()
continuar = str(input('Quer continuar? [S/N] -> ')).strip().upper()[0]
if continuar == 'N':
break
print('-=' * 30)
print(f'Os dados foram {principal}')
print(f'Ao todo você cadastrou {len(principal)} pessoas.')
print(f'O maior peso foi de {pesado}Kg. Peso de ', end='')
for p in principal:
if p[1] == pesado:
print(f'[{p[0]}] ', end='')
print()
print(f'O menor peso foi de {leve}Kg. Peso de ', end='')
for p in principal:
if p[1] == leve:
print(f'[{p[0]}] ', end='')
print()
|
dias = int(input('Quantos dias alugados? '))
quilometros = float(input('Quantos Km rodados? '))
precoDias = 60.0
precoQuilometro = 0.15
resultado = (dias * precoDias) + (quilometros * precoQuilometro)
print('O preço a pagar é: R${}{:.2f}{}'.format('\033[33m', resultado, '\033[m'))
|
numero = int(input('Digite um número: '))
unidade = numero // 1 % 10
dezena = numero // 10 % 10
centena = numero // 100 % 10
milhar = numero // 1000 % 10
print('unidade: {}{}{}'.format('\033[35m', unidade, '\033[m'))
print('dezena: {}'.format(dezena))
print('centena: {}'.format(centena))
print('milhar: {}'.format(milhar))
|
metros = int(input('Digite um valor: '))
metros1 = (metros) * 10 ** 0
centimetros = (metros) * 10 ** -2
milimetros = (metros) * 10 ** -3
print('Esse número em metros é = {}{}{}m\nEm centímetros é = {}cm\nEm milímetros = {}mm'.format('\033[31m', metros1, centimetros, milimetros, '\033[m'))
|
soma = 0
count = 0
for i in range(1, 7):
valor = int(input('Digite um valor: '))
if i % 2 == 0:
soma = soma + valor
count = count + 1
print('A soma de todos os {} números PARES é igual a {}'.format(count, soma))
|
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
print('A média desse aluno foi: {}{}{}'.format('\033[34m', media, '\033[m'))
|
from datetime import date
ano_de_nascimento = int(input('Digite o ano de nascimento: '))
atual = date.today().year
idade = atual - ano_de_nascimento
print('Sua idade é: {}'.format(idade))
if idade <= 9:
print('Até 9 anos, MIRIM')
elif idade <= 14:
print('Até 14 anos, INFANTIL')
elif idade <= 19:
print('Até 19 anos, JUNIOR')
elif idade <= 20:
print('Até 20 anos, SÊNIOR')
elif idade > 20:
print('Acima de 20 anos, MASTER')
|
# RGB color table
# based on http://en.wikipedia.org/wiki/File:1Mcolors.png
def draw_square(steps, pos, b):
color_step = 1.0 / steps
x, y = pos
for i in range(steps):
for j in range(steps):
r = j * color_step
g = i * color_step
fill(r, g, b)
stroke(r, g, b)
strokeWidth(0.1)
rect(x, y, 1, 1)
x += 1
x = pos[0]
y += 1
def draw_table(steps, pos):
x, y = pos
b = 0
count = 0
color_step = 1.0 / (steps[0] ** 2)
for i in range(steps[0]):
for j in range(steps[0]):
draw_square(steps[1], (x, y), b)
b = count * color_step
x += steps[1]
count += 1
x = pos[0]
y += steps[1]
steps = 4, 10
s = steps[0] * steps[1]
size(s, s)
draw_table(steps, (0, 0))
|
# Emily Simon
# Assignment - Lab4
# Aug 4 2019
# Imports the turtle graphics module
import turtle
# creates a turtle (pen) an sets the speed (where 0 is fastest and 10 is slowest)
# The colors can be set through their names or through hexadecimal codes, use hex for accuracy
turtle.screensize(200, 200, bg="#FFFFFF")
myPen = turtle.Turtle()
myPen.color("#000000")
myPen.speed(100)
# If you would like to slow down the animation, uncomment the next line. Higher delay, the slower it will be
#turtle.delay(100)
# setting out box sizes to the n sq pixels per box
boxSize = 10
# myPen.setheading(n) points pen to given angle direction.
# where n queals the angle (think unit circle).
# 0 points to the right, 90 to go up, 180 to go to the left 270 to go down
# Positions myPen in top left area of the screen
# This canvas is currently set to 200*200 pixels or a 20x20 box of 10 sq pixels each
def goto_origin(myPen):
myPen.home()
# This function draws a box by drawing each side of the square and using the fill function
def box(intDim):
# Can also be done with a for loop - Can you rewrite thise function as such?
myPen.begin_fill()
for i in range(4):
myPen.forward(intDim)
myPen.left(90)
myPen.end_fill()
myPen.forward(intDim)
# Here is an example of how to draw a box using the box function
# Comment these two lines out when you draw your own images
#box(boxSize)
#turtle.done()
# Challenge functions (2 bonus pts each)
# def save_image(): # saves the screen to an image/vector file
# You have a function for boxes, can you make functions for circles and triangles?
# def circle(intRadius):
# def triangle(intLength): #This can be an equilateral triangle, or not
# These are the instructions on how to move "myPen" around after drawing a box.
# penup() lifts the pen so it doesn't draw anything and can be moved freely
# pendown() puts the pen down and it draws as it moves, e.g.:
# myPen.penup()
# myPen.forward(boxSize)
# myPen.pendown()
# You will save your drawings in text files, which you will read from the art folder.
# You have two sample art pieces already saved. The first line will be a list of colors, and the
# rest of the lines will be rows of pixels, which you should read and save as a list of lists.z
# This first list stores the color values, e.g.:
# #FFFFFF,#FFFF00,#000000,#61380B,#F4FA58
# The drawings are stored using a "list of lists" structure where each value within every list
# element is the index of the color in the pallet list for that pixel
# This function will take in a filename path and load the art piece stored in that file.
# You are to parse the art into two lists, one for the color palette (first line of file),
# and a second with the pixel values (list of lists).
# The function returns both lists
def load_art(path):
with open(path, "r") as art_file:
file_list = []
for line in art_file:
if line[-1] == '\n':
line = line[:-1]
file_line = line.split (",")
file_list.append(file_line)
return file_list[0], file_list[1:]
# This function takes a pallet and pixel list (matrix) to draw the picture
# You are to write this function
def draw(pallet, pixels):
goto_origin(myPen)
for list in pixels:
for elem in list:
myPen.color(pallet[int(elem)])
box(boxSize)
myPen.penup()
myPen.right(90)
myPen.forward(boxSize)
myPen.right(90)
myPen.forward(boxSize*len(list))
myPen.right(180)
# Should give the user a list of the possible drawing pieces you have and ask which one to draw
# After drawing the piece, ask the if they would like to draw a different piece until they quit the program.
if __name__ == '__main__':
# sample for loading art and calling draw
pallet_1, pixels_1 = load_art('art/'+input("What are we drawing?")+".txt")
draw(pallet_1, pixels_1)
# You need this to prevent the window from closing after drawing
turtle.done()
|
# importing random int maker module
from random import randint
# class defines what happens when a player dies.
# in this case, it has a list of phrases to be displayed
# randomly, and returns the string 'died' to let the engine know.
class Death(object):
quips = ["You died. You kinda suck at this.",
"Your mom would be proud...",
"Such a loser.",
"I have a small puppy that's better at this.",
"Better luck next time."
# raise ValueError ('todo')
]
def enter(self):
print (Death.quips[randint(0, len(self.quips)- 1)])
return 'died'
def test_death():
test_death = Death()
test_death()
|
# interpolation between 2D cartesian points
# visualize this example here: https://www.desmos.com/calculator/lkyi2y4kbx
# tuples are a good way to represent point coordinates, since they cannot change
# these are in the format (x, y)
point_A = (20, 16)
point_B = (24, 8)
# now compute the slope of the line connecting the two points
# (y2 - y1) / (x2 - x1)
slope = (point_B[1] - point_A[1]) / (point_B[0] - point_A[0])
# this is an x-value between the x-values of point A and point B
x_value_to_interpolate = 22.5
# this finds the change in x between the interpolation point and the lower x-value of the two original points
change_in_x = x_value_to_interpolate - point_A[0]
# now multiply the change in x by the slope, to find the change in y
delta_y = change_in_x * slope
# add the original y of the first point
y = delta_y + point_A[1]
print('The interpolated value at x = %f is %f' % (x_value_to_interpolate, y))
|
# a string which contains both lower and upper case letters.
# notice the extra letter 'a' at the end of each alphabet. This is to make shifting easier.
caesar_alphabet = 'abcdefghijklmnopqrstuvwxyzaABCDEFGHIJKLMNOPQRSTUVWXYZA'
def caesar_cipher(original_string):
"""
Returns the caesar cipher for a given string
"""
# make a new string that is empty at first
new_string = ''
# go through each individual character in the original string
for character in original_string:
# check if the character is not alphabetic.
# If not, append the character as-is and move on to the next character in the string
if character not in caesar_alphabet:
new_string += character
continue
# at this point, the character is known to be alphabetic
# find the index in the alphabet string corresponding to the letter
alphabet_index = caesar_alphabet.index(character)
# find the letter one position higher in the alphabet from the current letter
shifted_letter = caesar_alphabet[alphabet_index + 1]
# append the shifted letter to the string
new_string += shifted_letter
return new_string
|
#!/usr/bin/python3
from shape3 import *
N = 50
LINE = '=' * N # It's used in drawing a line between
# individual segments.
"""
This external routine is to print out certain parameters of
some of the two- or three-dimensional geometric shapes.
"""
def Print ( name, shape, flag = True ):
print ( name, end = ': ' ); print ( shape )
print ( 'area = %.2f' % shape.area ( ) )
if flag: print ( 'perimeter = %.2f' % shape.perimeter ( ) )
else: print ( 'volume = %.2f' % shape.volume ( ) )
print ( )
"""Test rectangle objects"""
print ( '\nRectangle:' )
r1 = Rectangle ( 7.5, 2.5 ); r2 = Rectangle ( )
Print ( 'r1', r1 ); Print ( 'r2', r2 )
r2 += r1; Print ( 'r2', r2 )
print ( LINE, '\n' )
"""Test circle objects"""
print ( 'Circle:' )
c1 = Circle ( 2.5 ); c2 = Circle ( 5 )
Print ( 'c1', c1 ); Print ( 'c2', c2 )
c1 += c2; Print ( 'c1', c1 )
print ( LINE, '\n' )
"""Test triangle objects"""
print ( 'Triangle:' )
t1 = Triangle ( 5.1, 12.2, 13.3 ); Print ( 't1', t1 )
t1 += t1; Print ( 't1', t1 )
print ( LINE, '\n' )
"""Test square objects - inherited from rectangular objects"""
print ( 'Square:' )
s1 = Square ( 2.5 ); Print ( 's1', s1 )
s1 += s1; Print ( 's1', s1 )
print ( LINE, '\n' )
"""Test right-triangle objects - inherited from triangular objects"""
print ( 'Right Triangle:' )
rt1 = rightTriangle( 5, 12 ); Print ( 'rt1', rt1 )
rt1 += rt1; Print ( 'rt1', rt1 )
print ( LINE, '\n' )
"""Test equilateral-triangle objects - inherited from triangular objects"""
print ( 'Equilateral Triangle:' )
et1 = equTriangle ( 5 ); Print ( 'et1', et1 )
et1 += et1; Print ( 'et1', et1 )
print ( LINE, '\n' )
"""Test box objects - inherited from rectangle objects"""
print ( 'Box:' )
b1 = Box ( 3, 4, 5 ); Print ( 'b1', b1, False )
b1 += b1; Print ( 'b1', b1, False )
print ( LINE, '\n' )
"""Test cube objects - inherited from square objects"""
print ( 'Cube:' )
cu1 = Cube ( 2.5 ); Print ( 'cu1', cu1, False )
cu1 += cu1; Print ( 'cu1', cu1, False )
print ( LINE, '\n' )
"""Test cylinder objects - inherited from circle objects"""
print ( 'Cylinder:' )
cy1 = Cylinder ( 2.5, 5 ); Print ( 'cy1', cy1, False )
cy1 += cy1; Print ( 'cy1', cy1, False )
print ( LINE, '\n' )
"""Test cone objects - inherited from circle objects"""
print ( 'Cone:' )
co1 = Cone ( 2.5, 5 ); co2 = Cone ( 3.75, 4.25 )
Print ( 'co1', co1, False ); Print ( 'co2', co2, False )
co2 += co1; Print ( 'co2', co2, False )
print ( LINE, '\n' )
"""Test sphere objects - inherited from circle objects"""
print ( 'Sphere:' )
sp1 = Sphere ( 2.5 ); Print ( 'sp1', sp1, False )
sp1 += sp1; Print ( 'cp1', sp1, False )
print ( LINE, '\n' )
"""Test tetrahedron objects - inherited from equilateral-triangle objects"""
print ( 'Tetrahedron:' )
te1 = Tetrahedron ( 5 ); Print ( 'te1', te1, False )
te2 = Tetrahedron ( ); Print ( 'te2', te2, False )
te2 += te1; Print ( 'te2', te2, False )
|
#!/usr/bin/env python3
"""
CSCI 503 - Assignment 5 - Spring 2019
Author: Sneha Ravi Chandran
Z-ID: z1856678
Date Due: May 02, 2019
Purpose: This API implements various 3D shapes
and provides for means to determine their area,
volume and by extension allow for changes.
"""
from shape2 import *
"""
Class Name:
class Box(Rectangle)
Description:
A class representing the 3-D geometric shape Box
and inheriting from the class Rectangle. The class
contains the attribute length ,width and height, with
functions to determine, volume and surface area.
"""
class Box(Rectangle):
"""
Function Name:
__init__()
Description:
Constructor for Box class inheriting Rectangle class
taking length, width and height of the Box for the arguments.
Parameters:
length - length of the Box
width - width of the Box
height - width of the Box
Returns:
None
"""
def __init__(self, length=0, width=0, height=0):
# making use of Constructor from inherited Rectangle class to set
# length and width of top face of the box.
Rectangle.__init__(self, length, width)
# new attribute for Box
self.height = height
"""
Function Name:
area()
Description:
Method to calculate and return the surface area of
the Box whose length, width and height exists in the given instance.
Parameters:
None.
Returns:
Returns the value of area of the Box calculated using the formula
A= 2A0 + ℎ𝑃0 where A0 is the area and 𝑃0 is the perimeter of the
top of the box
"""
def area(self):
# Area = 2A0 + ℎ𝑃0 where A0 is the area and 𝑃0 is the perimeter of the box's top
# Hence its Area = 2 * Area of top face of box + height * Perimeter of top face
return (2 * Rectangle.area(self)) + (self.height * Rectangle.perimeter(self))
"""
Function Name:
volume()
Description:
Method to calculate and return the volume of
the Box whose length,width and height exists in the given instance
Parameters:
None.
Returns:
Returns the value of volume of the Box calculated using the formula
V = ℎA0 where A0 is the area of the top of the box.
"""
def volume(self):
# Volume of the box is given by product area of a top face and height.
return Rectangle.area(self)*self.height
"""
Function Name:
__iadd__()
Description:
Overloaded method for standard operator "+="
whose result is the instance of class Box with the
length, width and height of current instance and the
argument added together.
Parameters:
other - instance of the class Box to be added
together.
Returns:
Returns an instance of the class Box with dimensions
of both the intstance itself and the argument supplied
added together.
"""
def __iadd__(self, other):
return Box(self.length+other.length, self.width+other.width, self.height+self.height)
"""
Function Name:
__str__()
Description:
Method to return the string for the object instance.
Parameters:
None.
Returns:
Returns a string containing the length width and height of the Box's
instance for which it exists up to two decimal digits.
"""
def __str__(self):
return "length = %0.2f : width = %0.2f : height = %0.2f" % (self.length, self.width, self.height)
"""
Class Name:
class Cube(Square)
Description:
A class representing the 3-D geometric shape Cube
and inheriting from the class Square. The class
contains the attribute length of the side, with
functions to determine, volume and surface area.
"""
class Cube(Square):
"""
Function Name:
__init__()
Description:
Constructor for Cube class inheriting Square class
taking length of side of the Cube for the arguments.
Parameters:
length - length of the Cube
Returns:
None
"""
def __init__(self, length=0):
# All sides of the cube are the same and can be made to
# make use of the __init__ call from its superclass.
Square.__init__(self, length)
"""
Function Name:
area()
Description:
Method to calculate and return the surface area of
the Cube whose length of the side exists in the given instance
Parameters:
None.
Returns:
Returns the value of area of the Cube calculated using the formula
A= 6A0 where A0 is the area of one face of the Cube
"""
def area(self):
# A cuble has 6 square faces and hence the surface area is 6*A0.
return 6 * Square.area(self)
"""
Function Name:
volume()
Description:
Method to calculate and return the volume of
the Cube whose length of side exists in the given instance
Parameters:
None.
Returns:
Returns the value of volume of the Cube calculated using the formula
V = ℎA0 where A0 is the area of the top of the cube's face.
"""
def volume(self):
# volume of a cuble is a*a*a i.e. Area of top surface of cube * height
# since height is same as lenght or width we have
# volume = Area of top surface of cube * length
return Square.area(self)*self.length
"""
Function Name:
__iadd__()
Description:
Overloaded method for standard operator "+="
whose result is the instance of class Cube with the
length of side of cube of current instance and the
argument added together.
Parameters:
other - instance of the class Cube to be added
together.
Returns:
Returns an instance of the class Cube with the length
of side of both the intstance itself and the argument
supplied added together.
"""
def __iadd__(self, other):
# dimension of both the instances get added together and a new instance
# is created.
return Cube(self.length+other.length)
"""
Class Name:
class Cylinder(Circle)
Description:
A class representing the 3-D geometric shape Cylinder
and inheriting from the class Circle. The class
contains the attribute base radius and height, with
functions to determine, volume and surface area.
"""
class Cylinder(Circle):
"""
Function Name:
__init__()
Description:
Constructor for Cylinder class inheriting Circle class
taking radius and height of the Cylinder for the arguments.
Parameters:
radius - radius of the Cylinder
height - length of the Cylinder
Returns:
None
"""
def __init__(self, radius=0, height=0):
# Include radius component using the inherited superclass.
Circle.__init__(self, radius)
# new attribute for Cylinder
self.height = height
"""
Function Name:
area()
Description:
Method to calculate and return the surface area of
the Cylinder whose radius and height exists in the given instance
Parameters:
None.
Returns:
Returns the value of surface area of the cylinder calculated using the formula
A = 2A0 + A1 where A0 is the area of the base and A1 is the area of the
lateral surface of the cylinder. r. If 𝑃0 is the perimeter
of the base of the cylinder, then A1 = ℎ𝑃0.
"""
def area(self):
# Surface are of cylinder is sum of base ares of top and bottom and
# the curved surface area.
# 2* base are of cyliner + curved surface area -> (circumference * height)
return 2 * Circle.area(self) + Circle.perimeter(self) * self.height
"""
Function Name:
volume()
Description:
Method to calculate and return the volume of
the cylinder whose radius and height exists in the given instance
Parameters:
None.
Returns:
Returns the value of volume of the Cylinder calculated using the formula
V = ℎA0 where A0 is the area of the base of Cylinder.
"""
def volume(self):
# Volume of cylinter is product of base area and height.
return Circle.area(self)*self.height
"""
Function Name:
__iadd__()
Description:
Overloaded method for standard operator "+="
whose result is the instance of class Cylinder with the
radius and height of current instance and the
argument added together.
Parameters:
other - instance of the class Cylinder to be added
together.
Returns:
Returns an instance of the class Cylinder with dimensions
of both the intstance itself and the argument supplied
added together.
"""
def __iadd__(self, other):
# Add both components of radius and height , to a new instance.
return Cylinder(self.radius + other.radius, self.height+other.height)
"""
Function Name:
__str__()
Description:
Method to return the string for the object instance.
Parameters:
None.
Returns:
Returns a string containing the radius and height of the Cylinder's
instance for which it exists up to two decimal digits.
"""
def __str__(self):
# return string with radius and height upto two decimal digits.
return "radius = %0.2f : height = %0.2f" % (self.radius, self.height)
"""
Class Name:
class Cone(Circle)
Description:
A class representing the 3-D geometric shape Cone
and inheriting from the class Circle. The class
contains the attribute base radius and height, with
functions to determine, volume and surface area.
"""
class Cone(Circle):
"""
Function Name:
__init__()
Description:
Constructor for Cone class inheriting Circle class
takeing radius and height of the Cone for the arguments.
Parameters:
radius - radius of the Cone
height - length of the Cone
Returns:
None
"""
def __init__(self, radius=0, height=0):
Circle.__init__(self, radius)
self.height = height
"""
Function Name:
area()
Description:
Method to calculate and return the surface area of
the Cone whose radius and height exists in the given instance
Parameters:
None.
Returns:
Returns the value of surface area of the Cone calculated using the formula
A = A0 + A1 where A0 is the area of the base and and A1 is the area of the
lateral surface of the cone.
"""
def area(self):
# total surface area of cone is given by sum of base area and lateral surface area
return Circle.area(self) + 0.5*Circle.perimeter(self)*((self.radius**2)+(self.height**2))**(0.5)
"""
Function Name:
volume()
Description:
Method to calculate and return the volume of
the cylinder whose radius and height exists in the given instance
Parameters:
None.
Returns:
Returns the value of volume of the Cylinder calculated using the formula
V = (1/3)ℎA0 where A0 is the area of the base of Cylinder.
"""
def volume(self):
# Volume of cone is one-third product of base area and height.
return (1/3)*Circle.area(self)*self.height
"""
Function Name:
__iadd__()
Description:
Overloaded method for standard operator "+="
whose result is the instance of class Cone with the
radius and height of current instance and the
argument added together.
Parameters:
other - instance of the class Cone to be added
together.
Returns:
Returns an instance of the class Cone with dimensions
of both the intstance itself and the argument supplied
added together.
"""
def __iadd__(self, other):
# Add both components of radius and height , to a new instance.
return Cone(self.radius + other.radius, self.height+other.height)
"""
Function Name:
__str__()
Description:
Method to return the string for the object instance.
Parameters:
None.
Returns:
Returns a string containing the radius and height of the Cone's
instance for which it exists up to two decimal digits.
"""
def __str__(self):
# return string with radius and height upto two decimal digits.
return "radius = %0.2f : height = %0.2f" % (self.radius, self.height)
"""
Class Name:
class Sphere(Circle)
Description:
A class representing the 3-D geometric shape Sphere
and inheriting from the class Circle. The class
contains the attribute base radius, with
functions to determine, volume and surface area.
"""
class Sphere(Circle):
"""
Function Name:
__init__()
Description:
Constructor for Sphere class inheriting Circle class
taking radius of the Sphere for the arguments.
Parameters:
radius - radius of the Sphere
Returns:
None
"""
def __init__(self, radius=0):
# Initialize radius attribute, inherited from Circle class.
self.radius = radius
"""
Function Name:
area()
Description:
Method to calculate and return the surface area of
the Sphere whose radius exists in the given instance
Parameters:
None.
Returns:
Returns the value of surface area of the Sphere calculated using the formula
A = 4A0 where A0 is the area of the sphere where the cross-section is the
largest.
"""
def area(self):
# Surface area is 4 times largest cross sectional area.
return 4*Circle.area(self)
"""
Function Name:
volume()
Description:
Method to calculate and return the volume of
the Sphere whose radius exists in the given instance
Parameters:
None.
Returns:
Returns the value of volume of the Sphere calculated using the formula
V = (4/3)rA0 where A0 is the area of the sphere where the cross-section is the
largest.
"""
def volume(self):
# Returns volume which four-third the product of largest cross sectional area
# and radius of sphere
return (4/3) * Circle.area(self) * self.radius
"""
Function Name:
__iadd__()
Description:
Overloaded method for standard operator "+="
whose result is the instance of class sphere with the
radius of current instance and the
argument added together.
Parameters:
other - instance of the class sphere to be added
together.
Returns:
Returns an instance of the class sphere with dimensions
of both the intstance itself and the argument supplied
added together.
"""
def __iadd__(self, other):
# Add both components of radius to a new instance.
return Sphere(self.radius + other.radius)
"""
Class Name:
class Tetrahedron(equTriangle)
Description:
A class representing the 3-D geometric shape Tetrahedron
and inheriting from the class equTriangle. The class
contains the attribute side of the Tetrahedron, with
functions to determine, volume and surface area.
"""
class Tetrahedron(equTriangle):
"""
Function Name:
__init__()
Description:
Constructor for Cube class inheriting equTriangle class
taking length of side of the Tetrahedron for the arguments.
Parameters:
length - length of the side of the Tetrahedron.
Returns:
None
"""
def __init__(self, a=0):
# A tetrahedron consists of four equilateral triangles taking the sides
# of the tetrahedron.
equTriangle.__init__(self, a)
"""
Function Name:
area()
Description:
Method to calculate and return the surface area of
the Tetrahedron whose length of the side exists in the given instance
Parameters:
None.
Returns:
Returns the value of area of the Tetrahedron calculated using the formula
A= 4A0 where A0 is the area of one of the faces of the Tetrahedron.
"""
def area(self):
# Area is area of all the faces of tetrahedron that, i.e. the
# equilateral triangles that constitute the tetrahedron.
return 4*equTriangle.area(self)
"""
Function Name:
volume()
Description:
Method to calculate and return the volume of
the Tetrahedron whose length of side exists in the given instance
Parameters:
None.
Returns:
Returns the value of volume of the Tetrahedron calculated using the formula
V = (1/3)hA0, where A0 is the area of one of the faces of the tetrahedron.
"""
def volume(self):
# Area is one third the product of base area of one face and height of
# tetrahedron.
return (1/3) * equTriangle.area(self) * ((2/3)**0.5)*self.a
"""
Function Name:
__iadd__()
Description:
Overloaded method for standard operator "+="
whose result is the instance of class Cube with the
length of side of Tetrahedron of current instance and the
argument added together.
Parameters:
other - instance of the class Tetrahedron to be added
together.
Returns:
Returns an instance of the class Tetrahedron with the length
of side of both the intstance itself and the argument
supplied added together.
"""
def __iadd__(self, other):
# Add both components of side to a new instance.
return Tetrahedron(self.a + other.a)
|
def collatz(n):
dictCollatz, keyMaxTraject = {}, 1
for i in range(n):
chisloK, pathLength = i + 1, 0
while chisloK:
if not chisloK in dictCollatz and chisloK != 1:
if not chisloK % 2:
chisloK //= 2
else:
chisloK = 3 * chisloK + 1
pathLength += 1
else:
if chisloK == 1:
dictCollatz.update({i + 1: pathLength})
else:
pathLength += dictCollatz[chisloK]
dictCollatz.update({i + 1: pathLength})
chisloK = 0
if dictCollatz[keyMaxTraject] < pathLength:
keyMaxTraject = i
tupleCollatz = (keyMaxTraject, dictCollatz[keyMaxTraject])
return tupleCollatz
if __name__ == "__main__":
tupleCollatz = collatz(1000000)
print(tupleCollatz)
|
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def check(self, advantage):
try:
for n in advantage:
if n == '{':
self.push('{')
if n == '(':
self.push('(')
if n == '[':
self.push('[')
if n == '}':
self.items.remove('{')
if n == ')':
self.items.remove('(')
if n == ']':
self.items.remove('[')
element = self.size()
if element == 0:
print("Сбалансировано")
else:
self.items.clear()
print("Несбалансировано")
except IndexError:
self.items.clear()
print("Несбалансировано")
except ValueError:
self.items.clear()
print("Несбалансировано")
def specularity(self, string):
for item in string:
self.items.append(item)
run = self.size()
if (run % 2) == 0 and run != 0:
print('проверка на зеркальность:')
while run != 0:
left = self.items.pop()
right = self.items.pop(0)
if right == '(' and left == ')':
run = run - 2
elif right == '[' and left == ']':
run = run - 2
elif right == '{' and left == '}':
run = run - 2
else:
break
if self.size() == 0:
print("Выполняется зеркальность")
else:
self.items.clear()
print("Зеркальность не выполняется")
else:
self.items.clear()
print("Зеркальность не выполняется")
test = Stack()
print('\n Проверка (((([{}])))) \n')
test.specularity('(((([{}]))))')
test.check('(((([{}]))))')
print('\n Проверка [([])((([[[]]])))]{()} \n')
test.specularity('[([])((([[[]]])))]{()}')
test.check('[([])((([[[]]])))]{()}')
print('\n Проверка {{[()]}} \n')
test.specularity('{{[()]}}')
test.check('{{[()]}}')
print('\n Проверка }{} \n')
test.specularity('}{}')
test.check('}{}')
print('\n Проверка {{[(])]}} \n')
test.specularity('{{[(])]}}')
test.check('{{[(])]}}')
print('\n Проверка [[{())}] \n')
test.specularity('[[{())}]')
test.check('[[{())}]')
|
# Btree data structure and methods for manipulating same to be find unique
# subsequences and their successors.
class BNode:
# Canonical key order
KEY_ORDER = []
##########################################################################
def __init__(self, key_in_parent=None):
# Key in parent is used to find the next sibling. For root, it's None
self.key_in_parent = key_in_parent
self.children = {}
##########################################################################
# Returns true if we are a root (key_in_parent == None)
def is_root(self):
return (self.key_in_parent == None)
##########################################################################
# Returns true if we are a leaf (data exists in dir(self))
def is_leaf(self):
return ('data') in dir(self)
##########################################################################
# Peel off the next item of the key and pass the data on down recursively,
# creating new children as we go, until we bottom out (len(key_list) == 0)
# then insert the data into a leaf.
# Make a defensive copy of the key_list, it will be modified!
def insert_data(self, key_list, data):
if (len(key_list) == 0):
# If this is the base case, that's it: we're the leaf
self.data = data
else:
# Peel off the key and add to the list
next_key = key_list[0]
key_list.remove(next_key)
new_node = BNode(next_key)
new_node.parent = self
new_node.key_in_parent = next_key
self.children[next_key] = new_node
new_node.insert_data(key_list, data)
##########################################################################
# Find the data corresponding to the given key list, if it exists in tree
# Return the node where the data is (if node.data != None)
# or where the data would be (if node.data == None)
# or None if the key is not found
def find_data(self, key_list):
if (len(key_list) == 0):
# We are the leaf, and have been found!
return self
# Peel off the next item in the key
next_key = key_list[0]
next_child = None
if (next_key in self.children.keys()):
next_child = self.children[next_key]
key_list.remove(next_key)
# Recursively find the next child
next_child = next_child.find_data(key_list)
return next_child
#########################################################################
def __str__(self):
if (self.key_in_parent != None):
label = str(self.key_in_parent)
else:
label = "Root"
string = label + ": " + str(self.children.keys()) + " "
if ('data' in dir(self)):
string += str(self.data)
return string
#########################################################################
def get(self, key):
return self.children[key]
#########################################################################
# Returns the next sibling to the child with the given key, if any exists
# according to canonical key order.
# Otherwise returns None
def find_next_child(self, key):
children_keys = self.children.keys()
if ((key not in children_keys) or (key not in BNode.KEY_ORDER)):
return None
index1 = BNode.KEY_ORDER.index(key)
# Initially set next_index to invalid value
next_index = len(BNode.KEY_ORDER)
for key2 in BNode.KEY_ORDER:
if (key2 not in children_keys):
continue
index2 = BNode.KEY_ORDER.index(key2)
if ((index2 > index1) and (index2 < next_index)):
# Update the next index if we find one that's closer
next_index = index2
if (next_index != len(BNode.KEY_ORDER)):
# If we've updated, then that means key2 must be in children_keys
return self.children[BNode.KEY_ORDER[next_index]]
else:
return None
##########################################################################
# Find the leftmost child of the given node in the canonical KEY_ORDER
# Return None otherwise
def find_leftmost_child(self):
for key in BNode.KEY_ORDER:
if (key in self.children.keys()):
return self.children[key]
# Otherwise, there are no children, return None
return None
##########################################################################
# Returns the successor in lexicographic order of the key list,
# going as far back as the root
def find_successor(self):
current_node = self
while (not current_node.is_root()):
sibling = current_node.parent.find_next_child(current_node.key_in_parent)
# Check if we have no sibling, if so, go up one more level
if (sibling == None):
current_node = current_node.parent
else:
break
if (sibling == None):
# If we can't find a next sibling, this is the lexicographically
# last node
return None
else:
# Else traverse the leftmost child of the sibling until we get to
# leaf
current_node = sibling
while (not current_node.is_leaf()):
current_node = current_node.find_leftmost_child()
return current_node
|
import pyhop
"""
HELPER FUNCTIONS
"""
def is_done(state, a):
"""Checks current state of domain for whether the player has reached the goal"""
if state.x[a] == state.goal_x[a] and state.y[a] == state.goal_y[a]:
return True
else:
return False
def is_dead_end(state, a):
"""Checks current state of domain for whether the player has reached a dead end"""
paths = 0
if state.maze.cell_at(state.x[a], state.y[a]).has_wall('N'):
paths += 1
elif state.maze.cell_at(state.x[a], state.y[a]).has_wall('S'):
paths += 1
elif state.maze.cell_at(state.x[a], state.y[a]).has_wall('E'):
paths += 1
elif state.maze.cell_at(state.x[a], state.y[a]).has_wall('W'):
paths += 1
if paths > 1 and state.x[a] != 0 and state.y[a] != 0:
return False
else:
return True
def status(state, a):
"""Checks current state and returns a message if player is either done or in a dead end"""
if is_done(state, a):
return 'done'
elif is_dead_end(state, a):
return 'dead_end'
"""
METHODS
"""
# Methods for FindGoal
def walk(state, a):
"""If player has not reached goal, walk in a single direction"""
if status(state, a) == 'done':
return []
else:
return [('WalkTask', a)]
pyhop.declare_methods('FindGoal', walk)
# Methods for WalkTask
def north(state, a):
"""Walk 1 unit north, then recurse for next direction"""
return [('up', a), ('FindGoal', a)]
def south(state, a):
"""Walk 1 unit south, then recurse for next direction"""
return [('down', a), ('FindGoal', a)]
def west(state, a):
"""Walk 1 unit west, then recurse for next direction"""
return [('left', a), ('FindGoal', a)]
def east(state, a):
"""Walk 1 unit east, then recurse for next direction"""
return [('right', a), ('FindGoal', a)]
pyhop.declare_methods('WalkTask', south, north, west, east)
|
# Task 1
if __name__ == "__main__":
# Number of test cases
test_cases = int(input())
# Iterate through each of the test cases
for i in range(test_cases):
# Get the number of patients in the case
noPatients = int(input())
# Iterate through each patient
# Create an array to store the intervals available
intervals = []
for j in range(noPatients):
patient = input().split(" ")
intervals.append((int(patient[0]), int(patient[1]), j + 1))
# Sort the intervals by start date
intervals_sorted = sorted(intervals, key=lambda x: (x[1] - x[0], x[0]))
# Create placeholder arrays for the occupied days and what day each patient is on
occupied = []
schedule = noPatients * [0]
for interval in intervals_sorted:
for j in range(interval[0], interval[1] + 1):
if j not in occupied:
occupied.append(j)
schedule[interval[2]-1] = j
break
if len(occupied) == noPatients:
print(' '.join(str(i) for i in schedule))
else:
print('impossible')
|
print('Programa que muestra todos los numeros pares positivos hasta el numero introducido por el usuario',end='\n')
numero = int(input('Ingrese N >>> '))
for i in range(numero):
if i%2==0:
print(i,end=' ')
|
# Common Ground
#
# Consider the strings "Tapachula" and "Temapache", both of which name
# towns in the country of Mexico. They share a number of substrings in
# common. For exmaple, "T" and "pa" can be found in both. The longest
# common unbroken substring that they both share is "apach" -- it starts
# at position 1 in "Tapachula" and at position 3 in "Temapache". Note that
# "Tapach" is not a substring common to both: even though "Temapache"
# contains both "T" and "apach", it does not contain the unbroken substring
# "Tapach".
#
# Finding the longest common substring of two strings is an important
# problem in computer science. It is a building block to related problems,
# such as "sequence alignment" or "greatest common subsequence" that are
# used in problem domains as diverse as bioinformatics and making spelling
# checkers.
#
# We will use memoization, recursion and list comprehensions to tackle this
# problem. In particular, we will build up a chart that stores computed
# partial answers.
#
# To make the problem a bit easier, we'll start by computing the longest
# common *suffix* of two strings. For example, "Tapachula" and "Temapache"
# have no common suffix -- or a common suffix of length 0, if you prefer.
# By contrast, "Tapach" and "Temapach" have a longest common suffix of
# length 5 ("apach"). One way to reason to that is that their last letters
# match (an "h" in both cases) -- and if you peel those last letters off
# the smaller problem of "Temapac" vs. "Tapac" has a common suffix of size
# four.
#
# Write a memoized procedure csuffix(X,Y) that returns the size of the
# longest common suffix of two strings X and Y. This is 0 if X and Y have
# different final letters. Otherwise, it is 1 plus csuffix() of X and Y,
# each with that common last letter removed. Use a global dictionary chart
# that maps (X,Y) pairs to their longest common suffix values to avoid
# recomputing work. If either X or Y is the empty string, csuffix(X,Y) must
# return 0.
#
# Once we have csuffix(), we can find the largest common substring of X and
# Y by computing the csuffix() of all possible combinations of *prefixes*
# of X and Y and returning the best one. Write a procedure prefixes(X) that
# returns a list of all non-empty strings that are prefixes of X. For
# example, prefixes("cat") == [ "c", "ca", "cat" ].
#
# Finally, write a procedure lsubstring(X,Y) that returns the length of the
# longest common substring of X and Y by considering all prefixes x of X
# and all prefixes y of Y and returning the biggest csuffix(x,y)
# encountered.
# Hint 1. Reminder: "hello"[-1:] == "o"
#
# Hint 2. Reminder: "goodbye"[:-1] == "goodby"
#
# Hint 3. prefixes(X) can be written in one line with list comprehensions.
# Consider "for i in range(len(X))".
#
# Hint 4. max([5,-2,8,3]) == 8
#
# Hint 5. You can "comprehend" two lists at once!
# [ (a,b) for a in [1,2] for b in ['x','y'] ]
# == [(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y')]
# This is by no means necessary, but it is convenient.
chart = { }
def csuffix(X,Y):
if (X, Y) in chart:
return chart[(X, Y)]
if (X[-1:] != Y[-1:]) or (X == '') or (Y == ''):
chart[(X, Y)] = 0
return chart[(X, Y)]
result = 1 + csuffix(X[:-1], Y[:-1])
chart[(X, Y)] = result
return result
def prefixes(X):
return [X[:i] for i in range(len(X) + 1)]
def lsubstring(X,Y):
return max([csuffix(px, py) for px in prefixes(X) for py in prefixes(Y)])
# We have included some test cases. You will likely want to write your own.
print lsubstring("Tapachula", "Temapache") == 5 # Mexico, "apach"
print chart[("Tapach","Temapach")] == 5
print lsubstring("Harare", "Mutare") == 3 # Zimbabwe, "are"
print chart[("Harare","Mutare")] == 3
print lsubstring("Iqaluit", "Whitehorse") == 2 # Canada, "it"
print chart[("Iqaluit","Whit")] == 2
print lsubstring("Prey Veng", "Svay Rieng") == 3 # Cambodia, "eng"
print chart[("Prey Ven","Svay Rien")] == 2
print chart[("Prey Veng","Svay Rieng")] == 3
print lsubstring("Aceh", "Jambi") == 0 # Sumatra, ""
print chart[("Aceh", "Jambi")] == 0
|
# ----------
# User Instructions:
#
# Create a function compute_value() which returns
# a grid of values. Value is defined as the minimum
# number of moves required to get from a cell to the
# goal.
#
# If it is impossible to reach the goal from a cell
# you should assign that cell a value of 99.
# ----------
grid = [[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']
cost_step = 1 # the cost associated with moving from a cell to an adjacent one.
# ----------------------------------------
# insert code below
# ----------------------------------------
def compute_value():
value = [[99 for c in range(len(grid[0]))] for r in range(len(grid))]
value[goal[0]][goal[1]] = 0
open = [[0, goal[0], goal[1]]]
while len(open) > 0:
open.sort()
open.reverse()
c = open.pop()
x = c[1]
y = c[2]
d = c[0]
for i in range(len(delta)):
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and y2 >= 0 and x2 < len(grid) and y2 < len(grid[0]) and grid[x2][y2] == 0:
d2 = d + cost_step
if value[x2][y2] > d2:
value[x2][y2] = d2
open.append([d2, x2, y2])
return value #make sure your function returns a grid of values as demonstrated in the previous video.
v = compute_value()
for r in v:
print r
|
# -----------------
# User Instructions
#
# Write a function, bsuccessors(state), that takes a state as input
# and returns a dictionary of {state:action} pairs.
#
# A state is a (here, there, t) tuple, where here and there are
# frozensets of people (indicated by their times), and potentially
# the 'light,' t is a number indicating the elapsed time.
#
# An action is a tuple (person1, person2, arrow), where arrow is
# '->' for here to there or '<-' for there to here. When only one
# person crosses, person2 will be the same as person one, so the
# action (2, 2, '->') means that the person with a travel time of
# 2 crossed from here to there alone.
def bsuccessors(state):
"""Return a dict of {state:action} pairs. A state is a (here, there, t) tuple,
where here and there are frozensets of people (indicated by their times) and/or
the 'light', and t is a number indicating the elapsed time. Action is represented
as a tuple (person1, person2, arrow), where arrow is '->' for here to there and
'<-' for there to here."""
result = {}
here, there, t = state
if 'light' in here:
for p1 in [_ for _ in here if _ != 'light']:
for p2 in [_ for _ in here if _ != 'light']:
a = (p1, p2, '->')
t_here = frozenset([p for p in here if p != p1 and p != p2 and p != 'light'])
t_there = frozenset([p for p in there] + [p1] + [p2] + ['light'])
t_t = t + max(p1, p2)
result[(t_here, t_there, t_t)] = a
else:
for p1 in [_ for _ in there if _ != 'light']:
for p2 in [_ for _ in there if _ != 'light']:
a = (p1, p2, '<-')
t_there = frozenset([p for p in there if p != p1 and p != p2 and p != 'light'])
t_here = frozenset([p for p in here] + [p1] + [p2] + ['light'])
t_t = t + max(p1, p2)
result[(t_here, t_there, t_t)] = a
return result
def test():
assert bsuccessors((frozenset([1, 'light']), frozenset([]), 3)) == {
(frozenset([]), frozenset([1, 'light']), 4): (1, 1, '->')}
assert bsuccessors((frozenset([]), frozenset([2, 'light']), 0)) =={
(frozenset([2, 'light']), frozenset([]), 2): (2, 2, '<-')}
return 'tests pass'
print test()
|
#Spelling Correction
#Double Gold Star
#For this question, your goal is to build a step towards a spelling corrector,
#similarly to the way Google used to respond,
# "Did you mean: audacity"
#when you searched for "udacity" (but now considers "udacity" a real word!).
#One way to do spelling correction is to measure the edit distance between the
#entered word and other words in the dictionary. Edit distance is a measure of
#the number of edits required to transform one word into another word. An edit
#is either: (a) replacing one letter with a different letter, (b) removing a
#letter, or (c) inserting a letter. The edit distance between two strings s and
#t, is the minimum number of edits needed to transform s into t.
#Define a procedure, edit_distance(s, t), that takes two strings as its inputs,
#and returns a number giving the edit distance between those strings.
#Note: it is okay if your edit_distance procedure is very expensive, and does
#not work on strings longer than the ones shown here.
#The built-in python function min() returns the mininum of all its arguments.
#print min(1,2,3)
#>>> 1
def edit_distance(s, t):
dist = [[0 for c in range(len(s) + 1)] for r in range(len(t) + 1)]
for r in range(len(dist)):
dist[r][0] = r
for c in range(len(dist[0])):
dist[0][c] = c
for c in range(1, len(dist[0])):
for r in range(1, len(dist)):
if s[c-1] == t[r-1]:
dist[r][c] = dist[r-1][c-1]
else:
d = dist[r-1][c] + 1 # deletion
i = dist[r][c-1] + 1 # insertion
b = dist[r-1][c-1] + 1 # substitution
dist[r][c] = min(d, i, b)
return dist[len(t)][len(s)]
#For example:
# Delete the 'a'
print edit_distance('audacity', 'udacity')
#>>> 1
# Delete the 'a', replace the 'u' with 'U'
print edit_distance('audacity', 'Udacity')
#>>> 2
# Five replacements
print edit_distance('peter', 'sarah')
#>>> 5
# One deletion
#print edit_distance('pete', 'peter')
#>>> 1
|
#Lecture 5: Clustering Coefficient Code
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = 1
return G
flights = [("ORD", "SEA"), ("ORD", "LAX"), ('ORD', 'DFW'), ('ORD', 'PIT'),
('SEA', 'LAX'), ('LAX', 'DFW'), ('ATL', 'PIT'), ('ATL', 'RDU'),
('RDU', 'PHL'), ('PIT', 'PHL'), ('PHL', 'PVD')]
G = {}
for (x,y) in flights: make_link(G,x,y)
def clustering_coefficient(G,v):
neighbors = G[v].keys()
if len(neighbors) == 1: return -1.0
links = 0
for w in neighbors:
for u in neighbors:
if u in G[w]: links += 0.5
return 2.0*links/(len(neighbors)*(len(neighbors)-1))
print clustering_coefficient(G,"ORD")
total = 0
for v in G.keys():
total += clustering_coefficient(G,v)
print total/len(G)
#Lecture 7: Connected Components Code:
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = 1
return G
connections = [('a', 'g'), ('a', 'd'), ('d', 'g'), ('g', 'c'), ('b', 'f'),
('f', 'e'), ('e', 'h')]
G = {}
for (x,y) in connections: make_link(G,x,y)
###################################################################
# Transversal...
# Call this routine on nodes being visited for the first time
def mark_component(G, node, marked):
marked[node] = True
total_marked = 1
for neighbor in G[node]:
if neighbor not in marked:
total_marked += mark_component(G, neighbor, marked)
return total_marked
def list_component_sizes(G):
marked = {}
for node in G.keys():
if node not in marked:
print "Component containing", node, ": ", mark_component(G, node, marked)
list_component_sizes(G)
#Lecture 9: Checking Pairwise Connectivity (Solution)
def mark_component(G, node, marked):
marked[node] = True
total_marked = 1
for neighbor in G[node]:
if neighbor not in marked:
total_marked += mark_component(G, neighbor, marked)
return total_marked
def check_connection(G, v1, v2):
marked = {}
mark_component(G, v1, marked)
return v2 in marked
#Lecture 17: BFS Code
import csv
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = 1
return G
def read_graph(filename):
# Read an undirected graph in CSV format. Each line is an edge
tsv = csv.reader(open(filename), delimiter='\t')
G = {}
for (node1, node2) in tsv: make_link(G, node1, node2)
return G
# Read the marvel comics graph
marvelG = read_graph('uniq_edges.tsv')
# distance from start (original)
def distance(G, v1, v2):
distance_from_start = {}
open_list = [v1]
distance_from_start[v1] = 0
while len(open_list) > 0:
current = open_list[0]
del open_list[0]
for neighbor in G[current].keys():
if neighbor not in distance_from_start:
distance_from_start[neighbor] = distance_from_start[current] + 1
if neighbor == v2: return distance_from_start[v2]
open_list.append(neighbor)
return False
# path from start (after modification on distance())
def path(G, v1, v2):
#distance_from_start = {}
path_from_start = {} # modification
open_list = [v1]
#distance_from_start[v1] = 0
path_from_start[v1] = [v1] # modification
while len(open_list) > 0:
current = open_list[0]
del open_list[0]
for neighbor in G[current].keys():
#if neighbor not in distance_from_start:
if neighbor not in path_from_start: # modification
#distance_from_start[neighbor] = distance_from_start[current] + 1
path_from_start[neighbor] = path_from_start[current]
+ [neighbor] # modification
#if neighbor == v2: return distance_from_start[v2]
if neighbor == v2: return path_from_start[v2] # modification
open_list.append(neighbor)
return False
from_node = "A"
to_node = "ZZZAX"
print distance(marvelG, from_node, to_node)
print path(marvelG, from_node, to_node)
#Lesson 19: Centrality
def centrality(G, v):
distance_from_start = {}
open_list = [v]
distance_from_start[v] = 0
while len(open_list) > 0:
current = open_list[0]
del open_list[0]
for neighbor in G[current].keys():
if neighbor not in distance_from_start:
distance_from_start[neighbor] = distance_from_start[current] + 1
open_list.append(neighbor)
return float(sum(distance_from_start.values()))/len(distance_from_start)
|
# Writing Reductions
# We are looking at chart[i] and we see x => ab . cd from j.
# Hint: Reductions are tricky, so as a hint, remember that you only want to do
# reductions if cd == []
# Hint: You'll have to look back previously in the chart.
def reductions(chart, i, x, ab, cd, j):
# x -> ab * cd from j
# chart[j] has y -> * x from k
return [(jstate[0], jstate[1] + [x], jstate[2][1:], jstate[3]) for jstate in chart[j] if cd == [] and jstate[2] <> [] and jstate[2][0] == x]
chart = {0: [('exp', ['exp'], ['+', 'exp'], 0), ('exp', [], ['num'], 0), ('exp', [], ['(', 'exp', ')'], 0), ('exp', [], ['exp', '-', 'exp'], 0), ('exp', [], ['exp', '+', 'exp'], 0)], 1: [('exp', ['exp', '+'], ['exp'], 0)], 2: [('exp', ['exp', '+', 'exp'], [], 0)]}
print reductions(chart,2,'exp',['exp','+','exp'],[],0) == [('exp', ['exp'], ['-', 'exp'], 0), ('exp', ['exp'], ['+', 'exp'], 0)]
|
#Complete the median function to make it return the median of a list of numbers
data1=[1, 2, 5, 10, -20]
def median(data):
#Insert your code here
m = len(data) / 2
return sorted(data)[m]
print median(data1)
|
print("*********************************************\n")
print(" "*10+"\033[1;96;40mRemoving Punctuations\033[0m \n")
print("*********************************************\n")
usr = input("\033[1;34;40mEnter a string with punctuatuions: \033[0m").lower()
punc = ['!','/','(',')',',','-','[',']','{','}',';',':','\\','<','>','.','\/','?','@','#','$','%','^','&','*','_','~']
string2 = ''
for letter in usr:
if letter not in punc:
string2 += letter
print("\n\033[1;36;40mEntered string without punctuations:\033[0m\r")
print(string2)
|
print("***********************************",'\n')
print(" "*10+"\033[1;34;40mPalindrome Test\033[0m\n")
print("***********************************")
#header with allignment and coloured text
usr = input("Enter a string: ")
#accepting user string
rev = ''
#initailising a rev variable(to store reverse) to null
flag = False
#flag to indicate if the string is palindrome, initialised to Flase
for i in range(len(usr)-1,-1,-1):
rev += usr[i]
#loop to obtain reverse of the user string
print("Reverse is: ",rev,end=' ')
#printing reversed string
for i in range(len(usr)):
if rev[i] == usr[i]:
flag = True #when the comparison is a hit, flag is set to true
else: flag = False #else it is false
#comparing actual string to the reversed string
if flag == False: print("which is \033[1;91;40mnot a palindrome\033[0m") #printing not a palindrome if flag is false
else: print("which is a \033[1;92;40mpalindrome\033[0m") #printing: it is a palindrome if flag is true
#result:✔
#$ py ml_4_StringPalidrome_check.py
#***********************************
# Palindrome Test
#***********************************
#Enter a string: Nurses run
#Reverse is: nur sesrun which is a palindrome
#2
#***********************************
# Palindrome Test
#***********************************
#Enter a string: 1010101
#Reverse is: 1010101 which is a palindrome
#3
#$ py ml_4_StringPalidrome_check.py
#***********************************
# Palindrome Test
#***********************************
#Enter a string: oporop
#Reverse is: poropo which is not a palindrome
|
# this code is showing comment and print basic variable
"""
this is docstring i don't know how to
use it properly i will learn about it
"""
first = 3
second = 5
sum_of_both = first + second
print(sum_of_both)
name = 'anshul'
surname = 'gera'
fullname = "my name is " + name + " "+ surname
print(fullname)
def unique(list1):
# intilize a null list
unique_list = []
# traverse for all elements
for x in list1:
# check if exists in unique_list or not
if x not in unique_list:
unique_list.append(x)
# print list
for x in unique_list:
print (x)
store = [2, 3, 1, 4, 5, 5, 6, 7, 7]
store.sort()
store.reverse()
print(unique(store))
|
import re
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
if re.match(r'^\d{3}\-\d{3,8}$', '010-12345') :
print 'ok'
else:
print 'failed'
print re.split(r'\s+', 'a b c')
print re.split(r'[\s\,]+', 'a,b, c d')
print re.split(r'[\s\,\;]+','a,b;c d')
#Group regex
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print m.group(0)
print m.group(1)
print m.group(2)
print re.match(r'^(\d+)(0*)$','102300').groups()
print re.match(r'^(\d+?)(0*)$','102300').groups()
print re_telephone.match('010-12345').groups()
print re_telephone.match('012-1234567').groups()
|
from collections import Iterable
age=20
if age >= 6:
print 'teenager'
elif age >=18:
print 'adult'
else:
print 'kid'
names=['a','b','c']
for name in names:
print name
sum=0
for x in range(101):
sum = sum + x
print sum
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print sum
def my_abs(x):
if not isinstance(x,(int)):
raise TypeError('bad')
if x>=0:
return x
else:
return -x
print my_abs(-6)
#my_abs('abc')
import math
def move(x,y,step,angle=0):
nx= x + step*math.cos(angle)
ny= y - step*math.sin(angle)
return nx,ny
x,y=move(100,100,60,math.pi/6)
print x,y
def enroll(name,gendar,age=6,city="beijign"):
print 'name:',name
print 'gendar:',gendar
print 'age:',age
print 'city:',city
enroll('kk','M')
enroll('mm','f',7)
enroll('ppp','M',city='tinajin')
#可变参数
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
print calc(1,2)
print calc(1,2,3)
nums=[1,2,3,4]
print calc(*nums)
#关键字参数
def person(name,age,**kw):
print 'name:',name,'age:',age,'other:',kw
person('aaa',20)
#递归
def fact(n):
if n == 1:
return 1
return n*fact(n-1)
print fact(5)
print fact(100)
#切片
L = range(100)
print L
print L[:10]
print L[-10:]
print L[10:20]
print L[:10:2]
print L[::5]
print L[:]
print (0,1,2,3,4,5)[:3]
print 'abcdefg'[:3]
print 'abcdefg'[::2]
#迭代
d={'a':1,'b':2,'c':3}
for key in d:
print key
for value in d.itervalues():
print value
for k,v in d.iteritems():
print 'k:',k,"v:",v
#是否可迭代
print isinstance('abc',Iterable)
#列表生成式
print [x*x for x in range(1,11)]
print [x*x for x in range(1,11) if x % 2 == 0]
#两层循环
print [m + n for m in 'abc' for n in 'xyz']
import os
print [d for d in os.listdir('.')]
dd = {'x':'1','y':'2','z':'3'}
print [k + '=' + v for k,v in dd.iteritems()]
LL = ['Hello','World']
print [s.lower() for s in LL]
#生成器
g=(x*x for x in range(10))
print g.next()
for x in g:
print x
def fib(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b=b,a+b
n = n + 1
print '======================'
for n in fib(10):
print n
|
from collections import deque
def solution(priorities, location):
# 대기목록의 중요도와 인덱스를 튜플로 같이 저장한다
order = deque([(n, idx) for idx, n in enumerate(priorities)])
q = [] # q = 최종 인쇄 순서
while len(order) != 1: # 마지막 한개만 남을 때까지
# 만약 현재 중요도보다 더 큰 중요도가 있으면 뒤로 넘기고, 아니면 q에 추가
now = order.popleft()
priority, idx = now
maxi = max(order)[0]
if maxi > priority:
order.append(now)
else:
q.append(now)
# 마지막 남은 한개도 q에 추가
q.append(order.popleft())
# 기존 location과 일치하는 인덱스를 찾으면 해당 인덱스 리턴
for i in range(len(q)):
p, idx = q[i]
if idx == location:
print(i+1)
return i+1
solution([2, 1, 3, 2], 2)
solution([1, 1, 9, 1, 1, 1], 0)
|
import numpy as np
X = np.array([3,1,8,6,0])
def softmax(X):
Y = np.exp(X)
return Y/np.sum(Y)
print("argmax :",np.argmax(X))
p = softmax(X)
for i in range(len(X)):
print("p[{:d}] = {:.4f}".format(i,p[i]) )
|
import numpy as np
import matplotlib.pyplot as plt
# ----------------------------------------------------
# 1. Un exemple
def f(x):
return np.exp(-x**2)
a,b = -3,3
X = np.linspace(a,b,num=100)
Y = f(X)
plt.plot(X,Y)
# plt.savefig('pythonx-gauss.png')
plt.show()
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#------------------------------------------
# Newton
#------------------------------------------
# La fonction f(x)
def f(x):
return x**3 - 100
# La fonction dérivée f'(x)
def df(x):
return 3*(x**2)
# Méthode de Newton
# x0 est le terme initial, n est le nombre d'étapes
def newton(x0,n):
x = x0
for i in range(1,n+1):
x = x - f(x)/df(x)
# print("Etape ", i, " : ",x,"Erreur :",x-100**(1/3))
# print("Etape ", i, " : ",x,"Erreur :",x-100**(1/3))
return x
print("Calcul de racine cubique de 100 par la méthode de Newton")
print(newton(10,9))
#------------------------------------------
# Newton
#------------------------------------------
# Calcul de racine cubique de 100 avec 1000 décimales
# Module décimale pour avoir une grande précision
from decimal import *
# Precision souhaitée (par exemple 1010 décimales pour éviter les erreurs d'arrondi)
getcontext().prec = 1010
# Cas de la racine carrée sqrt(a)
# n est le nombre d'itérations
def newton_bis(x0,n):
x = Decimal(x0)
for i in range(1,n+1):
x = x - f(x)/df(x)
# print("Etape ", i, " : ", x)
# print("Etape ", i, " : ",x,"Erreur :",x**3-100)
return x
# Exemple
n=13
sqrt3_100 = newton_bis(10,n)
# print("Racine cubique de 100 (n=%d) : " %n, sqrt3_100)
# Test
# print(sqrt3_100-Decimal(100**1/3))
# print(sqrt3_100)
print(sqrt3_100**3)
#------------------------------------------
# Newton
#------------------------------------------
from math import *
# La fonction g(x)
def g(x):
return x**2 - sin(x) + 1
# La fonction f(x) ( = g'(x) )
def f(x):
return 2*x - cos(x)
# La fonction dérivée f'(x)
def df(x):
return 2 + sin(x)
ell = 0.45018361129487355
def newton(x0,n):
x = x0
for i in range(1,n+1):
x = x - f(x)/df(x)
print("Etape ", i, " : ",x,"Erreur :",x-ell)
return x
print("Calcul de 'l' où g atteint son minimum (là ou f=0) par la méthode de Newton")
print("-- x0 = 0 --")
ell = newton(0,10)
ell = 0.45018361129487355
print('l =',ell)
print('f(l) =',f(ell))
print('g(l) =',g(ell))
print("-- x0 = 10 --")
ell = newton(10,10)
|
#!/usr/bin/python3
# Descente de gradient classique -- 2 variables
from descente import *
from descente_stochastique import *
from descente_lot import *
def exemple1():
# fonction de 2 variables
def f(x, y):
return x**2 + 3*y**2
# gradient calculer par nos soins
def grad_f(x, y):
g = [2*x, 6*y]
return np.array(g)
# Test
print("--- Descente de gradient ---")
X0 = np.array([2, 1])
mon_delta = 0.2
X0 = np.array([-1, -1])
mon_delta = 0.1
affiche_descente(f, grad_f, X0, delta=mon_delta, nmax = 21)
graphique_descente_2var_2d(f, grad_f, X0, delta=mon_delta, nmax = 10, zone = (-2.5,2.5,-1.5,1.5) )
return
def exemple2():
f = lambda x, y : x**2 + (x-y**2)**2
grad_f = lambda x, y :np.array([2*x+2*(x-y**2), -4*y*(x-y**2)])
X0 = np.array([2.2, 0.6])
mon_delta = 0.2
affiche_descente(f, grad_f, X0, delta=mon_delta, nmax=10)
graphique_descente_2var_2d(f, grad_f, X0, delta=mon_delta, nmax = 0, zone = (-2,3,-2,2))
return
# exemple1()
exemple2()
|
import numpy as np
import matplotlib.pyplot as plt
# ----------------------------------------------------
# 5. Fonctions mathématiques de numpy
print("\n\n--- 1. Fonctions mathématiques de numpy ---\n")
X = np.array([0,1,2,3,4,5])
print(X**2)
print(np.sqrt(X))
print(np.exp(X))
print(np.cos(X)) # en radians
print(np.cos(2*np.pi/360*X)) # en degrés
# Ne pas utiliser le mode math
# import math
# print(math.cos(X)) # ERREUR
|
#!/usr/bin/env python
# coding: utf-8
# # Applying Stereo Depth to a Driving Scenario
# Now that you've reviewed the algorithms behind stereo vision and cross correlation we can begin to tackle real-world examples (Actually, we'll use images from the Carla simulator, so I suppose real-world-like would be more appropriate). This is an ungraded practice assignment. This exercise gives you a brief introduction to using Python to implement what you've recently learned in order to find the distance to collision with an obstacle.
#
# #### Instructions:
#
# - You will be using Python 3.
# - Avoid using for-loops and while-loops, unless you are explicitly told to do so.
# - After coding your function, run the cell right below it to check if your result is correct.
#
# #### After this assignment you will:
#
# - Be able to use OpenCV to complete standard vision tasks.
# - Understand the process of obtaining depth from a pair of stereo images and their respective projection matrices.
# - Understand the advantages of cross-correlation for localization of important information in an image.
#
# #### Feedback:
# As this is a practice assignment, you have access to the assignment solution. We recommend that you use OpenCV documentation for solving the assignment and refer to the solution only after you finish this practice exercise.
#
#
# Let's go!
# ## 1 - Getting Set-up
#
# First, let's run the cell below to import all the packages that you will need during this assignment.
# - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python.
# - [matplotlib](http://matplotlib.org) is a famous library to plot graphs in Python.
# - [cv2] (https://opencv.org) is the most used library for computer vision applications in Python.
# - The `files_management` package contains pre-developed functions for importing data for the assignment.
# In[1]:
import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import patches
get_ipython().run_line_magic('matplotlib', 'inline')
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')
get_ipython().run_line_magic('precision', '%.2f')
import files_management
# Now, let's get the pair of stereo images you will work with. The following code will load the images and then display them for you.
# In[2]:
# Read the stereo-pair of images
img_left = files_management.read_left_image()
img_right = files_management.read_right_image()
# Use matplotlib to display the two images
_, image_cells = plt.subplots(1, 2, figsize=(20, 20))
image_cells[0].imshow(img_left)
image_cells[0].set_title('left image')
image_cells[1].imshow(img_right)
image_cells[1].set_title('right image')
plt.show()
# In[3]:
# Large plot of the left image
plt.figure(figsize=(16, 12), dpi=100)
plt.imshow(img_left)
# To go with these images are their respective projection matrices. Let's run the following to gather these and print them.
# In[4]:
# Read the calibration
p_left, p_right = files_management.get_projection_matrices()
# Use regular numpy notation instead of scientific one
np.set_printoptions(suppress=True)
print("p_left \n", p_left)
print("\np_right \n", p_right)
# With this information we can move into finding the depth of the scene.
# ## 2 - Estimating Depth
#
# As we covered in Module 1 Lesson 3 Part 1, we can estimate the depth of a stereo scene using the following sequence of actions:
# 1. Determine the disparity between the two images.
# 2. Decompose the projection matrices into the camera intrinsic matrix $K$, and extrinsics $R$, $t$.
# 3. Estimate depth using what we've gathered in the two prior steps.
# ### 2.1 - Computing the Disparity
#
# It's time we began exploring some OpenCV functions. The following `compute_left_disparity_map` function is expected to recieve a stereo pair of images and return a disparity map from the perspective of the left camera.
#
# There are two OpenCV functions that we can use to compute a disparity map [StereoBM](https://docs.opencv.org/3.4.3/d9/dba/classcv_1_1StereoBM.html) and [StereoSGBM](https://docs.opencv.org/3.4.3/d2/d85/classcv_1_1StereoSGBM.html).
#
# **Note**: if the disparity output is set to 16-bit fixed-point, you will need to divide the output by 16 to obtain the true disparity values. This is because the output has a precision of 1/16, so the bits are shifted left by 4 (corresponding to multiplication by 16). If the disparity output is set to 32-bit floating point, no division by 16 is needed. You can check OpenCV's [compute](https://docs.opencv.org/3.4.3/d2/d6e/classcv_1_1StereoMatcher.html#a03f7087df1b2c618462eb98898841345) function for more details.
#
# Once you've chosen the matcher to use you can call `matcher.compute(img_left, img_right)` to generate the disparity output.
#
# **Note**: make sure you are using grayscale images for the `matcher.compute()` method. You can use `cvtColor()` to convert an image from the RGB color space to grayscale in the following way:
#
#
# `img_g = cv2.cvtColor(img_rgb, code)`
#
#
# Parameters:
#
# - `img_rgb` - an RGB image
#
# - `code` - color space conversion code, e.g. `cv2.COLOR_BGR2GRAY` for grayscale
#
# - `img_g` - the image converted to grayscale
#
# For more information on `cvtColor()` please refer to the [corresponding OpenCV documentation](https://docs.opencv.org/3.4/d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab)
#
# In[5]:
def compute_left_disparity_map(img_left, img_right):
### START CODE HERE ###
img_left_g = cv2.cvtColor(img_left, cv2.COLOR_BGR2GRAY)
img_right_g = cv2.cvtColor(img_right, cv2.COLOR_BGR2GRAY)
num_disp=6*16
block=11
min_disp=0
wind=6
left_bm = cv2.StereoBM.create(numDisparities=num_disp,blockSize=block)
left_gbm = cv2.StereoSGBM.create(minDisparity=min_disp, numDisparities=num_disp,blockSize=block,P1=8*3*wind**2,P2=32*3*wind**2, mode=cv2.STEREO_SGBM_MODE_SGBM_3WAY)
disp_left = left_gbm.compute(img_left_g,img_right_g).astype(np.float32)/16
### END CODE HERE ###
return disp_left
# In order to get an idea of how the parameters and choice of matcher change the resulting disparity map you can run the following code to visualize it.
#
# As you will find while you continue in this course, your choices in paramters will have to vary to fit the data being provided. Take some time to experiment with different combinations, and both of the matchers to see which best fits the images you have been provided.
#
# Don't forget to read about the functions and the restrictions on the paramters.
# In[6]:
# Compute the disparity map using the fuction above
disp_left = compute_left_disparity_map(img_left, img_right)
# Show the left disparity map
plt.figure(figsize=(10, 10))
plt.imshow(disp_left)
plt.show()
# ### 2.2 - Decompose the projection matrices
#
# In Lesson 2 we touched on how to decompose a projection matrix $P$:
# 1. Represent $P$ as a combination of the intrinsic parameters $K$ and the extrinsic rotation $R$ and translation $t$ as follows:
# $$ $$
# $$P = K[R|t]$$
# $$ $$
# 2. Take the inverse of $KR$, which allows us to perform QR-decomposition to get $R^{-1}$ and $K^{-1}$:
# $$ $$
# $$(KR)^{-1} = R^{-1}K^{-1}$$
# $$ $$
# 3. From here it would seem as though we could easily determine $K$, $R$, and $t$.
#
# Unfortunately, this isn't as simple as it seems due to the QR-decomposition isn't unique. This results in us having to check the signs of the diagonal of the $K$ matrix and adjust $R$ appropriately. We must also make assertions about the directions of our camera and image x, y, and z axes.
#
# Luckily for us, OpenCV provides us with a single function that does all of this. Using cv2.[decomposeProjectionMatrix()](https://docs.opencv.org/3.4.3/d9/d0c/group__calib3d.html#gaaae5a7899faa1ffdf268cd9088940248). Use this function below to extract the required matrices.
#
#
# **Note**: After carrying out the matrix multiplication, the homogeneous component $w_c$ will, in general, not be equal to 1. Therefore, to map back into the real plane we must perform the homogeneous divide or perspective divide by dividing each component by $w_c$
#
#
#
# #### Optional
# You can optionally use the space in the function below to try your hand at finding $K$, $R$, and $t$ manually. The numpy functions `np.linalg.inv()`, `np.linalg.qr()`, and `np.matmul()` would be of help in this case.
# You can use the following code block to compare your resulting $K$, $R$, and $t$ with those returned by the OpenCV function.
# In[7]:
def decompose_projection_matrix(p):
### START CODE HERE ###
k, r, t, _, _, _, _ = cv2.decomposeProjectionMatrix(p)
t = t/t[3]
### END CODE HERE ###
return k, r, t
# The following code section uses your function above to decompose and print all of the matrices from the left and right projection matrices.
# In[8]:
# Decompose each matrix
k_left, r_left, t_left = decompose_projection_matrix(p_left)
k_right, r_right, t_right = decompose_projection_matrix(p_right)
# Display the matrices
print("k_left \n", k_left)
print("\nr_left \n", r_left)
print("\nt_left \n", t_left)
print("\nk_right \n", k_right)
print("\nr_right \n", r_right)
print("\nt_right \n", t_right)
# ### 2.3 - Generate the depth map
#
# Lesson 3 explains how to derive the depth from a pair of images taken with a stereo camera setup. Recall the sequence of this procedure:
#
# 1. Get the focal length $f$ from the $K$ matrix
# 2. Compute the baseline $b$ using corresponding values from the translation vectors $t$
# 3. Compute depth map of the image: $$Z = \frac{f b}{x_L - x_R} = \frac{f b}{d}$$ In the above equation, $d$ is a disparity map which we have already computed in one of the previous steps in this assignment.
#
# **Your task**: Complete the `calc_depth_map` function below to return a depth map of the same dimensions as the disparity map being provided.
#
# **Note:** Don't forget to address problematic disparities (the ones having of 0 and -1) to eliminate potential computational issues.
# In[9]:
def calc_depth_map(disp_left, k_left, t_left, t_right):
### START CODE HERE ###
f = k_left[0, 0]
b = t_left[1] - t_right[1]
disp_left[disp_left==0] = 0.1
disp_left[disp_left==-1] = 0.1
depth_map=np.ones(disp_left.shape, np.single)
depth_map[:] = (f*b)/disp_left[:]
### END CODE HERE ###
return depth_map
# Below we call the calc_depth_map function to generate a depth map for the disparity map we found in 2.1.
#
# The depth map is displayed for reference.
# In[10]:
# Get the depth map by calling the above function
depth_map_left = calc_depth_map(disp_left, k_left, t_left, t_right)
# Display the depth map
plt.figure(figsize=(8, 8), dpi=100)
plt.imshow(depth_map_left, cmap='flag')
plt.show()
# Excellent! Now you have successfully used a stereo pair of images to determine the depth of a scene!
# ## 3 - Finding the distance to collision
#
# While we may have a map of the depths of each pixel in the scene, our system does not yet know which of these pixels are safe (like the road) or a potential obstacle (like a motorcycle). To find these objects of interest we run an object detector that has been trained to select a rectangular section containing the object we are concerned about. Object detection will be covered in future modules, so for now we will just work with the motorcycle image that was identified by the detector.
#
# Run the following section of code to read the motorcycle image and display it.
# In[11]:
# Get the image of the obstacle
obstacle_image = files_management.get_obstacle_image()
# Show the obstacle image
plt.figure(figsize=(4, 4))
plt.imshow(obstacle_image)
plt.show()
# What we would like to do now is have the system automatically determine where this obstacle is in the scene. For this we will use cross correlation as described in Lesson 4. As described in the lesson, the algorithm behind cross correlation requires us to perform large numerical computations at each pixel in the image.
# However, once again we are saved by OpenCV. Using the cv2.[matchTemplate()](https://docs.opencv.org/3.4.3/df/dfb/group__imgproc__object.html#ga586ebfb0a7fb604b35a23d85391329be) function we can quickly and easily complete the cross correlation of the obstacle template. From this heatmap we can use the cv2.[minMaxLoc()](https://docs.opencv.org/3.4.3/d2/de8/group__core__array.html#ga8873b86a29c5af51cafdcee82f8150a7) function to extract the position of the obstacle.
# minMaxLoc
# Implement these two functions in the below section to extract the cross correlation heatmat and the corresponding point of the obstacle.
#
# #### Optional:
# Again, if you'd like to challenge yourself you can instead implement the cross correlation algorithm manually in the function below.
# In[12]:
def locate_obstacle_in_image(image, obstacle_image):
### START CODE HERE ###
cross_corr_map = cv2.matchTemplate(image,obstacle_image,method=cv2.TM_CCOEFF)
_,_,_,obstacle_location = cv2.minMaxLoc(cross_corr_map)
### END CODE HERE ###
return cross_corr_map, obstacle_location
# Running the following code section will call your above function and then display the resulting cross correlation heatmap and obstacle location coordinates.
#
# You may take this opportunity to try different "methods" for the matchTemplate function.
# In[13]:
# Gather the cross correlation map and the obstacle location in the image
cross_corr_map, obstacle_location = locate_obstacle_in_image(img_left, obstacle_image)
# Display the cross correlation heatmap
plt.figure(figsize=(10, 10))
plt.imshow(cross_corr_map)
plt.show()
# Print the obstacle location
print("obstacle_location \n", obstacle_location)
# One final step to go! All that's left to do is to crop the section of the depth map that corresponds to the obstacle and find the nearest point in that crop.
#
# Complete the function below to return the obstacle's bounding box and the distance to the nearest point within that bounding box.
# In[14]:
def calculate_nearest_point(depth_map, obstacle_location, obstacle_img):
### START CODE HERE ###
obstacle_width = obstacle_img.shape[1]
obstacle_height = obstacle_img.shape[0]
obstacle_min_x_pos = obstacle_location[0]
obstacle_max_x_pos = obstacle_location[0] + obstacle_width
obstacle_min_y_pos = obstacle_location[1]
obstacle_max_y_pos = obstacle_location[1] + obstacle_height
obstacle_depth = depth_map_left[obstacle_min_x_pos:obstacle_max_x_pos, obstacle_min_y_pos:obstacle_max_y_pos]
closest_point_depth = obstacle_depth.min()
### END CODE HERE ###
# Create the obstacle bounding box
obstacle_bbox = patches.Rectangle((obstacle_min_x_pos, obstacle_min_y_pos), obstacle_width, obstacle_height,
linewidth=1, edgecolor='r', facecolor='none')
return closest_point_depth, obstacle_bbox
# At this point you should know where the obstacle is in the image as well as the estimated nearest point of the obstacle.
#
# Run the section of code below to visualize the bounding box and the depth of the nearest point.
# In[15]:
# Use the developed nearest point function to get the closest point depth and obstacle bounding box
closest_point_depth, obstacle_bbox = calculate_nearest_point(depth_map_left, obstacle_location, obstacle_image)
# Display the image with the bounding box displayed
fig, ax = plt.subplots(1, figsize=(10, 10))
ax.imshow(img_left)
ax.add_patch(obstacle_bbox)
plt.show()
# Print the depth of the nearest point
print("closest_point_depth {0:0.3f}".format(closest_point_depth))
# ## 4 - Results:
#
# To summurize your work on this assignment we will have a look at three outputs for frame 1 of the dataset:
#
# 1. The decomposed components of left and right projection matrices from part 2.
# 2. The estimated obstacle location from part 2.
# 3. The estimated closest point depth from part 2.
#
# **Expected Result Output**:
#
# ```
# Left Projection Matrix Decomposition:
# [[left camera calibration matrix], [left camera rotation matrix], [left camera translation vector]]
#
# Right Projection Matrix Decomposition:
# [[right camera calibration matrix], [right camera rotation matrix], [right camera translation vector]]
#
# Obstacle Location (left-top corner coordinates):
# [x, y]
#
# Closest point depth (meters):
# d
# ```
# In[16]:
# Part 1. Read Input Data
img_left = files_management.read_left_image()
img_right = files_management.read_right_image()
p_left, p_right = files_management.get_projection_matrices()
# Part 2. Estimating Depth
disp_left = compute_left_disparity_map(img_left, img_right)
k_left, r_left, t_left = decompose_projection_matrix(p_left)
k_right, r_right, t_right = decompose_projection_matrix(p_right)
depth_map_left = calc_depth_map(disp_left, k_left, t_left, t_right)
# Part 3. Finding the distance to collision
obstacle_image = files_management.get_obstacle_image()
cross_corr_map, obstacle_location = locate_obstacle_in_image(img_left, obstacle_image)
closest_point_depth, obstacle_bbox = calculate_nearest_point(depth_map_left, obstacle_location, obstacle_image)
# Print Result Output
print("Left Projection Matrix Decomposition:\n {0}".format([k_left.tolist(),
r_left.tolist(),
t_left.tolist()]))
print("\nRight Projection Matrix Decomposition:\n {0}".format([k_right.tolist(),
r_right.tolist(),
t_right.tolist()]))
print("\nObstacle Location (left-top corner coordinates):\n {0}".format(list(obstacle_location)))
print("\nClosest point depth (meters):\n {0}".format(closest_point_depth))
# Congrats on finishing this assignment!
|
# -*- coding: utf-8 -*-
## @package guided_filter.util.timer
#
# Timer utility package.
# @author tody
# @date 2015/07/29
import time
class Timer(object):
def __init__(self, timer_name="", output=False, logger=None):
self._name = timer_name
self._logger = logger
self._output = output
self._end_time = None
self.start()
def start(self):
self._start_time = time.time()
def stop(self):
self._end_time = time.time()
def seconds(self):
if self._end_time is None:
self.stop()
return self._end_time - self._start_time
def milliseconds(self):
return self.seconds() * 1000 # millisecs
def _secondsStr(self):
return "%s: %f s" % (self._name, self.seconds())
def __enter__(self):
self.start()
return self
def __exit__(self, *args):
self.stop()
if self._logger is not None:
self._logger.debug(self._secondsStr())
if self._output:
print(self._secondsStr())
def __str__(self):
return self._secondsStr()
def timing_func(func=None, timer_name=None, logger=None):
def _decorator(func):
_timerName = timer_name
if timer_name is None:
_timerName = func.__name__
import functools
@functools.wraps(func)
def _with_timing(*args, **kwargs):
with Timer(_timerName, output=True, logger=logger) as t:
ret = func(*args, **kwargs)
return ret
return _with_timing
if func:
return _decorator(func)
else:
return _decorator
|
def get_and(i, j):
if i is False or j is False:
return False
elif i is None or j is None:
return None
else:
return True
def get_or(i, j):
if i is True or j is True:
return True
elif i is None or j is None:
return None
else:
return False
while True:
n = int(raw_input())
if n == 0:
break
reg = [None for x in xrange(32)]
for _ in range(n):
command = raw_input().split(" ")
if len(command) is 2:
i = int(command[1])
if command[0][0] == "S":
reg[i] = True
else:
reg[i] = False
else:
i, j = [int(x) for x in command[1:]]
if command[0][0] == "A":
reg[i] = get_and(reg[i], reg[j])
else:
reg[i] = get_or(reg[i], reg[j])
# Print out the reg
to_char = lambda x: "?" if x is None else ("1" if x else "0")
print "".join(to_char(x) for x in reg)[::-1]
|
# Determine the threshold of distance
# Method 1. Look at the distance when its coefficient in the Hedonic regression function approaches 0
# Method 2. Look at the distance when the Pearson correlation coefficient approaches 0
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# path = "F:/RetrofitPolicy/SF Exp2/"
# os.chdir(path)
url ='https://raw.githubusercontent.com/juanfung/retrofit-policy/master/data/processed/SF_Exp2/Attributes.csv'
df = pd.read_csv(url,index_col=0)
# df = df[df['Bed'] <= 10] # Remove single-family homes with more than 10 bedrooms
df.sort_values('SoftStory') # Sort data by the distance to soft-story buildings
Year = 2020
age = Year - np.array(df['YRBLT'])
bed = np.array(df['Bed'])
bath = np.array(df['Bath'])
Parea = np.array(df['SQFT'])*0.092903
CBD = np.array(df['CBD'])
Park = np.array(df['Park'])
School = np.array(df['School'])
Police = np.array(df['Police'])
Fire = np.array(df['Fire'])
Hazard = np.array(df['SoftStory'])
Income = np.array(df['Income'])
Income = np.log(Income)
value = np.array(df['Sale_price_adj'])
Y = np.log(value)
##################################### Method 1 ###########################################
X = np.stack((age, bed, bath, Parea, Park, School, Police, Fire, Hazard, Income), axis=-1)
coefficient = []
for i in range(20):
x = X[int(round(len(X)/20*i)) : int(round(len(X)/20*(i+1)))] # 20 sections
y = Y[int(round(len(Y)/20*i)) : int(round(len(Y)/20*(i+1)))] # 20 Hedonic regrssion functions
reg = LinearRegression().fit(x, y)
coefficient.append(reg.coef_[8])
distance = df['SoftStory'].quantile([.05,.1,.15,.2,.25,.3,.35,.4,.45,.5,.55,\
.6,.65,.7,.75,.8,.85,.9,.95,1])
threshold1 = distance.iloc[coefficient.index(min(np.absolute(coefficient)))]
print('The threshold is %f km.' % threshold1)
plt.figure(figsize=(5, 4))
plt.scatter(distance, coefficient, s=4, label='True')
plt.xlabel('Shortest distance from soft-story buildings (km)', fontsize=12)
plt.ylabel('Coefficient', fontsize=12)
plt.show()
## The threshold is 0.088825 km.
################################### Method 2 ############################################
correlation = []
for j in range(20):
x = Hazard[int(round(len(Hazard)/20*j)) : int(round(len(Hazard)/20*(j+1)))] # 20 sections
y = Y[int(round(len(Y)/20*j)) : int(round(len(Y)/20*(j+1)))] # 20 correlation coefficients
cor = np.corrcoef(x,y)
correlation.append(cor[0,1])
# distance = df['SoftStory'].quantile([.05,.1,.15,.2,.25,.3,.35,.4,.45,.5,.55,\
# .6,.65,.7,.75,.8,.85,.9,.95,1])
try:
threshold2 = distance.iloc[correlation.index(min(np.absolute(correlation)))]
except ValueError:
threshold2 = distance.iloc[correlation.index(-min(np.absolute(correlation)))]
print('The threshold is %f km.' % threshold2)
plt.figure(figsize=(5, 4))
plt.scatter(distance, correlation, s=4, label='True')
plt.xlabel('Shortest distance from soft-story buildings (km)', fontsize=12)
plt.ylabel('Correlation', fontsize=12)
plt.show()
## The threshold is 0.088825 km.
|
# Project will be continued to find best combination for area message
# TODO: Implement Area Message
import math
import random
import sys
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'This is a Project for {name}') # Press Strg+F8 to toggle the breakpoint.
def Triangle_Check(a, b, c):
if a + b > c and a + c > b and b + c > a:
# print(f'\bVALID TRIANGLE ~ ({a}, {b}, {c})')
return True
else:
print(f'({a}, {b}, {c}) is not a valid triangle.')
return False
def HeightOfSideATriangle(a, b, c):
# sin(60) because of 60 ° angle meaning all sides are equal length
degrees = 60 / 180 * math.pi
height = b * math.sin(degrees)
# print(f'Sidelength "A" is {a} | Height from Side "A" is {height}.')
return height
def write2file(String):
f = open("triangle_data_sketch.txt", "a")
f.write(String)
f.close()
# def Checker(remainder_height, remainder_side):
# newHeight = min(remainder_height, float(1-remainder_height))
# newSide = min(remainder_side, float(1-remainder_side))
#
# print(f"height = {newHeight * newHeight} | side = {newSide * newSide}")
def Side_Check(remainder_side):
Side = min(remainder_side, float(.5-remainder_side))
sqSide = float(Side) * float(Side)
newSide = float(math.sqrt(sqSide))
return newSide
def Height_Check(remainder_height):
Height = min(remainder_height, float(.5-remainder_height))
# print(f"normal = {remainder_height} | extra = {float(1-remainder_height)}")
sqHeight = float(Height) * float(Height)
# print(f"sqHeight = {sqHeight}")
newHeight = float(math.sqrt(sqHeight))
# print(f"rootHeight = {newHeight}")
return newHeight
# Todo: important Part Starts here!
def Check_HeightAndSides(treshold, myFloat):
if Triangle_Check(myFloat, myFloat, myFloat):
height = HeightOfSideATriangle(myFloat, myFloat, myFloat)
remainder_height = height % .5
remainder_side = myFloat % .5
new_remainder_height = Height_Check(remainder_height)
new_remainder_side = Side_Check(remainder_side)
if new_remainder_height < treshold and new_remainder_side < treshold:
print("\rpossible Solution found!")
myString = f'Side A = %.3f | Height A = {height} | accuracy_side = {new_remainder_side} | accuracy_height = {new_remainder_height}' %myFloat
sys.stdout.write("\b\r" + myString)
sys.stdout.flush()
String_Point = f"{myFloat}, {height}, {new_remainder_side}, {new_remainder_height}"
write2file(String_Point + "\n")
return True
else:
myString = f"Side A = %.3f | Not exact enough ({treshold}) ~ rem = {new_remainder_height} | {new_remainder_side} " %myFloat
sys.stdout.write(myString + "\r")
sys.stdout.flush()
return False
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('Triangle Calculation')
while True:
for i in range(300, 15000, 1): # given in millimeters
i = i/100
if Check_HeightAndSides(.01, i):
print("\n")
# open and read the file after the appending:
f = open("triangle_data_sketch.txt", "r")
myLine = f.read()
print(f"The total length of worthy combinations is {len(myLine)}.")
break
|
demo_list =[1, 'hello', 1.34, True,[1, 2, 3]]
colors = ['red', 'green', 'blue']
numbers_list = list((1, 2, 3, 4)) #Uso una tupla que generar 1 variable en vez de 4
print(numbers_list)
print(type(numbers_list)) #Tipo de la lista
r = list(range(1, 10)) #Enumera del 1 hasta el 9
print(r)
print(type(colors)) #Class "List"
#print(dir(colors)) #"dir" para ver la info (List)
print(len(colors)) #Para saber la longitud este caso es "3" (solo tiene 3 elementos)
print(colors[1]) #Para denotar la posicion 1 (green)
print(colors[-1]) #Blue
print('green'in colors) #"green esta en colors?"/ true
print("violet" in colors) #False
print("hello" in demo_list) #True
print('1' in demo_list) #False
print(colors)
#colors[1] = 'yellow' #Cambia una variable
print(colors) #Cambia según la úliima alteración
#print(dir(colors)) #"dir" para ver todos los cambios
#colors.append('violet') #Para agregar ['red', 'green, 'blue', 'violet']
#colors.append(('violet', 'yellow')) #Para agregar ['red', 'green, 'blue', ('violet', 'yellow')]
colors.extend(['violet','yellow'])
colors.extend(['pink', 'black']) #['red', 'green', 'blue', 'violet', 'yellow', 'pink', 'black']
print(colors)
colors.insert(-1, 'purple')
colors.insert(1, 'purple')
print(colors) #['red', 'purple', 'green', 'blue', 'violet', 'yellow', 'pink', 'purple', 'black']
colors.insert(len(colors), 'violet')
print(colors) #['red', 'purple', 'green', 'blue', 'violet', 'yellow', 'pink', 'purple', 'black', 'violet']
colors.pop() #Para quitar el ultimo elemento
colors.pop() #Para quitar los 2 ultimos elementos
print(colors) #['red', 'purple', 'green', 'blue', 'violet', 'yellow', 'pink', 'purple']
colors.remove('green')
colors.pop(1)
print(colors) #['red', 'blue', 'violet', 'yellow', 'pink', 'purple']
#colors.clear() #Para borrar todo los datos
#print(colors) #[]
colors.sort() #Los coloca alfabeticamente
print(colors) #['blue', 'pink', 'purple', 'red', 'violet', 'yellow']
colors.sort(reverse= True) #Los coloca al revez del sentiso alfabetico
print(colors) #['yellow', 'violet', 'red', 'purple', 'pink', 'blue']
print(colors.index('yellow')) # '0' ya que comenzo con yellow
colors.insert(1, 'pink') # Para insertar pink
print(colors)
print(colors.count('pink')) #cuantas veces se repite 'pink'?, 2 veces
|
myStr = "Hello World"
#Para ver las propiedades
# #print(dir(myStr)) #"Quitar el '#'para visualizar" <-
# | ctrl + 'k+ctrl' + c = comment
#-----------------------------------------------------------------------------------------
print("Mood " + myStr) #Lo agrupa sin espaciado, por eso uno debe de separarlo con espacio
print(f"Mood {myStr}") #Mi preferida
print("Mood {0}".format(myStr))
#-----------------------------------------------------------------------------------------
print(myStr.upper()) #Para que todo el texto este en mayuscula
print(myStr.lower()) #Para que todo el texto este en minuscula
print(myStr.swapcase()) #Lo que antes era Mayuscula cambia Minuscula
print(myStr.capitalize()) #La primera letra del texto es mayuscula
print(myStr.replace('Hello','Bye')) #Para hacer un cambio de variable
print(myStr.replace('Hello', 'BYE').upper()) #Puedes combinar las variables
print(myStr.count('l')) #Para contar los caracteres, se puede contar los vacios (' ')
print(myStr.startswith('hola')) #Sera cierto que comienza con ('---'), true or false
# ->le podria decir que empiza con ('H') o ('He') ambas son correctas
print(myStr.endswith('World')) #Es "True", ya que termina el World
#--------------------------------------------------------------
myStrr = "Hello World car"
print(myStrr.split()) #Separa los caracteres según lo que hemos determinado
print(myStrr.split('o')) #['Hell', 'W', 'orl']
print(myStrr.find('W')) # Es la letra '6', el primer caracter es '0'
#--------------------------------------------------------------
print(len(myStr)) #Cuenta todas las letras, en este caso el primer termino lo cuenta como '1'
print(myStr.index('e')) #Cuenta la 'h' como '0' y la 'e' se determina en '1'
print(myStr.isnumeric())
print(myStr.isalpha())
print(myStr[4]) #Para denotar el valor que se encuentra en esa posicion 'o', comienza de 0
print(myStr[3]) #'l'
print(myStr[0]) #'H'
print(myStr[-1]) #'d', la ultimo determinando se considera "[-1]"
print(myStr[-3]) #'r'
|
import threading
# uses a set for the queue. Duplicates are therefore discarded, and results popped() at random
class SetQueue:
def __init__(self):
self.items = set()
def push(self, item):
self.items |= set([item])
def push_group(self, items):
self.items |= set(items)
def pop(self):
return self.items.pop()
def pop_group(self, amount):
return [self.items.pop() for i in range(amount)]
def __len__(self):
return len(self.items)
# provides a thread-safe way to push/pop
class PubSub:
tid = lambda self: threading.current_thread()
# queue is dependency injected
def __init__(self, queue):
self.cv = threading.Condition()
self.queue = queue
self.pushed = 0
self.popped = 0
# thread-safe push onto queue. takes a single item
def push(self, item):
self.cv.acquire()
self.queue.push(item)
self.pushed += 1
self.cv.notify() # 1 item added, only need to notify 1 waiter
self.cv.release()
# thread-safe push onto queue. takes a list of items
def push_group(self, items):
self.cv.acquire()
self.queue.push_group(items)
self.pushed += len(items)
self.cv.notify_all() # notify all. Docs say notify(len(items)) is not garuenteed in future impls, so we dont rely on it
self.cv.release()
# thread-safe pop. returns a single item if amount is 1, otherwiser returns a list
# this is a blocking call
def pop(self, amount=1):
self.cv.acquire()
while (len(self.queue) < amount):
self.cv.wait()
if amount == 1:
result = self.queue.pop()
self.popped += 1
else:
result = self.queue.pop_group(amount)
self.popped += amount
self.cv.release()
return result
# returns a string of some stats
def print_info(self):
print('PubSub: pushed=%s, popped=%s, current_size=%s' % (self.pushed, self.popped, len(self.queue)))
|
#class_of_python
#class_name: TWP030 Declarando nossas primeiras variáveis
#link_class: https://www.youtube.com/watch?v=qHx8SRYqW2E&list=PLUukMN0DTKCtbzhbYe2jdF4cr8MOWClXc&index=4
#some basic calculus to learn some thins about python lenguage
# print(type('abacate'))
# print(dir('abacate'))
# help('abacate'.upper)
# print(help(print))
a = 42
b = 'abacate'
print(a*3)
a = 'banana'
|
# Find the char that is not repeated in a string. if more than, return the first repeated char
# if empty or too few return -1
# one by one, check the charcaters in dictionary. If found, add the count. Else add the char to dictionary
# Now iterrate thru the dictionary. Return the first char with count == 1
# if iteration completes, then it means that there is no unique char. return None
def findRepeatChar(str):
# if empty or too few return -1
if (len(str)) <= 1:
return -1
# one by one, check the charcaters in dictionary. If found, return the char. Else add the char to dictionary
charDictionary = {}
for ch in str.lower():
if ch != " ":
if ch in charDictionary:
charDictionary[ch] += 1
else:
charDictionary[ch] = 1
for c in str.lower():
if c != " " and charDictionary[c] == 1:
return c
return "None"
# Scenarios
# with one repeated char
print('ab cd e a- exp b')
print(findRepeatChar('ab cd e a'))
# with multiple repeated chars
print('ab cd ed c b a -exp e')
print(findRepeatChar('ab cd ed c b a'))
# with lower and upper repeated chars
print('ab cd e E b a -exp c')
print(findRepeatChar('ab cd e E b a'))
# with no repeated char
print('ab cd e - exp a')
print(findRepeatChar('ab cd e'))
# with all repeated char
print('ab ab - exp None')
print(findRepeatChar('ab ab '))
# with empty str
print('Empty -Exp -1')
print(findRepeatChar(''))
|
#from collections import namedtuple
#from typing import AsyncGenerator
print((2+10)*(10+4))
a=5
print(a)
print(a+a)
a=a*5
#print a
print(a)
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
print(my_taxes)
#strings (use "double quotes and single quote'' ")
mystring ='abcdegh'
print(mystring[::])
#slicing
mystring.upper()
mystring = 'abcdefg'
x = mystring.capitalize()
print(x)
mystring= "hello world"
x = mystring.split()
print(x)
#print formatting
x="item one: {y} item two:{y}".format(x="dog",y="cat")
print(x)
#list
mylist = [1,2,3]
#mylist = ['stringadgasfd' , 1,2 ,32, 23.3, true[1,2,3,4]]
print(len(mylist))
#indexing and slicing(if you want the very first thing in the list)
mylist = ['a', 'b', 'c']
print(mylist[:3])
#adding items to a list
print('before reassignment:')
print(mylist)
mylist[0] = 'NEW ITEM'
print('after reassignment')
print(mylist)
#basic list method(adding a new items )
mylist = ['a', 'b', 'c', 'd', 'e']
mylist.append("NEW ITEM")
print(mylist)
#exttend
mylist = ['a', 'b', 'c', 'd', 'e', ]
mylist.extend(['x', 'y','z'])
print(mylist)
#removing something from a list
mylist = ['a', 'b', 'c', 'd', 'e']
item = mylist.pop(0)
print(mylist)
print(item)
#reversing and sorting a list
mylist = ['a', 'b' ,'c', 'd', 'e', 'f', 'g']
mylist.reverse()
print(mylist)
#sorting
mylist = [2, 4 ,1 ,6, 97,76]
mylist.sort()
print(mylist)
#nested list index and
#nested list
mylist = [1,2,['x','y', 'z']]
print(mylist[2])
#to specify the index
mylist= [1,2, ['x', 'y','z']]
print(mylist[2][1])
#list comprehension
matrix = [[1,2,3],[4,5,6],[7,8,9]]
first_col = [row[0] for row in matrix]
print(first_col)
#dictionaries
my_stuff = {"key1":"value1","key2":"value2","key3":{'123' :[1, 2, 'grab me']}}
print(my_stuff['key3']['123'][2].upper())
my_stuff = {'lunch':'pizza', 'brakefast':'eggs', 'supper':'ugali'}
my_stuff['lunch'] = "burger"
my_stuff['dinner'] = 'pasta'
print(my_stuff['lunch'])
print(my_stuff)
#tuples ,sets and booleans
#booleans(true or false)or 0 or 1
#tuples are immutables sequences
t= (1, 2, 3, 4)
print(t[0])
mylist = ['a', 'true', '123']
print(mylist)
mylist[0] = 'new'
print(mylist)
#set
x = set()
x.add(1)
x.add(2)
x.add(4)
x. add(3)
x.add(3)
x.add(3)
print(x)
#converting a set into a list
converted = set([1, 2, 3, 1, 2, 2, 3, 4, 5, 3, 6, 6, 6, 6 ])
print(converted)
#function
#def greet(name):
# """ this function greet to the person passed in as a parameter"""
def absolute_value(num):
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
#scope of a variable insie a function
def my_func():
x = 10
print("value inside function:",x)
x=20
my_func()
print("value outside function:",x)
def greet(name, msg):
"""This function greets to
the person with the provided message"""
print("Hello", name + ', ' + msg)
greet("Monica", "Good morning!")
def greet(name, msg='goodmorning!'):
#"""this function greets to the prson with the provided message
#if the message is not provided it defaults to good morning!"""
print("hello", name+',' +msg)
greet('kate')
greet("bruce","how do you do?")
3#lass Customer:
# def__init__(self, name,membership_type):
# self.name = name
# self.membership_type = membership_type
#print("customer created")
#c = Customer("Caleb", "Gold")
#print(c.name, c.membership_type)
#c2 = Customer("brad", "bronze")
#print(c2.name, c2.membership_type)
def greet(name):
"""this function greets to the person passed in as a parameter"""
print("hello," +name+".good morning!")
greet("paul")
def absolute_value(num):
if num>= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
#arbitrary
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello", name)
#example 2
greet("Monica", "Luke", "Steve", "John")
def greet(*names):
for name in names:
print("hello", name)
greet("ruth", "jane", "hosea")
#filter function to filter only even numbers from a list
my_list = [1, 2,3,4, 5,6, 7, 8,12]
new_list= list(filter(lambda x:(x%2==0) ,my_list))
print(new_list)
#program to double each item in a ist using map
my_list = [1, 2, 3, 4, 5, 7, 12]
new_list = list(map(lambda x: x*2, my_list))
print(new_list)
#global variable and local variable in the same code
x= "global"
def foo():
global x
y="local"
x = x * 2
print(x)
print(y)
foo()
#global vaiable and local variable as the same name
x =5
def foo():
x =10
print("local x:", x)
foo()
print("global x:",x) # mendrygals
c = 1 #global variable
def add():
print(c)
add()
# (Modifying Global Variable From Inside the Function
#c = 1 #global variable
#def add():
#c = c + 2 #increment with 2
#print(c)
#add()
#when we run the above program the output unbound local error because we can only access the global variable but cannot modify it from side the function
# Changing Global Variable From Inside a Function using global
c = 0 #global variable
def add():
global c
c = c + 2 #increment by two
print("inside add:", c)
add()
print ("in main:",c)
#using global variable in nested function
def foo():
x = 20
def bar():
global x
x = 25
print("before calling bar:", x)
print("calling bar now")
bar()
print("after calling bar:", x)
foo()
print("x in main:", x)
#class description
class parrot:
#class attribute
species = "bird"
#instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the parrot
blu = parrot("blu", 10)
woo = parrot("woo", 15)
#access the class attribute
print("blu is a {}".format(blu.__class__.species))
print("woo is also a{}".format(woo.__class__.species))
#access the instance attribute
print("{} is {} years old".format(blu.name, blu.age))
print("{} is {} years old".format(blu.name, blu.age))
#methods
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
#inheritence
#parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("swim faster")
#child class
class penguin(Bird):
def __init__(self):
#call super() function
super().__init__()
print("penguinis ready")
def whoisThis(self):
print("penguin")
def run(self):
print("run faster")
peggy = penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
#encapsulation
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
def a_void_function():
a = 1
b = 2
c = a + b
x = a_void_function()
print(x)
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
a =2
print('id(2) =', id(2))
print('id(a) =', id(a))
#example 2
a = 2
print("id(a) =", id(a))
a = a+1
print("id(a)=", id(a))
print("id(3) =", id(3))
b = 2
print("id(b) =", id(b))
print("id(2) =", id(2))
#if statement
num = 3
if num > 0:
print(num, "is always a positive number")
print("this is always printed")
num = -1
if num > 0:
print(num, "is a positive number")
print("this ia also always printed.")
#if else statement
#program checks if the number is positive or negative
#and displays an appropriatenmassage
num = 0
#try these two variation as well
if num >= 0:
print ("positive or zero")
else:
print ("negative number")
#if... else.... elif ...else
# elif is the short form of if else(it allows us chck for multiple expression)
num = 0
#try these two variation as well
# num = 0
# num = -4.5
if num > 0:
print("positive number")
elif num == 0:
print("zero")
else:
print ("negative number")
#nested if ...eli else statement
num = float(input("enter a number: "))
if num >= 0:
if num == 0:
print("zero")
else:
print("positive number")
else:
print("negative number")
#a program to find the sum of all stored in a list
# #list of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
#variable to store the sum
sum = 0
#iterate over the list
for val in numbers:
sum = sum + val
print("the sum is", sum)
#program to iterate through a list using indexing
genre = ['pop', 'rock', 'jazz']
#iterate over the list using index
for i in range(len(genre)):
print("i like", genre[i])
#programto display student's mark from record
student_name = 'soyuj'
marks = {"james": 90, "jules": 55, "arthur": 77}
for student in marks:
if student ==student_name:
print(marks[student])
break
else:
print("no entry with that name foound.")
#filter even numbers from a list
my_list=[1, 2, 3,4 , 6, 8, 5, 12]
new_list= list(filter(lambda x:(x%2==0), my_list))
print(new_list)
#program to double each tem in a list using map
my_list=[1, 2, 3, 4, 4, 45 , 6 ,11]
new_list=list(map(lambda x: x*2, my_list))
print(new_list)
def myfunc(n):
return lambda x: x * n
mydoubler = myfunc(2)
print(mydoubler(11))
#use the the same function definition to double and triple the number you send in
def myfunc(n):
return lambda x: x*n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
#inheritance
|
# TO RUN THIS SCRIPT COPY THIS COMMAND INTO THE TERMINAL -----> index_list.py
packages_setup = ['''
conda create -n stocks-env python=3.7 # (first time only)
conda activate stocks-env
pip install -r requirements.txt
pip install pytest # (only if you'll be writing tests)
python index_list.py
''']
# Examples (click for JSON output)
# https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo
# https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo
# To issue an http request in python, you must import a 'request package'
import os
import requests
import json # need this to import json string into dictionary
from datetime import datetime # taken from stackoverflow
import csv # so you can write date to .csv
# Current Time for transaction pull
date_time = datetime.now().strftime("%m/%d/%Y, %I:%M:%S%P\n") # Formatted for easy to understand human reading instead of military time
# print(date_time)
# Also, we know that we are working with $ pricing so let's get the formatting out of the way
def usd_format(my_price):
return "${0:,.2f}".format(my_price) # This UDF will change numerical denomination to currency and cents (2 digits) format when passed through
# request_url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={user_input_ticker}&apikey={api_key}"
index_list_request_url = f"https://financialmodelingprep.com/api/v3/majors-indexes"
index_list_response = requests.get(index_list_request_url)
# print(type(response))
# print(response.status_code)
# print(response.text) # This is a string
index_list_parsed_response = json.loads(index_list_response.text) #this converts string format into dictionary
# print(index_list_parsed_response)
# breakpoint()
# variable ="txt"
# print("{:^5s}".format(variable))
# print("{:^10s}".format(variable))
# print("{:^15s}".format(variable))
# print("{:^25s}".format(variable))
# print("{:^35s}".format(variable))
# print("{:^45s}".format(variable))
# print("{:^55s}".format(variable))
# print("{:^65s}".format(variable))
# print("{:^75s}".format(variable))
# def aligner1 (spacer):
# return '{:>8}'.format(*str(spacer))
# f"{'Trades:':<15}{cnt:>10}",
# "{:>20} {:>10} {:>10}".format(*cols)s
# def aligner2 (spacer):
# return (str(spacer).rjust(20, '-'))
# def aligner3 (spacer):
# return "{:^35s}".format(spacer)
# def aligner4 (spacer):
# return "{:^45s}".format(spacer)
# def aligner4 (spacer):
# return "{:^55s}".format(spacer)
# def aligner4 (spacer):
# return "{:^65s}".format(spacer)
# print(aligner("tester"))
for i in index_list_parsed_response["majorIndexesList"]:
print("\n")
# print( i["ticker"], ",", i["indexName"], ",", i["price"], ",", i["changes"] )
ticker = i["ticker"]
index_name = i["indexName"]
price = i["price"]
changes = i["changes"]
print(ticker)
print (index_name)
print("Index Price: $", price)
print("Index Change: $", changes)
|
# TO RUN THIS SCRIPT COPY THIS COMMAND INTO THE TERMINAL -----> crypto_ticker.py
packages_setup = ['''
conda create -n stocks-env python=3.7 # (first time only)
conda activate stocks-env
pip install -r requirements.txt
pip install pytest # (only if you'll be writing tests)
python crypto_ticker.py
''']
# Examples (click for JSON output)
# https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo
# https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo
# To issue an http request in python, you must import a 'request package'
import os
import requests
import json # need this to import json string into dictionary
from datetime import datetime # taken from stackoverflow
import csv # so you can write date to .csv
# Current Time for transaction pull
date_time = datetime.now().strftime("%m/%d/%Y, %I:%M:%S%P\n") # Formatted for easy to understand human reading instead of military time
# print(date_time)
# Also, we know that we are working with $ pricing so let's get the formatting out of the way
def usd_format(my_price):
return "${0:,.2f}".format(my_price) # This UDF will change numerical denomination to currency and cents (2 digits) format when passed through
# request_url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={user_input_ticker}&apikey={api_key}"
print("Please enter your desired crypto ticker")
bitcoin_ticker = input()
bitcoin_ticker_lower= bitcoin_ticker.lower()
crypto_list_request_url = f"https://financialmodelingprep.com/api/v3/cryptocurrency/{bitcoin_ticker_lower}"
crypto_list_parsed_response = requests.get(crypto_list_request_url)
# print(type(response))
# print(response.status_code)
# print(response.text) # This is a string
crypto_list_parsed_response = json.loads(crypto_list_parsed_response.text) #this converts string format into dictionary
try:
crypto_list_parsed_response["ticker"]
except:
print("Please rerun the script and enter a valid crypto currency ticker")
exit()
# print(crypto_parsed_response)
selected_crypo_ticker = crypto_list_parsed_response["ticker"]
selected_crypo_name = crypto_list_parsed_response[ "name"]
selected_crypo_price = crypto_list_parsed_response[ "price"]
selected_crypo_change = crypto_list_parsed_response[ "changes"]
selected_crypo_market_cap = crypto_list_parsed_response[ "marketCapitalization"]
# last_refreshed = parsed_response["Meta Data"]["3. Last Refreshed"]
# most_recent_open = parsed_response["Time Series (Daily)"][current_date]["1. open"]
# most_recent_close = parsed_response["Time Series (Daily)"][current_date]["4. close"]
# most_recent_high = parsed_response["Time Series (Daily)"][current_date]["2. high"]
# most_recent_low = parsed_response["Time Series (Daily)"][current_date]["3. low"]
# most_recent_total_volumes_traded = parsed_response["Time Series (Daily)"][current_date]["5. volume"]
print("Cryptocurrency Ticker:", selected_crypo_ticker)
print("Cryptocurrency Name:", selected_crypo_name)
print("Current Price: $", float(selected_crypo_price) )
print("Price Change:", usd_format( float(selected_crypo_change) ) )
print("Market Capitalization:", usd_format( float(selected_crypo_market_cap) ) )
|
# from math import *
# a = int(input("son kirit= "))
# b = int(input(" yana son kirit= "))
# if a > 0 and b > 0:
# x1 = sqrt(a+b)
# x2 = sqrt(a-b)
# print(f"x1 = {x1}, x2 = {x2}")
# elif a < 0 or b < 0:
# y = ((a) + (b))*-1
# u = ((a) - (b))*-1
# x1 = sqrt(y)
# x2 = sqrt(u)
# print(f"x1 = {x2}, x2 = {x1}")
# else:
# if a == 0 or b == 0:
# x = sqrt(a + b)
# print(f"x = {x}")
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 11:14:41 2019
@author: Matthew Mulhall
"""
import os
def rename(path = ''):
#Set old dir to the path up until your char folder . Something like: "C:\Users\yourname\Documents\OCR-Handwriting\bin\data\char"
#Created more generality in the script, rather than needing an IDE to change path it is now interactive at the cmd.
directory = ""
if path:
directory = path
else:
try:
pathFile = open("path.txt", "r+")
except:
pathFile = open("path.txt", "w+")
line = []
for line in pathFile.readlines(): print(line)
if not line:
directory = input("Please enter the path of your data file")
pathFile.write(directory)
else:
directory = line
pathFile.close()
os.chdir(directory)
overallCount = 0;
#Sets up the walk starting at the char folder.
for dir, subdirs, files in os.walk(directory):
#Walks all subdirectories, and sets the "count" to 0, this is for naming purposes
count = 0
for f in files:
#if it is a readme we don't want to rename, also if it is a directory we don't want to rename it.
if(f == "readme.txt" or os.path.isdir(f)):
continue
#fetches the parent directory name, this is useful in order to have our standardized naming
d = os.path.basename(dir)
fnew = 'a.01.'+ d + "_" + (str(0) * (3-len(str(count)))) + str(count) + ".png";
#creates the new name, calculates the required number, if we did up to 4 numbers we would need to do 4-len(str(count)) etc
if(f == fnew):
#if our file is named what we calculate its name to be, theres no use in renaming it, this saves us a lot of time.
count += 1
continue
#changes us to the directory we are currently walking
os.chdir(dir)
#Does the renaming:
os.rename(os.path.join(os.getcwd(),f), os.path.join(os.getcwd(), fnew))
#gives a confirmation it worked.
print("Renamed [" + f + "] to: [" + fnew + "]\n")
overallCount+=1
#increments count.
count += 1
print("\nRenamed a total of " + str(overallCount) + " photos\n")
if __name__ == "__main__":
rename()
|
Pizzas=['Ks bakers','dominos','pizza hut']
print(Pizzas)
for item in Pizzas: # In For Loop item is a variable which takes items from List
print("this is "+item.title()+" pizza")
print("I really love pizza..!!\n")
# indendations are important in the loop
# variables are declared and definied at a time in the for loop
Animals=['cat','dog','cow']
for pet in Animals:
print(pet.title()+" is a domestic pet")
print("Any of the above animals would be a great pet to accompany as a friend")
print(5%2)
|
class Ejercicios:
def __init__(self):
pass
def num_cuadrado11(self):
suma = 0
for i in range(1, 101):
suma = suma + i * i
print('Suma:', suma)
print('-'*6 + '-'*len(str(suma)))
def numero12(self):
i = 1
while i <= 100:
print(i)
i = i + 1
print('---')
def producto_num13(self):
suma, prod, num, resp = 0, 1, 0, ''
resp = input('Ingresa una letra: ')
while (resp != 'N') and (resp != 'n'):
num = int(input('Ingrese un número: '))
suma = suma + num
prod = prod * num
print('Desea continuar (S/N)?')
resp = input('Ingrese una letra: ')
print('\nEl total de la suma es:', suma)
print('El total del producto es:', prod)
print('-'*26 + '-'*len(str(prod)))
def producto_suma14(self):
suma, prod, num = 0, 1, 0
num = int(input('Ingrese un número: '))
while (num != -1):
suma = suma + num
prod = prod * num
num = int(input('Ingrese un número: '))
print('\nEl total de la suma es:', suma)
print('El total del producto es:', prod)
print('-'*26 + '-'*len(str(prod)))
def numero_primo15(self):
primo, divisor, num, res, divisor = 'T', 0, 0, 0, 2
num = int(input('Ingrese un número: '))
while ((divisor < num) and (primo == 'T')):
res = num % divisor
if (res == 0):
primo = 'F'
divisor = divisor + 1
if primo == 'T':
print('Número', num, 'es primo.')
else:
print('Número', num, 'no es primo.')
print('-'*20 + '-'*len(str(num)))
def estructura_repeat16(self):
i, n, serie, band = 1, 0, 0, 'T'
n = int(input('Ingrese un número: '))
while (i < n):
if band == 'T':
serie = serie + (1/i)
band = 'F'
else:
serie = serie - (1/i)
band = 'T'
i = i + 1
print('Serie:', serie)
print('-'*7 + '-'*len(str(serie)))
def factorial17(self):
n = int(input('Numero de repeticiones: '))
for _ in range(1, n+1):
numero = int(input('Ingrese un número: '))
fact = 1
for j in range(1, numero+1):
fact = fact * j
print('El factorial del número', numero, 'es', fact)
print('-'*30)
def arrays18(self):
num, a, b = [], [], []
for i in range(1, 21):
num.append(int(input('Ingrese el número {}: '.format(i))))
if (num[i-1] > 0):
a.append(num[i-1])
else:
b.append(num[i-1])
print('Array: A')
for i in a:
print(i)
print('Array: B')
for i in b:
print(i)
print('-'*15)
def calificaciones_30_alumnos19(self):
notas_list, alumnos_list, promedio_exam = [], [], []
for alum in range(1, 31):
alumno = input('Nombre del alumno {}: '.format(alum))
alumnos_list.append(alumno)
for nota in range(1, 7):
print('Escriba la calificación para el alumno {} en el exámen {}.'.format(alumno, nota))
notas_temp = float(input('Nota #{}: '.format(nota)))
if nota == 1:
notas_list.append([notas_temp])
else:
notas_list[alum-1].append(notas_temp)
print('')
for num_examen in range(6):
sum_notas = 0
for nota in notas_list:
sum_notas += nota[num_examen]
promedio = (sum_notas/30)
print('Promedio de exámen {}= {}'.format(num_examen+1, promedio))
print('')
for numero, alum in enumerate(alumnos_list):
sum_notas = sum(notas_list[numero])
promedio = (sum_notas/6)
print('Promedio del alumno {}= {}'.format(alum, promedio))
promedio_mayor = 0
for num_examen in range(6):
sum_notas = 0
for nota in notas_list:
sum_notas += nota[num_examen]
promedio = (sum_notas/30)
if promedio_mayor < promedio:
promedio_mayor = promedio
promedio_exam.append(promedio)
print('\nEl exámen', promedio_exam.index(promedio_mayor)+1, 'obtuvo el mayor promedio:', promedio_mayor)
print('-'*50)
tarea = Ejercicios()
# tarea.num_cuadrado11()
# tarea.numero12()
# tarea.producto_num13()
# tarea.producto_suma14()
# tarea.numero_primo15()
# tarea.estructura_repeat16()
# tarea.factorial17()
# tarea.arrays18()
tarea.calificaciones_30_alumnos19()
|
def print_board(board):
for i in range(len(board)):
for j in range(len(board[0])):
print(board[i][j],end=" ")
print("")
# checks if a given row contains the given number,if it contains the function returns False
def is_row_valid(board,row,number):
for i in range(len(board)):
if board[row][i] == number:
return False
return True
# checks if a given colum contains the given number,if it contains the function returns Flase
def is_column_valid(board,column,number):
for i in range(len(board)):
if board[i][column] == number:
return False
return True
# returns first empty square
def get_empty_square(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]==0:
return (i,j)
return None
# checks if the 3x3 square doesnt contain a given number
def is_box_valid(board,row,column,number):
# gets the x and y position of the 3x3 square
row_offset = row//3
column_offset = column//3
# loops through 3x3 square
for i in range(row_offset*3,row_offset*3+3):
for j in range(column_offset*3,column_offset*3+3):
if board[i][j] == number:
return False
return True
# algorithm for solving sudoku
def backtrack(board):
# gets the first empty square
empty_square = get_empty_square(board)
# if all squares are not empty our board is solved
if empty_square == None:
return True
row = empty_square[0]
column = empty_square[1]
# checks every number from 1 to 9 if it fits for the given square
for i in range(1,10):
if is_row_valid(board,row,i) and is_column_valid(board,column,i) and is_box_valid(board,row,column,i):
board[row][column] = i
if backtrack(board):
return True
board[row][column] = 0
return False
# reads from file into a 2D board
def read_from_file(board):
file = open("testCase.txt","r")
for line in file.readlines():
board.append([int(num)for num in line.split(",")])
board = []
read_from_file(board)
backtrack(board)
print_board(board)
|
civilization_world = [
#0 1 2 3 4 5 6 7 8 9 10
[0,0,0,0,0,0,0,0,0,1,0], #0
[0,0,0,0,1,0,0,0,0,0,0], #1
[0,0,0,0,1,0,0,0,1,0,0], #2
[0,0,0,0,1,1,0,1,1,0,0], #3
[0,0,0,1,1,1,0,1,0,0,0], #4
[1,1,1,1,1,1,1,1,0,0,0], #5
[0,0,0,0,1,0,0,0,0,1,0], #6
[0,0,0,0,1,0,0,0,0,1,0], #7
[0,0,0,0,1,0,0,1,1,1,0], #8
[0,1,0,0,0,0,0,0,1,1,1], #9
[0,0,0,0,0,0,0,0,0,0,0], #10
]
visitted = [[0 for x in range(11)] for y in range(11)]
queue = [(5,5)]
continent_counter = 0
def civilization(x,y):
global continent_counter, queue, visitted
if visitted[x][y] == 1:
return
if civilization_world[x][y] == 0:
return
visitted[x][y] = 1
continent_counter +=1
if x<10:
queue.append((x+1, y))
if x>0:
queue.append((x-1, y))
if y <10:
queue.append((x, y+1))
if y>0:
queue.append((x, y-1))
while len(queue) > 0:
x, y = queue.pop(0)
civilization(x,y)
print(continent_counter)
|
#segun los números digitados, se escoge en las
#condicionales y los muestra en pantalla
def matriz(n):
if n=="1":
lista=[" ","#"," "," ","#"," "," ","#"," "," ","#"," "," ","#"," "]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="2":
lista=["#","#","#"," "," ","#","#","#","#","#"," "," ","#","#","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="3":
lista=["#","#","#"," "," ","#","#","#","#"," "," ","#","#","#","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="4":
lista=["#"," ","#","#"," ","#","#","#","#"," "," ","#"," "," ","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="5":
lista=["#","#","#","#","-","-","#","#","#","-","-","#","#","#","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="6":
lista=["#","#","#","#","-","-","#","#","#","#","-","#","#","#","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="7":
lista=["#","#","#"," "," ","#"," "," ","#"," "," ","#"," "," ","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="8":
lista=["#","#","#","#","-","#","#","#","#","#","-","#","#","#","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="9":
lista=["#","#","#","#"," ","#","#","#","#"," "," ","#"," "," ","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
if n=="0":
lista=["#","#","#","#"," ","#","#"," ","#","#"," ","#","#","#","#"]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
print(lista[i],"\n")
else:
print(lista[i],end="")
def funcion(x):
list(x)
for i in range(len(x)):
numeros=x[i]
matriz(numeros)
#inicia el programa y solicita ingresar la opción y luego lo muestra
x=funcion(input("Digite opcion: "))
|
import unittest
from app.models import News,Articles
News = news.News
class NewsTest(unittest.TestCase):
'''
Test Class to test the behaviour of the News class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_news = News(1234,'Ineos 159','Eliud Kipchoge super human','bbc.com','general','U.K','en')
def test_instance(self):
self.assertTrue(isinstance(self.new_news,News))
|
import time
import numpy as np
import pandas as pd
from pandas.core.algorithms import value_counts
from pandas.core.tools.datetimes import to_datetime
def city_list():
return
CITY_DATA = {
"chicago": pd.read_csv("chicago.csv"),
"new york": pd.read_csv("new_york_city.csv"),
"washington": pd.read_csv("washington.csv")}
month_text = ["january", "february", "march", "april", "may", "june"]
day_text = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or 'all' to apply no month filter
(str) day - name of the day of week to filter by, or 'all' to apply no day filter
"""
print("Hello! Let's explore some US bikeshare data!")
# get user input for city (chicago, new york city, washington)
print("Would you like to see data for Chicago, New York, or Washington?")
while True:
try:
city = input("Please type the city name:").lower()
except ValueError:
print("That's not a valid input, please try again")
continue
else:
if city not in CITY_DATA.keys():
print("City out of range, please try again")
continue
else:
break
# ask user how they'd like to filter the date
print('Would you like to filter the data by month, day, both, or "none" for no time filter?')
while True:
try:
date_filter = input("Specify the date filter:").lower()
except ValueError:
print("That's not a valid input, please try again")
continue
else:
if date_filter not in ["month", "day", "both", "none"]:
print("Input out of range, please try again")
continue
else:
break
month, day = None, None
# get user input for month
if date_filter in ["month", "both"]:
print("Which month - January, February, March, April, May, or June?")
while True:
try:
month = input("Specify the month:").lower()
except ValueError:
print("That's not a valid input for month, please try again")
continue
else:
if month not in month_text:
print("Month out of range, please try again")
continue
else:
break
# get user input for day of week (all, monday, tuesday, ... sunday)
if date_filter in ["day", "both"]:
print("Which day - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday?")
while True:
try:
day = input("Specify the day:").lower()
except ValueError:
print("That's not a valid input for day, please try again")
continue
else:
if day not in day_text:
print("Day out of range, please try again")
continue
else:
break
print("-" * 40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or 'all' to apply no month filter
(str) day - name of the day of week to filter by, or 'all' to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = CITY_DATA[city]
df["Start Time"] = pd.to_datetime(df["Start Time"])
df["month"] = df["Start Time"].dt.month
df["day"] = df["Start Time"].dt.weekday
df["hour"] = df["Start Time"].dt.hour
if month != None:
month = month_text.index(month) + 1
df = df.loc[df["month"] == month]
if day != None:
day = day_text.index(day)
df = df.loc[df["day"] == day]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print("\nCalculating The Most Frequent Times of Travel...\n")
start_time = time.time()
# display the most popular month
month_mode = df["month"].mode()[0]
month_mode_count = df.loc[df["month"] == month_mode].count()[0]
print("Most Popular Month: {}, Count: {} ".format(
month_mode, month_mode_count))
# display the most popular day
day_mode = df["day"].mode()[0]
day_mode_count = df.loc[df["day"] == day_mode].count()[0]
print("Most Popular Day: {}, Count: {} ".format(
day_mode, day_mode_count))
# display the most popular hour
hour_mode = df["hour"].mode()[0]
hour_mode_count = df.loc[df["hour"] == hour_mode].count()[0]
print("Most Popular Hour: {}, Count: {} ".format(
hour_mode, hour_mode_count))
print("\nThis took %s seconds." % (time.time() - start_time))
print("-" * 40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print("\nCalculating The Most Popular Stations and Trip...\n")
start_time = time.time()
# display most commonly used start station
s_station_mode = df["Start Station"].mode()[0]
s_station_mode_count = df.loc[df["Start Station"] == s_station_mode].count()[0]
print("Most Popular Start Station: {}, Count: {} ".format(
s_station_mode, s_station_mode_count))
# display most commonly used end station
e_station_mode = df["End Station"].mode()[0]
e_station_mode_count = df.loc[df["End Station"] == e_station_mode].count()[0]
print("Most Popular End Station: {}, Count: {} ".format(
e_station_mode, e_station_mode_count))
# display most frequent combination of start station and end station trip
df["Station Combo"] = df["Start Station"] + " --> " + df["End Station"]
stn_combo_mode = df["Station Combo"].mode()[0]
stn_combo_mode_count = df.loc[df["Station Combo"] == stn_combo_mode].count()[0]
print("Most Popular End Station: {}, Count: {} ".format(
stn_combo_mode, stn_combo_mode_count))
print("\nThis took %s seconds." % (time.time() - start_time))
print("-" * 40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print("\nCalculating Trip Duration...\n")
start_time = time.time()
# display total travel time
print("The total trip duration in hours: ", df["Trip Duration"].sum()/3600)
# display mean travel time
print("The mean trip duration in minutes: ", df["Trip Duration"].mean()/ 60)
print("\nThis took %s seconds." % (time.time() - start_time))
print("-" * 40)
def user_stats(df, city):
"""Displays statistics on bikeshare users."""
print("\nCalculating User Stats...\n")
start_time = time.time()
# Display counts of user types
type_count = df["User Type"].value_counts()
print("The counts of user types: ", type_count, "\n", "-"*10, "\n")
# Display counts of gender
if city != 'washington':
age_count = df["Gender"].value_counts()
print("The counts of gender: ", age_count, "\n", "-"*10, "\n")
# Display earliest, most recent, and most common year of birth
print("The earliest birth: ", df["Birth Year"].min(), "\n", "-"*10, "\n",
"The latest birth: ", df["Birth Year"].max(), "\n", "-"*10, "\n",
"The most common birth: ", df["Birth Year"].mode())
print("\nThis took %s seconds." % (time.time() - start_time))
print("-" * 40)
def raw_data(df):
"""
Asks user if they wanna see the raw data.
Returns:
if 'yes' - print 5 rows of the data at a time, then ask if wanna see more
if 'yes' - ontinue prompting and printing the next 5 rows at a time
if 'no' - stop printing raw data
"""
# ask users if they wanna see the raw data, and print the raw data 5 lines a time
print("Would you like to see the raw data?")
count = 0
while True:
try:
raw = input("Please type 'yes' or 'no':").lower()
except ValueError:
print("That's not a valid input, please try again")
continue
else:
if raw == 'yes':
print(df.iloc[count:count+5,:])
print("Do you wanna see more raw data?")
count +=1
continue
else:
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
df.info()
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df, city)
raw_data(df)
restart = input("\nWould you like to restart? Enter yes or no.\n")
if restart.lower() != "yes":
break
if __name__ == "__main__":
main()
|
while True:
print "Type in a month's number and learn what month that is."
month = raw_input()
if month == "1":
print "January"
print "Happy New Year!"
elif month == "2":
print "February"
print "Celebrate the loved ones in your lives on Valentines Day!"
elif month == "3":
print "March"
print "Get the lucky four leafed clovers and celebrate your fathers in this month!"
elif month == "4":
print "April"
print "Get out those woopie cushions and celebrate April Fool's Day!"
elif month == "5":
print "May"
print "Make sure to celebrate your mothers on Mother's Day!"
elif month == "6":
print "June"
print "What time is it? Summertime!"
elif month == "7":
print "July"
print "Make sure to watch some fireworks on the 4th of July."
elif month == "8":
print "August"
print "Enjoy the very hot last month of summer."
elif month == "9":
print "September"
print "Time to get back to school."
elif month == "10":
print "October"
print "Have fun trick or treating!"
elif month == "11":
print "November"
print "Eat lots of turkey and stuffing while at the Thanksgiving table!"
elif month == "12":
print "December!"
print "Elsie's-the most amazing person ever-birthday month!"
elif month == "Elsie Rocks":
print "So true!"
else:
print "Type a number 1-12"
|
from flask import Flask
from flask import render_template
from flask import request
# The parameter static_url_path tells Flask where to look for the "static" directory.
# Requests for paths not explicitly listed with @app.route() directives below will be
# interpreted as requests for files from the "static" directory.
app = Flask('Reverser', static_url_path='')
# By default, Flask serves the file index.html if there's no path after
# the URL. This overrides that default to send the static file reverse_home.html
# instead (found in ./static/reverse_home.html)
@app.route("/")
def reverse():
return app.send_static_file('mini_project_quiz.html')
# When the user goes to the website with /reversed after the base URL, show the
# reverse_result.html template, customized based on what they entered in the form.
# Note "/reversed" matches the form action in reverse_home.html.
@app.route("/grade")
def result():
# Get the URL parameter named forward, and store it in a variable named forward.
# If the URL doesn't have a parameter named forward, it'll default to '' - the empty string.
forward = request.args.get('forward', '')
# Python code to generate the backward version of the string and store it in a variable named backward.
# The details of this aren't important for understanding Flask handlers.
backward = ''.join(reversed(forward))
# Render the reverse_result.html template using our forward variable for the template's forward variable,
# and our backward variable for the template's backward variable.
return render_template('grade_4_quiz.html', forward=forward, backward=backward)
app.run()
|
def recurse(a):
a.append(a[len(a)-1]+1)
for x in a:
print 1
print x
if a[len(a)-1]<8:
recurse(a)
a = [2]
recurse(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.