text stringlengths 37 1.41M |
|---|
a=input("the interger number is:")
b=int(a)
c=b*b
print('the square value of interger is:',c)
|
def add(a,b):
c=a+b
return c
def mult(a,b):
c=a*b
return c
def addition (a,b):
c=a-b
return c
def div (a,b):
c=a/b
return c |
import turtle
def read_coords(file):
henrydraper = []
coords = []
magnitudes = []
names = {}
# Opens file and creates lists for HD number, coordinates, and magnitudes
data = open(file, 'r')
for line in data:
data_list = line.split(' ', maxsplit=6)
henrydraper += [int(data_list[3])]
coords += [(float(data_list[0]), float(data_list[1]))]
magnitudes += [float(data_list[4])]
# Creates dictionary for star names
if len(data_list) == 7 and ';' in data_list[6]:
data_list[6] = data_list[6].split(';')
data_list[6][1] = data_list[6][1].strip("\n").lstrip()
names.update({data_list[6][0]: data_list[3],
data_list[6][1]: data_list[3]})
elif len(data_list) == 7:
data_list[6] = data_list[6].strip("\n")
names.update({data_list[6]: data_list[3]})
# Creates coordinate and magnitude dictionaries
coordinates_dict = dict(zip(henrydraper, coords))
magnitudes_dict = dict(zip(henrydraper, magnitudes))
dictionaries = (coordinates_dict, magnitudes_dict, names)
return dictionaries
def draw_square(size):
turtle.speed(0)
turtle.penup()
turtle.bgcolor('black')
turtle.pencolor('white')
turtle.fillcolor('white')
turtle.begin_fill()
turtle.pendown()
for i in range(4):
turtle.fd(size)
turtle.rt(90)
turtle.penup()
turtle.end_fill()
def plot_plain_stars(picture_size, coordinates_dict):
turtle.setup(picture_size, picture_size)
turtle.ht()
for i in coordinates_dict:
turtle.penup()
turtle.goto(coordinates_dict[i][0] * picture_size / 2.1,
coordinates_dict[i][1] * picture_size / 2.1)
draw_square(1)
def plot_by_magnitude(picture_size, coordinates_dict, magnitudes_dict):
turtle.screensize(picture_size, picture_size)
turtle.ht()
for i in coordinates_dict:
turtle.penup()
turtle.goto(coordinates_dict[i][0] * picture_size / 2,
coordinates_dict[i][1] * picture_size / 2)
star_size = round(10.0 / (magnitudes_dict[i] + 2))
if star_size > 8:
star_size = 8
draw_square(star_size)
def main():
dictionaries = read_coords('stars.txt')
coordinates_dict = dictionaries[0]
magnitudes_dict = dictionaries[1]
names_dict = dictionaries[2]
# plot_plain_stars(700, coordinates_dict)
plot_by_magnitude(700, coordinates_dict, magnitudes_dict)
main()
|
from tkinter import *
window=Tk()
def fun1():
grams=float(e1_value.get())*1000
pounds=float(e1_value.get())*2.20462
ounces=float(e1_value.get())*35.274
t1.insert(END,grams)
t2.insert(END,pounds)
t3.insert(END,ounces)
b1=Label(window,text="kg")
b1.grid(row=0,column=0)
b2=Button(window,text="convert",command=fun1)
b2.grid(row=0,column=2)
e1_value=StringVar()
e1=Entry(window,textvariable=e1_value)
e1.grid(row=0,column=1)
t1=Text(window,height=1,width=10)
t1.grid(row=1,column=0)
t2=Text(window,height=1,width=10)
t2.grid(row=1,column=1)
t3=Text(window,height=1,width=10)
t3.grid(row=1,column=2)
window.mainloop() |
#%%
import random
from math import *
import matplotlib.pyplot as plt
# 구 설정
R = int(input("구의 반지름 : "))
nExp = int(input("입자의 갯수 : "))
x_list, y_list, z_list = [], [], []
for i in range(nExp):
r = random.uniform(0, R)
r = r ** (1 / 2)
theta = random.uniform(0, 180)
phi = random.uniform(0, 360)
x = r * sin(theta) * cos(phi)
y = r * sin(theta) * sin(phi)
z = r * cos(theta)
x_list.append(x)
y_list.append(y)
z_list.append(z)
plt.plot(x_list, y_list, ".")
plt.show()
plt.plot(x_list, z_list, ".")
plt.show()
# 임의의 좌표 설정
location = []
while True:
x = random.uniform(0, 3 * R)
y = random.uniform(0, 3 * R)
z = random.uniform(0, 3 * R)
if x ** 2 + y ** 2 + z ** 2 < R ** 2:
location.append(x)
location.append(y)
location.append(z)
break
else:
continue
print(f"임의의 입자의 좌표 : {location}")
# Electric Field 계산
force = []
force_x, force_y, force_z = [], [], []
for i in range(nExp):
dif_x = location[0] - x_list[i]
dif_y = location[1] - y_list[i]
dif_z = location[2] - z_list[i]
l = sqrt(dif_x ** 2 + dif_y ** 2 + dif_z ** 2)
f = 1 / (l ** 2)
force.append(f)
force_x.append(dif_x * f)
force_y.append(dif_y * f)
force_z.append(dif_z * f)
print(f"힘의 합 : {sum(force)}")
print(f"힘의 평균 : {sum(force)/nExp}")
print(f"x축 벡터 평균 : {sum(force_x) / len(force_x)}")
print(f"y축 벡터 평균 : {sum(force_y) / len(force_y)}")
print(f"z축 벡터 평균 : {sum(force_z) / len(force_z)}")
# %%
|
"""
Dada a seqüência, calcular o cos:
"""
cos = fatorial = n = 1.0
fator = -1.0
while n % 2 != 0:
x = float(input("Digite o ângulo em radianos: "))
n = int(input("Digite o N: "))
for i in range(2,n+1):
fatorial *= i
if i % 2 == 0:
cos += fator*((x**i) / fatorial)
fator *= -1
print(cos) |
"""
Dada uma seqüência de letras terminada pelo caracter Z. Imprima a quantidade
de vogais lidas.
"""
status = True
sequencia = vogais = 0
while status:
letra = input("Digite uma letra: ")
if letra == "z":
status = False
elif letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u":
vogais += 1
else:
sequencia += 1
print(sequencia + vogais, " letras e ", vogais,"são vogais.") |
"""
Dados dois números inteiros positivos x e y, fazer a divisão de x por y sem usar
o operador de divisão.
"""
x = int(input("Digite um número inteiro para x: "))
y = int(input("Digite um número inteiro para y: "))
x_temporario = x
i = 0
while x_temporario >= y:
i += 1
x_temporario -= y
print("O quociente inteiro da divisão de x por y é:",i)
|
"""
Dada uma lista de números reais terminada pelo número 99.99, imprima cada
número lido. No final, imprima a média aritmética de todos os números da lista
(É claro que o nº 99.99 não faz parte da média).
"""
lista = n = cont = 0
while n != 99.99:
n = float(input("Digite um elemento para lista (caso queira parar, digite \
99.99): "))
if n != 99.99:
print(n)
lista += n
cont += 1
print("A média aritmética é:", lista/cont,".") |
"""
Dado um número inteiro N, divida-o por 2 (sucessivamente) enquanto o resultado
for maior que 0. No final, imprima o nº de divisões necessárias para zerar o
quociente.
"""
n = int(input("Digite um número inteiro: "))
i = 0
while n != 0:
n = n // 2
i += 1
print("O número de divisões necessário para zerar o quociente foi:", i) |
import traceback
print('test')
a = input()
if (a == 'e'):
try:
raise Exception('This is the error message.')
except:
errorFile = open('errorinfo.txt', 'w')
errorFile.write('error on line')
errorFile.close()
print('The traceback info was written to errorinfo.txt')
|
# Calculator
# Creating function for Addition.
def Add(x,y):
return x + y
# Creating function for Subtraction.
def Sub(x,y):
return x - y
# Creating function for Multiplication.
def Mult(x,y):
return x * y
# Creating function for Division.
def Div(x,y):
return x / y
print ("Select operation for Calculation")
print ("1: Addition")
print ("2: Subtraction")
print ("3: Multiplication")
print ("4: Division")
while True:
# Taking input from the user.
choice = input("Enter choice (1/2/3/4):")
# Check if choice is from any of these 4.
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", Add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", Sub(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", Mult(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", Div(num1, num2))
break
else:
print("Invalid Input") |
#!/usr/bin/env python
# coding=utf-8
class A(object):
"""docstring for A."""
def __init__(self, cantidad):
self.cantidad = cantidad
def porciento(self,p):
return self.cantidad * (p/100)
def main():
a = A(100)
print(a.cantidad)
print(a.porciento(85))
if __name__ == '__main__':
main()
|
print('3 x 1 = {}'.format(3*1))
print('3 x 2 = ', 3*2)
print('3 x 3 = ', 3*3)
print('3 x 8 = ', 3*8)
print('3 x 9 = ', 3*9)
print('3 x 10 = ', 3*10)
|
import speech_recognition as sr
import win32api
def recognize_speech_from_mic(recognizer, microphone):
"""Transcribe speech from recorded from `microphone`.
Returns a dictionary with three keys:
"success": a boolean indicating whether or not the API request was
successful
"error": `None` if no error occured, otherwise a string containing
an error message if the API could not be reached or
speech was unrecognizable
"transcription": `None` if speech could not be transcribed,
otherwise a string containing the transcribed text
"""
# check that recognizer and microphone arguments are appropriate type
if not isinstance(recognizer, sr.Recognizer):
raise TypeError("`recognizer` must be `Recognizer` instance")
if not isinstance(microphone, sr.Microphone):
raise TypeError("`microphone` must be `Microphone` instance")
# adjust the recognizer sensitivity to ambient noise and record audio
# from the microphone
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# set up the response object
response = {
"success": True,
"error": None,
"transcription": None
}
# try recognizing the speech in the recording
# if a RequestError or UnknownValueError exception is caught,
# update the response object accordingly
try:
response["transcription"] = recognizer.recognize_sphinx(audio)
except sr.RequestError:
# API was unreachable or unresponsive
response["success"] = False
response["error"] = "API unavailable"
except sr.UnknownValueError:
# speech was unintelligible
response["error"] = "Unable to recognize speech"
return response
def recognizeSpeech(application):
r = sr.Recognizer()
mic = sr.Microphone()
result = recognize_speech_from_mic(r, mic)
choice = FuzzySearch(result['transcription'])
if choice:
if choice == 'music':
PlayMusic()
application.ui.gif.stop()
if choice == 'file':
OpenFile()
application.ui.gif.stop()
else:
pass
# 模糊搜索
def FuzzySearch(r):
a = r.split(' ')
b = ['machine', 'music', 'magic', 'magazine', 'major', 'mommy', 'market', 'supermarket', 'marriage', 'match',
'maybe']
c = ['file', 'fire']
d = list(set(a).intersection(set(b)))
e = list(set(a).intersection(set(c)))
print(a, b, c, d, e)
if len(d):
return 'music'
if len(e):
return 'file'
else:
return False
def PlayMusic():
# 播放音乐
# ShellExecute 查找与指定文件关联在一起的程序的文件名
# 第一个参数默认为0,打开,路径名,默认空,默认空,是否显示程序1or0
win32api.ShellExecute(0, 'open', r'goodnight.mp3', '', '', 1)
def OpenFile():
# 打开文件
win32api.ShellExecute(0, 'open', r'file.txt', '', '', 1)
|
# -*- coding: utf-8 -*-
"""
THE PROBLEM:
The purpose of the project is to create a python program that could rate a comment or review of a restaurant
in the number of stars. It could be between 1-5 depending upon the performance of the restaurant. In this
case the program will be able to classify the comment given by a customer on the 'yelp' using a SVM classifier.
The user will be able to see the accuracy of the program and the confusion matrix depicting the true positives
and true negatives. The program used different natural language processing tools such as n-grams. The comments
are fist preprocessed using data slicing and TfidfVectorizer that removes the words that occur most frequently
in the text data. The data is then balanced according to the least number of comments for a star rating. e.g. if
there are 500 reviews for 1 star rating and more than that for other star ratings, then the program will only take
500 reviews of all the star ratings in order to balance the output. Then the 70% of the data, called test data, is
ran on SVM classifier and the model is trained. The model is tested on the remaining 30% of the data and the results
are shown as output.
YELP SCRIPT:
[Enter] python balanced_yelp_project.py yelp.csv
[Output] Accuracy and confusion matrix
USAGE:
The program is called 'balanced_yelp_project.py', and it should be run from the command line or linux.
ALGORITHM:
1. The program starts with prompting the user to enter the inputs:
"python balanced_yelp_project.py(the python file) yelp.csv(the csv data file) ngram"
For e.g. "python balanced_yelp_project.py yelp.csv 2"
2. The program will then read the files and import the dataset.
3. It will seperate the columns of the .cs file using ',' as delimiter.
4. It will store the list of text comments in texts list and star rating in stars list
5. It will store the ngrams given by the user.
5. It will call the method that will balance the data according to the least number of reviews for
any star rating.
6. It will break the words into single tokens and bi-grams then then it will vectorize them according to
the number of times it is repeating.
7. It will build up the vocabulary from all the reviews and turns each indivdual text into a matrix of numbers
8. Now, the SVM classifier model is created and trained on 70% of the data.
9. The classifier model is then checked and run on remaining test data.
10. CASE 1: Then the program breaks the data in 2 parts, i.e. 'positive' and 'negative'. The star ratings 1 & 2 are
considered as negative while 4 & 5 are considered as 'positive' while 3 is taken as 'neutral'.
11. CASE 2: Then the program breaks the data in 2 parts, i.e. 'positive' and 'negative'. The star ratings 1 & 2 are
considered as negative while 3, 4 & 5 are considered as 'positive'.
12. CASE 3: Then the program breaks the data in 2 parts, i.e. 'positive' and 'negative'. The star ratings 1, 2 & 3
are considered as negative while 4 & 5 are considered as 'positive'.
13. Case 4. Then the program breaks the data in 2 parts, i.e. 'positive' and 'negative'. The star ratings 1 & 2
are considered as negative while 4 & 5 are considered as 'positive'.
COURSE: AIT 690 - Natural Language Proccessing
AUTHOR’s NAME: Preetpal Singh and Ahmed Alshaibani
DATE: 5 December 2018
"""
'''Importing the libraries '''
import warnings
warnings.filterwarnings("ignore")
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import confusion_matrix
from collections import Counter
from datetime import datetime
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
import sys
import csv
import pandas as pd
''' Read the yelp data for text and star ratings '''
texts = []
stars = []
argList = sys.argv
with open(argList[1], 'r') as my_file:
csv_reader = csv.reader(my_file, delimiter = ',')
line_count = 0
for row in csv_reader:
if line_count > 0:
texts.append(row[4])
stars.append(int(row[3]))
line_count += 1
#text = pd.read_csv('yelp_file', usecols=['text'])
#star = pd.read_csv('yelp.csv', usecols=['stars'])
#print(texts)
#print(stars)
''' Read the n-grams from the user '''
n = int(argList[2])
#n = 2
#''' Making list of texts and ratings fromt the data above '''
#texts = []
#stars = []
#for i in range(len(text)):
# texts.append(text['text'][i])
#for i in range(len(star)):
# stars.append(star['stars'][i])
#print(text+" "+ star)
#print(texts)
#print(stars)
#print("Results with balanced data !!!")
#print("N-Gram is set as:"+str(n))
''' Balancing the data according to the number of reviwes available for each rating '''
def balance_classes(xs, ys):
''' Undersample xs, ys to balance classes '''
freqs = Counter(ys)
''' The least common rating is the maximum number we want for all the other ratings '''
max_allowable = freqs.most_common()[-1][1]
num_added = {clss: 0 for clss in freqs.keys()}
new_ys = []
new_xs = []
for i, y in enumerate(ys):
if num_added[y] < max_allowable:
new_ys.append(y)
new_xs.append(xs[i])
num_added[y] += 1
return new_xs, new_ys
''' This shows the number of stars for each star rating '''
print('\n\nThis shows the results for the Balanced data..')
print('\n\nInital number of reviews of each star rating:')
print(Counter(stars))
''' This will balance the data-- the least number was 749 '''
balanced_x, balanced_y = balance_classes(texts, stars)
print('\n\nThe number of reviews of each star rating after balancing:')
print(Counter(balanced_y))
#print(balanced_x)
#print(balanced_y)
''' This vectorizer breaks text into single words and bi-grams and then calculates the TF-IDF representation '''
vectorizer = TfidfVectorizer(ngram_range=(1,n))
''' The 'fit' builds up the vocabulary from all the reviews
while the 'transform' step turns each indivdual text into a matrix of numbers '''
vectors = vectorizer.fit_transform(balanced_x)
X_train, X_test, y_train, y_test = train_test_split(vectors, balanced_y, test_size=0.3, random_state=42)
''' Initialise and train the SVM classifier '''
classifier = LinearSVC()
classifier.fit(X_train, y_train)
''' Test the classifier and check the accuracy '''
preds = classifier.predict(X_test)
print('\n\nAccuracy:')
print(accuracy_score(y_test, preds))
#print(classification_report(y_test, preds))
print('\n\nConfusion Matrix for star ratings')
print(confusion_matrix(y_test, preds))
print("\n\n----------------------------------------------------------------------------------------------------------")
keep = set([1,2,3,4,5])
print("\n\nCASE 1: The below results consider 1 & 2 stars as 'negative', 4 & 5 star as 'positive' and 3 star as 'neutral'")
''' to keep the examples we want to keep within the keep set '''
keep_train_is = [i for i, y in enumerate(y_train) if y in keep]
keep_test_is = [i for i, y in enumerate(y_test) if y in keep]
''' convert the stars in the train set to stars 1 and 2 as "negative" and 4 and 5 as "positive" '''
X_train2 = X_train[keep_train_is, :]
y_train2 = [y_train[i] for i in keep_train_is]
y_train2 = ["n" if (y == 1 or y == 2) else ("p" if (y == 4 or y == 5) else "non" )for y in y_train2]
''' convert the test set to stars 1 and 2 as "n" and the rest which is 4 and 5 as "p" '''
X_test2 = X_test[keep_test_is, :]
y_test2 = [y_test[i] for i in keep_test_is]
y_test2 = ["n" if (y == 1 or y == 2) else ("p" if (y == 4 or y == 5) else "non" )for y in y_test2]
classifier.fit(X_train2, y_train2)
preds = classifier.predict(X_test2)
print('\nConfusion matrix')
print(confusion_matrix(y_test2, preds))
print('\nFinal accuracy')
print( accuracy_score(y_test2, preds))
print("\n\nCASE 2: The below results consider 1, 2 stars as 'negative' and 3, 4 & 5 star as 'positive'")
y_train2 = [y_train[i] for i in keep_train_is]
y_train2 = ["n" if (y == 1 or y == 2) else "p" for y in y_train2]
''' convert the test set to stars 1 and 2 as "n" and the rest which is 4 and 5 as "p" '''
X_test2 = X_test[keep_test_is, :]
y_test2 = [y_test[i] for i in keep_test_is]
y_test2 = ["n" if (y == 1 or y == 2) else "p" for y in y_test2]
classifier.fit(X_train2, y_train2)
preds = classifier.predict(X_test2)
print('\nConfusion matrix')
print(confusion_matrix(y_test2, preds))
print('\nFinal accuracy')
print( accuracy_score(y_test2, preds))
print("\n\nCASE 3: The below results consider 1, 2 & 3 stars as 'negative' and 4 & 5 star as 'positive'")
y_train2 = [y_train[i] for i in keep_train_is]
y_train2 = ["n" if (y == 1 or y == 2 or y == 3) else "p" for y in y_train2]
''' convert the test set to stars 1 and 2 as "n" and the rest which is 4 and 5 as "p" '''
X_test2 = X_test[keep_test_is, :]
y_test2 = [y_test[i] for i in keep_test_is]
y_test2 = ["n" if (y == 1 or y == 2) else "p" for y in y_test2]
classifier.fit(X_train2, y_train2)
preds = classifier.predict(X_test2)
print('\nConfusion matrix')
print(confusion_matrix(y_test2, preds))
print('\nFinal accuracy')
print( accuracy_score(y_test2, preds))
print("\n\nCASE 4: The below results consider 1 & 2 stars as 'negative' and 4 & 5 star as 'positive'")
''' convert the stars in the train set to stars 1 and 2 as "n" and the rest which is 4 and 5 as "p" '''
keep = set([1,2,4,5])
keep_train_is = [i for i, y in enumerate(y_train) if y in keep]
keep_test_is = [i for i, y in enumerate(y_test) if y in keep]
y_train2 = [y_train[i] for i in keep_train_is]
y_train2 = ["n" if (y == 1 or y == 2) else "p" for y in y_train2]
X_train2 = X_train[keep_train_is, :]
''' convert the test set to stars 1 and 2 as "n" and the rest which is 4 and 5 as "p" '''
X_test2 = X_test[keep_test_is, :]
y_test2 = [y_test[i] for i in keep_test_is]
y_test2 = ["n" if (y == 1 or y == 2) else "p" for y in y_test2]
classifier.fit(X_train2, y_train2)
preds = classifier.predict(X_test2)
print('\nConfusion matrix')
print(confusion_matrix(y_test2, preds))
print('\nFinal accuracy')
print( accuracy_score(y_test2, preds))
|
def showMenu():
print "A: Convert celsius to fahrenheit"
print "B: Convert fahrenheit to celsius"
print "X: Exit"
def celsiusToFahrenheit(celsiusTemperature):
"This function converts Celsius temps to Fahrenheit temps"
fahrenheit = celsiusTemperature * (9.0 / 5.0) + 32.0
return fahrenheit
def fahrenheitToCelsius(fahrenheitTemperature):
"This function converts Fahrenheit temps to Celsius temps"
celsius = (fahrenheitTemperature - 32.0) * (5.0 / 9.0)
return celsius
showMenu()
option = raw_input("Option: ")
while option != "X":
if option == "A" or option == "B":
number = raw_input("Number to convert: ")
if option == "A":
print(celsiusToFahrenheit(float(number)))
elif option == "B":
print(fahrenheitToCelsius(float(number)))
else:
print "Please enter a valid option."
showMenu()
option = raw_input("Option: ")
|
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
print(num1 + num2)
# numm1 = 5
# num2 = 4
# nu1 + num2 = 5 + 4 = 9
|
'''
Надо написать функцию которая возвращает N-мерный массив с ширинами заданными в аргументе списком из N элементов:
n_arr([2,2])
>> [[“”,“”],[“”,“”]]
n_arr([2,2,2])
>> [[[“”,“”],[“”,“”]], [[“”,“”],[“”,“”]]]
'''
def array(lst):
if len(lst) == 1:
return ['' for i in range(0, lst[0])]
sp = [array(lst[1:]) for i in range(0, lst[0])]
return sp
print(array([2, 2]))
print(array([2, 2, 2]))
print(array([2, 3, 2]))
print(array([4, 3, 2]))
print(array([2, 3, 5]))
ar = array([2, 2, 2])
ar[1][1][1] = 'x'
print(ar)
|
import sys
import csv as csv
from bs4 import BeautifulSoup
import os
def main():
stop_words = get_common_english_words('common-english-words.csv')
# if no filenames were given as input it would try to run on the default 'train.csv' and 'test.csv'
if len(sys.argv)==1:
pre_process_csv('train.csv',stop_words)
pre_process_csv('test.csv',stop_words)
# pre process any given filename in the command line input
for arg in sys.argv[1:]:
pre_process_csv(arg,stop_words)
def filter_common_words(text, stop_words):
if isinstance(text, unicode):
text = text.encode('utf8')
# the following symbols will be replaced with white space
symbols = [',','.',':',';','+','=','"','/']
for symbol in symbols:
text = text.replace(symbol,' ')
output = ""
for word in text.split():
if not word.lower() in stop_words:
output += word + ' '
return output
def filter_html_tags(text):
# the following tags and their content will be removed, for example <a> tag will remove any html links
tags_to_filter = ['code','a']
if isinstance(text, unicode):
text = text.encode('utf8')
soup = BeautifulSoup(text)
for tag_to_filter in tags_to_filter:
text_to_remove = soup.findAll(tag_to_filter)
[tag.extract() for tag in text_to_remove]
return soup.get_text()
def pre_process_csv(filename, word_set_to_filter=None):
if word_set_to_filter is None:
word_set_to_filter = set()
print 'pre processing '+filename+'...'
train_file_object = csv.reader(open('..'+os.path.sep+'csv'+os.path.sep+filename, 'rb'))
header = train_file_object.next()
pre_processed_file = csv.writer(open('..'+os.path.sep+'csv'+os.path.sep+'pre_process_'+filename, "wb"),quoting=csv.QUOTE_NONNUMERIC)
pre_processed_file.writerow(header)
# if the csv file is the test data
if len(header)==3:
for row in train_file_object:
pre_processed_file.writerow([int(row[0]), filter_common_words(row[1],word_set_to_filter), filter_common_words(filter_html_tags(row[2]),word_set_to_filter)])
# if the csv file is the train data
if len(header)==4:
for row in train_file_object:
pre_processed_file.writerow([int(row[0]), filter_common_words(row[1],word_set_to_filter), filter_common_words(filter_html_tags(row[2]),word_set_to_filter),row[3]])
print 'finished'
def get_common_english_words(filename):
english_words_file = csv.reader(open('..'+os.path.sep+'csv'+os.path.sep+filename, 'rb'))
stop_words = set()
for row in english_words_file:
for word in row:
stop_words.add(word.lower())
return stop_words
if __name__ == '__main__':
main() |
#Crie um programa que leia um número inteiro e mostre na tela se ele é par ou Ímpar
num = int(input("Digite um número inteiro: "))
if num%2 == 0:
print("O número {} é par".format(num))
else:
print("O número {} é ímpar".format(num)) |
#Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz
num = int(input('Digite um número: '))
print("O dobro do número {0} é {1}, o triplo é {2} e a raiz é {3}".format(num, (num * 2), (num * 3), (num ** (1 / 2)))) |
#O mesmo professor do desafio anterior quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada
from random import shuffle
var1 = input("Nome do primeiro alunos: ")
var2 = input("Nome do segundo alunos: ")
var3 = input("Nome do terceiro alunos: ")
var4 = input("Nome do quarto alunos: ")
lista = [var1, var2, var3, var4]
shuffle(lista)
print('A ordem de apresentação será: ', lista)
|
#Faça um progrmama que leia a largura e a altura de uma parede em metros, calucele a sua área e aquantidade de tinta necessãria para pintá-la, sabendo que casa litro de tinta pinta uma área de 2m².
import math
width = float(input('Type the wall width: '))
height = float(input('Type the wall height: '))
size = width*height
print('Para pintar {} é necessário {} litros de tinta'.format(size, math.ceil(size/2))) |
#Desenvolva um programa que pergunte a distância de uma viagem em km. Calcule o preço da passagem, cobrando R$0,50 por km para viagens de até 200km e R$0,45 para viagens mais longas
distancia = int(input("Digite a distância em km da viagem: "))
if distancia <= 200:
print("O preço da passagem é R${}".format(distancia*0.5))
else:
print("O preço da passagem é R${}".format(distancia*0.45)) |
cars = ['bmw', 'audi', 'toyota', 'subaru']
# print("Here is the orginal list: ")
# print(cars)
#
# print("\nHere is the sorted list: ")
# print(sorted(cars))
#
# print("\nHere is the orginal list again: ")
# print(cars)
cars.reverse()
# print(cars)
l = len(cars)
# print(l)
cars = ['bmw', 'audi', 'toyota', 'subaru']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
|
# Задача 8. Вариант 23.
# Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4)
# так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право на
# подсказку в том случае, если у него нет никаких предположений. Разработайте
# систему начисления очков, по которой бы игроки, отгадавшие слово без подсказки,
# получали больше тех, кто запросил подсказку.
# Shmakov M. A.
# 02.11.2016
import random
WORDS = ("питон", "анаграмма", "простая", "сложная", "ответ", "подстаканник")
correct = random.choice(WORDS)
word = correct
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[position+1:]
print('''
Добро пожаловать в игру "Анограммы"!
Надо переставить буквы так, чтобы получилось осмысленное слово.
(Для выхода нажмите Enter, не вводя своей версии.)
(Для получения подсказки введите :п)
''')
print("Вот анаграмма:", jumble)
hint = ""
while True:
guess = input("\nПопробуйте отгадать исходное слово: ")
if not guess:
break
elif guess == ":п":
litter = correct[len(hint)]
hint += litter.upper()
jumble = jumble.replace(litter, "")
if len(hint) == len(correct):
print("Вы проиграли!\nПравильное слово: ", hint)
else:
print("Подсказка:", hint+jumble)
elif guess != correct:
print("К сожалению, вы не правы.")
else:
print("Да, именно так! Вы отгадали!\n")
print("Вам начислено {} баллов".format((len(correct) - len(hint)) * 100))
break
print("Спасибо за игру.")
input("\nНажмите Enter для выхода.")
|
def hello(s):
print("Hello " + s)
def sestevanje(a, b):
rezultat = 0
rezultat += a
rezultat += a
return rezultat
hello("student")
print(sestevanje(1, 3))
def switch(a, b)
return (b, a)
|
import tkinter as tk
window = tk.Tk()
label = tk.Label(text = 'Hello, Tkinter', foreground = 'white', background = 'blue', width = 10, height = 10) # Can also use hexidecimal color codes
label.pack()
button = tk.Button(text = 'Click Me', width = 25, height = 5, fg = 'black', bg = 'blue')
button.pack()
entry = tk.Entry(fg="white", bg="red", width=50)
entry.pack()
window.mainloop() # This executes the code so the window appears
|
# LIST STRING METHODS
def get_all_letters(string):
return list(string)
print(get_all_letters('Radagast'))
print('\n')
#======================================================================================================================
def get_all_words(string):
return string.split()
print(get_all_words('Radagast the Brown'))
print('\n')
#======================================================================================================================
# ADVANCED 1
from collections import Counter, defaultdict
def count_words(string):
d = {}
count = 1
for i in sorted(string.split()):
if i not in d:
d[i] = count
else:
d[i] = count + 1
return d
string = 'ask a bunch, get a bunch'
print(count_words(string))
print('\n')
#======================================================================================================================
def count_words(string):
d = Counter(sorted(string.split()))
return d
string = 'ask a bunch, get a bunch'
print(count_words(string))
print('\n')
#======================================================================================================================
def count_words(string):
if not string:
return {}
word_dict = {}
words = string.split(" ")
for word in words:
if word_dict.get(word):
word_dict[word] += 1
else:
word_dict[word] = 1
return word_dict
string = 'ask a bunch, get a bunch'
print(count_words(string))
print('\n')
#======================================================================================================================
def invert_dictionary(d):
'''
Given a dictionary d, return a new dictionary with d's values
as keys and the value for a given key being
the set of d's keys which shared the same value.
Parameters
----------
d: dict
Returns
-------
dict
A dictionary of sets of input keys indexing the same input values
indexed by the input values.
>>>invert_dictionary({'a': 2, 'b': 4, 'c': 2})
{2: {'a', 'c'}, 4: {'b'}}
'''
dict_ = {}
for key, value in d.items():
dict_.setdefault(value, set()).add(key)
return dict_
print(invert_dictionary({'a': 2, 'b': 4, 'c': 2}))
print('\n')
#======================================================================================================================
# LIST METHODS 6
def remove_from_back(lst):
if lst:
lst.pop()
return lst
lst = []
print(remove_from_back(lst))
print('\n')
#======================================================================================================================
# CONDITIONALS 6
def is_either_even_or_are_both_7(num1, num2):
return num1 % 2 == 0 or num2 % 2 == 0 or (num1 == 7 and num2 == 7)
print(is_either_even_or_are_both_7(3,7))
print(is_either_even_or_are_both_7(2,3))
print(is_either_even_or_are_both_7(7,7))
print('\n')
#======================================================================================================================
def is_either_even_and_both_less_than_9(num1, num2):
return (num1 < 9 and num2 < 9) and (num1 % 2 == 0 or num2 % 2 == 0)
print(is_either_even_and_both_less_than_9(2,4))
print(is_either_even_and_both_less_than_9(72,2))
print('\n')
#======================================================================================================================
# ADVANCED 2
def extend(dict1,dict2):
for k,v in dict2.items():
if k not in dict1:
dict1[k] = v
return dict1
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 4, 'c': 3}
print(extend(dict1, dict2))
print('\n')
#======================================================================================================================
# DICTIONARY 4
def remove_numbers_larger_than(num, dict1):
res = {}
for key in dict1:
if not (isinstance(dict1[key], int) and dict1[key] > num):
res[key] = dict1[key]
return res
dictionary = {'a': 8, 'b': 2, 'c': 'montana'}
result = remove_numbers_larger_than(5, dictionary)
print(result)
print('\n')
#======================================================================================================================
# DICTIONARY 4: SECOND METHOD
def remove_numbers_larger_than(target, dictionary):
removal_list = []
for key in dictionary:
if isinstance(dictionary[key], int):
if dictionary[key] > target: removal_list.append(key)
for key in removal_list:
dictionary.pop(key)
return dictionary
dictionary = {'a': 8, 'b': 2, 'c': 'montana'}
result = remove_numbers_larger_than(5, dictionary)
print(result)
print('\n')
#======================================================================================================================
# DICTIONARY 4: SINGLE LINE METHOD
res = {key : val for key, val in dictionary.items() if not (isinstance(val, int) and (val > 5))}
print(res)
print('\n')
#======================================================================================================================
# DICTIONARY 4: CON'T
def remove_integers_less_than(target, dictionary):
return {key:value for key, value in dictionary.items() if not (isinstance(value, int) and (value < target))}
dictionary = {'a': 8, 'b': 2, 'c':'montana'}
result = remove_integers_less_than(5, dictionary)
print(result)
print('\n')
#======================================================================================================================
def remove_integers_less_than(target, dictionary):
res = {}
for key in dictionary:
if not (isinstance(dictionary[key], int) and dictionary[key] < target):
res[key] = dictionary[key]
return res
dictionary = {'a': 8, 'b': 2, 'c':'montana'}
result = remove_integers_less_than(5, dictionary)
print(result)
print('\n')
#======================================================================================================================
def remove_integers_less_than(target, dictionary):
removal_list = []
for key in dictionary:
if isinstance(dictionary[key], int):
if dictionary[key] < target: removal_list.append(key)
for key in removal_list:
dictionary.pop(key)
return dictionary
dictionary = {'a': 8, 'b': 2, 'c':'montana'}
result = remove_integers_less_than(5, dictionary)
print(result)
print('\n')
#======================================================================================================================
# DICITONARY 4: CON'T
def remove_string_values_longer_than(target, dictionary):
return {key:value for key,value in dictionary.items() if not (isinstance(dictionary[key], str) and len(dictionary[key]) > target)}
dictionary = {'name': 'Montana', 'age': 20, 'location': 'Texas'}
result = remove_string_values_longer_than(6, dictionary)
print(result)
print('\n')
#======================================================================================================================
def remove_string_values_longer_than(target, dictionary):
removal_list = []
for key in dictionary:
if isinstance(dictionary[key], str):
if len(dictionary[key]) > target: removal_list.append(key)
for key in removal_list:
dictionary.pop(key)
return dictionary
dictionary = {'name': 'Montana', 'age': 20, 'location': 'Texas'}
result = remove_string_values_longer_than(6, dictionary)
print(result)
print('\n')
#======================================================================================================================
# DICTIONARY 5
def remove_even_values(dictionary):
return {key : value for key, value in dictionary.items() if not isinstance(dictionary[key], int) or (value % 2 !=0)}
dictionary = {'a': 2, 'b': 3, 'c': 4, 'd':'Texas'}
output = remove_even_values(dictionary)
print(output)
print('\n')
#======================================================================================================================
def remove_even_values(dictionary):
removal_list = []
for key in dictionary:
if isinstance(dictionary[key], int):
if dictionary[key] % 2 == 0:
removal_list.append(key)
for key in removal_list:
dictionary.pop(key)
return dictionary
dictionary = {'a': 2, 'b': 3, 'c': 4, 'd':'Texas'}
output = remove_even_values(dictionary)
print(output)
print('\n')
#======================================================================================================================
def count_number_of_keys(dictionary):
return len(dictionary)
dictionary = {'a': 1, 'b': 2, 'c': 3}
output = count_number_of_keys(dictionary)
print(output)
print('\n')
#======================================================================================================================
def count_number_of_keys(dictionary):
return len(dictionary.keys())
dictionary = {'a': 1, 'b': 2, 'c': 3}
output = count_number_of_keys(dictionary)
print(output)
print('\n')
#======================================================================================================================
def remove_odd_values(dictionary):
return {key:value for key,value in dictionary.items() if not isinstance(dictionary[key], int) or (value % 2 == 0)}
dictionary = {'a': 1, 'b': 2, 'c': 3, 'd':'montana'}
output = remove_odd_values(dictionary)
print(output)
print('\n')
#======================================================================================================================
def remove_odd_values(dictionary):
removal_list = []
for key in dictionary:
if isinstance(dictionary[key], int):
if dictionary[key] % 2 == 1:
removal_list.append(key)
for key in removal_list:
dictionary.pop(key)
return dictionary
dictionary = {'a': 1, 'b': 2, 'c': 3, 'd':'montana'}
output = remove_odd_values(dictionary)
print(output)
print('\n')
#======================================================================================================================
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def max_index(arr):
return max(arr),arr.index(max(arr))
def func(nums):
if not nums:
return None
val,index=max_index(nums)
root=TreeNode(val)
root.left=func(nums[:index])
root.right=func(nums[index+1:])
return root
return func(nums) |
import math
class Solution:
def judgeSquareSum(self, c: int) -> bool:
lo = 0
hi = int(math.sqrt(c))
while lo <= hi:
summ = lo * lo + hi * hi
if summ > c:
hi -= 1
elif summ < c:
lo += 1
else:
return True
return False
|
from turtle import*
shape("turtle")
color("blue")
speed(0)
for i in range(15):
forward(20)
left(90)
forward(20)
left(90)
forward(20)
left(90)
forward(20)
right(90)
forward(20)
right(90)
forward(20)
right(90)
forward(20)
mainloop() |
a = int(input("Xin hãy nhập n từ bàn phím"))
b = int(input("Xin hãy nhập m từ bàn phím"))
while (a >= b):
print(a)
a = a - 1
|
a=12
b=3
print(a+b) #15
print(a-b) #9
print(a*b) #36
print(a/b) #4.0
print(a//b) # 4 integer division, rounded down towards minus infinity
print(a%b) #0 modulo: the remainder after integer division
print()
print(a + b /3 - 4 *12)
print(a+(b/3)-(4*12))
print((((a+b)/3)-4)*12)
print(((a+b)/3 -4)*12)
c=a+b
d=c/3
e=d-4
print(e*12)
print()
print(a/(b*a)/b) |
import random
answer = random.randint(1,10)
print("please enter the number between 1 and 10: ")
guess =0
guess = int(input())
while guess!=answer and guess != 0:
if(guess>answer):
print("please guess lower")
else:
print("please guess higher")
guess = int(input())
if guess == 0:
print("you are quit")
else:
print("you guessed correctly") |
numero = int(input("Dame un numero mayor a 5: "))
if numero >= 5:
print("Bien hecho!") #la sangria indica el bloque
else:
print("No sabes contar jeje")
#cuando se quita la sangria se sale del bloque
input("\nPresiona cualquier tecla para continuar")
|
flotante = 1.5
entero = 25
print("Tu entero es:", entero)
print("Tu flotante es:", flotante)
enteroDos = int(flotante)
flotanteDos = float(entero)
print("Tu entero es:", enteroDos)
print("Tu fltante es:", flotanteDos)
input("\n Presiona cualquier tecla para continuar")
|
iNumero = 15
sCadena = "hola"
fNumero = 1.56
bEstado = True
"""type(iNumero) #Esto nos va a decir enla cosola qué tipo de dato es la variable"""
numero = 234
numeroL = 37564263454265774
print("El numero corto es:", numero, "Su tipo es:", type(numero))
print("\n")
print("El numero largo es:", numeroL, "Su tipo es:", type(numeroL))
input("\n Presiona cualquier tecla para continuar")
|
#7/15/2013
#Find the largest palindrome made from the product of two 3-digit numbers.
three_digits = range( 100, 999 )
three_digit_mult = []
while len(three_digits) > 1:
mult_digit = three_digits[0]
three_digits.remove(mult_digit)
for left_digit in three_digits:
three_digit_mult.append(mult_digit * left_digit )
three_digit_mult = list(set(three_digit_mult))
print three_digit_mult
palindrome_array = []
for test_digit in three_digit_mult:
digit_string = str(test_digit)
if digit_string == digit_string[::-1]:
palindrome_array.append(test_digit)
print palindrome_array
print max(palindrome_array)
|
#!/usr/bin/python
# Copyright (C) 1015
# Author: Vinod NK
"""
Script to copy images from origin to target path.
When an image is created in target path, the creation date of this image is
the creation date of the origin directory. This is because if exists a new folder
in the origin path, all photos has highest priority to copy in the target path.
For check if one image on target path has a new image to replace it,
get the last modified date of the target image and compare with the creation
date of origin directory. If the directory creation date is greater than the
last modified date of image, replace the image.
"""
import os
import imghdr
from stat import *
from PIL import Image
base_width = 300
path = "/apps/images/Fotos/"
target = "/apps/images/"
dirs = os.listdir(path)
def create_image(original_image, local_image, date_dir):
try:
print("Creating...")
im = Image.open(original_image)
# Resize the image
wpercent = (base_width / float(im.size[0]))
hsize = int((float(im.size[1]) * float(wpercent)))
im = im.resize((base_width, hsize))
file_image = open(local_image, 'w+')
im.save(local_image)
st = os.stat(local_image)
os.utime(local_image, (st[ST_ATIME], date_dir))
print("OK date new image: ", date_dir)
except OSError:
print("Oops! cannot create image OSError: " + original_image)
except IOError:
print("Oops! cannot create image IOError: " + original_image)
for file in dirs:
dir_path = path + file + "/"
if os.path.isdir(dir_path) and not os.listdir(dir_path) == []:
# Get the creation date of directory
date_dir = os.path.getctime(dir_path)
print("\nDir: " + dir_path + ", Date str: ", date_dir)
for image in os.listdir(dir_path):
dir_image = dir_path + image
extension = imghdr.what(dir_image);
# If the file is a imge jpeg (if if added new extensio, check authLoginLogicV2 mashup)
if os.path.isfile(dir_image) and extension == "jpeg":
print("Image: " + dir_image)
# Create name of directory fot the local image.
local_image = target + image
if os.path.exists(local_image):
print("Image exists")
date_file = os.path.getmtime(local_image)
print("Date image", date_file)
if int(date_dir) > int(date_file):
print("Create image")
create_image(dir_image, local_image, date_dir)
else:
print("Image no exists")
create_image(dir_image, local_image, date_dir)
|
# Taking input and displaying it as a list and tuple
a = input("Enter the numbers")
print(a)
a = a.split(",")
b = []
for i in a:
b.append(int(i))
print(b)
c = tuple(b)
print(c) |
# coding: utf-8
# In[ ]:
def getMax(data):
""" Find the maximum number of steps in the data and the date it was achieved.
Parameters:
data: Pandas DataFrame containing Apple Health data imported from a
.csv file.
Return:
The row of values for when the maximum number of steps were achieved:
Start date, Finish date, Distance(mi), Steps (count)"""
import pandas as pd # ensure pandas has been imported
# find the row containing the maximum steps and return that row.
maximum = data.loc[data['Steps (count)'].idxmax()]
return maximum
def getMin(data):
""" Find the maximum number of steps in the data and the date it was achieved.
Parameters:
data: Pandas DataFrame containing Apple Health data imported from a
.csv file.
Return:
The row of values for when the maximum number of steps were achieved:
Start date, Finish date, Distance(mi), Steps (count)"""
import pandas as pd #ensure pandas has been imported
# find the row containing the minimum steps and return that row.
minimum = data.loc[data['Steps (count)'].idxmin()]
return minimum
|
import numpy as np
import utils
import velocity
import curvature
import angle
import friction as friction_module
import normal_force as normal_force_module
"""
Calculate the absolute value of the ratio between friction and normal force in each of the 1400 steps
|Friksjon / Normalkraft|
"""
def calculate():
"""Calculate the ratio, and return it as a list"""
# Retrieve friction and normal force list
friction = friction_module.calculate()
normal_force = normal_force_module.calculate()
# Calculate ratio
ratio = []
for i in range(len(friction)):
value = np.abs(friction[i] / normal_force[i])
ratio.append(value)
return ratio
def main():
"""Method to execute when script is invoked"""
# Retrieve ratio list
ratio = calculate()
# Plot the results
utils.plot(
ratio,
y_min=0,
y_max=0.3,
x_label="x (m)",
y_label="|f/N|",
title="Forhold mellom friksjonskraft og normalkraft",
)
# Snippet to run main function when script is executed
if __name__ == "__main__":
main()
|
# Read an integer:
a = input("Pls enter the string ")
try:
result = a.index('f')
result1 = a.rindex('f')
if result == result1:
print(result)
elif result != result1:
print(result, result1)
except ValueError:
print("")
# chudo code
# s = input()
# if s.count('f') == 1:
# print(s.find('f'))
# elif s.count('f') >= 2:
# print(s.find('f'), s.rfind('f')) |
import random
class dice:
def __init__(self, top = 6):
self.top = top
self.score = 1
def roll(self):
self.score = random.randint(1,self.top)
def __repr__(self):
return(str(self.score))
dices = [dice(), dice(4), dice(12)]
playing = True
while playing:
print('you have {0} dice\n'.format(len(dices)))
for ind, die in enumerate(dices, start =1):
print('dice {0}, reads {1}'.format(ind, die.score))
print('Which die would you like to roll?')
choice = input ('please enter the die number, a for all, or x to exit. ')
choice = str(choice)
if choice.isnumeric():
choice = int(choice)
choice = choice -1
dices[choice].roll()
elif 'x' in choice:
playing = False
elif 'a' in choice:
for die in dices:
die.roll()
|
import unittest # Importing the unittest module
from accounts import Account # Importing the user class
class TestAccounts(unittest.TestCase):
'''
Test class that defines test cases for the accounts class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_accounts = Account("facebook", "1234")
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
Account.accounts_list = []
def test_accounts_instance(self):
"""
method to test if the new accounts have been instanciated properly
"""
self.assertEqual(self.new_accounts.account_name, "facebook")
self.assertEqual(self.new_accounts.account_password, "1234")
def test_save_accounts(self):
"""
testcase to test if account objects have been saved
"""
self.new_accounts.save_accounts() # saving the new account
self.assertEqual(len(Account.accounts_list), 1)
def test_delete_accounts(self):
"""
testcase to delete account
"""
self.new_accounts.save_accounts()
test_accounts = Account("facebook","1234")
test_accounts.save_accounts()
self.new_accounts.delete_accounts() #to delete an account object
self.assertEqual(len(Account.account_list),1)
def test_find_accounts_by_name(self):
"""
test to check if accounts by the account name and can display information
"""
self.new_accounts.save_accounts()
test_accounts = Account("facebook","1234")
test_accounts.save_accounts()
def test_display_all_accounts(self):
"""
test to check if all contacts can be veiwed
"""
self.assertEqual(Account.display_accounts(),Account.account_list)
if __name__ == '__main__':
unittest.main() |
#build list of primes from 2 up to and including integer x and compute sum
def isPrime(x,prime_array):
n=0
if x%2==0:
return False
for j in str(x):
n+=int(j)
if n%3==0:
return False
else:
for k in prime_array:
if x%k==0:
return False
return True
#test using subpar algorithm, heavy on mem and time
prime_array = [2,3,5]
for i in range(6,2000000):
if isPrime(i, prime_array):
prime_array.append(i)
print sum(prime_array)
|
import numpy as np
import pandas as pd
class Node:
def __init__(self, value, children, branch_value=None):
"""
:param value: split attribute or, if leaf node, class label
:param children: array of child nodes
:param branch_value: value of branch coming from parent node
"""
self.value = value
self.children = children
self.branch_value = branch_value
# Copied from first stackoverflow result when searching 'print tree python' and modified
# for a quick and dirty printable representation of the decision tree
def __repr__(self, level=0):
ret = "\t" * level + (self.branch_value + ': ' if self.branch_value is not None else '') + self.value + "\n"
for child in self.children:
ret += child.__repr__(level + 1)
return ret
def entropy(examples):
"""
:param examples: list of probabilities
:return: resulting entropy
"""
p = examples[class_index].value_counts() / len(examples)
return np.sum([-px * np.log2(px) for px in p])
def information_gain(examples, target_attr):
"""
:param examples: set of examples to be split
:param target_attr: attribute to be used for split
:return: information gain achieved if split was performed
"""
unique_attributes = examples[target_attr].unique()
remainder = 0
for u_attr in unique_attributes:
u_attr_examples = examples[examples[target_attr] == u_attr]
remainder += len(u_attr_examples) / len(examples) * entropy(u_attr_examples)
return entropy(examples) - remainder
def choose_best_attr(examples, attributes):
"""
:param examples: set of examples for which the best split attribute is to be determined
:param attributes: list of attributes on which the data can be split
:return: split attribute that yields the maximum information gain
"""
ig = {attr: information_gain(examples, attr) for attr in attributes}
return max(ig, key=ig.get)
def gen_tree(examples, attributes, branch_value=None):
"""
Generates decision tree using the ID3 algorithm
:param examples: set of examples which are used for the recursive splitting
:param attributes: list of attributes on which the data can be split
:param branch_value: value of branch coming from parent node
:return: decision tree for given arguments
"""
if examples[class_index].nunique() == 1:
# All examples have same class label, return leaf node with class label
return Node(examples.iloc[0, -1], [], branch_value)
elif len(attributes) == 0:
# No attributes left to split on, return leaf node with majority class label
return Node(examples[class_index].mode()[0], [], branch_value)
else:
# Perform recursive split on attribute which yields highest IG
best = choose_best_attr(examples, attributes)
children = []
# Create child node for each possible attribute value
for av in attribute_values[best]:
examples_av = examples[examples[best] == av]
if len(examples_av) == 0:
# No examples with attribute value left, return leaf node with majority class label of parent node
children.append(Node(examples[class_index].mode()[0], [], av))
else:
# Recursively generate subtree for attribute value av and examples containing av
children.append(gen_tree(examples_av, [a for a in attributes if a != best], av))
return Node(best, children, branch_value)
def classify(node, d):
""" Recursively descends into decision tree according to given decision problem
:param node: root of decision tree to be used for classification
:param d: decision problem dict with attributes as keys
:return: class label
"""
if len(node.children) == 0:
return node.value
attribute_value = d[node.value]
return classify(next(filter(lambda child: child.branch_value == attribute_value, node.children)), d)
df = pd.read_csv('data-cls.csv')
class_index = 'tennis'
all_attributes = df.columns.values[:-1]
attribute_values = {attr: df[attr].unique() for attr in all_attributes}
tree = gen_tree(df, all_attributes)
decision_problem = {'forecast': 'rainy', 'temperature': 'hot', 'humidity': 'high', 'wind': 'strong'}
print(tree)
print('------------------ Task 1 ------------------')
print(f'Classification of problem {decision_problem}: {classify(tree, decision_problem)}')
|
#Common Elements in Two Sorted Arrays
#Write a function that returns the common elements (as an array) between two sorted arrays of integers (ascending order).
#Example: The common elements between [1, 3, 4, 6, 7, 9] and [1, 2, 4, 5, 9, 10] are [1, 4, 9].
#O(max(n,m)) where n is the number of items of the first array and m the number of items of the second array
#REMINDER: We're going to use lists instead of arrays in Python for simplicity.
# Function implementation.
def common_elements(list1, list2):
result = []
index1 = 0
index2 = 0
while index1 < len(list1) and index2 < len(list2):
if list1[index1] == list2[index2]:
result.append(list1[index1])
index1 += 1
index2 += 1
elif list1[index1] > list2[index2]:
index2 += 1
else:
index1 += 1
return result
# NOTE: The following input values will be used for testing your solution.
list_a1 = [1, 3, 4, 6, 7, 9]
list_a2 = [1, 2, 4, 5, 9, 10]
# common_elements(list_a1, list_a2) should return [1, 4, 9] (a list).
list_b1 = [1, 2, 9, 10, 11, 12]
list_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15]
# common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list).
list_c1 = [0, 1, 2, 3, 4, 5]
list_c2 = [6, 7, 8, 9, 10, 11]
# common_elements(list_c1, list_c2) should return [] (an empty list).
result = common_elements(list_b1, list_b2)
print(result)
result = common_elements(list_a1, list_a2)
print(result)
result = common_elements(list_c1, list_c2)
print(result) |
#import OS and CSV
import os
import csv
from collections import Counter
#import the csv and show the csv
with open('Resources/election_data.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
# print(csvreader)
csv_header = next(csvreader)
# print(f"pybank: {csv_header}")
# for row in csvreader:
# print(row)
#spaces for answers
totalVotes=[]
numvotes=0
allCandidates=[]
iVote=Counter()
percent=[]
winner=[]
#Corry=0
#Li=0
# Khan=0
# otooley=0
for row in csvreader:
allCandidates.append(row[2])
numvotes = len(allCandidates)
for name in allCandidates:
iVote[name]+=1
victor= max(zip(iVote.values(), iVote.keys()))
candidates=tuple(iVote.keys())
votes=tuple(iVote.values())
for x in votes:
percent.append((int(x)/numvotes)*100)
print (f"number of voters:{numvotes}")
print ("names of the candidates: Corry, Li, Khan, O'Tooley ")
for x in range(len(candidates)):
print(candidates[x] + ":" + str(round(percent[x],1))+ "%" + str(votes[x]))
print(f"winner:" +victor[1])
with open("output.txt", "w") as new:
new.write("names of the candidates: Corry, Li, Khan, O'Tooley ")
new.write("\n")
for x in range(len(candidates)):
new.write(candidates[x] + ":" + str(round(percent[x],1))+ "%" + str(votes[x]))
new.write("\n")
new.write(f"winner:" +victor[1])
|
"""Reference: https://docs.python-guide.org/writing/logging/
"""
import logging
def get_logger(name: str, level: int = logging.DEBUG):
"""Sets up a logger.
Parameters
----------
name: str
The module name
level: int, optional
The logging level, by default logging.DEBUG
"""
logger = logging.getLogger(name)
logger.setLevel(level=level)
log_handler = logging.StreamHandler()
log_formatter = logging.Formatter(
"%(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)"
)
log_handler.setFormatter(log_formatter)
logger.addHandler(log_handler)
logger.propagate = False
return logger
|
# Написать функцию которая принимает на вход число от 1 до 100. Если число равно 13,
# функция поднимает исключительную ситуации ValueError иначе возвращает введенное число,
# возведенное в квадрат.
# Далее написать основной код программы. Пользователь вводит число. Введенное число передаем
# параметром в написанную функцию и печатаем результат, который вернула функция.
# Обработать возможность возникновения исключительной ситуации,
# которая поднимается внутри функции.
def excep(question):
number = int(input(question))
if number > 1 or number < 100:
if number == 13:
raise ValueError("Число 13!!!")
else:
return number ** 2
try:
number = excep("Введите число: ")
print(number)
except Exception:
print('Что-то пошло не так') |
# Дан список, заполненный произвольными числами. Получить список из элементов исходного, удовлетворяющих следующим условиям:
# Элемент кратен 3,
# Элемент положительный,
# Элемент не кратен 4.
#
# Примечание: Список с целыми числами создайте вручную в начале файла.
# Не забудьте включить туда отрицательные числа. 10-20 чисел в списке вполне достаточно.
import random
rnd_list = [random.randint(-100, 100) for i in range(1,20)]
print(rnd_list)
result = [number for number in rnd_list if number%3 == 0 and number > 0 and number%4 != 0]
print(result)
|
# Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(num1, num2, num3):
sum1 = num1 + num2
sum2 = num2 + num3
sum3 = num1 + num3
result = max(sum1, sum2, sum3)
print(result)
my_func(19,14,29) |
# Игра угадай число
import random
def game():
# Компьютер загадывает число
comp_num = random.randint(1, 100)
# print(comp_num)
# Выбираем количество пользователей
num_players = 0
while num_players < 1 or num_players > 4:
num_players = int(input("Введите количество игроков: "))
# Задаем имена игроков
player_names = []
for i in range(num_players):
name = input(f'Введите имя игрока {i}: ')
player_names.append(name)
print(player_names)
#Создаем переменную пользовательского числа
hum_num = None
# Задаем уровни сложности
difficulties = (1, 4, 10, 20)
difficult = -1
while difficult < 0 or difficult > 3:
difficult = int(input("Выберите уровень сложности от 0 до 3: "))
else:
pass
max_count = difficulties[difficult]
#Запускаем цикл угадывания числа
is_winner = False
winner_name = ""
for i in range(max_count):
print("Попытка №: ", i + 1)
for player in player_names:
print(f"Ход игрока {player}")
hum_num = int(input("Введите число от 1 до 100: "))
if hum_num == comp_num:
print("Вау! Вы угадали")
print("Уложились в", i + 1, "попыток")
is_winner = True
winner_name = player
break
elif hum_num > comp_num:
print("Число больше, чем должно быть")
else:
print("Число меньше")
if is_winner:
print(f"Выиграл пользователь {winner_name}")
break
if i == max_count - 1:
print("Вы проиграли")
if __name__ == '__main__':
game() |
'''Helper functions for machine learning.'''
import numpy as np
def angle_to_cos_sin(angle):
'''Convert an angle in radian to its cos and sin.
This useful to preserve the topology of periodic features.
'''
return [np.cos(angle), np.sin(angle)]
def cos_sin_to_angle(cos, sin):
'''Get an angle from its cos and sin.
The range of the angle is [-pi, -pi]
'''
return np.arctan2(sin, cos)
|
import numpy as np
from PIL import Image
class GreyImage:
""" Класс, преобразующий картинку в черно-белый пиксель-арт
Тест значения градации изображения
>>> res = GreyImage(np.array(Image.open('picture.jpg')), 10, 100)
>>> res.grad
2
Тест размера блока
>>> res = GreyImage(np.array(Image.open('picture.jpg')), 75, 10)
>>> res.size
75
"""
def __init__(self, pix_array, pix_size=10, gradation=50):
self.image = np.array(pix_array)
self.size = pix_size
self.grad = 255 // gradation
self.width = len(self.image)
self.height = len(self.image[0])
def get_grey_image(self):
""" Преобразование картинки в черно-белую, пиксельную
Тест размера полученной картинки
>>> GreyImage(np.array(Image.open('picture.jpg')), 10, 50).get_grey_image().size
(1920, 1080)
>>> GreyImage(np.array(Image.open('picture_2.jpg')), 10, 50).get_grey_image().size
(750, 750)
:return: черно-белая картинка
"""
for x in range(0, self.width, self.size):
for y in range(0, self.height, self.size):
self.image[x:x + self.size, y:y + self.size] = self.get_middle_color(x, y)
return Image.fromarray(self.image)
def get_middle_color(self, x, y):
"""
Закрашивает блок пикселей одной градацией серого цвета и вычисляет среднее значение яркости блока
:param get_middle_color: Поиск нужного цвета
:param x: координата пикселя по оси x
:param y: координата пикселя по оси y
:return: Среднее значение яркости
Тест исходной картинки
>>> GreyImage(np.array(Image.open('picture.jpg')), 10, 50).get_middle_color(1,1)
170
Тест черно-белой картинки
>>> GreyImage(np.array(Image.open('pics/new_pic.jpg')), 10, 50).get_middle_color(1,1)
155
"""
return int(self.image[x:x + self.size, y:y + self.size].sum() / 3 // self.size ** 2 // self.grad * self.grad)
flag = 'no'
while flag == 'no':
print('Введите название картинки')
orig_img = Image.open('{}'.format(input()))
print('Выберите величину ячейки, на которую будут делить изображение\n' +
'Размер должен быть инициализирован целым положительным числом')
pic_size = int(input())
print('Выберите количество оттенков\n' +
'Количество должно быть инициализировано целым положительным числом')
grad = int(input())
arr = GreyImage(orig_img, pix_size=pic_size, gradation=grad).get_grey_image()
print('Введите название новой картинки')
name = input()
print('Введите формат новой картинки(jpg, png и т.д.)')
formt = input()
arr.save('{}.{}'.format(name, formt))
print('Если хотите завершить сессию, наберите \'yes\', если нет-нажмите enter')
if input() == 'yes':
flag = 'yes'
|
from math import exp
from functions import Differentiable
class Sigmoid(Differentiable):
"""The Sigmoid activation function."""
@staticmethod
def f(x):
return 1.0 / (1.0 + exp(-x))
@staticmethod
def df(x):
return Sigmoid.f(x) * (1 - Sigmoid.f(x))
class ReLU(Differentiable):
"""The ReLU activation function."""
@staticmethod
def f(x):
return x if x > 0 else 0
@staticmethod
def df(x):
return 1 if x > 0 else 0
|
while(1):
num = input()
if(num == '0 0'):
break
num = num.split()
result = int(num[0])+ int(num[1])
print(result) |
class Warrior:
health = 50
attack = 5
is_alive = True
class Knight():
health = 50
attack = 7
is_alive = True
def fight(unit_1, unit_2):
while True :
unit_2.health -= unit_1.attack
print(unit_2.health)
if(unit_2.health <= 0):
unit_2.is_alive = False
break
unit_1.health -= unit_2.attack
if(unit_1.health <= 0):
unit_1.is_alive = False
break
if(unit_1.is_alive==True):
return True
else:
return False
chuck = Warrior()
bruce = Warrior()
print(fight(chuck,bruce))
|
import math
import random
class Point :
def __init__(self, X, Y):
self.X = X
self.Y = Y
def distanceFrom(self, B):
return math.sqrt((self.X - B.X)**2 + (self.Y - B.Y)**2)
def distanceFromOrigin(self):
O = Point(0, 0)
return self.distanceFrom(O)
def display(self):
print(f"({self.X} , {self.Y})")
def isInRedSurface(self) :
return self.distanceFrom(Point(2, 2)) > 2
@staticmethod
def randomPoint():
x = 2 * random.random()
y = 2 * random.random()
return Point(x, y) |
"""
VKİ 18 ile < 25 aralığındaysa normal,
VKİ 25 ile <30 aralığındaysa kilolu,
VKİ 30 ve daha yüksekse obez,
VKİ 35 ve daha fazlaysa ciddi obez olarak kabul edilir.
VKİ’ni hesaplayarak kişinin durumunu yazdırınız
(VKİ=ağırlık/(boy*boy), boymetre cinsinden verilmeli)
try:
hata oluşabilecek satıralr
except:
hata oluşursa burası çalışacak
"""
while True:
try :
agr=float(input("Lütfen kilonuzu giriniz : "))
boy=float(input("Lütfen boyunuzu metre cinsinden giriniz : "))
except:
print("Lütfen geçerli bir sayı giriniz.")
continue
vki=agr/boy**2
print(vki)
if 18<=vki<25:
print("Kilonuz Gayet Normal Afferim..")
elif 25<=vki<30:
print("Fazla kilo Almışsın azıcık şu boğazını kıs...")
elif 30<=vki<35:
print("Abooo kız sana nolmuş??")
else:
print("Allah affetsin...")
break
|
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 15:05:42 2018
Chromosomes are a list of genes, in this case each element in the list represents a morphologial operator:
0: No operator
1: Erosion
2: Dilation (opposite of erosion)
3: Opening (erosion followed by dilation)
4: Closing (dilation followed by erosion)
5: Gradient (difference between dilation and erosion of an image)
5: Thinning <--- not yet implemented
6: Thickening <--- not yet implemented
@author: etcyl
"""
import random
class chromosome():
def __init__(self, length):
self.accuracy = 0#random.randint(0, 99) #Accuracy of an SVM, when it sequentially applies the genes to an image
self.genes = [0]*length #Storage for an individual
for i in range(length): #For all the genes in the list, 50% for the current element to be present or absent
if(random.randint(0, 1) == 1):
self.setGene(i, random.randint(1, 5)) #Random value was 1 so the gene is present
else:
self.setGene(i, 0) #Random value was 0 so the gene is absent
def toggleGene(self, index): #Turn the gene on or off
self.genes[index] = 0
def getGene(self, index):
return self.genes[index]
def setGene(self, index, value):
self.genes[index] = value
def getAccuracy(self):
return self.accuracy
def setAccuracy(self, new_accuracy):
self.accuracy = new_accuracy
def getChromosome(self):
return self.genes
def setChromosome(self, genes):
self.genes = genes
|
from tetrimino import *
rows, colns = 20, 10
board = create_board(rows, colns)
tet = O
tet["pos"] = (18, 0)
place(tet, board)
tet["pos"] = (8, 0)
place(tet, board)
tet["pos"] = (0, 8)
place(tet, board)
print(board)
move_left(tet, board)
place(tet, board)
print(board)
tet["pos"] = (0, 0)
place(tet, board)
print(board)
move_right(tet, board)
print(board)
move_down(tet, board)
place(tet, board)
tet["pos"] = (18, 8)
move_down(tet, board)
place(tet, board)
print(board)
move_right(tet, board)
print(board)
tet = L
# L["pos"] = (0, 5)
# place(L, board)
# print(board)
# rotate_clockwise(L, board)
# print(board)
# rotate_anticlockwise(L, board)
# print(board)
|
x=input("enter number to check")
for i in range(2,x):
if x%i==0:
print"it is not a prime number"
break
else:
print"its a prime number"
break |
# class Users:
# name="Sunday"
# location="Okeho"
# def __init__(self):
# self.name="Sunday"
# self.age=12
# self.address="32 Asiwaju Omidiran Way, Orita-Sabo"
# person = Users()
# print(person.location)
# print(person.name)
class Users:
def __init__(self, name="Sunday Opeyemi", age=2, address="32, Asiwaju Omidiran"):
self.name=name
self.age=age
self.address=address
def login(self, email, password):
email
user1=Users()
print(user1.email)
# print(user1.age)
# print(user1.address) |
'''
- Leia a idade do usuário e classifique-o em:
- Criança – 0 a 12 anos
- Adolescente – 13 a 17 anos
- Adulto – acima de 18 anos
-Se o usuário digitar um número negativo, mostrar a mensagem que a idade é inválida
2- Calcular a média de um aluno que cursou a disciplina de Programação I, a
partir da leitura das notas M1, M2 e M3; passando por um cálculo da média
aritmética. Após a média calculada, devemos anunciar se o aluno foi aprovado,
reprovado ou pegou exame
- Se a média estiver entre 0.0 e 4.0, o aluno está reprovado
- Se a média estiver entre 4.1 e 6.0, o aluno pegou exame
- Se a média for maior do que 6.0, o aluno está aprovado
- Se o aluno pegou exame, deve ser lida a nota do exame. Se a nota do exame for
maior do que 6.0, está aprovado, senão; está reprovado
'''
#primeira parte
idade = int(input('digite a sua idade:\n'))
if idade < 0:
print('idade invalida')
elif idade < 13:
print('crianca')
elif idade < 18:
print('adolescente')
else:
print('adulto')
#segunda parte
m1 = int(input('digite a sua nota 1\n'))
m2 = int(input('digite a sua nota 2\n'))
m3 = int(input('digite a sua nota 3\n'))
media = (m1 + m2 + m3) / 3
if media <= 4:
print('reprovado')
elif media <= 6:
print('exame')
nota_exame = float(input('digite a nota do exame:\n'))
if nota_exame > 6:
print('aprovado')
else:
print('reprovado')
elif media > 6:
print('aprovado') |
money=int(input("Beloppet som ska betalas : "))
if 500<=money :
print(f"Det är {int(money/500)} 500 lappar, {int((money%500)/100)} 100 lappar och {money%100} kronor")
elif money>=100 :
print(f"Det är {int(money/100)} 100 lappar, och {money%100} kronor")
else :
print(f"Det är {money} kronor") |
country = input("Mata in landet där du bor : ")
if country == "Sverige" or country == "Danmark" or country == "Norge" :
print ("Du bor i Skandinavien")
else :
print("Du bor inte i Skandinavien")
|
#!/usr/bin/python3.8
import numpy as np
import pandas as pd
class Labelling:
@staticmethod
def _compute_threshold(stable_to_crypto, fees):
"""
compute threshold for going stable to crypto or crypto to stable given fees.
Parameters
----------
stable_to_crypto : bool
fees : float
transaction fees
Returns
-------
float
"""
if stable_to_crypto:
thresh = 1 / (1 - fees)**2
else:
thresh = (1 - fees)**2
return thresh
@staticmethod
def compute_labels(streak_rdt, t0, T, fees):
"""
given a series of expected return from a pair X/Y will create 2 vectors of labels :
- first : label 1 we must sell X for Y, label 0 we must do nothing (don't move)
- second : label 1 we must sell Y for X, label 0 we must do nothing (don't move)
These labels are obtained by looking at future data, so the function also return 2 vectors called index_knowledge which notice at what time (in the future)
the information was found.
Finally, 2 vectors of wheights for each labels are also provided as cumprod of expected return since t to t+h, h belongs to [1,T].
In brief:
first vector of labels answers to the question, if I am long on X at time t : should I buy Y or not? And this for each t belongs to [t0,T].
second vector of labels answers to the question, if I am long on Y at time t : should I buy X or not? And this for each t belongs to [t0,T].
Parameters
----------
streak_rdt : numpy.ndarray
expected return
t0 : int
start
T : int
end
fees : float
transaction fees
Returns
-------
numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray
labelsXtoY, labelsYtoX, weightsXtoY, weightsYtoX, index_knowledgeXtoY, index_knowledgeYtoX
"""
actions_crypto_to_stable = np.full(shape=len(streak_rdt[t0:T]), fill_value=2, dtype=np.uint8)
actions_stable_to_crypto = np.full(shape=len(streak_rdt[t0:T]), fill_value=2, dtype=np.uint8)
weights_crypto_to_stable = np.empty(shape=len(streak_rdt[t0:T]))
weights_stable_to_crypto = np.empty(shape=len(streak_rdt[t0:T]))
index_knowledge_crypto_to_stable = np.zeros(shape=len(streak_rdt[t0:T]), dtype=np.uint8)
index_knowledge_stable_to_crypto = np.zeros(shape=len(streak_rdt[t0:T]), dtype=np.uint8)
idx = np.arange(len(streak_rdt[t0:T]))
cumprod_rdt = np.cumprod(1 + streak_rdt[t0:T])
thresh_stable_to_crypto = __class__._compute_threshold(stable_to_crypto=True, fees=fees)
thresh_crypto_to_stable = __class__._compute_threshold(stable_to_crypto=False, fees=fees)
for i in range(len(streak_rdt[t0:T-1])):
cumprod_sliced = cumprod_rdt[i+1:T] / cumprod_rdt[i]
idx_sliced = idx[i+1:T] - (i+1) # - (i+1) for starting at 0.
# m1 : find the first time both conditions will met.
argmin_c1 = next((x[0] for x in zip(idx_sliced, cumprod_sliced) if x[1] > thresh_stable_to_crypto), T - (t0 + i + 2))
argmin_c2 = next((x[0] for x in zip(idx_sliced[:argmin_c1], cumprod_sliced[:argmin_c1]) if x[1] < 1), T - (t0 + i + 2))
# which condition occur first ?
is_c1_occur_first = True if argmin_c1 < argmin_c2 else False
if is_c1_occur_first:
actions_stable_to_crypto[i] = 1
weights_stable_to_crypto[i] = cumprod_sliced[argmin_c1]
index_knowledge_stable_to_crypto[i] = i + argmin_c1 + 1
else:
actions_stable_to_crypto[i] = 0
weights_stable_to_crypto[i] = cumprod_sliced[argmin_c2]
index_knowledge_stable_to_crypto[i] = i + argmin_c2 + 1
# m2 : find the first time both conditions will met.
argmin_c1 = next((x[0] for x in zip(idx_sliced, cumprod_sliced) if x[1] < thresh_crypto_to_stable), T - (t0 + i + 2))
argmin_c2 = next((x[0] for x in zip(idx_sliced[:argmin_c1], cumprod_sliced[:argmin_c1]) if x[1] > 1), T - (t0 + i + 2))
# which condition occur first ?
is_c1_occur_first = True if argmin_c1 < argmin_c2 else False
if is_c1_occur_first:
actions_crypto_to_stable[i] = 1
weights_crypto_to_stable[i] = cumprod_sliced[argmin_c1]
index_knowledge_crypto_to_stable[i] = i + argmin_c1 + 1
else:
actions_crypto_to_stable[i] = 0
weights_crypto_to_stable[i] = cumprod_sliced[argmin_c2]
index_knowledge_crypto_to_stable[i] = i + argmin_c2 + 1
# fill last value, unknown because no access to future
actions_stable_to_crypto[-1], actions_crypto_to_stable[-1], weights_stable_to_crypto[-1], weights_crypto_to_stable[-1] = 0, 0, 0, 0
return actions_stable_to_crypto, actions_crypto_to_stable, weights_stable_to_crypto, weights_crypto_to_stable, index_knowledge_stable_to_crypto,\
index_knowledge_crypto_to_stable
@staticmethod
def compute_optimal_actions(streak_rdt, t0, T, fees, position_start=0):
"""
given a vector of expected return will compute for each time if we must switch position or not.
action = 1 -> stay on crypto or buy crypto (sell stable).
action = 0 -> stay on stable or buy stable (sell crypto).
NB: action(t) depends to action(t-1) because action(t) <=> position(t+1), unlike method compute_labels.
Parameters
----------
streak_rdt : numpy.ndarray
expected return
t0 : int
start
T : int
end
fees : float
transaction fees
position_start : int, optional
by default 0
Returns
-------
numpy.ndarray
for each time, the action that maximizes portfolio.
"""
current_position = position_start
optimal_actions = np.full(shape=len(streak_rdt[t0:T]), fill_value=2, dtype=np.uint8)
idx = np.arange(len(streak_rdt[t0:T]))
cumprod_rdt = np.cumprod(1 + streak_rdt[t0:T])
thresh_stable_to_crypto = __class__._compute_threshold(stable_to_crypto=True, fees=fees)
thresh_crypto_to_stable = __class__._compute_threshold(stable_to_crypto=False, fees=fees)
for i in range(len(streak_rdt[t0:T-1])):
cumprod_sliced = cumprod_rdt[i+1:T] / cumprod_rdt[i]
idx_sliced = idx[i+1:T] - (i+1) # - (i+1) for starting at 0.
# long stable
if not current_position:
# m1 : find the first time both conditions will met.
argmin_c1 = next((x[0] for x in zip(idx_sliced, cumprod_sliced) if x[1] > thresh_stable_to_crypto), T - (t0 + i + 2))
argmin_c2 = next((x[0] for x in zip(idx_sliced[:argmin_c1], cumprod_sliced[:argmin_c1]) if x[1] < 1), T - (t0 + i + 2))
# which condition occur first ?
is_c1_occur_first = True if argmin_c1 < argmin_c2 else False
if is_c1_occur_first:
optimal_actions[i] = 1
else:
optimal_actions[i] = 0
# long crypto
else:
# m2 : find the first time both conditions will met.
argmin_c1 = next((x[0] for x in zip(idx_sliced, cumprod_sliced) if x[1] < thresh_crypto_to_stable), T - (t0 + i + 2))
argmin_c2 = next((x[0] for x in zip(idx_sliced[:argmin_c1], cumprod_sliced[:argmin_c1]) if x[1] > 1), T - (t0 + i + 2))
# which condition occur first ?
is_c1_occur_first = True if argmin_c1 < argmin_c2 else False
if is_c1_occur_first:
optimal_actions[i] = 0
else:
optimal_actions[i] = 1
current_position = optimal_actions[i]
# fill last value, unknown because no access to future
optimal_actions[-1] = 0
return optimal_actions
if __name__ == "__main__":
# example of use and quick test
# settings
path_data = "data/preprocessed/preproc_BTCUSDT_1h_f0.00075_2017-09-28_02:00:00_to_2021-01-31_20:00:00.csv"
# run
df = pd.read_csv(path_data, index_col=0)
optimal_actions = Labelling.compute_optimal_actions(streak_rdt=df.rdt_crypto_1h.values, t0=0, T=len(df.rdt_crypto_1h), fees=0.00075)
labels_weights_index = Labelling.compute_labels(streak_rdt=df.rdt_crypto_1h.values, t0=0, T=len(df.rdt_crypto_1h), fees=0.00075)
print(f"optimal_actions: {optimal_actions}")
print(f"labels_stable_to_crypto: {labels_weights_index[0]}")
print(f"labels_crypto_to_stable: {labels_weights_index[1]}")
print(f"weights_stable_to_crypto: {labels_weights_index[2]}")
print(f"weights_crypto_to_stable: {labels_weights_index[3]}")
print(f"index_knowledge_stable_to_crypto: {labels_weights_index[4]}")
print(f"index_knowledge_crypto_to_stable: {labels_weights_index[5]}")
|
from program2_2 import Dmatrix
ROW = 3 # 行の要素数
COLUMN = 4 # 列の要素数
def main():
global ROW, COLUMN
a = Dmatrix(1, ROW, 1, COLUMN) # 行列 a[1...ROW][1...COLUMN]
b = Dmatrix(1, ROW, 1, COLUMN) # 行列 b[1...ROW][1...COLUMN]
# 行列の定義
for i in range(1, ROW+1):
for j in range(1, COLUMN+1):
a[i][j] = 2.0 * (i + j)
b[i][j] = 3.0 * (i + j)
# 行列の和の計算
c = matrix_sum(a, b)
# 結果の表示
print("行列 A と行列 B の和は次の通りです")
for i in range(1, ROW+1):
for j in range(1, COLUMN+1):
print(c[i][j], end=" ")
print()
# 行列の和
# a[m1...m2][n1...n2] と b[m1...m2][n1...n2] の和を求める.
def matrix_sum(a: Dmatrix, b: Dmatrix):
m1, m2 = a.row_head_idx, a.row_last_idx
n1, n2 = a.col_head_idx, a.col_last_idx
c = Dmatrix(m1, m2, n1, n2)
for i in range(m1, m2+1):
for j in range(n1, n2+1):
c[i][j] = a[i][j] + b[i][j]
return c
if __name__ == "__main__":
main() |
def main():
n = 100
print(f"2.0/(x*x) を [1,2] で積分します. 分割数は{n}です")
print("結果は{:20.15f} です".format(trapezoidal(1.0, 2.0, n, func1)))
print(f"4.0/(1+x*x) を [0,1] で積分します. 分割数は{n}です")
print("結果は{:20.15f} です".format(trapezoidal(0.0, 1.0, n, func2)))
# 台形公式
def trapezoidal(a: float, b: float, n: int, f) -> float:
h = ( b - a ) / n # 刻み幅の指定
# 台形公式
T = (f(a) + f(b)) / 2.0
for i in range(1, n):
T += f(a + i*h)
T *= h
return T
# 関数の定義
def func1(x: float) -> float:
return 2.0 / (x * x)
def func2(x: float) -> float:
return 4.0 / (1.0 + x*x)
if __name__ == "__main__":
main() |
import itertools
import string
import typing
# Chunk iterators
def chunk(iterable: typing.Iterable[typing.Any], chunk_size: int) -> typing.Iterator[typing.List[typing.Any]]:
'''Splits the given iterable into chunks of a fixed size'''
iterator = iter(iterable)
while True:
chunk_iterator = itertools.islice(iterator, chunk_size)
chunk = list(chunk_iterator)
if not chunk:
return
# Bring common types back to their original
# A string should be chunked into a list of strings, not a list of lists of characters
if isinstance(iterable, str):
chunk = ''.join(chunk)
elif isinstance(iterable, bytes):
chunk = bytes(chunk)
yield chunk
# Hex dumps
_hexdump_print = set(string.printable) - set('\f\v\t\n\r')
def hexdump(data: typing.Iterable[int], chunk_size: int = 16) -> typing.Iterator[str]:
'''Formats a hexdump, with chunk_size bytes per line'''
offset = 0
for block in chunk(data, chunk_size):
# Hex-encode all the bytes
encoded_bytes = ('{:02X}'.format(b) for b in block)
# Add extra spacing if the chunk size is a multiple of 8
if chunk_size % 8 == 0 and chunk_size > 8:
blocks = (' '.join(block) for block in chunk(encoded_bytes, 8))
encoded_chunk = ' '.join(blocks)
expected_length = 3 * chunk_size - 1 + (chunk_size // 8 - 1)
else:
encoded_chunk = ' '.join(encoded_bytes)
expected_length = 3 * chunk_size - 1
encoded_chunk += ' ' * (expected_length - len(encoded_chunk))
# Create the ASCII representation
chars = (chr(b) for b in block)
ascii_chunk = ''.join(c if c in _hexdump_print else '.' for c in chars)
# Format the entire thing
yield '{:08X}: {} {}'.format(offset, encoded_chunk, ascii_chunk)
def parse_hexdump(data: str) -> bytes:
'''Parses a hexdump (in the general format produced by hexdump(...))'''
result = b''
# In each line, extract the hex-encoded bytes in the middle
for line in data.split('\n'):
line = line.strip()
middle = line.split(' ', 1)[1].rsplit(' ', 1)[0].strip()
# ... and add them to the result
result += bytes.fromhex(result.replace(' ', ''))
return result
|
from collections import defaultdict
class CastleKilmereMember:
"""
Creates a member of the Castle Kilmere School of Magic
"""
def __init__(self, name: str, birthyear: int, sex: str):
self._name = name
self.birthyear = birthyear
self.sex = sex
self._traits = defaultdict(lambda: False)
def add_trait(self, trait, value=True):
self._traits[trait] = value
def exhibits_trait(self, trait):
value = self._traits[trait]
if value:
print(f"Yes, {self._name} is {trait}!")
else:
print(f"No, {self._name} is not {trait}!")
return value
if __name__ == "__main__":
bromley = CastleKilmereMember('Bromley Huckabee', '1959', 'male')
bromley.add_trait('tidy-minded')
bromley.add_trait('kind')
bromley.exhibits_trait('kind')
bromley.exhibits_trait('mean')
|
import numpy as np
#arr = np.array([1,2,3,])
#print(arr)
#arr = np.array([[1,2,3],[4,5,6]])
#print(arr)
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(arr) |
#https://www.geeksforgeeks.org/python-programming-examples/#simple
#max of numbers
num1=input("enter num1")
num2=input("enter num2")
if num1 > num2:
print("{0} is bigger number than {1}".format(num1,num2))
elif num1 < num2:
print("{0} is bigger number than {1}".format(num2, num1))
else:
print("{0} is equal to {1}".format(num2, num1))
max_num = max(num1,num2)
min_of_num = min(num1,num2)
print("using max function {0}".format(max_num))
print("using min function {0}".format(min_of_num))
max_num_multiple_input = max(23, 76, 11, 90, 76)
print("using max function {0}".format(max_num_multiple_input))
min_num_multiple_input = min(23,76,11,90,76)
print("using max function {0}".format(min_num_multiple_input))
|
# NameComics.py
""" This Python Script Will re-name Comic files """
# Import Statement
import os
import re
def main():
"""
Main Function, which will re-name comics to desired format.
### Comic Name.pdf
"""
directory = "/Users/ramanmehat/Desktop/Re-name Comics"
remove_unwanted_stings(directory)
rearrange_comic_issue_number(directory)
def remove_unwanted_stings(directory):
""" This function will remove any un-wanted strings from the comic name"""
for fileName in os.listdir(directory):
src = os.path.join(directory, fileName)
if "GetComics.INFO" in fileName:
new_file_name = fileName.replace("GetComics.INFO", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(Webrip) (The Last Kryptonian-DCP)" in fileName:
new_file_name = fileName.replace("(Webrip) (The Last Kryptonian-DCP)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(The Last Kryptonian-DCP)" in fileName:
new_file_name = fileName.replace("(The Last Kryptonian-DCP)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(BlackManta-Empire)" in fileName:
new_file_name = fileName.replace("(BlackManta-Empire)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(Son of Ultron-Empire)" in fileName:
new_file_name = fileName.replace("(Son of Ultron-Empire)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(Digital) (AnHeroGold-Empire)" in fileName:
new_file_name = fileName.replace("(Digital) (AnHeroGold-Empire)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(Webrip)" in fileName:
new_file_name = fileName.replace("(Webrip)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(Digital)" in fileName:
new_file_name = fileName.replace("(Digital)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif "(digital)" in fileName:
new_file_name = fileName.replace("(digital)", "").replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
for fileName in os.listdir(directory):
src = os.path.join(directory, fileName)
start = fileName.find('(')
end = fileName.rfind(')')
if start != -1:
remove_string = fileName[start: end + 1]
new_file_name = fileName.replace(remove_string, '').replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
for fileName in os.listdir(directory):
src = os.path.join(directory, fileName)
start = fileName.find('v')
start2 = fileName.find('V')
end = start + 2
end2 = start2 + 2
if start != -1 and int(start + 1):
remove_string = fileName[start: end + 1]
new_file_name = fileName.replace(remove_string, '').replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif start2 != -1 and int(start + 1):
remove_string = fileName[start2: end2 + 1]
new_file_name = fileName.replace(remove_string, '').replace(' .pdf', '.pdf')
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
def rearrange_comic_issue_number(directory):
""" This function will put the comic issue number at the front of the comic name"""
new_file_name = []
for fileName in os.listdir(directory):
src = os.path.join(directory, fileName)
comic_issue = re.findall(r'\d+', fileName)
if len(comic_issue) is 1:
intermediate_file_name = fileName.replace(comic_issue[0], "").replace(' .pdf', '.pdf')
if len(comic_issue[0]) >= 3:
new_file_name = comic_issue[0] + ' ' + intermediate_file_name
elif len(comic_issue[0]) is 2:
new_file_name = '0' + comic_issue[0] + ' ' + intermediate_file_name
elif len(comic_issue[0]) is 1:
new_file_name = '00' + comic_issue[0] + ' ' + intermediate_file_name
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif len(comic_issue) is 2:
intermediate_file_name = fileName.replace(comic_issue[1], "").replace(' .pdf', '.pdf')
if len(comic_issue[1]) >= 3:
new_file_name = comic_issue[1] + ' ' + intermediate_file_name
elif len(comic_issue[1]) is 2:
new_file_name = '0' + comic_issue[1] + ' ' + intermediate_file_name
elif len(comic_issue[1]) is 1:
new_file_name = '00' + comic_issue[1] + ' ' + intermediate_file_name
dst = os.path.join(directory, new_file_name)
os.rename(src, dst)
elif len(comic_issue) is 0:
pass
else:
print("Lets Go Man To Many Numbers :p")
if __name__ == '__main__':
# Calling main() function
main()
|
def solution(phoneBook):
phoneBook = sorted(phoneBook)
#리스트 for을 하면 어차피 다은꺼 가져오니깐 zip으로 묶음
for p1, p2 in zip(phoneBook, phoneBook[1:]):
if p2.startswith(p1):
return False
return True |
# def solution(priorities, location):
# answer = list()
# # 1. 가장 큰 위치 찾기 (index)
# # 2. 그 전까지의 위치를 위로 땡기기
# _get = priorities[location]
# big_index = priorities.index(max(priorities))
# answer = priorities[big_index:] + priorities[:big_index]
# if big_index <= location:
# b=answer.index(_get)+1
# else:
# b=answer.index(_get)+len(priorities[big_index:])
# return b
# print(solution([1, 1, 1, 1, 1, 1],3))
# def solution(priorities, location):
# before_dict = dict()
# change_dict = dict()
# for count, i in enumerate(priorities):
# before_dict[count]=i
# # location 위치 찾기
# big_index = priorities.index(max(priorities))
# # test dictionary 분리한것 test2에 넣기
# for key, value in before_dict.items():
# if key >= big_index:
# change_dict[key] = value
# for key, value in before_dict.items():
# if key < big_index:
# change_dict[key] = value
# answer_list = list(change_dict.keys())
# return answer_list.index(location)+1
# print(solution([1, 2, 3, 4],2))
# 위에는 테스트 케이스가 별로 없어 문제 이해를 잘 못해서 저지른 ㅠㅠ
def solution(priorities, location):
a = priorities.copy()
priorities = list(enumerate(priorities))
count = 0
while priorities:
if priorities[0][1] == max(a):
count = count + 1
if location == priorities[0][0]:
break
priorities = priorities[1:] + priorities[0:1]
a = a[1:] + a[0:1]
priorities.pop()
a.pop()
else:
priorities = priorities[1:] + priorities[0:1]
a = a[1:] + a[0:1]
return count
print(solution([1, 2, 3, 4],2)) |
#이거 안된다고 합니다... 왜 안됐는지는 잘 모르겠습니다 ㅠㅠ
def solution(numbers, hand):
#누른 것 위치 저장 필요
left_save_current = 10
right_save_current = 12
answer = ''
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
]
for i in numbers:
if i in (1, 4, 7, '*'):
answer = answer + 'L'
left_save_current = i
elif i in (3, 6, 9, '#'):
answer = answer + 'R'
right_save_current = i
else:
if i == 0:
i = 11
if i == '*':
i = 10
if i == '#':
i = 12
#왼손 거리 찾기
#배열 위치의 값
if i == a[(right_save_current-1)//3][(right_save_current-1)%3]:
answer = answer + 'R'
right_save_current = i
continue
elif i == a[(left_save_current-1)//3][(left_save_current-1)%3]:
answer = answer + 'L'
right_save_current = i
continue
left_count2 = 0
right_count2 = 0
count2 = 0
for m in range((i-1)//3,-1,-1): #위쪽
if a[m][(i-1)%3] == a[(left_save_current-1)//3][(left_save_current-1)%3]:
left_count2 = count2
elif a[m][(i-1)%3-1] == a[(left_save_current-1)//3][(left_save_current-1)%3]:
count2 = count2 + 1
left_count2 = count2
if left_count2:
count2 = count2 - 1
if a[m][(i-1)%3] == a[(right_save_current-1)//3][(right_save_current-1)%3]:
right_count2 = count2
elif a[m][(i-1)%3+1] == a[(right_save_current-1)//3][(right_save_current-1)%3]:
count2 = count2 + 1
right_count2 = count2
if right_count2:
count2 = count2 - 1
count2 = count2 + 1
count2 = 0
for m in range((i-1)//3,len(a)): #아래쪽
if a[m][(i-1)%3] == a[(left_save_current-1)//3][(left_save_current-1)%3]:
left_count2 = count2
elif a[m][(i-1)%3-1] == a[(left_save_current-1)//3][(left_save_current-1)%3]:
count2 = count2 + 1
left_count2 = count2
if left_count2:
count2 = count2 - 1
if a[m][(i-1)%3] == a[(right_save_current-1)//3][(right_save_current-1)%3]:
right_count2 = count2
elif a[m][(i-1)%3+1] == a[(right_save_current-1)//3][(right_save_current-1)%3]:
count2 = count2 + 1
right_count2 = count2
if right_count2:
count2 = count2 - 1
count2 = count2 + 1
# print(i, left_count2, right_count2, a[(left_save_current-1)//3][(left_save_current-1)%3], a[(right_save_current-1)//3][(right_save_current-1)%3])
if left_count2 < right_count2:
answer = answer + 'L'
left_save_current = i
elif left_count2 > right_count2:
answer = answer + 'R'
right_save_current = i
else:
if hand == "right":
answer = answer + 'R'
right_save_current = i
elif hand == "left":
answer = answer + 'L'
left_save_current = i
return answer
print(solution([0,1,2,3,4,5,6,7,8,0,2,5,8,0], "right")) |
class No:
def __init__(self, valor):
self.dado = valor
self.proximo = None
self.anterior = None
def __str__(self):
if self.proximo is None and self.anterior is None:
return f"|\t Anterior: {self.anterior} \t|\t Nó: {self.dado} \t|\t Próximo: {self.proximo} \t| "
elif self.proximo is None:
return f"|\t Anterior: {self.anterior.dado} \t|\t Nó: {self.dado} \t|\t Próximo: {self.proximo} \t| "
elif self.anterior is None:
return f"|\t Anterior: {self.anterior} \t|\t Nó: {self.dado} \t|\t Próximo: {self.proximo.dado} \t| "
else:
return f"|\t Anterior: {self.anterior.dado} \t|\t Nó: {self.dado} \t|\t Proximo: {self.proximo.dado} \t| "
|
def Indent( elem, level=0, indent=' ' ):
"""
Function used to 'prettify' output xml from cElementTree's tree.getroot()
method into lines so it's easily read.
"""
i = "\n" + level * indent
if len( elem ):
if not elem.text or not elem.text.strip():
elem.text = i + indent
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
Indent( elem, level + 1, indent )
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and ( not elem.tail or not elem.tail.strip() ):
elem.tail = i
def GetCamelCase( name ):
return name[0].upper() + name[1:]
def GetLowerCamelCase( name ):
return name[0].lower() + name[1:]
def GetUniqueName( name, elems ):
"""
Return a unique version of the name indicated by incrementing a numeral
at the end. Stop when the name no longer appears in the indicated list of
elements.
"""
digits = []
for c in reversed( name ):
if c.isdigit():
digits.append( c )
else:
break
stem = name[0:len( name ) - len( digits )]
val = ''.join( digits )[::-1] or 0
i = int( val )
while True:
i += 1
newName = ''.join( [stem, str( i )] )
if newName not in elems:
break
return newName |
class WrappedFunction( object ):
def __init__( self, fn=None ):
self.fns = []
# Add base function
if fn is not None:
self.Add( fn )
def __call__( self, *args, **kwargs ):
return self.fn( *args, **kwargs )
def Add( self, fn ):
"""Add a function."""
self.fns.append( fn )
self.Compile()
def Compile( self ):
"""Compile the final function."""
compiledFn = self.fns[0]
for i in range( 1, len( self.fns ) ):
compiledFn = self.Wrap( compiledFn, self.fns[i] )
self.fn = compiledFn
def Wrap( self, fn, wrapFn ):
"""Return function fn wrapped with wrapFn."""
def Wrapped( *args ):
return wrapFn( *fn( *args ) )
return Wrapped
|
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
total = 0
for num in xrange(1000):
if num % 3 == 0 or num % 5 == 0:
total += num
print total
# >>> 233168
|
students=[20,10,35]
total=sum(students)
print("Total marks obtained",total)
length=len(students)
print("Length is:",length)
mean=total/length
print("Mean is:",mean) |
def weather(temp):
if temp <= 10:
result = "COLD"
elif temp > 10 and temp <= 25:
result = "WARM"
else:
result = "HOT"
return result
user_input = float(input("Please enter a temperature: "))
print("The weather is",weather(user_input)) |
# Requirements: Instead of a Fibonacci sequence, we'll make a TRI-bonacci sequence
#
# Your function will be given a signature array of 3 numbers and a positive integer n
# it must return an array of size n, where the n-th number is the sum of the previous 3
#
# For n < 3, we have our base cases, so if n == 1, we return the first item in the signature
# For n == 2, we return the first two items in the signature
# and for n == 3, we simply return the signature
# for n == 0, we return an empty array, []
def tribonacci(signature, n):
if n == 0:
return []
if n == 1:
return [signature[0]]
if n == 2:
signature.remove(signature[2])
return signature
sigcopy = signature
indexCount = 0
while n > 3:
sigcopy.append((sigcopy[indexCount]+sigcopy[indexCount+1]+sigcopy[indexCount+2]))
indexCount += 1
print ("indexCount: ",indexCount)
n = n-1
print(sigcopy)
return sigcopy
## Best Solution ##
#
# A better solution to this problem takes advantage of python's slicing syntax
# which is very effective at accessing specific parts of an array of numbers
#
# def tribonacci(signature, n):
# result = signature[:n]
# for i in range(n - 3):
# res.append(sum(res[-3:]))
# return res
|
from math import sqrt
# We'll recall that anytime we're working with number methods we
# should utilize Python's large math library. In this case, the only one that
# comes to mind is the sqrt() function
def findNextSquare(sq):
# First we check the square root of the given number against mod 1
# since this will either return 0, if it's an integer and otherwise
# return a decimal.
if((sqrt(sq) % 1) == 0):
return ((sqrt(sq)+1)*(sqrt(sq)+1))
# Here we keep the code clean by avoiding an unnecessary else statemnt
return -1
print(findNextSquare(4))
|
#!/usr/bin/python
#-*-coding:utf8-*-
# a = 2
# def fun(x,y=100):
# a = 10
# print id(a)
# return x*y*a
# print fun(3,30)
# print a,id(a)
# x = "my is string"
# def fun():
# global y
# y = 100
# global x
# x = 10
# # fun()
# print x,id(x)
# # print y,id(y)
# try:
# print y,id(y)
# except NameError:
# 'aaa'
# print "whatever not defined"
# bb = lambda x,y:x*y
# dd = lambda : 123
# # print bb(12,12)
# def cc(bb):
# try:
# print y,id(y)
# except NameError:
# print bb(1,2)
# # print "whatever not defined"
# cc(bb)
# print dd()
# bb = lambda x:x*(x-1)
# print bb(5)
# def dg(n):
# if n<10:
# print "--"*n,n
# dg(n+1)
# print "--"*n,n
# dg(0)
class demo():
lis = (1,2,3,4,5)
def sayHi(self):
for x in self.lis:
print x
def add(x,y):
return x+y
|
from typing import List
def generate_10_numbers_from_0_until_100() -> List[int]:
import random
List = [random.randint(0, 99) for k in range(10)]
return List
def print_list(numbers: List[int]):
for i in range(10):
print(numbers[i])
def sort_in_ascending_order(numbers: List[int]) -> List[int]:
n = numbers
n.sort()
return n
def remove_content_which_number_is_under_50(numbers: List[int]) -> List[int]:
l = [i for i in numbers if i>=50]
return l
if __name__ == '__main__':
x = generate_10_numbers_from_0_until_100()
print_list(x)
y = sort_in_ascending_order(x)
print(y) #確認
z = remove_content_which_number_is_under_50(x)
print(z) #認確
|
class Node(object):
"""docstring for Node"""
__slots__ = ('data', 'next')
def __init__(self, data, next):
self.data = data
self.next = next
class Stack(object):
"""docstring for Stack"""
def __init__(self):
self.head = Node(None, None) # sentinel node
self.len = 0
def __len__(self):
return self.len
def push(self, data):
self.head = Node(data, self.head)
self.len += 1
def pop(self):
if not self.len:
raise IndexError
result = self.head
self.head = self.head.next
self.len -= 1
return result.data
def reverse(self):
if self.len < 2:
# reverse would do nothing
return
prev = self.head
pointer = self.head.next
tail = self.head
while pointer.next is not None:
# temp <- pointer.next
# pointer.next <- prev
# prev <- pointer
# pointer <- temp
pointer.next, prev, pointer = prev, pointer, pointer.next
self.head = prev
# reassigned the sentinel to the new end
tail.next = pointer
class Queue(object):
"""docstring for Queue"""
def __init__(self):
self.inbox = Stack()
self.outbox = Stack()
def queue(self, data):
self.inbox.push(data)
def dequeue(self):
if not self.outbox:
self.outbox, self.inbox = self.inbox, self.outbox
self.outbox.reverse()
try:
return self.outbox.pop()
except IndexError:
raise IndexError, "Queue is empty."
if __name__ == "__main__":
q = Queue()
q.queue(1)
print q.dequeue() |
#!/usr/bin/python
#Javier Alegria
ProteinSeq = raw_input("Enter a protein sequence: ")#this function will allow to input data
ProteinSeq = ProteinSeq.upper()#becomes everything in uppercase letters so that the program can still read it (the opposite would be lower()"
AminoDict = {#this is a dictionary of the aminoacids and the mollecular weight
'A':89.09,
'R':174.20,
'N':132.12,
'D':133.10,
'C':121.15,
'Q':146.15,
'E':147.13,
'G':75.07,
'H':155.16,
'I':131.17,
'L':131.17,
'K':146.19,
'M':149.21,
'F':165.19,
'P':115.13,
'S':105.09,
'T':119.12,
'W':204.23,
'Y':181.19,
'V':117.15,
'X':0.0,
'-':0.0,
'*':0.0}
MolWeight = 0
for AminoAcid in ProteinSeq:#this loop will treat proteinSeq as a list. It steps through each letter of the string and assings it to AminoAcid in turn. So each time you loop is as if you write Aminoacid = [ 'F' ] before the print statement.
MolWeight = MolWeight + AminoDict[AminoAcid]#here, for each value assigned by the loop it will look for the value assigned to it in the dictionary (AminoDict[AminoAcid]) and add it to the value of molWeight.
print "Protein: ", ProteinSeq
print "Molecular weight: %.1f" % (MolWeight)
|
# node:
# - metadata: [int]
# - children: [nodes]
data = open('input_08.txt').read()
from collections import namedtuple
TreeNode = namedtuple('TreeNode', 'children, metadata')
def fetch_node(numbers):
n_children = numbers.pop()
n_metadata = numbers.pop()
child_nodes = [fetch_node(numbers) for _ in range(n_children)]
metadata = [numbers.pop() for _ in range(n_metadata)]
return TreeNode(metadata=metadata, children=child_nodes)
def build_tree(raw_data):
parsed_data = list(map(int, data.split()))
parsed_data.reverse()
try:
return fetch_node(parsed_data)
except:
return None
def sum_metadata(node):
return sum(node.metadata) + sum(sum_metadata(child) for child in node.children)
tree = build_tree(data)
checksum = sum_metadata(tree)
print(f'The sum of all metadata entries is {checksum}')
#############
def node_value(node):
if not node.children:
return sum(node.metadata)
child_to_sum = [node.children[i-1] for i in node.metadata if i <= len(node.children)]
value = sum(node_value(child) for child in child_to_sum)
return value
new_checksum = node_value(tree)
print(f'The value of the root node {new_checksum}')
|
def part_1(print_result: bool = True) -> int:
pk_card, pk_door = 1614360, 7734663
size = 20201227
looked_pks = pk_card, pk_door
for loop_size in range(size):
estimated_pk = pow(7, loop_size, size)
if estimated_pk not in looked_pks:
continue
if estimated_pk == pk_card:
encryption_key = pow(pk_door, loop_size, size)
break
elif estimated_pk == pk_door:
encryption_key = pow(pk_card, loop_size, size)
break
else:
assert False, "There is a solution!"
if print_result:
print(f"Encryption key is {encryption_key}")
return encryption_key
def part_2(print_result: bool = True) -> int:
if print_result:
print("All done!")
return 50
SOLUTION_1 = 5414549
SOLUTION_2 = 50
IS_SOLUTION_1_SLOW = True
if __name__ == "__main__":
part_1()
part_2()
|
from dataclasses import dataclass
from typing import Optional
@dataclass
class Marble:
value: int
next_cw: Optional['Marble']
next_ccw: Optional['Marble']
class MarbleCircle:
def __init__(self):
self.current = None
self.first = None
def next_cw(self):
return self.current.next_cw
def second_next_cw(self):
return self.next_cw().next_cw
def add_new_marble(self, marble):
if self.current is None:
self.update_circle(marble, marble, marble)
self.first = marble
else:
self.update_circle(marble, self.next_cw(), self.second_next_cw())
self.current = marble
def remove_marble_seven_ccw(self):
first_ccw = self.current.next_ccw
second_ccw = first_ccw.next_ccw
third_ccw = second_ccw.next_ccw
fourth_ccw = third_ccw.next_ccw
fifth_ccw = fourth_ccw.next_ccw
sixth_ccw = fifth_ccw.next_ccw
seventh_ccw = sixth_ccw.next_ccw
eight_ccw = seventh_ccw.next_ccw
# Update
sixth_ccw.next_ccw = eight_ccw
eight_ccw.next_cw = sixth_ccw
self.current = seventh_ccw.next_cw
return seventh_ccw.value
def update_circle(self, new_marble, first_cw, second_cw):
new_marble.next_cw = second_cw
new_marble.next_ccw = first_cw
first_cw.next_cw = new_marble
second_cw.next_ccw = new_marble
def __repr__(self):
marbles = [self.first]
while marbles[-1].next_cw.value != self.first.value:
marbles.append(marbles[-1].next_cw)
return marbles
def __str__(self):
marbles = [str(m.value) for m in self.__repr__()]
return ",".join(marbles)
class Players:
def __init__(self, number_of_elves):
self.players = [0] * number_of_elves
self.current_player = -1
def get_next_player(self):
self.current_player += 1
if self.current_player == len(self.players):
self.current_player = 0
return self.current_player
def add_score(self, player, score):
self.players[player] += score
def get_highest_score(self):
return max(self.players)
def play_marble(value, mc, pl):
player = pl.get_next_player()
if value and value % 23 == 0:
pl.add_score(player, value)
bonus = mc.remove_marble_seven_ccw()
pl.add_score(player, bonus)
else:
m = Marble(value=value, next_cw=None, next_ccw=None)
mc.add_new_marble(m)
def play_game(max_marble, number_of_elves):
mc = MarbleCircle()
pl = Players(number_of_elves)
for value in range(max_marble):
play_marble(value, mc, pl)
return mc, pl
mc, pl = play_game(72170, 470)
print(f'Higest score is {pl.get_highest_score()}')
#######
mc, pl = play_game(72170*100, 470)
print(f'Higest score for 100 times longer case is {pl.get_highest_score()}')
|
import math
from fractions import Fraction
from common import read_data
def parse_spacemap(map_data):
spacemap = {}
for y, line in enumerate(map_data):
for x, char in enumerate(line.strip()):
spacemap[(x, y)] = char == '#'
return spacemap
################
# ## PART 1 ## #
################
def los_map_for_point(space, center):
los_map = {p: True for p in space}
for p in space:
if p == center:
continue
mark_covered(los_map, space, center, p)
return los_map
def mark_covered(los_map, spacemap, center, point):
if not spacemap[point]:
# No asteroids here, so it will not cover anything
return
step_x, step_y = get_steps(center, point)
point_analyzed = point
while True:
point_analyzed = (point_analyzed[0] + step_x, point_analyzed[1] + step_y)
if point_analyzed in spacemap:
los_map[point_analyzed] = False
else:
break
def get_steps(center, point):
dx = point[0] - center[0]
if dx == 0:
return 0, -1 if center[1] > point[1] else 1
dy = point[1] - center[1]
ratio = Fraction(dy, dx)
step_x = abs(ratio.denominator) * (-1 if center[0] > point[0] else 1)
step_y = abs(ratio.numerator) * (-1 if center[1] > point[1] else 1)
return step_x, step_y
def asteroids_in_los(spacemap, center, los_map):
return [point for point in spacemap if spacemap[point] and los_map[point] and point != center]
def visibility_per_point(spacemap):
all_los_maps = {p: los_map_for_point(spacemap, p) for p in spacemap if spacemap[p]}
visible_asteroids_per_point = {p1: asteroids_in_los(spacemap, p1, los_map) for p1, los_map in all_los_maps.items()}
visible_count_per_point = [(p, len(visible_asteroids_per_point[p])) for p in visible_asteroids_per_point]
sorted_points = list(reversed(sorted(visible_count_per_point, key=lambda vp: vp[1])))
return sorted_points
data = read_data('10', True)
points_and_visibility = visibility_per_point(parse_spacemap(data))
print(points_and_visibility[0]) # (23, 19), 278
################
# ## PART 2 ## #
################
def get_laser_target(station_position, max_map_size):
aim_x = station_position[0]
aim_y = 0
direction = 'right'
while True:
assert 0 <= aim_x < max_map_size[0]
assert 0 <= aim_y < max_map_size[1]
yield aim_x, aim_y
if direction == 'right':
aim_x = aim_x + 1
if aim_x == max_map_size[0] - 1:
direction = 'down'
elif direction == 'down':
aim_y = aim_y + 1
if aim_y == max_map_size[1] - 1:
direction = 'left'
elif direction == 'left':
aim_x = aim_x - 1
if aim_x == 0:
direction = 'up'
elif direction == 'up':
aim_y = aim_y - 1
if aim_y == 0:
direction = 'right'
def first_target_in_los(spacemap, station, target_point):
step_x, step_y = get_steps(station, target_point)
point_in_laser_path = station
while True:
point_in_laser_path = (point_in_laser_path[0] + step_x, point_in_laser_path[1] + step_y)
if point_in_laser_path not in spacemap:
return None
if spacemap[point_in_laser_path]:
return point_in_laser_path
def get_angle(station, asteroid):
"""
Proof that I need to get better at trigonometry
"""
dx = (asteroid[0] - station[0])
dy = (asteroid[1] - station[1])
at = math.atan2(dy, dx)
return at if at >= -math.pi / 2 else at + 2 * math.pi
def remove_asteroids(spacemap, station):
asteroids_in_maps = sum(1 for p in spacemap.values() if p is True and p != station)
asteroids_removed = 0
while True:
los_map = los_map_for_point(spacemap, station)
removed_asteroids = sorted(asteroids_in_los(spacemap, station, los_map))
if not removed_asteroids:
print(f'** Removed {asteroids_removed} out of {asteroids_in_maps} **')
break
for asteroid in removed_asteroids:
spacemap[asteroid] = False
removed_with_angles = [(asteroid, get_angle(station, asteroid)) for asteroid in removed_asteroids]
sorted_removed_with_angles = sorted(removed_with_angles, key=lambda a: a[1])
for removed in sorted_removed_with_angles:
asteroids_removed += 1
print(f'Removed {asteroids_removed} - {removed}')
if asteroids_removed == asteroids_in_maps:
break
data = read_data('10', True)
remove_asteroids(parse_spacemap(data), (23, 19))
|
# This example demonstrates:
# - creation of the Model object
# - creation of training instances of features
# - training a model
# - creation of testing instances of features
# - testing the tesiing instances against the trained model
# - accessing the predictions
from wekapy import *
# CREATE NEW MODEL INSTANCE WITH A CLASSIFIER TYPE
model = Model(classifier_type = "bayes.BayesNet")
# CREATE TRAINING INSTANCES. LAST FEATURE IS THE PREDICTION OUTCOME
instance1 = Instance()
instance1.add_features([ Feature(name="num_milkshakes", value=46, possible_values="numeric"),
Feature(name="is_sunny", value=True, possible_values="{False, True}"),
Feature(name="boys_in_yard", value=True, possible_values="{False ,True}") ])
instance2 = Instance()
instance2.add_features([ Feature(name="num_milkshakes", value=2, possible_values="numeric"),
Feature(name="is_sunny", value=False, possible_values="{False, True}"),
Feature(name="boys_in_yard", value=False, possible_values="{False ,True}") ])
model.add_train_instance(instance1)
model.add_train_instance(instance2)
model.train(folds=2)
# CREATE TEST INSTANCES
test_instance1 = Instance()
test_instance1.add_features([ Feature(name="num_milkshakes", value=44, possible_values="numeric"),
Feature(name="is_sunny", value=True, possible_values="{False, True}"),
Feature(name="boys_in_yard", value="?", possible_values="{False ,True}") ])
test_instance2 = Instance()
test_instance2.add_features([ Feature(name="num_milkshakes", value=5, possible_values="numeric"),
Feature(name="is_sunny", value=False, possible_values="{False, True}"),
Feature(name="boys_in_yard", value="?", possible_values="{False ,True}") ])
model.add_test_instance(test_instance1)
model.add_test_instance(test_instance2)
model.test()
# CHECK THE PREDICTIONS:
predictions = model.predictions
for prediction in predictions:
print prediction
|
def choice_sort(A: list):
for i in range(len(A)):
for j in range(i + 1, len(A)):
if (A[j] < A[i]):
A[i], A[j] = A[j], A[i]
def test_choice_sort():
A = [4, 2, 5, 1, 3, 0, 5, 3, -1, -2, 17, 10]
print(A)
choice_sort(A)
print(A)
test_choice_sort() |
def reverse_list(List):
""" Reverse list List
LoL :D
"""
lenght = len(List)
for i in range(lenght // 2):
List[i], List[lenght - 1 - i] = List[lenght - 1 - i], List[i]
def test_reverse_list():
List = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(List)
reverse_list(List)
print(List)
test_reverse_list() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.