text stringlengths 37 1.41M |
|---|
"""
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a b, then a and b are an
amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110;
therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
"""
import math
from p12 import factor, getPrimes
import unittest
PRIMES = getPrimes(10001)
def sumProperDivisors(n, PRIMES):
"""
Returns the sum of the proper divisors of n
"""
factors = factor(n, PRIMES)
s = 1
for x in factors:
s *= (math.pow(x, factors[x]+1)-1) / (x - 1)
return int(s) - n
class testProblem(unittest.TestCase):
def setUp(self):
pass
def testSumProperDivisors(self):
self.assertEquals(16, sumProperDivisors(12, PRIMES))
self.assertEquals(42, sumProperDivisors(30, PRIMES))
if __name__ == '__main__':
#test
suite = unittest.TestLoader().loadTestsFromTestCase(testProblem)
unittest.TextTestRunner(verbosity=2).run(suite)
candidates = range(1,10000)
amicable = []
rejected = []
for x in candidates:
if (x not in amicable) and (x not in rejected):
sumDivisors = sumProperDivisors(x, PRIMES)
sumOtherDivisors = sumProperDivisors(sumDivisors, PRIMES)
if x == sumOtherDivisors and x != sumDivisors:
amicable.append(x)
amicable.append(sumDivisors)
else:
rejected.append(x)
rejected.append(sumDivisors)
print sum(amicable) |
"""
What is the first term in the Fibonacci sequence to contain 1000 digits?
"""
import math
import unittest
def firstFibDigGtr(n):
"""
Returns the counter of the first Fibonacci number with # digits greater than n
"""
f1 = 1
f2 = 1
counter = 2
keepGoing = True
while keepGoing:
f1, f2 = f2, f1 + f2
counter += 1
if n < len(str(f2)):
keepGoing = False
break
return counter
class testProblem(unittest.TestCase):
def setUp(self):
pass
def testFirstFibDigGtr(self):
self.assertEquals(7, firstFibDigGtr(1))
self.assertEquals(12, firstFibDigGtr(2))
if __name__ == '__main__':
#test
suite = unittest.TestLoader().loadTestsFromTestCase(testProblem)
unittest.TextTestRunner(verbosity=2).run(suite)
print firstFibDigGtr(999) |
"""
Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 2020 grid?
"""
import unittest
def getMatrix(n):
"""
Returns an (n+1) by (n+1) matrix result of ways to get from result[i,j] to result[-1,-1]
for n = 2, should return
[[6,3,1],
[3,2,1],
[1,1,1]
]
"""
res = []
for i in range(n+1):
res.append([0]*(n+1))
#build the origin
res[0][0] = 1
#build the edges
for x in range(1, len(res)):
res[x][0] = res[x-1][0]
for y in range(1, len(res)):
res[0][y] = res[0][y-1]
#build the inside
for x in range(1,len(res)):
for y in range(1, len(res)):
res[x][y] = res[x-1][y] + res[x][y-1]
return res
class testProblem(unittest.TestCase):
def setUp(self):
pass
def testGetMatrix(self):
pass
self.assertEquals([[1,1,1],[1,2,3],[1,3,6]], getMatrix(2))
if __name__ == '__main__':
#test
suite = unittest.TestLoader().loadTestsFromTestCase(testProblem)
unittest.TextTestRunner(verbosity=2).run(suite)
print getMatrix(20)[-1][-1] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sympy import *
#símbolo, função, valor inicial, número de iterações
def pfixo (px, pf, x0, it):
x = Symbol(px)
f = sympify(pf)
print ("f(x) =", pf, "\n")
for i in range(0, it):
print ("Iteração", i+1)
fx0 = f.subs(x, x0).evalf()
print ("x =", x0, "\t", "f(x) =", fx0)
x0 = fx0
pfixo ('x', 'ln(10/x)', 1, 15)
# pfixo ('x', 'ln(x) * cos(x)', 1.1, 15) #não converge
|
power_cache = {x: x ** 5 for x in xrange(0, 10)}
def get_digits(num):
digits = []
while (num >= 10):
digit = num % 10
num = num / 10
digits.append(digit)
digits.append(num)
return digits
def sum_digit_powers(num_list):
total = 0
for num in num_list:
total += power_cache[num]
return total
final_sum = 0
upper_limit = 6 * (9 ** 5)
for i in xrange(2, upper_limit):
if i == sum_digit_powers(get_digits(i)):
final_sum += i
print final_sum
|
from abc import ABCMeta, abstractmethod
class Component(metaclass=ABCMeta):
# variable initiation
target = None
value = 0
speed = 1
# getter and setter methods
def set_target(self, target: object = None):
self.target = target
def get_target(self):
return self.target
def set_value(self, value: int = 0):
self.value = value
def get_value(self):
return self.value
def set_speed(self, speed: int = 1):
self.speed = speed
def get_speed(self):
return self.speed
def add_value(self, value: int = 1):
self.value += value
# init method
def __init__(self, target: object = None, value: int = 0, speed: int = 1):
self.set_target(target)
self.set_value(value)
self.set_speed(speed)
# custom methods
def execute(self):
if self.get_target() is not None\
and self.get_value() > 0:
if self.get_value() >= self.get_speed():
self.get_target().add_value(self.get_speed())
self.add_value(-self.get_speed())
else:
self.get_target().add_value(self.get_value())
self.add_value(-self.get_value())
@abstractmethod
def to_text(self):
pass
def update(self):
self.execute()
|
import turtle
myPen = turtle.Turtle()
myPen.speed(0)
myPen.color("black")
side=200
for i in range (1,20):
myPen.forward(side)
myPen.left(90)
side=side-10
|
def is_multiple(x,y):
'''is_multiple(x,y) -> bool
returns True is x is a multiple of y, False otherwise'''
# check if y divides evenly into x
return (x % y == 0)
def is_prime(n):
'''is_prime(n) -> bool
returns True if n is prime, False if n is not prime'''
# check every divisor from 2 up to sqrt(n)
for div in range(2,int(n**0.5)+1):
if is_multiple(n,div):
return False # n isn't prime
return True # n is prime
def sum_of_primes(k):
'''sum_of_primes(k) -> int
returns sum of the first k primes'''
total = 0 # running total
nextNumber = 2
for i in range(k):
while not is_prime(nextNumber): # find the next prime
nextNumber += 1
total += nextNumber # we found a prime, add it to the total
nextNumber += 1
return total
print(sum_of_primes(10002)) |
from Input import name, position, salary
class Employee:
"""
Keep information of employee and their information.
"""
def __init__(self, name, position, salary):
self.name = name
self.position = position
self.salary = salary
def get_employee_name(self):
return "Employee Name: " + str(self.name)
def get_position(self):
return "Position: " + str(self.position)
def get_salary(self):
return "Salary: " + str(self.salary)
p = Employee(name, position, salary)
print(p.get_position())
|
# map(), filter(), and reduce()
from functools import reduce
# map()
my_list = [1, 2, 3, 4]
my_list = list(map(lambda num: num * num, my_list))
# Option 2 not use map()
my_list = [1, 2, 3, 4]
my_list = [num * num for num in my_list]
# filter()
my_list = [1, 2, 3, 4]
my_even_list = list(filter(lambda x: x % 2 == 0, my_list))
# Option 2 not to use filter()
my_even_list = [num for num in my_list if num % 2 == 0]
# reduce()
my_list = [1, 2, 3, 4]
sum = 0
for num in my_list:
sum += num
result_with_reduce = reduce(lambda sum, cur_num: sum + cur_num, my_list)
|
# Abstract class allows us to create methods that must be created within any child class
from abc import ABC, abstractmethod # Abstract Base classes(ABC)
from typing import List
# You can't initiate an abstract class
class Animal(ABC):
@abstractmethod
def eat(self):
pass
@abstractmethod
def sleep(self):
pass
def shout(self):
print("Shouting...")
# Child class must initiate abstract method
class Bird(Animal):
def eat(self):
print("Bird is eating")
def sleep(self):
print("Bird is sleeping")
# Child class must initiate abstract method
class Pig(Animal):
def eat(self):
print("Pig is eating")
def sleep(self):
print("Pig is sleeping")
my_bird = Bird()
my_pig = Pig()
animals: List[Animal] = [my_bird, my_pig]
for animal in animals:
animal.eat()
animal.sleep()
animal.shout()
print("done")
|
import random
file = open("/usr/share/dict/words")
file = file.read()
dictionary_words = file.split()
def get_random_words(word_count):
sentence = ""
for i in range(0,words):
random_number = random.randint(0, len(dictionary_words)-1)
sentence += dictionary_words[random_number] + " "
test = True
print sentence
words = input("Number of Words: ")
get_random_words(words)
|
import os
class Atbash(object):
def __init__(self, msg, oper):
self.msg = msg
self.oper = oper
def ValidateMsg(self):
opers = {"ENCRYPT": lambda: Atbash.Encrypt(self), "DECRYPT": lambda: Atbash.Decrypt(self)}
for x in range(len(self.msg) + 1):
if x < len(self.msg):
check = ord(self.msg[x])
if check < 65 or check > 90:
print "Invalid Message."
pause = raw_input()
main()
break
else:
pass
else:
opers[self.oper]()
def Encrypt(self):
cipherText = ""
"""if chr(i + 13) > chr(90):
NEW_KEY = (i + 13) - 26
cipher_msg += chr(NEW_KEY)"""
for x in range(len(self.msg)):
msgChr = ord(self.msg[x])
if chr(msgChr + 13) > chr(90):
cipherText += chr((msgChr + 13) - 26)
else:
cipherText += chr(msgChr + 13)
print "Plain Text: %s\nCipher Text: %s" % (self.msg, cipherText)
pause = raw_input()
main()
def Decrypt(self):
plainText = ""
for x in range(len(self.msg)):
msgChr = ord(self.msg[x])
if chr(msgChr - 13) < chr(65):
plainText += chr((msgChr - 13) + 26)
else:
plainText += chr(msgChr - 13)
print "Cipher Text: %s\nPlain Text: %s" % (self.msg, plainText)
pause = raw_input()
main() |
class Encrypt(object):
def __init__(self, key, word):
self.key = key
self.word = word
def errors(self, error):
print error
pause = raw_input()
def encrypt(self):
if self.key > 25 or self.key == 0:
super(Encrypt, self).errors("key must be: > 0 & < 26")
else:
LAST_LETTER = 90
numericList = []
cipherList = []
cipher_word = ""
for c in self.word:
numericList.append(ord(c))
for i in numericList:
if i in range(65, 91):
pass
elif i == 32:
pass
else:
pass
for i in numericList:
if chr(i + self.key) > chr(90):
NEW_KEY = (i + self.key) - 26
cipherList.append(chr(NEW_KEY))
elif i != 32:
cipherList.append(chr(i + self.key))
elif i == 32:
cipherList.append(" ")
for c in cipherList:
cipher_word += c
return "Plain Text: %s\nCipher Text: %s" % (self.word, cipher_word)
test = Encrypt(12, "Hey")
print test.encrypt() |
import sys
print ("CALCULADORA")
print ("1. Suma")
print ("2. Resta")
print ("3. Multiplicacion")
print ("4. Division")
print ("5. Salir")
print ("")
def suma():
print ("*****SUMA*****")
num1 = int(input("Digite el primer numero: "))
num2 = int(input("Digite el segundo numero: "))
resul = num1 + num2
print("El resultado de la suma es: ", resul)
print ("")
def resta():
print ("*****RESTA*****")
num1 = int(input("Digite el primer numero: "))
num2 = int(input("Digite el segundo numero: "))
resul = num1 - num2
print("El resultado de la resta es: ", resul)
print ("")
def multi():
print ("*****MULTIPLICACION*****")
num1 = int(input("Digite el primer numero: "))
num2 = int(input("Digite el segundo numero: "))
resul = num1 * num2
print("El resultado de la multiplicacion es: ", resul)
print ("")
def div():
print ("*****DIVISION*****")
num1 = int(input("Digite el primer numero: "))
num2 = int(input("Digite el segundo numero: "))
if (num2 != 0):
resul = num1 // num2
print("El resultado de la division es: ", resul)
print ("")
else:
print("La division entre 0 no esta definida, escoja otro numero.")
def salir():
print("Gracias por utilizar nuestra aplicacion, hasta pronto.")
sys.exit()
try:
a = int(input("Escoja una opcion del menu: "))
while (a<=5):
operaciones = [suma,resta,multi,div,salir]
operaciones[a-1]()
print ("CALCULADORA")
print ("1. Suma")
print ("2. Resta")
print ("3. Multiplicacion")
print ("4. Division")
print ("5. Salir")
print ("")
a = int(input("Escoja una opcion del menu: "))
except (ValueError):
print("A ocurrido un error, vuelva a intentarlo.")
|
'''
Proj - Memory Game
CS5001 Fall 2020
Nolen Belle Bryant
Function check_button - Will take the x and y coordinates
of the click and will return an integer if the click was 'on a card'. The returned int serves as the index #
of where the clicked on card is stored in the deck.box
area - a list containing tuples of tuples which correspond to the x min and max & the y min and max
coordinates of each card displayed on the table.
'''
area = [((160, 250), (75, 225)), ((160, 250), (-100, 50)), ((45, 135), (75, 225)), ((45, 135), (-100, 50)), ((-70, 20), (75, 225)), ((-70, 20), (-100, 50)), ((-185, -95), (75, 225)), ((-185, -95), (-100, 50)), ((-300, -210), (75, 225)), ((-300, -210), (-100, 50)), ((-415, -325), (75, 225)), ((-415, -325), (-100, 50))]
def delay(x,y):
x = 0
y = 0
def check_button(x,y):
''' Function: check_button - checks if an on screen click was on a card
Parameters: x (int), y (int) - coordinates of click
Return- int - the index of the card stored in deck.box if a click on a card or string if not
'''
for i in range(12):
if area[i][0][0] <= x and area[i][0][1] >= x: # check valid x
if area[i][1][0] <= y and area[i][1][1] >= y: # check valid y
return(i)
return ('invalid')
|
https://www.luogu.org/problemnew/solution/P1909?page=2
import math
ans = 1e9
n = int(input())
for i in range(3):
num, price = map(int, input().split())
tmp = math.ceil(n / num) * price
if tmp < ans:
ans = tmp
print(ans)
from math import ceil
n = int(input())
l = (tuple(map(int, input().split())) for i in range(3))
r = min(ceil(n/number)*price for number, price in l)
print(r) |
#作者:SunnyMarkLiu
#链接:https://www.zhihu.com/question/37146648/answer/80425957
#来源:知乎
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#!/usr/bin/python2.7
# _*_ coding: utf-8 _*_
from matplotlib import pyplot as plt
from matplotlib import font_manager
# 准备数据
def file2matrix(filename):
fr = open(filename)
arrayOLines = fr.readlines()
# print(type(arrayOLines))
# print(arrayOLines[1:10])
numberOfLines = len(arrayOLines) #get the number of lines in the file
# print(numberOfLines)
returnMat = zeros((numberOfLines,3)) #prepare matrix to return
classLabelVector = [] #prepare labels return
fr = open(filename)
index = 0
for line in fr.readlines():
line = line.strip() #移除头尾的指定符(回车字符),默认空格
listFromLine = line.split('\t') #以行进行读取,以\t进行分割
returnMat[index,:] = listFromLine[0:3]
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
matrix, labels = file2matrix('datingTestSet2.txt')
#print(matrix)
#print(labels)
#zhfont = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/ukai.ttc')
""" 比较好看的绘制方法 """
plt.figure(figsize=(8, 5), dpi=80)
axes = plt.subplot(111)
# 将三类数据分别取出来
# x轴代表飞行的里程数
# y轴代表玩视频游戏的百分比
type1_x = []
type1_y = []
type2_x = []
type2_y = []
type3_x = []
type3_y = []
#print('range(len(labels)):')
#print(range(len(labels)))
for i in range(len(labels)):
if labels[i] == 1: # 不喜欢
type1_x.append(matrix[i][0])
type1_y.append(matrix[i][1])
if labels[i] == 2: # 魅力一般
type2_x.append(matrix[i][0])
type2_y.append(matrix[i][1])
if labels[i] == 3: # 极具魅力
# print(i, ':', labels[i], ':', type(labels[i]))
type3_x.append(matrix[i][0])
type3_y.append(matrix[i][1])
type1 = axes.scatter(type1_x, type1_y, s=20, c='red')
type2 = axes.scatter(type2_x, type2_y, s=40, c='green')
type3 = axes.scatter(type3_x, type3_y, s=50, c='blue')
# plt.scatter(matrix[:, 0], matrix[:, 1], s=20 * numpy.array(labels),
# c=50 * numpy.array(labels), marker='o',
# label='test')
plt.xlabel(u'每年获取的飞行里程数')
plt.ylabel(u'玩视频游戏所消耗的事件百分比')
axes.legend((type1, type2, type3), (u'不喜欢', u'魅力一般', u'极具魅力'), loc=2)
#axes.legend((type1, type2, type3), (u'不喜欢', u'魅力一般', u'极具魅力'), loc=2, prop=zhfont)
plt.show() |
print('let\'s calculate some squares')
for the_num in range(13):
print(the_num, 'squared is', the_num**2)
print('all done')
num_hi = int(input('how many times to say hi?'))
for dont_matter in range(num_hi):
print('hi!') |
keep_going = 'y'
while keep_going == 'y':
sales = float(input('please enter sales'))
comm_rate = float(input('please enter rate'))
commission = sales * comm_rate
print('commission is', commission)
keep_going = input('another? (y for yes)') |
from time import time
def timer(func):
"""
Timing wrapper for a generic function.
Prints the time spent inside the function to the output.
"""
def new_func(*args, **kwargs):
start = time()
val = func(*args,**kwargs)
end = time()
print('Time taken by function {} is {} seconds'.format(func.__name__, end-start))
return val
return new_func
|
def csOppositeReverse(txt):
reversedOrder = txt[::-1]
reversedCase = reversedOrder.swapcase()
return reversedCase
print(csOppositeReverse('Hello World')) |
#5 A school decided to replace the desks in three classroom. Each desk sits two students. Given the number of students
# in each class ,print the smallest possible number of desks that can be purchased
# the program should read three integers. the number of students in each of the three classes a, b and c respectively
# in the first test there are three groups
no_student_class1 = int(input("enter the number of student in first class : "))
no_student_class2 = int(input("enter the number of student in second class : "))
no_student_class3 = int(input("enter the number of student in third class : "))
desk_class1 = (no_student_class1 // 2)
print(f"the required number of desk for the first class is {desk_class1}")
desk_class2 = (no_student_class2 // 2)
print(f"the required number of desk for the second class is {desk_class2}")
desk_class3 = (no_student_class3 // 2)
print(f"the required number of desk for the third class is {desk_class3}")
remain_class1 = (no_student_class1 % 2)
print(f"remaining desk for first class is {remain_class1}")
remain_class2 = (no_student_class2 % 2)
print(f"remaining desk for first class is {remain_class2}")
remain_class3 = (no_student_class3 % 2)
print(f"remaining desk for first class is {remain_class3}")
total_desk = desk_class1+desk_class2+desk_class3+remain_class1+remain_class2+remain_class3
print(f"the total number of desks that can be purchased are{total_desk}")
|
#WAP to check and print if the number is even or odd
for i in range(0,10,1) :
if i % 2 == 0:
print (f"{i} is even")
else:
print (f"{i} is odd")
|
d=float(input("how far did you travel today (in miles)?"))
t=float(input("how long did it take you (in hours)?"))
speed=d//t
km=d*1.609
kmph=km//t
print(f"your speed was {speed} miles per hour")
print(f"your speed was {kmph} km per hour")
|
'''
STEP 1: Choose the number K of neighbors
STEP 2: Take the K nearest neighbors of the new data point, according to your distance metric
STEP 3: Among these K neighbors, count the number of data points to each category
STEP 4: Assign the new data point to the category where you counted the most neighbors
'''
# Importing and preperation of data
# E:/ds_practice/case_study/knn
import numpy as np
import pandas as pd
# Load Dataset
dataset = pd.read_csv(r'Iris.csv')
print(dataset.head())
# Summarize dataset
print(dataset.shape)
print(dataset.describe())
print(dataset.groupby('Species').size())
# Dividing data into features and labels
feature_columns = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm','PetalWidthCm']
#X = dataset[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm','PetalWidthCm']].values
X = dataset[feature_columns].values
print(type(X))
print(X[0:2])
y = dataset['Species'].values
print(type(y))
print(y[0])
print(y[0:2])
# Label encoding
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)
print(type(y))
print(y[0:150])
# Spliting dataset into training set and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 0)
# Data Visualization
import matplotlib.pyplot as plt
import seaborn as sns
# Parallel Coordinates (for multivariate data )
from pandas.plotting import parallel_coordinates
plt.figure(figsize=(15,10))
parallel_coordinates(dataset.drop("Id", axis=1), "Species")
plt.title('Parallel Coordinates Plot', fontsize=20, fontweight='bold')
plt.xlabel('Features', fontsize=15)
plt.ylabel('Features values', fontsize=15)
plt.legend(loc=1, prop={'size': 15}, frameon=True,shadow=True, facecolor="white", edgecolor="black")
plt.show()
# Andrews Curves
from pandas.plotting import andrews_curves
plt.figure(figsize=(15,10))
andrews_curves(dataset.drop("Id", axis=1), "Species")
plt.title('Andrews Curves Plot', fontsize=20, fontweight='bold')
plt.legend(loc=1, prop={'size': 15}, frameon=True,shadow=True, facecolor="white", edgecolor="black")
plt.show()
# 3D
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(1, figsize=(20, 15))
ax = Axes3D(fig, elev=48, azim=134)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y,
cmap=plt.cm.Set1, edgecolor='k', s = X[:, 3]*50)
for name, label in [('Virginica', 0), ('Setosa', 1), ('Versicolour', 2)]:
ax.text3D(X[y == label, 0].mean(),
X[y == label, 1].mean(),
X[y == label, 2].mean(), name,
horizontalalignment='center',
bbox=dict(alpha=.5, edgecolor='w', facecolor='w'),size=25)
ax.set_title("3D visualization", fontsize=40)
ax.set_xlabel("Sepal Length [cm]", fontsize=25)
ax.w_xaxis.set_ticklabels([])
ax.set_ylabel("Sepal Width [cm]", fontsize=25)
ax.w_yaxis.set_ticklabels([])
ax.set_zlabel("Petal Length [cm]", fontsize=25)
ax.w_zaxis.set_ticklabels([])
plt.show()
# Using KNN for classification
# Fitting clasifier to the Training set
# Loading libraries
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, accuracy_score,classification_report
from sklearn.model_selection import cross_val_score
# Instantiate learning model (k = 3)
classifier = KNeighborsClassifier(n_neighbors = 3)
# Fitting the model
classifier.fit(X_train, y_train)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
print(y_pred)
print(y_test)
cm = confusion_matrix(y_test, y_pred)
print(cm)
print(classification_report(y_test, y_pred))
accuracy = accuracy_score(y_test, y_pred)*100
print('Accuracy of our model is equal ' + str(round(accuracy, 2)) + ' %.')
# Using cross-validation for parameter tuning:
# creating list of K for KNN
k_list = list(range(1,50,2))
# creating list of cv scores
cv_scores = []
# perform 10-fold cross validation
for k in k_list:
knn = KNeighborsClassifier(n_neighbors=k)
scores = cross_val_score(knn, X_train, y_train, cv=10, scoring='accuracy')
cv_scores.append(scores.mean())
print(cv_scores)
# changing to misclassification error
MSE = [1 - x for x in cv_scores]
plt.figure()
plt.figure(figsize=(15,10))
plt.title('The optimal number of neighbors', fontsize=20, fontweight='bold')
plt.xlabel('Number of Neighbors K', fontsize=15)
plt.ylabel('Misclassification Error', fontsize=15)
sns.set_style("whitegrid")
plt.plot(k_list, MSE)
plt.show()
# finding best k
best_k = k_list[MSE.index(min(MSE))]
print("The optimal number of neighbors is %d." % best_k)
'''
Pros and Cons of KNN
In this section we'll present some of the pros and cons of using the KNN algorithm.
Pros
* It is extremely easy to implement
* As said earlier, it is lazy learning algorithm and therefore requires no training prior to making real time predictions. This makes the KNN algorithm much faster than other algorithms that require training e.g SVM, linear regression, etc.
* Since the algorithm requires no training before making predictions, new data can be added seamlessly.
* There are only two parameters required to implement KNN i.e. the value of K and the distance function (e.g. Euclidean or Manhattan etc.)
Cons
* The KNN algorithm doesn't work well with high dimensional data because with large number of dimensions, it becomes difficult for the algorithm to calculate distance in each dimension.
* The KNN algorithm has a high prediction cost for large datasets. This is because in large datasets the cost of calculating distance between new point and each existing point becomes higher.
* Finally, the KNN algorithm doesn't work well with categorical features since it is difficult to find the distance between dimensions with categorical features.
'''
|
class Piece(object):
def __init__(self):
self.is_king = False
def is_king(self):
self.is_king = True
class RedPiece(Piece):
def disp_color(self):
if self.is_king == True:
color = "KR"
else:
color = " R"
return color
class BlkPiece(Piece):
def disp_color(self):
if self.is_king == True:
color = "KB"
else:
color = " B"
return color
|
#3.Faça um Programa que peça dois números e imprima a soma.
#
n1 = int(input("Digite um número: "))
n2 = int(input("Digite um número: "))
result = n1+n2
print("A soma dos dois números é: ", result) |
"""
Tema: Busqueda Binaria.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
objetivo = int(input('Type a number: '))
epsilon = 0.001
bajo = 0.0
alto = max(1.0, objetivo)
respuesta = (alto + bajo) / 2
while abs(respuesta**2 - objetivo) >= epsilon:
print(f'bajo={bajo}, alto={alto}, respuesta={respuesta}')
if respuesta**2 < objetivo:
bajo = respuesta
else:
alto = respuesta
respuesta = (alto + bajo) / 2
print(f'La raiz cuadrada de {objetivo} es {respuesta}') |
"""
Tema: Resolviendo reto.
Curso: Python intermedio.
Plataforma: Platzi.
Profesor: Facundo García Martoni.
Alumno: @edinsonrequena.
"""
def divisor(num):
divisor_list = []
for i in range(1, num + 1):
if num % i == 0:
divisor_list.append(i)
return divisor_list
def main():
try:
num = int(input('type number: '))
if len(divisor(num)) == 0:
raise EOFError('No se pueden ingresar numeros negavtivos')
print(divisor(num))
print('The program finally')
except EOFError as e:
print(e)
except ValueError:
print('Solo puedes ingresar un numero')
if __name__ == '__main__':
main()
|
"""
Resolviendo Retos
alumno: @edinsonrequena
"""
def squeares():
arr = [i**2 for i in range(1, 101)]
# print(arr)
def squeares_divisible_3():
# arr = [i**3 for i in range(1, 101) if i % 3 == 0]
arr = [i**2 for i in range(1, 101) if i % 3 is False]
print(arr)
def squeares_par():
# arr = [i**2 for i in range(1, 101) if i % 2 == 0]
arr = [i**2 for i in range(1, 101) if i % 2 is False]
print(arr)
|
"""
Tema: Listas y mutabilidad.
Curso: Pensamiento computacional.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
a = [1, 2, 3]
b = a
print(b) # Vemos como los elementos de a pasan a estar en b
print(id(a)) # Aca podemos ver como a y b estan en el mismo lugar de
print(id(b)) # memoria, lo que quiere decir que son la misma lista.
c = [a, b] # c sera una lista que contigan las listas de a y b
print(c)
print(id(c)) # Aca podemos ver como c ocupa otro lugar en memoria.
a.append(5)
print(a) # Se agrega el elemento 5
print(b) # Se agrega el elemento 5 tambien porque a y b ocupan el mismo lugar en memoria
print(c) # Esto podemos verlo como si c fuese una caja que contiene las cajas a y b pero al a y b ocupar el mismo
# espacio en memoria cuando se modifica a tambien se modifica b y viceversa.
|
"""
Tema: Herencia.
Curso: Curso de python, video 30.
Plataforma: Youtube.
Profesor: Juan diaz - Pildoras informaticas.
Alumno: @edinsonrequena.
"""
class Vehiculo:
def __init__(self, marca, modelo):
self.marca = marca
self.modelo = modelo
self.enmarcha = False
self.acelera = False
self.frena = False
def arrancar(self): self.enmarcha = True
def acelerar(self): self.acelera = True
def frenar(self): self.frena = True
def estado(self):
print(f"""Marca: {self.marca} \n Modelo: {self.modelo} \n En marcha:
{self.enmarcha} \nAcelera: {self.acelera},\n Frena: {self.frena} \n""") # TODO #13
class Moto(Vehiculo): pass
class App: # TODO #16
def crear(self):
objeto_moto_1 = Moto('Honda', 'CBR')
objeto_moto_2 = Moto('Horse', 'x34')
objeto_moto_1.estado()
objeto_moto_2.estado()
if __name__ == '__main__':
App().crear()
|
"""
Tema: Algoritmos de busqueda y ordenamiento - Ordenamiento por Inserccion.
Curso: Pensamiento Computacional, 2da entrega.
Plataforma: Platzi.
Profesor: David Aroesti.
Alumno: @edinsonrequena.
"""
import random
def ordenamiento_por_insercion(lista):
for indice in range(1, len(lista)):
valor_actual = lista[indice]
posicion_actual = indice
while posicion_actual > 0 and lista[posicion_actual - 1] > valor_actual:
lista[posicion_actual] = lista[posicion_actual - 1]
posicion_actual -= 1
lista[posicion_actual] = valor_actual
print(lista)
def main():
tamano_lista = int(input('Tamano de la lista: '))
lista = [random.randint(0,100) for i in range(tamano_lista)]
ordenamiento_por_insercion(lista)
if __name__ == '__main__':
main()
|
"""
Tema: Manejo de Excepciones.
Curso: Python intermedio.
Plataforma: Platzi.
Profesor: Facundo García Martoni.
Alumno: @edinsonrequena.
"""
def palindrome(string):
try:
if len(string) == 0:
raise ValueError('No se puede ingresar una cadena vacia')
return string == string[::-1]
except ValueError as ve:
print(ve)
return False
try:
print(palindrome(''))
except TypeError:
print('Solo puedes ingresar numeros!')
|
"""
Tema: Funciones Lambda
Curso: Python intermedio.
Plataforma: Platzi.
Profesor: Facundo García Martoni.
Alumno: @edinsonrequena.
"""
palindrome = lambda string: string == string[::-1]
print(palindrome('ana'))
|
from random import randint
from turtle import*
#Turtle 1 attributes
t = Turtle()
t.speed(0)
t.hideturtle()
#Turtle 2 attributes
t2 = Turtle()
t2.speed(0)
t2.hideturtle()
#Drawing the hangman
def draw_gallows():
t.penup()
t.goto(0,0)
t.pendown()
t.setheading(0)
t.forward(200)
t.back(100)
t.setheading(90)
t.forward(300)
t.setheading(0)
t.forward(100)
t.right(90)
t.forward(50)
def draw_head():
t.right(90)
t.circle(25)
t.penup()
t.right(270)
t.penup()
t.forward(50)
def draw_body():
t.pendown()
t.forward(100)
def draw_rleg():
t.right(315)
t.forward(75)
def draw_lleg():
t.back(75)
t.right(90)
t.forward(75)
def draw_larm():
t.back(75)
t.right(135)
t.forward(75)
t.right(270)
t.forward(75)
def draw_rarm():
t.back(150)
def draw_hangman(limbs):
if limbs == 0:
draw_gallows()
elif limbs == 1:
draw_head()
elif limbs == 2:
draw_body()
elif limbs == 3:
draw_rleg()
elif limbs == 4:
draw_lleg()
elif limbs == 5:
draw_larm()
elif limbs == 6:
draw_rarm()
#Checks to see if guessed word is inside of the actual word
def update(word, dash, ch):
matchmaker = 0
z = 0
while z < len(word):
if ch == word[z:z + 1]:
dash[z:z + 1] = ch
matchmaker = 1
z = z + 1
return(matchmaker)
#Returns False if the game is over, and returns True if the game is still running
def gameStillRunning(word, dash, gamerunning):
#Checks to see if game is over
z = 0
while z < len(word):
if word[z:z + 1] != dash[z]:
break
z = z + 1
if z == len(word):
return False
else:
return True
#Writes the dashes to show how many letters in word
def dash_writer(dash):
t2.color("black")
t2.penup()
t2.goto(-200,-200)
t2.write(''.join(dash),align="center",font=("Comic Sans",30,"normal"))
#Draws a white line over the dashes so they can update the letters
def white_line():
t2.penup()
t2.goto(-400,-200)
t2.pendown()
t2.color("white")
t2.goto(400,-200)
#Creates the pop-up box
def pop_up():
guessc = ""
while len(guessc) != 1:
guessc = sc.textinput("Virus.py","Choose one letter ")
return guessc
#Either displays you win or you lose after the game
def display_end_of_game_message(xguess, word):
t2.penup()
t2.color("green")
t2.goto(-400,-200)
if xguess < 6:
t2.write("You Win!", align="left", font=("Times New Roman",50,"normal"))
else:
t2.color("red")
t2.write("You Lose", align="left", font=("Times New Roman", 50, "normal"))
t2.goto(-400,-300)
t2.write("The word you were guessing was " + word, align="left",font=("Times New Roman",30,"normal"))
#Movie list and chooser
movies = ["endgame", "the fault in our stars","now you see me","conjuring", "moana", "toy story", "the book of henry", "hacksaw ridge", "godzilla", "alien", "star wars", "harry potter"]
word = movies[randint(0, len(movies)-1)]
dash = ["-"] * len(word)
#Variables
z = 0
sc = Screen()
gamerunning = 1
xguess = 0
#This loop checks for spaces and adds the spaces
while z < len(word):
if " " == word[z:z + 1]:
dash[z] = " "
z = z + 1
t2.pensize(100)
draw_hangman(xguess)
#This loop contains everything that happens inside the game
while gamerunning == 1 and xguess < 6:
#Writers dashes
dash_writer(dash)
#This loop just checks if they put one letter into the pop-up and if they didn't it asks again
guessc = pop_up()
#This If statement checks if they got the guess wrong and if they did then it draws a body part
if update(word, dash, guessc) == False:
xguess = xguess + 1
draw_hangman(xguess)
#Is the game over
gamerunning = gameStillRunning(word, dash, gamerunning)
#Draws a white line over the word to put the updated guessed letters in.
white_line()
#Either writes you win or you lose depending on outcome.
display_end_of_game_message(xguess, word)
|
import os
import csv
def txt_to_csv(txtfile, csvfile=None):
''' Convert txtfile to csvfile
Params:
txtfile : path to txtfile
csvfile : path to new csvfile
Return :
csvfile : path to saved csvfile
'''
if csvfile == None:
csvfile_name = txtfile.strip().split('/')[-1].split('.')[0] + '.csv'
csvfile = os.path.join('/'.join(txtfile.strip().split('/')[:-1]), csvfile_name)
with open(txtfile, 'r') as f:
data = (line.strip().split('\t') for line in f)
with open(csvfile, 'w+') as out_f:
writer = csv.writer(out_f)
writer.writerows(data)
return csvfile
|
import random
def random_y_for(x):
min_y = 0
max_y = 10
if x >= 0:
min_y = -10
max_y = 0
return random.randint(min_y, max_y)
def label_for(x):
return 'o' if x < 0 else 'x'
def make_random():
x = random.randint(-10, 10)
y = random_y_for(x)
return (x, y, label_for(x))
def make_n_random(n):
return [make_random() for _ in range(0, n)]
def all_labels():
return ['x', 'o']
|
#if you wanna study 3d graphs, this is the best example on the pc
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d
matplotlib.rcParams["backend"] = "TkAgg"
fig = plt.figure()
chart=fig.add_subplot(1,1,1, projection="3d")
x =[1,2,3,4,5,6,7,8,9]
y =[2,4,6,8,10,12,14,16,18] #x-y graph, watch from above for perspective, since x and y are present on the base it'll create a ladder
z =[0,0,0,0,0,0,0,0,0] #all are 0 such that graph sits on the base, z reps height
dx=np.ones(9) #np.ones means [1,1,1,1,1,1,1,1,1] 9 times 1
dy=np.ones(9)
dz=[1,2,3,4,5,6,7,8,9] #graph ascends in this manner
chart.bar3d(x,y,z,dx,dy,dz,color="cyan")
chart.set_xlabel("x=axis")
chart.set_ylabel("y=axis")
chart.set_zlabel("z=axis")
print(plt.switch_backend("TkAgg"))
print(plt.show())
'''from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
chart=fig.add_subplot(1,1,1, projection="3d")
#x,y,z represent where the bar is located on the graph
x =[1,2,3,4,5,6,7,8,9]
y =[0,0,0,0,0,0,0,0,0]
z =[0,0,0,0,0,0,0,0,0] #all are 0 such that graph sits on the base, z reps height
#dx,dy,dz give the dimensions to the bar itself
dx=np.ones(9) #np.ones means [1,1,1,1,1,1,1,1,1] 9 times 1, i,e square of unit lenght is the base with dz ascending
dy=np.ones(9)
dz=[1,2,3,4,5,6,7,8,9] #graph ascends in this manner because you can invision it as a height
chart.bar3d(x,y,z,dx,dy,dz,color="cyan")
chart.set_xlabel("x=axis")
chart.set_ylabel("y=axis")
chart.set_zlabel("z=axis")
print(plt.show())
'''
|
import re
import urllib.request
url = "http://dictionary.reference.com/browse/"
word = input("Enter your word: ")
url = url + word
data = urllib.request.urlopen(url).read()
data1 = data.decode("utf-8")
m = re.search('meta name="description" content="', data1)
start = m.end()
end = start + 300
newString = data1[start: end]
m = re.search("See more.", newString)
end = m.start() - 1
definition = newString[0:end]
print(definition) |
'''
This program is a simple example of Message Box in Tkinter where you can use various types,
in this program we only came across (askquestion & showinfo)
'''
from tkinter import *
import tkinter.messagebox
root=Tk()
answer=tkinter.messagebox.askquestion("Question","Do you get offended if i use swear words?")
if answer=="no":
tkinter.messagebox.showinfo("Information Title","You're a nice person")
else:
tkinter.messagebox.showinfo("Information Title","You're just another typical shithead")
root.mainloop() |
#creating a colorful graph
import matplotlib.pyplot as pp
fig = pp.figure()
rect = fig.patch
rect.set_facecolor("xkcd:mint green") #changes the color of the background/figure
x=[2,4,8,9,9]
y=[4,7,6,8,7]
graph1=fig.add_subplot(1,1,1)
graph1.set_facecolor('xkcd:salmon') #changes the color of plot inside
graph1.plot(x,y,"white",linewidth=2.0)
graph1.tick_params(axis="x",color="red") #gives color to parameters (x-axis)
graph1.tick_params(axis="y",color="red") #gives color to parameters (y-axis)
graph1.spines["top"].set_color("white") #this and following 3 lines give color to the boundary
graph1.spines["bottom"].set_color("white")
graph1.spines["left"].set_color("white")
graph1.spines["right"].set_color("white")
graph1.set_title("Test Graph",color="blue") #this and following 2 lines set title and x,y labels along with there colors
graph1.set_xlabel("This is an x-axis",color="blue")
graph1.set_ylabel("This is a y-axis",color="blue")
print(pp.show())
"""" For code to put in perspective, for learning purpose only
>>> import matplotlib
>>> import matplotlib.pyplot as hit
>>> kit = hit.figure()
>>> pot = kit.patch
>>> pot.set_facecolor('green')
>>> x = [3,12,20,24,29]
>>> y = [5,9,15,19,23]
>>> bit = kit.add_subplot(1,1,1,axisbg='red')""" |
#random rectrangle generator
from tkinter import *
import random
root=Tk()
can=Canvas(root,width=400,height=400)
can.pack()
def rect(num): #num represents number of rectrangles to be printed
for i in range(0,num):
x1=random.randrange(400)
y1=random.randrange(400)
x2=x1+random.randrange(400)
y2=y1+random.randrange(400)
can.create_rectangle(x1,x2,y1,y2)
rect(910) #here 720 is no. of rectrangles
can.mainloop() |
number = int(input())
word = input()
print(word*number)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 3 09:43:39 2019
@author: abhineet
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('winequality-red.csv', delimiter=';')
col = data.columns
mean = data.mean()
for i in col:
if i == 'quality':
continue
data[i]=data[i].apply(lambda x:(x-mean[i])/(data[i].max()-data[i].min()))
data.insert(0, 'x0', 1)
print(data.head())
X_df = data.iloc[:,:-1]
y_df = data.iloc[:,12:]
m=len(y_df)
#print (m)
#plt.figure(figsize=(10,8))
#plt.plot(X_df, y_df)
alpha1 = 1
alpha2 = 0.003
alpha3 = 0.00003
noi = 500
X = np.array(X_df)
y = np.array(y_df)
theta = np.array([[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]])
def cost_function(X, y, theta):
## number of training examples
m = len(y)
## Calculate the cost with the given parameters
J_theta = (np.sum((X.dot(theta)-y)**2))/2/m
return J_theta
J = cost_function(X, y, theta)
print(J)
def gradient_descent(X, y, theta, alpha, iterations):
cost_update = [0] * iterations
for i in range(iterations):
#print(theta.shape,X.shape,"theta,X")
hypothesis = X.dot(theta)
#print(hypothesis.shape,"hypo")
#print(y.shape)
loss = hypothesis-y
#print(X.shape, loss.shape,"X shape")
#print(X.transpose().shape,"transpose")
gradient = (X.transpose()).dot(loss)/m
#print(gradient, "grad")
theta1 = theta - alpha*gradient
cost = cost_function(X, y, theta1)
cost_update[i] = cost
theta = theta1
print(i,cost)
plt.scatter(i,cost)
return theta, cost_update
(t1, c1) = gradient_descent(X, y, theta , alpha1, noi)
#print("Theta Parameters")
#print(X,"X")
#print(t1,"t1")
#print(X.dot(t1), y)
#print("Cost Function for alpha = 0.0003")
#print(c1)
#
#(t2, c2) = gradient_descent(X, y, theta , alpha2, noi)
##print("Theta Parameters")
##print(t2)
#
#print("Cost Function for alpha = 0.003")
#print(c2)
#
#(t3, c3) = gradient_descent(X, y, theta , alpha3, noi)
##print("Theta Parameters")
##print(t3)
#
#print("Cost Function for alpha = 0.00003")
#r2 = r2_score(y, X.dot(theta))
#print(r2)
# mean squared error
mse = np.sum((y - X.dot(t1))**2)
# root mean squared error
# m is the number of training examples
rmse = np.sqrt(mse/m)
# sum of square of residuals
ssr = np.sum((y - X.dot(t1))**2)
# total sum of squares
sst = np.sum((y - np.mean(y))**2)
# R2 score
r2 = 1 - (ssr/sst)
print(r2)
|
def countSmallerToTheRight(values):
"""
Codefights.com interview practice question from Google by the same name.
My first submission was to bisect a sorted list,
which I new had O(n) insertion time complexity.
After a search on the internet,
I see how I could index in O(log n),
I read nneoneo's algorithm outline to count in the binary tree.
http://stackoverflow.com/questions/25251340/in-a-bst-find-count-of-nodes-smaller-greater-than-a-given-node-in-olog-n
"""
if not values:
return []
length = len(values)
counts = [0] * length
indexes = range(length - 2, -1, -1)
root = CountTreeNode(values[-1])
for index in indexes:
value = values[index]
child = insert(root, value)
counts[index] = countSmaller(child)
return counts
class CountTreeNode(object):
def __init__(self, value):
self.value = value
self.parent = None
self.numDescendents = 0
self.children = [None, None]
def insert(root, value):
parent = root
while True:
parent.numDescendents += 1
childIndex = 1 if parent.value < value else 0
children = parent.children
child = children[childIndex]
if child:
parent = child
else:
child = CountTreeNode(value)
children[childIndex] = child
child.parent = parent
return child
def countSmaller(newChild):
count = 0
child = newChild
smaller = child.children[0]
if smaller:
count += smaller.numDescendents
parent = child.parent
while parent:
isGreater = parent.children[1] == child
isEqual = parent.value == newChild.value
if isGreater:
count += 1
if isGreater or isEqual:
smaller = parent.children[0]
if smaller:
count += smaller.numDescendents
child = parent
parent = child.parent
return count
|
def list_o_matic(list, input_pasado):
while list:
if input_pasado in list:
list.remove(input_pasado)
return print("look at the animals:",list)
else:
list.append(input_pasado)
return print("look at the animals:",list)
list.pop()
return print(list)
animals=['cat', 'goat', 'cat']
print(animals)
print("\n")
while animals:
input_animal=input("Introduce el nombre de un animal: ")
if input_animal=="quit":
print("Goodbye!")
break
list_o_matic(animals,input_animal)
|
#Task 1 Create Lists
# [ ] create team_names list and populate with 3-5 team name strings
team_names=["northface", "lasportiva", "redbull", "bestard", "boreal"]
# [ ] print the list
print(team_names)
# [ ] Create a list mix_list with numbers and strings with 4-6 items
mix_list=[5, 2.4, "Banana", 1882, "Hola mundo"]
# [ ] print the list
print(mix_list)
print("\n\n\n\n\n\n")
empty_list = [ ]
sample_list = [1, 1, 2, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5]
mixed_list = [1, 1, "one", "two", 2.0, sample_list, "Hello World"]
# [ ] review and run example
# define list of strings
ft_bones = ["calcaneus", "talus", "cuboid", "navicular", "lateral cuneiform", "intermediate cuneiform", "medial cuneiform"]
# display type information
print("ft_bones: ", type(ft_bones))
# print the list
print(ft_bones)
# [ ] review and run example
# define list of integers
age_survey = [12, 14, 12, 29, 12, 14, 12, 12, 13, 12, 14, 13, 13, 46, 13, 12, 12, 13, 13, 12, 12]
# display type information
print("age_survey: ", type(age_survey))
# print the list
print(age_survey)
# [ ] review and run example
# define list of mixed data type
mixed_list = [1, 34, 0.999, "dog", "cat", ft_bones, age_survey]
# display type information
print("mixed_list: ", type(mixed_list))
# print the list
print(mixed_list) |
from tkinter import Tk, Text, Menu, filedialog, Label, Button, END, W, E, FALSE
from tkinter.scrolledtext import ScrolledText
from src.Solver import Solver
class Editor():
def __init__(self, root):
self.root = root
self.file_path = None
self.root.title( 'Prolog Interpreter' )
# Create a rule label
self.rule_editor_label = Label( root
, text = "Prolog Rules: "
, padx = 10
, pady = 1
)
self.rule_editor_label.grid( sticky="W"
, row = 0
, column = 0
, columnspan = 2
, pady = 3
)
# Create rule editor where we can edit the rules we want to enter:
self.rule_editor = ScrolledText ( root
, width = 100
, height = 30
, padx = 10
, pady = 10
)
self.rule_editor.grid( sticky = W + E
, row = 1
, column = 0
, columnspan = 2
, padx=10
)
self.rule_editor.config( wrap="word"
, undo = True
)
self.rule_editor.focus()
# Create a query label:
self.query_label = Label( root
, text = "Prolog Query:"
, padx = 10
, pady = 1
)
self.query_label.grid( sticky = W
, row = 2
, column = 0
, columnspan = 2
, pady = 3
)
# Create the Prolog query editor we'll use to query our rules:
self.query_editor = Text( root
, width = 77
, height = 2
, padx = 10
, pady = 10
)
self.query_editor.grid( sticky = W
, row = 3
, column = 0
, pady = 3
, padx = 10
)
self.query_editor.config( wrap = "word"
, undo = True
)
# Create a run button which runs the query against our rules and outputs the results in our
# solutions text box / editor.
self.run_button = Button( root
, text='Find Query Solutions'
, height = 2
, width = 20
, command = self.run_query
)
self.run_button.grid( sticky = E
, row = 3
, column = 1
, pady = 3
, padx = 10
)
# Create a solutions label
self.solutions_label = Label( root
, text = "Query Solutions:"
, padx = 10
, pady = 1
)
self.solutions_label.grid( sticky = "W"
, row = 4
, column = 0
, columnspan = 2
, padx = 10
, pady = 3
)
# Create a text box which we'll use to display our Prolog query solutions:
self.solutions_display = ScrolledText ( root
, width = 100
, height = 5
, padx = 10
, pady = 10
)
self.solutions_display.grid( row=5
, column = 0
, columnspan = 2
, padx = 10
, pady = 7
)
# Finally, let's create the file menu
self.create_file_menu()
# Create a menu which will allow us to open / save our Prolog rules, run our query,
# and exit our editor interface
def create_file_menu (self):
self.menu_bar = Menu(root)
file_menu = Menu(self.menu_bar, tearoff=0)
file_menu.add_command(label="Open...", underline=1, command=self.open_file)
file_menu.add_separator()
file_menu.add_command(label="Save", underline=1, command=self.save_file)
file_menu.add_command(label="Save As...", underline=5, command=self.save_file_as)
file_menu.add_separator()
file_menu.add_command(label="Run", underline=1, command=self.run_query)
file_menu.add_separator()
file_menu.add_command(label="Exit", underline=2, command=self.root.destroy)
self.menu_bar.add_cascade(label="File", underline=0, menu=file_menu)
self.root.config(menu=self.menu_bar)
# Show a busy cursor and update the UI
def set_busy(self):
self.root.config(cursor = "watch")
self.root.update()
# Show a regular cursor
def set_not_busy(self):
self.root.config(cursor = "")
# Interpret the entered rules and query and display the results in the solutions text box
def run_query(self):
# Delete all of the text in our solutions display text box
self.solutions_display.delete('1.0', END)
self.set_busy()
# Fetch the raw rule / query text entered by the user
rules_text = self.rule_editor.get(1.0, "end-1c")
query_text = self.query_editor.get(1.0, "end-1c")
# Create a new solver so we can try to query for solutions.
try:
solver = Solver( rules_text )
except Exception as exception:
self.handle_exception("Error processing prolog rules.", exception)
return
# Attempt to find the solutions and handle any exceptions gracefully
try:
solutions = solver.find_solutions( query_text )
except Exception as exception:
self.handle_exception("Error processing prolog query.", exception)
return
# If our query returns a boolean, we simply display a 'Yes' or a 'No' depending on its value
if isinstance(solutions, bool):
self.solutions_display.insert(END, 'Yes.' if solutions else 'No.')
# Our solver returned a map, so we display the variable name to value mappings
elif isinstance(solutions, dict):
self.solutions_display.insert( END, "\n".join("{} = {}"
# If our solution is a list contining one item, we show that
# item, otherwise we display the entire list
.format(variable, value[0] if len(value) == 1 else value)
for variable, value
in solutions.items())
)
else:
# We know we have no matching solutions in this instance so we provide relevant feedback
self.solutions_display.insert(END, "No solutions found.")
self.set_not_busy()
# Handle the exception by printing an error message as well as exception in our solution text editor / display
def handle_exception (self, error_message, exception = ''):
self.solutions_display.insert(END, error_message + "\n")
self.solutions_display.insert(END, str(exception) + '\n')
self.set_not_busy()
def is_file_path_selected (self, file_path):
return file_path != None and file_path != ''
# Return a string containing the file contents of the file located at the specified file path
def get_file_contents(self, file_path):
with open(file_path, encoding="utf-8") as f:
file_contents = f.read()
return file_contents
def set_rule_editor_text ( self, text ):
self.rule_editor.delete(1.0, "end")
self.rule_editor.insert(1.0, text )
self.rule_editor.edit_modified( False )
def open_file(self, file_path=None):
# Open a a new file dialog which allows the user to select a file to open
if file_path == None:
file_path = filedialog.askopenfilename()
if self.is_file_path_selected( file_path ):
file_contents = self.get_file_contents( file_path )
# Set the rule editor text to contain the selected file contents
self.set_rule_editor_text ( file_contents )
self.file_path = file_path
# If we have specified a file path, save the file - otherwise, prompt the user to specify the file location
# prior to saving the file
def save_file(self):
if self.file_path == None:
result = self.save_file_as()
else:
result = self.save_file_as(file_path = self.file_path)
return result
def write_editor_text_to_file (self, file ):
editor_text = self.rule_editor.get(1.0, "end-1c")
file.write(bytes(editor_text, 'UTF-8'))
self.rule_editor.edit_modified(False)
def save_file_as(self, file_path = None):
# If there is no file path specified, prompt the user with a dialog which allows him/her to select
# where they want to save the file
if file_path == None:
file_path = filedialog.asksaveasfilename(
filetypes = (
('Text files', '*.txt')
, ('Prolog files', '*.pl *.pro')
, ('All files', '*.*')
)
)
try:
# Write the Prolog rule editor contents to the file location
with open(file_path, 'wb') as file:
self.write_editor_text_to_file ( file )
self.file_path = file_path
return "saved"
except FileNotFoundError:
return "cancelled"
def undo(self, event=None):
self.rule_editor.edit_undo()
def redo(self, event=None):
self.rule_editor.edit_redo()
if __name__ == "__main__":
root = Tk()
editor = Editor(root)
# Don't allow users to re-size the editor
root.resizable(width = FALSE, height = FALSE)
root.mainloop()
|
list_numbers = list(range(15, 25))
count_even = 0 # количество четных чисел
for value in list_numbers: # перебираем все числа
if value % 2 == 0:
count_even += 1
print(count_even)
|
# Problem name: Special Pythagorean triplet (problem 9)
# Problem url: https://projecteuler.net/problem=9
# Author: Thorvaldur Gautsson
# Question:
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
# a^2 + b^2 = c^2
# For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
import math
def findTriplets(number):
triplets = []
for b in range(1, int(number/2)):
for a in range(1, b):
if pow(number, 2) - 2*number*math.sqrt(pow(a, 2) + pow(b, 2)) - 2*a*b == 0:
c = int(math.sqrt(pow(a, 2) + pow(b, 2)))
triplets.append((a,b,c))
return triplets
def multiplyTriplets(triplet_list):
return [triplet[0] * triplet[1] * triplet[2] for triplet in triplet_list]
triplets = findTriplets(1000)
print("The triplets are: " + str(triplets))
print("The multiplies are: " + str(multiplyTriplets(triplets))) |
mass = [int(ind) for ind in input().split()]
n = len(mass)
def insertion_sort(mass):
count = 0
for j in range(1, n):
key = mass[j]
i = j - 1
while i >= 0 and mass[i] > key:
count += 1
mass[i + 1] = mass[i]
i -= 1
mass[i + 1] = key
return mass
|
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def plot_dense_sensordata(dense_data, ax=None, show=True, show_missing=False, time=None, text=None, ylabels=True):
"""view single patient's worse of dense sensordata, a ndarray or df
where the columns are: heart_rate, activity_rank, resp_pattern.
Optionally supply a series of times of the same length as the array, for xlabel.
If dense_data is a list or batched array, interpret it as a series of dense data arrays
and plot all of them."""
if isinstance(dense_data, list) or (len(dense_data.shape) == 3 and dense_data.shape[0] > 1):
if len(dense_data) > 10:
# display up to a max of 10 rows
dense_data = dense_data[:10]
num_plots = len(dense_data)
fig = plt.figure()
for p in range(num_plots):
ax = fig.add_subplot(num_plots, 1, p+1)
if isinstance(text, list): # interpret text as an input list of text strings
this_text = text[p]
else:
this_text = None
plot_dense_sensordata(dense_data[p], ax=ax, show=False, show_missing=show_missing, text=this_text, ylabels=ylabels)
if show:
plt.show()
return
if ax is None:
fig = plt.figure()
ax = plt.gca()
if isinstance(dense_data, pd.DataFrame):
# cast to numpy values for simplicity
dense_data = np.copy(dense_data.values)
else:
dense_data = np.copy(dense_data)
if time is None:
# default x axis is just a range
time = np.arange(dense_data.shape[0])
ax2 = ax.twinx() # secondary axis for heart rate
# ax3 = ax.twinx() # tertiary axis for resp pattern
resp_pattern = dense_data[:,2]
missing = np.where(resp_pattern == 0)[0]
# time = dense_data.index
# heartrate:
hr = dense_data[:,0]
activity = dense_data[:,1]
if not show_missing:
activity[missing] = np.nan
hr[missing] = np.nan
ax.plot(time, hr, c='tab:orange')
# activity (rank):
ax2.plot(time, activity, c='tab:blue')
# remove margin to ensure the background colour lines up:
ax.margins(x=0)
# ax2.margins(x=0)
plt.xlim([0, len(dense_data)])
# resp pattern:
if len(missing) > 0:
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
dense_data[:,2][np.newaxis],
cmap=plt.get_cmap('Reds').reversed(), alpha=0.3)
# show y-labels
if ylabels:
ax.set_ylabel(f'Heartrate (orange)')
ax2.set_ylabel(f'Activity (blue)')
if text is not None:
plt.text(0.05, 0.9, text,
horizontalalignment='left',
verticalalignment='center',
transform = ax.transAxes)
if show:
plt.show()
else:
return ax
def plot_learning_curve(hist, epoch_start=0):
plt.plot(hist.history['loss'][epoch_start:], c='red', linestyle='-')
plt.plot(hist.history['val_loss'][epoch_start:], c='red', linestyle='--')
plt.plot(hist.history['binary_accuracy'][epoch_start:], c='blue', linestyle='-')
plt.plot(hist.history['val_binary_accuracy'][epoch_start:], c='blue', linestyle='--')
plt.legend(['loss', 'val_loss', 'acc', 'val_acc'])
plt.xlabel('Epoch'); plt.title('Learning curve for self-supervision task')
# plt.ylim([0,0.2])
plt.show()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/2/27 2:30 PM
# @Author : huxiaoman
# @File : 3_longest_substring_without_repeating_characters.py
# @Package : LeetCode
class Solution:
"""
:type s: str
:rtype: int
"""
def lengthOfLongestSubstring(self, s):
max_length, start, char_dict = 0, 0, {}
for idx, char in enumerate(s, 1):
if char_dict.get(char, -1) >= start:
start = char_dict[char]
char_dict[char] = idx
max_length = max(max_length, idx - start)
return max_length
if __name__ == '__main__':
s = Solution()
print s.lengthOfLongestSubstring("abcabcbb") |
__author__ = 'My'
import time
import math
#Teams are split up between White team and Black team
#White team goes first
#To start Timer:
# 1) create instance of TimerClass (in = TimerClass())
# 2) immediately call startTimer for that instance (in.TimerClass(in))
#A single turn for a team is 20 seconds (15 seconds to move, 5 second "break")
#At the end of the first 15 seconds in a turn, collectVotes is called
#To differentiate the teams, the boolean whiteTurn is used (True if it is whites turn, False if it is blacks turn)
#collectVotes is where code to initiate vote collection goes
#When a person first joins the game, to get the time of the current turn, they call getTime()
#The two arguments will be the instance of the class and a boolean depending on their team (white = true, black = false)
#This function returns an integer of how many seconds are left in their team's current turn (0 if it isn't their teams turn)
#this integer is then used to update their personal timer
#From then on their turn times will be updated through notifyTurnStart()
#notifyTurnStart() should prompt members of the appropriate team (based on whiteTurn boolean) to update their personal timers to 15
#Runs indefinitely
class TimerClass:
timer = time.time()
whiteTurn = True
def startTimer(self):
while True:
TimerClass.notifyTurnStart(self, TimerClass.whiteTurn)
time.sleep(15)
TimerClass.collectVotes(self, TimerClass.whiteTurn)
if TimerClass.whiteTurn == False:
TimerClass.whiteTurn = True
else:
TimerClass.whiteTurn = False
time.sleep(5)
def collectVotes(self, wT):
#code to prompt the collecting of votes
if wT == True:
#collect white teams votes
return
else:
#collect black teams votes
return
def notifyTurnStart(self, wT):
if wT == True:
#notify white team that their turn is starting so they can update their countdown timer to 15
return
else:
#notify black team that their turn is starting so they can update their countdown timer to 15
return
def getTime(self, wTeam):
timeNow = time.time()
totalTime = math.floor(timeNow - TimerClass.timer)
turnTime = totalTime%40
#whites turn
if turnTime < 20:
if wTeam == False:
return 0
else:
if turnTime < 15:
return -turnTime+15
return 0
#blacks turn
else:
if wTeam == True:
return 0
else:
if turnTime-20 < 15:
return -turnTime+15
return 0
def main():
h = TimerClass
h.startTimer(h)
return 0
if __name__ == "__main__":
main()
|
from itertools import permutations
import sys
N = int(sys.stdin.readline())
lst = [(i + 1) for i in range(N)]
value = list(permutations(lst, N))
for element in value:
element = list(element)
print(' '.join(list(map(str, element))))
|
import sys
class circular_linked_list:
def __init__(self):
self.head = None
self.tail = None
self.cursor = None
def add(self, node):
if self.tail:
node.next = self.head
node.prev = self.tail
self.tail.next = node
self.head.prev = node
self.tail = node
else:
self.head = node
self.tail = self.head
self.cursor = self.head
def remove(self, K):
for _ in range(K - 1):
self.cursor = self.cursor.next
prev, next = self.cursor.prev, self.cursor.next
stack.append(self.cursor.value)
self.cursor = next
prev.next = next
next.prev = prev
class node:
def __init__(self, value, prev = None, next = None):
self.value = value
self.prev = prev
self.next = next
N, K = map(int, sys.stdin.readline().split())
if N == K == 1:
print("<1>")
else:
stack = list()
cll = circular_linked_list()
for i in range(1, N + 1):
cll.add(node(str(i)))
for _ in range(N):
cll.remove(K)
answer = "<"
for i in range(N):
if i < N - 1:
answer += (stack[i] + ', ')
else:
answer += (stack[i] + ">")
print(answer) |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 5 16:32:41 2020
@author: elin9
"""
# combination (pick m elements from n elements)
def pick(n, picked, m):
if (m == 0):
print(picked)
return
if len(picked) == 0 :
smallest = 0
else :
smallest = picked[-1] + 1
for next in range(smallest, n):
picked.append(next)
pick(n, picked, m - 1)
picked.pop()
pick(5, [], 3) |
from collections import deque
def bfs(graph, root, length):
visited = [-1 for _ in range(length + 1)]
count = 0
queue = deque([[root, count]])
while queue:
value = queue.popleft()
n = value[0]
count = value[1]
if visited[n] == -1:
visited[n] = count
count += 1
for element in graph[n]:
queue.append([element, count])
return visited
def dfs(graph, root, length):
visited = [-1 for _ in range(length + 1)]
count = 0
queue = deque([[root, count]])
while queue:
value = queue.popleft()
n = value[0]
count = value[1]
if visited[n] == -1:
visited[n] = count
count += 1
for element in graph[n]:
queue.append([element, count])
return visited
def solution(n, edge):
answer = 0
graph = {} #dict
for value in edge:
if value[0] not in graph:
graph[value[0]] = [value[1]]
else:
graph[value[0]].append(value[1])
if value[1] not in graph:
graph[value[1]] = [value[0]]
else:
graph[value[1]].append(value[0])
print(bfs(graph, 1, n))
return answer
def main():
n = 6
vertex = [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]
solution(n, vertex)
if __name__ == "__main__":
main() |
# normal output
msg = "Hello"
print(msg)
print(1, 2, 3, "fu", "*")
print(" " + "fu" + " ")
# dynamic input
name = input("Hi , what is you name")
print(" Heyy, ", name)
# escape chars
# line break
print(" 1, \n", 2)
# or """ indentation
print("""
1
2
3
""")
print("""
1 \
2 \
""")
# tabs 8 chars
print("Tab", "\n3\t4")
# escape characters
print("the pet shop owner said \"No,no 'e's uh,.... he's resting\" ")
print('the pet shop owner said "No,no \'e\'s uh,.... he\'s resting" ')
# or
print("""the pet shop owner said "No,no 'e's uh,.... he's resting" """)
# Print backslash
print("""C:\\tim\\notes""")
print("""C:\\bim\\motes""")
# or Raw strings
print(r"C:\tim\notes")
|
from abc import ABC, abstractclassmethod
# Method Overloading
# Method Overriding
# Duck Typing
# Operator Overloading
# Duck Typing
class PyCharm:
@staticmethod
def execute():
print("PyCharm")
print("Compile")
class VsCode:
@staticmethod
def execute():
print("VsCode")
print("Format")
print("Compile")
class Laptop:
def code(self, ide):
ide.execute()
py = PyCharm()
vs = VsCode()
lapy = Laptop()
lapy.code(py)
lapy.code(vs)
# 5 + "satvik"
# doesn't work
# Operator Overloading
# '+' operator's definition is __add__ (method) in python
class Students:
def __init__(self, marks1):
self.marks1 = marks1
def __add__(self, other):
return self.marks1 + other.marks1
s1 = Students(40)
s2 = Students(50)
sum = s1 + s2
print("sum ", sum)
a = 9
b = s1
print("9 number is ", a.__str__(), " similarly, s1 obj is ", b.__str__())
print()
# Method Overloading
# Method Overriding
class A:
def show(self):
print("Hi in A")
class B(A):
# pass
# pass then A
# else B
def show(self):
print("Hi in B")
b = B()
b.show()
# Absctract class
# can't instantiate
# as no defined methods
class Computer:
@abstractclassmethod
def process(self):
raise NotImplementedError
# If inherited we need to define
# NotImplemented even if one un-implemented
# enforcing inherited classes to implement those methods
class Laptop(Computer):
def process(self):
print("Yo man")
lapy = Laptop()
lapy.process()
|
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occured.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
# Catching Specific Exceptions in Python
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
pass
except:
# handle all other exceptions
pass
raise MemoryError("This is an argument")
try:
f = open("albums.txt", encoding='utf-8')
# perform file operations
finally:
f.close()
|
cur_max, last1, last2, last3, last4, last5 = 0, 0, 0, 0, 0, 0
x = int(input())
while x != 0:
cur_max = max(cur_max, last1)
last1, last2, last3, last4, last5 = last2, last3, last4, last5, x
x = int(input())
print(cur_max)
|
"""Draws a spring consisting of n arches of sizes x"""
import turtle
import math
def fn_draw_arch(radius=50, smooth_factor=30):
"""Will draw a square of size n"""
rotation_angle = 180 / smooth_factor
move_distance = radius * math.pi / smooth_factor
for _i in range(smooth_factor):
turtle.forward(move_distance)
turtle.right(rotation_angle)
def fn_draw_spring(number_of_arches=10, spring_size=50):
turtle.penup()
turtle.goto(-300, 0)
turtle.pendown()
big_arch = spring_size
small_arch = spring_size // 5
turtle.left(90)
for _i in range(number_of_arches):
fn_draw_arch(big_arch)
fn_draw_arch(small_arch)
turtle.shape("turtle")
turtle.speed(9)
fn_draw_spring()
turtle.done()
|
num1 = int(input())
num2 = int(input())
def highest_common_divisor(a, b):
if a < b:
a, b = b, a
if b == 0:
return a
else:
return highest_common_divisor(a % b, b)
print(highest_common_divisor(num1, num2))
|
import turtle
import time
import math
# Initialize turtle and bring it to start position
turtle.shape("turtle")
turtle.color("green")
turtle.penup()
turtle.goto(-150, -150)
turtle.pendown()
turtle.speed("fast")
# End of initialize
def draw_dragon_curve(length=300.00, depth=1):
if depth == 1:
step = length / 2 / math.cos(45 * math.pi / 180)
turtle.right(45)
turtle.forward(step)
turtle.left(90)
turtle.forward(step)
return
else:
step = length / 2 / math.cos(45 * math.pi / 180)
turtle.right(45)
draw_dragon_curve(step, depth - 1)
turtle.left(45)
draw_dragon_curve(step, depth - 1)
draw_dragon_curve(300.00, 2)
time.sleep(5)
|
N = 50
arr = [True] * N
for k in range(2, N):
if arr[k]:
for m in range(k+k, N, k):
print(f"m is now {m}")
arr[m] = False
for i in range(N):
print(i, "-", "simple" if arr[i] else "complex")
|
def display_result(result):
initial_sorting_based_on_score =sorted(result,key=lambda x:x['score'])
# check if we need to active the kickers
add_kickers_to_result=check_to_Show_kickers(initial_sorting_based_on_score)
# sorting result
sorted_result=sorting_result(add_kickers_to_result)
# display
display(sorted_result)
def sorting_result(results):
""" Based on scores, creatign a dictioanry where key is score and then sorting by key"""
result_dict={}
for result in results:
result_dict[result['score']]= result_dict.get(result['score'], [])+[result ]
sorted_result=[]
for i in sorted (result_dict.keys(),reverse=True):
sorted_result.append(result_dict[i])
return sorted_result
def display(sorted_result):
""" Display result to console"""
for i in range(len(sorted_result)):
final_name=""
hand_value= sorted_result[i][0]['hand_value']
for player in sorted_result[i]:
name=player['name']
final_name+=name+" "
kickers=None
kickers = check_kickers(sorted_result[i])
if kickers:
print(f'{i+1} {final_name} {hand_value}, Kickers {kickers}')
else:
print(f'{i+1} {final_name} {hand_value}')
def check_to_Show_kickers(result):
""" Add a new property (active_kickers) to player by evaluating the score and hand value"""
for player_one,player_two in zip(result,result[1:]):
if player_one['score'] != player_two['score'] and player_one['hand_value'] == player_two['hand_value']:
player_one['active_kickers']=True
player_two['active_kickers']=True
return result
def check_kickers(cards):
""" Return Kickers if the kicker is active"""
for card in cards:
if "active_kickers" in card and 'kickers' in card:
return card['kickers']
return False
|
"""
Check if two strings begins with the same letter and print True
or you print out some words
Make your code generic by using the input function
Note: uppercases != lowercases
M != m
Goodluck!
e.g
Crocodile == Crab
Spider == Snake
Bee != Cat
""" |
import math
a, b, c = float(input()), float(input()), float(input())
d = b**2 - 4*a*c
if d < 0:
print("Нет решений!")
elif a == 0 and b == 0 and c == 0:
print("Деление на 0")
elif d == 0:
print(-b/(2*a))
else:
print(((-b + math.sqrt(d))/(2*a)), " ", ((-b - math.sqrt(d))/(2*a))) |
from mapcreator import parse_and_create_map
from pathfinding import path_between_points, _path_between_points
from hashiterator import find_zero_collision_from_salt
def all_together(start_x, start_y, end_x, end_y, coordinates_directory, number_of_zeros, temp_filepath='temporary'):
""" Takes the files in the coordinates directory and creates a map. Then
given start and end coordinates it outputs the shortest path from the start
to end points on the map. This map is then saved to a file location.
The function will then take the string of the path taken,
find the hash collisions with the number of zeros input and
return the hash result.
Args:
start_x (int): The x coordinate of the start position.
start_y (int): The y coordinate of the start position.
end_x (int): The x coordinate of the end position.
end_y (int): The y coordinate of the end position.
coordinates_directory (string): Directory containing the files to parse.
number_of_zeros (int): The number of zeros to be searching for at the start of the hash.
Returns:
The collisions string the function has built.
"""
the_map = parse_and_create_map(coordinates_directory)
with open(temp_filepath, mode='w') as fp:
fp.write(the_map)
path = \
_path_between_points(start_x=start_x, start_y=start_y, end_x=end_x, end_y=end_y,
map_file_location=temp_filepath)[1]
# path_str = "".join(['x{}y{}'.format(elem[0], elem[1]) for elem in path])
# TODO not sure if the hash function should take the above input or the below, sorry confused from description in pdf file
path_str = "".join(['{:02d}{:02d}'.format(elem[0], elem[1]) for elem in path])
collision_output = find_zero_collision_from_salt(salt=path_str, number_of_zeros=number_of_zeros)
import os
os.remove(temp_filepath)
return collision_output
if __name__ == '__main__':
print all_together(start_x=7, start_y=1, end_x=17, end_y=27, coordinates_directory='CoordinateSystem',
number_of_zeros=2)
|
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# Os filhos de uma tag estão disponíveis em uma lista chamada .contents:
titel_tag = soup.title
head_tag = soup.head
# Se uma tag tiver apenas um filho e esse filho for um NavigableString, o filho será disponibilizado como .string:
print(titel_tag.string)
# Se o único filho de uma tag for outra tag, e essa tag tiver um .string, a tag pai será considerada igual a
# .stringsua filha:
print(head_tag.contents)
# [<title>The Dormouse's story</title>]
print(head_tag.string)
# 'The Dormouse's story'
# Se uma tag contém mais de uma coisa, não está claro a que .stringse refere, então .stringé definido como None:
print(soup.html.string) |
"""
Prometheus: Text-Based Game
A person stuck on an island who has to complete tasks in order to get off of it.
"""
import random
import json #https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
from os import path #https://www.guru99.com/python-check-if-file-exists.html
heroXp = 50
wolfXp = -30
fireXp = -25
treasureXp = 20
collectedTreasures = 0
level = 1
kills = 0
runLimit = 0
wolves = []
fires = []
treasures = []
loadedGame = False
heroName = ''
maxMapSize = 3
heroLocation = [maxMapSize//2, maxMapSize//2]
moveCount = 0
#Functions
def placeWolves(heroLocation, number):
"""
Randomly places wolves on the map, where the hero is not located
"""
wolvesLocations = []
wolfLocation = [random.randrange(0, maxMapSize), random.randrange(0, maxMapSize)]
count = 0
#This will ensure that a wolf is not placed on a space with the hero or another wolf
while count < number:
while wolfLocation == heroLocation or wolfLocation in heroLocation or wolfLocation in wolvesLocations:
wolfLocation = [random.randrange(0, maxMapSize), random.randrange(0, maxMapSize)]
wolvesLocations.append(wolfLocation)
count += 1
return wolvesLocations
def placeFires(heroLocation, wolves, number):
"""
Randomly places fires on the map, where the hero or wolves are not located
"""
fireLocations = []
fireLocation = [random.randrange(0, maxMapSize), random.randrange(0, maxMapSize)]
count = 0
#This will ensure that a fire is not placed on a space with the hero, a wolf or a fire
while count < number:
while fireLocations == heroLocation or fireLocations in heroLocation or fireLocation in wolves or fireLocation in fireLocations:
fireLocation = [random.randrange(0, maxMapSize), random.randrange(0, maxMapSize)]
fireLocations.append(fireLocation)
count += 1
return fireLocations
def placeTreasures(heroLocation, number):
"""
Randomly places treasures on the map, where the hero is not located
"""
treasureLocations = []
treasureLocation = [random.randrange(0, maxMapSize), random.randrange(0, maxMapSize)]
count = 0
#This will ensure that a treasure is not placed on a space with the hero or treasure
while count < number:
while treasureLocation == heroLocation or treasureLocation in treasureLocations:
treasureLocation = [random.randrange(0, maxMapSize), random.randrange(0, maxMapSize)]
treasureLocations.append(treasureLocation)
count += 1
return treasureLocations
def printHeroData():
"""
Prints hero's data
"""
global heroXp, heroLocation, collectedTreasures, level, kills, heroName
print(heroName)
print('XP:', heroXp)
print(f'Location: {heroLocation[0]}, {heroLocation[1]}')
print(f'Treasures: {collectedTreasures}')
print(f'Kills: {kills}')
if (level >= 3) : print(f'Runs Left: {3 - runLimit}')
print(f'Current Level: {level}')
#Move on to the next level after fires and wolves have been fought
if (len(wolves) == 0 and len(fires) == 0):
nextLevel()
else:
validateInput('\n1. UP \n2. DOWN \n3. LEFT \n4. RIGHT \n5. SAVE \n6. LOAD \n99. EXIT \n')
def moveHero(move):
"""
Moves hero around the map
"""
global heroLocation, moveCount
#Determine the input to determine the next move
if (move == 1):
moveUp = heroLocation[1] - 1
if (moveUp < 0):
validateInput('Sorry not valid move! Please try 2, 3 or 4: ')
else:
newPosition =[heroLocation[0], moveUp]
danger = checkForDanger(newPosition)
if (not danger[0] or danger[1]):
heroLocation[1] = moveUp
collectTreasure()
elif (move == 2):
moveDown = heroLocation[1] + 1
if (moveDown >= maxMapSize):
validateInput('Sorry not valid move! Please try 1, 3 or 4: ')
else:
newPosition =[heroLocation[0], moveDown]
danger = checkForDanger(newPosition)
if (not danger[0] or danger[1]):
heroLocation[1] = moveDown
collectTreasure()
elif (move == 3):
moveLeft = heroLocation[0] - 1
if (moveLeft < 0):
validateInput('Sorry not valid move! Please try 1, 2 or 4: ')
else:
newPosition = [moveLeft, heroLocation[1]]
danger = checkForDanger(newPosition)
if (not danger[0] or danger[1]):
heroLocation[0] = moveLeft
collectTreasure()
elif (move == 4):
moveRight = heroLocation[0] + 1
if (moveRight >= maxMapSize):
validateInput('Sorry not valid move! Please try 1, 2 or 4: ')
else:
newPosition = [moveRight, heroLocation[1]]
danger = checkForDanger(newPosition)
if (not danger[0] or danger[1]):
heroLocation[0] = moveRight
collectTreasure()
elif (move == 5):
saveGame(False)
elif (move == 6):
loadGame()
elif (move == 99):
if (moveCount > 0):
try:
save = int(input('Do you want to save the game? (This will overwrite any exisiting saved game) \n1. YES \n2. NO \n'))
if (save == 1):
saveGame(True)
else:
exit()
except SystemExit:
exit()
except SystemError:
print('Game not saved! Please enter a valid number \n')
else:
exit()
else:
validateInput('Sorry not valid move! Please try 1, 2, 3 or 4: ')
if (move in range(1, 5)) : moveCount += 1
printHeroData()
def collectTreasure():
"""
The hero collects the treasure
"""
global heroXp, heroLocation, collectedTreasures
if heroLocation in treasures:
heroXp += treasureXp
collectedTreasures += 1
treasures.remove(heroLocation)
print(f'You found treasure and gained {treasureXp} XP!')
def checkForDanger(newPosition):
"""
The hero checks for danger
"""
global wolfXp, fireXp, wolves, fires
if newPosition in wolves:
print("DANGER! WOLF! \n")
encountered = encounterDanger(wolfXp, newPosition)
return [True, encountered]
elif newPosition in fires:
print("DANGER! FIRE! \n")
encountered = encounterDanger(fireXp, newPosition)
return [True, encountered]
return [False, False]
def encounterDanger(dangerXp, location):
"""
The hero encouters danger
"""
global heroXp, wolves, fires, runLimit, heroLocation, kills, wolfXp, fireXp
takenLocations = []
takenLocations.append(location)
takenLocations.append(heroLocation)
if (runLimit >= 3):
print("You cannot run anymore! You have to fight!")
encounter = 2
else:
encounter = int(input("Do you want to run or fight? \n1. RUN \n2. FIGHT \n"))
if (encounter == 1):
if (dangerXp == wolfXp):
runLimit += 1
if (level >= 3):
for wolf in wolves:
takenLocations.append(wolf)
placeWolves(takenLocations, 1)
wolves.remove(location)
return False
heroXp += dangerXp
if (heroXp <= 0):
print('Game Over! New game starting!')
startGame()
else:
print(f'Danger defeated! {-1 * dangerXp} XP lost!')
kills += 1
if (dangerXp == wolfXp):
if location in wolves:
wolves.remove(location)
elif (dangerXp == fireXp):
if location in fires:
fires.remove(location)
return True
def startGame():
"""
Resets the game variable for new game
"""
global heroXp, wolves, fires, treasures, maxMapSize, heroLocation, collectedTreasures, level, runLimit, kills, moveCount, heroName
heroName = input('What is your hero\'s name?: ')
heroXp = 50
collectedTreasures = 0
level = 1
runLimit = 0
kills = 0
moveCount = 0
wolves = placeWolves(heroLocation, 1)
fires = placeFires(heroLocation, wolves, 1)
treasures = placeTreasures(heroLocation, 2)
maxMapSize = 3
heroLocation = [maxMapSize//2, maxMapSize//2]
makeMove('')
def nextLevel():
"""
Advances hero to next level
"""
global level, wolves, fires, treasures, heroLocation, runLimit, treasures, maxMapSize
level += 1
runLimit = 0
number = 2 * level
wolves = placeWolves(heroLocation, number)
fires = placeFires(heroLocation, wolves, number)
treasures = placeTreasures(heroLocation, number)
maxMapSize = number + 1
heroLocation = [maxMapSize//2, maxMapSize//2]
if (level >= 5):
print(f'Well done, {heroName}! You have won with:')
print(f'XP: {heroXp}')
print(f'Kills: {kills}')
print(f'Treasures: {collectedTreasures}')
deleteSavedGame()
initialiseGame()
else:
print(f'Well done, {heroName}! You have completed level {level - 1}. You are now on level {level}.')
print('Level Summary:')
print(f'XP: {heroXp}')
print(f'Kills: {kills}')
print(f'Treasures: {collectedTreasures}')
print(f'Location: {heroLocation}')
makeMove('')
def loadGame():
"""
Load saved game
"""
global heroXp, wolfXp, fireXp, treasureXp, collectedTreasures, level, runLimit, wolves, fires, treasures, maxMapSize, heroLocation, kills, loadedGame, moveCount, heroName
if (not path.exists('saved_game.json')):
makeMove('No saved game data')
with open('saved_game.json', 'r') as savedGame:
gameData = json.load(savedGame)
if (len(gameData) == 0):
makeMove('No saved game data')
heroName = gameData['heroName']
heroXp = gameData['heroXp']
wolfXp = gameData['wolfXp']
fireXp = gameData['fireXp']
treasureXp = gameData['treasureXp']
collectedTreasures = gameData['collectedTreasures']
level = gameData['level']
runLimit = gameData['runLimit']
wolves = gameData['wolves']
fires = gameData['fires']
treasures = gameData['treasures']
maxMapSize = gameData['maxMapSize']
heroLocation = gameData['heroLocation']
kills = gameData['kills']
moveCount = gameData['moveCount']
loadedGame = True
savedGame.close()
makeMove('Saved Game loaded!')
def saveGame(exitGame):
"""
Save game
"""
global heroXp, wolfXp, fireXp, treasureXp, collectedTreasures, level, runLimit, wolves, fires, treasures, maxMapSize, heroLocation, kills, moveCount, heroName
gameData = {
'heroName': heroName,
'heroXp': heroXp,
'wolfXp': wolfXp,
'fireXp': fireXp,
'treasureXp': treasureXp,
'collectedTreasures': collectedTreasures,
'level': level,
'runLimit': runLimit,
'wolves': wolves,
'fires': fires,
'treasures': treasures,
'maxMapSize': maxMapSize,
'heroLocation': heroLocation,
'kills': kills,
'moveCount': moveCount
}
with open('saved_game.json', 'w') as savedGame:
json.dump(gameData, savedGame)
savedGame.close()
message = 'Game saved!'
if (exitGame):
print(message)
exit(0)
else:
makeMove(message)
def deleteSavedGame():
"""
Delete saved game data
"""
global loadedGame
if (loadedGame):
gameData = ''
with open('saved_game.json', 'w') as savedGame:
json.dump(gameData, savedGame)
loadedGame = False
savedGame.close()
def makeMove(message):
print(message)
move = int(input('\nMake your move!\n\n1. UP \n2. DOWN \n3. LEFT \n4. RIGHT \n5. SAVE \n6. LOAD \n99. EXIT \n'))
moveHero(move)
def validateInput(message):
try:
moveHero(int(input(message)))
except SystemExit:
exit()
except:
print('Please enter a valid number \n')
moveHero(int(input(message)))
def initialiseGame():
"""
Prompt a user to either start a new game or load an existing one
"""
print('“Prometheus”, a person stuck on an island who has to complete tasks in order to get off of it. \n')
try:
startAGame = int(input('Start a new game or load a saved game? \n1. NEW \n2. LOAD \n99. EXIT \n'))
if (startAGame == 1):
startGame()
elif (startAGame == 2):
loadGame()
elif (startAGame == 99):
exit()
else:
print('Please enter 1, 2 or 99')
initialiseGame()
except SystemExit:
exit()
except:
print('Please enter a valid number \n')
initialiseGame()
#Start Game
initialiseGame() |
from random import choice
def rps_game():
scores = [0,0]
choices = ["Rock", "Paper", "Scissors"]
while max(scores) < 3:
while True:
user_choice = input("1. Rock\n2. Paper\n3. Scissors\n\nPlease enter your weapon: ")
if user_choice in ["1", "2", "3"]:
break
else:
print("invalid choice")
user_choice = choices[int(user_choice)-1]
computer_choice = choice(choices)
if user_choice == computer_choice:
print("tie - no one wins")
elif user_choice == "Rock" and computer_choice == "Paper":
print(f"{computer_choice} beats {user_choice} - computer wins")
scores[1] += 1
elif user_choice == "Rock" and computer_choice == "Scissors":
print(f"{user_choice} beats {computer_choice} - user wins")
scores[0] += 1
elif user_choice == "Paper" and computer_choice == "Scissors":
print(f"{computer_choice} beats {user_choice} - computer wins")
scores[1] += 1
elif user_choice == "Paper" and computer_choice == "Rock":
print(f"{user_choice} beats {computer_choice} - user wins")
scores[0] += 1
elif user_choice == "Scissors" and computer_choice == "Rock":
print(f"{computer_choice} beats {user_choice} - computer wins")
scores[1] += 1
elif user_choice == "Scissors" and computer_choice == "Paper":
print(f"{user_choice} beats {computer_choice} - user wins")
scores[0] += 1
print(f"User won {scores[0]} time(s) and computer won {scores[1]} time(s)")
if scores[0] > scores[1]:
print("User has won the game!")
else:
print("Computer has won the game!")
#choices = {"Rock":("Scissors", "Paper"), "Paper": ("Rock", "Scissors"), "Scissors": ("Paper", "Rock")}
def rps_game2():
scores = [0,0]
choices = {"Rock": "Scissors", "Paper": "Rock", "Scissors": "Paper"}
while max(scores) < 3:
while True:
user_choice = input("1. Rock\n2. Paper\n3. Scissors\n\nPlease enter your weapon: ")
if user_choice in ["1", "2", "3"]:
break
else:
print("invalid choice")
user_choice = list(choices.keys())[int(user_choice)-1]
computer_choice = choice(list(choices.keys()))
if user_choice == computer_choice:
print("tie - no one wins")
elif choices[user_choice] == computer_choice:
print(f"{user_choice} beats {computer_choice} - user wins")
scores[0] += 1
else:
print(f"{computer_choice} beats {user_choice} - computer wins")
scores[1] += 1
print(f"User won {scores[0]} time(s) and computer won {scores[1]} time(s)")
if scores[0] > scores[1]:
print("User has won the game!")
else:
print("Computer has won the game!")
rps_game2()
|
def display_board(board):
print(board[1]+'|'+board[2]+'|'+board[3])
print(board[4]+'|'+board[5]+'|'+board[6])
print(board[7]+'|'+board[8]+'|'+board[9])
def player_input():
choice = ''
while choice != 'X' or choice != 'O':
try:
choice = input("player 1:Please pick a marker 'X' or 'O' ").upper()
if choice == 'X':
return ('X','O')
else:
return ('O','X')
except:
print('invalid option')
def space_check(board, position):
return board[position] == ' '
def place_marker(board, marker, position):
try:
board[position] = marker
except:
print('error')
def win_check(board, mark):
#horizontal
if board[1] == board[2] == board[3] == mark:
return True
elif board[4] == board[5] == board[6] == mark:
return True
elif board[7] == board[8] == board[9] == mark:
return True
#diagonal
elif board[1] == board[5] == board[9] == mark:
return True
elif board[3] == board[5] == board[7] == mark:
return True
#vertical
elif board[1] == board[4] == board[7] == mark:
return True
elif board[2] == board[5] == board[8] == mark:
return True
elif board[3] == board[6] == board[9] == mark:
return True
else:
return False
import random
def choose_first():
if random.randint(0, 1) == 0:
return 'Player 2'
else:
return 'Player 1'
def full_board_check(board):
for i in range(1, 10):
if board[i] not in ['X','O']:
return False
return True
#asks for a player's next position (as a number 1-9)
#uses the function from step 6 to check if it's a free position.
# If it is, then return the position for later use.
def player_choice(board):
position = 0
while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):
try:
position = int(input('Choose your next position: (1-9) '))
except:
print('non digit')
return position
#asks the player if they want to play again and returns a boolean
def replay():
ask = ''
while ask not in ['yes', 'no']:
ask = (input("Play again? ('yes' or 'no') "))
if ask == 'yes' or ask == "Yes":
return True
elif ask == 'no' or ask == 'No':
return False
else:
pass
def reset_board():
global test_board,game
test_board =[' '] * 10
game = True
#runs game together
print('Welcome to Tic Tac Toe!')
game = True
test_board =[' '] * 10
player1_marker, player2_marker = player_input()
turn = choose_first()
print(turn + ' will go first.')
while game:
if turn == 'Player 1':
display_board(test_board)
position = player_choice(test_board)
place_marker(test_board, player1_marker, position)
if full_board_check(test_board):
display_board(test_board)
print('The game is a draw!')
if replay() == False:
game = False
else:
reset_board()
if win_check(test_board,player1_marker):
display_board(test_board)
print('Player 1 is the winner!')
if replay() == False:
game = False
else:
reset_board()
else:
turn = 'Player 2'
if turn == 'Player 2':
display_board(test_board)
position = player_choice(test_board)
place_marker(test_board, player2_marker, position)
if full_board_check(test_board):
display_board(test_board)
print('The game is a draw!')
if replay() == False:
game = False
else:
reset_board()
if win_check(test_board,player2_marker):
display_board(test_board)
print('Player 2 is the winner!')
if replay() == False:
game = False
else:
reset_board()
else:
turn = 'Player 1'
|
class Node(object):
def __init__(self, key):
self.key = key
self.next = None
self.prev = None
def __repr__(self):
return "[{prev} <- [{key}] -> {next}".format(key=self.key,
next=self.next.key if self.next else None,
prev=self.prev.key if self.prev else None)
class LinkedList(object):
def __init__(self, node = None):
self.head = node
self.tail = node
def append(self, node):
node.next = None
if self.head:
node.prev = self.tail
self.tail.next = node
self.tail = node
else:
self.head = self.tail = node
def pop(self):
if not self.head:
raise IndexError("Head is None!")
oldHead = self.head
self.head = oldHead.next
if self.head:
self.head.prev = None
else:
# if we ended up removing the only node in the list!
self.tail = None
oldHead.next = None
return oldHead
def remove(self, node):
if not self.head:
raise IndexError("Head is None!")
# also works if the only node is being removed
# It'll set both head and tail to empty
if node.prev:
node.prev.next = node.next
else:
# we're removing head! It's the same as pop
self.head = self.head.next
if self.head:
self.head.prev = None
if node.next:
node.next.prev = node.prev
else:
# we're removing tail!
self.tail = self.tail.prev
if self.tail:
self.tail.next = None
def __repr__(self):
keys = []
node = self.head
while node:
keys.append(str(node.key))
node = node.next
reversed_keys = []
node = self.tail
while node:
reversed_keys.append(str(node.key))
node = node.prev
return "{fwd}\n{back}\n{match}".format(fwd=' -> '.join(keys),
back=' -> '.join(reversed_keys),
match=list(reversed(keys)) == reversed_keys)
class LRU:
def __init__(self):
self.dict = {}
self.linkedList = LinkedList()
def accessed(self, key):
node = self.dict.get(key)
if node:
self.linkedList.remove(node)
else:
node = Node(key)
self.dict[key] = node
self.linkedList.append(node)
def expireOldest(self):
node = self.linkedList.pop()
if node.key in self.dict:
del self.dict[node.key]
return node.key
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self._capacity = capacity
self.main = {}
self.lru = LRU()
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.main:
self.lru.accessed(key)
return self.main[key]
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if key in self.main:
self.main[key] = value
else:
if len(self.main) < self._capacity:
self.main[key] = value
else:
# make room
poppedKey = self.lru.expireOldest()
del self.main[poppedKey]
# add new entry
self.main[key] = value
self.lru.accessed(key)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value) |
class Solution(object):
def isPalindrome(self, n):
nStr = str(n)
for i in range(int(len(nStr) / 2)):
if nStr[i] != nStr[~i]:
return False
return True
def getNextHigherPalindrome(self, a, b, current):
"""
The minute we find a palindrome (a*b) composed of two digits a and b, we now know that the only
compititor to it, i.e. larger in value than a*b must be a number such that it's a product of
two numbers x and y where: a < x < b AND a < y < b, if at all.
So we should start our loops to count down from one number short of a and be respectively
"""
for x in range(a - 1, b, -1):
for y in range(x, b, -1):
product = x * y
# print(f"{x} x {y} = {product}")
if self.isPalindrome(product) and product > current:
return (x, y, product)
return None
def largestPalindrome(self, n):
a = 10 ** n
b = 1
current = 1
while True:
better = self.getNextHigherPalindrome(a, b, current)
if not better:
break
else:
(a, b, current) = better
return current % 1337 |
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stk = []
opening = "([{"
closing = ")]}"
close2open = {
")" : "(",
"}" : "{",
"]" : "[",
}
for c in s:
if c in opening:
stk.append(c)
elif c in closing:
if stk:
if close2open[c] == stk.pop():
pass # this one was matched
else:
return False
else:
return False
else:
pass # this is neither open nor close bracket so we ignore it
return True |
r"""
DNA strings must be labeled when they are consolidated into a database.
A commonly used method of string labeling is called FASTA format. In this
format, the string is introduced by a line that begins with ">", followed
by some information naming and characterizing the string. Subsequent lines
contain the string itself; the next line starting with ">" indicates the
label of the next string.
In Rosalind's implementation, a string in FASTA format will be labeled by
the ID "Rosalind_xxxx", where "xxxx" denotes a four-digit code between
0000 and 9999.
Given: At most 10 DNA strings in FASTA format (of length at most 1 kbp
each).
Return: The ID of the string having the highest GC-content, followed by
the GC-content of that string. The GC-content should have an accuracy of
4 decimal places (see the note below on decimal accuracy).
"""
import sys
from collections import Counter
from StringIO import StringIO
import operator
def gc_content(dna_string):
c = Counter(dna_string)
return float((c["G"] + c["C"])) / float(len(dna_string))
sample_dataset = """\
>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT"""
if len(sys.argv) > 1:
data = open(sys.argv[1], 'r')
else:
data = StringIO(sample_dataset)
strings = dict()
key = ""
for line in data:
line = line.rstrip()
if line[0] == ">":
if key:
strings[key] = gc_content(dna_string)
key = line[1:]
dna_string = ""
else:
dna_string += line
strings[key] = gc_content(dna_string)
name, content = sorted(strings.iteritems(), key=operator.itemgetter(1), reverse=True)[0]
print "{0}\n{1:.6f}%".format(name, content * 100)
|
def grph(fasta):
r"""
Given: A collection of DNA strings in FASTA format having total length
at most 10 kbp.
Return: The adjacency list corresponding to O3.
"""
from itertools import product
overlap = lambda ((n1, s1),(n2, s2)): n1 != n2 and s1[-3:] == s2[0:3]
stringify = lambda ((n1, s1),(n2, s2)): " ".join([n1, n2])
return "\n".join(\
map(stringify, \
filter(overlap, \
product(fasta.iteritems(), repeat=2))))
def parse_fasta(text):
from StringIO import StringIO
data = StringIO(text)
strings = dict()
for line in data:
line = line.rstrip()
if line[0] == ">":
key = line[1:]
strings[key] = ""
else:
strings[key] += line
return strings
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as data_file:
print grph(parse_fasta(data_file.read())) |
""" Programa que resolve questões de provas"""
pontos = 0
questao = 1
while questao <= 3:
resposta = input(f'Resposta da questão {questao}: ').upper()
if questao == 1 and resposta == 'b' or resposta == 'B':
pontos = pontos + 1
if questao == 2 and resposta == 'c' or resposta == 'C':
pontos = pontos + 1
if questao == 3 and resposta == 'd' or resposta == 'D':
pontos = pontos + 1
questao = questao + 1
print(f'O aluno fez {pontos} ponto(s)')
|
# Programa 2.2 - Calculo de aumento de salário
# Composição de strings utilizando o f'string
sal = 750
aum = 15
por = sal + (sal * aum / 100)
print(f'O salário base de R${sal} com o aumento de {aum}% foi de: R${por}')
# Forma de Composição usando o .format
nome = 'Joao'
idade = 22
grana = 51.34
print('{} tem {} anos e R${} no bolso'.format(nome, idade, grana))
# Forma de Composição usanfo o fstring
nome = 'Joao'
idade = 22
grana = 51.34
print(f'{nome} tem {idade} anos e R${grana} no bolso')
|
a = []
a.append(2)
a.append(10)
a.append(14)
for item in a:
print(item)
b = a.pop()
print(b)
a.append(15)
l = len(a)
print(l)
|
import sqlite3
conn = sqlite3.connect('data/exploitable_db.sqlite')
c = conn.cursor()
def connect(username, password):
query = f"""
SELECT *
FROM users
WHERE users.username = '{username}'
AND users.password = '{password}'
"""
c.execute(query)
user = c.fetchone()
if user is None:
return "Unauthorized"
else:
return "Authorized"
def connect_safe(username, password):
query = f"""
SELECT *
FROM users
WHERE users.username = :username
AND users.password = :password
"""
# c.execute(query, (username, password))
c.execute(query, { 'username': username, 'password': password })
user = c.fetchone()
if user is None:
return "Unauthorized"
else:
return "Authorized"
username = "john"
password = "' OR 1=1 --passw0dierd"
print(connect(username, password))
print(connect_safe(username, password))
|
"""
alphacode.py: CIS 210 assignment 1, Fall 2013
Authors: FIXME: Anthony Plueard
Credits: FIXME: list sources and collaborators. If none, delete this line.
Convert PIN code to mnemonic alphabetic code
"""
import argparse # Used in main PROGRAM to get PIN code from command line
# # Constants used by this program
CONSONANTS = "bcdfghjklmnpqrstvwyz"
VOWELS = "aeiou"
def alphacode(pin):
"""
Convert numeric pin code to an
easily pronounced mnemonic.
args:
pin: code as positive integer
returns:
mnemonic as string
"""
mnemonic = ""
while pin > 0:
pin2 = pin % 100
pin = pin // 100
x = pin2 // 5
y = pin2 % 5
z = ##TODO Assign x to the CONSTANTS ARRAY##
w = ## TODO Assign y to the VOWELS ARRAY##
mnemonic = z + w + mnemonic
return mnemonic
def run_tests():
"""
This function runs a set of tests to help you debug your
program as you develop it.
"""
## (Cell marker for running tests in IEP) ##
print("**** TESTING --- examples from course assignment page")
print("4327 => 'lohi'?", alphacode(4327))
print("1298 => 'dizo'?", alphacode(1298))
print("***** Longer PIN CODES ****")
print("1234567 => begomari?", alphacode(1234567))
print("42424242 => lililili ?", alphacode(4242424242))
print("98765 => cuwira?", alphacode(98765))
print("987654 => zotenu?", alphacode(987654))
print("(same digit pairs, reverse order) 547698 => nutezo ?", alphacode(547698))
print("**** Edge cases (robustness testing) ****")
print("0 => empty mnemonic ?", alphacode(0))
print("-42 and all negative numbers => empty mnemonic? ", alphacode(-42))
## (Marks end of cell in IEP)
def main():
"""
Interaction if run from the command line.
Magic for now; we'll look at what's going on here
in the next week or two.
"""
parser = argparse.ArgumentParser(description="Create mnemonic for PIN code")
parser.add_argument("PIN", type=int,
help="personal identifier number (an integer)")
args = parser.parse_args() # gets arguments from command line
pin = args.PIN
mnemonic = alphacode(pin)
print("Encoding of " + str(pin) + " is:", mnemonic)
if __name__ == "__main__":
#run_tests() #FIXME: Comment this out when your program is working
#main() #FIXME: Uncomment this when your program is working
|
#!/usr/bin/env python3
# -*- coding: Utf-8 -*
# import all the required libraries
""" Function to create items in the macgyver-game"""
from classes import Items
def prep_items(structure):
"""
The function is use for creation of items objects in the game .
Parameters:
structure (list): list generated from the Maze class.
Returns:
items (objects): return three item objects
"""
# Creates a new instance of the class(Items) and assigns this object to a variable item_1
item_1 = Items(structure)
# Calling method items_positions()
item_1.items_position()
# Creates a new instance of the class(Items) and assigns this object to a variable item_2
item_2 = Items(structure)
# Calling method items_positions()
item_2.items_position()
# Creates a new instance of the class(Items) and assigns this object to a variable item_3
item_3 = Items(structure)
# Calling method items_positions()
item_3.items_position()
while item_1.case_y == item_2.case_y and item_1.case_x == item_2.case_x:
item_2.items_position()
while (item_1.case_y == item_3.case_y and item_1.case_x == item_3.case_x) or (
item_2.case_y == item_3.case_y and item_2.case_x == item_3.case_x):
item_3.items_position()
# Return three items class objects
return item_1, item_2, item_3
|
class SuccessorWithDelete(object):
def __init__(self,N):
self._N = N
self._suc = [i+1 for i in range(N)]
self._suc[N-1] = N-1
self._pred = [i-1 for i in range(N)]
self._pred[0] = 0
def remove(self,x):
px = self._pred[x]
sx = self._suc[x]
if sx == x:
self._suc[px] = px
elif px == x:
self._pred[sx] = sx
else:
self._suc[px] = sx
self._pred[sx] = px
self._pred[x] = None
self._suc[x] = None
def successor(self,x):
return self._suc[x]
def predecessor(self,x):
return self._pred[x]
if __name__ == '__main__':
k = SuccessorWithDelete(4)
k.remove(1)
print k.successor(2), k.predecessor(2)
print k.successor(0), k.predecessor(0)
k.remove(0)
print k.successor(1), k.predecessor(1)
print k.successor(2), k.predecessor(2)
# Sample Output
# 3 0
# 2 0
# None None
# 3 2 |
class IndexMinPQ(object):
def __init__(self,N):
self._N = N
self._n = 0
self._keys = [None] * (self._N+1)
self._pq = [None] * (self._N+1)
self._qp = [None] * (self._N+1)
def show(self):
print "Keys:",self._keys
print "pq:",self._pq
print "qp:",self._qp
def findKey(self,index,key):
return self._keys[index]
def changeKey(self,index,key):
self._keys[index] = key
self._swim(self._qp[index])
self._sink(self._qp[index])
def decreaseKey(self,index,key):
# print "Index:",index,"Key:",key
# print "Keys:",self._keys
# print "QP:",self._qp
# print "PQ:",self._pq
self._keys[index] = key
self._swim(self._qp[index])
def delMin(self):
Min = self._pq[1]
self._exch(1,self._n)
self._n -= 1
self._sink(1)
self._pq[self._n+1] = None
self._qp[Min] = None
self._keys[Min] = None
return Min
def insert(self,i,key):
self._n += 1
self._keys[i] = key
self._qp[i] = self._n
self._pq[self._n] = i
self._swim(self._n)
def isEmpty(self):
return self._n == 0
def contains(self,index):
return self._keys[index] is not None
def size(self):
return self._n
def _exch(self,i,j):
self._pq[i], self._pq[j] = self._pq[j], self._pq[i]
self._qp[self._pq[i]] = i
self._qp[self._pq[j]] = j
def _swim(self,i):
if i/2 == 0:
return
if self._keys[self._pq[i]] < self._keys[self._pq[i/2]]:
self._exch(i,i/2)
i = i/2
self._swim(i)
return
def _sink(self,i):
if 2*i > self._n:
return
j = self._lesser(2*i, 2*i+1)
if self._keys[self._pq[i]] > self._keys[self._pq[j]]:
self._exch(i,j)
self._sink(j)
return
def _lesser(self,i,j):
if i <= self._n and j <= self._n:
if self._keys[self._pq[i]] > self._keys[self._pq[j]]:
return j
return i
if i > self._n:
return j
return i
|
class InsertionSort(object):
def __init__(self,arr):
self._arr = arr
self._N = len(arr)
def sort(self):
for i in range(1,self._N):
for j in range(i,0,-1):
if self._arr[j] < self._arr[j-1]:
self._arr[j], self._arr[j-1] = \
self._arr[j-1], self._arr[j]
return self._arr
if __name__ == '__main__':
arr = [1,2,3,4,5,6,7,8,7,6,5,4,3,2,1]
k = InsertionSort(arr)
print k.sort()
# Sample Output
# [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8] |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
sum = 0
counter = 0
while l1 or l2 or carry:
sum = carry
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
digit = sum%10
carry = sum/10
if counter == 0:
l3 = ListNode(digit)
k = l3
else:
k.next = ListNode(digit)
k = k.next
counter += 1
return l3
if __name__ == '__main__':
l1 = None
for val in [3,8,1]:
next = l1
l1 = ListNode(val)
l1.next = next
l2 = None
for val in [1,7]:
next = l2
l2 = ListNode(val)
l2.next = next
k = Solution()
l = k.addTwoNumbers(l1,l2)
m = l1
# while m:
# print m.val
# m = m.next
while l:
print l.val,
l = l.next
# 8 9 9
# 5
# 9 9 8
# 0 0 5
# 1 0 0 3
# 3 0 0 1
|
# a = 21414
# b = 'eghgeojgenafljeijfjaejfalgfnjh'
# print(type(str(a)))
# list = [',7','efe','34']#sequence:序列类型
# print(3 in list)
# print(len(list))#统计列表元素个数
# print(list.count(3))#统计列表中特定元素个数
# # print(max(list))#统计列表最大值
# # print(min(list))#统计列表最小值
# print("a在字符串中的个数:"+str('fahefhaenkjafhea'.count('a')))#统计字符串中某个元素个数
# print('fhahefeagheoa'.startswith('fh'))
# print('fhahefeagheoa'.endswith('hf'))
# print(str(a).isalnum(),str(a).isdigit(),'fefge'.isalpha())
# print('fd'.join(list))#连接字符串
# print(b.split('e'))#切割
# print('_'.join(b.split('e')))
# print(b.upper(),list[1].upper())#转换成大写
# list.append('sean')#末尾添加
# print(list)
# list.insert(1,567)#中间插入
# print(list)
# del list[0]#删除
# print(list)
# c = list.pop(2)#删除,并返回删除元素的值
# print(c,list)
# list.reverse()#倒序排列不返回值
# print(list)
# fh = open(r'c:\Users\Administrator\Desktop\a.txt','a')#打开文件
# # str1 = fh.read()#读取文件全部
# # print(str1)
# # str1 = fh.readlines()
# # print('\n',str1[0])
# fh.write('\nfyt')
# fh.close()
#
a = 'fefoefoeofieieo'.replace('f','9',3)#替换
print(a) |
#!/usr/bin/python
# to send an email...
# Import smtplib for the actual sending function
import smtplib
import email
from email.mime.multipart import MIMEMultipart
# Import the email modules we'll need
from email.mime.text import MIMEText
#tmsg = MIMEMultipart('alternative')
#tmsg = MIMEMultipart()
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open('email.msg', 'rb')
# Create a text/plain message
#tmsg = MIMEText(fp.read())
#tmsg.attach( MIMEText(fp.read()) )
tmpMsg = fp.read()
fp.close()
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open('email.end', 'rb')
# Create a text/plain message
#tmsg.attach( MIMEText(fp.read()) )
tmpMsg = tmpMsg + fp.read()
fp.close()
tmsg = MIMEText(tmpMsg)
#fromaddr = 'spdroid@gmail.com'
fromaddr = 'project-N399@mic.com.com'
toaddrs = ['span.liu@mic.com.tw','aiken.chou@mic.com.tw']
#msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs)))
#msg = 'There was a terrible error that occured and I wanted you to know!'
tmsg['Subject'] = '[N399]The message FYI broadcasting...'
tmsg['From'] = fromaddr
tmsg['To'] = ','.join(toaddrs)
# Credentials (if needed)
username = 'spdroid@gmail.com'
password = 'gmail999'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
#server.sendmail(fromaddr, toaddrs, msg)
server.sendmail(fromaddr, toaddrs, tmsg.as_string())
server.quit()
"""
main
"""
|
#!/usr/bin/env python
class Player:
x=0
y=0
Inventory=[]
life=100
gold=0
armed=""
inHand=""
def addInventory(self,e):
if e.desc=="gold":
self.gold=self.gold+1
else:
self.Inventory.append(e)
print self.Inventory
|
"""
Author: Jaineel Vyas
Filename: DecisionT.py
"""
import math
class Node:
"""A decision tree node."""
def __init__(self, examples, maxcols):
'''
Initialize a node with examples(data array rows).
:param examples: data array
:param maxcols: number of columns in the data array
'''
self.left = None
self.right = None
self.cols = None # stores the selected column number (attribute selected at current node)
self.maxcols = maxcols
self.parentcols = [] # list of parent columns of the current node
self.examples = examples
self.prediction = None # the class to be given out as prediction corresponding to the current node
def calculateginitest(var):
vargini = (var[2] / (var[2] + var[5]))
if var[0] == 0 or var[1] == 0:
totalvarentropy = 0
else:
totalvarentropy = vargini * (
1 - (math.pow((var[0] / (var[2])), 2) + math.pow(((var[1] / (var[2]))), 2)))
vargini = (var[5] / (var[2] + var[5]))
if var[3] == 0 or var[4] == 0:
totalvarentropy += 0
else:
totalvarentropy = vargini * (
1 - (math.pow((var[3] / (var[5])), 2) + math.pow(((var[4] / (var[2]))), 2)))
return totalvarentropy
def calculategini(var):
'''
Takes an array containing incorrect and correct count of attributes
:param var: array containing counts of an attribute
:return: ginivalue of an attribute
'''
varentropy = (var[2] / (var[2] + var[5]))
if var[0] == 0:
totalvarentropy = 0
else:
totalvarentropy = varentropy * ((-1) * ((var[0] / (var[2])) * math.log((var[0] / (var[2])), 2)))
if var[1] == 0:
totalvarentropy += 0
else:
totalvarentropy = varentropy * ((-1) * ((var[1] / (var[2])) * math.log((var[1] / (var[2])), 2))) + totalvarentropy
varentropy = (var[5] / (var[2] + var[5]))
if var[3] == 0:
totalvarentropy += 0
else:
totalvarentropy = varentropy * ((-1) * ((var[3] / (var[5])) * math.log((var[3] / (var[5])), 2))) + totalvarentropy
if var[4] == 0:
totalvarentropy += 0
else:
totalvarentropy = varentropy * ((-1) * ((var[4] / (var[5])) * math.log((var[4] / (var[5])), 2))) + totalvarentropy
return totalvarentropy
def learn_grow_tree(node):
'''
Takes node and selects best attribute for that node.
Recursively creates left and ride child node, assuming left child to be associated with
True value of current node and right child with False value of current attribute.
:param node: starts with root node, each node represent an attribute
:return: node returned with selected best attribute and predicted class
'''
already_selected = node.parentcols
if len(node.parentcols) > 0:
if len(node.parentcols) > 8:
return
temp = [[0 for i in range(6)] for r in range(node.maxcols)]
acnt = 0
bcnt = 0
#print(node.maxcols)
colcnt = 0
found = 0
found1 = 0
for line in node.examples:
for i in range(node.maxcols-1):
#if len(already_selected) > 0:
if i in already_selected:
i += 1
continue
else:
if line[i] == 'True' and line[len(line)-1] == 'en':
temp[i][0] += 1
temp[i][2] += 1
found += 1
elif line[i] == 'True' and line[len(line)-1] == 'nl':
temp[i][1] += 1
temp[i][2] += 1
found += 1
elif line[i] == 'False' and line[len(line)-1] == 'en':
temp[i][3] += 1
temp[i][5] += 1
found1 += 1
elif line[i] == 'False' and line[len(line)-1] == 'nl':
temp[i][4] += 1
temp[i][5] += 1
found1 += 1
i += 1
#varcnts.append(temp)
#print(temp)
if line[len(line)-1] == 'en':
acnt += 1
else:
bcnt += 1
#break;
if acnt > bcnt:
node.prediction = 'en'
else:
node.prediction = 'nl'
#print(acnt)
#print(temp)
ginis = [-100, -100, -100, -100, -100, -100, -100, -100, -100, -100]
giniroot = 1 - (math.pow((acnt / (acnt + bcnt)), 2) + math.pow((bcnt / (acnt + bcnt)), 2))
if found == 0 or found1 == 0:
return node
for i in range(node.maxcols-1):
if i in already_selected:
continue
else:
ginis[i] = giniroot - calculategini(temp[i])
#print(ginis)
mx = -100
for g in ginis:
if g > mx and g != 0:
mx = g
if mx == -100:
return node
select = ginis.index(mx)
#print("Selected - " , select)
node.cols = select
left = []
right = []
for line1 in node.examples:
if line1[select] == 'True':
left.append(line1)
else:
right.append(line1)
if len(left) > 0:
#print("max cols left - ", len(left[0]), " of ", left[0])
nodechild = Node(left, len(left[0]))
for n in node.parentcols:
nodechild.parentcols.append(n)
nodechild.parentcols.append(select)
node.left = learn_grow_tree(nodechild)
if len(right) > 0:
#print("max cols right - ", len(right[0]), " of ", right[0])
nodechildr = Node(right, len(right[0]))
for n in node.parentcols:
nodechildr.parentcols.append(n)
nodechildr.parentcols.append(select)
node.right = learn_grow_tree(nodechildr)
return node
def predict(root, test):
'''
Function to run the prediction.
:param root: the root node of decision tree
:param test: the test data (1 row at a time as input)
:return: the class selected for the test data
'''
for i in range(len(test)):
col = root.cols
if col == None:
return root.prediction
#print("parents - " , root.parentcols , " and selected is ", root.cols)
classify = root.prediction
if test[col] == 'True':
if root.left != None:
root = root.left
else:
return classify
else:
if root.right != None:
root = root.right
else:
return classify
i += 1
return classify
# Use only to test the decisiontree algorithm for classifying
if __name__ == "__main__":
f = open("new5000.txt", "r")
examples = []
for line in f:
entries = line.split(" ")
colcnt = 0
temp = []
for e in entries:
temp.append(e.replace(" ", "").replace("\n", ""))
examples.append(temp)
print(examples[0], " - length = ", len(examples[0]))
node = Node(examples, len(examples[0]))
tree = learn_grow_tree(node)
print("Predict - ", predict(node, ['True', 'True', 'False', 'False', 'True', 'False', 'False', 'True'])) |
n = 8
space = ' '
sharp = '#'
for i in range(n):
print(space*(n-i), end='') # Spaces before hash
print(sharp*(i+1) + space*2, end='') # Hashes + space
print(sharp*(i+1), end='') # Opposite pyramid
print('') # New line |
def hello(x):
print("Hey")
print("Howdy")
print("Holla")
print(x)
x = x + x
#print(x)
return x
x = 5
print("Olá\n")
print(x)
x = hello(int(input()))
print(x)
|
def greater_num(num): #id_40973454
return (num * 4)[:4]
if __name__ == '__main__':
quantity = int(input())
array = input().split()
array.sort(key=greater_num, reverse=True)
print(''.join(array))
|
class MyQueue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.isEmpty():
print(None)
else:
print(self.items.pop(0))
def peek(self):
if self.isEmpty():
print(None)
else:
print(self.items[0])
def size(self):
print(len(self.items))
queue = MyQueue()
n = int(input())
for i in range(n):
c = input()
if c == 'pop':
queue.pop()
elif c == 'peek':
queue.peek()
elif c == 'size':
queue.size()
else:
x = c.split()
queue.push(int(x[-1])) |
class Node:
def __init__(self, value, next_item=None):
self.value = value
self.next_item = next_item
# 0 > 1 > 2 > 3 >4 > 5
def solution(node):
while node:
print(node.value)
node = node.next_item
def solution2(node, number):
asd = []
i = 0
while node:
if node.value == number:
asd.append(node.value)
return i
node = node.next_item
i += 1
if len(asd) == 0:
return '-1'
node4 = Node('4')
node3 = Node('3', node4)
node2 = Node('2', node3)
node1 = Node('1', node2)
solution(node1)
#print(solution2(node1, str(3)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.