text
stringlengths 37
1.41M
|
---|
# 2019-01-31
# number sorting and reading in list
number = [4, 6, 2, 7, 1, 8, 9, 0, 3, 5]
number.sort()
print(number[0])
print(number[9])
print(number[len(number) - 1])
print(number[-1])
|
# problem 7: expression calculator
# change minus to negative value with the integer
exp = input("Enter an expression: ").replace(" ", '').replace("-", "+-").split('+')
result = 0
for number in exp:
result += int(number)
print("=", result)
|
# 2019-01-29
# money rate calculator
money = int(input("Account balance: "))
rate = int(input("Rate (%): "))
year = int(input("Simulation year: "))
for i in range(year):
money += money*(rate/100)
print("Year " + str(i + 1) + ", balance is " + str(int(money)))
|
# problem 5: 5 word shiritori
f = open('dict_test.TXT', 'r', encoding='utf-8')
words = []
for line in f:
word = line.split(" : ", 1)[0]
if len(word) == 5:
if " n." in line:
words.append(word)
f.close()
previous = "apple"
used_words = [previous]
while True:
while True:
word = input(previous + ", next word: ").lower()
if len(word) is 5:
if word in words:
if word not in used_words:
if word[0] == previous[-1]:
used_words.append(word)
previous = word
break
else:
print("Error: the word '" + word + "' doesn't match")
else:
print("Error: the word '" + word + "' was already used")
else:
print("Error: the word '" + word + "' doesn't exist")
elif len(word) > 5:
print("Error: the word is longer than 5 characters")
else:
print("Error: the word is shorter than 5 characters")
|
import random
import math
print("\n-------- CONFIG YOUR GAME -------- \n")
lower = int(input("ENTER LOWER BOUND: "))
upper = int(input("ENTER UPPER BOUND: "))
print("\n--------- START THE GAME --------- \n")
x = random.randint(lower, upper)
print("\nYOU HAVE ONLY", round(math.log(upper - lower + 1, 2)), "CHANCES TO GUESS THE NUMBER!\n")
count = 0
while count < math.log(upper - lower + 1, 2):
count += 1
guess = int(input("GUESS A NUMBER: "))
if x == guess:
print("CONGRATULATIONS, YOU DID IT INT ",
count, " TRY")
break
elif x > guess:
print("TOO SMALL!")
elif x < guess:
print("TO HIGH!")
if count >= math.log(upper - lower + 1, 2):
print("\nTHE NUMBER IS %d" % x)
print("\nTHE NEXT TIME WILL BE THE RIGHT TIME!\n") |
import itertools
valid = "Valid"
notValid= "Not Valid"
cardNumber = input("Enter your card number ")
def checkCard(cardNumber):
cardNumber=str(cardNumber)
if (len(cardNumber.split('-')) == 1 and len(cardNumber) == 16) or (len(cardNumber.split('-')) == 4 and all(len(i) == 4 for i in cardNumber.split("-"))):
cardNumber = cardNumber.replace("-", "")
try:
int(cardNumber)
if max(len(list(g)) for _, g in itertools.groupby(cardNumber)) > 3:
result=notValid
else:
result = valid
except ValueError as e:
result = notValid
else:
result = notValid
return result
print(checkCard(cardNumber))
|
import codecademylib
from matplotlib import pyplot as plt
unit_topics = ['Limits', 'Derivatives', 'Integrals', 'Diff Eq', 'Applications']
middle_school_a = [80, 85, 84, 83, 86]
middle_school_b = [73, 78, 77, 82, 86]
def create_x(t, w, n, d):
return [t*x + w*n for x in range(d)]
# Make your chart here
school_a_x = [0.8, 2.8, 4.8, 6.8, 8.8]
school_b_x = [1.6, 3.6, 5.6, 7.6, 9.6]
n = 1 # This is our first dataset (out of 2)
t = 2 # Number of datasets
d = 5 # Number of sets of bars
w = 0.8 # Width of each bar
school_a_x = [t*x + w*n for x in range(d)]
plt.bar(school_a_x, middle_school_a)
#1
n = 2 # This is our second dataset (out of 2)
t = 2 # Number of datasets
d = 5 # Number of sets of bars
w = 0.8 # Width of each bar
school_b_x = [t*x + w*n for x in range(d)]
#2 creating width & height
plt.figure(figsize=(10, 8))
# Make your chart here#creating set of axes
ax = plt.subplot()#3
plt.bar(school_a_x, middle_school_a )#4
plt.bar(school_b_x, middle_school_b)
middle_x = [(a + b)/2.0 for a, b in zip(school_a_x, school_b_x)]#5
ax.set_xticks(middle_x)#6
ax.set_xticklabels(unit_topics)#7
plt.legend(['Middle School A', 'Middle School B'])#8
plt.title("Test Averages on Different Units")#9
plt.xlabel("Unit")
plt.ylabel("Test Average")
plt.show()
plt.savefig('my_side_by_side.png')
|
def multi_table(a):
for i in range(1,11):
print('{0} × {1} = {2}'.format(a,i,i*a))
if __name__ == '__main__':
a=input('Enter a number: ')
multi_table(float(a))
|
customer = ['fullname', 'type of account',500]
balance= customer.pop(2)
def deposit(balance,Amnt_deposit):
balance = balance + Amnt_deposit
return balance
def withdrawal(balance,Wid_Amnt):
balance = balance -Wid_Amnt
return balance
print('your balance after deposit is',deposit( balance,500))
print('your balance after withdrawal is',withdrawal(balance,300))
#print(balance)
|
import pandas as pd
import numpy as np
wine = pd.read_csv("C:\\Users\\cawasthi\\Desktop\\Data Science\\R ML Code\\dimensionality reduction\\wine.csv")
wine.describe()
wine.head()
'''
Perform Principal component analysis and perform clustering using first
3 principal component scores (both heirarchial and k mean clustering(scree plot or elbow curve) and obtain
optimum number of clusters and check whether we have obtained same number of clusters with the original data
(class column we have ignored at the begining who shows it has 3 clusters)df
'''
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
from sklearn.preprocessing import scale
# Considering only numerical data
wine.data = wine.ix[:,1:]
wine.data.head(4)
# Normalizing the numerical data
wine_normal = scale(wine.data)
pca = PCA(n_components = 13)
pca_values = pca.fit_transform(wine_normal)
# The amount of variance that each PCA explains is
var = pca.explained_variance_ratio_
var
pca.components_[0]
# Cumulative variance
var1 = np.cumsum(np.round(var,decimals = 4)*100)
var1
'''
array([ 36.2 , 55.41, 66.53, 73.6 , 80.16, 85.1 , 89.34, 92.02,
94.24, 96.17, 97.91, 99.21, 100.01])
'''
#observation if we take first 10 columns 96 % of data is covered
# Variance plot for PCA components obtained
plt.plot(var1,color="red")
# plot between PCA1 and PCA2
x = pca_values[:,0]
y = pca_values[:,1]
z = pca_values[:,2]
plt.scatter(x,y,color=["red","blue"])
################### Clustering ##########################
#kmeans with original data set
from sklearn.cluster import KMeans
Sum_of_squared_distances = []
K = range(1,15)
for i in K:
kmeans = KMeans(n_clusters = i)
kmeans.fit(wine.iloc[:,1:])
kmeans.labels_
Sum_of_squared_distances.append(kmeans.inertia_)
#elbow curve
#As k increases, the sum of squared distance tends to zero from K = 3 sharp bend
plt.plot(K, Sum_of_squared_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()
#hierarchical clustering with original data set
from scipy.cluster.hierarchy import linkage
import scipy.cluster.hierarchy as sch # for creating dendrogram
#p = np.array(df_norm) # converting into numpy array format
z = linkage(wine.iloc[:,1:], method="complete",metric="euclidean")
plt.figure(figsize=(25, 5));plt.title('Hierarchical Clustering Dendrogram');plt.xlabel('Index');plt.ylabel('Distance')
sch.dendrogram(
z,
leaf_rotation=0., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
plt.show()
# Now applying AgglomerativeClustering choosing 3 as clusters from the dendrogram
from sklearn.cluster import AgglomerativeClustering
h_complete = AgglomerativeClustering(n_clusters=3, linkage='complete',affinity = "euclidean").fit(wine.iloc[:,1:])
cluster_labels=pd.Series(h_complete.labels_)
wine['clust']=cluster_labels # creating a new column and assigning it to new column
wine['clust'].value_counts()
'''
1 83
2 52
0 43
'''
#kmeans with first 3 principal component scores
from sklearn.cluster import KMeans
new_df = pd.DataFrame(pca_values[:,0:4])
Sum_of_squared_distances = []
K = range(1,15)
for i in K:
kmeans = KMeans(n_clusters = i)
kmeans.fit(new_df)
kmeans.labels_
Sum_of_squared_distances.append(kmeans.inertia_)
#elbow curve
#As k increases, the sum of squared distance tends to zero from K = 3 sharp bend
plt.plot(K, Sum_of_squared_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum_of_squared_distances')
plt.title('Elbow Method For Optimal k')
plt.show()
#hierarchical clustering with PCA
from scipy.cluster.hierarchy import linkage
import scipy.cluster.hierarchy as sch # for creating dendrogram
#p = np.array(df_norm) # converting into numpy array format
z = linkage(new_df, method="complete",metric="euclidean")
plt.figure(figsize=(25, 5));plt.title('Hierarchical Clustering Dendrogram');plt.xlabel('Index');plt.ylabel('Distance')
sch.dendrogram(
z,
leaf_rotation=0., # rotates the x axis labels
leaf_font_size=8., # font size for the x axis labels
)
plt.show()
# Now applying AgglomerativeClustering choosing 4 as clusters from the dendrogram
from sklearn.cluster import AgglomerativeClustering
h_complete = AgglomerativeClustering(n_clusters=4, linkage='complete',affinity = "euclidean").fit(new_df)
cluster_labels=pd.Series(h_complete.labels_)
new_df['clust']=cluster_labels # creating a new column and assigning it to new column
new_df['clust'].value_counts()
'''
Final observation :
1) With full data without PCA
K Means :- 3 Clusters (best fit)
Hireracy :- 3 Clusters (best fit)
2) With PCA takin 3 inital PCA values
K Means :- 3 Clusters (best fit)
Hireracy :- 4 Clusters (best fit)
''' |
__author__ = 'student'
print('Hello World')
c = 10
print(c)
S = str(input())
print(S.replace('','*')[1:-1])
начальное_значение = 1
конечное_значение = 10
i = начальное_значение
while i < конечное_значение:
print(i,i*2,sep=',')
i += 1
print(1, 2, 3)
print(1, 2, 3, sep='')
print(1, 2, 3, sep='~')
print(4, 5, 6, sep=':', end='\n\n')
|
from tkinter import *
from rwFileTest import *
import rwFileTest
root = Tk()
list = readfile()
createTree(list)
searchenty = StringVar()
outputlbl = StringVar()
insertentry= StringVar()
deleteentry = StringVar()
sizelbl=StringVar()
heightlbl=StringVar()
sizetext = "Dictionary Size",rwFileTest.size
depthtext = "Height Of Tree",rwFileTest.maxDepth(rwFileTest.tree.root)
sizelbl.set(sizetext)
heightlbl.set(depthtext)
root.title("Dictionary")
[bfs_list, red_list] = Breadth_first_search(tree.root)
tree.pretty_print()
print(" Size : ",rwFileTest.size)
print("Height: ",rwFileTest.maxDepth(rwFileTest.tree.root))
def searchbtn():
searchenty.get()
if found(searchenty.get()):
outputlbl.set("found")
else:
outputlbl.set("not found")
def insertbtn():
if inserttree(insertentry.get()):
outputlbl.set("Inserted Successfully")
sizetext = "Dictionary Size", rwFileTest.size
depthtext = "Height Of Tree", maxDepth(rwFileTest.tree.root)
sizelbl.set(sizetext)
heightlbl.set(depthtext)
[bfs_list, red_list] = Breadth_first_search(tree.root)
writefile(bfs_list)
tree.pretty_print()
print(" Size : ",rwFileTest.size)
print("Height: ",rwFileTest.maxDepth(rwFileTest.tree.root))
insertentry.set("")
else:
outputlbl.set("ERROR: Word already in the dictionary!")
def deletebtn():
if remmovetree(deleteentry.get()) == 1:
outputlbl.set("Deleted Successfully")
sizetext = "Dictionary Size", rwFileTest.size
depthtext = "Height Of Tree", maxDepth(rwFileTest.tree.root)
sizelbl.set(sizetext)
heightlbl.set(depthtext)
[bfs_list, red_list] = Breadth_first_search(tree.root)
writefile(bfs_list)
tree.pretty_print()
print(" Size : ",rwFileTest.size)
print("Height: ",rwFileTest.maxDepth(rwFileTest.tree.root))
deleteentry.set("")
else:
outputlbl.set("ERROR: Word Not Found in the dictionary!")
Entry(root , width = 30,font="Helvetica 20 bold",textvariable = searchenty). grid(row = 0, column =1)
Entry(root , width = 30,font="Helvetica 20 bold",textvariable = insertentry). grid(row = 1, column =1)
Entry(root , width = 30,font="Helvetica 20 bold",textvariable =deleteentry). grid(row = 2, column =1)
Label(root , text = "Search",font = "Helvetica 12 bold").grid(row = 0 , column =0 , sticky = W)
Label(root , text = "Insert",font = "Helvetica 12 bold").grid(row = 1 , column =0 , sticky = W)
Label(root , text = "Delete",font = "Helvetica 12 bold").grid(row = 2 , column =0 , sticky = W)
Label(root , text = "Output:",font = "Helvetica 12 bold").grid(row = 3 , column =0 , sticky = W)
Label(root , text = " ",font = "Helvetica 14 bold",textvariable = outputlbl).grid(row = 3 , column =1 , sticky = W)
Label(root , text = "None",font = "Helvetica 14 bold",textvariable = sizelbl).grid(row = 4 , column =1 , sticky = W)
Label(root , text = "None",font = "Helvetica 14 bold",textvariable = heightlbl).grid(row = 4 , column =1 , sticky = E)
photo = PhotoImage(file ="search.png")
photo1 = PhotoImage(file ="insert.png")
photo2 = PhotoImage(file ="delete.png")
Button(root,image = photo,command =searchbtn).grid(row =0, column = 8)
Button(root, image = photo1,command = insertbtn).grid(row =1, column = 8)
Button(root, image = photo2,command = deletebtn).grid(row =2, column = 8)
root.mainloop()
|
# クラスの作成 コンストラクタ(インスタンス生成の初期設定メソッド) デクストラクタ(メモリ開放メソッド)
class Color:
def __init__(self, text="red"):
self.text = text
def __del__(self):
print(str(self) + "が破棄されました")
# デクストラクタは必須ではない
color = Color()
print(color.text)
print(color)
color2 = Color("green")
print(color2.text)
print(color2)
|
# 複数インスタンスの生成
class Color:
def __init__(self, r_name="red", g_name="green", b_name="blue"):
self.r_name = r_name
self.g_name = g_name
self.b_name = b_name
def name_p(self, delim=","):
r, g, b = self.r_name, self.g_name, self.b_name
print(f"{r}{delim}{g}{delim}{b}")
color_1, color_2 = Color("赤", "緑", "青"), Color(g_name="midori")
color_1.name_p("|")
color_2.name_p()
color_1.r_name, color_2.r_name = "あか", "きいろ"
color_1.name_p("#")
color_2.name_p("-")
|
# クラスメソッド
class MyClass1:
def __init__(self, a="abc"):
self.a = a
# インスタンス変数
def print_a(self):
print(self.a)
# インスタンス変数aを持つメソッド
def print_hello(self):
print("hello")
# インスタンス変数を持たないメソッド
# クラスメソッドとして定義できる。
@classmethod
def print_bye(cls):
print("bye")
MyClass1().print_a()
MyClass1().print_hello()
MyClass1.print_bye()
print("-"*5)
# clsとは何か
class MyClass2:
a = "A"
# クラス変数
# @classmethod(プロパティ):関数やメソッドの働きを定義する宣言
@classmethod
def print_hello(cls):
print(cls.a)
print(type(cls))
MyClass2.print_hello()
# クラスメソッドの中からもクラス自身(cls)が参照され、"A"が出力される。
print("-" * 5)
# クラスメソッドの作用
class MyClass3:
d = 'クラス変数'
# クラス変数
def print_self_e(self):
print(self.d) # インスタンス変数dの出力
def set_self_e(self, d):
self.d = d # インスタンス変数dの入力
@classmethod
def print_cls_d(cls):
print(cls.d) # クラス変数dの出力
@classmethod
def set_cls_d(cls, d):
cls.d = d # クラス変数dの入力
# インスタンス変数はクラス変数を参照している。
MyClass3().print_self_e()
MyClass3.print_cls_d()
print("#クラス変数の入力を変更")
# クラス変数の入力値を変更
MyClass3.set_cls_d("変更されたクラス変数")
MyClass3().print_self_e()
MyClass3.print_cls_d()
print("MyClass3()を変数mc1,mc2の初期値に設定")
mc1 = MyClass3()
mc2 = MyClass3()
mc1.print_self_e()
mc1.print_cls_d()
mc2.print_self_e()
mc2.print_cls_d()
print("mc1のインスタンス変数の入力を変更")
mc1.set_self_e("EE")
mc1.print_self_e()
mc1.print_cls_d()
print("mc2のインスタンス変数に入力なし")
mc2.print_self_e()
mc2.print_cls_d()
|
# 子クラスにコントラクタを定義するとき、super関数を用いる super().親のコンストラクタ
class Parent:
parent_static_v = "親の静的変数"
def __init__(self, parent_self_v="親インスタンス変数"):
print("親のコンストラクタ")
self.parent_self_v = parent_self_v
def func_parent(self):
print("親のメソッド")
class Child(Parent):
child_static_v = "子の静的変数:この変数の初期値"
def __init__(self, child_self_v="子のインスタンス変数"):
super().__init__("親インスタンス変数")
print("子のコンストラクタ")
self.child_self_v = child_self_v
def func_child(self):
print("子のメソッド")
child = Child()
print(Parent.parent_static_v)
print(Child.child_static_v)
child.func_child()
child.func_parent()
print(child.child_static_v)
print(child.parent_static_v)
print(child.child_self_v)
print(child.parent_self_v)
|
# メソッドの定義
class Color:
def __init__(self, r_name="red", g_name="green", b_name="blue"):
self.r_name = r_name
self.g_name = g_name
self.b_name = b_name
def name_p(self, delim=","):
r, g, b = self.r_name, self.g_name, self.b_name
print(f"{r}{delim}{g}{delim}{b}")
def __del__(self):
print(str(self) + "が破棄されました")
color = Color("赤", "緑", "青")
color.name_p("|")
|
def func(_):
return int(_) * 5
print(func(5))
print((lambda _: _*5)(5))
def func_conv(_):
if " " in _:
res = _.title()
else:
res = _.upper()
return res
print(func_conv("helloworld"))
print(func_conv("hello world"))
print((lambda _: _.title() if " " in _ else _.upper())("helloworld"))
print((lambda _: _.title() if " " in _ else _.upper())("hello world"))
l = ["helloworld", "hello world"]
for i in map(lambda _: _.title() if " " in _ else _.upper(), l):
print(i)
|
# 変数のスコープ(範囲) if文と for文
global_v = "global"
# if文と変数
if True:
# ifブロックからでもグローバル変数は参照できる
print("0:{0}".format(global_v))
# ifブロックからでもグローバル変数を変更できる
global_v = "if1_local"
# ifブロックからローカル変数を設定できるし、当然に変更できる
local_v = "if2_local"
print("1:{0}".format(global_v))
print("2:{0}".format(local_v))
print("3変更されたgloval_v:{0}".format(global_v))
print("4:{0}".format(local_v))
print("-"*10)
for _ in range(3):
# forブロックからグローバルへンスは参照できる
print("0:{0}".format(global_v))
# forブロックからグローバル変数の変更できる
global_v = "for1_local"
local_v = "for2_local"
print("1:{0}".format(global_v))
print("2:{0}".format(local_v))
print("-"*10)
print("3変更されたglobal_v:{0}".format(global_v))
print("4:{0}".format(local_v))
|
import pandas as pd
from io import StringIO
import string
def topic(s):
if isinstance(s, float) or len(s) < 2 or "), (" not in s:
return ""
arr = s.split("), (")
tmp = arr[0].split(',')
text = tmp[0][3:len(tmp[0]) - 1]
num = tmp[1][1:len(tmp[1]) - 1]
# print(num)
return text
def num(s):
if isinstance(s, float) or len(s) < 2 or "), (" not in s:
return ""
arr = s.split("), (")
tmp = arr[0].split(',')
num = tmp[1][1:len(tmp[1]) - 1]
# print(num)
return num
def main():
with open('tuples.csv', 'r') as csvfile:
data = csvfile.read()
df = pd.read_csv(StringIO(data))
df["main_topic"] = df["topics"].apply(topic)
df["probability"] = df["topics"].apply(num)
f = open('main_topic.csv', 'w')
f.write(df.to_csv())
f.close()
print("done")
main() |
def main():
word = input("Please enter a sentence: ")
count(word)
def count(word):
x = word.split()
length = len(x)
print(length)
return length
#def main():
#word = input("Please enter a sentence")
#print(count(word)
if __name__ == "__main__":
main()
|
"""Analyses a ciphertext and predicts whether ciphtext is a transpostion or substitution cipher
Applies letter frequency analysis to predict cipher type.
Compares ciphertext letter frequency against letter frequency proportion from military messages.
Letter frequency is unchanged for a letter transposition cipher (positions moved).
Letter frequency *IS* changed for a letter substitution cipher.
Inputs: Ciphertext text filename, Military letter frequency text file, Threshold letter freqency difference
---Letter frequency table format---
Letter frequency given as a ratio of total letters.
Letters labelled in line
26 lines - each new line indicating a letter.
(eg.
A 0.0813
B 0.0345
etc)
-----------------------------------
Outputs: Prints letter frequency comparison results and prediction of cipher type.
"""
import sys
from collections import defaultdict
#==================================================================================================
# USER INPUT:
# The Ciphertext filename to be analysed:
ciphertext_filename = 'cipher_b .txt'
# Letter frequency table filename to compare against:
military_frequency_filename = 'letter_frequency_military.txt'
# Threshold for classifying ciphers - substitution cipher if freq_diff > THRESHOLD
THRESHOLD = 1
# END OF USER INPUT - DO NOT EDIT BELOW THIS LINE!
#==================================================================================================
def main():
"""Run the program and print a prediction"""
# Load given files
ciphertext = load_text(ciphertext_filename)
military_frequency = load_letter_freq(military_frequency_filename)
# Compare ciphertext letter frequency to given letter frequency
ciphertext_freq = generate_freq(ciphertext)
freq_diff = compare_freq(ciphertext_freq, military_frequency)
# Output results:
print('\nThe difference in letter frequency totals: {}'.format(freq_diff))
print('\nFrequency difference threshold = {}'.format(THRESHOLD))
if (freq_diff - THRESHOLD) > 0:
print('\n\nTherefore this is a letter substitution cipher.')
else:
print('\n\nTherefore this is a letter transposition cipher.')
def load_text(filename):
"""Load the given text file name to a string"""
try:
with open(filename) as file:
text = file.read().lower() # all text processed in lowercase
except IOError as e:
print("{}\nError opening {}. Terminating program.".format(e, file), file=sys.stderr)
sys.exit(1)
return text
def load_letter_freq(filename):
"""Load the given letter frequency table and return as a dictionary"""
letter_freq = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, \
'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, \
'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, \
'y': 0, 'z': 0} # output dictionary
freq_text = load_text(filename)
letter_freq_line = freq_text.split('\n')
# Generate dictionary values and keys
for line in letter_freq_line:
if line == '':
break
(letter, freq) = line.split()
letter_freq[letter] = float(freq)
return letter_freq
def generate_freq(input_string):
"""Generates list of letter frequency as a proportion for 'text_in'"""
stripped_string = ''.join(l for l in input_string if l.isalnum()) # only alphanumeric characters
letter_freq = proportion_letters(stripped_string)
return letter_freq
def proportion_letters(letter_list):
"""Generate proportion of letters in a lowercase alphanum letter list as a decimal. Output as dictionary."""
proportion_dict = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, \
'h': 0, 'i': 0, 'j': 0, 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0, 'p': 0, \
'q': 0, 'r': 0, 's': 0, 't': 0, 'u': 0, 'v': 0, 'w': 0, 'x': 0, \
'y': 0, 'z': 0}
list_len = len(letter_list)
counter = defaultdict(int)
for l in letter_list:
counter[l] += 1
# normalise by list length
for letter, value in counter.items():
value = value/list_len
proportion_dict[letter] = value
return proportion_dict
def compare_freq(freq1, freq2):
"""Outputs the sum of differences between to letter frequency lists"""
result = 0
# sum differences across letters
for key, value in freq1.items():
diff = abs(value - freq2[key])
result += diff
return result
if __name__ == '__main__':
main()
|
"""
Python provides a number of ways to perform printing. Research
how to print using the printf operator, the `format` string
method, and by using f-strings.
"""
x = 10
y = 2.24552
z = "I like turtles!"
# # print integer and float value
# print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))
# # print integer value
# print("Total students : % 3d, Boys : % 2d" %(240, 120))
# # print octal value
# print("% 7.3o"% (25))
# # print exponential value
# print("% 10.3E"% (356.08977))
# Output :
# Geeks : 1, Portal : 5.33
# Total students : 240, Boys : 120
# 031
# 3.561E+02
# Using the printf operator (%), print the following feeding in the values of x,
# y, and z:
# x is 10, y is 2.25, z is "I like turtles!"
print("X is % 2d, Y is % 2.2f, Z is % s" %(x,y,z))
# Use the 'format' string method to print the same thing
print("X is {}, Y is {}, Z is {}".format(x,y,z))
# Finally, print the same thing using an f-string
f"x is {x}, y is {y}, z is {z}"
|
num = 2
name = 'Rabindra'
numType = type(num)
nameType = type(name)
typeType = type(nameType)
print('Number is ' + str(numType) )
# Number is <class 'int'>
print('Name is ' + str(nameType) )
# Name is <class 'str'>
print('Type is ' + str(typeType) )
# Type is <class 'type' |
print("Hello")
userInput='abc'
option=input("d or e?")
print("User input?",userInput)
incBy=input("key?")
key=int(incBy)
if option is 'e':
encryptedOutput=''
for ch in userInput:
asc=ord(ch)
asc=asc+key
newCh=chr(asc)
encryptedOutput= encryptedOutput+newCh
print("Encrypted user input", encryptedOutput)
else:
decryptedOutput=''
for ch in userInput:
asc=ord(ch)
asc=asc-key
newCh=chr(asc)
decryptedOutput=decryptedOutput +newCh
print("Receiver Output:", decryptedOutput) |
#Write a program which can compute the factorial of a given numbers.
#he results should be printed in a comma-separated sequence on a single line.
#Suppose the following input is supplied to the program:
a=8
total=0
while (a<1):
total=a*(a-1)
a=a-1
print(total)
|
import random
list_a = []
list_b = []
list_c = []
#length_a = int(input('enter the length of first list: '))
#length_b = int(input('enter the length of second list: '))
length_a = 50000
length_b = 50000
random_low = 0
random_high = 20000
while length_a > 0:
list_a.append(random.randint(random_low, random_high))
length_a -= 1
while length_b > 0:
list_b.append(random.randint(random_low, random_high))
length_b -= 1
#print("First randomly generated list is: ", ListA)
#print("Second randomly generated list is: ", ListB)
for each in list_a:
if each in list_b and each not in list_c:
list_c.append(each)
# print("Common values between two list is: ", list_c)
print("Common: ", len(list_c))
|
'''
Any generator also is an iterator(not vice versa). Any generator, therefore is a factory that lazily produces values. Here is
the same Fibonacci sequence factory, but written as a generator
'''
# Generator Function
from itertools import islice
def fib():
prev, curr = 0, 1
while True:
yield curr
# Yield first return the value and pause the function until, for next value it is called
prev, curr = curr, prev+curr
f = fib()
# f is now a generator object. Here no code gets executed but is in an idle state.
# list(islice(f, 0, 100000) is iterator object
# list() starts to create a list and the start calling next() on islice() instance. The islice() will call next() of f instance.
# print(list(islice(f, 0, 100000)))
# for _ in range(100000):
# print(next(f))
numbers= [1, 2, 3, 4, 5]
a = (x*x for x in numbers)
# print(list(a)) This makes iterable object. And iterable object must be converted to iterator using iter().
print(next(a))
print(list(a)) |
#Write a program which accepts a sequence of comma-separated numbers from
# console and generate a list and a tuple which contains every number.
num=input("Enter a number")
a=num.split(',')
print(a)
print(tuple(a))
##########teacher solution
num=input("Enter a number")
a=num.split(',')
#a = [item for item in a]
#print(a)
#print(type(a))
m = []
for x in a:
z = int(x)
m.append(z)
print(m) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
name = "Rabindra"
print("Your name is " + name)
name = input("Enter your name: ")
print(f"Your name is: {name}")
num = str(2)
print('My number is '+ num)
|
checkIn = [1,3,5]
checkOut = [2, 6, 8]
room = 1
r = 0
x = len(checkIn)
for j in range(0,x):
for i in range(0,x):
if (checkOut[j] >= checkIn[i+1]):
r+=1
if(room >= r):
r=0
else:
print("impossible")
|
a = int(input())
y=2*a
x =" minutos"
print(format(y)+x) |
a= float(input())
b= int(input())
c= int(input())
tip = (a * (b/100))
x= tip
tax = (a * (c/100))
total = a+ x+ tax
print(round(total))
|
def array(ara):
c = 1
for i in range(1, len(ara)):
if (ara[i] != ara[i - 1]):
ara[c] = ara[i]
c += 1
return c
if __name__== "__main__":
ara=[1,2,3,3,4,4,5,6]
x = array(ara)
print(ara[:x])
|
number = input("Enter the value :")
data_mapping = {
"1" : "One",
"2" : "two",
"3" : "Three"
}
output=""
for ch in number:
print(data_mapping.get(ch,ch))
hey = input("Enter a sentence")
x = input("enter your spilt char :")
print(hey.split(x))
|
def date_fashion(eu, par):
if eu <= 2 or par <= 2:
return 0
elif eu >= 8 or par >= 8:
return 2
else:
return 1 |
def string_permutation(str1,str2):
str_len1=len(str1)
str_len2=len(str2)
ascii_dict = dict.fromkeys([i for i in range(256)],0)
if (str_len1 != str_len2):
return False
for c in str1:
ascii_dict[ord(c)]+=1
for ch in str2:
ascii_dict[ord(ch)]-=1
for key in ascii_dict:
if ascii_dict[key] > 0:
return False
return True
def string_permutation_sort(str1,str2):
str_len1=len(str1)
str_len2=len(str2)
s1=''.join(sorted(str1))
s2=''.join(sorted(str2))
if (str_len1 != str_len2):
return False
for c in range(str_len1):
if s1[c] != s2[c]:
return False
return True
s1="asdfghh"
s2="asdfghh"
print(string_permutation(s1,s2))
print(string_permutation_sort(s1,s2))
|
def find_largest(numbers):
if len(numbers) == 1:
return numbers[0]
else:
m = find_largest(numbers[1:])
return m if m > numbers[0] else numbers[0]
|
from itertools import izip
from textwrap import wrap
# FASTA functions and classes
def fasta_itr(f) :
'''Returns a generator that iterates through a FASTA formatted file.
*f* may be either a text or gzipped file, or a file-like python object
representing either of these. Records are returned in the order they
are found.'''
if isinstance(f,str) :
f = open(f)
# check for magic number 1f 8b indicating gzip file, I dunno, just cuz
if f.read(2) == "\x1f\x8b" : f = gzip.GzipFile(f)
else : f.seek(0)
curr_header, curr_seq = None, None
for r in f :
if r.startswith('>') :
if curr_header is not None :
yield (curr_header, curr_seq)
curr_header = r[1:].strip()
curr_seq = ''
else :
curr_seq += r.strip()
# return the last record
yield (curr_header,curr_seq)
def fasta_to_dict(f) :
'''Returns a dictionary whose keys are FASTA headers and values are
sequences. *f* may be a text, gzipped file, or a file-like
python object representing either of these.'''
return dict(fasta_itr(f))
def write_fasta_to_file(fasta,f,linelen=None) :
'''Writes the FASTA records in *fasta* to file specified in *f*. *fasta*
may be a dictionary like that returned by *fasta_to_dict* or a *FASTAFile*
instance. *f* may be a filename or a file-like object opened with write
mode.'''
if isinstance(fasta,dict) :
fasta_itr = fasta.iteritems()
else :
fasta_itr = fasta
if isinstance(f,str) :
f = open(str,'w')
for header, seq in fasta_itr :
if linelen is not None :
seq = fill(seq,linelen)
f.write('>%s\n%s\n'%(header,seq))
f.close()
class FASTAFile(object) :
'''A file-like object providing information and statistics about the
sequences in a FASTA formatted file. Efficiently iterates through a
text or gzipped FASTA file and provides sequential or random access to
the records. Instances store header and sequence data as they are read.
>>> fasta_str = StringIO(">seq1\\nACATAGGGAT\\n>seq2\\nTTATNTAGATA\\n")
>>> fasta_f = FASTAFile(fasta_str)
>>> [r for r in fasta_f]
[('seq1', 'ACATAGGGAT'), ('seq2', 'TTATNTAGATA')]
>>> fasta_f['seq1']
ACATAGGGAT
>>> fasta_f.headers
['seq1', 'seq2']
>>> fasta_f.sequences
['ACATAGGGAT', 'TTATNTAGATA']
Instances have the following members:
**headers**
list of FASTA headers in original order
**sequences**
list of FASTA sequences in original order
.. NOTE::
The members **headers** and **sequences** are not available until the
the FASTA records have been iterated once.
When indexing like `fasta_f['seq1']`, the class assumes all headers are
unique, iterating does not make this assumption.
'''
def __init__(self,f) :
self._f = f
self._fasta_itr = fasta_itr(f)
self.headers = []
self.sequences = []
self._dict = {}
def __getitem__(self,key) :
return self._dict[key]
def __setitem__(self,key,val) :
self._dict[key] = val
def next(self) :
'''Returns next FASTA record in the file as (header, sequence) tuple.'''
if self._fasta_itr is None :
self._fasta_itr = izip(self.headers,self.sequences)
try :
header, seq = self._fasta_itr.next()
except StopIteration, e :
self._fasta_itr = None
self._f = None
raise e
if self._f is not None :
# this means we're not done reading through the file yet
self.headers.append(header)
self.sequences.append(seq)
self._dict[header] = seq
return header, seq
def __iter__(self) :
return self
# FASTQ functions and classes
def fastq_itr(f) :
'''Returns a generator that iterates through a FASTQ formatted file.
*f* may be either a text or gzipped file, or a file-like python object
representing either of these. Records are returned in the order they
are found.'''
if isinstance(f,str) :
f = open(f)
# check for magic number 1f 8b indicating gzip file, I dunno, just cuz
if f.read(2) == "\x1f\x8b" : f = gzip.GzipFile(f)
else : f.seek(0)
SEQ, QUAL = 0,1
in_region = SEQ
curr_header, curr_seq, curr_qual = None, None, None
for r in f :
if r.startswith('@') :
if curr_header is not None :
yield (curr_header, (curr_seq, curr_qual))
curr_header = r[1:].strip()
curr_seq = ''
curr_qual = ''
in_region = SEQ
elif r.startswith('+') :
in_region = QUAL
else :
curr_field = r.strip()
if in_region == SEQ :
curr_seq += curr_field
elif in_region == QUAL :
curr_qual += curr_field
# return the last record
yield (curr_header,(curr_seq,curr_qual))
def fastq_to_dict(f) :
'''Returns a dictionary whose keys are FASTQ headers and values are
sequences. *f* may be a text, gzipped file, or a file-like
python object representing either of these.'''
return dict(fastq_itr(f))
def write_fastq_to_file(fastq,f,linelen=None) :
'''Writes the FASTQ records in *fasta* to file specified in *f*. *fastq*
may be a dictionary like that returned by *fastq_to_dict* or a *FASTQFile*
instance. *f* may be a filename or a file-like object opened with write
mode.'''
if isinstance(fastq,dict) :
fastq_itr = fasta.iteritems()
else :
fastq_itr = fasta
f_out = open(str,'w') if isinstance(f,str) else f
for header, (seq, qual) in fastq_itr :
if linelen is not None :
seq = fill(seq,linelen)
f_out.write('>%s\n%s\n'%(header,seq))
if isinstance(f,str) :
f_out.close()
class FASTQFile(object) :
'''A file-like object providing information and statistics about the
sequences in a FASTQ formatted file. Efficiently iterates through a
text or gzipped FASTQ file and provides sequential or random access to
the records. Instances store header and sequence data as they are read
>>> fastq_str = StringIO("@seq1\\nACATAGGGAT\\n+seq2\\nY^_cccQYJQ\\n
@seq2\\nTTATNTAGAT\\n+seq2\\nY^_cJcQQJQ")
>>> fastq_f = FASTQFile(fastq_str)
>>> [r for r in fastq_f]
[('seq1', ('ACATAGGGAT', 'Y^_cccQYJQ')), ('seq2', ('TTATNTAGATA', 'Y^_cJcQQJQ'))]
>>> fastq_f['seq1']
('seq1', ('ACATAGGGAT', 'Y^_cccQYJQ'))
>>> fastq_f.headers
['seq1', 'seq2']
>>> fastq_f.sequences
['ACATAGGGAT', 'TTATNTAGAT']
>>> fastq_f.quals
['Y^_cccQYJQ', 'Y^_cJcQQJQ']
Instances have the following members:
**headers**
list of FASTQ headers in original order
**sequences**
list of FASTQ sequences in original order
**quals**
list of FASTQ quality scores in original order
.. NOTE::
The members **headers**, **sequences**, and **quals** are not available
until the the FASTQ records have been iterated once
When indexing like `fastq_f['seq1']`, the class assumes all headers are
unique, iterating does not make this assumption.
'''
def __init__(self,f) :
self._f = f
self._fastq_itr = fastq_itr(f)
self.headers = []
self.sequences = []
self.quals = []
self._dict = {}
def __getitem__(self,key) :
return self._dict[key]
def __setitem__(self,key,val) :
self._dict[key] = val
def next(self) :
'''Returns next FASTA record in the file as (header, sequence) tuple.'''
if self._fastq_itr is None :
self._fastq_itr = izip(self.headers,self.sequences)
try :
header, (seq, qual) = self._fastq_itr.next()
except StopIteration, e :
self._fastq_itr = None
self._f = None
raise e
if self._f is not None :
# this means we're not done reading through the file yet
self.headers.append(header)
self.sequences.append(seq)
self.quals.append(qual)
self._dict[header] = (seq, qual)
return header, (seq, qual)
def __iter__(self) :
return self
|
#!/usr/bin/env python
import sys
import math
import random
import hashlib
SQRT_MAX_PRIME = 45
MAX_PRIME = SQRT_MAX_PRIME ** 2
HASH_SIZE = 20
STRING_SIZE = HASH_SIZE * 2
PRIME_SIZE = STRING_SIZE * 8 / 2
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def generate_primes():
arr: list = [True for i in range(MAX_PRIME)]
for i in range(2, SQRT_MAX_PRIME):
if arr[i]:
j = i ** 2
while j < MAX_PRIME:
arr[j] = False
j += i
return [num for num, i in enumerate(arr) if i and num > 1]
MAIN_PRIMES = generate_primes()
def power(x, y, p):
res = 1
x = x % p
while (y > 0):
if (y & 1):
res = (res * x) % p
y = y>>1
x = (x * x) % p
return res;
# https://www.geeksforgeeks.org/primality-test-set-3-miller-rabin/
def miiller_test(d, n):
a = 2 + random.randint(1, n - 4)
x = power(a, d, n)
if x == 1 or x == n - 1:
return True
while (d != n - 1):
x = (x * x) % n
d *= 2
if (x == 1):
return False
if (x == n - 1):
return True
return False;
def test_is_prime(n, k):
if (n <= 1 or n == 4):
return False
if (n <= 3):
return True
d = n - 1;
while (d % 2 == 0):
d //= 2
for _ in range(k):
if (miiller_test(d, n) == False):
return False
return True
def get_random_prime_range(start, end):
x = random.randrange(start, end)
while True:
is_prime = True
for i in MAIN_PRIMES:
if x % i == 0:
is_prime = False
break
if is_prime and test_is_prime(x, 5):
return x
x += 1
def get_random_prime(length):
return get_random_prime_range(2 ** (length - 1) + 1, 2 ** length)
def gcd_ext(a, b):
if a == 0:
return b, 0, 1
d, x1, y1 = gcd_ext(b % a, a)
return d, y1 - (b // a) * x1, x1
def generate_keys():
n = 0
while n.bit_length() != PRIME_SIZE * 2:
p = get_random_prime(PRIME_SIZE)
q = get_random_prime(PRIME_SIZE)
n = p * q
phi_n = (p - 1) * (q - 1)
K = 1
k = -1
while phi_n % K == 0 or k < 0:
K = random.choice(MAIN_PRIMES)
_, k, __ = gcd_ext(K, phi_n)
return (n, K, n, k)
def any_crypt(data, n, k):
return power(data, k, n)
def parse_block(data):
return int.from_bytes(data, byteorder='big')
def read_block(length):
return sys.stdin.buffer.read(length)
def main(args):
if 'key' in args[0]:
for i in generate_keys():
sys.stdout.buffer.write(i.to_bytes(STRING_SIZE, byteorder='big'))
elif 'sign' in args[0]:
n = parse_block(read_block(STRING_SIZE))
K = parse_block(read_block(STRING_SIZE))
data = read_block(-1)
h = hashlib.sha1(data).digest()
int_hash = parse_block(h)
sign = any_crypt(int_hash, n, K)
sign_bytes = sign.to_bytes(STRING_SIZE, byteorder='big')
sys.stdout.buffer.write(sign_bytes)
elif 'check' in args[0]:
n = parse_block(read_block(STRING_SIZE))
k = parse_block(read_block(STRING_SIZE))
sign = parse_block(read_block(STRING_SIZE))
data = read_block(-1)
h = hashlib.sha1(data).digest()
out = any_crypt(sign, n, k)
out = out.to_bytes(HASH_SIZE, byteorder='big')
# sys.stdout.buffer.write(b'\1' if out == h else b'\0')
print(out == h)
else:
print(args)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
|
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
#sort by height first and then by indexes
dic = dict()
height = []
for h,i in people:
if h not in dic:
dic[h] = [i]
height.append(h)
else:
dic[h].append(i)
height.sort()
height = height[::-1]
answer = []
for h in height:
indexes = dic[h]
for i in sorted(indexes):
answer.insert(i,[h,i])
return answer |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
serial = []
if not root:
return []
def preorder(node):
if node:
serial.append(node.val)
if node.left:
preorder(node.left)
if node.right:
preorder(node.right)
preorder(root)
serial = map(str, serial)
serial = ' '.join(serial)
return serial
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if len(data) == 0:
return []
data = data.split(" ")
serial = [int(x) for x in data]
queue = collections.deque(serial)
print(queue)
def buildTree(minVal, maxVal):
if queue and minVal < queue[0] < maxVal:
val = queue.popleft()
node = TreeNode(val)
node.left = buildTree(minVal, val)
node.right = buildTree(val, maxVal)
return node
# return buildTree(float('-infinity'), float('infinity'))
root = buildTree(float('-inf'), float('inf'))
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root)) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
level = [root]
res = []
rev = 1
while (level):
#Reverse the current traversal order of the result
rev *= -1
res.append([node.val for node in level[::rev]])
next_level = []
for node in level:
next_level.append(node.right)
next_level.append(node.left)
level = [node for node in next_level if node]
return res
|
# Создать несколько переменных, вывести на экран.
# Запросить у пользователя несколько чисел и строк и сохранить в переменные. Вывести на экран.
name = 'Кеша'
age = 4
print('Переменные: ', name, age)
number = int(input('Введите любое число '))
print('Пользователь ввел число', number)
number1 = int(input('Введите другое число '))
print('Пользователь ввел число', number1)
string = input('Введите любую строку ')
print('Пользователь ввел строку', string)
string1 = input('Введите другую строку')
print('Пользователь ввел строку', string1)
|
"""
CNN on mnist data using fluid api of paddlepaddle
"""
import paddle.v2 as paddle
import paddle.fluid as fluid
# Plot data
from paddle.v2.plot import Ploter
import matplotlib
matplotlib.use('Agg')
step = 0
def mnist_cnn_model(img):
"""
Mnist cnn model
Args:
img(Varaible): the input image to be recognized
Returns:
Variable: the label prediction
"""
conv_pool_1 = fluid.nets.simple_img_conv_pool(
input=img,
num_filters=20,
filter_size=5,
pool_size=2,
pool_stride=2,
act='relu')
conv_pool_2 = fluid.nets.simple_img_conv_pool(
input=conv_pool_1,
num_filters=50,
filter_size=5,
pool_size=2,
pool_stride=2,
act='relu')
fc = fluid.layers.fc(input=conv_pool_2, size=50, act='relu')
logits = fluid.layers.fc(input=fc, size=10, act='softmax')
return logits
def mnist_mlp_model(img):
"""
Mnist mlp model
Args:
img(Varaible): the input image to be recognized
Returns:
Variable: the label prediction
"""
fc1 = fluid.layers.fc(input=img, size=512, act='relu')
fc2 = fluid.layers.fc(input=fc1, size=512, act='relu')
logits = fluid.layers.fc(input=fc2, size=10, act='softmax')
return logits
def make_cnn_model(dirname):
"""
Train the cnn model on mnist datasets
"""
img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
logits = mnist_cnn_model(img)
cost = fluid.layers.cross_entropy(input=logits, label=label)
avg_cost = fluid.layers.mean(x=cost)
optimizer = fluid.optimizer.Adam(learning_rate=0.01)
optimizer.minimize(avg_cost)
batch_size = fluid.layers.create_tensor(dtype='int64')
batch_acc = fluid.layers.accuracy(
input=logits, label=label, total=batch_size)
BATCH_SIZE = 50
PASS_NUM = 3
ACC_THRESHOLD = 0.98
LOSS_THRESHOLD = 10.0
train_reader = paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=500),
batch_size=BATCH_SIZE)
# use CPU
place = fluid.CPUPlace()
# use GPU
# place = fluid.CUDAPlace(0)
exe = fluid.Executor(place)
feeder = fluid.DataFeeder(feed_list=[img, label], place=place)
exe.run(fluid.default_startup_program())
pass_acc = fluid.average.WeightedAverage()
for pass_id in range(PASS_NUM):
pass_acc.reset()
for data in train_reader():
loss, acc, b_size = exe.run(
fluid.default_main_program(),
feed=feeder.feed(data),
fetch_list=[avg_cost, batch_acc, batch_size])
pass_acc.add(value=acc, weight=b_size)
pass_acc_val = pass_acc.eval()[0]
print("pass_id=" + str(pass_id) + " acc=" + str(acc[0]) +
" pass_acc=" + str(pass_acc_val))
if loss < LOSS_THRESHOLD and pass_acc_val > ACC_THRESHOLD:
# early stop
break
print("pass_id=" + str(pass_id) + " pass_acc=" + str(pass_acc.eval()[
0]))
fluid.io.save_params(
exe, dirname=dirname, main_program=fluid.default_main_program())
print('train mnist cnn model done')
def make_mlp_model(dirname):
"""
Train the mlp model on mnist datasets
"""
img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
logits = mnist_mlp_model(img)
cost = fluid.layers.cross_entropy(input=logits, label=label)
avg_cost = fluid.layers.mean(x=cost)
optimizer = fluid.optimizer.Adam(learning_rate=0.01)
optimizer.minimize(avg_cost)
batch_size = fluid.layers.create_tensor(dtype='int64')
batch_acc = fluid.layers.accuracy(
input=logits, label=label, total=batch_size)
BATCH_SIZE = 50
PASS_NUM = 3
ACC_THRESHOLD = 0.98
LOSS_THRESHOLD = 10.0
train_reader = paddle.batch(
paddle.reader.shuffle(
paddle.dataset.mnist.train(), buf_size=500),
batch_size=BATCH_SIZE)
# use CPU
place = fluid.CPUPlace()
# use GPU
# place = fluid.CUDAPlace(0)
exe = fluid.Executor(place)
feeder = fluid.DataFeeder(feed_list=[img, label], place=place)
exe.run(fluid.default_startup_program())
pass_acc = fluid.average.WeightedAverage()
for pass_id in range(PASS_NUM):
pass_acc.reset()
for data in train_reader():
loss, acc, b_size = exe.run(
fluid.default_main_program(),
feed=feeder.feed(data),
fetch_list=[avg_cost, batch_acc, batch_size])
pass_acc.add(value=acc, weight=b_size)
pass_acc_val = pass_acc.eval()[0]
print("pass_id=" + str(pass_id) + " acc=" + str(acc[0]) +
" pass_acc=" + str(pass_acc_val))
if loss < LOSS_THRESHOLD and pass_acc_val > ACC_THRESHOLD:
# early stop
break
print("pass_id=" + str(pass_id) + " pass_acc=" + str(pass_acc.eval()[
0]))
fluid.io.save_params(
exe, dirname=dirname, main_program=fluid.default_main_program())
print('train mnist mlp model done')
def make_cnn_model_visualization(dirname):
"""
Train the cnn model on mnist datasets
"""
batch_size = 64
num_epochs = 5
use_cuda = 1
def optimizer_program():
return fluid.optimizer.Adam(learning_rate=0.001)
def train_program():
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
img = fluid.layers.data(name='img', shape=[1, 28, 28], dtype='float32')
predict = mnist_mlp_model(img)
# Calculate the cost from the prediction and label.
cost = fluid.layers.cross_entropy(input=predict, label=label)
avg_cost = fluid.layers.mean(cost)
acc = fluid.layers.accuracy(input=predict, label=label)
return [avg_cost, acc]
train_reader = paddle.batch(
paddle.reader.shuffle(paddle.dataset.mnist.train(), buf_size=500),
batch_size=batch_size)
test_reader = paddle.batch(paddle.dataset.mnist.test(), batch_size=batch_size)
# set to True if training with GPU
place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
trainer = fluid.Trainer(
train_func=train_program, place=place, optimizer_func=optimizer_program)
# Save the parameter into a directory. The Inferencer can load the parameters from it to do infer
params_dirname = dirname
lists = []
def event_handler(event):
if isinstance(event, fluid.EndStepEvent):
if event.step % 100 == 0:
# event.metrics maps with train program return arguments.
# event.metrics[0] will yeild avg_cost and event.metrics[1] will yeild acc in this example.
print "step %d, epoch %d, Cost %f Acc %f " % (event.step, event.epoch,event.metrics[0],event.metrics[1])
if isinstance(event, fluid.EndEpochEvent):
avg_cost, acc = trainer.test(
reader=test_reader, feed_order=['img', 'label'])
print("Test with Epoch %d, avg_cost: %s, acc: %s" %
(event.epoch, avg_cost, acc))
# save parameters
print "save_params"
trainer.save_params(params_dirname)
lists.append((event.epoch, avg_cost, acc))
# Train the model now
trainer.train(
num_epochs=num_epochs,
event_handler=event_handler,
reader=train_reader,
feed_order=['img', 'label'])
# find the best pass
best = sorted(lists, key=lambda list: float(list[1]))[0]
print 'Best pass is %s, testing Avgcost is %s' % (best[0], best[1])
print 'The classification accuracy is %.2f%%' % (float(best[2]) * 100)
def main():
make_cnn_model_visualization('./mnist_blackbox/cnn/')
#make_mlp_model('./mnist_blackbox/mlp')
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 13:38:05 2017
@author: khushalidave
"""
"""
Reads a list of reviews and return the count of positive words in reviews.
"""
#function that loads a lexicon of positive words to a set and returns the set
def loadLexicon(fname):
newLex=set()
lex_conn=open(fname,encoding='utf-8')
#add every word in the file to the set
for line in lex_conn:
newLex.add(line.lower().strip())# remember to strip to remove the lin-change character
lex_conn.close()
return newLex
def removeDuplicates(line):
lineWords=set()
words=line.split(' ')
for word in words:
lineWords.add(word.strip())
return lineWords
#function that reads in a file with reviews and decides if each review is positive or negative
#The function returns a list of the input reviews and a list of the respective decisions
def run(path):
freq={} # new dictionary. Maps each word to each frequency
#load the positive and negative lexicons
posLex=loadLexicon('positive-words.txt')
fin=open(path)
for line in fin: # for every line in the file (1 review per line)
line=line.lower().strip()
lineWords=removeDuplicates(line)
for word in lineWords: #for every word in the review
if word in posLex: # if the word is in the positive lexicon
freq[word] = freq.get(word, 0) + 1
fin.close()
return freq
if __name__ == "__main__":
freq=run('textfile')
for key in freq:
print(key, freq[key])
|
known_users = ["Alice","Bob","Claire","Dan","Emma","Fred","Georgie","Harry","Holger","Holk"]
print(len(known_users))
while True:
print ("Hi! My Name is Travis")
name = input ("Wie ist dein name? ").strip().capitalize()
print (name)
if name in known_users:
print ("Hello {} wie gehts?".format(name))
remove = input ("Möchtest du von der Liste gelöscht werden j/n ").lower()
if remove == "j":
print (known_users)
known_users.remove (name)
print (known_users)
else:
print ("Du bist nicht bekannt")
# Na dat läuft doch schon recht gut! |
student_number = 12
# 학생의 번호를 출력합니다.
print('학생번호 : ', student_number)
# print(student_number)
st_number_str=str(student_number) # 문자열로 변경해주는 형변환 함수 str
print(type(student_number)) # 변수의 타입 확인
print(type(st_number_str)) # 변수의 타입 확인
number_list1 = range(10) # 0~9까지의 숫자 리스트 반환
number_list2 = range(5, 10) # 5~9까지의 숫자 리스트 반환
number_list3 = range(0, 10, 2) #0~9까지의 짝수 숫자 리스트 반환
print("number_list1 : ", type(number_list1))
print("number_list2 : ", number_list2)
print("number_list3 : ", number_list3)
del student_number # 변수 삭제
|
#---------------------------------------------------------------
# Title: Assignment07
# Developer: Thivanka Samaranayake
# Date June01 2020
# Changelog:
# Thivanka, June01 2020, Created Pickling Script
# Thivanka, June02 2020, Created Exception Handling Script
#---------------------------------------------------------------
# How Pickling Works
# https://www.youtube.com/watch?v=2Tw39kZIbhs
import pickle # This imports code from another code file!
example_data = {"Key": "1", "Name": "Frodo", "Title": "Ring Bearer", "Importance": "High"} # Set of data to be pickled
pickle_out = open("dict.pickle", "wb") # creating a binary file to pickle data
pickle.dump(example_data, pickle_out) # pickling data
pickle_out.close() # closing binary file
pickle_in = open("dict.pickle", "rb") # opening binary filed with pickled data
list_of_dic = pickle.load(pickle_in) # unpickling data from binary file
print(example_data) # printing pickled data
print(example_data["Key"]+","+example_data["Name"]) # Still acting like a dictionary
# How Exceptions Work
# https://www.youtube.com/watch?v=NIWwJbo-9_8
class CapitalizationError(Exception):
"""The first letter not capitalized in file name error"""
def __str__(self):
return "Please capitalize the t in test"
try:
docfile = input("Please provide the name of the file you want to open: ")
file = open(docfile)
if file.name == "test.txt":
raise CapitalizationError
except FileNotFoundError as e:
print("This file does not exist")
#print(e)
except Exception as e:
print(e)
else:
print(file.read())
file.close()
finally:
pass
|
class Date:
def __init__(self, date):
self.date = date
def get_date(self):
print('getting the date...')
return self.date
# csak egy fv a classon belül, nem kell hozzá a self, példány
@staticmethod
def to_dash_date(date):
return date.replace('/', '-')
@classmethod
def extra_year(cls, date):
date_parts = date.get_date().split('-')
year = date_parts[0]
month = date_parts[1]
day = date_parts[2]
new_date = f"{int(year)+1}-{month}-{day}"
return cls(new_date)
my_date = Date("2020-01-15")
print(my_date.get_date())
date_from_db = '2021/03/23'
converted_date_from_db = Date.to_dash_date(date_from_db)
print(converted_date_from_db)
extra_year_date = Date.extra_year(my_date)
print(extra_year_date.get_date()) |
from functools import wraps
def max_grade(max_grade_value):
'''Adds the 'max_grade' annotation'''
def max_grade_decorator(func):
'''Adds the 'max_grade' attribute to the specified function'''
func.max_grade = max_grade_value
@wraps(func)
def _wrapper(*args, **kwargs):
return func(*args, **kwargs)
return _wrapper
return max_grade_decorator
|
#动态规划,大规模的问题,能由小问题推出;
#建立动态方程 f(x) = g(f(x-1)), 存储中间解, 按顺序从小往大算
#动态规划:求最长子序列
def lis(d):
b = []
for i,v in enumerate(d):
if i==0:
b.append(v)
if d[i] < b[-1]:
for k,bv in enumerate(b):
if d[i] > v:
b = b[0:k]
if d[i] > b[-1]:
b.append(d[i])
return b
#动态规划:斐波那契数列
def fib(n):
#缓存结果
results = list(range(n+1))
for i in range(n+1):
if i<2 :
results[i] = i
else:
results[i] = results[i-1] + results[i-2]
return results[-1]
if __name__ == '__main__':
print(lis([1,3,5,6,2,4,7,9]))
print(fib(100)) |
# KNN algorithm example
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# importing the dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
# assign column names to the dataset
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
# read dataset to pandas dataframe
dataset = pd.read_csv(url, names=names)
dataset.head()
# preprocessing
X = dataset.iloc[:, :-1].values # select everything except the last column
y = dataset.iloc[:, 4].values # only the fourth column is selected
from sklearn.model_selection import train_test_split
# this splits the dataset into 80% train data and 20% test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
# feature scaling
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# training and predictions
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(X_train, y_train)
# make the prediction
y_pred = classifier.predict(X_test)
# evaluating the algorithm
from sklearn.metrics import classification_report, confusion_matrix
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
# comparing error rate with the K value
error = []
# calculating error for K values between 1 and 40
for i in range(1, 40):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train, y_train)
pred_i = knn.predict(X_test)
error.append(np.mean(pred_i != y_test))
plt.figure(figsize=(12,6))
plt.plot(range(1,40), error, color='red', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=10)
plt.title('Error Rate K Value')
plt.xlabel('K Value')
plt.ylabel('Mean Error')
|
a = 9
b = 7
# ADD 2 NUMBERS
print(a + b)
# MULTIPLY 2 NUMBERS
c = a * b
print(c)
# DIVIDE 2 NUMBERS
d = a / b
print (d)
# INTEGER DIVISION
e = a // b
print(e)
# EXPONENT: b squared
print(b ** 2)
# MODULUS - remainder of a division
print(b % 3)
print(a % 4)
# EVEN? OR ODD - USE MOD
print(a % 2 == 0)
print(14 % 2 == 0)
# single = sign is for assigning a value to a variable
# double == is for comparisons
|
"""
Given a array of positive numbers and a positive number S, find the length of the smallest
contiguous subarray whose sum is greater than or equal to S.
Return 0, if no such subarray exist.
"""
import numpy
def smallest_subarray_with_given_sum(s, arr):
j = 0
ssum = 0
import math
length=math.inf
minL = []
for i in range(0, len(arr)):
ssum += arr[i]
while ssum >= s:
length = min(length, i-j+1)
minL.append(length)
ssum -= arr[j]
j=j+1
print(minL)
if minL == []:
return 0
else:
r = min(minL)
return r
def main():
arr = [1,2,4,1,1]
r = smallest_subarray_with_given_sum(7,arr)
print(r)
main()
|
## Caterpillar method
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
type s: str
rtype: int
"""
length = 0
#print(len(s))
chars = set()
left,right=0,0
while left < len(s) and right < len(s):
#if s[right] in chars:
# if s[right] == s[left]:
# chars.remove(s[left])
# left+=1
#else:
# char.adds([right])
#
#right+=1
if s[right] in chars:
if s[right]==s[left]:
chars.remove(s[left])
chars.add(s[right])
left+=1
else:
chars.add(s[right])
right+=1
return len(chars),chars
def main():
#str = 'babbcaza'
str = 'abcabcbb'
str = 'abbb'
result, chars = Solution().lengthOfLongestSubstring(str)
print(result)
print(chars)
main()
|
from utils import *
from constants import *
def process_words(word_list_file):
"""
This function reads a file of words and produces word-level and character-level information.
:param word_list_file: a file of words, one per line. '#' and '//' are used for comments.
:return: a list of unique words, a list of unique words in the HEX representation and a
list of unique characters in the HEX representation
"""
try:
words = []
encoded_words = []
hex_chars = []
#Loop over the file and process word by word.
with open(word_list_file, 'r', encoding="utf-8") as fin:
for line in fin:
line = line.strip()
#Ignore comment lines.
if not line or line.startswith('#') or line.startswith('//'):
continue
word = line
words.append(word)
#Covert the word to its HEX representation.
encoded_word = convert_string_to_hex(word)
encoded_words.append(encoded_word)
#Keep track of the unique characters (in the HEX representation).
hex_chars.extend(encoded_word.split())
#Sort the outputs.
words.sort()
encoded_words.sort()
hex_chars = sort_unique(hex_chars)
return set(words), set(encoded_words), hex_chars
except:
print(ERROR_MESSAGE)
return None, None, None
def write_encoded_words(encoded_words, output_path):
"""
This function writes a list of encoded words (in the HEX representation) into a file.
:param encoded_words: a list of encoded words
:param output_path: output path
"""
try:
with open(output_path, 'w') as fout:
fout.writelines('^^^ %s $$$\n' % word for word in encoded_words)
except:
print(ERROR_MESSAGE)
def read_grammar(grammar_file):
"""
This function reads a grammar file and returns a map of the grammar rules.
:param grammar_file: the path of a grammar file
:return: grammar map. The keys represent the unique LHS terms, while
the values are a list of the RHS terms of the corresponding keys
"""
try:
grammar = defaultdict(list)
#Loop over the file and process rule by rule.
with open(grammar_file, 'r', encoding="utf-8") as fin:
for line in fin:
line = line.strip()
#Ignore comment lines.
if not line or line.startswith('#') or line.startswith('//'):
continue
#Read the current rule.
columns = line.partition('-->')
key = columns[0].strip()
value = columns[2].strip()
grammar[key].append(value)
return grammar
except:
print(ERROR_MESSAGE)
return None
def write_grammar(grammar, output_path):
"""
This function writes a grammar map into a file.
:param grammar: grammar map
:param output_path: output path
"""
try:
with open(output_path, 'w', encoding="utf-8") as fout:
for key in grammar:
for value in grammar[key]:
fout.write(key + ' --> ' + value + '\n')
except:
print(ERROR_MESSAGE)
def add_chars_to_grammar(grammar, hex_chars):
"""
This function writes a grammar map into a file - Default AG parameters: 1, 1
:param grammar: grammar map
:param hex_chars: a lust of encoded characters (in the HEX representation)
:return: grammar map with encoded characters
"""
try:
grammar['1 1 Char'].extend(hex_chars)
return grammar
except:
print(ERROR_MESSAGE)
return None
def prepare_cascaded_grammar(grammar, segmentation_path, n, in_prefix_nonterminal, in_suffix_nonterminal, out_prefix_nonterminal, out_suffix_nonterminal, concerntration_param_alphaa, concerntration_param_alphab):
"""
This function seeds a grammar tree with prefixes and suffixes read from the output of some grammar.
:param grammar: grammar map
:param segmentation_path: PYAGS segmentation output path
:param in_prefix_nonterminal: the prefix nonterminal to read from the output
:param in_suffix_nonterminal: the suffix nonterminal to read from the output
:param n: the number of most frequent affixes to extract and seed
:param out_prefix_nonterminal: the prefix nonterminal to seed the prefixes into
:param out_suffix_nonterminal: the suffix nonterminal to seed the suffixes into
:param concerntration_param_alphaa: concentration parameter αA
:param concerntration_param_alphab: concentration parameter αB
:return: cascaded grammar map
"""
try:
_, prefixes, suffixes = get_top_affixes(segmentation_path, n, in_prefix_nonterminal, in_suffix_nonterminal)
#Seed the grammar with the prefixes.
if concerntration_param_alphaa == 0 and concerntration_param_alphab == 0:
grammar[out_prefix_nonterminal].extend([convert_string_to_hex(prefix) for prefix in prefixes])
else:
grammar[str(concerntration_param_alphaa) + ' ' + str(concerntration_param_alphab) + ' ' + out_prefix_nonterminal].extend([convert_string_to_hex(prefix) for prefix in prefixes])
#Seed the grammar with the suffixes.
if concerntration_param_alphaa == 0 and concerntration_param_alphab == 0:
grammar[out_suffix_nonterminal].extend([convert_string_to_hex(suffix) for suffix in suffixes])
else:
grammar[str(concerntration_param_alphaa) + ' ' + str(concerntration_param_alphab) + ' ' + out_suffix_nonterminal].extend([convert_string_to_hex(suffix) for suffix in suffixes])
return grammar
except:
print(ERROR_MESSAGE)
return None
def prepare_scholar_seeded_grammar(grammar, lk_path, out_prefix_nonterminal, out_suffix_nonterminal, concerntration_param_alphaa, concerntration_param_alphab):
"""
This function seeds a grammar tree with prefixes and suffixes read from an LK file (LK stands for Loinguistic Knowledge).
:param grammar: grammar map
:param lk_path: linguistic-knowledge file path (see examples under data)
:param out_prefix_nonterminal: the prefix nonterminal to seed the prefixes into
:param out_suffix_nonterminal: the suffix nonterminal to seed the suffixes into
:param concerntration_param_alphaa: concentration parameter αA
:param concerntration_param_alphab: concentration parameter αB
:return: scholar-seeded grammar map
"""
try:
#Read the prefixes and suffixes from the file.
prefixes, suffixes = read_linguistic_knowledge(lk_path)
#Seed the grammar with the prefixes.
if concerntration_param_alphaa == 0 and concerntration_param_alphab == 0:
grammar[out_prefix_nonterminal].extend([convert_string_to_hex(prefix) for prefix in prefixes])
else:
grammar[str(concerntration_param_alphaa) + ' ' + str(concerntration_param_alphab) + ' ' + out_prefix_nonterminal].extend([convert_string_to_hex(prefix) for prefix in prefixes])
#Seed the grammar with the suffixes.
if concerntration_param_alphaa == 0 and concerntration_param_alphab == 0:
grammar[out_suffix_nonterminal].extend([convert_string_to_hex(suffix) for suffix in suffixes])
else:
grammar[str(concerntration_param_alphaa) + ' ' + str(concerntration_param_alphab) + ' ' + out_suffix_nonterminal].extend([convert_string_to_hex(suffix) for suffix in suffixes])
return grammar
except:
print(ERROR_MESSAGE)
return None
def read_linguistic_knowledge(lk_file):
"""
This function reads the prefixes and suffixes in an LK file (LK stands for Linguistic Knowledge).
:param lk_path: linguistic-knowledge file path (see examples under data)
:return: lists of prefixes and suffixes o be seeded
"""
try:
prefixes = []
suffixes = []
read_prefixes = False
read_suffixes = False
#Loop over the lines in the file.
with open(lk_file, 'r', encoding="utf-8") as fin:
for line in fin:
line = line.strip()
if len(line) == 0:
continue
#Read prefixes.
if line == LK_PREFIXES:
read_prefixes = True
read_suffixes = False
#Read suffixes.
elif line == LK_SUFFIXES:
read_prefixes = False
read_suffixes = True
elif line.startswith('###'):
break
else:
#Read a merker line.
if read_prefixes:
prefixes.append(line)
elif read_suffixes:
suffixes.append(line)
return prefixes, suffixes
except:
print(ERROR_MESSAGE)
return None, None
def get_top_affixes(segmentation_output_path, count, prefix_nonterminal, suffix_nonterminal):
"""
This function generates top n affixes from a PYAGS segmentation output
:param segmentation_output_path: PYAGS segmentation output path
:param count: an integer indicating how many of the top affixes to return.
:param prefix_nonterminal: the prefix nonterminal to read
:param suffix_nonterminal: the suffix nonterminal to read
:return: top n affixes, all prefixes, and all suffixes
"""
try:
prefix_counter = defaultdict(int)
suffix_counter = defaultdict(int)
with open(segmentation_output_path, 'r', encoding='utf-8') as fin:
for line in fin:
line = line.strip()
#Search for a nonterminal match with a morph RegEx given as input.
morphs, _, _ = get_morphs_from_tree(line, [prefix_nonterminal, suffix_nonterminal])
#Separate into respective affix counter.
for nonterminal in morphs:
for morph in morphs[nonterminal]:
is_prefix = (nonterminal == prefix_nonterminal)
if is_prefix:
prefix_counter[morph] += 1
else:
suffix_counter[morph] += 1
#Return top n affixes.
#Sort prefixes.
prefix_list_sorted = sorted(prefix_counter.items(), key=lambda x: x[1], reverse=True)
suffix_list_sorted = sorted(suffix_counter.items(), key=lambda x: x[1], reverse=True)
n_affixes = []
p = 0 #index for prefix_list_sorted
s = 0 #index for suffix_list_sorted
#Final list of x prefixes and y suffixes such that x+y=n.
prefix_x = []
suffix_y = []
#If prefix and suffix lists were empty, return empty lists.
if len(prefix_list_sorted) == len(suffix_list_sorted) == 0:
return n_affixes, prefix_x, suffix_y
#Get top affixes.
total_count = len(prefix_list_sorted) + len(suffix_list_sorted)
if count > total_count:
count = total_count
while count > 0:
if p == len(prefix_list_sorted) and s == len(suffix_list_sorted):
break
if len(prefix_list_sorted) > 0 and (len(suffix_list_sorted) == 0 or s == len(suffix_list_sorted) or prefix_list_sorted[p][1] > suffix_list_sorted[s][1]):
n_affixes.append(prefix_list_sorted[p][0])
prefix_x.append(prefix_list_sorted[p][0])
p += 1
else:
n_affixes.append(suffix_list_sorted[s][0])
suffix_y.append(suffix_list_sorted[s][0])
s += 1
count -= 1
return n_affixes, prefix_x, suffix_y
except:
print(ERROR_MESSAGE)
return None, None, None
|
#!/bin/env python3
n = int(input())
print(*[num**2 for num in range(n)], sep="\n")
|
def display_board(board_state):
"""
Displays the given state string in a 3 X 3 tic tac toe board
"""
if type(board_state) != str:
raise TypeError('Given board input must be String')
if len(board_state) != 9:
raise Exception("Input board string length is not 9")
counter = 0
# print()
for position in board_state:
counter += 1
if counter % 3 == 0:
if counter != 9:
paddingString = "\n---------\n"
else:
paddingString = ''
else:
paddingString = " | "
if position.isnumeric():
print(" ", end=paddingString)
else:
print(position, end=paddingString)
print("\n\n")
def input_to_board(input_index, board_state, player_symbol):
"""
input_to_board(input_index, board_state, player_symbol)
It returns the a new board state based on the given input index, input board state and player symbol
Input : input_index where user wants to enter his symbol in the board,
board_state is the input state of the board,
player_symbol is the symbol player wants to enter in the board (like X/O).
Output : returns a new state with the input index
"""
output_state = ''
for ind, val in enumerate(board_state):
if ind == input_index - 1:
if val.isnumeric():
output_state += player_symbol
else:
raise Exception("Cannot change already assigned board values")
else:
output_state += val
return output_state
def check_board(board_state, player_symbol, display_message = False):
"""
check_board function receives board state and player symbol to be checked and returns whether the status of the
game with respect to the player
INPUT:
board_state: It refers the state string
player_symbol: It refers the player's symbol by which the board has to be verified
display_message: an optional parameter, when enabled prints additional result
OUTPUT:
returns True or False based on the end result of the game
"""
is_board_completely_filled = board_state.isalpha()
indices_set = set([ind+1 for ind, val in enumerate(board_state) if val == player_symbol])
if {1, 2, 3}.issubset(indices_set) or {4, 5, 6}.issubset(indices_set) or {7, 8, 9}.issubset(indices_set):
if display_message:
print("Row completed..!!!")
print("Player "+player_symbol+" won the game.")
return True
if {1, 4, 7}.issubset(indices_set) or {2, 5, 8}.issubset(indices_set) or {3, 6, 9}.issubset(indices_set):
if display_message:
print("Column completed..!!!")
print("Player "+player_symbol+" won the game.")
return True
if {1, 5, 9}.issubset(indices_set) or {3, 5, 7}.issubset(indices_set):
if display_message:
print("Diagonal completed..!!!")
print("Player "+player_symbol+" won the game.")
return True
if is_board_completely_filled:
if display_message:
print("Game is drawn...!")
return "Draw"
return False
def find_possible_actions(board_state):
"""
find_possible_actions(board_state)
It is function that accepts the board state string as input and returns the list of indices from 1 to 9 (not from 0-8).
These empty slots are places in the board where a user/agent attempt an action.
Input : 9 - Character board state string
Output : Returns a list of indices where where one can make a new move.
"""
empty_slot_indices = [ind+1 for ind,
val in enumerate(board_state) if val.isnumeric()]
return empty_slot_indices
def check_board_all(board_state, symbols, display_message = False):
is_board_completely_filled = board_state.isalpha()
for player_symbol in symbols:
indices_set = set(
[ind+1 for ind, val in enumerate(board_state) if val == player_symbol])
if {1, 2, 3}.issubset(indices_set) or {4, 5, 6}.issubset(indices_set) or {7, 8, 9}.issubset(indices_set):
if display_message:
print("Row completed..!!!")
print("Player "+player_symbol+" won the game.")
return (True, player_symbol)
if {1, 4, 7}.issubset(indices_set) or {2, 5, 8}.issubset(indices_set) or {3, 6, 9}.issubset(indices_set):
if display_message:
print("Column completed..!!!")
print("Player "+player_symbol+" won the game.")
return (True, player_symbol)
if {1, 5, 9}.issubset(indices_set) or {3, 5, 7}.issubset(indices_set):
if display_message:
print("Diagonal completed..!!!")
print("Player "+player_symbol+" won the game.")
return (True, player_symbol)
if is_board_completely_filled:
if display_message:
print("The game has been drawn !!!")
return (True, "Draw")
return (False, "Game not over")
def action_diff(state1, state2, player_symbol):
for i in range(9):
if (state1[i] != state2[i]) and ((state1[i] == player_symbol) or (state2[i] == player_symbol)):
if state1[i].isnumeric():
return int(state1[i])
else:
return int(state2[i])
|
number = 5
while number < 50:
number += 1
if number > 8:
print(number)
|
#!/usr/bin/python
# What is the largest prime factor of the number 600851475143
nums = [13195, 600851475143]
def is_prime(num):
if num == 1:
return False
if num % 2 == 0:
return False
for jakaja in range(3,int(num**0.5)+1, 2):
if num % jakaja == 0:
return False
return True
for num in nums:
largest_factor = 0
for factor in range(3,int(num**0.5)+1, 2):
if num % factor == 0:
if is_prime(factor) == True:
largest_factor = factor
print 'Largest factor for num %d is %d' % (num, largest_factor)
|
def rob(nums):
even = sum(nums[1::2])
odd = sum(nums[0::2])
"""
if len(nums) % 2: # odd number of houses
#even = sum([i for i in range(len(nums)) if i % 2 == 1])
even = sum(nums[1::2])
#odd = sum([i for i in nums[:-1] if i % 2])
odd = sum(nums[0::2])
if len(nums) % 2 == 0: # even number of houses
#even = sum([i for i in nums if i % 2 == 0])
even = sum(nums[1::2])
#odd = sum([i for i in nums if i % 2])
odd = sum(nums[0::2])
"""
return even if even > odd else odd
if __name__ == '__main__':
a = [1,2,3,1] #4
b = [1,2,3,4,5] #9
c = [1,4,5,7,9,10]
print(rob(a))
print(rob(b))
print(rob(c))
|
print("Welcome to BMI calculator!")
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
BMI = round(weight/height**2)
a = (f"Your BMI is {BMI}.")
if BMI<=18.5:
print(a, "You are underweight.")
elif BMI<25:
print(a, "You are normal weight.")
elif BMI<30:
print(a, "You are slightly overweight.")
elif BMI<35:
print(a,"You are obese.")
else:
print(a,"You are clinically obese.") |
import numpy as np
from scipy import optimize as opt
from back_propagation import back_propagation
from cost_function import cost_function
from cost_function import unroll_params
from feed_forward import feed_forward
def train(init_params, x, y, y_map, hyper_p=0, iters=100):
""" Trains a Neural Network, compares to the labelled outputs and reports an accuracy. """
result = opt.minimize(cost_function, init_params, args=(x, y_map, hyper_p),
jac=back_propagation, method='TNC', options={'maxiter': iters})
theta1, theta2 = unroll_params(result.x)
prediction = np.argmax(feed_forward([theta1, theta2], x)[1][1], axis=0)
accuracy = np.mean(prediction == y.T) * 100
return accuracy
|
import torch.nn.functional as F
import torch.nn as nn
class BinaryClassifier(nn.Module):
"""
Define a neural network that performs binary classification.
The network should accept your number of features as input, and produce
a single sigmoid value, that can be rounded to a label: 0 or 1, as output.
"""
def __init__(self, input_features, hidden_dim, output_dim):
"""
Initialize the model by setting up linear layers. Use the input parameters to help define the layers of your model.
:param input_features:
the number of input features in your training/test data
:param hidden_dim:
helps define the number of nodes in the hidden layer(s)
:param output_dim:
the number of outputs you want to produce
"""
super(BinaryClassifier, self).__init__()
self.fc1 = nn.Linear(input_features, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, 12)
self.fc3 = nn.Linear(12, output_dim)
self.dropout = nn.Dropout(p=0.25)
self.sig = nn.Sigmoid()
def forward(self, x):
"""
Perform a forward pass of our model on input features, x.
:param x:
A batch of input features of size (batch_size, input_features)
:return:
A single, sigmoid-activated value as output
"""
x = self.dropout(F.relu(self.fc1(x)))
x = self.dropout(F.relu(self.fc2(x)))
x = self.sig(self.fc3(x))
return x
|
# Author: Nick Zwart
# Date: 2013oct18
# Exercise 2:
# Make the port labeled 'in-data' require a 2-D float (64bit) array only.
# Set the output port to only post 1D arrays (modify the algorithm
# accordingly).
#
# Hint: Type-attributes can also be found in the Node Developer's Guide.
# Multi-dimensional arrays can be flattened to 1D see http://www.numpy.org/.
# Don't forget to import numpy. Use a Shapes and Statistics node for testing.
import gpi
import numpy as np
class ExternalNode(gpi.NodeAPI):
"""This is an example node that shows how ports are instantiated,
configured and set.
"""
def initUI(self):
'''This is where UI elements such as widgets and ports are declared.
'''
# Ports
# InPorts have an 'obligation' attribute that determines whether or
# or not they require data in order for the node to execute. By
# default it is set to 'REQUIRED'.
#
# set the: <name>, <type>, <attributes>
self.addInPort('in-data', 'NPYarray', ndim=2, dtype=np.float64, obligation=gpi.OPTIONAL)
self.addOutPort('out-data', 'NPYarray', ndim=1)
def compute(self):
'''This is where the main algorithm should be implemented.
'''
# get data from the port
data = self.getData('in-data')
# if the port is 'OPTIONAL', then check to see
# if data exists before trying to use it.
if data is not None:
# do something with the data
out = data * 2.0
# set the output port, make it 1D
self.setData('out-data', out.flatten())
# Play with this clause. If 'None' is not set, then the second time
# the node is run, the port will change to a yellow color indicating
# that the data have not changed, no downstream event will be triggered.
else:
# don't trigger a downstream event
# -the port will turn red indicating no data present
#self.setData('out-data', None)
pass
return 0 # success
|
import unittest
from src.drink import Drink
class DrinkTest(unittest.TestCase):
def setUp(self):
self.drink1 = Drink("orange juice", 2.50, 0)
self.drink2 = Drink("beer", 6, 2)
def test_drink_has_name(self):
self.assertEqual("orange juice", self.drink1.name)
def test_drink_has_price(self):
self.assertEqual(2.50, self.drink1.price)
def test_alcohol_level_is_2(self):
self.assertEqual(2, self.drink2.alcohol_level) |
from tkinter import *
class LoanCompare:
def __init__(self):
window = Tk()
window.title("Loan Compare")
frame1 = Frame(window)
frame1.pack()
Label(frame1, text = "Loan Amount").pack(side = LEFT)
self.amount = StringVar()
Entry(frame1, textvariable = self.amount, justify = RIGHT).pack(side = LEFT)
Label(frame1, text = "Years").pack(side = LEFT)
self.years = StringVar()
Entry(frame1, textvariable = self.years, justify = RIGHT).pack(side = LEFT)
Button(frame1, text = "Calculate", command = self.processButton).pack(side = LEFT)
self.text = Text(window) # Create and add text to the window
self.text.pack()
self.text.insert(END, format("Interest Rate", "30s") + format("Monthly Payment", "30s") + "Total Payment\n")
self.text.mark_set("table", INSERT)
self.text.mark_gravity("table", LEFT)
window.mainloop()
def processButton(self):
self.text.delete("table", END)
self.text.insert("table", "\n")
for i in range(0, 25):
monthlyPayment = self.getMonthlyPayment(float(self.amount.get()), (.05 + i * 0.0125)/12, int(self.years.get()))
totalPayment = monthlyPayment * 12 * int(self.years.get())
self.text.insert(END, format(5 + i * 0.125, "<30.2f"))
self.text.insert(END, "$" + format(monthlyPayment, "<29.2f"))
self.text.insert(END, "$" +format(totalPayment, "<.2f") + "\n")
return
def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears):
monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
return monthlyPayment
LoanCompare()
|
from tkinter import *
class MouseClicker:
def __init__(self):
window = Tk()
window.title("Mouse Position")
self.canvas = Canvas(window, height = 100, width = 250, bg = "white")
self.canvas.pack()
self.canvas.bind("<Button-1>", self.processMouseEvent)
window.mainloop()
def processMouseEvent(self, event):
self.canvas.delete("location")
self.canvas.create_text(event.x, event.y, text = "(" + str(event.x) + ", " + str(event.y) + ")", tags = "location")
class MouseDragger:
def __init__(self):
window = Tk()
window.title("Mouse Position")
self.canvas = Canvas(window, height = 100, width = 250, bg = "white")
self.canvas.pack()
self.canvas.bind("<Button-1>", self.onMouseClick)
self.canvas.bind("<ButtonRelease-1>", self.onMouseRelease)
window.mainloop()
def onMouseClick(self, event):
self.canvas.create_text(event.x, event.y, text = "(" + str(event.x) + ", " + str(event.y) + ")", tags = "location")
def onMouseRelease(self, event):
self.canvas.delete("location")
MouseDragger()
|
class Rectangle2D:
def __init__(self, x, y, width, height):
self.__x = x
self.__y = y
self.__width = width
self.__height = height
def getX(self):
return self.__x
def setX(self, x):
self.__x = x
def getY(self):
return self.__y
def setY(self, y):
self.__y = y
def getWidth(self):
return self.__width
def setWidth(self, width):
self.__width = width
def getHeight(self):
return self.__height
def setHeight(self, height):
self.__height = height
def getArea(self):
return self.__height * self.__width
def getPerimeter(self):
return 2 * (self.__height + self.__width)
def containsPoint(self, x, y):
xDist = abs(x - self.__x)
yDist = abs(y - self.__y)
return ((xDist < self.__width / 2) and (yDist < self.__height / 2))
def containsRectangle(self, rectangle):
lBound = rectangle.getX() - rectangle.getWidth() / 2
rBound = rectangle.getX() + rectangle.getWidth() / 2
uBound = rectangle.getY() - rectangle.getHeight() / 2
dBound = rectangle.getY() + rectangle.getHeight() / 2
return self.containsPoint(lBound, uBound) and self.containsPoint(rBound, dBound)
def overlaps(self, rectangle):
xDist = abs(self.__x - rectangle.getX())
yDist = abs(self.__y - rectangle.getY())
return xDist < (self.__width + rectangle.getWidth())/2 and yDist < (self.__height + rectangle.getHeight())/2
def __contains__(self, another):
return another.containsRectangle(self)
def __cmp__(self, another):
temp = self.getArea() - another.getArea()
if temp > 0:
return 1
elif temp < 0:
return -1
else:
return 0
def __lt__(self, another):
return self.getArea() < another.getArea()
def __le__(self, another):
return self.getArea() <= another.getArea()
def __eq__(self, another):
return self.getArea() == another.getArea()
def __ne__(self, another):
return self.getArea() != another.getArea()
def __gt__(self, another):
return self.getArea() > another.getArea()
def __ge__(self, another):
return self.getArea() >= another.getArea()
|
"""
This is a class hierarchy of animals.
"""
# classes of vertebrates
class Animal:
def __init__(self, class_name, habitat):
self.class_name = class_name
self.habitat = habitat
def info(self):
print(f'In total, there are 5 classes of vertebrates. It is a {self.class_name}.')
print(f'My habitat is" {self.habitat}.')
class Wild(Animal):
def __init__(self, class_name, habitat, nutrition, height):
super().__init__(class_name, habitat)
self.nutrition = nutrition
self.height = height
def size(self):
if self.height < 10:
print("Small")
else:
print("Big")
class Pet(Animal):
def __init__(self, class_name, habitat, nickname, age):
super().__init__(class_name, habitat)
self.nickname = nickname
self.age = age
def info(self):
print(f'It is a {self.class_name}.')
print(f'I Live in {self.habitat}.')
print(f'My nickname is {self.nickname}.')
print("Age:" + self.age)
class Elephant(Wild, Pet):
def __init__(self, class_name, habitat, nutrition, height, nickname, age):
super().__init__(self, class_name, habitat, nutrition, height, nickname, age)
pass
class Cat(Pet):
def __init__(self, class_name, habitat, nickname, age):
super().__init__(class_name, habitat, nickname, age)
def noise(self):
print("Says: Mew!")
class Dog(Pet):
def __init__(self, class_name, habitat, nickname, age):
super().__init__(class_name, habitat, nickname, age)
def noise(self):
print("Says: Woof!")
def prise(self):
print(f'{self.nickname} is good boy!')
if __name__ == "__main__":
lion = Wild('Mammals', 'Africa', 'predator', 8)
dog = Dog('Mammals', 'home', 'Kos', 1)
cat = Cat('Mammals', 'home', 'Onyx', '5')
print(lion.size())
print(lion.info())
print(dog.info())
print(cat.info())
|
# put your code here.
our_file = open("test.txt")
#our_bigger_file =open("twain.txt")
#pseudo code
#open file
#create a function
#we want the function to take the body of text inside file and counts how many times
#each word occurs separated by spaces
#we need a empty dictionary to store word count
# create for loop for file;
#we need a for loop that iterates thru file
#inside our for loop we need a conditional that checks if word is in dict then +1 if not add 1
def count_words(afile):
our_dict = {}
#sentence = afile.split(" ")
for line in afile:
sentence = line.split()
print sentence
count_words(our_file) |
class TreeMapNode:
__slots__ = 'key', 'val', 'left', 'right'
def __init__(self, key, val=None, left=None, right=None):
self.key = key
self.val = val
self.left = left
self.right = right
def __iter__(self):
if self:
if self.left:
for elem in self.left: yield elem
yield self.key
if self.right:
for elem in self.right: yield elem
class TreeMap:
__slots__ = 'root', 'size'
def __init__(self):
self.root = None
self.size = 0
def __len__(self):
return self.size
def __put(self, key, val, node):
if key == node.key:
node.val = val
elif key < node.key:
if not node.left: node.left = TreeMapNode(key, val)
else: self.__put(key, val, node.left)
else:
if not node.right: node.right = TreeMapNode(key, val)
else: self.__put(key, val, node.right)
def put(self, key, val=None):
if not self.root: self.root = TreeMapNode(key, val)
else: self.__put(key, val, self.root)
self.size += 1
def __setitem__(self, key, val=None):
self.put(key, val)
def __get(self, key, node):
if node == None: return None
elif key == node.key: return node.val
elif key < node.key: return self.__get(key, node.left)
else: return self.__get(key, node.right)
def get(self, key):
if not self.root: raise KeyError(key)
else:
val = self.__get(key, self.root)
if val: return val
else: raise KeyError(key)
def __getitem__(self,key):
return self.get(key)
def __contains__(self,key):
return self.__get(key, self.root)
def __iter__(self):
return self.root.__iter__()
def __str__(self):
if not self.root: return '{}'
result = '{'
for key in self.root:
result += repr(key) + ': ' + repr(self[key]) + ', '
result = result[:-2]
result += '}'
return result
def testTreeMap():
t0 = TreeMap()
print('t0:', t0)
print('t0 size (0):', len(t0))
print('a in t0 (False)?', 'a' in t0)
print()
t1 = TreeMap()
t1['a'] = 1
print('t1:', t1)
print('t1 size (1):', len(t1))
print('t1["a"] (1):', t1['a'])
print('a in t1 (True)?', 'a' in t1)
print('b in t1 (False)?', 'b' in t1)
t1['a'] = 2
print('t1["a"]=2, t1:', t1)
print()
t2 = TreeMap()
for key,val in zip(('c','a','b'), (3, 1, 2)):
t2[key] = val
print('t2:', t2)
print('t2 size (3):', len(t2))
print('t1["c"] (2):', t2['c'])
print('c in t2 (True)?', 'c' in t2)
print('z in t2 (False)?', 'z' in t2)
t2['c'] = 3
print('t2["c"]=3, t2:', t2)
print()
t3 = TreeMap()
for key in ('q','w','e','r','t','y','a','s','d'):
t3[key] = ord(key)
print('t3:', t3)
print('t3 size (9): t3')
print('t3["y"] (121):', t3['y'])
print('t in t3 (True):', 't' in t3)
print('z in t3 (False):', 'z' in t3)
t3['t'] = 99
print('t3["t"]=99, t3:', t3)
if __name__ == '__main__':
testTreeMap() |
__author__ = 'MrBIGL'
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line, how?
# in_file = open(from_file) # open from file
# indata = in_file.read() # reads the data in the from file
# the information up there shortened
indata = open(from_file).read()
print "The input file is %d bytes long" % len(indata) # calculates how many bytes are in the from file
# print "Does the output file exist? %r" % exists(to_file) # checks if the to file exists
# print "Ready, hit RETURN to continue, CTRL-C to abort."
print "Continue with copying?"
raw_input()
out_file = open(to_file, 'w') # opens the outfile in writing mode (to be able to copy to it)_
out_file.write(indata) # copys the data in from file to outfile which is to file openeed in writable mode
print "Alright, all done."
out_file.close() # closes out file
# in_file.close() # closes in file / Commented out because it became irrelevant once it was included in the indata
|
from unittest import TestCase
class BasicTests(TestCase):
status = "Not Testing"
class_status = "Not Constructed"
@classmethod
def setUpClass(cls):
cls.class_status = "Set Up"
def setUp(self):
if self.class_status != "Set Up":
raise Exception("BasicTests was not \'Set Up\'!")
self.status = "Testing"
@classmethod
def tearDownClass(cls):
cls.class_status = "Torn Down"
def tearDown(self):
self.status = "Not Testing"
def test_setUp_runs_at_start(self):
"""
BasicTests is "Testing" while running unit tests
"""
self.assertEqual(self.status, "Testing")
|
"""Database Functions
The functions that interacts with replit's builtin database named "db".
"""
from replit import db
def insert_testcase(uid, typ, idx, name, tc_in, tc_out):
"""Inserts the test case into the database.
Parameters
uid : int
The unique identification number of the test case
typ : str
Can either be "LE", "PA", or "MP" and tells the type of problem
idx : int
The problem number. It should be typecasted to str (for some reason related sa db)
name : str
The label / description for the inserted test case
tc_in, tc_out : str
Contains information on the test cases
"""
idx = str(idx)
if typ not in db.keys():
print(f"ADDING {typ} TO DB")
db[typ] = dict()
temp_db = db[typ]
if idx not in temp_db.keys():
print(f"ADDING {idx} to {typ}")
temp_db[idx] = [[name, tc_in, tc_out, uid]]
db[uid] = (typ, idx)
db[typ] = temp_db
temp_db = db[typ]
if idx not in temp_db.keys():
print(f"SHIIIIIIIIT. Database cannot insert {uid} {typ} {idx} {name}.")
else:
print("NICEEEEEEEEEEE. Testcase successfully inserted!")
else:
temp_db = db[typ]
temp_db[idx].append([name, tc_in, tc_out, uid])
db[uid] = (typ, idx)
db[typ] = temp_db
def erase_db():
keys = [*db.keys()]
for x in keys:
del db[x]
def get_all(typ, idx):
idx = str(idx)
if typ not in db.keys():
print(f"NO TYP {typ} in DB")
return []
temp_db = db[typ]
if idx not in temp_db.keys():
print(f"NO IDX {idx} in {typ}")
return []
return temp_db[idx]
def get_id():
if "id" not in db.keys():
db["id"] = 0
res = db["id"]
db["id"] += 1
return res
def delete_entry(uid):
print(*db.keys())
try:
typ, idx = db[uid]
print(f"AT {typ}{idx}")
for i in range(len(db[typ][idx])):
if db[typ][idx][i][3] == uid:
temp_db = db[typ]
del temp_db[idx][i]
db[typ] = temp_db
del db[uid]
return True
except Exception:
print(f"Can't find {uid} in UID Database")
found = False
for typ in ['LE', 'PA']:
for idx in range(9):
if typ not in db.keys():
continue
temp_db = db[typ]
if str(idx) not in temp_db:
continue
print(typ, idx, temp_db[str(idx)])
print(type(uid))
for i in range(len(temp_db[str(idx)])):
x = temp_db[str(idx)][i]
if x[3] == uid:
del temp_db[str(idx)][i]
found = True
if found:
db[typ] = temp_db
return True
return False
return False
def get_entry(uid):
try:
typ, idx = db[uid]
except Exception:
print(f"Test case with UID {uid} has no typ or idx.")
return
try:
temp_db = db[typ]
for x in temp_db[idx]:
if x[3] == uid:
io = x
break
return typ, idx, io
except Exception:
print(f"Cannot access problem {uid} but it exists.")
return
def delete_row(typ, idx):
try:
temp_db = db[typ]
for x in temp_db[idx]:
del db[x[3]]
del temp_db[idx]
db[db] = temp_db
except Exception:
raise IndexError
|
# Sebastian Raschka, 03/2014
# Date and Time in Python
import time
# print time HOURS:MINUTES:SECONDS
# e.g., '10:50:58'
print(time.strftime("%H:%M:%S"))
# print current date DAY:MONTH:YEAR
# e.g., '06/03/2014'
print(time.strftime("%d/%m/%Y"))
|
# Sebastian Raschka, 03/2014
# Getting the positions of min and max values in a list
import operator
values = [1, 2, 3, 4, 5]
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))
print('min_index:', min_index, 'min_value:', min_value)
print('max_index:', max_index, 'max_value:', max_value)
|
from sympy import diff,symbols,hessian,poly,matrix2numpy,eye
from numpy import matrix,squeeze,asarray
from numpy.linalg import inv
global epsilon
epsilon = 1E-5
def fValue(f,x0,X):
"""
Description : Returns the value of the function f evaluated at point x0
Parameters:
1. f : symbolic representation of the function to be minimized
2. x0 : list of independant variables for the function
3. X : symbolic list of the dependant variables in the function f
Output:
gradient vector as numpy matrix
"""
length = range(0,len(x0))
return f.subs([(X[i],x0[i]) for i in length])
def gradValue(gradF,x0,X):
"""
Description : Returns the value of the gradient of the function evaluated as point x0
Parameters:
1. gradF : symbolic list of gradient coefficients
2. x0 : list of independant variables for the function
3. X : symbolic list of the dependant variables in the function f
Output:
gradient vector as numpy matrix
"""
length = range(0,len(x0))
gradAsList = [gradF[j].subs( [ (X[i],x0[i]) for i in length] ) for j in length]
return matrix(gradAsList,'float')
def hessianValue(Q,x0,X):
"""
Description : Calculates the Value of the Hessian of a function at a specified point
Parameters:
1. Q : symbolic representation of the Hessian Matrix
2. x0 : list of independant variables for the function
3. X : symbolic list of the dependant variables in the function f
Output:
gradient vector as numpy matrix
"""
lQ = range(0,len(Q))
lX = range(0,len(x0))
a = matrix([ Q[j].subs( [ ( X[i],x0[i] ) for i in lX ] ) for j in lQ],'float')
return matrix(a.reshape(len(Q)**0.5,len(Q)**0.5))
def sDescent(f,x0,X):
"""
Description : Returns the minimizer using the Steepest Descent Algorithm
Parameters:
1. f : symbolic representation of the function to be minimized
2. x0 : list of independant variables for the function
3. X : symbolic list of the dependant variables in the function f
Output:
Prints the minimizer of the function f to terminal
"""
def stepSizeSteepestDescent(f,x0,g0):
"""
Description : Calculates the minimized step size for the steepest descent algorithm using Newton's 1D method
Parameters:
1. f : symbolic symbolic representation of the function f
2. x0 : list of independant variables for the function
3. g0 : gradient value at point x0 as a numpy matrix
Output:
gradient vector as numpy matrix
"""
phi,alpha = symbols('phi alpha')
Q = hessian(f,X)
if (poly(f).is_quadratic):
return float(g0*g0.transpose()/matrix2numpy(g0*Q*g0.transpose()))
else:
xStar = x0 - squeeze(asarray(alpha*g0))
def alphaValue(phi,a0): return phi.subs([(alpha,a0)])
a0 = 0.
phi = fValue(f,xStar)
while (True):
a = a0
a0 = a0 - alphaValue(diff(phi,alpha),a0)/alphaValue(diff(diff(phi,alpha),alpha),a0)
if (abs(a-a0)<epsilon): return a0
gradF=[f.diff(x) for x in X]
while(True):
g0 = gradValue(gradF,x0,X)
x = x0
step = stepSizeSteepestDescent(f,x0,g0)
x0 = [float(i) for i in (x0 - squeeze(asarray(step *g0)))]
g0 = gradValue(gradF,x0,X)
if(abs(fValue(f,x0,X) - fValue(f,x,X))< epsilon):
print "\n+++++++++++++++++++++++++++++STEEPEST DESCENT METHOD+++++++++++++++++++++++++++++"
print "\nThe minimizer of the function\n\nf = %s \nis at \nx = %s" %(f,x0)
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
return 0
def conjugateGradient(f,x0,X):
"""
Description : Returns the minimizer using the Conjugate Gradient Algorithm (as a Direct Method)
Parameters:
1. f : symbolic representation of the function to be minimized
2. x0 : list of independant variables for the function
3. X : symbolic list of the dependant variables in the function f
Output:
Prints the minimizer of the function f to terminal
"""
def printFunction(f,x0):
"""
Description : Prints the minimizer of the function on the screen
Inputs:
f = symbolic representation of the function to be minimized
x0 = Initial guess of the minimizer
"""
print "\n+++++++++++++++++++++++++++++CONJUGATE GRADIENT METHOD+++++++++++++++++++++++++++++"
print "\nThe minimizer of the function\n\nf = %s \nis at \nx = %s" %(f,x0)
print "+++++++++++++++++++++++++++++++++++++++++++++++++=============+++++++++++++++++++++++\n"
return 0
gradF = [f.diff(x) for x in X]
g0 = gradValue(gradF,x0,X)
if(all(abs(i) < epsilon for i in squeeze(asarray(g0,'float')))): return printFunction(f,x0)
Q = matrix2numpy(hessian(f,X))
d0 = -g0
while(True):
alpha = -squeeze(asarray(g0*d0.transpose()))/squeeze(asarray(d0*Q*d0.transpose()))
x0 = [float(i) for i in (x0 + squeeze(asarray(alpha *d0)))]
g0 = gradValue(gradF,x0,X)
if(all(abs(i) < epsilon for i in squeeze(asarray(g0,'float')))): return printFunction(f,x0)
beta = float(squeeze(asarray(g0*Q*d0.transpose())/squeeze(asarray(d0*Q*d0.transpose()))))
d0 = -g0 +beta*d0
def newton(f,x0,X):
"""
Description : Returns the minimizer using Newton's Algorithm
Inputs:
f = symbolic representation of the function to be minimized
x0 = Initial guess of the minimizer
X = list of the function's dependant variables
Outputs:
Displays the minimizer on the screen
"""
def printFunction(f,x0):
"""
Description : Prints the minimizer of the function on the screen
Inputs:
f = symbolic representation of the function to be minimized
x0 = Initial guess of the minimizer
"""
print "\n+++++++++++++++++++++++++++++NEWTONS METHOD+++++++++++++++++++++++++++++"
print "\nThe minimizer of the function\n\nf = %s \nis at \nx = %s\n\nThe value of f is \nf(x) = %f\n "%(f,x0,fValue(f,x0,X))
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
return 0
gradF = [f.diff(x) for x in X]
hessianF = hessian(f,X)
while(True):
g0 = gradValue(gradF,x0,X)
if(all(abs(i) < epsilon for i in squeeze(asarray(g0,'float')))): return printFunction(f,x0)
F0 = hessianValue(hessianF,x0,X)
x0 = x0 - squeeze(asarray((inv(F0)*g0.transpose()).transpose()))
|
# on 2D array with 0 and 1 return array of sizes of all connected 1s,
# where connection is up/down left/right, but not diagonal
# [[1,0,0,1,0]
# [1,0,1,1,0]] => [2,3]
# O(rc) time | O(rc) space
def riverSize(matrix):
size = []
visited = [[False for value in row] for row in matrix] # 2D with all false
for i in range(len(matrix)) :
for j in range(len(matrix[i])) :
if visited[i][j] : continue
# TODO
#dfs or bfs, both works
return size
# in: [12, 3, 1, 2, -6, 5, -8, 6], 0
# out: [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
# # O(n^2) time | O(n) space
def threeNumSum(array, targetSum) :
s_array = sorted(array) # [-8, -6, 1, 2, 3, 5, 6, 12]
triplets = []
length = len(s_array)
for tmp_idx in range(length - 2) :# as we are looking for triplets
left_idx = tmp_idx + 1 # 2nd num in triplet : from current + 1
right_idx = length - 1 # 3rd num in triplet : from end
while left_idx < right_idx :
n1, n2, n3 = s_array[tmp_idx], s_array[left_idx], s_array[right_idx] # n1 could be before the while loop
tmp_sum = n1 + n2 + n3
if tmp_sum == targetSum :
triplets.append([n1, n2, n3])
left_idx += 1
right_idx -= 1
elif tmp_sum < targetSum : left_idx += 1
elif tmp_sum > targetSum : right_idx -= 1
return triplets
print(str(threeNumSum([12, 3, 1, 2, -6, 5, -8, 6], 0)))
# [-1, 5, 10, 20, 28, 3], [26, 134, 135, 15, 17] => [28, 26]
# O(nlog(n) + mlon(m)) time | O(1) space
def smallestDifference(array1, array2):
s_array1, s_array2 = sorted(array1), sorted(array2) # array1.sort(),
len_1, len_2 = len(s_array1), len(s_array2)
idx_1, idx_2 = 0, 0
smallest, current = float("inf"), float("inf")
result = []
while idx_1 < len_1 and idx_2 < len_2:
first_num = s_array1[idx_1]
second_num = s_array2[idx_2]
if first_num < second_num:
current = second_num - first_num
idx_1 += 1
elif second_num < first_num:
current = first_num - second_num
idx_2 += 1
else:
return [first_num, second_num]
if smallest > current:
smallest = current
result = [first_num, second_num]
return result
print(str(smallestDifference([-1, 5, 10, 20, 28, 3], [26, 134, 135, 15, 17])))
# O(n) time | O(n) space
def in_order_traverse(tree, array):
if tree is not None:
in_order_traverse(tree.left, array)
array.append(tree.value)
in_order_traverse(tree.right, array)
return array
# O(n) time | O(n) space
def pre_order_traverse(tree, array):
if tree is not None:
array.append(tree.value)
pre_order_traverse(tree.left, array)
pre_order_traverse(tree.right, array)
return array
# O(n) time | O(n) space
def post_order_traverse(tree, array):
if tree is not None:
post_order_traverse(tree.left, array)
post_order_traverse(tree.right, array)
array.append(tree.value)
return array
# O(n) time | O(n) space
def invert_binary_tree_iterative(tree):
queue = [tree] # root node
while len(queue):
current = queue.pop(0)
if current is None: continue
swap_left_and_right(current)
queue.append(current.left)
queue.append(current.right)
# O(n) time | O(d) space , here d = depth of the tree
def invert_binary_tree_rec(tree):
if tree is None: return
swap_left_and_right(tree)
invert_binary_tree_rec(tree.left)
invert_binary_tree_rec(tree.right)
def swap_left_and_right(tree):
tree.left, tree.right = tree.right, tree.left
# [75, 105, 120, 75, 90, 135] => 330 (75, 120, 135)
# O(n) time | O(n) space
def maxSumNonAdjacent(array):
if not len(array): return 0
if len(array) == 1: return array[0]
max_sums = [0 for i in array]
max_sums[0] = array[0]
max_sums[1] = max(array[0], array[1])
for i in range(2, len(array)): # start fromm index=2
max_sums[i] = max(max_sums[i-1], max_sums[i-2] + array[i])
return max_sums[len(array) - 1]
print(str(maxSumNonAdjacent([75, 105, 120, 75, 90, 135])))
# maximum sum that can be obtained by summing up all the numbers in a non-empty
# subarray of the input array. A subarray must only contain adjacent numbers
# input: [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]
# output: 19 ([1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1])
# O(n) time | O(1) space - where n is the length of the input array
def kadaneAlgorithm(array):
tmpsum = array[0]
maxsum = array[0]
for i in range(1, len(array)):
tmpsum = max(array[i], tmpsum + array[i])
maxsum = max(tmpsum, maxsum)
return maxsum
print(str(kadaneAlgorithm([3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4])))
class MinMaxStack:
# O(1) time | O(1) space
# for all methods
def __init__(self):
self.minmaxstack = []
self.stack = []
def peek(self):
return self.stack[len(self.stack) -1]
def pop(self):
self.minmaxstack.pop()
return self.stack.pop()
def push(self, number):
minmax = {"min": number, "max": number}
if len(self.minmaxstack): # if not empty
lastminmax = self.minmaxstack[len(self.minmaxstack) - 1]
minmax["min"] = min(lastminmax["min"], number)
minmax["max"] = max(lastminmax["max"], number)
self.minmaxstack.append(minmax)
self.stack.append(number)
def getMin(self):
return self.minmaxstack[len(self.minmaxstack) - 1]["min"]
def getMax(self):
return self.minmaxstack[len(self.minmaxstack) - 1]["max"]
# TODO
# def moveElementToEnd
# def singleCycleCheck
# def BFS
# def youngestCommonAncestor(root, node1, node2):
# compare node1 and node2, get the lower in hierarchy, then go up until finding one that is higher than the other
|
class Solution(object):
def findRepeatNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)):
while i != nums[i]:
temp = nums[i]
# 似乎不能用:nums[i], nums[nums[i]] = nums[nums[i]], nums[i] 因为交换过程中nums[i]变了
nums[i] = nums[temp]
nums[temp] = temp
if nums[temp] == temp:
return temp
if __name__ == '__main__':
solution = Solution()
result = solution.findRepeatNumber([2, 3, 1, 0, 2, 5, 3])
print(result)
|
a = 5
b = 3
print(f"{a} + {b} = {a+b}")
print(f"{a} - {b} = {a-b}")
print(f"{a} * {b} = {a*b}")
print(f"{a} / {b} = {a/b}")
print(f"{a} % {b} = {a%b}")
print(f"{a} ** {b} = {a**b}")
print(f"{a} // {b} = {a//b}")
|
import unittest
from app.models import Review,User
from app import db
class MovieTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Movie class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.user_Mugera = User(username = 'Mugera',password = 'chicken', email = '[email protected]')
self.new_review = Review(movie_id=12345,movie_title='Review for movies',image_path="https://image.tmdb.org/t/p/w500/jdjdjdjn",movie_review='This movie is the best thing since sliced bread',user = self.user_Mugera )
# self.new_movie = Movie(1234,'Python Must Be Crazy','A thrilling new Python Series','/khsjha27hbs',8.5,129993)
def tearDown(self):
Review.query.delete()
User.query.delete()
# We then check if the values of variables are correctly being placed.
def test_check_instance_variables(self):
self.assertEquals(self.new_review.movie_id,12345)
self.assertEquals(self.new_review.movie_title,'Review for movies')
self.assertEquals(self.new_review.image_path,"https://image.tmdb.org/t/p/w500/jdjdjdjn")
self.assertEquals(self.new_review.movie_review,'This movie is the best thing since sliced bread')
self.assertEquals(self.new_review.user,self.user_Mugera)
# We then create a test for our save review method. We also query the database to confirm that we actually have data saved.
def test_save_review(self):
self.new_review.save_review()
self.assertTrue(len(Review.query.all())>0)
#We then test the get_reviews class method that we pass in the id of a movie and get a response which is a review for that movie.
def test_get_review_by_id(self):
self.new_review.save_review()
got_reviews = Review.get_reviews(12345)
self.assertTrue(len(got_reviews) == 1)
|
# Time Complexity :
# Space Complexity :
# Did this code successfully run on Leetcode :
# Any problem you faced while coding this :
# Your code here along with comments explaining your approach
class linkedListNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.next = None
class MyHashMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashMap = [None for _ in range(1000)]
def put(self, key: int, value: int) -> None:
"""
value will always be non-negative.
"""
hIndex = key//1000
if self.hashMap[hIndex] is None:
self.hashMap[hIndex] = linkedListNode(key, value)
else:
curr = self.hashMap[hIndex]
while curr.next is not None:
curr = curr.next
curr.next = linkedListNode(key, value)
def get(self, key: int) -> int:
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
"""
hIndex = key//1000
curr = self.getPrev(self.hashMap[hIndex], key)
if curr.next is None:
return -1
else:
return curr.next.value
def remove(self, key: int) -> None:
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
"""
curr = self.getPrev(self.hashMap[hIndex], key)
if curr.next is not None:
curr.next = curr.next.next
def getPrev(self, node, key):
prev = None
while node.key != key and node.next is not None:
prev = node
node = node.next
return prev
# Your MyHashMap object will be instantiated and called as such:
key, value = 10023, 65461
obj = MyHashMap()
obj.put(key,value)
param_2 = obj.get(key)
print(param_2)
obj.remove(key) |
import sys
def binary_search(start,end,array):
if end<start:
return False
mid=(start+end)//2
if array[mid]==mid:
return mid
elif array[mid]<mid:
return binary_search(mid+1,end,array)
else:
return binary_search(start,mid-1,array)
n=int(input())
array=list(map(int,sys.stdin.readline().split()))
result=binary_search(0,n-1,array)
if result:
print(result)
else:
print(-1)
|
def solution(s):
answer=''
if s[0].isalpha():
answer+=s[0].upper()
else:
answer+=s[0]
for i in range(1,len(s)):
if s[i].isalpha() and s[i-1]==' ':
answer+=s[i].upper()
elif s[i].isalpha() and s[i-1]!=' ':
answer+=s[i].lower()
else:
answer+=s[i]
return answer
|
from itertools import permutations
n = int(input())
numbers = [x for x in range(1,n+1)]
candidates = list(permutations(numbers, n))
candidates.sort()
for value in candidates:
for idx in range(n):
print(value[idx],end = ' ')
print()
|
while True:
try:
sentence = input()
if sentence == '':
break
lower, upper, number, blank = (0, 0, 0, 0) #순서대로 소문자 대문자 숫자 공백
for string in sentence:
if string.islower():
lower += 1
elif string.isupper():
upper += 1
elif string.isdigit():
number += 1
elif string == ' ':
blank += 1
print(lower, upper, number, blank)
except EOFError:
break
|
number=list(map(int,input()))
if len(number)==1:
print(number[0])
else:
result=0
if 0 in number[:2] or 1 in number[:2]:
result=number[0]+number[1]
else:
result=number[0]*number[1]
for i in range(2,len(number)):
if number[i]<=1:
result+=number[i]
else:
result*=number[i]
print(result)
|
def repeatedString(s, n):
if len(s)==1:
if s[0]=='a':
return n
else:
return 0
else:
count=s.count('a')*(n//len(s))
if n%len(s)==0:
return count
else:
count+=s[:n%len(s)].count('a')
return count
|
import sys
input = sys.stdin.readline
prime_numbers = set()
for number in range(2,(2*123456)+1):
check = True
for target in range(2,int(number**(1/2))+1):
if number % target == 0:
check = False
break
if check:
prime_numbers.add(number)
def count_decimal(n):
count = 0
for num in range(n+1,(2*n)+1):
if num in prime_numbers:
count += 1
return count
while True:
n = int(input())
if not n:
break
print(count_decimal(n))
|
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
parent_a = find_parent(parent, a)
parent_b = find_parent(parent, b)
if parent_a < parent_b:
parent[parent_a] = parent_b
else:
parent[parent_b] = parent_a
n, m = map(int, input().split())
parent = [number for number in range(n+1)]
for _ in range(m):
operator, a, b = map(int, input().split())
if operator == 0:
union_parent(parent, a, b)
else:
if find_parent(parent, a) == find_parent(parent, b):
print("YES")
else:
print("NO")
|
from itertools import combinations
def solution(nums):
answer = 0
combi = list(combinations(nums,3))
for value in combi:
current = sum(value)
check = True
for num in range(2,int(current**(1/2))+1):
if current % num == 0:
check = False
break
if check:
answer += 1
return answer
|
'''여기서 핵심은 answer.sort(key=lamba x: x*3,reverse=True)라고 생각한다.
가장 이해가 안가는 부분이기도 하고....
일단 key를 사용하면 정렬할 기준을 설정할 수 있다고 한다.
예를 들어 여러 단어들이 담긴 리스트가 있다고 가정했을 때 만약 단어의 길이를 기준으로
리스트를 정렬하고 싶다면, list.sort(key=lambda x:len(x) 처럼 작성해야한다.
즉 이 문제에서는 x*3을 기준으로 정렬하기로 한거고, x*3인 이유는 문제 조건에서
numbers의 원소가 1000이하의 숫자라고 했기 때문이다.
이렇게 정렬한 것을 다시 reverse=True를 하는 이유는 올림차순 된 것을 내림차순으로
바꿔야 가장 큰 수가 되기 때문이다.
그렇게 해서 answer에 리턴되는 것은 key에 따라 정렬되고, 다시 그 정렬된 것이
내림차순으로 정리된 numbers의 원소들인 것이다.
'''
def solution(numbers):
answer = list(map(str,numbers))
answer.sort(key=lambda x: x*3,reverse=True)
return str(int(''.join(answer)))
|
#!/usr/bin/python
import MySQLdb
# Function for connecting to the MySQL database
def mySQLConnect():
try:
# Open the database connection
conn = MySQLdb.connect("localhost", "root", "myPassword", "CSR")
print("A MySQL connection has been opened!")
return conn
except MySQLdb.Error as err:
print("Error while connecting to the MySQL database!", err)
return 0
# Function to test if the database connection works as intended
def testSQLConnection(conn):
# Make a Cursor object for query execution
cursor = conn.cursor()
# Execute SQL query
cursor.execute("SELECT * FROM Profile")
# Fetch all of the data from the previously executed query
profileData = cursor.fetchall()
# Find the total number of rows in the Profile table
cursor.execute("SELECT COUNT(*) FROM Profile")
profileRows = cursor.fetchone()
# Find the total number of columns in the Profile table
cursor.execute("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = 'CSR' AND table_name = 'Profile'")
profileColumns = cursor.fetchone()
''' Print contents of the Profile table '''
i = 0
j = 0
for i in range(profileRows[0]):
print('Row', i)
for j in range(profileColumns[0]):
print('profileData(', i, j, '): ', profileData[i][j])
def mySQLDisconnect(conn):
# Close the database connection
conn.close()
print("The MySQL connection is closed!")
''' Script starts here '''
# Connect to the MySQL database
myConnection = mySQLConnect()
# Test the connection
testSQLConnection(myConnection)
# Call the search function
import search
# Disconnect from the MySQL database
mySQLDisconnect(myConnection)
|
#aumento salarial conforme valor do salário
salario = float(input('Digite o valor do salário: R$'))
if salario > 1250.00:
aumento = (salario * 0.1) + salario
print('O valor do salário com aumento é: R${:.2f}'.format(aumento))
else:
aumento = (salario * 0.15) + salario
print('O valor do salário com aumento é: R${:.2f}'.format(aumento)) |
#multa acima do limite de velocidade
velocidade = float(input('Digite a velocidade do veículo: ')) #solicita a velocidade do veículo pelo usuário
#caso a velocidade seja superior ao permitido calcula a multa para o usuário
if velocidade > 80:
multa = (velocidade - 80) * 7.00
print('Você estava dirigindo a {}km/h você foi multado em R${:.2f}'.format(velocidade, multa))
#caso contrário printa mensagem de ba viagem
else:
print('Boa viagem! Dirija com segurança!') |
#aprovação de empréstimo para imóvel
valor = float(input('Valor do imóvel: R$ '))
salario = float(input('Valor do salário do comprador: R$ '))
periodo = int(input('Quantos anos vai pagar: '))
prestacao = valor / (periodo * 12)
print('Empréstimo de R${:.2f} em {} pestações o valor da prestação fica R${:.2f}'.format(valor, periodo, prestacao))
if prestacao <= (salario * 0.30):
print('Empréstimo APROVADO')
else:
print('Empréstimo NEGADO')
|
#converter ºC em ºF
temperatura = float(input('Digite uma temperatura em ºC:'))
fahrenheit = (temperatura * 9 / 5) + 32
print('A temperatura é {}ºF'.format(fahrenheit)) |
#mostrar o primeiro e ultimo nome
nome = str(input('Digite seu nome completo: ')).strip()
novo = nome.split()
print('Primeiro nome: {}'.format(novo[0]))
print('Último nome: {}'.format(novo[-1])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.