text stringlengths 37 1.41M |
|---|
'''"""
PROBLEM STATEMENT:-
To build a model to accurately classify a piece of news as REAL or FAKE. Using sklearn, build a TfidfVectorizer
on the provided dataset. Then, initialize a PassiveAggressive Classifier and fit the model. In the end,
the accuracy score and the confusion matrix tell us how well our model fares. On completion, create a GitHub
account and create a repository. Commit your python code inside the newly created repository.
Author = Vedant Deshpande
References = Medium.com
'''
import pandas as pd
import numpy as np
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
import itertools
from sklearn.metrics import accuracy_score, confusion_matrix
dataset = pd.read_csv('news.csv')
print(dataset.info())
labels = dataset.label
x_train,x_test,y_train,y_test=train_test_split(dataset['text'], dataset['label'], test_size=0.2, random_state=7)
vectoriser = TfidfVectorizer()
tfidf_train = vectoriser.fit_transform(x_train)
tfidf_test = vectoriser.transform(x_test)
pac = PassiveAggressiveClassifier(max_iter = 50)
pac.fit(tfidf_train,y_train)
y_pred = pac.predict(tfidf_test)
score = accuracy_score(y_test,y_pred)
print('accuracy = ', round(score*100,2))
print(confusion_matrix(y_test,y_pred,labels=['FAKE','REAL']))
|
# <문제> 곱하기 혹은 더하기: 문제 설명
# 각 자리가 숫자로만 이루어진 문자열 S가 주어졌을 때, 왼쪽부터 오른쪽으로 하나씩 모든 숫자를 확인하며
# 숫자 사이에 "x", "+" 연산자를 넣어 결과적으로 만들어질 수 잇는 가장 큰술르 구하는 프로그램을 작성하시오.
# 단, 모든 연산은 왼쪽부터 순서대로 이루어진다.
s = "213"
answer = 0
for i in s:
i = int(i)
if i <= 1 or answer <= 1:
answer += i
else:
answer *= i
print(answer) |
n = int(input())
a = 1
b = 2
c = 3
def hanoi(n, a, b, c):
global count
if n <= 0:
pass
else:
hanoi(n-1, a, c, b)
print(a, c)
hanoi(n-1, b, a, c)
def count(n):
if n == 1:
return n
else:
return count(n-1)*2+1
print(count(n))
hanoi(n, a, b, c)
# n = int(input())
# a = 1
# b = 3
# c = 2
# def hanoi(n, a, b, c):
# global count
# if n <= 0:
# pass
# else:
# hanoi(n-1, a, c, b)
# print(a, b)
# hanoi(n-1, c, b, a)
# def count(n):
# if n == 1:
# return n
# else:
# return count(n-1)*2+1
# print(count(n))
# hanoi(n, a, b, c) |
# Author: Branden Kim
# Assignment: 5
# Description: Recursive function to print out the echoes of a sentence
def echo_game(word, fraction, num_echoes):
if len(word) > 1:
echo_len = len(word) - int(len(word) * fraction)
print(word)
return echo_game(word[echo_len:], fraction, num_echoes + 1)
else:
print(f'Total number of echoes: {num_echoes}')
def main():
while True:
try:
fraction = float(input('Enter the fraction: '))
except ValueError:
print('Your number must be a fraction (in decimal form).')
else:
if fraction >= 0 and fraction < 1:
break
else:
print('Your number must be a fraction (in decimal form).')
word = input('Enter the sentence: ')
echo_game(word, fraction, 0)
if __name__ == '__main__':
main()
|
# Author: Branden Kim
# Assignment: 5
# Description: Recursive GCD function
def gcd(first, second, curr_attempt):
if second == 0:
return first
else:
return gcd(second, first % second, first % second)
def main():
while True:
try:
first = int(input('Please enter the first number: '))
except ValueError:
print('Only numbers greater than or equal to 1 are accepted as valid input.')
else:
if first >= 1:
break
else:
print('Only numbers greater than or equal to 1 are accepted as valid input.')
while True:
try:
second = int(input('Please enter the second number: '))
except ValueError:
print('Only numbers greater or than equal to 1 are accepted as valid input.')
else:
if second >= 1:
break
else:
print('Only numbers greater than or equal to 1 are accepted as valid input.')
print(f'The GCD for {first} and {second} is {gcd(first, second, second)}')
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on Saturday, April 1st 2018
@author: Sagar Kishore
"""
class Stack:
"""
Stack Class that takes in the stack name as mandatory parameter.
"""
def __init__(self, name, **kwargs):
self.name = name
self.words = []
self._rank_dict = {
'-1': set(self.words),
'0': set(),
'1': set(),
'2': set(),
'3': set(),
'4': set(),
'5': set(),
'6': set(),
}
@property
def rank_dict(self):
return self._rank_dict
@rank_dict.setter
def rank_dict(self, value):
self._rank_dict = value
def refresh_rank_dict(self):
self.rank_dict['-1'] = set(self.words)
self.rank_dict['0'] = set()
self.rank_dict['1'] = set()
self.rank_dict['2'] = set()
self.rank_dict['3'] = set()
self.rank_dict['4'] = set()
self.rank_dict['5'] = set()
self.rank_dict['6'] = set()
@property
def size(self):
return len(self.words)
def __repr__(self):
return "Stack({!r})".format((self.name))
def __str__(self):
return f"""\
Stack - {self.name}
Words - {self.words}
Size - {self.size}
"""
def __len__(self):
return len(self.words)
|
#Polynomial Regression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the Dataset
dataset = pd.read_csv('Test_data.csv')
X = dataset.iloc[:,4:6].values
y = dataset.iloc[:,8:9].values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X[:, 1] = labelencoder_X.fit_transform(X[:, 1])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
#Avoiding Dummy Variable Trap
X = X[:,2:]
#Splittung the data into training and test set
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test= train_test_split(X,y,test_size=0.3,random_state=0)
#Fitting Multiple Linear Regression To Training Set
from sklearn.linear_model import LinearRegression
linear_regressor = LinearRegression()
linear_regressor.fit(X_train, y_train)
#Fitting Polynomial Regression to training and test set
from sklearn.preprocessing import PolynomialFeatures
poly_regressor = PolynomialFeatures(degree = 4)
X_poly = poly_regressor.fit_transform(X_train)
lin_regressor_2 = LinearRegression()
lin_regressor_2.fit(X_poly, y_train)
#Visualising the Linear Regression Results
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = X_train[:,0]
y = X_train[:,1]
z = y_train
ax.scatter(x, y, z, c='r', marker='+')
ax.set_title(' Linear Regression ')
ax.set_xlabel(' Male/Female')
ax.set_ylabel(' Age ')
ax.set_zlabel(' Calories ')
x1 = X_test[:,0]
y1 = X_test[:,1]
z1 = linear_regressor.predict(X_test)
ax.scatter(x1, y1, z1, c='b', marker='*')
plt.show()
#Visualising the Polynomial Regression Results
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = X_train[:,0]
y = X_train[:,1]
z = y_train
ax.scatter(x, y, z, c='r', marker='+')
ax.set_title(' Polynomial Regression ')
ax.set_xlabel(' Male/Female')
ax.set_ylabel(' Age ')
ax.set_zlabel(' Calories ')
x1 = X_test[:,0]
y1 = X_test[:,1]
z1 = lin_regressor_2.predict(poly_regressor.fit_transform(X_test))
ax.scatter(x1, y1, z1, c='b', marker='*')
plt.show()
#Predicting a new result with Linear Regression
linear_regressor.predict([1,39])
#Predicting a new result with Polynomial Regression
lin_regressor_2.predict(poly_regressor.fit_transform([1,39]))
|
#Polynomial Regression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the Dataset
dataset = pd.read_csv('Final_file_of_family_data.csv')
X = dataset.iloc[:,[4,9,12,13]].values
y = dataset.iloc[:,8:9].values
#Splittung the data into training and test set
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test= train_test_split(X,y,test_size=0.3,random_state=0)
#Fitting Multiple Linear Regression To Training Set
from sklearn.linear_model import LinearRegression
linear_regressor = LinearRegression()
linear_regressor.fit(X_train, y_train)
#Fitting Polynomial Regression to training and test set
from sklearn.preprocessing import PolynomialFeatures
poly_regressor = PolynomialFeatures(degree = 4)
X_poly = poly_regressor.fit_transform(X_train)
lin_regressor_2 = LinearRegression()
lin_regressor_2.fit(X_poly, y_train)
X_poly_2 = poly_regressor.fit_transform(X)
#Predicting a new result with Linear Regression
linear_regressor.predict(X)
#Predicting a new result with Polynomial Regression
y_pred=lin_regressor_2.predict(X_poly_2)
y_pred = y_pred.ravel()
#Predicting a new result
#y_pred = regressor_2.predict(X)
"""#Adding to the main dataset
import csv
rows=[]
fields=[]
with open('Answer.csv','r') as csv_input:
csvreader= csv.reader(csv_input)
fields=next(csvreader)
for row in csvreader:
rows.append(row)
fields.append("Polynomial_Predicted")
i=0
for row in rows:
row.append(y_pred[i])
i+=1
with open('Answer.csv','w') as csvfile:
csvwriter=csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)"""
|
def primo (numero):
valor = range(2,numero)
contador = 0
for n in valor:
if numero % n == 0:
contador +=1
print("divisor:", n)
if contador > 0 :
return False
else:
return True
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Решить поставленную задачу:
написать функцию, вычисляющую среднее гармоническое
своих аргументов a1, a2, ... an
Если функции передается пустой список аргументов,
то она должна возвращать значение None
"""
def average(*x):
"""Поиск среднего гармонического"""
summa = 0
if x:
for i in x:
if i == 0:
return None
else:
summa += 1 / float(i)
z = 1 / (1 / len(x) * summa)
return z
else:
return None
if __name__ == '__main__':
print("Введите числа в массив через пробел: ")
mas = list(map(float, input().split()))
print(average(*mas))
|
#괄호 맞추기
#(())() -> True
#())()(()) -> False
"""왼쪽 괄호는 자기 짝인 오른쪽 괄호가 올때까지 기다려야한다. 왼쪽 괄호를 Stack에 저장하여 짝이 맞는
오른쪽 괄호가 나올때까지 저장해둔다."""
# 1. Stack 객체를 사용해야 하므로 Stack 클래스를 만든다.
class Stack:
# 생성 함수
def __init__(self):
self.li = []
# Stack에 val 추가 함수
def push(self, val):
self.li.append(val)
# Stack의 맨 위에 있는 val 삭제하는 함수
def pop(self):
try:
return self.li.pop()
except IndexError:
print("Stack is empty")
# Stack의 맨 위에 있는 val
def top(self):
try:
return self.li[-1]
except IndexError:
print("Stack is empty")
# Stack에 저장되어 있는 원소의 개수
def __len__(self):
return len(self.li)
# 2. 괄호 맞추기 코드 작성.
"""2-1. 우리는 왼쪽 괄호를 Stack에 저장하기로 하였으므로 Stack 객체 생성한다."""
S = Stack()
# brackets = input() #입력
brackets = '())()(())' #예시
for b in brackets:
if b == '(':
S.push()
elif b == ')':
if S.len() != 0:
S.pop()
else:
print(False) #왼쪽 짝이 없이 오른쪽이 더 많은 경우 error
else:
print("input data Error") # '(',')' 이외의 값이 있을경우 error
if S.len() > 0:
print("Error") # for문을 다 끝내고 난 뒤, Stack의 len이 0 이상이면 '('가 더 많은 경우
else:
print('True') # 그 이외의 경우는 True
|
import os
p = 'insert path of the directory you want to index' #path to explore
t = 'target directory to store the index in' #folder to store the index file in
filename = 'index.txt' #name of index file
#i is step of indentation
def makeline(txt, i):
ind = " " * i
txt = ind + txt
return txt
#i initialises as 0 for parent
def explore(file, path, i=0):
d={}
for f in os.scandir(path):
if f.is_dir():
d[f.name]='dir'
else:
d[f.name]='file'
for n in d:
if (n == '.git')or(n=='indices'):
continue
if d[n]=='dir':
name = 'Folder : '+n
m = makeline(name, i)
file.write(m+'\n')
i+=1
explore(file, path+'/'+n, i)
i-=1
elif d[n]=='file':
name = n.split('.')
fil = name.pop()
n = fil+' : '+ ('.'.join(name))
m = makeline(n, i)
file.write(m+'\n')
index = open(t+'/'+filename, "w")
explore(index, p)
index.close() |
# -*- coding: utf-8 -*-
"""
:mod:`test` module : test module for experiences assignment
:author: `FIL - IEEA - Univ. Lille1.fr <http://portail.fil.univ-lille1.fr>`_
:date: 2015, december
"""
import sys
import experience
import sorting
def compare (m1,m2):
return experience.compare(m1,m2)
# STRATEGY 1
def negative_markers1(markers,positive):
"""
Computes the list of negative markers from the list of markers and
the list of positive markers.
:param markers: The list of markers
:type markers: List of String
:param positive: The list of positive markers
:type positive: List of String
:return: The list of negative markers
:rtype: List of String
"""
negative = []
inc=0
for m in markers:
for p in positive:
inc+=1
if (m==p):
return inc,negative
negative.append(m)
return inc,negative
# STRATEGY 2
def negative_markers2(markers,positive):
positive=sorting.merge_sort(positive,compare)
return negative_markers1(markers,positive)
# STRATEGY 3
def negative_markers3(markers,positive):
markers=sorting.merge_sort(markers,compare)
return negative_markers2(markers,positive)
def ee(inc):
"""
structure the number in parameter to be returned in a 3 caracter string
"""
if inc<10:
return " "+str(inc)
elif inc<100:
return " "+str(inc)
else:
return str(inc)
def print(value):
file = open("fichier10.txt","a")
file.write(value+"\n")
file.close()
if __name__ == "__main__":
p = int(sys.argv[1])
m = int(sys.argv[2])
n=10
try :
n= int(sys.argv[3])
except:
n=n
markers = experience.markers(m)
positive = experience.experience(p,markers)
print("Markers: %s" % (markers))
print("Positive markers: %s" % (positive))
# test stategy 1
cmp,negative=negative_markers1(markers,positive)
print("Negative markers: %s" % (negative))
print("Nb. comparaisons: %d" % (cmp))
# test stategy 2
cmp,negative=negative_markers2(markers,positive)
print("Negative markers: %s" % (negative))
print("Nb. comparaisons: %d" % (cmp))
# test stategy 3
cmp,negative=negative_markers3(markers,positive)
print("Negative markers: %s" % (negative))
print("Nb. comparaisons: %d" % (cmp))
for i in range (1,n+1):
markers=experience.markers(m)
positive=experience.experience(p,markers)
cmp1,negative=negative_markers1(markers,positive)
cmp2,negative=negative_markers2(markers,positive)
cmp3,negative=negative_markers3(markers,positive)
print("%d %s %s %s %s" %(n,ee(i),ee(cmp1),ee(cmp2),ee(cmp3)))
|
#!/usr/bin/env python3
"""
:author: Vienne & Lecornet
:date: 20/09/16
:object: representation of numbers
"""
def integer_to_digit(entier):
"""
Parameters: integer (int) –
Returns: the character representing the hexadecimal digit
Return type: str
CU: integer >= 0 and integer < 16
"""
assert ( (entier >=0) and (entier<=15) )
return "{:X}".format(entier)
def integer_to_string(n,b):
"""
Parameters: integer (int) – the integer we want to representbase (int) – the base in which the integer must be represented
Returns: The string representation of the integer given in parameter in base base.
Return type: str
CU: base >= 2 and base <= 16 and integer >= 0
"""
assert ( b>1 )
assert ( n>=0 )
r=n%b
q=n//b
fin=str(r)
while (q>=b):
r=q%b
q=q//b
fin=fin+str(r)
fin=fin+str(q)
return fin[::-1]
def deux_puissance(n):
"""
Parameters: n (int) – The power of two
Returns:The value of 2^n
Return type:int
CU: n >= 0
"""
return 1<<n
def integer_to_binary_str(entier):
"""
Parameters: integer (int) – the integer to be converted in binary
Return type:str
Returns:Return the binary representation (as a string) of integer
CU: integer >= 0
"""
retour=""
tmp=""
while (entier>0):
if(entier&1):
tmp="1"
else:
tmp="0"
retour = tmp + retour
entier = entier>>1
return retour
def binary_str_to_integer(binary):
"""
Parameters: bin_str (str) – The input binary string
Returns:The integer whose binary representation is bin_str
Return type:int
CU: bin_str is a binary string (containing only 0s or 1s).
"""
retour=0
inc=0
while (inc<len(binary)):
tmp=0
if(binary[inc]=="1"):
tmp=1
retour=(retour<<1)|tmp
inc=inc+1
return retour
if __name__ == "__main__":
import doctest
doctest.testmod()
# 1.1 Impression des entiers avec print
print("\n1.1 Q1\n")
entier = 4242
print (entier,"entier de base")
print ("{:x} {:o} {:X}".format(entier,entier,entier),"=> :x :o :X")
print("\n1.1 Q2\n")
entier = 1331
print (bin(entier),"bin")
print (oct(entier),"oct")
print (hex(entier),"hex")
#1.2 Transformer un entier en un chiffre
print("\n1.2 Q3\n")
for n in range(1,15):
print (chr(ord('0') + n))
# 0<n<10 vaut les chiffres de 1 Ã 9
# 9<n<... vaut des caractères tel que : ; < = > ...
print("\n1.2 Q4\n")
for n in range(10,16):
print (chr(ord('0') + n +7))
print("\n1.2 Q5\n")
for n in range(0,16):
print(integer_to_digit(n))
#1.3 Convertir un entier en une chaîne de caractères
print("\n1.3 Q6\n")
print(integer_to_string(15,2))
print(integer_to_string(100,16))
print(integer_to_string(42,10))
print("\n1.3 Q7\n")
for nb in range(0,21):
print ("{:2d} : {:>6s} {:>3s} {:>3s}".format(nb,integer_to_string(nb,2),integer_to_string(nb,8),integer_to_string(nb,16)))
#2.1 Les opérateurs logiques sur les entiers en Python
print("\n2.1 Q8\n")
print((4>2) & (8>6))
print((4>2) | (1>5))
print((4>2) ^ (8>6))
print(~(4))
print(bin(0b1010<<2))
print(bin(0b1001>>2))
print("\n2.1 Q9\n")
print("n << 1 signifie qu'on decale l'écriture binaire de 'n' d'un bit vers la gauche")
print("n >> 1 signifie qu'on decale l'écriture binaire de 'n' d'un bit vers la droite")
print("\n2.1 Q10\n")
test=4
print("2^n avec n="+str(test)+" => "+str(deux_puissance(4)))
print("\n2.1 Q11\n")
chiffre=0b10101
if (chiffre&1):
print(str(bin(chiffre))+"est impaire")
else:
print(str(bin(chiffre))+"est paire")
print("\n2.2 Q12\n")
test=25
print(str(test)+"="+integer_to_binary_str(test))
print("\n2.2 Q13\n")
test=integer_to_binary_str(25)
print(test+"="+str(binary_str_to_integer(test)))
|
p=input()
q=p[::-1]
if p==q:
print("palidrom")
else:
print("not Palidorm")
|
import itertools
a=[1,2,3,4,5,6,7,8,9]
for i in range(1,len(a)):
b=list(itertools.combinations(a,i))
for j in range(len(b)):
print(a.index(8))
|
n=7;
for i in range(0,n):
if i==(n//2):
print("x"*n,end=" ")
else:
for j in range(0,n):
if j==(n//2):
print("x",end=" ")
else :
print(" ",end="")
print()
|
approve = input("Are you ready to use my program? ")
approve_list = ["yeah", "yes", "yh", "y"]
if approve in approve_list:
print("Welcome!, this is a simple python program!")
name = input("What is your name: ")
age = int(input("How old are you?: "))
day = age * 365
hour = day * 24
minute = hour * 60
names = ["Ade", "Bola", "Shade", "Kola", "Bolu"]
if name in names:
print("Welcome to the game" ,name, "you are" ,age, "years old. Please proceed to to next stage")
else:
print ("I still calculated your age" ,name, "and not in any way close to " ,hour, "hours")
else:
print("Goodbye!, and thanks for using my program!") |
# Write a function that takes in a string of one or more words, and returns the same string,
# but with all five or more letter words reversed (Just like the name of this Kata).
#Strings passed in will consist of only letters and spaces.
#Spaces will be included only when more than one word is present.
# Examples: spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
# spinWords( "This is a test") => returns "This is a test" spinWords( "This is another test" )=> returns "This is rehtona test"
def spin_words(sentence):
# Your code goes here
start_index = 0
last_index = len(sentence) - 1
result = ""
while last_index >= start_index:
result += sentence[last_index]
last_index -= 1
return result
spin_words("we are happy") |
import random
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
lengthOfNames=len(names)
print(lengthOfNames)
r=random.randint(0,lengthOfNames-1)
print(f"Today {names[r]} have to buy meals") |
# A simple sequential search implementation
def sequential_search(l, search_item):
position = 0
for i in l:
if i == search_item:
return position
position += 1
return 'Not Found'
print(sequential_search([1, 5, 7, 8, 23, 4543], 1))
# A sequential search taking advantage of a sorted list
def sequential_ordered_search(l, search_item):
position = 0
for i in l:
if i > search_item:
return 'Not Found'
if i == search_item:
return position
position += 1
return 'Not Found'
print(sequential_ordered_search([1, 5, 7, 8, 23, 45430], 6))
|
import time
numbers = [23 , 1999, -23333, 1, 0, 675, 90]
def find_minimum_fast(nums):
"""
Finds the minimum number in a list
O(n2)
:param nums:
:return:
"""
smallest = nums[0]
for n in nums:
if n < smallest:
smallest = n
return smallest
def find_minimum_slow(nums):
"""
Finds the minimum number in a list
O(n)
:param nums:
:return:
"""
smallest = nums[0]
issmallest = True
for i in nums:
issmallest = True
# print(i)
for j in nums:
# print(i, j)
if i > j:
issmallest = False
if issmallest:
smallest = i
return(smallest)
start1 = time.time()
find_minimum_slow(numbers)
end1 = time.time()
print("SLOW: ", end1 - start1)
# find_minimum_fast(numbers)
# start2 = time.time()
# end2 = time.time()
# print("FAST: ", end2 - start2)
|
# The Divide by 2 algorithm assumes that we start with an integer greater than 0. A simple iteration then
# continually divides the decimal number by 2 and keeps track of the remainder. The first division by 2 gives
# information as to whether the value is even or odd. An even value will have a remainder of 0.
# It will have the digit 0 in the ones place. An odd value will have a remainder of 1 and will have the
# digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first
# remainder we compute will actually be the last digit in the sequence
from stack_my_implementation import Stack
def convert_decimal_to_binary(num):
remainder = num
stack = Stack()
if remainder % 2 == 0:
stack.push(0)
else:
stack.push(1)
while remainder > 1:
remainder //= 2
if remainder % 2 == 0:
stack.push(0)
else:
stack.push(1)
binary_number = ''
while not stack.isEmpty():
binary_number += str(stack.pop())
return int(binary_number)
# runestone implementation (more sophisticated, shorter, not sure about performance
def divideBy2(decNumber):
remstack = Stack()
while decNumber > 0:
rem = decNumber % 2
remstack.push(rem)
decNumber = decNumber // 2
bin_string = ''
while not remstack.isEmpty():
bin_string += str(remstack.pop())
return bin_string
# MY IMPROVED VERSION OF IT. ACCOUNTS FOR 0
from stack_my_implementation import Stack
def convert_decimal_to_binary_revised(num):
remStack = Stack()
while num > 0:
remStack.push(num % 2)
num //= 2
binaryString = ''
while not remStack.isEmpty():
binaryString += str(remStack.pop())
return binaryString or 0
###############################################
# TEST CASES
###############################################
print(convert_decimal_to_binary(1000))
print(divideBy2(1000))
print(convert_decimal_to_binary_revised(1000))
|
import random
from queue import Queue
# The Printer class will need to track whether it has a current
# task. If it does, then it is busy and the amount of time
# needed can be computed from the number of pages in the task. The
# constructor will also allow the pages-per-minute setting to be initialized.
# The tick method decrements the internal timer and sets the printer to idle
# if the task is completed.
class Printer:
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0
def tick(self):
if self.currentTask != None:
self.timeRemaining = self.timeRemaining - 1
if self.timeRemaining <= 0:
self.currentTask = None
def busy(self):
if self.currentTask != None:
return True
else:
return False
def startNext(self, newtask):
self.currentTask = newtask
self.timeRemaining = newtask.getPages() * 60/self.pagerate
# The Task class will represent a single printing task. When the task is
# created, a random number generator will provide a length from 1 to 20
# pages. We have chosen to use the randrange function from the random module.
# Each task will also need to keep a timestamp to be used for computing
# waiting time. This timestamp will represent the time that the task was
# created and placed in the printer queue. The waitTime method can then be
# used to retrieve the amount of time spent in the queue before printing begins.
class Task:
def __init__(self, time):
self.timestamp = time
self.pages = random.randrange(1,21)
def getStamp(self):
return self.timestamp
def getPages(self):
return self.pages
def waitTime(self, currenttime):
return currenttime - self.timestamp
# The main simulation implements the algorithm described above. The
# printQueue object is an instance of our existing queue ADT. A boolean
# helper function, newPrintTask, decides whether a new printing task has
# been created. We have again chosen to use the randrange function from
# the random module to return a random integer between 1 and 180. Print
# tasks arrive once every 180 seconds. By arbitrarily choosing 180 from
# the range of random integers, we can simulate this random
# event. The simulation function allows us to set the total time and
# the pages per minute for the printer.
def simulation(numSeconds, pagesPerMinute):
labprinter = Printer(pagesPerMinute)
printQueue = Queue()
waitingtimes = []
for currentSecond in range(numSeconds):
if newPrintTask():
task = Task(currentSecond)
printQueue.enqueue(task)
if (not labprinter.busy()) and (not printQueue.isEmpty()):
nexttask = printQueue.dequeue()
waitingtimes.append(nexttask.waitTime(currentSecond))
labprinter.startNext(nexttask)
labprinter.tick()
averageWait = sum(waitingtimes)/len(waitingtimes)
print("Average Wait %6.2f secs %3d tasks remaining."%(round(averageWait),printQueue.size()))
def newPrintTask():
num = random.randrange(1, 181)
if num == 180:
return True
else:
return False
for i in range(10):
simulation(3600, 10)
|
# 二叉搜索树或二叉排序树、二叉查找树
"""
一颗二叉树,可以为空;如果不为空,则:
1:非空左子树的所有键值小于其根节点的键值
2:非空右子树的所有键值大于其根节点的键值
3:左、右子树都是二叉搜索树
Position Find
Position FindMin
Position FindMax
该页面除了第一个搜索测试没问题之后,后续应该都有错误
"""
class Node(object):
"""节点类"""
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
class Tree(object):
"""树类"""
def __init__(self, root=None):
self.root = root
def add(self, elem):
"""为树添加节点"""
node = Node(elem)
# 如果树是空的,则对根节点赋值
if self.root is None:
self.root = node
else:
queue = list()
queue.append(self.root)
# 对已有的节点进行层次遍历
while queue:
# 弹出队列的第一个元素
cur = queue.pop(0)
if cur.lchild is None:
cur.lchild = node
return
elif cur.rchild is None:
cur.rchild = node
return
else:
# 如果左右字数都不为空,加入队列继续判断
queue.append(cur.lchild)
queue.append(cur.rchild)
# 递归实现-尾递归,在程序返回的时候才递归,尾递归可以使用循环实现-测试完成
def position_find_1(self, elem, *args):
if self is None:
return
if len(args) == 0:
temproot = self.root
else:
temproot = args[0]
if temproot is not None:
if elem > temproot.elem:
return self.position_find_1(elem, temproot.rchild)
elif elem < temproot.elem:
return self.position_find_1(elem, temproot.lchild)
else:
print(temproot.elem)
return temproot.elem
else:
print("节点不存在")
# 循环实现/迭代函数,查找效率比递归高,效率取决于树的高度
def position_find_2(self, elem):
while self:
if elem > self.root.elem:
return self.position_find_2(self.root.rchild)
elif elem < self.root.elem:
return self.position_find_2(self.root.lchild)
else:
return self.root
return
# 查找最小值
def position_find_min(self, *args):
if self is None:
return
elif self.root.lchild is None:
return self.root
else:
elem = None
if args is not None:
elem = Node(*args)
if elem is None:
elem = self.root
return self.position_find_min(elem.lchild)
# 查找最大值
def position_find_max(self):
if self is not None:
elem = self.root.rchild
while elem is not None:
elem = elem.rchild
return elem
# 插入一个节点
def insert(self, elem, *args):
node_tree = Node(*args)
if self is None:
self.root = elem
self.root.lchild = None
self.root.rchild = None
else:
if node_tree is None:
node_tree = self.root
if elem < node_tree:
self.insert(elem, node_tree.lchild)
elif elem > node_tree:
self.insert(elem, node_tree.rchild)
return self
# 删除一个节点,先找到节点,没找到则递归删除
# 如果没有儿子可以直接删掉
# 如果只有1个儿子,则删除节点后,把儿子移到被删除节点位置上
# 如果有2个儿子,有两种方式
# 1:在右子树找到最小的值移动到被删除节点位置
# 2:在左子树找到最大的值移动到被删除节点位置
tree = Tree()
tree.add(30)
tree.add(15)
tree.add(41)
# tree.insert(35)
tree.position_find_2(41) |
def sumodd():
x=int(input())
y=int(input())
s=x+y
if s%2==0:
print('even')
else :
print('odd')
try:
sumodd()
except:
print('invalid')
|
n=float(input("Enter any decimal value:"))
if(n<0):
a=int(n-0.5)
else:
a=int(n+0.5)
print(a);
|
def greet_user():
"""this is a docstring, something that describe the function."""
print("Hello!!!")
greet_user() # this is how we Call function
def greet_user_by_name(name): # (name) is requared parameter
"""it will say hello and use the name entered."""
print(f"Hello, {name.title()}!")
greet_user_by_name('ali') # if doesnot choose (name) will be error
# 03/21/2021 Functions
def greet_user():
"""this is a docstring, something that describe the function."""
print("Hello!!!")
def greet_user_by_name(name):
"""
it will say hello and use the name entered.
name is required parameter, user has to pass to a function
"""
print(f"Hello, {name.title()}!")
def sum_numbers(num1, num2):
print(f"sum of {num1} and {num2} is {num2 + num1}")
print(f"square of the {num2} is : {num2 ** 2}")
# def describe_pet(pet='dog', pet_name ): always put required parameters first
def describe_pet(pet_name, pet='dog'):
"""
Keyword argument is pet with default value
:param pet_name:
:param pet: it is pet type : dog, cat etc, optional param, default is dog
:return:
"""
print(f"I have a {pet} and we call it {pet_name.title()}")
# ******************************************************
# All executions of the functions (Calling the functions)
greet_user() # this is how you CALL function
# greet_user_by_name() # expected TypeError
# greet_user_by_name('ali')
# sum_numbers(45, 78)
# sum_numbers(-46, 34)
# sum_numbers(num2=-46, num1=34)
describe_pet('Lazy', 'cat')
describe_pet('Fluffy', 'dog')
describe_pet('Fluffy')
describe_pet(pet='cat', pet_name='Pretty')
# describe_pet(pet='snake') # TypeError: required parameter is missing
|
class User:
login_attempts = 0
def __init__(self):
pass # pass means do nothing, it is just place holder
### self.login_attempts = 0 this is the alternative way of creating global variable
def increment_login_attempt(self):
print("incrementing the value by 1 ...")
self.login_attempts += 1
def reset_login_attempt(self):
print("reseting the value to 0 ...")
self.login_attempts = 0
user1 = User()
user1.increment_login_attempt()
user1.increment_login_attempt()
user1.increment_login_attempt()
user1.increment_login_attempt()
print("Login attempts: ", user1.login_attempts)
user1.reset_login_attempt()
print("Login attempts: ", user1.login_attempts)
|
# tabular data manipulation
import numpy as np
import pandas as pd
# datetime utilities
from datetime import timedelta, datetime
import datetime
# visualization
import matplotlib.pyplot as plt
# no yelling in the library
import warnings
warnings.filterwarnings("ignore")
def drop_cols(df):
'''
Takes in df and drops unnecessary indexed columns
'''
df= df.drop(columns= ['Unnamed: 0_x', 'Unnamed: 0_y', 'Unnamed: 0'])
return df
def datatype_datatime64(df):
'''
Takes in df and converts sale data column to datatime64 datatype
'''
#Changing sale date datatype to datatime64 object
df.sale_date= pd.to_datetime(df.sale_date)
return df
def plot_sale_amount(df):
'''
Takes in df and plots the distribution of sale_amount column
'''
# Plot the distribution of sale_amount
plt.figure()
df.sale_amount.hist(label= "Sale Amount")
plt.title('Plot of Sale Amount')
plt.legend()
plt.show()
def plot_item_price(df):
'''
Takes in df and plots the distribution item_price column
'''
plt.figure()
df.item_price.hist(label= "Item Price")
plt.title('Plot of Item Price')
plt.legend()
plt.show()
def set_store_index(df):
'''
Takes in df, sets sale_date as index and sorts by index
'''
# Set the index to be the datetime variable.
df= df.set_index('sale_date').sort_index()
return df
def month_day_and_sales_col(df):
'''
Takes in df and creates columns
(month column, day column, and sales_total column)
'''
# Creating day column
df['month'] = df.index.month
# Creating day column
df['day'] = df.index.day_name()
df['sales_total'] = df.sale_amount * df.item_price
return df
def prepare_germany_data(df):
'''
Prepare Germany Data
'''
#Changing date datatype to datatime64 object
df.Date= pd.to_datetime(df.Date)
# Plot of consumption
plt.figure()
df.Consumption.hist(label= "Consumption")
plt.title('Distribution of Consumption')
plt.legend()
plt.show()
# Plot of Wind
plt.figure()
df.Wind.hist(label= "Wind")
plt.title('Distribution of Wind')
plt.legend()
plt.show()
# Plot of Solar
plt.figure()
df.Solar.hist(label= "Solar")
plt.title('Distribution of Solar')
plt.legend()
plt.show()
# Plot of Wind+Solar
plt.figure()
df['Wind+Solar'].hist(label= "Wind and Solar")
plt.title('Distribution of Wind + Solar')
plt.legend()
plt.show()
#Set the index to be the datetime variable.
df= df.set_index('Date').sort_index()
#Adding month column
df['month'] = df.index.month
#Creating year column
df['year'] = df.index.year
#Fill any missing values
df = df.fillna(value=0)
return df |
print("Introduce el valor del radio: ")
rRadio = float(input())
print("Introduce el angulo: ")
rAngulo = float(input())
rVolumen = float(3) / 4 * (3.1416 * rRadio ** 3 / 360 * rAngulo)
print("El volumen de la cuña es: ", end='', flush=True)
print(rVolumen, end='', flush=True)
|
import math
def sum_of_primes(limit):
# This function finds the sum of all the prime numbers below the limit.
count = limit
total = 2
# If the input limit is even, it's stepped down to the next odd.
if count % 2 == 0:
count -= 1
# The while loop moves the count down from the limit by the odds, and checks
# if they're prime numbers. If they are, the number is added to the total.
while count > 1:
if check_if_prime(count):
total += count
count -= 2
return total
def is_divisible_5(input_num):
# A filter to prevent unnecesary computation.
# Returns True if the last digit of the input_num is 5 or 0 to
# determine if it's divisible by 5, excluding 5 itself.
if input_num == 5:
return False
input_string = str(input_num)
if input_string[len(input_string) - 1] == '5' or input_string[len(input_string) - 1] == '0':
return True
return False
def is_divisible_3(input_num):
# A filter to prevent unnecesary computation.
# Returns True if the sum of the digits of the input_num is
# divisible by 3, exluding 3 itself.
if input_num == 3:
return False
input_string = str(input_num)
total = 0
for char in input_string:
total += ord(char)
if total % 3 == 0:
return True
return False
def check_if_prime(input_num):
# After a series of quick tests eliminate multiples of
# 2, 3, and 5, a loop from 7 to sqrt(input_num) counting by odds
# tries to divide the input_num by the counter (poss_factors)
# to see if it has any factors. If it has no factors, it returns True.
if is_divisible_3(input_num):
return False
if is_divisible_5(input_num):
return False
if input_num == 2:
return True
if input_num % 2 == 0:
return False
poss_factors = 7
for counter in range(2, int(math.sqrt(input_num)) / 2):
if input_num % poss_factors == 0:
return False
poss_factors += 2
return True
print sum_of_primes(2000000)
|
'''
1. Palindrome(n)
Write a recursive function that iteratively calculates whether a sequence is a palindrome
(the same forwards as backwards). You need to explicitly highlight the base case
and recursive case in your comments (marks will be heavily weighted towards this).
'''
import math #importing the math function
n = (input('Please enter a word/number to check if it is a palindrome or not :')) #here i am asking the user to input a word or numbers to check if it is a
#palindrome - the input is in the form of a string data type and is places in the variable 'n'
def recursive_palindrome(n):
if len(n) < 1: #if the length of the string is less than 1... complete the following: #here is the base case
return "This is a palindrome"
else:
if n[0] == n[-1]: #if the first letter is equal to the last letter - complete the following: #here is the recursive case
return recursive_palindrome(n[1:-1])
else:
return "This is not a palindrome"
print(recursive_palindrome(n)) #envoking the function while also printing the output |
import copy
dictionary = {'key1': 'value1', 'key2': 'value2'}
dictionary['key3'] = 'value3'
print(dictionary)
print(dictionary['key1'])
d1 = dict(key1='val1', key2='val2')
print(d1)
d2 = {
'str': 'string as key',
12345: 'int as key',
(1, 2, 3): 'tuple as key'
}
print(d2)
print(d2[(1, 2, 3)])
# check key in dictionary
print(d2.get('no_key'))
# d2['no_key'] key not exist return error
if d2.get('no_key') is None:
print('create key')
if 'no_key' not in d2:
print('create key')
# check value in dictionary
print('int as key' in d2.values())
print(len(d2))
print()
print('loop keys')
for k in d2:
print(k)
print()
print('loop values')
for v in d2.values():
print(v)
print()
print('loop key value')
for i in d2.items():
print(i)
print(i[0], ' => ', i[1])
print()
print('loop key value 2')
for k, v in d2.items():
print(k, '=>', v)
print()
print('sub dictionary')
d3 = {
'person1': {
'name': 'Anna',
'lastname': 'Mag'
},
'person2': {
'name': 'Lois',
'lastname': 'Clarck'
},
}
for pk, pv in d3.items():
print(pk)
for vk, vv in pv.items():
print(f'\t{vk} => {vv}')
print()
print('assignment the dictionary they point to same object ')
d4 = {1:'a', 2:'b', 3:'c'}
d5 = d4
d5[1] = 'abc'
print(d4)
print(d5)
print()
print('use deepcopy to have identical dictionary ')
d5 = copy.deepcopy(d4)
d5[1] = 'xpt'
print(d4)
print(d5)
|
cup_str = input('Введите количество чашек ') # age_str это строка
cup = int(cup_str) # age это int
cup_bonus = int(cup / 6)
print(cup_bonus)
|
#Code written by Farbod Kamiab
#The code reads GPS data from the New York City Taxi & Limousine Commission (NYCT&L) data on taxi trips and plots the GPS points on a map of New York City.
import numpy as np
import pandas as pd
import matplotlib.pyplot as pl
import pygmaps #One needs to install pygmaps to run this code
number_rows=14863778 #This is the total number of rows in the file
READ_ALL_DATA = 0 #SET THIS TO 1 IF YOU LIKE ALL DATA TO BE READ OR TO 0 FOR A SMALLER SAMPLE OF DATA FOR A FASTER RUN --> this code was run for a random sample of 10000 rows from the data as the purpose was map illustration.
# READING DATA
#Location of the file should be changed accordingly, as the data file is too large to be uploaded on the Github repository
if (READ_ALL_DATA==1):
#TAKES ALL OF DATA
df=pd.read_csv('./trip_data_1_2010.csv', nrows=number_rows, usecols=[' pickup_longitude', ' pickup_latitude', ' dropoff_longitude', ' dropoff_latitude'])
else:
#IF NOT, TAKES A SAMPLE OF RANDOM ROWS FROM THE FIRST 'number_rows' ROWS OF DATA
number_rows=1000
df_initial=pd.read_csv('./trip_data_1_2010.csv', nrows=number_rows)
rows = np.random.choice(df_initial.index.values, 10)
df = df_initial.ix[rows]
#########################################################################
# SETTING COORDINATES OF THE MAP TO NEW YORK CITY
pickup_map = pygmaps.maps(40.752928, -73.881528, 12)
dropoff_map = pygmaps.maps(40.752928, -73.881528, 12)
# PUTTING POINTS ON THE MAP AND GETTING RID OF BAD DATA ROWS
for i in rows:
pickup_lat=df[' pickup_latitude'][i]
pickup_long=df[' pickup_longitude'][i]
dropoff_lat=df[' dropoff_latitude'][i]
dropoff_long=df[' dropoff_longitude'][i]
if (isinstance(pickup_lat, float) and isinstance(pickup_long, float) and isinstance(dropoff_lat, float) and isinstance(dropoff_long, float)):
pickup_map.addpoint(df[' pickup_latitude'][i], df[' pickup_longitude'][i], "#FF0000")
dropoff_map.addpoint(df[' dropoff_latitude'][i], df[' dropoff_longitude'][i], "#0000FF")
# PRINTING OUTPUT
pickup_map.draw('./pickup_map.html')
dropoff_map.draw('./dropoff_map.html')
|
import sqlite3
dataFile = 'data/data.db'
defaultData = 'data/default_data.txt'
def init():
conn = sqlite3.connect(dataFile)
cursor = conn.cursor()
cursor.execute('CREATE TABLE soul (id INTEGER PRIMARY KEY AUTOINCREMENT, text VARCHAR(1024))')
try:
with open(defaultData, 'r', encoding='UTF-8') as f:
lines = f.readlines()
for line in lines:
cursor.execute('INSERT INTO soul (text) VALUES (?)',(line,))
finally:
if f:
f.close()
cursor.close()
conn.commit()
conn.close()
def add(text):
conn = sqlite3.connect(dataFile)
cursor = conn.cursor()
cursor.execute('INSERT INTO soul (text) VALUES (?)',(text,))
cursor.close()
conn.commit()
conn.close()
def list():
conn = sqlite3.connect(dataFile)
cursor = conn.cursor()
cursor.execute('SELECT * FROM soul ORDER BY id')
values = cursor.fetchall()
cursor.close()
conn.close()
return values
def get():
conn = sqlite3.connect(dataFile)
cursor = conn.cursor()
cursor.execute('SELECT * FROM soul ORDER BY RANDOM() LIMIT 1')
value = cursor.fetchone()
cursor.close()
conn.close()
return value
def delete(id):
conn = sqlite3.connect(dataFile)
cursor = conn.cursor()
cursor.execute('DELETE FROM soul WHERE id=?',(id,))
cursor.close()
conn.commit()
conn.close() |
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
sum = int(num1) + int(num2)
print('The sum of {0} + {1} is {2}'.format(num1, num2, sum))
|
# Automatic Sebastian game player
# B551 Fall 2020
#
# Based on skeleton code by D. Crandall
#
#
# This is the file you should modify to create your new smart player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice object which records the
# result of the first roll (state of 5 dice) and current Scorecard.
# You should implement this method so that it returns a (0-based) list
# of dice indices that should be re-rolled.
#
# 2. It then re-rolls the specified dice, and calls second_roll, with
# the new state of the dice and scorecard. This method should also return
# a list of dice indices that should be re-rolled.
#
# 3. Finally it calls third_roll, with the final state of the dice.
# This function should return the name of a scorecard category that
# this roll should be recorded under. The names of the scorecard entries
# are given in Scorecard.Categories.
#
from SebastianState import Dice
from SebastianState import Scorecard
import random
import itertools
import copy
class SebastianAutoPlayer:
def __init__(self):
pass
def first_roll(self, dice, scorecard):
return self.expectimax(dice.dice, scorecard)
def second_roll(self, dice, scorecard):
return self.expectimax(dice.dice, scorecard)
def third_roll(self, dice, scorecard):
return self.fit_in_category(dice.dice, scorecard)
def possible_moves(self):
'''
Return a list of possible combinations of rerolls that can happen.
Eg, [[],[0],[0,1],[0,2],[0,3],[0,4],[1,1],......,[0,1,2,3,4]
'''
valid_moves = []
dice_numbers = [0,1,2,3,4]
valid_moves.append([])
for i in range(1,6):
for subset in itertools.combinations(dice_numbers, i):
valid_moves.append(list(subset))
return valid_moves
def dice_combination(self, num_dice_roll):
'''
Returns a list of all dice combinations if the selected dice are rolled
For every dice combination of [1,2,3,4,5,6]
'''
dice_roll_possibilities = [1,2,3,4,5,6]
return list(itertools.product(dice_roll_possibilities, repeat=num_dice_roll))
def fit_in_category(self, dice, scorecard):
'''
This function returns the category with the maximum value of score.
'''
score = self.calculate_score_for_dice(dice, scorecard)
max_score_category = max(score, key=lambda x: score[x])
return max_score_category
def calculate_score_for_dice(self, dice_value, scorecard):
'''
Find the score for each category possible for current dice pattern.
This function returns a dictionary of score values for all categories.
'''
Numbers = { "primis" : 1, "secundus" : 2, "tertium" : 3, "quartus" : 4, "quintus" : 5, "sextus" : 6 }
Categories = [ "primis", "secundus", "tertium", "quartus", "quintus", "sextus", "company", "prattle", "squadron", "triplex", "quadrupla", "quintuplicatam", "pandemonium" ]
counts = [dice_value.count(i) for i in range(1,7)]
score = {}
already_assigned = scorecard.scorecard.keys()
for category in Categories - already_assigned:
if category in Numbers:
score[category] = counts[Numbers[category]-1] * Numbers[category]
elif category == "company":
score[category] = 40 if sorted(dice_value) == [1,2,3,4,5] or sorted(dice_value) == [2,3,4,5,6] else 0
elif category == "prattle":
score[category] = 30 if (len(set([1,2,3,4]) - set(dice_value)) == 0 or len(set([2,3,4,5]) - set(dice_value)) == 0 or len(set([3,4,5,6]) - set(dice_value)) == 0) else 0
elif category == "squadron":
score[category] = 25 if (2 in counts) and (3 in counts) else 0
elif category == "triplex":
score[category] = sum(dice_value) if max(counts) >= 3 else 0
elif category == "quadrupla":
score[category] = sum(dice_value) if max(counts) >= 4 else 0
elif category == "quintuplicatam":
score[category] = 50 if max(counts) == 5 else 0
elif category == "pandemonium":
score[category] = sum(dice_value)
return score
def calculate_max_score(self, score):
'''
This function returns the maximum value of score in the dictionary.
'''
max_score_category = max(score, key=lambda x: score[x])
max_score = score[max_score_category]
return max_score
def expectimax(self, dice, scorecard):
'''
This function performs the expectimax algorithm and returns the best combination of move for maximizing the score.
The expectimax code written below only processes one layer and this is due to the reason that processing 2 layers was much expensive and it
gave almost similar results.
'''
valid_moves = self.possible_moves()
score_list = [0] * len(valid_moves)
for i in range(len(valid_moves)):
expectation = 0
outcomes = 0
for comb in self.dice_combination(len(valid_moves[i])):
new_dice = copy.deepcopy(dice)
for j in range(len(comb)):
new_dice[valid_moves[i][j]] = comb[j]
cost = self.calculate_max_score(self.calculate_score_for_dice(new_dice, scorecard))
expectation += cost
outcomes += 1
score_list[i] = expectation / outcomes
best_move_index = score_list.index(max(score_list))
best_move = valid_moves[best_move_index]
return best_move
|
import sqlite3
conn = sqlite3.connect('answers.db') # You can create a new database by changing the name within the quotes
c = conn.cursor() # The database will be saved in the location where your 'py' file is saved
# Create table - ANSWERS
c.execute('''CREATE TABLE ANSWERS
([generated_id] INTEGER PRIMARY KEY,[Username] text, [Task_Code] integer, [Question_Code] integer, [Answer_Score] integer, [Date] date)''')
conn.commit() |
import re
class Phone(object):
def __init__(self, phone_number):
self.number=phone_number
parse_number=re.sub(r'^(\+1)|[()-. ]',"",self.number)
if (parse_number[0]=="1" and len(parse_number)==11):
parse_number=re.sub(r'^1',"",parse_number)
if len(parse_number)>10 or parse_number[0]=="1" or parse_number[0]=="0" or parse_number[3]=="1" or parse_number[3]=="0" or re.findall(r'[a-z]@:\!',parse_number):
raise ValueError(".+")
self.number=parse_number
self.area_code=parse_number[:3]
def pretty(self):
return "("+self.number[:3]+")"+" "+self.number[3:6]+"-"+self.number[6:]
|
NODE, EDGE, ATTR = range(3)
from collections import defaultdict
class Node(object):
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge(object):
def __init__(self, src, dst, attrs):
self.src = src
self.dst = dst
self.attrs = attrs
def __eq__(self, other):
return (self.src == other.src and
self.dst == other.dst and
self.attrs == other.attrs)
class Graph(object):
def __init__(self, data=None):
if type(data)!=list and data!=None:
raise TypeError(".+")
print(type(data))
self.data=data
self.nodes=[]
self.edges=[]
self.attrs=defaultdict()
if self.data!=None:
for i in self.data:
if len(i)==0 or len(i)==1:
raise TypeError(".+")
if (i[0]!=NODE and i[0]!=EDGE and i[0]!=ATTR):
raise ValueError(".+")
if i[0] == NODE:
if len(i)>3 or len(i)<3:raise ValueError(".+")
self.nodes.append(Node(i[1], i[2]))
elif i[0]==EDGE:
if len(i) > 4 or len(i) < 4: raise ValueError(".+")
self.edges.append(Edge(i[1],i[2],i[3]))
elif i[0]==ATTR:
if len(i) > 3 or len(i) < 3: raise ValueError(".+")
self.attrs[i[1]]=i[2]
|
"""
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a common practice to export both constants and functions that work with
those constants (ex. the constants in the os, subprocess and re modules).
You can learn more here: https://en.wikipedia.org/wiki/Enumerated_type
"""
# Possible sublist categories.
# Change the values as you see fit.
SUBLIST =0
SUPERLIST = 1
EQUAL = 2
UNEQUAL = 3
def sublist(list_one, list_two):
if list_one==list_two:
return EQUAL
elif check(list_one,list_two):
return SUBLIST
elif check(list_two,list_one):
return SUPERLIST
else:
return UNEQUAL
def check(a,b):
l1,l2=len(a),len(b)
return l1<l2 and any(b[i:i+l1]==a for i in range(l2)) |
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def get_length(list):
# determine length of the list
length_list = 0
current_node = list
current_node2 = list.next
while current_node != None and current_node != current_node2:
current_node = current_node.next
if current_node2 != None:
current_node2 = current_node2.next
if current_node2 != None:
current_node2 = current_node2.next
length_list += 1
# Check if the list is circular
if current_node == None:
return length_list
else:
return "circular"
def question5(list, m):
# check if m is integer
if type(m) != int:
return "Please enter an integer!"
length_list = get_length(list)
if length_list == "circular":
return "Linked list is circular!"
if length_list < m:
return "Number entered is greater than the length of list!"
# find mth element by traversing
current_node = list
for i in range(length_list - m):
current_node = current_node.next
return current_node.data
def test5():
n1, n2, n3, n4, n5 = Node(1), Node(2), Node(3), Node(4), Node(5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
print (question5(n1,3))
test5()
|
# создай список с целыми числами произвольных значений произвольной длины,
# отсортируй его по возрастанию и убыванию, запиши результат в отдельные переменные
datas = [10, 45, 165, 1834, 23, 57, 4]
minmax = sorted(datas)
maxmin = sorted(datas, reverse=True)
# даны два списка с числами, нужно вернуть список, который состоит из общих чисел
a = [1, 4, 5, 7, 23, 36, 67, 78, 99, 134, 142, 150]
b = [3, 5, 6, 19, 67, 77, 123, 134, 172, 323, 434]
def c(z,v):
return [x for x in z if x in v]
print(c(a,b))
# напиши функцию, которая складывает сумму двух чисел, переданных ей на вход
def summa(a,b):
c = a + b
print(c)
summa(4,6)
# напиши функцию, которая возвращает тип данных, переданный ей на вход, и возвращает его на русском языке (пример: "строка")
def checktype(dannye):
if dannye.isdigit() == True:
print('число')
else:
print('строка')
checktype('12')
# напиши функцию, которая принимает на вход любое количество чисел и говорит, есть ли среди них четное
def chetnoe(chislishko):
if chislishko % 2 == 0:
print('ЧЕТНОЕ')
else:
print('НЕЧЕТНОЕ')
chetnoe(5)
# используй тернарный оператор, чтобы вызвать функцию, если возраст больше 21 года, в противном случае верни сообщение "мы не продаем алкоголь несовершеннолетним"
age = 17
sell_alcohol()
def sell_alcohol(age):
if age < 21:
return('Мы не продаем алкоголь несовершеннолетним')
else:
return
print(sell_alcohol(age))
# загрузи список ключевых слова из модуля keyword, преобразуй его в строку со словами, разделенными запятой
import keyword
# напиши функцию, которая проверит, является ли строка ключевым словом, используй модуль keyword
# не забудь сначала изучить этот модуль с помощью dir, чтобы узнать, есть ли там полезные методы
print(', '.join(keyword.kwlist))
def keyy(part):
print(keyword.iskeyword(part))
keyy('False')
# посчитайте, сколько раз символ встречается в строке, функция принимает на вход символ и строку
def skolko(x,y):
print(x.count(y))
skolko('sdAsasasasasfdsfs','a')
|
import sqlite3 #enable control of an sqlite database
DB_FILE="ultimate.db"
db = sqlite3.connect(DB_FILE) #open if file exists, otherwise create
c = db.cursor() #facilitate db ops
#######################################
# USERS TABLE
# TABLE BREAKDOWN
# 1 BLOCK = identification to connect databases
# 2 BLOCK = login info
# 3 BLOCK = user's game inventory
# 4 BLOCK = user's game data
# 5 BLOCK = user settings
usermainTable = """ CREATE TABLE userStuff (
username TEXT,
password BLOB
);"""
userTable = """ CREATE TABLE userStuff (
id INTEGER,
username TEXT,
password BLOB,
bandages INTEGER,
food INTEGER,
fuel INTEGER,
money INTEGER,
shipParts INTEGER,
weapons INTEGER,
distance INTEGER,
difficulty TEXT,
foodSetting TEXT,
speedSetting TEXT,
foodFactor INTEGER,
speedFactor INTEGER
);"""
#######################################
#######################################
# USER'S TEAM TABLE
# TABLE BREAKDOWN
# 1 BLOCK = identification to connect databases
# 2 BLOCK = crew members of user
# 3 BLOCK = status of crew members; only important if "dead"
userteamTable = """ CREATE TABLE teams (
id INTEGER,
name TEXT,
crew0 TEXT,
crew1 TEXT,
crew2 TEXT,
nameStat TEXT,
crew0Stat TEXT,
crew1Stat TEXT,
crew2Stat TEXT
);"""
#######################################
#######################################
# MEMBER ENCOUNTERS TABLE
# TABLE BREAKDOWN
# CRITERIA = first check if criteria is True
# else, go to next random encounter
# ENCOUNTER = attach crewmember name in front
# RESULT = change crewmember status
"""
ex. criteria | encounter | result
foodSetting == "Meager" gets cannibalized dead
speedSetting == "Fast" is exhausted exhausted
health <= 30 gets pneumonia sick
CRITERIA: foodSetting {Meader, Normal, Banquet}
speedSetting {Slow, Steady, Fast}
hunger
energy
health
shipHealth
"""
userencounterTable = """ CREATE TABLE userencounters (
criteria BLOB,
encounter TEXT,
result TEXT
);"""
#######################################
#######################################
# SITUATIONS TABLE
# TABLE BREAKDOWN
# SITUATION = print out text
# RESULT = change game inventory
"""
ex. situation | result
The crew encountered a mysterious box. It explodes! bandages, -200
The starship got attacked by a space squid! shipParts, -30
"""
situationTable = """ CREATE TABLE situations (
situation TEXT,
result TEXT
);"""
#######################################
#c.execute(userTable)
#c.execute(userteamTable)
c.execute(usermainTable)
c.execute(userencounterTable)
c.execute(situationTable)
db.commit()
db.close()
|
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Created on Jan 24, 2014
@author: Songfan
'''
''' algorithm:
if current item == target item: return
elif first item < current item:
if first item < target item < current item: search left
else: search right
else:
if current item < target item < last item: search right
else: search left
'''
def findItem(A, e):
n = len(A)
if n == 0: return -1
left = 0
right = n - 1
while left <= right:
mid = (left + right) // 2
if A[mid] == e: return mid
''' caveat: compare A[left] to A[mid] '''
if A[left] <= A[mid]:
if A[left] <= e and e < A[mid]:
right = mid - 1
else:
left = mid + 1
else:
if A[mid] < e and e <= A[right]:
left = mid + 1
else:
right = mid - 1
return -1
A = [4, 5, 6, 7, 0, 1, 2]
e = 3
print findItem(A, e), 'should be -1'
e = 5
print findItem(A, e), 'should be 1'
e = 1
print findItem(A, e), 'should be 5'
e = 4
print findItem(A, e), 'should be 0'
e = 2
print findItem(A, e), 'should be 6'
#
# ''' thought: there is no duplicates, we can safely use binary search,
# if current item == target item: return
# elif current item < target item:
# if left item > target item, target is not in left, search right
# elif right item < target item, target is not in right, search left
# else: should search both sides
# else (current item > target item):
# if left item > target item, target is not in left, search right
# if right item > target item, target is not in right, search left
# else: should search both sides
# '''
#
# def findIn(A, e):
# # assume correct input
# return _find(A, e, 0, len(A) - 1)
#
# def _find(A, e, left, right):
# n = len(A)
# if n == 0 or left > right: return -1
# mid = (left + right) // 2
# if A[mid] == e: return mid
# elif A[mid] < e:
# if A[left] > e: return _find(A, e, mid + 1, right)
# elif A[right] < e: return _find(A, e, left, mid - 1)
# else: return max(_find(A, e, left, mid - 1), _find(A, e,mid + 1, right))
# else:
# if A[left] > e: return _find(A, e, mid + 1, right)
# elif A[right] > e: return _find(A, e, left, mid - 1)
# else: return max(_find(A, e, left, mid - 1), _find(A, e,mid + 1, right))
#
#
#
#
# print 'method 2, my implementation, not very efficient'
# e = 3
# print findIn(A, e), 'should be -1'
#
# e = 5
# print findIn(A, e), 'should be 1'
#
# e = 1
# print findIn(A, e), 'should be 5'
#
# e = 4
# print findIn(A, e), 'should be 0'
#
# e = 2
# print findIn(A, e), 'should be 6'
#
#
#
#
#
|
'''
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Created on Feb 12, 2014
@author: Songfan
'''
''' method 1: sort, 2 ptrs meet in the middle. Caveat: for loop on the front ptr p1, let middle ptr p2 and rear ptr p3 meet in the middle '''
import sys
def solution(num, target):
n = len(num)
if n <= 2: return -1
num = sorted(num)
closest = 0
minGap = sys.maxint
for p1 in range(n - 2):
p2 = p1 + 1
p3 = n - 1
while p2 < p3:
sum3 = num[p1] + num[p2] + num[p3]
gap = abs(sum3 - target)
if gap < minGap:
closest = sum3
minGap = gap
if sum3 == target: return closest
elif sum3 < target: p2 += 1
else: p3 -= 1
return closest
num = [-1, 2, 1, -4]
print solution(num, 1)
|
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
Created on Jan 12, 2014
@author: Songfan
'''
''' thought: two pointer track from the back '''
def addBinary(a, b):
assert(isinstance(a,str) and isinstance(b,str)), 'input error'
na = len(a)
nb = len(b)
res = ''
carry = 0
while(na > 0 or nb > 0):
''' mistake track: since we decrement na and nb, we need to judge 'na > 0' instead of 'na == 0' '''
if na > 0: v1 = int(a[na-1])
else: v1 = 0
if nb > 0: v2 = int(b[nb-1])
else: v2 = 0
tmpTotal = v1 + v2 + carry
tmpV = tmpTotal % 2
carry = tmpTotal // 2
res = str(tmpV) + res
na -= 1
nb -= 1
if carry:
res = '1' + res
return res
a = '11'
b = '1'
print addBinary(a, b) |
'''
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
able to handle dups
Created on Jan 12, 2014
@author: Songfan
'''
'''
recursion + memoization
recursively add the last element to the every possible position of the previous list
O(N!) time worst case, O(N!) space
'''
def permutations(A):
assert(isinstance(A,list)),'input error'
return _permutations(A, {}, len(A) - 1)
def _permutations(A, h, m):
n = len(A)
if n == 0: return []
if n == 1: return [A]
if m in h: return h[m]
prevPerms = _permutations(A[:m], h, m - 1)
lastElem = A[m]
currPerms = []
for perm in prevPerms:
for i in range(len(perm)+1):
''' add the element to possible location '''
''' caveat: since it is list not string, we cannot use +, instead, use extend which requires deep copy of the tmp variable '''
tmp = perm[:i][:]
tmp.extend([lastElem])
tmp.extend(perm[i:])
if tmp not in currPerms:
currPerms.append(tmp)
h[m] = currPerms
return currPerms
''' unittest '''
A = [1,2,1]
print permutations(A) |
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Created on Feb 2, 2014
@author: Songfan
'''
''' start from left and jump right, check every possible location and find out max reach position (currMax), if currMax >= n in the end, return True
'''
def solution(A):
n = len(A)
if n == 0: return False
currMax = 0
for i in range(n):
if i > currMax:
''' we cannot even reach i '''
return False
currMax = max(currMax, A[i] + i)
return currMax >= n - 1
A = [2,3,1,1,4]
print solution(A), 'should be True'
A = [3,2,1,0,4]
print solution(A), 'should be False'
|
'''
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Created on Jan 12, 2014
@author: Songfan
'''
''' algorithm: reuse merge 2 sorted list, O(n1+n2+...+nk) time. O(1) space '''
from LC_mergeTwoSortedList import mergeList, ListNode, LinkedList
def mergeKList(lists):
if len(lists) == 0: return lists
p = lists[0]
for i in range(1,len(lists)):
p = mergeList(p, lists[i])
return p
''' unittest '''
n1 = ListNode(2)
n2 = ListNode(4)
n3 = ListNode(5)
n1.next = n2
n2.next = n3
A = LinkedList(n1)
print 'A:',A
n4 = ListNode(3)
n5 = ListNode(4)
n6 = ListNode(8)
n4.next = n5
n5.next = n6
B = LinkedList(n4)
print 'B:',B
n7 = ListNode(1)
n8 = ListNode(6)
n9 = ListNode(7)
n10 = ListNode(9)
n7.next = n8
n8.next = n9
n9.next = n10
C = LinkedList(n7)
print 'merge A, B, C:',LinkedList(mergeKList([n1,n4,n7])) |
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Created on Jan 2, 2014
@author: Songfan
'''
''' thought: two pointer from begin and end, meet together '''
def isAlphaNum(s):
return s.isalpha() or s.isdigit()
def isValidParlin(s):
assert(isinstance(s,str)),'input error'
n = len(s)
if n == 1: return True
s = s.lower()
p1 = 0
p2 = n - 1
while p1 < p2:
if not isAlphaNum(s[p1]):
p1 += 1
continue
elif not isAlphaNum(s[p2]):
p2 -= 1
continue
elif s[p1] != s[p2]:
return False
else:
p1 += 1
p2 -= 1
return True
s = 'A man, a plan, a canal: Panama'
print isValidParlin(s), 'should be True'
s = 'race a car'
print isValidParlin(s), 'should be False'
|
'''
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
Created on Feb 6, 2014
@author: Songfan
'''
''' dp + stack: '''
from stack import Stack
def solution(S):
n = len(S)
if n <= 1: return 0
s = Stack()
maxLen = 0
last = -1
for i in range(n):
if S[i] == '(':
s.push(i)
else:
if s.isEmpty():
last = i
else:
s.pop()
# global best vs. current best
if s.isEmpty():
maxLen = max(maxLen, i - last)
else:
maxLen = max(maxLen, i - s.peek())
return maxLen
S = '())(())'
print solution(S),'should be 4'
|
'''
Linear time selection
select the k-th largest
Created on Apr 5, 2014
@author: Songfan
'''
import timeit
# def by_med(A):
# A.sort()
# return A[len(A)//2]
#
# def partition(A):
# n = len(A)
# if n < 5:
# pi = by_med(A)
# else:
# ''' median of median as pivot '''
# meds = [by_med(A[i:i+5]) for i in range(0,n-4,5)]
# pi = by_med(meds)
# A.remove(pi)
# lo = [x for x in A if x <= pi]
# hi = [x for x in A if x > pi]
# return pi, lo, hi
def partition(A):
''' first element as pivot '''
pi, seq = A[0], A[1:]
lo = [x for x in seq if x <= pi]
hi = [x for x in seq if x > pi]
return pi, lo, hi
def select(A, k):
pi, lo, hi = partition(A)
n = len(lo)
if k == n: return pi
elif k < n: return select(lo, k)
else: return select(hi, k-n-1)
''' unittest '''
A = [3,2,5,4,1,6,7]
st = timeit.default_timer()
print select(A, 1), 'should be 1'
print 'time: ', timeit.default_timer() - st
st = timeit.default_timer()
print select(A, 3), 'should be 3'
print 'time: ', timeit.default_timer() - st
|
'''
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
Created on Jan 26, 2014
@author: Songfan
'''
import copy
''' thought: DP '''
def solution1(C, t):
h = {}
for k in range(1,t+1):
if k in C:
''' items that is the solution themselves, ex: [7] in this case '''
h[k] = [[k]]
for c in C:
if k - c in h:
''' check the previous item to see if them can achieve current k by addint any element in C'''
tmp = copy.deepcopy(h[k-c])
res = h.get(k,[])
for t in tmp:
if c >= t[-1]:
''' make sure ascending order '''
t.append(c)
res.append(t)
h[k] = res
return h[k]
''' dfs '''
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, C, t):
result = []
C = sorted(C)
self._dfs(C, t, [], result, 0)
return result
def _dfs(self, C, t, intermediate, result, currVal):
''' intermediate: track the current solution
result: store the final result
currVal: make sure ascending order '''
if t == 0:
''' we have found a solution '''
result.append(intermediate[:])
return
for c in C:
if t < c: return
if c >= currVal:
''' the number appended to intermediate solution has to be >= the current largest '''
intermediate.append(c)
self._dfs(C, t - c, intermediate, result, c)
''' remember to pop back '''
intermediate.pop()
''' thought: recursion + memoization '''
def solution3(C, t):
if len(C) == 0: return
return _comboSum(C, t, {})
def _comboSum(C, t, h):
if t <= 0: return
if t in h: return h[t]
res = []
if t in C:
''' this means [t] is a solution '''
res.append([t])
for c in C:
prev = _comboSum(C, t - c, h)
if prev:
prevCopy = copy.deepcopy(prev)
for item in prevCopy:
if c >= item[-1]:
''' ascending ordert '''
item.append(c)
res.append(item)
h[t] = res
return res
C = [2,3,6,7]
t = 7
print solution1(C,t)
solution2 = Solution()
print solution2.combinationSum(C, t)
print solution3(C,t) |
'''
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
Created on Feb 6, 2014
@author: Songfan
'''
from stack import Stack
def solution(path):
n = len(path)
if n == 0: return ''
if path[0] != '/': return ''
s = Stack()
i = 0
while i < n:
if '/' in path:
j = path[i:].index('/')
dir = path[i:j+i]
if len(dir) != 0 and dir != '.':
if dir == '..':
if not s.isEmpty():
s.pop()
else:
s.push('/' + dir)
if j != 0:
i += j
else:
i += 1
else:
break
res = []
if s.isEmpty():
res.append('/')
while not s.isEmpty():
res.append(s.pop())
res = ''.join(res[::-1])
return res
path = "/a/./b/../../c/"
print solution(path), 'should be /c'
path = "/../"
print solution(path), 'should be /'
path = "/home//foo/"
print solution(path), 'should be /home/foo'
|
'''
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Created on Jan 12, 2014
@author: Songfan
'''
''' thought: two pointer strategy, one is the running pointer, the other is the pointer that track the end
of the modified list '''
def removeElement(A, e):
n = len(A)
if n == 0: return A, 0
tail = 0
for i in range(n):
if A[i] != e:
A[tail] = A[i]
tail += 1
return A[:tail], tail
''' unittest '''
A =[]
e = 5
print removeElement(A, e), ', should be ([], 0)'
A =[5]
e = 5
print removeElement(A, e), ', should be ([], 0)'
A =[1,5]
e = 5
print removeElement(A, e), ', should be ([1], 1)'
A =[5,1,5,2,5]
e = 5
print removeElement(A, e), ', should be ([1,2], 2)' |
'''
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
Created on Feb 1, 2014
@author: Songfan
'''
''' for loop: 1. check rows, 2. check cols, 3. check 3*3 blocks
1 and 2 can be combined
'''
def validSudoku(board):
''' check rows '''
''' check rows and cols'''
for i in range(9):
memRow = {}
memCol = {}
for j in range(9):
if board[i][j] != '.':
if board[i][j] in memRow:
return False
else:
memRow[board[i][j]] = True
if board[j][i] != '.':
if board[j][i] in memCol:
return False
else:
memCol[board[j][i]] = True
''' check 3 by 3 blocks '''
for i in range(0,9,3):
for j in range(0,9,3):
memBlock = {}
for m in range(3):
for n in range(3):
if board[i+m][j+n] != '.':
if board[i+m][j+n] in memBlock:
return False
else:
memBlock[board[i+m][j+n]] = True
return True
board = [['5','3','.','.','7','.','.','.','.'],
['6','.','.','1','9','5','.','.','.'],
['.','9','8','.','.','.','.','6','.'],
['8','.','.','.','6','.','.','.','3'],
['4','.','.','8','.','3','.','.','1'],
['7','.','.','.','2','.','.','.','6'],
['.','6','.','.','.','.','2','8','.'],
['.','.','.','4','1','9','.','.','5'],
['.','.','.','.','8','.','.','7','9']]
print validSudoku(board) |
'''
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
Created on Jan 2, 2014
@author: Songfan
'''
''' thought:
1. valid characters are: '+-.e'
2. leading or trailing white space are valid
3. '+' and '-' should only appear in the beginning of the number or after 'e' followed with number
4. 'e' should follow with a valid number
conclusion:
1. validNum: divide the number by 'e', first part should be a valid float, second part should be a valid int (with sign allowed)
2. validFloat: divide the number by '.', first part should be a valid int (with sign allowed), second part should be a valid int (no sign allowed)
'''
def strip(s, c = ' '):
if s == '': return s
startPos = 0
endPos = len(s)
for e in s:
if e == ' ':
startPos += 1
else:
break
for e in s[::-1]:
if e == ' ':
endPos -= 1
else:
break
return s[startPos:endPos]
def findChar(s, c):
for i in range(len(s)):
if s[i] == c:
return i
return -1
def validFloat(s):
''' check if is valid float or int, (no leading or trailing space or 'e' allowed)'''
if s == '.': return False
dotPos = findChar(s, '.')
if dotPos != -1:
return validInt(s[:dotPos], True) and validInt(s[dotPos+1:], False)
else:
return validInt(s, True)
def validInt(s, signAllowed):
''' check if is a valid int (no leading or trailing space allowed), signAllowed is a flag is used for the following situation,
s = '+23.03', if it is divided by '.', then the front part '+23' is a signAllowed int, while back part '03' is not '''
for i in range(len(s)):
if i==0 and signAllowed and s[i] in '+-':
continue
elif s[i] in '0123456789':
continue
else:
return False
return True
def validNum(s):
# strip the leading and trailing white space
ss = strip(s)
ePos = findChar(ss, 'e')
if ePos != -1:
# if 'e' exist, then first part should be a valid float number; second part should be a valid int
return validFloat(ss[:ePos]) and ss[:ePos] != '' \
and validInt(ss[ePos+1:], True) and ss[ePos+1:] != ''
else:
return validFloat(ss)
''' unittest strip '''
print 'unittest: strip'
s = ' 34 '
print strip(s) + ' should be 34'
s = ''
print strip(s) + ' should be '''
print
''' unittest findChar '''
print 'unittest findChar'
s = '3a4.sf2'
print findChar(s, '.'), ' should be 3'
print findChar(s, '2'), ' should be 6'
s = '23e03'
print findChar(s, 'e'), ' should be 2'
print findChar(s, 'a'), ' should be -1'
print
''' unittest validFloat'''
print 'unittest validFloat'
s = '+12.45'
print validFloat(s), 'should be True'
s = '-.8'
print validFloat(s), 'should be True'
s = '12.'
print validFloat(s), 'should be True'
s = ' 12.45'
print validFloat(s), 'should be False'
s = '12.-45'
print validFloat(s), 'should be False'
print
''' unittest validInt '''
print 'unittest validInt'
s = '3425'
print validInt(s,False), 'should be True'
s = '+3425'
print validInt(s,True), 'should be True'
s = '-34'
print validInt(s,True), 'should be True'
s = '3425.'
print validInt(s,False), 'should be False'
s = '34e5'
print validInt(s,False), 'should be False'
s = '-3425.'
print validInt(s,False), 'should be False'
print
''' unittest validNum '''
n = "1."
print validNum(n), 'should be True'
n = "2e10"
print validNum(n), 'should be True'
n = "1.e2"
print validNum(n), 'should be True'
n = ".3 "
print validNum(n), 'should be True'
n = "+1.e+5"
print validNum(n), 'should be True'
n = ".e1"
print validNum(n), 'should be False'
n = "1e.1"
print validNum(n), 'should be False'
n = "1e1.1"
print validNum(n), 'should be False'
n = "2.3e"
print validNum(n), 'should be False'
|
'''
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Created on Jan 27, 2014
@author: Songfan
'''
''' memoization '''
def minPathSum(Grid):
row = len(Grid)
col = len(Grid[0])
return _minSumDP(Grid, row - 1, col - 1, {})
def _minSumDP(Grid, k, l, h):
tot = 0
if k == 0:
for j in range(l+1):
tot += Grid[0][j]
return tot
if l == 0:
for i in range(k+1):
tot += Grid[i][0]
return tot
if (k,l) in h: return h[k,l]
''' min path from left or from top, add the current value '''
tot = min(_minSumDP(Grid, k - 1, l, h), _minSumDP(Grid, k, l - 1, h)) + Grid[k][l]
h[k,l] = tot
return tot
''' unittest '''
Grid = [[1,1,2,2],[2,1,1,1],[2,2,2,1],[2,2,2,1]]
print minPathSum(Grid) |
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Created on Feb 2, 2014
@author: Songfan
'''
''' DP: O(N^2)
Greedy: O(N)
key idea: all the positions before the maximum reachable distance would be able to be reached in minimum steps
keey three variables
(1) the current maximum reach distance (currMax)
(2) the number of steps to reach this current maximum distances (step)
(3) the next maximum reachable distance (nextMax)
'''
def solution(A):
n = len(A)
if n == 0: return -1
currMax = 0
nextMax = 0
step = 0
for i in range(n):
if i > currMax:
''' we are now beyond the currMax,
need to take one step, update currMax '''
currMax = nextMax
step += 1
nextMax = max(nextMax, A[i] + i)
return step
A = [2,3,1,1,4]
print solution(A), 'should be 2'
|
'''
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
Created on Jan 30, 2014
@author: Songfan
'''
''' two pointer + hashtable
while currChar:
store (nextChar, position) to hashtable until nextChar is duplicated with previous,
store the longest length
update currChar to the next position of duplicates
Summary: for unordered sequence and occurance, think about hashtable
'''
def solution(A):
n = len(A)
if n == 0 or n == 1: return n
curr = 0
longest = 0
tmpLen = 0
h = {}
while curr < n:
if A[curr] not in h:
h[A[curr]] = curr
curr += 1
tmpLen += 1
else:
prevPos = h[A[curr]]
curr = prevPos + 1
longest = max(tmpLen, longest)
# update tmp var
h = {}
tmpLen = 0
return longest
A = 'abcabcbb'
print solution(A), 'should be 3'
A = 'bbbb'
print solution(A), 'should be 1'
|
'''
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Created on Feb 15, 2014
@author: Songfan
'''
''' 1. duplicate each node
2. copy each rand ptr
3. separate the linked list
'''
# Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
def __str__(self):
return str(self.label)
class Solution:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
if head is None: return head
# first pass, copy node
curr = head
while curr:
newNode = RandomListNode(curr.label)
newNode.next = curr.next
curr.next = newNode
curr = newNode.next
# second pass, copy random ptr
curr = head
while curr:
''' curr.random can be None '''
if curr.random:
curr.next.random = curr.random.next
curr = curr.next.next
# seperate list
curr = head
newHead = head.next
while curr:
tmp = curr.next
''' tmp can be None, which means the end of list '''
if tmp:
curr.next = tmp.next
curr = tmp
return newHead
n1 = RandomListNode(1)
n2 = RandomListNode(2)
n3 = RandomListNode(3)
n4 = RandomListNode(4)
n5 = RandomListNode(5)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n1.random = n4
n3.random = n5
n4.random = n2
ss = Solution()
newHead = ss.copyRandomList(n1)
curr = newHead
while curr:
print curr.label
curr = curr.next
|
'''
Created on Nov 7, 2013
@author: Songfan
'''
# use list structure to implement Minimum Binary Heap
class MinBinaryHeap:
def __init__(self):
self.heapList = [0]
self.size = 0
def insert(self, item):
self.heapList.append(item)
self.size += 1
self.siftUp(self.size)
def siftUp(self, size): # used for delete item from heap
while(size//2>0):
if self.heapList[size] < self.heapList[size//2]:
tmp = self.heapList[size]
self.heapList[size] = self.heapList[size//2]
self.heapList[size//2] = tmp
size = size//2
def delMin(self):
if self.size == 0:
return False
minItem = self.heapList[1]
self.heapList[1] = self.heapList[self.size]
self.heapList.pop()
self.size -= 1
self.siftDown(1)
return minItem
def siftDown(self, i): # used for building heap
while(i<=self.size//2):
minChildIdx = self.minChild(i)
if self.heapList[i] > self.heapList[minChildIdx]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[minChildIdx]
self.heapList[minChildIdx] = tmp
i = minChildIdx
def minChild(self, i):
if self.size == i*2:
return i*2
else:
if self.heapList[i*2]>self.heapList[i*2+1]:
return 2*i+1
else:
return 2*i
def buildMinBinaryHeap(self, aList):
self.heapList = aList
self.heapList.insert(0, 0)
self.size = len(self.heapList) - 1
i = self.size //2
while(i>0):
self.siftDown(i)
i -= 1
def printHeap(self):
print [i for i in self.heapList]
aMinBinaryHeap = MinBinaryHeap()
aMinBinaryHeap.insert(33)
aMinBinaryHeap.delMin()
aMinBinaryHeap.printHeap()
aMinBinaryHeap.insert(9)
aMinBinaryHeap.insert(21)
aMinBinaryHeap.insert(14)
aMinBinaryHeap.insert(18)
aMinBinaryHeap.insert(19)
aMinBinaryHeap.insert(11)
aMinBinaryHeap.insert(5)
aMinBinaryHeap.printHeap()
print aMinBinaryHeap.delMin()
aMinBinaryHeap.printHeap()
h = MinBinaryHeap()
h.buildMinBinaryHeap([9,6,5,2,3])
h.printHeap() |
'''
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
Created on Jan 30, 2014
@author: Songfan
'''
class TreeNode:
def __init__(self, val = None, left = None, right = None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.val)
class BinaryTree:
def __init__(self, root = None):
self.root = root
def __str__(self):
return self._display(self.root)
def _display(self, node):
if node is None: return '*'
res = str(node.val) + '(' + self._display(node.left) + ',' + self._display(node.right) + ')'
return res
''' need to store every possible result, has two vars, one store the tmp solution, and one store the entire result '''
def pathSum(root, num):
res = []
currSolu = []
_pathSum(root, num, currSolu, res)
return res
def _pathSum(node, num, currSolu, res):
if node.left is None and node.right is None and node.val == num:
''' stop condition '''
currSolu.append(num)
tmp = currSolu[:]
res.append(tmp)
return
currSolu.append(node.val)
if node.left:
_pathSum(node.left, num - node.val, currSolu, res)
currSolu.pop()
if node.right:
_pathSum(node.right, num - node.val, currSolu, res)
currSolu.pop()
return
n1 = TreeNode(1)
n2 = TreeNode(2)
n7 = TreeNode(7)
n13 = TreeNode(13)
n51 = TreeNode(5)
n4 = TreeNode(4, n51, n1)
n11 = TreeNode(11, n7, n2)
n8 = TreeNode(8, n13, n4)
n4 = TreeNode(4, n11, None)
n5 = TreeNode(5, n4, n8)
print BinaryTree(n5)
res = pathSum(n5, 22)
print res |
# Bradley N. Miller, David L. Ranum
# Introduction to Data Structures and Algorithms in Python
# Copyright 2005
#
#stack.py
class Stack:
def __init__(self):
self.data = []
def isEmpty(self):
return self.data == []
def push(self, item):
self.data.append(item)
def pop(self):
assert (self.size()>0), "Cannot pop from a empty stack!"
return self.data.pop()
def peek(self):
assert (self.size()>0), "Cannot peek from a empty stack!"
return self.data[-1]
def size(self):
return len(self.data)
def __str__(self):
result = []
for i in self.data:
result.append(str(i))
return 'stack from the bottom: '+', '.join(result)
# s = Stack()
# print s
# s.push(2)
# s.push(3)
# print s
# print s.peek() |
'''
print the leaf of a binary tree
Created on Mar 23, 2014
@author: Songfan
'''
class TreeNode:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __str__(self):
return str(self.val)
class BinaryTree:
def __init__(self, root=None):
self.root = root
def __str__(self):
return self._display(self.root)
def _display(self, node):
if node is None: return '*'
return str(node.val) + '(' + self._display(node.left) + ',' + self._display(node.right) + ')'
def printLeaf(node):
if node is None: return []
if node.left is None and node.right is None: return [node.val]
return printLeaf(node.left) + printLeaf(node.right)
''' unittest '''
n2 = TreeNode(2)
n4 = TreeNode(4)
n5 = TreeNode(5)
n3 = TreeNode(3, n4, n5)
n1 = TreeNode(1, n2, n3)
print BinaryTree(n1)
print printLeaf(n1) |
'''
print pascal's triangle, LeetCode, ex: n=3
[
[1]
[1,1]
[1,2,1]
]
Created on Dec 4, 2013
@author: Songfan
'''
def printPascal(result,n):
print'['
for i in range(1,n+1):
spaceNum = n-i+1
startIdx = i*(i-1)/2
endIdx = (i+1)*i/2
data = '['+','.join(result[startIdx:endIdx])+']'
print ' '*spaceNum+data
print ']'
def pascalTriangle(n):
assert(n>=0 and isinstance(n,int)),'input error'
result = []
if n==1: result = ['1']
else:
currList = ['1','1']
cnt = 2
result = ['1','1','1']
while(cnt<n):
nextList = ['1']
for i in range(len(currList)-1):
nextList.append(str(int(currList[i])+int(currList[i+1])))
nextList.append('1')
currList = nextList
result.extend(currList)
cnt+=1
printPascal(result,n)
n = 5
pascalTriangle(n) |
'''
Created on Dec 12, 2013
@author: Songfan
'''
from linkedList import LinkedList
def insertionSort(head):
if not head or not head.next: return head
head2 = head
curr1 = head.next
head2.next = None
while(curr1):
curr2 = head2
while(curr2):
if curr1.value<curr2.value:
head2 = curr1
curr1 = curr1.next
head2.next = curr2
curr2 = None
elif curr2.next and curr1.value<curr2.next.value:
tmp = curr2.next
curr2.next = curr1
curr1 = curr1.next
curr2.next.next = tmp
curr2 = None
elif not curr2.next:
curr2.next = curr1
curr1 = curr1.next
curr2.next.next = None
curr2 = None
else:
curr2 = curr2.next
return head2
aList = LinkedList()
aList.add(9)
print aList.displayLinkedListFromNode(insertionSort(aList.head))
aList.add(4)
print aList.displayLinkedListFromNode(insertionSort(aList.head))
aList.add(8)
aList.add(3)
aList.add(7)
aList.add(6)
print aList
print aList.displayLinkedListFromNode(insertionSort(aList.head))
|
class Person(object):
def __init__(self, name, education, age, uniform):
self.name = name
self.education = education
self.age = age
self.uniform = uniform
def work(self):
print("%s goes to work" % self.name)
class Employee(Person):
def __init__(self, name, education, age, uniform):
super(Employee, self).__init__(name, education, age, uniform)
def start_working(self):
print("%s started working." % self.name)
class Programmer(Employee):
def __init__(self, name, education, age, uniform):
super(Programmer, self).__init__(name, education, age, uniform)
def put_on(self):
print("%s put on the uniform" % self.name)
|
import math
def prime_checker():
num_check = int(input("Enter a number: ")) # Takes the input from the user and sets it to the variable num_check
sqr_test = math.sqrt(num_check) # Tests the number by square rooting it, if it returns an integar value then it cannot be a prime number
sqr_test = int(sqr_test)
# Prime numbers are greater than 1 (excluding 1 itself) so this is to filter out numbers less than 1 that cannot be prime
for n in range(sqr_test): # Checks for factors
if num_check % (n+2) == 0: # Here, if the division of the input (num_check) is equal to 0 then it cannot be a prime number.
print(num_check, "is not a prime number. It is a factor of ", n+2) # If it fails the tests then it cannot be a prime number
break
else:
print(num_check, "is a prime number!")
if __name__=='__main__': # Runs the program
prime_checker()
|
import numpy as np
import math
class LossFunction:
def __init__(self):
self._result = None
def zero_one(self, feature_vector, weight_vector, y):
score = np.dot(feature_vector, weight_vector) # how confident we are in prediction
margin = score * y # how correct weare in prediction
# the classifier makes an error when margin is less than 0 because the score and y are different signs
if(np.sign(margin) == -1): self._result = 1
elif(np.sign(margin) == 1): self._result = 0
return self._result
# def feature_map(data_point):
# # returns a feature vector of R superscript d numbers
# return True
# TODO: synthesise training data
# TODO: write gradient descent algorithm
feature_vector = np.array([1, 2, 3, 4])
weight_vector = np.ones(len(feature_vector))
# The score represents the weighted combination of features and weights
score = np.dot(feature_vector, weight_vector)
def linear_classifier(score): # or the sign(dot(feature_vector, weight_vector))
return np.sign(score)
def linear_regression(feature_vector, weight_vector): # in some senses this is simpler as it is already R
return np.dot(feature_vector, weight_vector)
def least_squares(feature_vector, weight_vector, y):
prediction = linear_regression(feature_vector, weight_vector)
residual = prediction - y # i.e. the amount of overshoot there is
loss = (residual * residual) # squared to allow punishment of over or undershoot
return loss
training_data = [(1, 2), (3, 4)]
def least_squares(w):
return sum((np.dot(x, w) - y) ** 2 for x, y in training_data)
def dleast_squares(w):
return sum(2*(np.dot(x, w) - y) * x for x, y in training_data)
# def data_synthesis(num, dim)
def main():
print("Feature vector: ", feature_vector)
print("Weight vector: ", weight_vector)
print("The score: %d" % score)
print("The classification: %d" % linear_classifier(score))
loss = LossFunction()
result = loss.zero_one(feature_vector, weight_vector, -1)
print("The loss: %d" % result)
# Gradient descent...
dim = 1
w = 0 # weights with 1 dimenson
step_size = 0.01
training_data = [(2, 4), (4, 2)]
for t in range(100):
value = least_squares(w)
gradient = dleast_squares(w)
w = w - step_size * gradient
print('iteration {}: w = {}, loss = {}'.format(t, w, value))
if __name__ == "__main__":
main()
|
# NFL Fourth Down Statistics
#
#In this code, we will examine the play-by-play data from the 2015 NFL season,
#focusing on the fourth down statistics.
import numpy as np # library for handling arrays
import pandas as pd #library for handling dataframes
import matplotlib.pyplot as plt #library for viewing graphs
from matplotlib.widgets import Slider #this method will allow us to add a slider to our graphs
#We first read in the 2015 NFL play-by-play data and grab: all fourth down plays
data = pd.read_csv('/home/matt/Downloads/nfl.csv')
fourth = data[data['down'] == 4]
fourth = fourth[fourth['PlayType'].isin(['Run', 'Pass', 'Punt', 'Field Goal'])]
yds = 1
#Initialize the plot
fig, ax = plt.subplots()
ax.pie(fourth['PlayType'].value_counts())
plt.legend(fourth['PlayType'].value_counts().index, loc = "best")
plt.title("Fourth Downs By Play Type")
#Draw the slider
axYTG = plt.axes([.2,.08, .65, .08], axisbg = 'white')
sYTG = Slider(axYTG, 'Yards To Go', 1, 40, valinit = 0, valfmt = '%0.0f', color = 'brown')
#This is the function that refreshes the plot with the new slider values
def update(val):
yds = int(round(val))
ax.clear()
ax.pie(fourth[fourth['ydstogo'] == yds]['PlayType'].value_counts(dropna = False))
ax.legend(fourth[fourth['ydstogo'] == yds]['PlayType'].value_counts().index)
ax.set_title("Fourth Downs By Play Type")
fig.canvas.draw()
sYTG.on_changed(update)
plt.show()
|
"""...
Global variables:
WIDGETS - a mapping from strings to the wx.Window class objects that
they represent
"""
import wx
WIDGETS = {
"Button": wx.Button,
"Slider": wx.Slider,
"Listbox": wx.ListBox
}
class Widget(object):
"""Represents a wx.Window.
Instance variables:
attrs -
"""
def __init__(self, title):
self.title = title
self.attrs = {}
class Window(object):
"""Represents a wx.Frame.
Instance variables:
title - title of the window
frame - the wx.Frame that this Window represents
widgets - a dict in the format:
key - string representing the type of widget
value - a dict containing widgets of that type, in the format:
key - title of a widget
value - the Widget instance object
"""
def __init__(self, title, parent=None):
self.title = title
self.widgets = {t: {} for t in WIDGETS.keys()}
self.frame = wx.Frame(
parent,
title = title,
style =
wx.SYSTEM_MENU |
# wx.RESIZE_BORDER |
# wx.MINIMIZE_BOX |
# wx.MAXIMIZE_BOX |
wx.CLOSE_BOX |
wx.CAPTION |
wx.CLIP_CHILDREN)
def all_widgets(self, objects=False):
"""..."""
def f(x, y):
z = x.copy()
z.update(y)
return z
if objects:
return reduce(f, self.widgets.itervalues())
else:
return reduce(f, self.widgets.itervalues()).keys()
def render(self):
"""Display the wx.Frame containing widgets configured as in
self.widgets."""
# Render each of the widgets.
# Show Frame.
self.frame.Fit()
self.frame.Show()
def hide(self):
self.frame.Hide()
class FormDialog(wx.Dialog):
"""A wx.Dialog containing a form.
Instance variables:
fields - a dict in the format:
key - name of the form field
value - a dict with the keys "sizer", "label", and "entry"
mapped to their corresponding wx objects.
"""
def __init__(self, title):
super(FormDialog, self).__init__(
None,
title = title,
style =
wx.CAPTION |
wx.SYSTEM_MENU |
wx.THICK_FRAME)
self.fields = {}
self.sizer = wx.BoxSizer(wx.VERTICAL)
def init(self):
"""..."""
self.ok = wx.Button(self, wx.ID_OK, "OK")
self.sizer.Add(self.ok, flag = wx.ALIGN_RIGHT)
self.SetSizer(self.sizer)
self.Fit()
def add_field(self, name, entry):
"""Initialize a new field."""
sizer = wx.BoxSizer(wx.HORIZONTAL)
label = wx.StaticText(self, label = name)
sizer.AddSpacer((5, 0))
sizer.Add(label, flag = wx.ALIGN_CENTER)
sizer.AddSpacer((5, 0))
sizer.Add(entry)
self.fields[name] = {
"sizer": sizer,
"label": label,
"entry": entry}
self.sizer.Add(sizer)
def add_text_field(self, name):
"""Initialize a new text entry."""
entry = wx.TextCtrl(self)
self.add_field(name, entry)
def add_menu_field(self, name, options):
"""..."""
entry = wx.ComboBox(self)
entry.SetItems(options)
self.add_field(name, entry)
class NewWindowDialog(FormDialog):
"""..."""
def __init__(self):
super(NewWindowDialog, self).__init__("New Window")
self.add_text_field("Title")
self.init()
def prompt(self):
self.ShowModal()
class NewWidgetDialog(FormDialog):
"""...
Instance variables:
window
"""
def __init__(self):
super(NewWidgetDialog, self).__init__("New Widget")
self.add_text_field("Title")
self.add_menu_field("Type", sorted(WIDGETS.keys()))
self.init()
def prompt(self, window):
self.window = window
self.ShowModal()
class MainFrame(wx.Frame):
"""...
Instance variables:
windows - a dict in the format:
key - string; Window identifier
value - Window instance
app - wx.App
sizer - wx.BoxSizer
nwind - FormDialog
nwidd - FormDialog
windows_lb - wx.ListBox
widgets_lb - wx.ListBox
windows_display - wx.Button
windows_edit - wx.Button
windows_del - wx.Button
widgets_new - wx.Button
widgets_edit - wx.Button
widgets_del - wx.Button
"""
def __init__(self):
"""Initialize non-wx data structures."""
self.windows = {}
def run(self):
"""Run wxPython's event loop."""
self.wx_init()
self.app.MainLoop()
def new_window(self, title):
"""Instantiate and install references to a new Window."""
assert title not in self.windows
window = Window(title = title)
self.windows[title] = window
self.windows_lb.Insert(window.title, 0)
def get_selected_window(self):
"""Returns the Window object represented by the selected item
in self.windows_lb."""
i = self.windows_lb.GetSelection()
if i is not wx.NOT_FOUND:
title = self.windows_lb.GetString(i)
return self.windows[title]
def wx_init(self):
"""Initialize wx component."""
self.app = wx.App()
super(MainFrame, self).__init__(
None,
title = "wxEditor",
# size = (400, 400),
style =
wx.SYSTEM_MENU |
# wx.RESIZE_BORDER |
# wx.MINIMIZE_BOX |
# wx.MAXIMIZE_BOX |
wx.CLOSE_BOX |
wx.CAPTION |
wx.CLIP_CHILDREN)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.SetSizer(self.sizer)
self.SetBackgroundColour(wx.Colour(255, 255, 255))
# init rest of GUI
self.init_menus()
self.init_gui_main()
self.nwind = NewWindowDialog()
self.nwidd = NewWidgetDialog()
self.nwind.Bind(
wx.EVT_BUTTON, self.OnNewWindowOk, self.nwind.ok)
self.nwidd.Bind(
wx.EVT_BUTTON, self.OnNewWidgetOk, self.nwidd.ok)
self.windows_display.Disable()
self.windows_edit.Disable()
self.windows_del.Disable()
self.widgets_new.Disable()
self.widgets_edit.Disable()
self.widgets_del.Disable()
# show GUI
self.Fit()
self.Show()
def init_menus(self):
"""Set up the editor's menu bar."""
# File menu
file_menu = wx.Menu()
load_item = file_menu.Append(
wx.ID_ANY,
"&Load",
"Open work previously saved using this program.")
save_item = file_menu.Append(
wx.ID_ANY,
"&Save",
"Store your progress on your computer.")
file_menu.AppendSeparator()
exit_item = file_menu.Append(
wx.ID_EXIT,
"E&xit",
"Terminate the program.")
# init MenuBar instance
menu_bar = wx.MenuBar()
menu_bar.Append(file_menu, "&File")
# init wx.Frame instance
self.SetMenuBar(menu_bar)
self.CreateStatusBar()
# bind events
self.Bind(wx.EVT_MENU, self.OnExit, exit_item)
def init_gui_main(self):
"""Set up the editor's main interface."""
# ListBox of windows
left_half = wx.BoxSizer(wx.VERTICAL)
l0 = wx.BoxSizer(wx.HORIZONTAL)
l1 = wx.BoxSizer(wx.VERTICAL)
self.windows_lb = wx.ListBox(self)
l1.Add(self.windows_lb)
l2 = wx.BoxSizer(wx.VERTICAL)
windows_new = wx.Button(self, wx.ID_ANY, "New")
self.windows_display = wx.Button(self, wx.ID_ANY, "Display")
self.windows_edit = wx.Button(self, wx.ID_ANY, "Edit")
self.windows_del = wx.Button(self, wx.ID_ANY, "Delete")
l2.Add(windows_new)
l2.Add(self.windows_display)
l2.Add(self.windows_edit)
l2.Add(self.windows_del)
l0.Add(l1)
l0.Add(l2)
windows_label = wx.StaticText(self, label = "Windows")
left_half.Add(windows_label)
left_half.Add(l0)
# new (Widget) button > dialog with ListBox of widget types
right_half = wx.BoxSizer(wx.VERTICAL)
r0 = wx.BoxSizer(wx.HORIZONTAL)
r1 = wx.BoxSizer(wx.VERTICAL)
self.widgets_lb = wx.ListBox(self)
r1.Add(self.widgets_lb)
r2 = wx.BoxSizer(wx.VERTICAL)
self.widgets_new = wx.Button(self, wx.ID_ANY, "New")
self.widgets_edit = wx.Button(self, wx.ID_ANY, "Edit")
self.widgets_del = wx.Button(self, wx.ID_ANY, "Delete")
r2.Add(self.widgets_new)
r2.Add(self.widgets_edit)
r2.Add(self.widgets_del)
r0.Add(r1)
r0.Add(r2)
widgets_label = wx.StaticText(self, label = "Widgets")
right_half.Add(widgets_label)
right_half.Add(r0)
# arrange sizers on frame
self.sizer.Add(left_half)
self.sizer.AddSpacer((10, 0))
self.sizer.Add(right_half)
# bind events
self.Bind(wx.EVT_LISTBOX, self.OnSelectWindow, self.windows_lb)
self.Bind(wx.EVT_BUTTON, self.OnNewWindow, windows_new)
self.Bind(wx.EVT_BUTTON, self.OnDelWindow, self.windows_del)
self.Bind(wx.EVT_LISTBOX, self.OnSelectWidget, self.widgets_lb)
self.Bind(wx.EVT_BUTTON, self.OnNewWidget, self.widgets_new)
self.Bind(wx.EVT_BUTTON, self.OnDelWidget, self.widgets_del)
def OnExit(self, e):
"""Exit the editor."""
self.Close(True)
exit()
def OnNewWindow(self, e):
"""Create a dialog prompting the user to initialize a new window."""
self.nwind.prompt()
def OnDelWindow(self, e):
"""Remove references to the Window object represented by the
selected item in self.windows_lb."""
i = self.windows_lb.GetSelection()
if i is not wx.NOT_FOUND:
title = self.windows_lb.GetString(i)
del self.windows[title]
self.windows_lb.Delete(i)
def OnNewWidget(self, e):
"""Create a dialog prompting the user to create a new widget
on the selected window."""
window = self.get_selected_window()
if window:
self.nwidd.prompt(window)
def OnDelWidget(self, e):
"""Remove references to the Widget object represented by the
selected item in self.windows_lb."""
window = self.get_selected_window()
widget_i = self.widgets_lb.GetSelection()
widget = self.widgets_lb.GetString(widget_i)
if widget is not wx.NOT_FOUND:
for wtype, widgets in window.widgets.iteritems():
for wtitle in widgets:
if wtitle == widget:
del window.widgets[wtype][wtitle]
self.widgets_lb.Delete(widget_i)
break
def OnSelectWindow(self, e):
"""Update the widgets listbox for the selected window."""
self.windows_display.Enable()
self.windows_edit.Enable()
self.windows_del.Enable()
self.widgets_new.Enable()
# Disable certain buttons when a Widget is not selected in the listbox.
self.widgets_edit.Disable()
self.widgets_del.Disable()
window = self.get_selected_window()
widgets = window.all_widgets()
if widgets:
self.widgets_lb.SetItems(window.all_widgets())
else:
self.widgets_lb.Clear()
def OnDeselectWindow(self, e):
"""Disable certain buttons when a Window is not selected
in the listbox."""
# Can this event even happen?
self.windows_display.Disable()
self.windows_edit.Disable()
self.windows_del.Disable()
def OnSelectWidget(self, e):
"""..."""
self.widgets_edit.Enable()
self.widgets_del.Enable()
def OnNewWindowOk(self, e):
title = self.nwind.fields["Title"]["entry"].GetValue()
if title not in self.windows:
self.nwind.EndModal(self.nwind.GetReturnCode())
self.new_window(title)
else:
pass
# display error message
def OnNewWidgetOk(self, e):
title = self.nwidd.fields["Title"]["entry"].GetValue()
wtype = self.nwidd.fields["Type"]["entry"].GetValue()
all_widgets = self.nwidd.window.all_widgets()
if (all_widgets is None) or (title not in all_widgets):
self.nwidd.EndModal(self.nwidd.GetReturnCode())
# Instantiate and install references to a new Widget.
self.nwidd.window.widgets[wtype][title] = Widget(title)
self.widgets_lb.Insert(title, 0)
else:
pass
# display error message |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 17 14:44:07 2021
@author: manis
"""
#sum of cubes
sum_of_cubes = []
sum_of_cubes= ["i=" + str(i) + " j=" + str(j) + " " + \
str(i**3 + j**3) for i in range(1 , 20) \
for j in range(1 , 20 ) if i <= j and (i**3 + j**3) == 1729 ]
#sum_of_cubes= [ i**3 + j**3 for i in range(1 , 20) \
# for j in range(1 , 20 ) if i <= j ]
sum_of_cubes.sort()
print(sum_of_cubes)
|
"""
The Parse class takes in a function and
returns the breakdown of the function needed to write a C function.
The bodyList is given to the Formatter class to generate a C-style code.
"""
#Libraries needed
import ast
import inspect
import symtable
#Parser class
class Parser:
#====================================================================
#initializing class and getting an ast dump by inspecting it
#and checking it for correct function types
#====================================================================
#Parser initilizer
def __init__(self, args):
function = args[0]
#length of all lists
self.length = args[1]
#Gives the function name
self.functionName = function.__name__
#gives the source code as a string
self.originalSourceCode = inspect.getsource(function)
#gives the source as a list, every line is an element
self.listSourceCode = inspect.getsourcelines(function)[0]
#gives the starting line number of function in file
self.startingLineNumber = inspect.getsourcelines(function)[1]
#gives the description of function which is written as comments on top
self.description = inspect.getcomments(function)
#gives Python source file location of the function
self.locationOfFolder = inspect.getsourcefile(function)
self.fileName = self.locationOfFolder.split("/")[-1]
#turn the code into an AST
self.astTree = ast.parse(self.originalSourceCode)
#input arguments list
self.argList = []
self.argValueList = args[2:]
#list of the complete body
self.bodyList = []
#local variables list
self.localVariablesList = []
#for the first line
self.firstLineOfFunction = "void " + self.functionName + "("
#already type casted variables
self.typeCastedList = []
self.returnType = ""
#CALLING all functions needed
self.checkTree()
self.parseArguments()
self.typeCastedList = self.argList
self.parseLocalVariables()
self.parseBody()
self.parseFirstLine()
self.wrapper()
#PRINTABLE function call
#self.printArgs()
#self.printTree()
#Prints all arguments of the kernel
def printArgs(self):
print "Verbose output of Parser class arguments: "
print "\nLocation: ", self.locationOfFolder
print "\nFunction name: ", self.functionName, ", Starting at line: ", self.startingLineNumber
print "\nFunction description: \n", self.description.rstrip('\n')
print "\nOriginal Source Code: \n", self.originalSourceCode.rstrip('\n')
print "\nSource Code in list form: \n", self.listSourceCode
#Print the complete ast tree
def printTree(self):
print ast.dump(self.astTree,annotate_fields=True, include_attributes=False)
#Check if the tree is valid
# - no function calling function
# - it is a function
# - it is a valid module
# - its name should match in the parsing
def checkTree(self):
#check if it is a valid module at root
if not isinstance(self.astTree, ast.Module):
raise Exception("Not a valid module, it is a %s"%(root.__class__))
#iterate through the tree to check
for node in ast.iter_child_nodes(self.astTree):
#check if all nodes of tree are FunctionDef
if not isinstance(node, ast.FunctionDef):
raise Exception("Not a Function Definition")
#check if all nodes have no decorators(function calling other functions)
if len(node.decorator_list) > 0:
raise Exception("Not a pure function")
#check if name is right
if node.name != self.functionName:
raise Exception("Function Name does not match %s != %s"%(node.name,self.functionName))
#====================================================================
#Parsing the input arguments / local variables
#====================================================================
#parses input arguments to function,
#as well as the default values
def parseArguments(self):
for node in ast.iter_child_nodes(self.astTree):
#getting names of all arguments as strings
for arg in node.args.args:
self.argList.append(arg.id)
#getting default values of arguments if any
for values in node.args.defaults:
self.argValueList.append(values.n)
#call only after parsing arguments
#not exhaustive
def parseLocalVariables(self):
table = symtable.symtable(self.originalSourceCode, "string", "exec")
tupleOfArgs = table.get_children()[0].get_locals()
for arg in tupleOfArgs:
if arg not in self.argList:
self.localVariablesList.append(arg)
#====================================================================
#Operations parser(x2) / BinOps parser / UnaryOp parser
#====================================================================
def opsParser(self, body):
if isinstance(body, ast.Eq):
return "=="
elif isinstance(body, ast.NotEq):
return "!="
elif isinstance(body, ast.Lt):
return "<"
elif isinstance(body, ast.LtE):
return "<="
elif isinstance(body, ast.Gt):
return ">"
elif isinstance(body, ast.GtE):
return ">="
else:
raise Exception("Operation(ops) not supported: %s"%(body))
def opParser(self, body):
if isinstance(body, ast.Add):
return "+"
elif isinstance(body, ast.Sub):
return "-"
elif isinstance(body, ast.Mult):
return "*"
elif isinstance(body, ast.Div):
return "/"
elif isinstance(body, ast.Mod):
return "%"
elif isinstance(body, ast.Pow):
return "**"
elif isinstance(body, ast.LShift):
return "<<"
elif isinstance(body, ast.RShift):
return ">>"
elif isinstance(body, ast.BitOr):
return "|"
elif isinstance(body, ast.BitXor):
return "^"
elif isinstance(body, ast.BitAnd):
return "&"
else:
raise Exception("Operation(op) not supported: %s"%(body))
def binOpsParser(self, body):
returnString = ""
#left
returnString += self.bodyHandlerLiterals(body.left)[0]
#op
returnString += self.opParser(body.op)
#right
returnString += self.bodyHandlerLiterals(body.right)[0]
return returnString
def unaryOpParser(self, body):
returnString = ""
#op
if isinstance(body.op, ast.UAdd):
returnString += "+"
elif isinstance(body.op, ast.USub):
returnString += "-"
elif isinstance(body.op, ast.Invert):
returnString += "~"
else:
raise Exception("Unary Operation not supported: %s"%(body.op))
#operand
returnString += self.bodyHandlerLiterals(body.operand)[0]
return returnString
#====================================================================
#Helper functions for parsing the body
#each helper should return a string
#which goes into a list
#====================================================================
#Handles literals including Num, Str, List, Name
#returns tuple of string of Literal and possible ctx(Name)
def bodyHandlerLiterals(self, body):
returnString = ""
#Name
if isinstance(body, ast.Name):
returnString += body.id
if isinstance(body.ctx, ast.Load):
return (returnString, "Load")
elif isinstance(body.ctx, ast.Store):
return (returnString, "Store")
else:
raise Exception("Literal Name's ctx not supported: %s"%(body.ctx))
#Num
elif isinstance(body, ast.Num):
returnString += str(body.n)
return (returnString, None)
#Str
elif isinstance(body, ast.Str):
returnString += body.s
return (returnString, None)
#List
elif isinstance(body, ast.List):
returnString += '['
count = 0
if len(body.elts) > 0:
for value in body.elts:
if count != 0:
returnString += ','
returnString += str(self.bodyHandlerLiterals(value)[0])
count += 1
returnString += ']'
if isinstance(body.ctx, ast.Load):
return (returnString, "Load")
elif isinstance(body.ctx, ast.Store):
return (returnString, "Store")
else:
raise Exception("Literal List's ctx not supported: %s"%(body.ctx))
elif isinstance(body, ast.Subscript):
returnString += self.bodyHandlerSubscript(body)
return (returnString, None)
elif isinstance(body, ast.BinOp):
returnString += self.binOpsParser(body)
return (returnString, None)
elif isinstance(body, ast.Call):
returnString += self.bodyHandlerCall(body)
return (returnString, None)
elif isinstance(body, ast.Attribute):
returnString += self.bodyHandlerAttribute(body)
return (returnString, None)
elif isinstance(body, ast.None):
return (returnString, None)
#Unknown Literal
else:
raise Exception("Literal not supported: %s"%(body))
#not handling more than 1 comparison
def bodyHandlerCompare(self,body):
returnString = ""
#left (Name, Num, Str, List)
returnString += ((self.bodyHandlerLiterals(body.left)[0]))
#ops
returnString += self.opsParser(body.ops[0])
#comparators
returnString += (self.bodyHandlerLiterals(body.comparators[0])[0])
return returnString
#only 1 argument allowed for now
def bodyHandlerCall(self, body):
returnString = ""
returnString += self.bodyHandlerLiterals(body.func)[0]
returnString += "("
for count in xrange(len(body.args)):
if count != 0:
returnString += ","
returnString += self.bodyHandlerLiterals(body.args[count])[0]
# returnString += self.bodyHandlerLiterals(body.args[0])[0]
returnString += ")"
return returnString
def bodyHandlerSubscript(self, body):
returnString = ""
#value (usually a name)
if isinstance(body.value, ast.Name):
returnString += self.bodyHandlerLiterals(body.value)[0]
else:
raise Exception("Subscript value not supported: %s"%(body.value))
#slice ( Index, Slice, ExtSlice(not supported) )
returnString += "["
if isinstance(body.slice, ast.Index):
returnString += self.bodyHandlerLiterals(body.slice.value)[0]
elif isinstance(body.slice, ast.Slice):
returnString += self.bodyHandlerLiterals(body.slice.lower)[0]
returnString += ":"
returnString += self.bodyHandlerLiterals(body.slice.upper)[0]
if body.slice.step != None:
returnString += ":" + self.bodyHandlerLiterals(body.slice.step)[0]
else:
raise Exception("Subscript.slice not supported: %s"%(body.slice))
returnString += "]"
#ctx (not needed for noe)
return returnString
def bodyHandlerAttribute(self,body):
if body.value.id != 'math':
raise Exception("Only math library allowed currently, not %s"%(body.value.id))
else:
return body.attr
#====================================================================
#Handlers for Parsing the body
#each handler should return a list of strings
#which can be appended to the full string
#====================================================================
def bodyHandlerIf(self, body, num):
returnList = []
returnList.append("")
if num==0:
returnList[0] += "if ("
else:
returnList[0] += "else if ("
#test
if isinstance(body.test, ast.Compare):
returnList[0] += (self.bodyHandlerCompare(body.test))
elif isinstance(body.test, ast.Num):
returnList[0] += ((self.bodyHandlerLiterals(body.test)[0]))
elif isinstance(body.test, ast.Name):
returnList[0] += ((self.bodyHandlerLiterals(body.test)[0]))
else:
raise Exception("If test type Unknown: %s"%(body.test))
returnList[0] += ") {"
#body*
for bodies in body.body:
if isinstance(bodies, ast.If):
returnList.append(self.bodyHandler(bodies))
else:
tempList = []
tempList.append(self.bodyHandler(bodies))
returnList.append(tempList)
returnList.append("}")
#orelse*
if len(body.orelse) > 0:
#else if case
if isinstance(body.orelse[0], ast.If):
tempList = self.bodyHandlerIf(body.orelse[0],1)
#last case
else:
tempList = ["else {"]
tempList2 = []
tempList2.append(self.bodyHandler(body.orelse[0]))
tempList.append(tempList2)
tempList.append("}")
returnList = returnList + tempList
return returnList
def bodyHandlerReturn(self, body):
returnList = []
returnList.append("")
returnList[0] += "return "
if isinstance(body.value, ast.BinOp):
returnList[0] += self.binOpsParser(body.value)
else:
returnList[0] += self.bodyHandlerLiterals(body.value)[0]
if self.bodyHandlerLiterals(body.value)[0] == 'None':
returnList[0] = 'return '
returnList[0] += ";"
#for the firstLine
if self.returnType == "":
if (isinstance(body.value, ast.Name) and body.value.id != 'None') or isinstance(body.value, ast.Num):
self.returnType += "float "
elif isinstance(body.value, ast.List):
self.returnType += "float* "
elif isinstance(body.value, ast.Str):
self.returnType += "char"
else:
self.returnType += "void "
#raise Exception("Return type not supported %s"%(body.value))
return returnList[0]
def bodyHandlerAssign(self, body):
returnList = []
#targets (list of target)
for target in body.targets:
if isinstance(target, ast.BinOp):
if isinstance(body.value, ast.Name) or isinstance(body.value, ast.Num):
if self.binOpsParser(target) not in self.typeCastedList:
returnList.append("float ")
returnList[0] += (self.binOpsParser(target))
self.typeCastedList.append(self.binOpsParser(target))
else:
returnList.append(self.binOpsParser(target))
else:
returnList.append(self.binOpsParser(target))
elif isinstance(target, ast.Name):
if isinstance(body.value, ast.Name) or isinstance(body.value, ast.Num) or isinstance(body.value, ast.BinOp) or isinstance(body.value, ast.Subscript):
if self.bodyHandlerLiterals(target)[0] not in self.typeCastedList:
returnList.append("float ")
returnList[0] += (self.bodyHandlerLiterals(target)[0])
self.typeCastedList.append(self.bodyHandlerLiterals(target)[0])
else:
returnList.append(self.bodyHandlerLiterals(target)[0])
else:
returnList.append(self.bodyHandlerLiterals(target)[0])
elif isinstance(target, ast.Str):
returnList.append(self.bodyHandlerLiterals(target)[0])
elif isinstance(target, ast.Subscript):
returnList.append(self.bodyHandlerSubscript(target))
else:
raise Exception("Assignment not supported for target: %s"%(target))
#equal sign
returnList[0] += "="
#value (single node, can be Name, Num, BinOp)
if isinstance(body.value, ast.BinOp):
returnList[0] += self.binOpsParser(body.value)
elif isinstance(body.value, ast.Name) or isinstance(body.value, ast.Num) or isinstance(body.value, ast.List):
returnList[0] += self.bodyHandlerLiterals(body.value)[0]
elif isinstance(body.value, ast.Subscript):
returnList[0] += self.bodyHandlerSubscript(body.value)
elif isinstance(body.value, ast.Call):
returnList[0] += self.bodyHandlerCall(body.value)
else:
raise Exception("Assign.value not supported %s"%(body.value))
returnList[0] += ";"
return returnList[0]
def bodyHandlerAugAssign(self, body):
returnList = []
#target
if isinstance(body.target, ast.Subscript):
returnList.append(self.bodyHandlerSubscript(body.target))
else:
returnList.append(self.bodyHandlerLiterals(body.target)[0])
#op + equals sign
returnList[0] += self.opParser(body.op)+"="
#value
returnList[0] += (self.bodyHandlerLiterals(body.value)[0])
returnList[0] += ";"
return returnList[0]
def bodyHandlerWhile(self, body):
returnList = []
returnList.append("")
returnList[0] += "while ("
#test
if isinstance(body.test, ast.Compare):
returnList[0] += (self.bodyHandlerCompare(body.test))
elif isinstance(body.test, ast.Num):
returnList[0] += ((self.bodyHandlerLiterals(body.test)[0]))
elif isinstance(body.test, ast.Name):
returnList[0] += ((self.bodyHandlerLiterals(body.test)[0]))
else:
raise Exception("While test type Unknown: %s"%(body.test))
returnList[0] += ") {"
#body*
for bodies in body.body:
if isinstance(bodies, ast.If):
returnList.append(self.bodyHandler(bodies))
else:
tempList = []
tempList.append(self.bodyHandler(bodies))
returnList.append(tempList)
returnList.append("}")
#orelse* (ignore)
return returnList
#only float interator allowed
#assuming always xrange(actually range doesnt make a difference)
def bodyHandlerFor(self,body):
returnList = [""]
returnList[0] += "for (int "
#target (only name)
returnList[0] += (self.bodyHandlerLiterals(body.target)[0])
returnList[0] += "="
#iter (1/2/3 arguments)
argumentList = []
for arg in body.iter.args:
if isinstance(arg, ast.Num):
argumentList.append(self.bodyHandlerLiterals(arg)[0])
elif isinstance(arg, ast.Name):
argumentList.append("("+self.bodyHandlerLiterals(arg)[0]+")")
elif isinstance(arg, ast.Call):
argumentList.append(self.bodyHandlerCall(arg))
else:
raise Exception("For loop iter not supported: %s"%(arg))
if len(argumentList) == 2:
argumentList.append('1')
elif len(argumentList) == 1:
argumentList.append('1')
argumentList = ["0"] + argumentList
elif len(argumentList) == 3:
pass
else:
raise Exception("For loop without correct number arguments: Length=%s"%(len(argumentList)))
returnList[0] += argumentList[0]
returnList[0] += "; "
returnList[0] += (self.bodyHandlerLiterals(body.target)[0])
returnList[0] += "<" + argumentList[1] + "; "
returnList[0] += (self.bodyHandlerLiterals(body.target)[0])
returnList[0] += "+= " + argumentList[2]
returnList[0] += ") {"
#body*
for bodies in body.body:
if isinstance(bodies, ast.If):
returnList.append(self.bodyHandler(bodies))
else:
tempList = []
tempList.append(self.bodyHandler(bodies))
returnList.append(tempList)
#orelse* (ignore)
returnList.append("}")
return returnList
def bodyHandlerBreak(self, body):
return "break;"
def bodyHandlerContinue(self, body):
return "continue;"
def bodyHandlerPrint(self, body):
returnString = "std::cout"
for value in body.values:
returnString += " << "
if isinstance(value, ast.Num):
returnString += str(value.n) + ' << " " '
elif isinstance(value, ast.Str):
returnString += '"' + value.s + ' "'
elif isinstance(value, ast.Name):
returnString += str(value.id) + ' << " " '
elif isinstance(value, ast.Subscript):
returnString += self.bodyHandlerSubscript(value) + ' << " " '
else:
raise Exception("Print type unsupported (%s)"%value)
returnString += " << std::endl;"
return returnString
#====================================================================
#Main Handler for Parsing the body
#should be a concatnation of lists
#====================================================================
#Handle the different cases in the body
def bodyHandler(self,body):
#different loop types
if isinstance(body, ast.If):
return self.bodyHandlerIf(body,0)
elif isinstance(body, ast.While):
return self.bodyHandlerWhile(body)
elif isinstance(body, ast.For):
return self.bodyHandlerFor(body)
#different assign types
elif isinstance(body, ast.Assign):
return self.bodyHandlerAssign(body)
elif isinstance(body, ast.AugAssign):
return self.bodyHandlerAugAssign(body)
#return body
elif isinstance(body, ast.Return):
return self.bodyHandlerReturn(body)
#print (hard to support, need typechecker somehow)
elif isinstance(body, ast.Print):
return self.bodyHandlerPrint(body)
# #loop modifiers
elif isinstance(body, ast.Break):
return self.bodyHandlerBreak(body)
elif isinstance(body, ast.Continue):
return self.bodyHandlerContinue(body)
#not parsable
else:
raise Exception("Body type not parsable: %s"%(body))
#parse the body of the function
def parseBody(self):
#go through the main body node
for node in ast.iter_child_nodes(self.astTree):
#pass it the handler
for body in node.body:
#unpack if If_
if isinstance(body, ast.If) or isinstance(body, ast.For) or isinstance(body, ast.While):
for l in self.bodyHandler(body):
self.bodyList.append(l)
else:
self.bodyList.append(self.bodyHandler(body))
#====================================================================
#Handler for first+last line of function
#====================================================================
def parseFirstLine(self):
for x in xrange(len(self.argValueList)):
if x != 0:
self.firstLineOfFunction += ","
if type(self.argValueList[x]).__name__ == "list":
self.firstLineOfFunction += "float*" + " " + self.argList[x]
else:
self.firstLineOfFunction += type(self.argValueList[x]).__name__ + " " + self.argList[x] #type(self.argValueList[x]).__name__
self.firstLineOfFunction += ") {"
#====================================================================
#Wrapper
#====================================================================
def wrapper(self):
#changing return type
if self.returnType != "":
self.firstLineOfFunction = self.returnType + self.firstLineOfFunction[5:]
#adding new and last line
newList = [self.firstLineOfFunction]
newList.append(self.bodyList)
newList.append("}")
self.bodyList = newList
|
#1q
def listoftuples(11,12):
return list(map(lambda x,y:(x,y),11,12))
list1 = [1,2,3]
list2 = ['a','b','c']
print(list of tuples(list1,list2))
def merge(list1,list2):
merged_list = list(zip(list1,list2))
return merged_list
list1 = [1,2,3]
list2 = ['a','b','c']
print(merge(list1,list2))
#2q
list1 = [1,2,3,4,5,6,7,8]
list2 = ['a','b','c','d','e','f','g','h',]
result = tuple(zip(list1,list2))
#3q
list1 = [1,2,3,4,5,6,7,8]
list2 = sorted(list1)
print(list2)
#4q
def filtereven(nums):
if nums%2 !=0:
return True
else:
return False
numbers = [55,36,74,25,32,3,65,22,3]
result = filter(filtereven,numbers)
for i in result:
print(i)
|
#Comparing Numbers
def max_num(x,y,z):
#Use a comparison operator to print the largest number.
if x >= y and x >= z:
return x
elif y >= x and y >= z:
return y
else:
return z
print(max_num(5,4,3)) |
# functions with/without parameters
# functions that return.
def addition(): # without params
x = 7
y = 8
answer = x + y
print('You total is ', answer)
addition()
addition()
#===================================
# with params
def addition2(x, y):
answer = x + y
print('Your 2nd total is ', answer)
addition2(x = 7, y = 8)
addition2(x = 9, y = 4)
# Return
|
# Control statements, loops for/while loop
county = str(input('Which are you from?:'))
if county == 'Meru':
print('Bring some bananas')
elif county == 'Mombasa':
print('Bring some coconut')
else:
print('Invalid County') |
# for loop - used to repeat a task n -times
for x in range(1,11, 1): # 2 is the step
print('Its looping ', x)
# lists/tuples
fruits = ('Apple', 'Orange', 'Mango', 'Passion') # tuple
# use a for loop to loop through the fruits
for fruit in fruits:
print(fruit) # prints each fruit
|
"""
This module contains functions designed to split a time series into linear segments by approximating them as straight lines.
This is a common form of time series data compression.
"""
# NOTE: e norm here is NOT standard error: it is length-averaged error
from itertools import chain
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def func_linear(x, m, b):
"""
Linear function
"""
return m*x+b
def get_r2(predicted, actual):
"""
Gives the r^2 value for a set of predicted data against actual data.
"""
predicted = np.array(predicted)
actual = np.array(actual)
mean_val = np.mean(actual)
sse = sum((actual - predicted) ** 2)
sst = sum((actual - mean_val) ** 2)
return 1 - (sse / sst)
def sum_of_error(predicted, actual):
predicted = np.array(predicted)
actual = np.array(actual)
error = predicted-actual
abs_error = [abs(i) for i in error]
return sum(abs_error)
def sum_of_square_error(predicted, actual):
predicted = np.array(predicted)
actual = np.array(actual)
error = predicted-actual
sq_error = [i**2 for i in error]
return sum(sq_error)
def get_lin_values(exes, m, b):
return [func_linear(x, m, b) for x in exes]
def get_line(exes, whys, start_end, return_e=False):
"""
Returns m, b and r2 value for the line that best fits a subset of points.
Args:
exes: the x values in the series
whys: the y values in the series
start_end: a list of len 2 indicating the start (inclusive) and end (exclusive) of the subset.
Does not need to be ordered
Returns: A tuple (m, b, e_norm)
"""
slicer = start_end[:]
slicer.sort()
start, end = slicer[0], slicer[1]
x = exes[start:end]
y = whys[start:end]
m, b = np.polyfit(x, y, 1)
predictions = get_lin_values(x, m, b)
e = sum_of_square_error(predictions, y)
e_norm = e / (start_end[1] - start_end[0])
if return_e:
return m, b, e_norm, e
else:
return m, b, e_norm
'''
def trawl(exes, whys, start, threshold=0.8, step=-1):
"""
For a data series, starts at a point and begins fitting lines to an increasing number of points,
terminating when the r2 value drops below a threshhold.
Args:
exes: the x values in the series
whys: the y values in the series
start: the start index
threshold: the r2 threshold
step: The increment value for traversing the data
Returns: The index of the last point that meets the threshhold criteria
"""
r2 = 1
if step < 0:
anchor = start + 1
ind = start
else:
anchor = start
ind = start + step
i = 0
while r2 > threshold:
ind += step
if ind < 0 or ind > len(exes)-1:
break
m, b, r2 = get_line(exes, whys, [anchor, ind])
i += 1
print(ind, r2)
if i == 1:
res = [ind, start]
else:
res = [ind-step, start]
res.sort()
return res
'''
def split_segment(exes, whys, segment):
"""
Takes a segment of a data series and splits it into two segments, where the new segments have optimal
linear fits based on minimizing the sum of the squared errors
Args:
exes: the x values in the series
whys: the y values in the series
segment: a list of len 2 indicating the start (inclusive) and end (exclusive) of the subset
Returns: a tuple with two sublists containing the start and end of each new segment and r2
"""
if segment[1] - segment[0] == 3:
seg1 = [segment[0], segment[0]+2]
seg2 = [segment[1]-2, segment[1]]
m1, b1, e_norm1, e1 = get_line(exes, whys, seg1, return_e=True)
m2, b2, e_norm2, e2 = get_line(exes, whys, seg2, return_e=True)
win_e1, win_e2 = e_norm1, e_norm2
win_segs = [[seg1[0], seg1[1], win_e1], [seg2[0], seg2[1], win_e2]]
#print(f'Split result: {win_segs}. Obligate result.')
return win_segs
win_e1, win_e2 = -1, -1
win_e_norm1, win_e_norm2 = 0, 0
win_segs = []
for i in range(segment[0]+2, segment[1]-1):
seg1 = [segment[0], i]
seg2 = [i-1, segment[1]]
m1, b1, e_norm1, e1 = get_line(exes, whys, seg1, return_e=True)
m2, b2, e_norm2, e2 = get_line(exes, whys, seg2, return_e=True)
#print(f'errors: {e1, e2}')
if 1/sum([e1, e2]) > 1/sum([win_e1, win_e2]):
#print(f'Winner')
win_e_norm1, win_e_norm2 = e_norm1, e_norm2
win_e1, win_e2 = e1, e2
win_segs = [[seg1[0], seg1[1], win_e_norm1], [seg2[0], seg2[1], win_e_norm2]]
#print(f'Split result: {win_segs}. Errors: {win_e1, win_e2}')
return win_segs
def flatten(x):
"""
Creates a generator object that loops through a nested list
"""
# First see if the list is iterable
try:
it_is = iter(x)
# If it's not iterable return the list as is
except TypeError:
yield x
# If it is iterable, loop through the list recursively
else:
for i in it_is:
for j in flatten(i):
yield j
def regroup(x, n):
"""
Turns a flat list into a list of lists with sublength n
Args:
x: flat list
i: sublist len
Returns: list of lists
"""
i = 0
new_list = []
while i < len(x):
new_list.append(x[i:i + n])
i += n
return new_list
def linear_recurse(exes, whys, threshold=1, segments=None):
"""
Recursively breaks a data series into segments until the e^2_norm for all segments is under the threshold.
Data cannot have any None, nan, etc. values
Args:
exes: the x values in the series
whys: the y values in the series
threshold: the e^2_norm threshold that all segments should be under
segments: an optional list of lists that indicate the segment slices to start with and corresponding e^2_norm
Returns: a tuple of lists, where each list is the start (incl), end (excl) and r2 of each segment
"""
if segments is None:
start_end = [0, len(exes)]
segments = [[start_end[0], start_end[1], get_line(exes, whys, start_end)[2]]]
#print(f'New segs: {segments}')
segments = [split_segment(exes,whys,seg) if seg[2] > threshold else seg for seg in segments]
flattened = [i for i in flatten(segments)]
segments = regroup(flattened, 3)
#print(f'New Segments: {segments}')
if all(seg[2] <= threshold for seg in segments):
return segments
else:
return linear_recurse(exes, whys, threshold=threshold, segments=segments) |
############################Problem 1###################################
import pandas as pd
import numpy as np
# Loading the data set
salary_train = pd.read_csv("C:/Users/hp/Desktop/naive bayes assi/SalaryData_Train.csv",encoding = "ISO-8859-1")
salary_test = pd.read_csv("C:/Users/hp/Desktop/naive bayes assi/SalaryData_Test.csv",encoding = "ISO-8859-1")
# Preparing a naive bayes model on training data set
from sklearn.naive_bayes import MultinomialNB as MB
x = {' <=50K' : 0 , ' >50K' : 1}
salary_train.Salary = [x[item] for item in salary_train.Salary]
salary_test.Salary = [x[item] for item in salary_test.Salary]
#getting dummy values for train dataset
salary_train_dummies = pd.get_dummies(salary_train)
salary_train_dummies.drop(['Salary'] , axis = 1 , inplace= True)
salary_train_dummies.head(3)
#checking for na values
salary_train_dummies.columns[salary_train_dummies.isna().any()]
#getting dummy values for test dataset
salary_test_dummies = pd.get_dummies(salary_test)
salary_test_dummies.drop(['Salary'] , axis = 1 , inplace= True)
salary_test_dummies.head(3)
#checking for na values
salary_train_dummies.columns[salary_test_dummies.isna().any()]
salary_test_dummies.columns[salary_test_dummies.isna().any()]
# Multinomial Naive Bayes
classifier_mb = MB()
classifier_mb.fit(salary_train_dummies, salary_train.Salary)
# Evaluation on Test Data
test_pred = classifier_mb.predict(salary_test_dummies)
accuracy_test = np.mean(test_pred == salary_test.Salary)
accuracy_test
from sklearn.metrics import accuracy_score
accuracy_score(test_pred, salary_test.Salary)
pd.crosstab(test_pred, salary_test.Salary)
# Training Data accuracy
train_pred = classifier_mb.predict(salary_train_dummies)
accuracy_train = np.mean(train_pred == salary_train.Salary)
accuracy_train
# Multinomial Naive Bayes changing default alpha for laplace smoothing
classifier_mb_lap = MB(alpha = 3)
classifier_mb_lap.fit(salary_train_dummies, salary_train.Salary)
# Evaluation on Test Data after applying laplace
test_pred_lap = classifier_mb_lap.predict(salary_test_dummies)
accuracy_test_lap = np.mean(test_pred_lap == salary_test.Salary)
accuracy_test_lap
from sklearn.metrics import accuracy_score
accuracy_score(test_pred_lap, salary_test.Salary)
pd.crosstab(test_pred_lap, salary_test.Salary)
# Training Data accuracy
train_pred_lap = classifier_mb_lap.predict(salary_train_dummies)
accuracy_train_lap = np.mean(train_pred_lap == salary_train.Salary)
accuracy_train_lap
####################################Problem 2##################################
import pandas as pd
import numpy as np
# Loading the data set
car_data = pd.read_csv("C:/Users/hp/Desktop/naive bayes assi/NB_Car_Ad.csv",encoding = "ISO-8859-1")
#droping first column which is of nominal type
car_data = car_data.iloc[:,1:]
#scaling the data
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
car_data [['Age','EstimatedSalary']] = scaler.fit_transform(car_data [['Age','EstimatedSalary']])
#splitting data into train and test
from sklearn.model_selection import train_test_split
car_train, car_test = train_test_split(car_data, test_size = 0.2)
#getting dummy values for train dataset
car_train_dummies = pd.get_dummies(car_train)
car_train_dummies.drop(['Purchased'] , axis = 1 , inplace= True)
car_train_dummies.head(3)
#getting dummy values for test dataset
car_test_dummies = pd.get_dummies(car_test)
car_test_dummies.drop(['Purchased'] , axis = 1 , inplace= True)
car_test_dummies.head(3)
# Preparing a naive bayes model on training data set
from sklearn.naive_bayes import MultinomialNB as MB
# Multinomial Naive Bayes
classifier_mb = MB(alpha = 3)
classifier_mb.fit(car_train_dummies, car_train.Purchased)
# Evaluation on Test Data
test_pred = classifier_mb.predict(car_test_dummies)
accuracy_test = np.mean(test_pred == car_test.Purchased)
accuracy_test
from sklearn.metrics import accuracy_score
accuracy_score(test_pred, car_test.Purchased)
pd.crosstab(test_pred, car_test.Purchased)
# Training Data accuracy
train_pred = classifier_mb.predict(car_train_dummies)
accuracy_train = np.mean(train_pred == car_train.Purchased)
accuracy_train
#since the model is giving less accuracy it is considered to be not a efficient model
#so we go for Gaussian model
# Gaussian Naive Bayes
from sklearn.naive_bayes import GaussianNB as GB
classifier_mb_lap = GB()
classifier_mb_lap.fit(car_train_dummies, car_train.Purchased)
# Evaluation on Test Data after applying laplace
test_pred_lap = classifier_mb_lap.predict(car_test_dummies)
accuracy_test_lap = np.mean(test_pred_lap == car_test.Purchased)
accuracy_test_lap
from sklearn.metrics import accuracy_score
accuracy_score(test_pred_lap, car_test.Purchased)
pd.crosstab(test_pred_lap, car_test.Purchased)
# Training Data accuracy
train_pred_lap = classifier_mb_lap.predict(car_train_dummies)
accuracy_train_lap = np.mean(train_pred_lap == car_train.Purchased)
accuracy_train_lap
###########################################Problem 3########################################
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer
# Loading the data set
tweet = pd.read_csv("C:/Users/hp/Desktop/naive bayes assi/Disaster_tweets_NB.csv",encoding = "ISO-8859-1")
tweet = tweet.iloc[:,3:5]
# cleaning data
import re
stop_words = []
# Load the custom built Stopwords
with open("C:/Users/hp/Desktop/naive bayes assi/stop.txt","r") as sw:
stop_words = sw.read()
stop_words = stop_words.split("\n")
def cleaning_text(i):
i = re.sub("[^A-Za-z" "]+"," ",i).lower()
i = re.sub("[0-9" "]+"," ",i)
w = []
for word in i.split(" "):
if len(word)>3:
w.append(word)
return (" ".join(w))
tweet.text = tweet.text.apply(cleaning_text)
# removing empty rows
tweet = tweet.loc[tweet.text != " ",:]
# CountVectorizer
# Convert a collection of text documents to a matrix of token counts
# splitting data into train and test data sets
from sklearn.model_selection import train_test_split
tweet_train, tweet_test = train_test_split(tweet, test_size = 0.2)
# creating a matrix of token counts for the entire text document
def split_into_words(i):
return [word for word in i.split(" ")]
# Defining the preparation of tweet texts into word count matrix format - Bag of Words
tweet_bow = CountVectorizer(analyzer = split_into_words).fit(tweet.text)
# Defining BOW for all tweets
all_tweet_matrix = tweet_bow.transform(tweet.text)
# For training messages
train_tweet_matrix = tweet_bow.transform(tweet_train.text)
# For testing messages
test_tweet_matrix = tweet_bow.transform(tweet_test.text)
# Learning Term weighting and normalizing on entire tweet
tfidf_transformer = TfidfTransformer().fit(all_tweet_matrix)
# Preparing TFIDF for train tweet
train_tfidf = tfidf_transformer.transform(train_tweet_matrix)
train_tfidf.shape # (row, column)
# Preparing TFIDF for test emails
test_tfidf = tfidf_transformer.transform(test_tweet_matrix)
test_tfidf.shape # (row, column)
# Preparing a naive bayes model on training data set
from sklearn.naive_bayes import MultinomialNB as MB
# Multinomial Naive Bayes
classifier_mb = MB()
classifier_mb.fit(train_tfidf, tweet_train.target)
# Evaluation on Test Data
test_pred_m = classifier_mb.predict(test_tfidf)
accuracy_test_m = np.mean(test_pred_m == tweet_test.target)
accuracy_test_m
from sklearn.metrics import accuracy_score
accuracy_score(test_pred_m, tweet_test.target)
pd.crosstab(test_pred_m, tweet_test.target)
# Training Data accuracy
train_pred_m = classifier_mb.predict(train_tfidf)
accuracy_train_m = np.mean(train_pred_m == tweet_train.target)
accuracy_train_m
# Multinomial Naive Bayes changing default alpha for laplace smoothing
classifier_mb_lap = MB(alpha = 3)
classifier_mb_lap.fit(train_tfidf, tweet_train.target)
# Evaluation on Test Data after applying laplace
test_pred_lap = classifier_mb_lap.predict(test_tfidf)
accuracy_test_lap = np.mean(test_pred_lap == tweet_test.target)
accuracy_test_lap
from sklearn.metrics import accuracy_score
accuracy_score(test_pred_lap, tweet_test.target)
pd.crosstab(test_pred_lap, tweet_test.target)
# Training Data accuracy
train_pred_lap = classifier_mb_lap.predict(train_tfidf)
accuracy_train_lap = np.mean(train_pred_lap == tweet_train.target)
accuracy_train_lap
################################################END######################################
|
# -*- coding: utf-8 -*-
"""
如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true;否则返回 false。
"""
class Solution:
# one 实现方式和 numsum_#653相同,存入集合中,判断最后集合是否只剩一个元素(True)。
# 执行用时 48ms,内存消耗 13.8MB
# def isUnivalTree(self, root):
# s = set()
# queue = [root]
# while queue:
# node = queue.pop(0)
# s.add(node.val)
# if node.left:
# queue.append(node.left)
# if node.right:
# queue.append(node.right)
# if len(s) == 1:
# return True
# return False
# two 执行用时52ms,内存消耗13.7MB
def isUnivalTree(self, root):
if (root.left and root.val != root.left.val) or (root.right and root.val != root.right.val):
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right) |
from collections import defaultdict
class Trie:
def __init__(self):
def node():
return defaultdict(node)
self.root = node()
def insert(self, word: str):
node = self.root
for c in word:
node = node[c]
node[None]
def find(self, word: str) -> bool:
node = self.root
for c in word:
if c not in node:
return False
node = node[c]
return None in node
def delete(self, word: str) -> bool:
node = self.root
for c in word:
if c not in node:
return False
node = node[c]
if None in node:
del node[None]
return True
return False
|
# 8.9 LAB: Car value (classes)
# Complete the Car class by creating an attribute purchase_price (type int) and the method print_info() that outputs the car's information.
#
# Ex: If the input is:
#
# 2011
# 18000
# 2018
# where 2011 is the car's model year, 18000 is the purchase price, and 2018 is the current year, then print_info() outputs:
#
# Car's information:
# Model year: 2011
# Purchase price: 18000
# Current value: 5770
# Note: print_info() should use three spaces for indentation.
class Car:
def __init__(self, purchase_price=0):
self.model_year = 0
self.purchase_price = purchase_price
self.current_value = 0
def calc_current_value(self, current_year):
depreciation_rate = 0.15
# Car depreciation formula
car_age = current_year - self.model_year
self.current_value = round(self.purchase_price * (1 - depreciation_rate) ** car_age)
def print_info(self):
print('Car\'s information:')
print(' Model year: {}'.format(self.model_year))
print(' Purchase price: {}'.format(self.purchase_price))
print(' Current value: {}'.format(self.current_value))
if __name__ == "__main__":
year = int(input())
price = int(input())
current_year = int(input())
my_car = Car()
my_car.model_year = year
my_car.purchase_price = price
my_car.calc_current_value(current_year)
my_car.print_info()
|
def find_number(p_array, c_array):
return sorted(p_array[c_array[0] - 1:c_array[1]])[c_array[2] - 1]
def solution(array, commands):
answer = []
for c in commands:
answer.append(find_number(array, c))
return answer |
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
ldx, rdx = 0, len(s) - 1
while (ldx < rdx):
s[ldx], s[rdx] = s[rdx], s[ldx]
ldx += 1
rdx -= 1 |
import pprint #pprint makes the print look cleaner
message = '''adjsajdbnasa
bndsDASDF
S''' #if I use three quotes to open and end a string, I can format it in any way!
count = {}
for character in message.upper():
count.setdefault(character,0) #adds letter seen for the first time as a key and defaults its value to 0
count[character] = count[character] + 1
pprint.pprint(count)
#to have it printed as a string instead of printed to the shell, I can use pprint.format e.g:
text = pprint.pformat(count)
print(text)
|
from collections import Counter
from matplotlib import pyplot as plt
grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
def decile(grade: float) -> int:
return grade // 10 * 10
histogram = Counter(decile(grade) for grade in grades)
# move cada barra para a esquerda em 4
# dá para cada barra sua altura correta
# dá para cada barra a largura de 8
plt.bar([x - 4 for x in histogram.keys()], histogram.values(), 8)
# eixo x de -5 até 105
# eixo y de 0 até 5
plt.axis([-10, 102, 0, 5])
# rótulos do eixo x em 0, 10, ..., 100
plt.xticks([10 * i for i in range(11)])
plt.xlabel("Decil")
plt.ylabel("# de Alunos")
plt.title("Distribuição das Notas do Teste 1")
plt.show()
|
import numpy as np
import matplotlib.pyplot as plt
def drag_force(velocity):
B_m = 0.0039 + 0.0058 / (1. + np.exp((velocity-35)/5))
return B_m * velocity
class BallInAir:
def __init__(self, x0, y0, velocity, angle_deg, noise=[1., 1.]):
self.x = x0
self.y = y0
angle = np.deg2rad(angle_deg)
self.vel_x = velocity * np.cos(angle)
self.vel_y = velocity * np.sin(angle)
self.noise = noise
def step(self, dt, vel_wind=0.):
# air drag
vel_x_wind = self.vel_x - vel_wind
vel = np.sqrt(vel_x_wind**2 + self.vel_y**2)
F = drag_force(vel)
# euler equations
self.x += self.vel_x * dt
self.y += self.vel_y * dt
self.vel_x -= F*vel_x_wind*dt
self.vel_y -= 9.81*dt + F*self.vel_y*dt
return (self.x + np.random.randn()*self.noise[0],
self.y + np.random.randn()*self.noise[1])
def generate_measurements(x=0, y=1, velocity=50, angle_deg=60, dt=1/10,
noise=[.3, .3]):
"""x, y: m. velocity: m/s. angle_deg: degree. dt: s. noise: m"""
ball = BallInAir(x, y, velocity, angle_deg, noise)
measurements = []
while y >= 0: # until ball falls on ground
x, y = ball.step(dt)
measurements.append((x, y))
measurements = np.array(measurements)
return measurements
if __name__ == "__main__":
x, y = 0, 1 # m
velocity = 50 # m/s
angle_deg = 60 # degree
dt = 1/10 # s
noise = [.3, .3]
measurements = generate_measurements(x, y, velocity, angle_deg, dt, noise)
plt.scatter(measurements[:, 0], measurements[:, 1])
plt.axis("equal")
plt.show()
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head
def add(self, key): #agregar al principio
nodo = Node(key)
if not self.isEmpty():
self.head = nodo
self.last = nodo
else:
nodo.next = self.head
self.head = nodo
def append(self,key):
nodo = Node(key)
if not self.isEmpty():
self.head = nodo
else:
self.last.next = nodo
self.last = nodo
def print(self):
i = self.head
while i:
print(i.data, end=' -> ')
i = i.next
print()
ll = LinkedList()
ll.add(2)
ll.add(3)
ll.add(7)
ll.add(1)
ll.append(6)
ll.append(8)
ll.print() |
#vectores
#Crear un programa que reciba 10 números y calcule su suma
i = 0 #contador
suma = 0 #acumulador
while i < 10:
numero = int(input(f"Digite el {i+1} número: "))
suma = suma + numero
i = i + 1
print(f"El valor de la suma es {suma}")
suma = 0
for i in range(0,10,1):
numero = int(input(f"Digite el {i + 1} número: "))
suma = suma + numero
i = i + 1
print(f"El valor de la suma es {suma}")
#Crear un programa que reciba 10 números y calcule su suma y después imprima cada uno de los números digitados
suma = 0
for i in range(0,10,1):
numero = int(input(f"Digite el {i + 1} número: "))
suma = suma + numero
i = i + 1
print(f"El valor de la suma es {suma}")
#Vectores
#Definicion e inicialización de vectores
vector = [0]*(10)
print(vector)
print(vector[9])
vector[8] = 4
print(vector[8])
vector = [0]*(10) #definir mi vector
suma = 0 #inicializo mi acumulador
for i in range(10): #Entrada de datos
vector[i] = int(input(f'Digite el {i+1} número'))
for i in range(10): #imprimer los datos que digitó el usuario
print(f'El {i+1} que usted digitó es {vector[i]}')
i = 0 #imprime la posición del vector y su respectivo valor
while i<10:
print(f'En la posicion {i} del vector esta el valor {vector[i]}')
i = i + 1
for i in range(10): #Calcula e imprime la suma de los datos
suma = suma + vector[i]
print ("La suma es: ", suma)
print(vector)
print("El número de datos que tiene el vector es ", len(vector))
#Crear una función que reciba un arreglo y un número (tamaño del arreglo)
#El usuario debe digitar el tamaño del arreglo y llenarlo con numeros aleatorios entre 1 a 99
import random
def llenadoArreglo(arreglo, n):
for i in range (0,n):
arreglo[i] = random.randint(1,99)
n = int(input("Digite el tamaño del vector: "))
arreglo = [0]*n
print(arreglo)
llenadoArreglo(arreglo,n)
print(arreglo)
#Crear un programa que cree un vector de n posiciones dadas por el usuario con numeros aleatorios
# e imprima los pares
import random
def llenadoArreglo(arreglo, n):
for i in range (0,n):
arreglo[i] = random.randint(1,99)
n = int(input("Digite el tamaño del vector: "))
arreglo = [0]*n
llenadoArreglo(arreglo, n)
print(arreglo)
for i in range(0,n):
if arreglo[i] % 2 == 0:
print(arreglo[i])
#Crear un programa que cree un vector de n posiciones dadas por el usuario con numeros aleatorios
# almacene en un vector los números pares, en otro los numeros impares y luego imprima los pares
#Opcion 1
import random
def llenadoArreglo(arreglo, n):
for i in range (0,n):
arreglo[i] = random.randint(1,99)
n = int(input("Digite el tamaño del vector: "))
arreglo = [0]*n
llenadoArreglo(arreglo, n)
print(arreglo)
contPares = 0
contImpares = 0
for i in range(0,n): #Se recorre el arreglo para saber si el numero es par o impar e incrementar el cont
if arreglo[i] % 2 == 0:
contPares = contPares+1
else:
contImpares = contImpares + 1
numerosPares = [0] * contPares #inicializar los vectores respectivos con la memoria necesaria
numerosImpares = [0] * contImpares
contPares=0
contImpares=0
for i in range(0,n):
if arreglo[i] % 2 == 0:
numerosPares[contPares] = arreglo[i]
contPares = contPares+1
else:
numerosImpares[contImpares] = arreglo[i]
contImpares = contImpares + 1
print("Numeros pares: ",numerosPares)
print("Numeros impares: ",numerosImpares)
#opcion2
import random
def llenadoArreglo(arreglo, n):
for i in range (0,n):
arreglo[i] = random.randint(1,99)
n = int(input("Digite el tamaño del vector: "))
arreglo = [0]*n
llenadoArreglo(arreglo, n)
print(arreglo)
numerosPares = []
numerosImpares = []
for i in range(0,n): #Se recorre el arreglo para saber si el numero es par o impar e incrementar el cont
if arreglo[i] % 2 == 0:
numerosPares.append(arreglo[i])
else:
numerosImpares.append(arreglo[i])
print("Numeros pares: ",numerosPares)
print("Numeros impares: ",numerosImpares)
print("Numeros pares ordenados: ",numerosPares.sort())
print(numerosPares)
print(type(numerosPares))
#Python no soporta arrays por lo que una opcion es usar list como lo mencionamos
#para usar el concepto de array se utiliza libreria externa
import numpy as np
arreglo = np.array([1,2,3,4,5,"data"])
print(arreglo)
print(type(arreglo))
#problema con array de numpy
|
#Paso 1 instalacion de la librería
#Paso 2 importar librería y crear ventana principal y su mainloop()
from tkinter import *
main_window = Tk() #Ventana principal de la aplicación
main_window.title("Formulario de registro")
#main_window.mainloop() #Abre la ventana y entra en un loop que permite tener la interfaz abierta en la ejecución
#Paso 3. Creación de Frames
#Frames / Marcos -> permiten agrupar contenido
main_frame = Frame(main_window, #Ventana donde se pondra el frame
bg='#FFFFFF', #background color, codigo html con el color
height = 500, #alto
width = 500, #ancho
padx = 50, #margen en el eje x
pady = 50, #margen en el eje y
cursor='arrow') #que figura tiene el cursor -> dot, arrow
main_frame.pack() #se instancia en la interfaz (se pone)
#main_window.mainloop() #Toda la creación de interfaces debe estar entre main_window= TK() y .mainloop()
#Paso 4. Labels -> Se utiliza para escribir texto, títulos, etiquetas de botones, etc
title_label = Label(main_frame, #frame donde se ubica el Label
text = "Formulario de registro", #texto a visualizar en el label
font=('Arial',11), #Tipo de letra y tamañO
fg = '#000000', #Color de la letra
justify = CENTER) #Alineación LEFT, RIGHT, CENTER
title_label.pack()
#main_window.mainloop()
#Paso 5. PhotoImage -> Insertar imagenes en el Frame que se esta trabajando
imagen = PhotoImage(file='register_form.png')
img_label = Label(main_frame, #frame donde se ubica el Label
image=imagen) #path de la imagen a visualizar
img_label.pack()
#main_window.mainloop()
#Paso 6. Button -> Botones
boton = Button(main_frame, text = "Click")
boton.pack()
#main_window.mainloop()
def accion():
global boton_text
if boton_text == "Click":
boton_text = "Le dió click"
else:
boton_text = "Click"
boton.config(text=boton_text)
#acciones en un boton
boton_text = "Click" #Se debe crear una variable para almacenar el texto
boton = Button(main_frame, text =boton_text, command = accion)
boton.pack()
#main_window.mainloop()
#Paso 7 -> Posicionamiento se utiliza .place(x = posX, y = posY)
ventana = Tk()
ventana.title("Posicionamiento")
ventana.geometry("400x200")
boton = Button(ventana, text = "Primer Widget").place(x=10, y=10)
etiqueta = Label(ventana, text="Segundo Widget").place(x=200, y=10)
etiqueta2 = Label(ventana, text="Tercer Widget").place(x=10, y=30)
etiqueta3 = Label(ventana, text="Cuarto Widget").place(x=200, y=30)
#ventana.mainloop()
#Ejercicio Paint -> haciendo clic "Dame clic para saludar" muestra el mensaje "Hola a todos
#haciendo clic para minimizar la ventana se minimiza
def saludo():
print("Hola a todos")
def minimizar():
ventana.iconify()
ventana = Tk()
ventana.title("Ejercicio Numero 1")
ventana.geometry("400x200")
etiqueta1 = Label(ventana, text = "Desde aqui saludamos").place(x=30, y=50)
etiqueta2 = Label(ventana, text="Desde aquí minimizamos").place(x=30, y=100)
boton1 = Button(ventana, text="Dame click para saludar", command=saludo).place(x=200, y =50)
boton2 = Button(ventana, text="Dame click para minimizar", command=minimizar).place(x=200, y=100)
ventana.mainloop()
#Paso 8 - > Entradas de texto
ventana = Tk()
ventana.title("Entrada de datos")
textbox = Entry(ventana)
textbox.pack()
#ventana.mainloop()
#Paso 9 -> Variables de control: Son objetos especiales que se asocian a los widgets para almacenar sus valores y facilitar su
#disponibilidad en otras partes del programa,
#entero = IntVar()
#flotante = DoubleVar()
#cadena = StringVar()
#boolean = BooleanVar()
#al declarar es posbile asignar un valor inicial
#blog = StringVar(value = "Python para impacientes")
#Método Set para asigar un valor Ej blog.set("Perdón para principiantes")
#Metodo Get para obtener el valor Ej blog.get()
#Ejercicio 2 Saludo Personalizado
def saludar():
print("Hola: "+nombre.get()+" "+primerApellido.get()+" "+segundoApellido.get())
ventana = Tk()
ventana.title("Entrada de datos")
ventana.geometry("400x400")
nombre = StringVar()
primerApellido = StringVar()
segundoApellido = StringVar()
nombre.set("Escribe tu nombre")
etiqueta1 = Label(ventana, text="Escribe tu nombre: ").place(x=10,y=10)
nombreCaja = Entry(ventana, textvariable = nombre).place(x=170, y=10)
etiqueta2 = Label(ventana, text="Escribe tu primer apellido: ").place(x=10, y=40)
primerApellidoCaja = Entry(ventana, textvariable = primerApellido).place(x=170, y=40)
etiqueta3 = Label(ventana, text="Escribe tu segundo apellido: ").place(x=10,y=70)
segundoApellidoCaja = Entry(ventana, textvariable = segundoApellido).place(x=170, y = 70)
boton= Button (ventana, text = "Saludo Personalizado ", command= saludar).place(x=10, y =100)
ventana.mainloop()
#Ejemplo Botones 1
"""import time
def parpadear():
ventana.iconify()
time.sleep(3)
ventana.deiconify()
ventana = Tk()
boton = Button(ventana, text = "Evento", command=parpadear)
boton.pack()
#ventana.mainloop()"""
#
|
#deque: list-like container with fast appends and pops on either end
#namedtuple: function for creating tuple subclasses with named fields
from collections import deque, namedtuple
#Make the default value for node distance infinity
infinity = float('inf')
#Define a namedtuple 'Edge'
Edge = namedtuple('Edge', 'start, end, cost', verbose = True)
#Setup a function that returns an edge namedtuple
def make_edge(start, end, cost = 1):
return Edge(start, end, cost)
#Creation of main class
class Metric:
#Always define __init__ first in a class
def __init__(self, edges):
#Should be empty unless an edge is entered incorrectly
wrong_edges = [e for e in edges if len(e) not in [2,3]]
#Shows which inputs led to an issue
if wrong_edges:
raise ValueError('Wrong edge data input: {}'.format(wrong_edges))
#(*edge) passes a variable length argument list (*args)
self.edges = [make_edge(*edge) for edge in edges]
|
from datetime import datetime
class MyLogger:
"""
Замеряет скорость работы кода. Результат печатает в консоль и логирует в файл.
"""
def __init__(self, log_file_path):
self.path = log_file_path
def __enter__(self):
self.log = open(self.path, 'a', encoding='utf-8')
self.start_time = datetime.now()
self.set_event('Перевод начат.')
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop_time = datetime.now()
if exc_tb:
self.set_event(f'Ошибка: {exc_val}')
self.set_event('Перевод остановлен.')
else:
self.set_event('Перевод окончен.')
self.time = self.stop_time - self.start_time
self.set_event(f'Время затраченное на перевод: {self.time}')
def set_event(self, message):
event = f'{datetime.now()}: {message}'
self.log.write(event + '\n')
print(event)
|
from turtle import *
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
x = 0
print(x)
for i in colors:
setx(x)
fillcolor(i)
begin_fill()
pencolor(i)
forward(30)
right(90)
forward(60)
right(90)
forward(30)
right(90)
forward(60)
right(90)
end_fill()
x += 30
print(x)
mainloop()
|
from turtle import *
length = 100
num_sides = 3
degrees = [60,30,18,12,8]
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
i = 0
for degree in degrees:
pencolor (colors[i])
left(degree)
for _ in range(num_sides):
forward(length)
right(360/num_sides)
num_sides += 1
i += 1
mainloop()
|
import os
def rename(path):
filelist = os.listdir(path)
for files in filelist:
Olddir = os.path.join(path, files)
if os.path.isdir(Olddir):
rename(Olddir)
continue
f,p = os.path.splitext(files)
f1,p1 = os.path.splitext(f)
Newdir = os.path.join(path, f1 + '.your_ext')
os.rename(Olddir, Newdir)
if __name__ == "__main__":
path = '/to/your/path'
rename(path)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.