text
stringlengths 37
1.41M
|
---|
# 1. Отсортируйте по убыванию методом "пузырька" одномерный целочисленный массив,
# заданный случайными числами на промежутке [-100; 100). Выведите на экран исходный
# и отсортированный массивы. Сортировка должна быть реализована в виде функции.
# По возможности доработайте алгоритм (сделайте его умнее).
import random
import statistics
li = []
for i in range(44):
li.append(random.randint(-100, 100))
print(li)
def buble(list):
n = 1
while n < len(li):
for i in range(len(li) - n):
if li[i] < li[i + 1]:
li[i], li[i + 1] = li[i + 1], li[i]
n += 1
buble(li)
print(li)
# 2. Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
# заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы.
li = []
for i in range(44):
li.append(random.randint(0, 50))
print(li)
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i = i + 1
else:
alist[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
alist[k] = righthalf[j]
j = j + 1
k = k + 1
mergeSort(li)
print(li)
# Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом.
# Найдите в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части:
# в одной находятся элементы, которые не меньше медианы, в другой – не больше медианы.
# Задачу можно решить без сортировки исходного массива.
# Но если это слишком сложно, то используйте метод сортировки, который не рассматривался на уроках
li = []
for i in range(44):
li.append(random.randint(0, 50) * 2 + 1)
print(li)
static = statistics.median(li)
listmin = []
listmax = []
for i in li:
if i < static:
listmin.append(i)
else:
listmax.append(i)
print(listmin)
print(listmax)
|
from cipher import Cipher
MENU = """0: exit
1: my info
2: list users
3: get user's public cube
4: get user's ciphercubes
5: go to cipher
"""
class DataManager:
def __init__(self, db, cipher_manager):
self.db = db
self.cipher_manager = cipher_manager
def list_users(self):
users = self.db.get_users()
print(f"Found {len(users)} users:")
for user in users:
print(f"- {user}")
print()
def get_users_public_cube(self):
print("Give me user's login")
login = input("> ")
if not self.db.check_user(login):
print("No user with this login!")
return
pub_cube = self.db.get_user_data(login)[0]
print(f"User's public cube: {pub_cube.as_str()}")
def get_users_ciphercubes(self):
print("Give me user's login")
login = input("> ")
if not self.db.check_user(login):
print("No user with this login!")
return
ciphercubes = self.db.get_ciphercube(login)
if ciphercubes:
print(f"User's ciphercubes: {ciphercubes.decode()}")
else:
print("User has no ciphercubes yet")
def process(self, login, info):
while True:
print(MENU)
try:
_input = int(input("> "))
except Exception:
return
if _input == 0:
print("Bye bye!")
return
elif _input == 1:
print(f"Your info: {info}")
elif _input == 2:
self.list_users()
elif _input == 3:
self.get_users_public_cube()
elif _input == 4:
self.get_users_ciphercubes()
elif _input == 5:
self.cipher_manager.process()
else:
return
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
#Mostrar la cantidad de numeros pares desde 1 hasta 100
numero=1
cantidad=0
while numero <= 100:
#print("Los numeros pares son: ",numero)
numero= numero+2
cantidad=cantidad+1
print("La cantidad de numero pares son: ",cantidad)
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
#Mostrar la cantidad de numeros multiplos de 3 desde 1 hasta el numero ingresado por teclado
num=int(input("Ingrese un numero: "))
i=3
cant=0
while i<=num:
if i%3==0:
print(i)
cant+=1
i+=1
print("La cantidad de multiplos de 3 es: ",cant)
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
# Un alumno desea saber cual será su calificación final en la materia de Matemáticas, dicha calificación se compone por 3 porcentajes , a su vez cada porcentaje tiene cierta cantidad de notas, primero diremos los siguiente:
#parciales 55% examen final 30% trabajos 15%
examenes=float(input("Ingrese nota: "))
examenfinal=float(input("Ingrese nota: "))
trabajos=float(input("Ingrese nota: "))
Exam=examenes*0.55
Finalexam=examenfinal*0.30
Trabajos=trabajos*0.15
Notafinal=Exam+Finalexam+Trabajos
print("Su nota final es de: ",Notafinal)
|
##Nombre: Alejandro Cadena
#Correo: [email protected]
# De acuerdo a tres números , indicar cual es el menor y cual es el mayor.
Numero1=float(input("Ingrese un numero: "))
Numero2=float(input("Ingrese un numero: "))
Numero3=float(input("Ingrese un numero: "))
if Numero1 > Numero2 and Numero1 > Numero3:
print("El primer numero es el mayor de todos ",Numero1)
if Numero2 > Numero3 and Numero2 > Numero1:
print("El segundo numero es el mayor de todos ",Numero2)
if Numero3 > Numero1 and Numero3 > Numero2:
print("El segundo numero es el mayor de todos ",Numero3),
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
# Diseñar un algoritmo que lea por consola el valor de una factura, en este caso aplicaremos un IGV 18% (Perú
factura=float(input("Por favor ingrese el valor de su factura: "))
gravamen=factura*0.18500
print("Su valor de IGV es: ",gravamen)
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
#Diseñar un algoritmo que al momento de ingresar tres números, indicar si hay números iguales y números diferentes,
# de ser así verificar si están ordenados ascendentemente, descendentemente o desordenados.
Numero1=float(input("Ingrese un numero: "))
Numero2=float(input("Ingrese un numero: "))
Numero3=float(input("Ingrese un numero: "))
if Numero1 != Numero2 and Numero1 != Numero3 and Numero2 != Numero3:
print("Todos los numeros son diferntes y estan en desorden")
else:
if Numero3 > Numero2 and Numero2 > Numero1:
print("Todos los numeros son diferentes y estan en orden ascendente")
if Numero1 > Numero2 and Numero2 > Numero3:
print("Todos los numeros son diferentes entre ellos y estan en orden descendente")
if Numero1 == Numero2 and Numero1 == Numero3:
print("Todos los numeros son iguales entre ellos y al ser iguales no tienen orden")
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
# Diseñar un algoritmo que permita aplicar un descuento en el supermercado de tal forma permita visualizar el monto a pagar después de aplicar dicho procedimiento
descuento=float(input("Por favor ingrese el valor de descuento: "))
costo=float(input("Por favor ingrese el valor de la compra: "))
descuento= descuento/100
valorcondescuento=costo*descuento
total= costo-valorcondescuento
print("Su valor a pagar con descuento es: ",valorcondescuento)
print("El valor a pagar es de: ", total)
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
#Mostrar la suma de 2 numeros ingresados por teclado
numero1=float(input("Ingrese numero: "))
numero2=float(input("Ingrese numero: "))
suma=numero1+numero2
if suma>0:
print("Los numeros ingresados fueron: ",numero1, numero2, "y su suma es: ",suma)
else:
print("Error")
|
#Nombre: Alejandro Cadena
#Correo: [email protected]
#Muestra de resto y cociente mediante restas
resto = 0
co = 0
num=int(input("Ingrese el numerador "))
den=int(input("Ingrese el denominador "))
while num > den:
num = num-den
resto = num
co+=1
print("El residuo es: ",resto)
print("El cociente es: ",co)
|
import unittest
from exercises.tree import BinarySearchTree
class TreeNodeTests(unittest.TestCase):
pass
class TreeTests(unittest.TestCase):
def test_left_insert(self):
#test insert right
tree = BinarySearchTree(3)
tree.insert(5)
tree.insert(3)
tree.insert(6)
self.assertEqual(tree.right.key, 5)
def test_right_insert(self):
#test insert left
tree = BinarySearchTree(5)
tree.insert(3)
tree.insert(2)
tree.insert(4)
self.assertEqual(tree.left.key, 3)
def test_lookup_right_exists(self):
#test lookup right if key exists
tree = BinarySearchTree(5)
tree.insert(2)
tree.insert(6)
tree.insert(0)
tree.insert(3)
self.assertEqual(tree.lookup(6)[0].key, 6)
def test_lookup_left_exists(self):
tree = BinarySearchTree(4)
tree.insert(2)
tree.insert(3)
tree.insert(5)
tree.insert(7)
self.assertEqual(tree.lookup(2)[0].key, 2)
def test_lookup_right_not_exists(self):
tree = BinarySearchTree(3)
self.assertEqual(tree.lookup(7)[0], None)
def test_lookup_left_not_exists(self):
tree = BinarySearchTree(3)
self.assertEqual(tree.lookup(1)[0], None)
def test_delete_tree(self):
tree = BinarySearchTree(3)
self.assertRaises(Exception, tree.delete, 3)
def test_delete_one_child(self):
#tesing delete nodes parent, node has one child (right side)
self.t = BinarySearchTree(10)
self.t.insert(15)
self.t.insert(20)
self.t.delete(10)
self.assertEqual(self.t.lookup(15)[0].key, 15)
self.assertEqual(self.t.lookup(20)[0].key, 20)
self.assertIsNone(self.t.lookup(10)[0])
class TreeDeleteTests(unittest.TestCase):
def setUp(self):
# 10
# / \
# 5 15
# / / \
# 2 12 20
# / \
# 1 3
self.t = BinarySearchTree(10)
self.t.insert(5)
self.t.insert(2)
self.t.insert(1)
self.t.insert(3)
self.t.insert(15)
self.t.insert(12)
self.t.insert(20)
def test_delete_leaf_left(self):
self.t.delete(12)
self.assertIsNone(self.t.lookup(12)[0])
self.assertEqual(self.t.lookup(15)[0].key, 15)
self.assertEqual(self.t.lookup(20)[0].key, 20)
def test_delete_leaf_right(self):
self.t.delete(20)
self.assertIsNone(self.t.lookup(20)[0])
self.assertEqual(self.t.lookup(12)[0].key, 12)
self.assertEqual(self.t.lookup(15)[0].key, 15)
def test_delete_one_child(self):
self.t.delete(5)
self.assertIsNone(self.t.lookup(5)[0])
self.assertEqual(self.t.lookup(1)[0].key, 1)
self.assertEqual(self.t.lookup(2)[0].key, 2)
self.assertEqual(self.t.lookup(3)[0].key, 3)
self.assertEqual(self.t.lookup(10)[0].key, 10)
def test_delete_parent(self):
self.t.delete(2)
self.assertIsNone(self.t.lookup(2)[0])
self.assertEqual(self.t.lookup(5)[0].key, 5)
self.assertEqual(self.t.lookup(3)[0].key, 3)
self.assertEqual(self.t.lookup(1)[0].key, 1)
def test_delete_no_parent(self):
self.t.delete(10)
self.assertIsNone(self.t.lookup(10)[0])
self.assertEqual(self.t.lookup(5)[0].key, 5)
def test_one_child_no_parent(self):
#Test for one child and no parent, left side
self.t.delete(15)
self.t.delete(12)
self.t.delete(20)
self.t.delete(10)
self.assertEqual(self.t.lookup(5)[0].key, 5)
self.assertListEqual([x.key for x in self.t.lookup(2)], [2, 5])
self.assertListEqual([x.key for x in self.t.lookup(1)], [1, 2])
self.assertListEqual([x.key for x in self.t.lookup(3)], [3, 2])
def test_traverse(self):
self.assertEqual([1, 2, 3, 5, 10, 12, 15, 20], [x.key for x in self.t.traverse()])
def test_str(self):
self.assertEqual(self.t.__str__(), '1, 2, 3, 5, 10, 12, 15, 20')
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Sympy example: How to solve a differential equation using sympy
@author: a.perez
"""
import sympy as sy
sy.init_printing()
# Define a generic function u and its variable, t
u = sy.Function('u')
t = sy.symbols('t')
# We want to solve the differential equation u''(t) - u(t) = exp(t)
u_tt = sy.diff(u(t), t, t) # Second derivative of u wrt t
# (symbolic, since u is a generic function)
lhs = u_tt - u(t) # Left hand-side of the equation
rhs = sy.exp(t) # Right hand-side of the equation
eq = sy.Eq(lhs, rhs) # We create the equation
sol = sy.dsolve(eq, u(t)) # And we solve it using the function dsolve,
# wrt the function u(t)
# Now sol is the equation:
# u(t) = C2*exp(-t) + (C1 + t/2)*exp(t)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 21:55:23 2019
@author: telu
"""
# %% 1)
def liste_puissance(p, n):
return [i**p for i in range(n)]
print('Question 1)')
print(liste_puissance(1, 5), liste_puissance(2, 10))
# %% 2)
def dernier_chiffre(i):
i_str = str(i) # Transformation de i en string
c_str = i_str[-1] # Dernier chiffre, sous format string
c = int(c_str) # Conversion du dernier chiffre en entier
return c
print('Question 2)')
print(dernier_chiffre(50), dernier_chiffre(123),
dernier_chiffre(12)+dernier_chiffre(53))
# %% 3)
def liste_magique(p, n):
return [dernier_chiffre(i) for i in liste_puissance(p, n)]
print('Question 3)')
print(liste_magique(1, 5), liste_magique(2, 10))
# %% 4)
print('Question 4)')
print('- Affichage des listes magiques pour les premiers nombres pairs')
n = 10
for p in range(2, 13, 2):
print(liste_magique(p, n))
print('=> une fois sur deux, les chiffres sont les memes')
print('- Affichage de la somme des listes magiques pour deux nombres pairs consecutifs')
for p in [2, 6]:
liste1 = liste_magique(p, n)
liste2 = liste_magique(p+2, n)
liste = []
for i in range(n):
liste.append(liste1[i] + liste2[i])
print(liste)
print('=> les sommes sont toujours les mêmes')
# %% 5)
print('Question 5)')
print('- Affichage des listes magiques pour les premiers nombres pairs')
n = 10
for p in range(1, 12, 2):
print(liste_magique(p, n))
print('=> pour 1, 5, 9, ..., les chiffres sont les memes et vont de 1 a 9, dans le bon ordre')
print('=> pour 3, 7, 11, ..., les chiffres sont les memes et vont de 1 a 9, mais pas dans le bon ordre')
|
"""Utility file to seed system database from sample data in seed_data/"""
import datetime
from sqlalchemy import func
from model import Teacher, TeacherClass, Class, StudentClass, Student, StudentMeasure, Response, Measure, Subject, Objective, Question, QuestionAnswerChoice, AnswerChoice, connect_to_db, db
from server import app
def load_teachers():
"""Load a single teacher into database."""
print "Teachers"
teacher = Teacher(first_name="Maria",
last_name="Mendiburo",
username="[email protected]")
db.session.add(teacher)
db.session.commit()
def load_subjects():
"""Load two subjects into database from u.subject"""
print "Subjects"
for i, row in enumerate(open("seed_data/u.subject.txt")):
row = row.rstrip()
name, description, course_number = row.split("|")
subject = Subject(name=name,
description=description,
course_number=course_number)
db.session.add(subject)
db.session.commit()
def load_classes():
"""Load three classes into database from u.class."""
print "Classes"
for i, row in enumerate(open("seed_data/u.class.txt")):
row = row.rstrip()
subject_id, name = row.split("|")
_class = Class(subject_id=subject_id,
name=name)
db.session.add(_class)
db.session.commit()
def load_students():
"""Load students from u.student into database."""
print "Students"
for i, row in enumerate(open("seed_data/u.student.txt")):
row = row.rstrip()
first_name, last_name, grade, gender, username, math_placement, reading_grade_equivalent = row.split("|")
student = Student(
first_name=first_name,
last_name=last_name,
grade=grade,
gender=gender,
username=username,
math_placement=math_placement,
reading_grade_equivalent=reading_grade_equivalent)
db.session.add(student)
db.session.commit()
def load_measures():
"""Load rows into the measures table."""
print "Measures"
for i, row in enumerate(open("seed_data/u.measure.txt")):
row = row.rstrip()
class_id, flag, status = row.split("|")
measure = Measure(
class_id=class_id,
flag=flag,
status=status)
db.session.add(measure)
db.session.commit()
def load_teachers_classes():
"""Load rows into the teachers_classes association table"""
print "Teachers_Classes"
for i, row in enumerate(open("seed_data/u.teacher_class.txt")):
row = row.rstrip()
teacher_id, class_id, permission_level = row.split("|")
teacher_class = TeacherClass(teacher_id=teacher_id,
class_id=class_id,
permission_level=permission_level)
db.session.add(teacher_class)
db.session.commit()
def load_students_classes():
"""Load rows into the students_classes association table"""
print "Students_Classes"
for i, row in enumerate(open("seed_data/u.student_class.txt")):
row = row.rstrip()
student_id, class_id = row.split("|")
student_class = StudentClass(student_id=student_id,
class_id=class_id)
db.session.add(student_class)
db.session.commit()
def load_students_measures():
"""Load rows into the students_measures association table"""
print "Students_Measures"
for i, row in enumerate(open("seed_data/u.student_measure.txt")):
row = row.rstrip()
student_id, measure_id = row.split("|")
student_measure = StudentMeasure(student_id=student_id,
measure_id=measure_id)
db.session.add(student_measure)
db.session.commit()
def load_objectives():
"""Load rows into the objectives table"""
print "Objectives"
for i, row in enumerate(open("seed_data/u.objective.tsv")):
row = row.rstrip()
objective_number, name, description, class_id = row.split("\t")
objective = Objective(objective_number=objective_number,
name=name,
description=description,
class_id=class_id)
db.session.add(objective)
db.session.commit()
def load_questions():
"""Load survey questions into table"""
print "Questions"
for i, row in enumerate(open("seed_data/u.question.tsv")):
row = row.rstrip()
measure_id, objective_id, prompt, measure_type, question_type, question_content, position = row.split("\t")
question = Question(measure_id=measure_id,
objective_id=objective_id,
prompt=prompt,
measure_type=measure_type,
question_type=question_type,
question_content=question_content,
position=position)
db.session.add(question)
db.session.commit()
def load_answers_choices():
"""Load answer choices into table"""
print "Answers_Choices"
for i, row in enumerate(open("seed_data/u.answer_choice.tsv")):
row = row.rstrip()
text, value, position = row.split("\t")
answer_choice = AnswerChoice(text=text,
value=value,
position=position)
db.session.add(answer_choice)
db.session.commit()
def load_questions_answers_choices():
"""Load answer choices into table"""
print "Questions_Answers_Choices"
for i, row in enumerate(open("seed_data/u.question_answer.tsv")):
row = row.rstrip()
question_id, answer_choice_id = row.split("\t")
question_answer_choice = QuestionAnswerChoice(question_id=question_id,
answer_choice_id = answer_choice_id)
db.session.add(question_answer_choice)
db.session.commit()
def load_response():
"""Load answer choices into table"""
print "Responses"
for i, row in enumerate(open("seed_data/u.response.tsv")):
row = row.rstrip()
student_measure_id, question_id, response = row.split("\t")
response = Response(student_measure_id=student_measure_id,
question_id=question_id,
response=response)
db.session.add(response)
db.session.commit()
# def set_val_user_id():
# """Set value for the next user_id after seeding database"""
# # Get the Max user_id in the database
# result = db.session.query(func.max(User.user_id)).one()
# max_id = int(result[0])
# # Set the value for the next user_id to be max_id + 1
# query = "SELECT setval('users_user_id_seq', :new_id)"
# db.session.execute(query, {'new_id': max_id + 1})
# db.session.commit()
if __name__ == "__main__":
connect_to_db(app)
db.create_all()
load_teachers()
load_subjects()
load_classes()
load_students()
load_measures()
load_teachers_classes()
load_students_classes()
load_students_measures()
load_objectives()
load_questions()
load_answers_choices()
load_questions_answers_choices()
load_response()
# set_val_user_id()
|
"""This module define the functions for preprocessing the signal data"""
import numpy as np
def bandPassFilter(data, sampleRate=None, highpass=None, lowpass=None):
"""
Return the signal filtered between highpass and lowpass. Note that neither
highpass or lowpass should be above sampleRate/2.
Parameters
----------
data: numpy.ndarray
The signal
sampleRate: numeric, optional
The frequency at which the signal was recorded. By default it is the
same as the number of samples of the signal.
highpass: numeric, optional
The signal will be filtered above this value.
lowpass: numeric, optional
The signal will be filtered bellow this value.
Returns
-------
numpy.ndarray
The signal filtered betwen the highpass and the lowpass
"""
size = len(data)
if not sampleRate:
sampleRate = size
if highpass:
highpassP = int(highpass * size / sampleRate)
highpassN = -highpassP
else:
highpassP = highpassN = None
if lowpass:
lowpassP = int(lowpass * size / sampleRate)
lowpassN = -lowpassP
else:
lowpassP = lowpassN = size // 2
fft = np.fft.fft(data)
window = np.zeros(size)
window[highpassP:lowpassP] = 1
window[lowpassN:highpassN] = 1
filtered_fft = fft * window
return np.real(np.fft.ifft(filtered_fft))
|
"""
This script generate time series of tweet volumes per hour or per day.
Author: Sofiane Abbar
Run: python volume.py tweets.txt daily
"""
import time
from datetime import datetime
import json
from collections import defaultdict
import sys
try:
fname = sys.argv[1]
granularity = sys.argv[2]
except:
print "Provide path to data file and granularity (hourly or daily). Eg. python volume.py tweets.txt daily"
sys.exit()
def to_ts(tw_time):
return time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(tw_time,'%a %b %d %H:%M:%S +0000 %Y'))
def to_ts_h(tw_time):
return time.strftime('%Y-%m-%d %H', time.strptime(tw_time,'%a %b %d %H:%M:%S +0000 %Y'))
def to_ts_day(tw_time):
return time.strftime('%Y-%m-%d', time.strptime(tw_time,'%a %b %d %H:%M:%S +0000 %Y'))
h_ts = defaultdict(int)
if granularity == 'hourly':
funct = to_ts_h
else:
# default is daily
funct = to_ts_day
with open(fname) as f:
for line in f:
try:
o = json.loads(line)
h_ts[funct(o['created_at'])] += 1
except:
continue
for k in sorted(h_ts.keys()):
print '%s,%s' % (k, h_ts[k])
|
def getHeight(self,root):
#Write your code here
left, right = 0, 0
if root.left != None:
left = self.getHeight(root.left) + 1
if root.right != None:
right = self.getHeight(root.right) + 1
return max(left, right)
|
#!/usr/bin/env python
''''''''
#Requesting the YUE cis-linked gene webpage to find cis-regulatory element genomic coordinates that are linked to down- and up-regulated genes
''''''''
''''''''
#To find an API, right click a webpage in chrome and inspect element.
#You will see the html format for the website. If you have an input box to
#type in on the website (ie some where to type a gene name to get cis-elements linked to it)
#you need to open up each arrow (>) and click on the input box until it highlights something in the html code
#This is your API code that you will feed into requests.get
''''''''
import sys
import requests
f=open(sys.argv[1])
genes = f.readlines()
gene_names = ['CACNG8', 'TUBB3', 'PACSIN1']
#print gene_names
#for i in genes:
# fields = i.rstrip()
# gene_names.append(fields)
for i in gene_names:
r = requests.get('http://promoter.bx.psu.edu/ENCODE/get_human_linkage.php?assembly=hg19&gene='+i)
#the core of the request package. Basically the API url + whatever you want to feed into it (ie a gene name)
#print r.url
#print out how the url link will look like
#r.encoding = 'gb2312'
# print out the type of encoding your text file will be returned as. This can convert html format into rich text format, possible others?
print r.text
#this is how you return what is on a webpage
#print r.content
''''''
#reference API, this is what most API's will look like
''''''
#assembly=hg19&gene=
#http://promoter.bx.psu.edu/ENCODE/get_human_linkage.php?assembly=hg19&gene=SYNGR3
''''''
#feeding in parameters to url via dictionary
''''''
#with open(f, 'rU') as document:
#dic = {} # initiate dictionary
#for line in document:
#key, value = line[:-1].split("\t") #split by tab delimiter
#dic[key] = value
#should be in this format dic={'gene': 'SYNGR3'}
#you can also feed in a dictionary into the request.get function, pretty sweet!
#r = requests.get("http://promoter.bx.psu.edu/ENCODE/get_human_linkage.php?assembly=hg19&=", params=dic)
#http://docs.python-requests.org/en/latest/user/quickstart/
#request quickstart manual
|
# print("Hey World 😎"[1:2])
my_name = "Stephen"
# print(my_name)
name_legnth = len(my_name)
print(f"{my_name} is {name_legnth} letters long")
print(my_name.center(20, "*"))
print(type(3/4))
print(int(10))
print(float(10))
print(str(10))
print(chr(97))
print(round(2.34567, 2))
print(type(True))
print(chr(0x1F4A9))
print(type(None))
# print(my_name + 5)
number1, number2 = 10, "5"
print(number1)
print(number2)
first_name, last_name, year_of_birth = "George", "Wilson", 1975
username = first_name[0:3] + last_name[0:3] + str(year_of_birth)[2:4]
print(username)
|
#!/usr/bin/env python3
def getLifeDigit(num, final = False):
r = 0
for i in num:
r += int(i)
if final: return r
else: return getLifeDigit(str(r), True)
print(getLifeDigit(input("Date of Birth: ")))
|
# -*- coding: cp1250 -*-
__author__ = 'Piotr'
import doctest
import unittest
class recursive_calculate_list_of_number():
def suma(self,tab):
if len(tab) ==1:
return tab[0]
else:
return tab[0]+self.suma(tab[1:])
convString = "abcd"
def anagramik(a,b):
if(len(a)!=len(b)):
return False
is_okay = True
while is_okay!=True and i<=len(a):
for i in range(len(a)):
for j in range(len(b)):
if a[i]!=b[j]:
is_okay = False
++i
return True
def theSame(a,b):
is_ok = True
a = list(a)
b = list(b)
if len(a)!=len(b):
return False
while len(a)>0 and is_ok:
if a[0] == b[0]:
a.pop(0)
b.pop(0)
else:
is_ok = False
return is_ok
return True
def palindrom(string):
string = list(string)
while len(string)>1:
if string.pop(0)==string.pop():
print('dsadas')
else:
return False
return True
print(palindrom('absba'))
#print(theSame('123','124'))
#print(anagramik('sad','das'))
class test_recursive_calculate_list_of_number(unittest.TestCase):
def setUp(self):
self.Item = recursive_calculate_list_of_number()
def test_sums_equals(self):
self.assertEqual(self.Item.suma([1,2,3,4]),10)
if __name__ == "__main__":
unittest.main()
|
"""Generate N random points inside a given Box"""
import random
import rhinoscriptsyntax as rs
def main(box, n):
if not box or not n:
raise ValueError('Box or Length undefined')
points = []
for _ in range(0, n):
x = random.uniform(box[0][0], box[6][0])
y = random.uniform(box[0][1], box[6][1])
z = random.uniform(box[0][2], box[6][2])
points.append((x, y, z))
return points
def rhino():
box = rs.GetBox()
if not box:
return
length = rs.GetInteger("Enter length of points")
if not length:
return
points = main(box, length)
for point in points:
rs.AddPoint(point)
if __name__ == '__main__':
rhino()
|
#-------------------------------------------------------------------------------
# INTPROG Python Coursework
# James Taylor
# 368574
# Autumn Teaching Block 2014
#-------------------------------------------------------------------------------
from graphics import *
def main():
print("Patchwork Drawing Program up368574")
patchWSize, colourGroup = getInputs()
win, patchColours, patchTypes = drawPatchwork(patchWSize*100, colourGroup)
changePatchwork(win, patchWSize*100, patchColours, patchTypes, colourGroup)
def getInputs():
patchworkSize = getValidPatchworkSize()
colourGroup = getValidColours()
return patchworkSize, colourGroup
def getValidPatchworkSize():
print("Enter desired patchwork dimensions. Valid sizes are 5, 7, and 9.")
size = 0
validSizes = [5, 7, 9]
while size not in validSizes:
sizeStr = input("Size: ")
if sizeStr.isdigit():
size = eval(sizeStr)
if size not in validSizes:
print("Invalid input. Valid sizes are 5, 7, and 9,")
return size
def getValidColours():
colourGroup = []
validColours = ["red", "green", "blue", "yellow", "magenta", "cyan"]
print("Enter colours wanted in patchwork. Valid colours are ", end = "")
for validColour in validColours:
if validColour == validColours[-1]:
print("and " + validColour + ".")
else:
print(validColour, end = ", ")
for i in range(1, 5):
inputColour = ""
while inputColour not in validColours:
inputString = "Colour " + str(i) + ": "
inputColour = input(inputString).lower()
if inputColour in validColours:
colourGroup.append(inputColour)
else:
print("Invalid input. Valid inputs are ", end = "")
for validColour in validColours:
if validColour == validColours[-1]:
print("and " + validColour + ".")
else:
print(validColour, end = ", ")
return colourGroup
def drawPatchwork(winSize, colourGroup):
win = GraphWin("Patchwork", winSize, winSize)
win.setBackground("white")
patchIndex = 0
patchColourCount = 0
patchColours = [] #list of numbers, used as indices for colourGroup
patchTypes = [] #list of booleans, used to determine patch type
for i in range(0, winSize, 100):
for j in range(0, winSize, 100):
patchColours.append(patchColourCount % 4)
patchColour = colourGroup[patchColours[patchIndex]]
if i == 0 or j <= 100:
patchTypes.append(True) #Patch 1
else:
patchTypes.append(False) #Patch 2
patchType = patchTypes[patchIndex]
drawPatch(win, j, i, patchColour, patchType)
patchIndex = patchIndex + 1
patchColourCount = patchColourCount + 1
return win, patchColours, patchTypes
def changePatchwork(win, winSize, patchColours, patchTypes, colourGroup):
while win.isOpen():
try:
patchNo, pX, pY = calculateClickedPatch(win.getMouse(), winSize)
if patchColours[patchNo] == 3:
patchColours[patchNo] = 0
else:
patchColours[patchNo] = patchColours[patchNo] + 1
patchColour = colourGroup[patchColours[patchNo]]
patchType = patchTypes[patchNo]
drawPatch(win, pX, pY, patchColour, patchType)
except GraphicsError:
print("Window was closed")
def calculateClickedPatch(click, winSize):
patchNumber = 0
clickX = click.getX()
clickY = click.getY()
for i in range(0, winSize, 100):
for j in range(0, winSize, 100):
if clickY >= i and clickY < (i + 100) \
and clickX >= j and clickX < (j + 100):
return patchNumber, j, i
patchNumber = patchNumber + 1
def drawPatch(win, x, y, patchColour, patchType):
if patchType: #Patch 1
drawPatch1(win, x, y, patchColour)
else: #Patch 2
drawPatch2(win, x, y, patchColour)
def drawPatch1(win, x, y, colour):
difference = y - x
for i in range(x, x + 99, 10):
lineLeft = Line(Point(x, difference + i), Point(i + 10, y + 100))
lineLeft.setFill(colour)
lineLeft.draw(win)
lineRight = Line(Point(x + 100, difference + i + 10 ), Point(i , y))
lineRight.setFill(colour)
lineRight.draw(win)
def drawPatch2(win, x, y, colour):
for i in range(y, y + 99, 10):
p1, p2 = Point(x, i), Point(x + 99, i + 10)
if i % 20 == 0:
for j in [x, x+25, x+55, x+85]:
if j == x or j == x + 85:
p1, p2 = Point(j, i), Point(j + 15, i + 10)
drawRectangle(win, p1, p2, colour)
else:
p1, p2 = Point(j, i), Point(j + 20, i + 10)
drawRectangle(win, p1, p2, colour)
else:
for j in range(x + 10, x+ 99, 30):
p1, p2 = Point(j, i), Point(j + 20, i + 10)
drawRectangle(win, p1, p2, colour)
def drawRectangle(win, p1, p2, colour):
rectangle = Rectangle(p1, p2)
rectangle.setFill(colour)
rectangle.draw(win)
main()
|
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
class ABCDataset(object):
"""Abstract base class for a dataset.
"""
__metaclass__ = ABCMeta
@abstractmethod
def add(self, iterable): # pragma: no cover
"""Adds a set of objects from the provided iterable
to the dataset.
If any object has no uids, the dataset will generate a new
uid for it. If the object has already an uid, it won't add the
object if an object with the same type uid already exists.
If the user wants to replace an existing object in the container
there is an 'update' method for that purpose.
Parameters
----------
iterable : iterable of objects
the new set of objects that will be included in the container.
Returns
-------
uids : list of uuid.UUID
The uids of the added objects.
Raises
------
ValueError :
when there is an object with an uids that already exists
in the dataset.
"""
@abstractmethod
def update(self, iterable): # pragma: no cover
"""Updates a set of objects from the provided iterable.
Takes the uids of the objects and searches inside the dataset for
those objects. If the object exists, they are replaced in the
dataset. If any object doesn't exist, it will raise an exception.
Parameters
----------
iterable : iterable of objects
the objects that will be replaced.
Raises
------
ValueError :
If any object inside the iterable does not exist.
"""
@abstractmethod
def get(self, uid): # pragma: no cover
"""Returns a copy of the object with the 'uid' id.
Parameters
----------
uid : uuid.UUID
the uid of the object
Raises
------
KeyError :
when the object is not in the container.
Returns
-------
object :
A copy of the internally stored info.
"""
@abstractmethod
def remove(self, uids): # pragma: no cover
"""Remove the object with the provided uids from the container.
The uids inside the iterable should exists in the container. Otherwise
an exception will be raised.
Parameters
----------
uids : iterable of uuid.UUID
the uids of the objects to be removed.
Raises
------
KeyError :
If any object doesn't exist.
"""
@abstractmethod
def iter(self, uids=None, item_type=None): # pragma: no cover
"""Generator method for iterating over the objects of the container.
It can receive any kind of sequence of uids to iterate over
those concrete objects. If nothing is passed as parameter, it will
iterate over all the objects.
Parameters
----------
uids : iterable of uuid.UUID, optional
sequence containing the uids of the objects that will be
iterated. When the uids are provided, then the objects are
returned in the same order the uids are returned by the iterable.
If uids is None, then all objects are returned by the iterable
and there is no restriction on the order that they are returned.
item_type: CUDSItem enum
Restricts iteration only to the specified item type.
e.g. CUDSItem.PARTICLE will only iterate over particles in
a Particles container.
Yields
------
object :
The object item.
Raises
------
KeyError :
if any of the ids passed as parameters are not in the dataset.
"""
@abstractmethod
def has(self, uid): # pragma: no cover
"""Checks if an object with the given uid already exists
in the dataset.
Parameters
----------
uid : uuid.UUID
the uid of the object
Returns
-------
True if the uid is found, False otherwise.
"""
@abstractmethod
def has_type(self, item_type): # pragma: no cover
"""Checks if the specified CUDSItem type is present
in the dataset.
Parameters
----------
item_type : CUDSItem
The CUDSItem enum of the type of the items to return the count of.
Returns
-------
True if the type is present, False otherwise.
"""
@abstractmethod
def count_of(self, item_type): # pragma: no cover
""" Return the count of item_type in the container.
Parameters
----------
item_type : CUDSItem
The CUDSItem enum of the type of the items to return the count of.
Returns
-------
count : int
The number of items of item_type in the dataset.
Raises
------
ValueError :
If the type of the item is not supported in the current
dataset.
"""
@abstractmethod
def __len__(self):
"""Returns the total number of items in the container.
Returns
-------
count : int
The number of items in the dataset.
"""
def __contains__(self, item):
"""Implements the `in` interface. Behaves as the has() method.
"""
return self.has(item)
|
"""he function object in question
remembers values in enclosing scopes regardless of whether those scopes are still
present in memory. In effect, they have attached packets of memory (a.k.a. state re-
tention), which are local to each copy of the nested function created, and often provide
a simple alternative to classes in this role.
simple function factory
Factory functions (a.k.a. closures) are sometimes used by programs that need to gen-
erate event handlers on the fly in response to conditions at runtime. For instance,
imagine a GUI that must define actions according to user inputs that cannot be antici-
pated when the GUI is built. In such cases, we need a function that creates and returns
another function, with information that may vary per function made."""
def maker(N):
def action(X):
return X**N
return action
f = maker(2) # pass 2 to argument N
print f
""" what we get back is a reference to the generated nested function—the one created when
the nested def runs. If we now call what we got back from the outer function:"""
print f(3)
print f(4)
#the nested function remembers the value of N in maker
g = maker(3) #g remembers 3 ,f remembers 2
print g(4)
print f(4)
#each call to a factory function like this gets its own set of state
#information
#as a lambda function
def maker1(N):
return lambda X:X ** N
h = maker1(3)
print h(4)
#In short, the syntax arg=val in a
"""def header means that the argument arg will default to the value val if no real value is
passed to arg in a call. This syntax is used here to explicitly assign enclosing scope state
to be retained."""
"""Nested scopes, defaults, and lambdas
Although they see increasing use in def s these days, you may be more likely to care
about nested function scopes when you start coding or reading lambda expressions.
We’ve met lambda briefly and won’t cover it in depth until Chapter 19, but in short, it’s
an expression that generates a new function to be called later, much like a def statement.
Because it’s an expression, though, it can be used in places that def cannot, such as
within list and dictionary literals.
Like a def , a lambda expression also introduces a new local scope for the function it
creates. Thanks to the enclosing scopes lookup layer, lambda s can see all the variables
that live in the functions in which they are coded. Thus, the following code—a variation
on the factory we saw earlier—works, but only because the nested scope rules are
applied:"""
"""Like a def , a lambda expression also introduces a new local scope for the function it
creates. Thanks to the enclosing scopes lookup layer, lambda s can see all the variables
that live in the functions in which they are coded. Thus, the following code—a variation
on the factory we saw earlier—works, but only because the nested scope rules are
applied:"""
"""
Loop variables may require defaults, not scopes
There is one notable exception to the rule I just gave (and a reason why I’ve shown you
the otherwise dated default argument technique we just saw): if a lambda or def defined
within a function is nested inside a loop, and the nested function references an enclosing
scope variable that is changed by that loop, all functions generated within the loop will
have the same value—the value the referenced variable had in the last loop iteration.
In such cases, you must still use defaults to save the variable’s current value instead.
This may seem a fairly obscure case, but it can come up in practice more often than
you may think, especially in code that generates callback handler functions for a num-
ber of widgets in a GUI—for instance, handlers for button-clicks for all the buttons in
a row. If these are created in a loop, you may need to be careful to save state with
defaults, or all your buttons’ callbacks may wind up doing the same thing.
Here’s an illustration of this phenomenon reduced to simple code: the following at-
tempts to build up a list of functions that each remember the current variable i from
the enclosing scope
"""
|
for x in [1,2,3,4]:print x **2
import os
f = open('script2.py')
"""print f.next()
print f.next()
l = [1,2,3]
i = iter(l)
while True:
try:
X = next(i)
except StopIteration:
break
print X **2"""
for line in f:
print line
|
def bonAppetit(bill, k, b):
#print bill
bill.pop(k)
#print bill
total_bill = sum(bill)
#print total_bill
anns_share = total_bill/2
if anns_share < b:
return b-anns_share
elif anns_share == b:
return " Bon Appetit "
print bonAppetit([3,10,2,9],1,12)
|
def sumpairs(arr,s):
count = 0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
if arr[i]+arr[j] == s:
count += 1
return count
print sumpairs([1,2,3,4,5],5)
|
#__str__ to return the card name as a string, and __gt__ and __lt__ to allow the cards to be compared against each other.
class Card:
def __init__(self,value,suit):
self.value = value
self.suit = suit
def __str__(self) -> str:
value_conv = {"A": "Ace",2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", "J": "Jack", "Q": "Queen", "K": "King"}
return value_conv[self.value] + " of " + self.suit
def get_value(self):
value_conv = {"A": "Ace",2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", "J": "Jack", "Q": "Queen", "K": "King"}
return value_conv[self.value]
def __lt__(self,card) -> bool:
card_strength = {"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10,"J":11, "Q":12, "K":13, "A":14}
suit_strength = {"Spades":4,"Diamonds":3,"Clubs":2,"Hearts":1}
try:
if card_strength[str(self.value)] < card_strength[str(card.value)]:
return True
if card_strength[str(self.value)] == card_strength[str(card.value)] and suit_strength[self.suit] < suit_strength[card.suit]:
return True
except:
print(str(self) + " -> " + str(card))
return False
def __gt__(self,card) -> bool:
card_strength = {"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10,"J":11, "Q":12, "K":13, "A":14}
suit_strength = {"Spades":4,"Diamonds":3,"Clubs":2,"Hearts":1}
if card_strength[str(self.value)] > card_strength[str(card.value)]:
return True
if card_strength[str(self.value)] == card_strength[str(card.value)] and suit_strength[self.suit] > suit_strength[card.suit]:
return True
return False
card1 = Card(5,"Spades")
card2 = Card(6,"Clubs")
print(card1 == card2)
print(card1 > card2)
|
with open(file= "new.txt", mode= "r+") as file_Obj:
#brand_new = file_Obj.write(str(58))
file_Obj.write(input(print("Nhao 1 chuoi vao file: ")))
file_Obj.seek(0)
brand_new1 = file_Obj.read()
#file_Obj.close()
print(brand_new1)
|
"""
A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.
He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).
His mother looks out of a window 1.5 meters from the ground.
How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?
Three conditions must be met for a valid experiment:
Float parameter "h" in meters must be greater than 0
Float parameter "bounce" must be greater than 0 and less than 1
Float parameter "window" must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.
Note:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.
Examples:
- h = 3, bounce = 0.66, window = 1.5, result is 3
- h = 3, bounce = 1, window = 1.5, result is -1
(Condition 2) not fulfilled).
"""
def bouncing_ball(h, bounce, window):
count=1
if h>0 and (bounce>0 and bounce<1) and (window<h):
while h*bounce>window:
count+=2
h = h*bounce
return count
return -1
|
import random
import collections
import time
import matplotlib.pyplot as plt
numbers = []
results = []
for i in range(1000):
numbers.append(random.randint(1, 10))
choice = int(input('Выберите метод(1 или 2)'))
start_time = time.time()
if choice == 1:
result = collections.Counter(numbers)
print(f'{result} \n Время:{time.time() - start_time}')
for i in range(1, 11):
results.append(result.get(i))
elif choice == 2:
count = 0
for z in range(1, 11):
for i in range(1000):
if numbers[i] == z:
count += 1
print(f"'{z}': {count} ")
results.append(count)
count = 0
print(time.time() - start_time)
x = [x for x in range(1, 11)]
plt.bar(x, results)
plt.show()
|
#Load file
FILENAME = "eventLocations.csv"
with open(FILENAME) as f:
lines = f.readlines()
def isPreTrail(date): #LemmingTrail happened August 2013
if date[:4] == '2014':
return False
elif date[:4] == '2013' and int(date[5:7]) > 8:
return False
else:
return True
dates = [l.split()[-1][:10] for l in lines[1:]]
bostondates = dates[245:]
wmassdates = dates[:245]
predates = (len([d for d in bostondates if isPreTrail(d)]), len([d for d in wmassdates if isPreTrail(d)]))
print "Boston events with date field before Lemming Trail:", predates[0]
print "Boston events with date field after Lemming Trail:", len(bostondates) - predates[0]
print "Western Mass events with date field before Lemming Trail:", predates[1]
print "Western Mass events with date field after Lemming Trail:", len(wmassdates)-predates[1]
|
"""
=================== TASK 1 ====================
* Name: Power to the Number
*
* Write a function `numpower()` that will for the
* passed based number `num` and exponent `expo`
* return the value of the number `num` raised to
* the power of `expo`.
*
* Note: Please describe in details possible cases
* in which your solution might not work. It is not
* allowed to use built-in operators and functions
* for this task.
*
* Use main() function to test your solution.
===================================================
"""
import numbers
def numpower(num, expo):
i = 1
res = 1
""" Making generic while loop so we multiply num with itself the precise number of times """
""" pom expo helps variable for storing the original value - we need to handle both negative and positive ecpos """
pom_expo = abs(expo)
while i <= pom_expo:
res = res * num
i = i + 1
""" In cases that we have negative exponent """
if expo < 0:
res = 1 / res
return res
def main():
num = 2
expo = -4
res = numpower(num, expo)
print("Exponent of a number: ", res)
main()
|
"""Important to point out that nearly all hidden payroll is paid to cops. Quantify that here"""
import pandas as pd
import sys
sys.path.insert(0, "../../Final_Results")
df = pd.read_csv("../../Final_Results/Final_by_Agency_Type_SP.csv", index_col=0)
yr = list(range(2016,2020))
df.rename(columns = {str(x):x for x in yr}, inplace=True)
def breakdown_hidden_payroll():
"""Where is hidden payroll paid?"""
hidden_payroll = df[df["Cost Type"] == "Hidden Payroll Costs"][yr].mean(axis=1)
hidden_payroll = hidden_payroll[hidden_payroll >= 1000]
print("the following agencies have more than 1k in hidden payroll")
print(hidden_payroll.index)
|
#-*- encoding=utf-8 -*-
from askmath.models import Lesson
class LessonSorting():
"""
Class for ordering the lessons using topological sorting.
"""
def __init__(self, initial_lessons):
"""
This function takes as a parameter a list of lessons that do not have prerequisites.
"""
self.__lessons = list(initial_lessons)
self.__lessons_levels = {}
self.__lessons_in_levels = []
def sorting(self):
level = 0
max_loops = len(self.__lessons) * len(self.__lessons)
while max_loops > 0:
if not self.__lessons:
break
temp_lessons_level = []
temp_lessons_in_levels = []
for index, l in enumerate(self.__lessons):
if not l in self.__lessons_in_levels:
insert = True
for r in l.get_requirements():
if not r in self.__lessons_in_levels:
insert=False
if insert:
temp_lessons_level.append(l)
temp_lessons_in_levels.append(l)
if temp_lessons_in_levels:
self.__lessons_levels[level] = temp_lessons_level
self.__lessons_in_levels.extend(temp_lessons_level)
level +=1
max_loops -=1
def get_lessons_level(self):
self.sorting()
return self.__lessons_levels
def get_lessons_in_level(self):
self.sorting()
return self.__lessons_in_levels
|
from tkinter import *
class SimpleAddCal:
def __init__(self, win):
# Labels
self.lbl1 = Label(win, text = "First Number")
self.lbl1.place(x = 100, y = 50)
self.lbl2 = Label(win, text = "Second Number")
self.lbl2.place(x = 100, y = 100)
self.lbl3 = Label(win, text = "Result")
self.lbl3.place(x = 100, y = 200)
# Entries
self.t1 = Entry(bd = 3)
self.t2 = Entry()
self.t3 = Entry()
self.t1.place(x = 200, y = 50)
self.t2.place(x = 200, y = 100)
self.t3.place(x = 200, y = 200)
# Butoons
self.btn1 = Button(win, text = 'Add', command = self.add)
self.btn2 = Button(win, text = 'Subtract', command = self.sub)
self.btn1.place(x = 100, y = 150)
self.btn2.place(x = 200, y = 150)
# Trigger
# Addition Trigger
def add(self):
self.t3.delete(0, 'end')
num1 = int(self.t1.get())
num2 = int(self.t2.get())
result = num1 + num2
self.t3.insert(END, str(result))
# Subtract Trigger
def sub(self):
self.t3.delete(0, 'end')
num1 = int(self.t1.get())
num2 = int(self.t2.get())
result = num1 - num2
self.t3.insert(END, str(result))
window = Tk()
mywin = SimpleAddCal(window)
window.title('Tclassified.com Calculator')
window.geometry('500x400+10+10')
window.mainloop()
|
from tkinter import *
from tkinter import ttk
import sqlite3
class ProductDB :
# Will hold database connection
db_conn = 0
# A cursor is used to traverse the records of a result
theCursor = 0
# Will store the current student selected
curr_student = 0
def setup_db(self):
# Open or create database
self.db_conn = sqlite3.connect('product.db')
# The cursor traverses the records
self.theCursor = self.db_conn.cursor()
# Create the table if it doesn't exist
try:
self.db_conn.execute("CREATE TABLE if not exists Products(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, PNum TEXT NOT NULL, GName TEXT NOT NULL, PDesc TEXT NOT NULL, SQuant INTEGER NOT NULL);")
self.db_conn.commit()
except sqlite3.OperationalError:
print("ERROR : Table not created")
def prod_submit(self):
# Insert products in the db
self.db_conn.execute("INSERT INTO Products (PNum, GName, PDesc, SQaunt) " +
"VALUES ('" +
self.pn_entry_value.get() + "', '" +
self.gn_entry_value.get() + "', '" +
self.pd_entry_value.get() + "', '" +
self.sq_entry_value.get() + "')")
# Clear the entry boxes
self.pn_entry.delete(0, "end")
self.gn_entry.delete(0, "end")
self.pd_entry.delete(0, "end")
self.sq_entry.delete(0, "end")
# Update list box with product list
self.update_listbox()
def update_listbox(self):
# Delete items in the list box
self.list_box.delete(0, END)
# Get products from the db
try:
result = self.theCursor.execute("SELECT ID, PNum, GName, PDesc, SQuant FROM Products")
# You receive a list of lists that hold the result
for row in result:
prod_id = row[0]
prod_pnum = row[1]
prod_gname = row[2]
prod_pdesc = row[3]
prod_squant = row[4]
# Put the product in the list box
self.list_box.insert(prod_id,
prod_pnum + " " +
prod_gname + " " +
prod_pdesc + " " +
prod_squant)
except sqlite3.OperationalError:
print("The Table Doesn't Exist")
except:
print("1: Couldn't Retrieve Data From Database")
# Load listbox selected product into entries
def load_product(self, event=None):
# Get index selected which is the product id
lb_widget = event.widget
index = str(lb_widget.curselection()[0] + 1)
# Store the current product index
self.curr_product = index
# Retrieve product list from the db
try:
result = self.theCursor.execute("SELECT ID, PNum, GName, PDesc, SQuant FROM Products WHERE ID=" + index)
# You receive a list of lists that hold the result
for row in result:
prod_id = row[0]
prod_pnum = row[1]
prod_gname = row[2]
prod_pdesc = row[3]
prod_squant = row[4]
# Set values in the entries
self.pn_entry_value.set(prod_pnum)
self.gn_entry_value.set(prod_gname)
self.pd_entry_value.set(prod_pdesc)
self.sq_entry_value.set(prod_squant)
except sqlite3.OperationalError:
print("The Table Doesn't Exist")
except:
print("2 : Couldn't Retrieve Data From Database")
# Update product info
def update_product(self, event=None):
# Update student records with change made in entry
try:
self.db_conn.execute("UPDATE Products SET PNum='" +
self.pn_entry_value.get() +
"', GName='" +
self.gn_entry_value.get() +
"', PDesc='" +
self.pd_entry_value.get() +
"', SQuant='" +
self.sq_entry_value.get() +
"' WHERE ID=" +
self.curr_product)
self.db_conn.commit()
except sqlite3.OperationalError:
print("Database couldn't be Updated")
# Clear the entry boxes
self.pn_entry.delete(0, "end")
self.gn_entry.delete(0, "end")
self.pd_entry.delete(0, "end")
self.sq_entry.delete(0, "end")
# Update list box with product list
self.update_listbox()
def __init__(self, root):
root.title("SuperMarket Inventory Application")
root.geometry("270x340")
# ----- 1st Row -----
pn_label = Label(root, text="Product Number")
pn_label.grid(row=0, column=0, padx=10, pady=10, sticky=W)
# Will hold the changing value stored first name
self.pn_entry_value = StringVar(root, value="")
self.pn_entry = ttk.Entry(root,
textvariable=self.pn_entry_value)
self.pn_entry.grid(row=0, column=1, padx=10, pady=10, sticky=W)
# ----- 2nd Row -----
gn_label = Label(root, text="General Name")
gn_label.grid(row=1, column=0, padx=10, pady=10, sticky=W)
# Will hold the changing value stored last name
self.gn_entry_value = StringVar(root, value="")
self.gn_entry = ttk.Entry(root,
textvariable=self.gn_entry_value)
self.gn_entry.grid(row=1, column=1, padx=10, pady=10, sticky=W)
# ----- 2nd Row -----
pd_label = Label(root, text="Product Description")
pd_label.grid(row=2, column=0, padx=10, pady=10, sticky=W)
# Will hold the changing value stored first name
self.pd_entry_value = StringVar(root, value="")
self.pd_entry = ttk.Entry(root,
textvariable=self.pd_entry_value)
self.pd_entry.grid(row=2, column=1, padx=10, pady=10, sticky=W)
# ----- 3rd Row -----
sq_label = Label(root, text="Stock Quantity")
sq_label.grid(row=3, column=0, padx=10, pady=10, sticky=W)
# Will hold the changing value stored last name
self.sq_entry_value = StringVar(root, value="")
self.sq_entry = ttk.Entry(root,
textvariable=self.sq_entry_value)
self.sq_entry.grid(row=3, column=1, padx=10, pady=10, sticky=W)
# ----- 4th Row -----
self.submit_button = ttk.Button(root,
text="Submit",
command=lambda: self.prod_submit())
self.submit_button.grid(row=4, column=0,
padx=10, pady=10, sticky=W)
self.update_button = ttk.Button(root,
text="Update",
command=lambda: self.update_product())
self.update_button.grid(row=4, column=1,
padx=10, pady=10)
# ----- 5th Row -----
scrollbar = Scrollbar(root)
self.list_box = Listbox(root)
self.list_box.bind('<<ListboxSelect>>', self.load_product)
self.list_box.insert(1, "Products Here")
self.list_box.grid(row=5, column=0, columnspan=4, padx=10, pady=10, sticky=W+E)
# Call for database to be created
self.setup_db()
# Update list box with student list
self.update_listbox()
#Get the root window object
root = Tk()
#Create the calculator
prodDB = ProductDB(root)
#Run the app until exited
root.mainloop()
|
# Given a square matrix, calculate the absolute difference between the sums of its diagonals.
# https://www.hackerrank.com/challenges/diagonal-difference/problem
def diagonalDifference(arr):
diagonalSum = 0
for i in range(n):
diagonalSum = diagonalSum + (arr[i][i] - arr[i][n-i-1])
return abs(diagonalSum)
|
# Lily has a chocolate bar that she wants to share it with Ron for his birthday.
# Each of the squares has an integer on it. She decides to share a contiguous segment
# of the bar selected such that the length of the segment matches Ron's birth month and
# the sum of the integers on the squares is equal to his birth day.
# You must determine how many ways she can divide the chocolate.
# https://www.hackerrank.com/challenges/the-birthday-bar/problem
def arraySum(arr):
sumArray = 0
for element in arr:
sumArray+=element
return sumArray
def birthday(s,d,m):
sharedChocolate = 0
if len(s) == m and arraySum(s) == d:
sharedChocolate = 1
return sharedChocolate
for chocolate in range(len(s)-(m-1)):
if arraySum(s[chocolate:(m+chocolate)]) == d:
sharedChocolate+=1
return sharedChocolate
|
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
# https://projecteuler.net/problem=4
def p(x):
z=x
y=0
while int(x) > 0:
y=y*10+x%10
x=int(x/10)
return y==z
def f():
for i in range (1000000,10000,-1):
if p(i):
for j in range (999,100,-1):
if i % j == 0 and i / j in range(100,1000):
return (i, j, int(i/j) )
print(f())
|
#build a block of code that will excute whenever we tell it to execute
def my_function_name(name):
print("Hello, {}!".format(name))
my_function_name("Jen")
#we mainly want functions to do only ONE thing but do ONE thing WELL
#if you need the funciton to do more things, then make more functions
#and have them call those "earlier" functions
#that makes debugging much easier
#you'll typically not use print as the final command, you'll use return
#you'll put the print command where you run the function if you want it printed
#you can assign the output (what's returned) to a variable
#then you can print that variable or work with it otherwise
|
#anytime you're thinking about returning a list from a function
#you can return a generator
#the output items are calculated as needed
#range is the mathematical promise of integers, that's really
#a generator
#this calculates it only when we need it
#it's better on memory
def gen_odd_num(less_than):
for x in range(less_than):
if x % 2 == 1:
yield x
#yield
print(gen_odd_num(101))
for i in gen_odd_num(101):
print(i)
#we cannot index a generator
|
import person
class Customer(person):
def __init__(self, name, address, telNumber, customerNumber, mailingList):
Person.__init__(self, name, address, telNumber)
self.__customerNumber = customerNumber
self.__mailingList = mailingList
def customerMailingChoice(self):
customerChoice = input('Would you like to be added to our mailing list? ')
if customerChoice == 'yes':
self.__mailingList = true
else:
self.__mailingList = false
def setCustomerNumber(self):
self.__customerNumber = customerNumber
def getCustomerNumber(self):
return self.__customerNumber
|
#[email protected]
#ask the user for 2 integers
def getNumber():
try:
numberOne = int(input('Enter the first number: '))
except ValueError:
print('This is not an interger! Try again.')
numberOne = int(input('Enter the first number: '))
else:
return numberOne
def getNumberTwo():
try:
numberTwo = int(input('Enter the second number: '))
except ValueError:
print('This is not an interger! Try again.')
numberTwo = int(input('Enter the second number: '))
else:
return numberTwo
#print the larger value
def compareNumbers(numberOne, numberTwo):
print(max(numberOne, numberTwo))
print('This is the larger number of the two')
def main():
import time
numberOne = getNumber()
numberTwo = getNumberTwo()
compareNumbers(numberOne, numberTwo)
time.sleep(5)
main()
|
# An animal shelter,
# which holds only dogs and cats, operates on a strictly"
# first in, first out" basis. People must adopt either the"oldest"
# (based on arrival time) of all animals at the shelter,
# or they can select whether they would prefer a dog or a cat
# (and will receive the oldest animal of that type).
# They cannot select which specific animal they would like.
# Create the data structures to maintain this system
# and implement operations such as enqueue, dequeueAny, dequeueDog,
# and dequeueCat. You may use the built-in Linked list data structure.
from queue import Queue
class AnimalQueue:
def __init__(self):
self.dogQueue = Queue()
self.catQueue = Queue()
self.otherQueue = Queue()
self.counter = 0
def enqueue(self, name, animal):
if animal == "dog":
self.dogQueue.push((name, self.counter))
if animal == "cat":
self.catQueue.push((name, self.counter))
else:
self.otherQueue.push((name, self.counter))
self.counter += 1
def dequeueCat(self):
result, _ = self.catQueue.pop()
return result
def dequeueDog(self):
result, _ = self.dogQueue.pop()
return result
def dequeueOther(self):
result, _ = self.otherQueue.pop()
return result
def dequeueAny(self):
_, dogAge = self.dogQueue.peek()
_, catAge = self.catQueue.peek()
_, otherAge = self.otherQueue.peek()
oldest = min(dogAge, catAge, otherAge)
if oldest == dogAge:
result, _ = self.dogQueue.pop()
if oldest == catAge:
result, _ = self.catQueue.pop()
else:
result, _ = self.otherQueue.pop()
return result
animalQueue = AnimalQueue()
animalQueue.enqueue("fluffy", "cat")
animalQueue.enqueue("axel", "dog")
print(animalQueue.dequeueAny())
|
# Given string inputString:
# Find if the the string contains only unique characters
# Naive
# Runtime O(n^2)
def naiveFind(inputString) -> bool:
for index, character in enumerate(inputString):
for otherCharacter in inputString[index+1:]:
if character == otherCharacter:
return False
return True
# Efficient without any data structures
# Runtime O(n log n)
def efficientNoDataStructuresFind(inputString) -> bool:
inputString = sorted(inputString)
for index, character in enumerate(inputString):
if index == len(inputString)-1:
return True
if character == inputString[index+1]:
return False
# Efficient find
# runtime O(n)
def efficientFind(inputString) -> bool:
dictionary = {}
for character in inputString:
if ord(character) in dictionary:
return False
else:
dictionary[ord(character)] = character
return True
correct = "world"
incorrect = "hello"
# Should return True
print(naiveFind(correct))
print(efficientNoDataStructuresFind(correct))
print(efficientFind(correct))
# Should return False
print(naiveFind(incorrect))
print(efficientNoDataStructuresFind(incorrect))
print(efficientFind(incorrect))
|
# Rotate a matrix 90 degrees
def rotate(matrix):
return list(zip(*matrix[::-1]))
matrix = [[1, 2], [3, 4]]
print(rotate(matrix))
|
#! /usr/bin/env python2.7
def array_merger(array_list):
"""
This function can be used to sort and merge k sorted arrays , where k is the number of arrays
"""
new_array = []
length_array = len(array_list)
range_array = range(length_array)
array_tmp = [array_list[array_index].pop(0) for array_index in range_array]
while array_tmp:
combined_value = zip(range_array,array_tmp)
min_value = min(combined_value, key = lambda x:x[1])
new_array.append(min_value[1])
try:
new_replace_element = array_list[min_value[0]].pop(0)
except Exception :
array_tmp.pop(min_value[0])
else:
array_tmp[min_value[0]] = new_replace_element
return new_array
if __name__ == "__main__":
print array_merger([[3,6,10],[2,4,5]])
|
class Vehicle():
def __init__(self,brand_name, color):
self.brand_name = brand_name
self.color = color
def getBrandName(self):
return self.brand_name
class Car(Vehicle):
def __init__(self,brand_name, model, color):
super().__init__(brand_name,color)
self.model = model
def get_Description(self):
return "Car Name: " + self.getBrandName() + self.model + " Color:" + self.color
car = Car("Audi ", "r8", " Red")
print("Car description:", car.get_Description())
print("Brand name:", car.getBrandName())
|
for x in xrange(100,1000):
print x
square = False
for i in xrange(10, x):
if i*i == x:
print "perfect square"
square = True
break
elif i*i > x:
print "not a perfect square"
break
if square == False:
prime = True
for i in xrange(2, x/2):
if x &i ==0:
prime = False
break
if prime == True:
print "prime!"
|
class A(object):
def __init__(self, a, b):
self.a = a
self.b = b
def change_first(first):
first.a = 6
first.b = 7
first = A(4,5)
change_first(first)
print(first.a, first.b)
|
def divide_by_zero_with_generic_exception(dividend):
try:
result = dividend / 0
except Exception as e:
print("Exception occurred!")
def divide_by_zero_with_exception(dividend):
try:
result = dividend / 0
except ZeroDivisionError as e:
print("Illegal operation: Division by zero")
if __name__ == '__main__':
divide_by_zero_with_generic_exception(5)
divide_by_zero_with_exception(5)
|
def solve():
simple_pirates = 1
coins = 119
found = False
while simple_pirates < 100:
simple_reward = 0
while simple_reward < 100:
simple_reward = simple_reward + 1
deputy_reward = 2 * simple_reward
chief_reward = 5 * simple_reward
result = simple_pirates * simple_reward + deputy_reward + chief_reward
print("Result: pirates=%d, reward=%d, result=%d" % (simple_pirates, simple_reward, result))
if result > coins:
break
elif result == coins:
found = True
break
if found:
break
simple_pirates = simple_pirates + 1
if __name__ == '__main__':
solve()
|
def use_map(list):
print("\nDemo of map function")
doubles = map(lambda num: num * 2, list)
for number in doubles:
print(number)
def use_filter(list):
print("\nDemo of filter function")
uneven = filter(lambda n: n % 2 != 0, list)
for number in uneven:
print(number)
def use_list_comprehension_instead_of_map(list):
print("\nDemo of list comprehension instead of map")
doubles = [num * 2 for num in list]
for number in doubles:
print(number)
def use_list_comprehension_instead_of_filter(list):
print("\nDemo of list comprehension instead of filter")
uneven = [num for num in list if num % 2 != 0]
for number in uneven:
print(number)
if __name__ == '__main__':
values = [1, 6, 8]
use_map(values)
use_list_comprehension_instead_of_map(values)
mixed_values = [1, 4, 8, 9, 13]
use_filter(mixed_values)
use_list_comprehension_instead_of_filter(mixed_values)
|
#!/usr/bin/python
print("Demo of some basic list operations")
print("")
print("")
def print_list(names):
for name in names:
print("%s" % (name))
print("-----END OF LIST------")
names = []
names.append("Martin")
print_list(names)
print("list content after insert")
names.insert(0, "Kalle")
print_list(names)
del names[0]
print("list content after del")
print_list(names)
if names.count("Joe") > 0:
names.remove("Joe")
names.append("Bill")
names.append("Lotta")
names.append("Paul")
print_list(names)
names.sort()
print_list(names)
del names[1]
print_list(names)
print("Getting the size of the list")
print(len(names))
|
class Login:
case = None
print("Press 0 to Login")
print("Press 1 to Create Account")
try:
case = int(input("Enter Your Choice ==> "))
if case == 0:
print("=============LOGIN===============")
userName = str(input("Enter Your Name : "))
password = input("Enter Your Password : ")
try:
flag = None
file = open("Credintials.txt", "r")
read = file.read()
read = read.splitlines()
for i in read:
spl = i.split()
if userName == spl[0] and password == spl[1]:
flag = "found"
if flag == "found":
print("Login Successful!")
else:
print("Login Failed!")
except IOError:
print("Oops! Something went wrong.")
finally:
file.close()
elif case == 1:
print("============CREATE ACCOUNT================")
name = str(input("Enter Your Name : "))
pasw = input("Enter Password : ").lower()
again = input("Enter Password Again : ").lower()
if pasw != again:
print("Sorry! You can't create account, Try Again later.")
exit()
else:
try:
file = open("Credintials.txt", "a+")
file.write(name + " " + pasw + "\n")
except IOError:
print("Oops! Something went wrong.")
finally:
file.close()
else:
print("Invalid Command!")
except ValueError:
print("Oops! You enter invalid input, kindly correct it.")
|
from datetime import datetime as dt
def isPrime(x):
for divisor in range(2,x):
if x%divisor == 0:
# X is non-prime
return False
return True
def factorize(x):
primeFactors = []
divisor = 2
while x > 1:
if isPrime(divisor):
if x % divisor == 0:
x = x / divisor
primeFactors.append(divisor)
else:
divisor += 1
else:
divisor += 1
return primeFactors
startTime = dt.now()
factors = factorize(600851475143)
timeDiff = dt.now() - startTime
print(factors)
print("Time taken: {}s".format(timeDiff.total_seconds()))
|
"""
Reverse a linked list
head could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def Reverse(head):
temp = head
last = None
while(temp is not None):
nxt = temp.next
temp.next = last
last = temp
temp = nxt
return last
|
"""
Delete Node at a given position in a linked list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
def Delete(head, position):
pos = 0
temp = head
while(True):
if position==0:
head = temp.next
return head
else:
pos = pos + 1
if pos == position:
p = temp.next
temp.next = p.next
return head
else:
temp = temp.next
|
'''
What is the smallest positive number that is evenly divisible by all of
the numbers from 1 to 20?
'''
from functools import reduce
from math import gcd
def lcm(a,b):
''' Returns least common multiple of a and b '''
return a*b // gcd(a,b)
def smallest_multiple(l):
''' Returns the smallest positive number that is evenly divisible by
all of the numbers in the provided list l
'''
return reduce(lcm, l)
if __name__ == '__main__':
result = smallest_multiple(list(range(1,20+1)))
print(result)
|
class People(object):
role = "students"
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print("%s is eating..."% self.name)
def get_age(self):
print("%s is %s years old..."% self.name,self.age)
def sleep(self):
print("%s is sleeping" % self.name)
class Relation(object):
def makeFriends(self,obj):
print("%s is making friends with %s "% (self.name,obj.name))
#多类继承
class Man(People,Relation):
#继承父类的属性和方法
def __init__(self,name,age,money):
# 继承父类的属性
People.__init__(self,name,age)
#super(Man, self).__init__(name, age) 跟上面这句作用一模一样
#声明自己的属性
self.money = money
print("%s has %s money when he was born .."%(self.name,self.money))
def sleep(self):
#调用父类的方法
People.sleep(self)
People.eat(self)
#重构父类中的方法
def get_age(self):
print("my age is %s"% self.age)
m1 = Man("wangdamai",22,200)
m2 = Man("wangxiaomai",12,100)
m1.makeFriends(m2)
m1.sleep()
m1.get_age()
#多态
class Animal(object):
def __init__(self,name):
self.name = name
@staticmethod
def animal_talk(obj):
obj.talk()
class Dog(Animal):
def talk(self):
print("wang!")
class Cat(Animal):
def talk(self):
print("meow!")
d = Dog("zhangsan")
c = Cat("lisi")
Animal.animal_talk(d)
Animal.animal_talk(c)
|
"""binarize.py
"""
import cv2
import numpy as np
from .utils import separate_lab, separate_luv
def binary_threshold_lab_luv(image_rgb, b_thresh, l_thresh):
""" Returns a binarized version of image_rgb computed by thresholding the
blue-yellow channel (b) of LAB representation and the l channel of LUV representation
"""
_, _, b = separate_lab(image_rgb)
l, _, _ = separate_luv(image_rgb)
binary = np.zeros_like(l)
binary[
((b > bthresh[0]) & (b <= bthresh[1])) |
((l > lthresh[0]) & (l <= lthresh[1]))
] = 1
return binary
def binary_threshold_grad(image_channel, threshold):
""" Apply binarization by thresholding the gradient obtained with the Sobel operator.
Filter works only on a single channel
"""
...
def binary_threshold_gray(image_rgb, threshold):
image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
thresh, binarize = cv2.threshold(image_gray, threshold[0], threshold[1], cv2.THRESH_BINARY)
return binarize
|
"""utils.py
"""
from matplotlib import pyplot as plt
from matplotlib import gridspec as gridspec
def generate_4_2_layout():
""" Returns a 4x2 standard layout
"""
fig = plt.figure(figsize=(10, 10), constrained_layout=True)
gs = fig.add_gridspec(4, 2)
return fig, gs
def generate_6_2_layout():
""" Returns a 6x2 standard layout
"""
fig = plt.figure(figsize=(10, 10), constrained_layout=True)
gs = fig.add_gridspec(6, 2)
return fig, gs
def generate_x_y_layout(rows: int, cols: int):
""" Returns a rows x cols standard layout
"""
fig = plt.figure(figsize=(10, 10), constrained_layout=True)
gs = fig.add_gridspec(rows, cols)
return fig, gs
def generate_1_1_layout():
""" Returns a 1x1 standard layout
"""
fig, ax = plt.subplots(1, 1)
return fig, ax
|
from wycash import Money, Bank
import unittest
class TestWyCash(unittest.TestCase):
def test_multiplication(self):
five = Money.dollar(5)
self.assertEqual(Money.dollar(10), five.times(2))
self.assertEqual(Money.dollar(15), five.times(3))
def test_equality(self):
# refactoring to keep it pythonic
self.assertEqual( Money.dollar(5), Money.dollar(5) )
self.assertNotEqual( Money.dollar(5), Money.dollar(6) )
self.assertNotEqual( Money.franc(5), Money.dollar(5) )
def test_currency(self):
self.assertEqual("USD", Money.dollar(1).currency())
self.assertEqual("CHF", Money.franc(1).currency())
def test_simple_addition(self):
five = Money.dollar(5)
sum = five + five
bank = Bank()
reduced = bank.reduce(sum, "USD")
self.assertEqual(Money.dollar(10), reduced)
if __name__ == '__main__':
unittest.main() # pragma: no cover
|
import random
def scores_grades():
print "Scores and Grades"
for i in range (10):
score = random.randint(60, 100)
if score >= 60 and score <=69:
print "Score:", score, ";", "Your grade is D"
elif score >= 70 and score <=79:
print "Score:", score, ";", "Your grade is C"
elif score >= 80 and score <=89:
print "Score:", score, ";", "Your grade is B"
elif score >= 90 and score <=100:
print "Score:", score, ";", "Your grade is A"
print "End of the program. Bye!"
scores_grades()
|
x = ['magical unicorns',19,'hello',98.98,'world']
y = [2,3,1,7,4,12]
z = ['magical','unicorns']
def typeList(arr):
sum = 0
string_list = []
for i in range(len(arr)):
if isinstance(arr, int) or isinstance(arr, float):
sum+=arr[i] #sums items in the list if they are numbers
elif type(arr[i]) == str:
string_list.append(arr[i]) #concatenates item onto a new string if they are string
if sum != 0:
print "Sum:", sum #prints sum if it is not empty
if len(string_list) != 0: #prints new string if it is not empty
print ' '.join(string_list)
if sum > 0 and len(string_list) > 0: #checks for the presence of number and string for mixed type
print "The list you entered is of mixed type"
elif len(string_list) > 0:
print "The list you entered is of string type" #checks for the presence of string for string type
elif sum > 0:
print "The list you entered is of integer type" #checks for the presence of number for integer type
typeList(x)
|
words = "It's thanksgiving day. It's my birthday,too!"
print "position of day:", words.find("day")
print "new words:", words.replace("day", "month")
x = [2,54,-2,7,12,98]
def minmax(x):
print "min", min(x)
print "max", max(x)
minmax(x)
x = ["hello",2,54,-2,7,12,98,"world"]
def firstlast(x):
print "first", x[0]
print "last", x[len(x)-1]
firstlast(x)
x = [19,2,54,-2,7,12,98,32,10,-3,6]
def newlist(x):
sorted = x.sort()
half = len(x)/2
firsthalf= x[:half]
print firsthalf
lasthalf= x[half:]
print lasthalf
lasthalf.insert(0, firsthalf)
print lasthalf
newlist(x)
|
"""Leia 3 valores reais (A, B e C) e verifique se eles formam ou não um triângulo.
Em caso negativo, calcule a área do trapézio que tem A e B como base e C como altura.
"""
A,B,C = input().split()
A = float(A)
B = float(B)
C = float(C)
perimetro = A+B+C
area_trapezio = C*(A+B)/2
Condicao_1 = (B-C) <A <B+C
Condicao_2 = (A-C) <B <A+C
Condicao_3 = (A-B) <C <A+B
if(Condicao_1 == True and Condicao_2==True and Condicao_3 == True):
print("Perimetro = {}".format(perimetro))
else:
print("Area = {:.1f}".format(area_trapezio))
|
"""Faça um programa que calcule e mostre o volume de uma esfera sendo fornecido o valor de seu raio (R).
A fórmula para calcular o volume é: (4/3) * pi * R3. Considere (atribua) para pi o valor 3.14159."""
Raio = float(input())
PI = 3.14159
Volume = (4/3.0)*PI*(Raio**3)
print("VOLUME = {:.3f}".format(Volume))
|
'''
Implement an algorithm to determine if a string has all
unique characters.
'''
unique_str = "AbCDefG"
non_unique_str = "non Unique STR"
def normalize_str(input_str):
# function that removes spaces from string and converts all characters to lower
input_str = input_str.replace(" ", "")
return input_str.lower()
def is_unique_1(input_str):
# loop through string and if the character is not in dictionary than add it to the dictionary
# this uses a new data structure which will use O(n) space
d = dict()
for char in input_str:
if char in d:
return False
else:
d[char] = 1
return True
def is_unique_2(input_str):
# set function returns all unique characters
return len(set(input_str)) == len(input_str)
def is_unique_3(input_str):
# this assumes that string will contain only letters
alpha = "abcdefghijklmnopqrstuvwxyz"
for char in input_str:
if char in alpha:
alpha = alpha.replace(char, "")
else:
return False
return True
unique_str = normalize_str(unique_str)
non_unique_str = normalize_str(non_unique_str)
print(unique_str)
print(non_unique_str)
print(is_unique_1(unique_str))
print(is_unique_1(unique_str))
print(is_unique_2(non_unique_str))
print(is_unique_2(non_unique_str))
print(is_unique_3(unique_str))
print(is_unique_3(non_unique_str))
|
'''
Given an array of size N-1 and given there are numbers from 1 to N with
one element missing, the missing number is to be found.
'''
def find_missing_number_in_array(arr):
'''
Time complexity: O(n)
Space complexity: O(1)
arr - array: int
'''
# sum all numbers in size N
target_sum = sum(i for i in range(1, len(arr)+2))
# subtract each element of array from target sum
for i in test:
target_sum -= i
# return what's left
return target_sum
test = [1,2,4,5]
print(find_missing_number_in_array(test))
|
# # Lesson 2
# # Lists and Loops
# # Lightning Review
# # Variables
# # Variables are names that you can assign values to
# # Variables can contain numbers, strings, lists, True/False
# # Variable names can contain letters and underscores and should be descriptive
# # Strings
# # Strings can contain anything that you can type out on the keyboard
# # Strings are commonly used for names, phone numbers, etc.
# # Slicing is used to see parts of a string
# # String methods allow you to do special actions on strings (find, replace, count, lowercase, etc.)
# # Conditionals
# # Conditionals allow you to change behavior of your program
# # Lists
# # Lists are containers that can hold multiple pieces of information. They can hold strings, numbers, etc.
# # Lists: Syntax
# # Lists are created by placing items inside of square brackets: []
# # Items in a list are separated by commas
# # Holding the name of each attendee in a separate variable isn't efficient:
attendee1 = 'Katie'
attendee2 = 'Michelle'
attendee3 = 'Di'
# # Below is a list of attendees:
attendees = ['Katie', 'Michelle', 'Di', 'Lauren', 'Sam', 'Allie', 'Samantha', 'Lisa', 'Jocelyn', 'Stacey', 'Tamar', 'Megan', 'Katie', 'Kelly', 'JihFan', 'Serena', 'Claudia']
print("Attendees list: {0}\n".format(attendees))
# # In Python 3, print is defined as a function so we print like this: print("Print me")
# # An empty lists looks like []
people_who_didnt_do_pbj = []
# # Lists: Slicing
# # A list can be sliced like a string can be sliced
# # Instead of printing characters by index, this will print items in the list by index
# # This will print the first two people in the list:
print("First two people in attendees list: {0}\n".format(attendees[0:2]))
# # This will print the fourth person in the list:
print("Fourth person in attendees list: {0}\n".format(attendees[3]))
# # To print all attendees on list using slice:
print("Printing the attendees list again using attendees[:]: {0}\n".format(attendees[:]))
# # To print last three people:
# # We could use negative indexing like this
# # This could be useful if you don't know how long your list is
# # (Though you can just get the length of the list using len())
print("Last three people in attendees list: {0}\n".format(attendees[-3:]))
# # Lists: Length
# # The length of the list can be calculated using len()
print("Length of attendees list: {0}\n".format(len(attendees)))
# # Lists: Adding Items
# # To add to the end of a list, use .append() method
attendees.append('Mary')
print("Adding 'Mary' to end of attendees list: {0}\n".format(attendees))
# # Lists: Changing Existing Items
# # An item in a list can be changed by getting the item using its index and setting it
attendees_ages = [28, 36, 32, 18, 25, 28]
print("Attendees' ages list: {0}\n".format(attendees_ages))
# # To get the first age in the list and change it:
attendees_ages[0] = 29
print("Changed first age in attendees' ages list to 29: {0}\n".format(attendees_ages))
# # Lists: Deleting Existing Items
days_of_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
print("Days of week list: {0}\n".format(days_of_week))
# # An item can be removed from a list using pop()
# # This will remove the last item from the list:
day = days_of_week.pop()
print("Last day removed from days of week list: {0}\n".format(day))
# # This will remove the fourth item from the list:
day = days_of_week.pop(3)
print("Fourth day removed from days of week list: {0}\n".format(day))
print("Days of week list now looks like: {0}\n".format(days_of_week))
# # To store removed item:
# # This will store the name of the TA in a variable
TA = attendees.pop(9)
print("Our TA is {0}\n".format(TA))
print("Now our attendees list looks like: {0}\n".format(attendees))
print("The length of the attendees list is now: {0}\n".format(len(attendees)))
# # Lists: Quick Exercise
months = ['January', 'February']
print("Months list: {0}\n".format(months))
months.append('March')
print("Append() adds one item at a time: {0}\n".format(months))
months.extend(['April', 'May', 'June'])
print("Extend() adds multiple items: {0}\n".format(months))
monthsToAdd = ['July', 'August', 'September', 'October', 'November', 'December']
months.extend(monthsToAdd)
print("Adding all months: {0}\n".format(months))
# # Append() will always add item at end of list
# # Lists: Add/Remove
# # Remove the first month:
months.pop(0)
print("Removing first month using pop(): {0}\n".format(months))
# # Insert 'January' before index 0:
months.insert(0, 'January')
print("Adding January back using insert(): {0}\n".format(months))
# # To get an item from a list without removing it:
thisMonth = months[8]
print("Printing month by index - months[8] is: {0}\n".format(thisMonth))
# # Lists: Strings to Lists
# # In this example, every time Python sees a space, it will use that to know
# # where to split the string into a list (you can split on any character)
addressTest = '1133 19th St. Washington, DC 20036'
addressAsList = addressTest.split(" ")
print("Printing address as a list using split(' '): {0}\n".format(addressAsList))
# # Lists: Membership
# # The in keyword allows you to check whether a value exists in the list
# # It will return a True/False boolean
# # Also works with strings!
nameCheck = 'ann' in 'Shannon'
print("Using 'in' to see if 'ann' is in string 'Shannon' - will return a boolean: {0}\n".format(nameCheck))
frankensteinMembership = 'Frankenstein' in attendees
print("Using 'in' to see if 'Frankenstein' is in attendees list - will return a boolean: {0}\n".format(frankensteinMembership))
# # Lists: Exercise
# # See lesson_2_quadrants.py for quadrant list exercise
# # Lists: Ranges of Numbers
# # The range function generates a list of numbers
print("Creating a list of numbers using range(): {0}\n".format(range(5)))
# # The range function can be provided with a start and a stop
print("Creating a list of numbers using range with start and stop: {0}\n".format(range(5, 10)))
# # We can use range when we need to do a task a certain number of times
print("Printing numbers in range(1,11):\n")
for number in range(1,11):
print(number)
# # Loops: For Loop Exercise
# # See lesson_2_quadrants.py for quadrant list exercise
# # Loops: For Loop
# # Simple loop for printing days of the week
days_of_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
print ("\nPrinting days of the week:\n")
for day in days_of_week:
print(day)
# # Loops: Nested For Loops
months_in_year = ["January","February","March","April","May","June","July","August","September","October","November","December"]
# # This loop will print 4 weeks with 7 days per week for each month of the year
for month in months_in_year:
print "\n" + month + "\n"
for week in range(1,5):
print "Week {0}".format(week)
for day in days_of_week:
print "\t" + day
# # Loops: Enumerate
# # enumerate() is a function that you use with a for loop to get the index (position) of that list item, too.
# # Commonly used when you need to change each item in a list one at a time.
# # This loop will print each month and its index
# # Put underscore in front of variables that may be reserved keywords
for _index, month in enumerate(months_in_year):
print(_index)
print(month)
# So if I want to change just February to 'Febrewary'
for _index, month in enumerate(months_in_year):
if (month == 'February'):
febIndex = _index
months_in_year[febIndex] = "Febrewary"
print(months_in_year)
# # Loops: Zip
# # A for loop iterates over each item in a single list one at a time
# # zip() can be used to combine lists into a single list so that items from multiple lists can be used in a loop together
states = ['Arizona', 'Virginia', 'Maryland']
stateAbbreviation = ['AZ', 'VA', 'MD', 'RI']
for items in zip(states, stateAbbreviation):
print(items)
# # Note that RI is left off because the two lists have different lengths
# # Loops: While
# # A for loop lets you use each item in a single list one at a time, which is great for performing actions a certain number of times.
# # Loops using while function like conditionals - will perform an action while a condition is true
# This loop will print a message about making a sandwich and subtract 2 from bread until bread is no longer greater than or equal to 2
bread = 9
while bread >= 2:
print("I'm making a sandwich")
# # bread = bread - 2
# # Shorthand:
bread -= 2
print("I now have {0} slices of bread left".format(bread))
# # This does something else!
# # bread =- 2
# # Make an open face sandwich:
if bread == 1:
print("I'm making an open face sandwich!")
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 18:57:50 2019
@author: Stephanie
"""
answer=("Ахахах, о еде. $$удивление $$улыбка В корпусе на первом этаже есть столовая и автомат с кофе, $$улыбка также прямо на остановке факультета есть киоск, выше по склону слата, и в библиотеке, где ты можешь ещё и почитать, есть столовая, где можно полноценно покушать.")
def search(text):
for word in text.split():
if word[:2:] =='$$':
return word[2::]
# answer[-1] = '@'
#def emoji(answer):
# answer[-1] = '@'
# while answer[-1] == '@':
# search(answer)
#
#
|
#生成单个机器人的路径
import random
from path import solve_maze_with_queue
def generate_cmd(start_pos, obj_pos):
current_direction = "S"
# 生成一个任务
print(start_pos, obj_pos)
# 生成一个路径
path = solve_maze_with_queue(start_pos[0], start_pos[1], obj_pos[0], obj_pos[1])
#print(path)
cmd_ary = []
for i in range(0, len(path) - 1):
if path[i][0] < path[i + 1][0]:
cmd_ary.append("S")
continue
if path[i][0] > path[i + 1][0]:
cmd_ary.append("B")
continue
if path[i][1] < path[i + 1][1]:
cmd_ary.append("R")
continue
if path[i][1] > path[i + 1][1]:
cmd_ary.append("L")
continue
#print(cmd_ary)
# L
# B o S
# R
# start:S
robot_cmd_ary = ""
i = 0
while i < len(cmd_ary):
if cmd_ary[i] == current_direction:
robot_cmd_ary = robot_cmd_ary + 's'
i += 1
continue
elif (((cmd_ary[i] == "L") and (current_direction == "B"))
or ((cmd_ary[i] == "S") and (current_direction == "L"))
or ((cmd_ary[i] == "R") and (current_direction == "S"))
or ((cmd_ary[i] == "B") and (current_direction == "R"))):
robot_cmd_ary = robot_cmd_ary + 'r'
current_direction = cmd_ary[i]
continue
elif (((cmd_ary[i] == "B") and (current_direction == "L"))
or ((cmd_ary[i] == "L") and (current_direction == "S"))
or ((cmd_ary[i] == "S") and (current_direction == "R"))
or ((cmd_ary[i] == "R") and (current_direction == "B"))):
robot_cmd_ary = robot_cmd_ary + 'l'
current_direction = cmd_ary[i]
continue
else:
robot_cmd_ary = robot_cmd_ary + 'b'
current_direction = cmd_ary[i]
continue
if (current_direction == "L"):
robot_cmd_ary = robot_cmd_ary + 'r'
elif (current_direction == "R"):
robot_cmd_ary = robot_cmd_ary + 'l'
elif (current_direction == "B"):
robot_cmd_ary = robot_cmd_ary + 'b'
print(robot_cmd_ary)
return robot_cmd_ary
#print(generate_cmd((4,4),"S"))
|
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# instance = MyClass(argument1, argument2...)
port_number = 65432
server_socket.bind(("0.0.0.0", port_number))
server_socket.listen()
print(f"Listening for incoming connection on port {port_number}...")
connection, address = server_socket.accept()
print(f"Connected by {address}.")
while True:
# for as long as you receive data...
# grab it in chunks of 1024 bytes
data = connection.recv(1024)
# (if you didn't get any data, stop listening)
if not data:
break
# and return it back to the sender in upper case
connection.sendall(data.upper())
server_socket.close()
|
from random import shuffle, randint
def getHash(length):
hash_arr = []
hash = ""
for x in range(48, 58):
hash_arr.append(chr(x))
shuffle(hash_arr)
for x in range(65, 91):
hash_arr.append(chr(x))
shuffle(hash_arr)
for x in range(97, 122):
hash_arr.append(chr(x))
shuffle(hash_arr)
for x in range(length):
hash += str(hash_arr[randint(0, 60)])
return hash
|
s=int(input())
if s<1 or s>31:
exit(0)
s=s%7
if s==1:
print("Monday")
elif s==2:
print("Tuesday")
elif s==3:
print("Wednesday")
elif s==4:
print("Thrusday")
elif s==5:
print("Friday")
elif s==5:
print("Saturday")
else:
print("Sunday")
|
t=float(input("Enter the temp"))
f=int(input("Enter 1 to convert celcius to farenhiet or press 2 to convert farenheit celcius"))
if f==1:
print(t*1.8 +32)
elif f==2:
print(((t-32)*5)/9)
|
a=float(input("Enters 1st no"))
b=float(input("Enters 2nd no"))
c=float(input("Enters 3rd no"))
if a>b:
if a>c:
print("1st no is greatest")
else:
print("3rd no is greatest")
else:
if(b>c):
print("2nd no is greatest")
else:
print("3rd no is greatest")
|
class FizzBuzz:
def return_fizz_buzz(self, number):
if int(number) % 3 == 0:
if int(number) % 5 != 0:
output = 'fizz'
else:
output = 'fizz-buzz'
else:
if int(number) % 5 != 0:
output = number
else:
output = 'buzz'
return output
|
from random import choice
from nltk.corpus import brown
from nltk.corpus import stopwords
difficulty = raw_input("Set the difficulty to either easy, medium, or hard:")
difficulty = difficulty.lower()
while difficulty != "hard" and difficulty != "medium" and difficulty != "easy":
difficulty = raw_input("Please enter 'easy', 'medium', or 'hard':")
difficulty = difficulty.lower()
if difficulty == "easy":
min_length = 6
max_length = 7
elif difficulty == "medium":
min_length = 8
max_length = 10
else:
min_length = 5
max_length = 5
word_list = brown.words()
stopwords = stopwords.words('english')
word_list1 = [w for w in word_list if w.lower() not in stopwords]
answer = choice(word_list1)
answer_length = len(answer)
while answer_length < min_length or answer_length > max_length or (not answer.isalpha()):
answer = choice(word_list1)
answer_length = len(answer)
answer = answer.lower()
used = ["Used Letters: "]
attempt = ["Word: "]
attempt.extend(["__ "] * len(answer))
guess = 0
max_guesses = 8
board = []
def display_word(a):
return a.append(attempt)
def display_used_letters(a):
return a.append(used)
def make_initial_board(a):
a.append([] * 20)
display_word(a)
a.append([] * 20)
display_used_letters(a)
return a
make_initial_board(board)
def print_board(a):
guesses_left = max_guesses - guess
for row in a:
print "".join(row)
print "Guesses left: " + str(guesses_left)
def take_input():
global attempt
global guess
guessed_letter = raw_input("What is your letter?")
guessed_letter = guessed_letter.lower()
while len(guessed_letter) > 1 or guessed_letter + " " in used:
if len(guessed_letter) > 1:
guessed_letter = raw_input("You can only guess one letter:")
else:
guessed_letter = raw_input("You already guessed that! Try again:")
guessed_letter = guessed_letter.lower()
else:
used.append(guessed_letter + " ")
if guessed_letter in answer:
index_list = []
for i in range(0,len(answer)):
if answer[i] == guessed_letter:
index_list.append(i)
for i in index_list:
j = i + 1
attempt[j] = guessed_letter + " "
else:
guess += 1
def word_match():
return not ("__ " in attempt)
while guess < max_guesses and (not word_match()):
print_board(board)
take_input()
else:
if word_match():
print "".join(answer)
print "Congratulations! You won! The word was " + answer + "."
else:
print_board(board)
print "You lost...the word was " + answer + ". Maybe try again?"
|
#문자열 포맷
# print("a" + "b")
# print("a", "b")
#방법 1
print("나는 %d살입니다." % 20) # d 는 정수값만 넣을 수 있음
print("나는 %s을 좋아해요." % "파이썬") # s 는 문자열 String 값을 넣겠다
print("Apple 은 %c로 시작해요." % "A") # c는 캐릭터라서 한 글자만 받겠단
# %s 로만 쓰면 정수건 문자건 상관없이 출력 가능
print("나는 %s살입니다." % 20) # d 는 정수값만 넣을 수 있음
print("나는 %s색과 %s색을 좋아해요." % ("파란", "빨간")) # 순서대로 대입
#방법 2
print("나는 {}살입니다.".format(20)) # 중괄호
print("나는 {}색과 {}색을 좋아해요.".format("파란", "빨간"))
print("나는 {0}색과 {1}색을 좋아해요.".format("파란", "빨간")) # 순번에 맞게
print("나는 {1}색과 {0}색을 좋아해요.".format("파란", "빨간")) # 순번에 맞게
#방법 3
print("나는 {age}살이며, {color}색을 좋아해요.".format(age = 20, color="빨간")) # 변수 처럼 중가로 속에 있는 값을 포맷 뒤에있는 값으로 가져가다 쓴다
print("나는 {age}살이며, {color}색을 좋아해요.".format(color="빨간", age = 20)) # 순서 상관없이
#방법 4(Python v3.6 이상~)
age = 20
color = "빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요.")
|
"""
generate nth fibonacci term
"""
from duration import duration
from multiprocessing import Process
def fib_recursion(n):
# using recursion
if n == 0: return 0
if n == 1: return 1
return fib_recursion(n-1) + fib_recursion(n-2)
def cache_fib(n, r):
# memoization
if r[n] >= 0:
return r[n]
if n == 0 or n == 1:
num = n
else:
num = cache_fib(n-1, r) + cache_fib(n-2, r)
r[n] = num
return num
@duration
def fib_dynamic_programming(n):
# using dp
r = [-1]*(n+1)
return cache_fib(n, r)
@duration
def func(num):
return fib_recursion(num)
@duration
def fib_simple(num):
if num == 0:return 0
a = 0
b = 1
for i in range(num):
c = a + b
a = b
b = c
return a+b
if __name__ == '__main__':
p1 = Process(target=func, args=(20,))
p1.start()
p2 = Process(target=fib_dynamic_programming, args=(20,))
p2.start()
p3 = Process(target=fib_simple, args=(20,))
p3.start()
p1.join()
p2.join()
p3.join()
|
"""
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 1, 1
for i in range(n):
a, b = b, a+b
return a
def climbStairs_dp(self, n):
if n<=2:
return n
dp = [0]*(n+1)
dp[2] = 2; dp[1]=1; dp[0]=1
# f(n) = f(n-1)+f(n-2)
for i in range(3, n+1):
dp[i] = dp[i-1]+dp[i-2]
return dp[n]
obj = Solution()
print(obj.climbStairs_dp(5))
|
def median(list_num):
s = sorted(list_num)
if len(s)%2 == 0:
return (s[len(s)/2] + s[(len(s)/2) - 1]) / 2.0
else:
return s[(len(s)-1)/2]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 6 23:33:08 2016
Final project intended to be able to schedule courses for students given a list of classes.
Initial prioritization is by listing order.
@author: clifp
"""
#from courseClass import*
from courseClass import*
import sys
BARRIER_TEXT = "===================="
"""
Opens file for reading.
"""
def readClasses(filename="classes.txt"):
file = open(filename, "r")
courseList = list()
for courseLine in file:
courseLine = (courseLine.upper())
courseList.append(courseLine)
return courseList
def printCourseList(courseList=None):
if (courseList==None):
print("No course list to print.")
return
for listing in courseList:
listing.printCourse()
def countViable(courseList=None):
if courseList == None:
print ("countViable:\t No list present.")
return -1
count = 0
for listing in courseList:
if (listing.isViable()):
count+=1
return count
def sumCourseUnits(acceptedList=None):
if (acceptedList==None):
print("sumCourseUnits:\tNo list available.")
return
sumUnits = 0
for listing in acceptedList:
sumUnits += listing.getUnits()
return sumUnits
"""
Input
Current Course List
Output
Index of next viable course.
"""
def findNextViableCourse(courseList=None):
if(courseList==None):
print("findNextViableCourse():\t Course List is missing.")
return
#Sort through list to find first viable course
index = 0
listLen = len(courseList)
while index < listLen:
if (courseList[index].isViable()):
return index
index += 1
return -1
"""
Input
Accepted Course List (State)
Full Course List (Entire List)
OPTIONAL courseIndex - location to start on courseList.
Objective
Take the course at the front of the list (if viable)
Compare it to the accepted list.
If it fits, add to accepted AND mark all remaining as viable/not
"""
def considerCourse(courseList=None, acceptedList=None, courseIndex=None):
if (courseList == None or acceptedList == None):
print("considerCourse():\tCourse or Accepted List is missing.")
return
if (len(acceptedList) == 0):
index = 0
else:
index = findNextViableCourse(courseList)
#Accept first found
acceptedCourse = courseList[index]
acceptedCourse.setViable(False)
acceptedList.append(acceptedCourse)
acceptedBool = (acceptedCourse.getName(), acceptedCourse.isViable())
for listing in courseList[index+1:]:
courseBool = (listing.getName(), listing.isViable()) #DEBUG - VISIBILITY
if (listing.isViable() == False):
continue
listing.setViable(isCompatibleCourse(acceptedCourse, listing))
courseBool = (listing.getName(), listing.isViable())
return
def findCourses(courseList=None, acceptedList=None):
if (courseList == None or acceptedList == None):
print("findCourses():\tCourse or Accepted List is missing.")
return
viableCount = countViable(courseList)
while viableCount > 0:
considerCourse(courseList, acceptedList)
viableCount = countViable(courseList)
return
def main():
if len(sys.argv) == 2:
classesTextList = readClasses(sys.argv[1])
else:
classesTextList = readClasses()
#print(classesTextList)
courseList = list() #General Course list
acceptedList = list() #Accepted courses
#Add all courses to standard list in structure.
for course in classesTextList:
newCourse = Course(course)
courseList.append(newCourse)
print("\nCourse List\n" + BARRIER_TEXT)
printCourseList(courseList)
print(BARRIER_TEXT)
#Begin considering courses.
findCourses(courseList, acceptedList)
print("\nACCEPTED COURSES\n" + BARRIER_TEXT)
print("Total Units:\t{}".format(sumCourseUnits(acceptedList)))
printCourseList(acceptedList)
print(BARRIER_TEXT)
#TEST COMPARISONS
#if ( isCompatibleCourse (courseList[1], courseList[3]) ):
#print("CLEAR")
return
main()
|
class BSTMap:
# empty map instance
def __init__(self):
self._root = None
self._size = 0
# return the number of entries in the map
def __len__ (self):
return self._size
# Returns an iterator for traversing the skeys in the map
def __iter__(self):
return _BSTMapITerator(self._root)
# Storage class for the binary search tree nodes of the map
class _BSTMapNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None
|
"""
Inspired by: https://www.hackerrank.com/challenges/validating-postalcode/problem (removed regex criteria)
Validate postcodes
A valid postal code P have to fulfil both below requirements:
P must be a number in the range from 100000 to 999999 inclusive.
P must not contain more than one alternating repetitive digit pair.
Alternating repetitive digits are digits which repeat immediately after the next digit.
In other words, an alternating repetitive digit pair is formed by
two equal digits that have just a single digit between them.
For example:
121426 # Here, 1 is an alternating repetitive digit.
523563 # Here, NO digit is an alternating repetitive digit.
552523 # Here, both 2 and 5 are alternating repetitive digits.
Return True (for valid) while postcode is between 100000 and 999999,
and there are no alternating digits
Return False for invalid
"""
# p -> postcode
def is_valid_postcode(p):
if p < 100000 or p > 999999:
return False
p = str(p)
for i in range(2,len(p)):
if p[i-2] == p[i]:
return False
return True
is_valid_postcode(15)
"""
>> False
"""
|
# Q4: Write a recursive function that checks whether a string
# is a palindrome (a palindrome is a string that's the same when
# reads forwards and backwards.)
def is_palindrome(cs):
if len(cs) == 0 or len(cs) == 1:
return True
if not cs[0] == cs[-1]:
return False
return is_palindrome(cs[1:-1])
test_cases = ["adcba", "abxba", "abba"]
res = [is_palindrome(tc) for tc in test_cases]
res
|
"""
hackerrank: https://www.hackerrank.com/challenges/ctci-recursive-staircase/problem
Davis has a number of staircases in his house and he likes to climb each staircase 1, 2
or 3 steps at a time. Being a very precocious child,
he wonders how many ways there are to reach the top of the staircase.
Given the respective heights for each of the staircases in his house,
find and print the number of ways he can climb each staircase,
module 10^9 + 7 on a new line.
For example, there is s = 1 staircase in the house that is n = 5 steps high.
There are 13 possible ways he can take these 5 steps.
Sample input:
3
1
3
7
Sample Output:
1
4
44
"""
import timeit
# Without dynamic programming
# nodp -> no dymanic programming
def calculate_permutations_nodp(n):
if n == 1: return 1
if n == 2: return 2
if n == 3: return 4
return (
calculate_permutations_nodp(n - 1) +
calculate_permutations_nodp(n - 2) +
calculate_permutations_nodp(n - 3)
)
%timeit for x in range(50): calculate_permutations_nodp(25)
"""
>> "6.86 s ± 4.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"
"""
# With dynamic programming
def __calculate_permutations(n, cache):
if n == 1: return 1
if n == 2: return 2
if n == 3: return 4
if n in cache:
return cache[n]
cache[n] = (
__calculate_permutations(n - 1, cache) +
__calculate_permutations(n - 2, cache) +
__calculate_permutations(n - 3, cache)
)
return cache[n]
# dp -> dynamic programming
def calculate_permutations_dp(n):
return __calculate_permutations(n, {})
%timeit for x in range(50): calculate_permutations_dp(25)
"""
513 µs ± 657 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
"""
|
"""
Hackerrank: https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-lite
For this question, you will write a program that generates values from the Fibonacci sequence.
The Fibonnaci sequence is recursively defined by:
Fn = Fn - 1 + Fn - 2
Using the following seed values:
F0 = 0, F1 = 1
Given a number n, print the nth value of the Fibonacci sequence.
Examples
Input:
12
Output:
144
Input:
30
Output:
832040
General Approach
Find the base case(s),
Have your function recognize the base case(s) and provide a solution,
Recursively define a solution to the sub-problem for other inputs,
Call your function on the input and print the result to STDOUT.
Things to think about
Although we are doing this mainly to learn recursion, think about whether this is effecient
in your language of choice. Does your language support tail call elimination?
Input Format and Restrictions
Each test case will consist of a single positive integer n.
The inputs will always satisfy the following restrictions:
Fn < 2^32 - 1,
0 <= n < 50
"""
def __fib(a,b,n,c=0):
if c == n:
return a
c += 1
return __fib(b,a+b,n,c)
def fib(n):
a = 0
b = 1
return __fib(a, b, n)
fib(12)
"""
>> 144
"""
fib(12)
"""
>> 832040
"""
|
"""
From my interviewcake.com question of the week email:
Write an algorithm that determines if two rectangles overlap on an xy grid.
A rectangle is defined as a dictionary like the below:
rectangle_one = {
'left_x' : 1,
'bottom_y' : 1,
'width' : 6,
'length' : 3
}
rectangle_two = {
'left_x' : 5,
'bottom_y' : 2
'width' : 3,
'length' : 6
}
These overlap at the coordinates (x, y) [(6,3), (6,4), (7,3), (7,4)]
The return only needs to be True/False
Assume they are never diagonal and each side is parallel.
"""
def get_xy_low_high(r):
xl = r["left_x"]
yl = r["bottom_y"]
xh = r["left_x"] + r["width"]
yh = r["bottom_y"] + r["length"]
return xl, yl, xh, yh
def is_overlap(r1, r2):
xl1, yl1, xh1, yh1 = get_xy_low_high(r1)
xl2, yl2, xh2, yh2 = get_xy_low_high(r2)
for x in range(xl1, xh1 + 1):
if x == xl2 or x == xh2:
return True
for y in range(yl1, yh1 + 1):
if y == yl2 or y == yh2:
return True
return False
r1={
'left_x' : 1,
'bottom_y' : 1,
'width' : 6,
'length' : 3
}
r2={
'left_x' : 5,
'bottom_y' : 2,
'width' : 3,
'length' : 6
}
is_overlap(r1,r2)
"""
>> True
"""
r1={
'left_x' : 1,
'bottom_y' : 1,
'width' : 1,
'length' : 1
}
r2={
'left_x' : 5,
'bottom_y' : 3,
'width' : 3,
'length' : 6
}
is_overlap(r1,r2)
"""
>> False
"""
|
"""
From: Cracking the Coding Interview
Pattern Matching
You are given two strings, pattern and value.
The pattern can only be a and b where as values can be for example
catcatcatgocatgo which matches with aaabab. Write a function which tests
to see if the value matches the pattern.
"""
def find_pattern(cs):
if len(cs) == 0:
return ""
# p -> pattern
p = [cs[0]]
# tc -> temporary container
tc = []
# mi -> match index
mi = 0
for i in range(1, len(cs)):
if cs[i] == p[mi]:
tc.append(cs[i])
mi += 1
if p == tc:
return "".join(p)
elif cs[i] != p[mi]:
p.append(cs[i])
return "".join(p)
def count_until_next_dif_elem(p):
c = 1
for i in range(1, len(p)):
if p[i-1] == p[i]:
c += 1
else:
break
return c
def is_pattern_match(cs, pm):
s = 0
while len(cs) > 0:
p = find_pattern(cs)
cut = count_until_next_dif_elem(pm)
if p * cut != cs[s:len(p) * cut]:
return False
if len(pm) == 0 and len(p) != 0:
return False
pm = pm[cut:]
cs = cs[len(p) * cut:]
return True
# tcs -> test cases
tcs = [
("catcatcatgogocat", "aaabba"),
("catcatcacar", "aabb"),
("catcaxcaca", "aabb")
]
[is_pattern_match(cs, pm) for cs, pm in tcs]
"""
>> [True, False, False]
"""
|
"""
FROM CTCI:
Pond Size: You have an integer matrix representing a plot of land, where the value at that location
represents the height above sea level. A value of zero indicates water. A pond is a region of
water connected vertically or horizontally. The size of the pond is the total number of connected
water cells. Write a method to compute all possible ponds.
Note: CTCI is also looking for diagonal connections. It also asks developer to return the length of
the ponds.
"""
def filter_negative_index(e):
# if any coordinate has a negative index
if any(c < 0 for c in e):
return 0
return 1
# vertical index set upper limit
def vi_set_upper(e):
if not e[0] < len(g):
return 0
return 1
# horizontal index set upper limit
def hi_set_upper(e):
if not e[1] < len(g[0]):
return 0
return 1
def compute_neighbours(i, j):
# vertical neighbour
vn = [
(i + 1, j),
(i - 1, j)
]
# horizontal neighbour
hn = [
(i, j + 1),
(i, j - 1)
]
vn = filter(filter_negative_index, vn)
vn = filter(vi_set_upper, vn)
hn = filter(filter_negative_index, hn)
hn = filter(hi_set_upper, hn)
return list(vn) + list(hn)
def filter_zero_coordinate(e):
# e -> (2, 3) coordinates
if g[e[0]][e[1]] == 0:
return 1
return 0
# remove previous zero coordinate
def remove_processed_zc(nze, processed):
return [nz for nz in nze if nz not in processed]
# get_neighbouring zero coordinates
def get_neighbouring_zc(r, c):
n = compute_neighbours(r, c)
return list(filter(filter_zero_coordinate, n))
def find_ponds(g):
processed = set()
ponds = []
# cc -> column count
cc = len(g[0])
# rc -> row count
rc = len(g)
for r in range(rc):
for c in range(cc):
if g[r][c] == 0 and (r,c) not in processed:
pond = set()
pond.add((r,c))
processed.add((r,c))
prev = (r, c)
# nzs -> non zero stack
nzs = get_neighbouring_zc(r, c)
while nzs:
last_nz = nzs.pop()
# non zero extended
nze = get_neighbouring_zc(last_nz[0], last_nz[1])
nzs = nzs + remove_processed_zc(nze, processed)
pond.add(last_nz)
processed.add(last_nz)
if pond not in ponds:
ponds.append(pond)
print("\n")
for pond in ponds:
print("*** --- ***")
print(pond)
print("\n")
g = [
[0,2,1,0,0],
[0,1,0,1,1],
[0,0,0,1,0],
[0,1,0,1,1],
]
# returns the coordinate of vertically or horizontally connected
# 0 elements
find_ponds(g)
"""
>> *** --- ***
>> {(1, 2), (3, 2), (0, 0), (3, 0), (2, 1), (2, 0), (2, 2), (1, 0)}
>> *** --- ***
>> {(0, 3), (0, 4)}
>> *** --- ***
>> {(2, 4)}
"""
g = [
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 0, 0]
]
find_ponds(g)
"""
*** --- ***
>> {(1, 3), (3, 0), (0, 3), (2, 5), (2, 4), (4, 4),
(1, 5), (2, 2), (0, 4), (3, 2), (0, 0), (4, 5),
(1, 4), (0, 5), (2, 3), (4, 2), (1, 0), (0, 1),
(3, 1), (2, 0), (4, 3), (0, 2)}
"""
|
# Write a function that is passed a linked list of integers and a “target” number
# and that returns the number of occurrences of the target in the linked list.
class Node:
def __init__(self, val, next_node=None):
self.val = val
self.next_node = next_node
class LinkedList:
def __init__(self, head):
self.head = head
def __count_occurrences(self, head, target):
if not head:
return 0
if head.val == target:
return 1 + self.__count_occurrences(head.next_node, target)
else:
return self.__count_occurrences(head.next_node, target)
def count_occurrences(self, target):
return self.__count_occurrences(self.head, target)
minus_one = Node(-1)
minus_five = Node(-5)
four = Node(4)
eleven = Node(11)
minus_five.next_node = minus_one
minus_one.next_node = four
four.next_node = eleven
ll = LinkedList(minus_five)
ll.traverse()
# >> -5
# >> -1
# >> 4
# >> 11
print(ll.count_occurrences(1))
print(ll.count_occurrences(-1))
# >> 0
# >> 1
|
"""
From: Cracking the Coding Interview
Assuming that we have a method isSubstring,
that returns true or false depending on whether or not string1 is a substring of string2,
use isSubstring to determine whether or not string2 is a rotation of string1.
Eg "waterbottle" is a rotation of "erbottlewat"
"""
def is_substring_rotation(s, to_check):
if len(s) != len(to_check):
return False
elif len(s) == 0 or len(to_check) == 0:
return False
return to_check in s * 2
is_substring_rotation("waterbottle", "erbottlewat")
"""
>> True
"""
|
from TrieNode import TrieNode
class Trie:
def __init__(self):
self.root = TrieNode()
def char_to_index(self, c):
return ord(c) - ord('a')
def insert(self, cs):
# ctn -> current trie node
ctn = self.root
cs = cs.lower()
for c in cs:
c_ascii_idx = self.char_to_index(c)
if not ctn.children[c_ascii_idx]:
ctn.children[c_ascii_idx] = TrieNode()
ctn = ctn.children[c_ascii_idx]
ctn.is_end = True
def __get_all_words(self, ro, word=[]):
words = []
if not ro.children:
return [word]
if ro.is_end:
words.append(word)
for i, c in enumerate(ro.children):
if c:
ew = self.__get_all_words(c, word=word + [chr(ord('a') + i)])
for w in ew:
words.append(w)
return words
def get_all_words(self):
for ws in self.__get_all_words(self.root):
yield "".join(ws)
def search(self, key):
# ctn -> current trie node
ctn = self.root
for c in key:
c_ascii_idx = self.char_to_index(c)
if not ctn.children[c_ascii_idx]:
return False
ctn = ctn.children[c_ascii_idx]
return True
# delete implemetion on Trie with a tail recursion
def __delete(self, key, ro, i):
# here the ro.children is essentially the list that holds the current
# letter (and others if any). if we are deleting "abc" and let's say
# that we are at letter c; essentially the children of letter c will
# be ro.children[<ascii_idx(c)>]
c_ascii_idx = self.char_to_index(key[i])
if key[i] == key[-1]:
# if the last letter has a children, then DO NOT delete the node
# change is_end to False and return the node as is
if ro.children[c_ascii_idx]:
ro.children[c_ascii_idx].is_end = False
return ro
# if however, the last letter hasn't got a children, return None
# which will be carried over the call stack to previous call
return None
ro.children[c_ascii_idx] = self.__delete(key, ro.children[c_ascii_idx], i=i+1)
return ro
def delete(self, key):
self.__delete(key, self.root, i=0)
t = Trie()
t.insert("abcd")
t.insert("abce")
t.insert("abc")
t.insert("abcef")
t.insert("abceg")
list(t.get_all_words())
"""
>> ['abc', 'abcd', 'abce', 'abcef', 'abceg']
"""
t.search("abc")
"""
>> True
"""
t.delete("abcef")
list(t.get_all_words())
"""
>> ['abc', 'abcd', 'abce', 'abceg']
"""
t.delete("abc")
list(t.get_all_words())
"""
>> ['abcd', 'abce', 'abceg']
"""
|
import alphabet
Nodes = []
class Node(object):
def __init__(self, name, num):
self.name = name
self.higher_nodes = []
self.lower_nodes = []
if(num == 1):
self.tentative = 0
else:
self.tentative = 1000
self.distances = {}
self.num_lower = 0
self.num_higher = 0
def add(self, node, dis):
self.higher_nodes.append(node)
node.lower_nodes.append(self)
self.distances[node.name] = dis
node.num_lower += 1
self.num_higher += 1
def ShortestPath(self):
for i in range(len(self.higher_nodes)):
node = self.higher_nodes[i]
d = self.distances[node.name]
if(self.tentative + d < node.tentative):
node.tentative = self.tentative + d
node.ShortestPath()
def mark(self,node):
self.higher_nodes[node] = self.d, True
f = open('/users/ethan/python/MarkOfAWizard/input.txt','r')
line = int(f.readline().rstrip())
while(line != 0):
marks = 0
for l in range(1,line+1):
letter = alphabet.letter(l).replace('\'','')
letter = Node(alphabet.letter(l),l)
Nodes.append(letter)
for i in range(line):
line2 = f.readline().rstrip()
nodes = line2.split()
for j in range(2,len(nodes),2):
for k in range(len(Nodes)):
if(Nodes[k].name == nodes[j]):
Nodes[i].add(Nodes[k], int(nodes[j+1]))
Nodes[0].ShortestPath()
for i in range(len(Nodes)):
if((i > 0 and i < len(Nodes)-1) and (len(Nodes[i].lower_nodes) == 0 or len(Nodes[i].higher_nodes) == 0)):
continue
remove = []
for j in range(len(Nodes[i].higher_nodes)):
if(Nodes[i].tentative + Nodes[i].distances[Nodes[i].higher_nodes[j].name] > Nodes[i].higher_nodes[j].tentative):
remove.append(Nodes[i].higher_nodes[j])
print Nodes[i].name + ' : ' + Nodes[i].higher_nodes[j].name
for r in range(len(remove)):
remove[r].lower_nodes.remove(Nodes[i])
Nodes[i].higher_nodes.remove(remove[r])
for i in range(len(Nodes)):
if(Nodes[i].num_higher > len(Nodes[i].higher_nodes)):
for q in range(len(Nodes[i].higher_nodes)):
marks += 1
print Nodes[len(Nodes)-1].tentative, marks
Nodes = []
line = int(f.readline().rstrip())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.