text
stringlengths 37
1.41M
|
---|
# Open a frame
###################################################
# Open frame
# Student should add code where relevant to the following.
import simplegui
message = "My second frame!"
# Handler for mouse click
def click():
print message
frame = simplegui.create_frame("My secode frame", 100, 200)
# Assign callbacks to event handlers
frame.add_button("Click me", click)
# Start the frame animation
frame.start()
|
import cards_tools
while True:
cards_tools.cards_menu()
action = input("请选择希望执行的操作:")
print("您选择的操作是【%s】" % action)
# 1,2,3 针对名片的操作
if action in ["1", "2", "3"]:
# 根据用户输入决定后续的操作
if action == "1":
cards_tools.add_card()
elif action == "2":
cards_tools.show_all()
elif action == "3":
cards_tools.search_card()
# 0 退出系统
elif action == "0":
print("欢迎再次使用名片管理系统。")
break
# 其他内容输入错误,需要提示用户
else:
print("您输入的不正确,请重新选择。")
|
# Bubble sort is the basic sorting algorithm to sort array elements. It compares the pair of adjacent elements from an array. If the order is wrong, it just swaps the element.
# If there are n-elements in the array, it iterates loop n times. In each iteration, one element is placed in the order at the end of the array.
def bubble_sort(list_a):
indexing_length = len(list_a) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, indexing_length):
if list_a[i] > list_a[i + 1]:
sorted = False
list_a[i], list_a[i + 1] = list_a[i + 1], list_a[i]
return list_a
print(bubble_sort([4,6,8,3,2,5,7,8,9]))
# Selection sort is another comparison sort algorithm that compares a single element with all the other elements from the list. It is not efficient on large lists and is used as a part of complicated algorithms. It is similar to insertion sort but uses fewer swaps. So, it is useful for those programs where swaps are expensive.
# Algorithm- Step by step procedure
# Step 1: Take the first element of the list
# Step 2: Compare the first element with all other elements in the list.
# Step 3: While comparing if any element is smaller than the selected element (ascending order), then these two are swapped.
# Step 4: Repeat the same process with all the positions in the list until the entire list is sorted.
def selection_sort(list_a):
indexing_length = range(0, len(list_a) - 1)
for i in indexing_length:
min_value = i
for j in range(i + 1, len(list_a)):
if list_a[j] < list_a[min_value]:
min_value = j
if min_value != i:
list_a[min_value], list_a[i] = list_a[i], list_a[min_value]
return list_a
print(selection_sort([7,8,9,8,7,6,5,6,7,8,9,0]))
# Heap sort is an advanced and efficient version of the selection sort algorithm. It works similarly by sorting the elements in the ascending or descending order by comparing but this is done by using a data structure called heap, which is a special tree base structure. Heap has the following properties:
# It is a complete tree
# Root has a greater value than any other element in the subtree
# Algorithm- Step by step procedure:
# Step 1: Form a heap from the given data
# Step 2: Remove the largest item from the heap
# Step 3: From the remaining data reform the heap
# Step 4: Repeat step 2 and 3 until all the data is over
# Insertion is the most basic sorting algorithm which works quickly on small and sorted lists. It takes elements one by one from the list and inserts them in the correct order in the new sorted list. Shellsort is another type of insertion sort which is more useful for larger lists.
# In the insertion sort algorithm, every step moves an element from the unsorted section to sorted section until all the elements are sorted in the list.
# Algorithm- Step by step procedure:
# Step 1: Assume that first element in the list is in the sorted section of the list and remaining all elements are in the unsorted section.
# Step 2: Consider the first element from the unsorted list and insert that element into the sorted list in the order specified (ascending or descending)
# Step 3: Repeat the above steps until all the elements from the unsorted list are moved to the sorted list
def insertion_sort(list_a):
indexing_length = range(1, len(list_a))
for i in indexing_length:
value_to_sort = list_a[i]
while list_a[i - 1] > value_to_sort and i > 0:
list_a[i], list_a[i-1] = list_a[i-1], list_a[i]
i = i -1
return list_a
print(insertion_sort([7,8,9,8,7,6,5,6,7,8,9,8,7,6,5,6,7,8,4,1]))
# Merge sort algorithm compares two elements of the list and then swaps them in the order required (ascending or descending). It applies the divide and rule concept. Merge sort works on sequential access and can work on large lists. This algorithm is popularly used in practical programming as it is used in the sophisticated algorithm Timsort. Timsort is used for standard sorting in languages such as Python and Jana. Merge sort algorithm is itself a standard routine in Perl.
# Algorithm- Step by step procedure:
# Step 1: Divide the list recursively into two or more sub-problems until it can no more be divided
# Step 2: Solve the sub-problems until it is reached to the base case
# Step 2: Merge the smaller lists into the new list in sorted order
# Quicksort is similar to merge sort which uses divide and conquers technique. Thus it is a recursive algorithm. But quicksort performs in a little different manner than mergesort does. In merge sort, the work does not happen in the division stage but it happens in the combined stage. But in quicksort it is totally opposite, everything happens in the division stage.
# Algorithm- Step by step process:
# Step 1: Divide the list by any chosen element and call it a Pivot element. Rearrange the elements, all the elements that are less than equal to the pivot element must be in left and larger ones on the right. This procedure is called Partitioning.
# Step 2: Conquer which mean recursively ordering the subarrays
# Step 3: There is nothing left in the combined stage as the conquer stage organizes everything. The smaller or equal elements to the pivot are organized at the left side and larger elements are organized at the right.
|
import csv
def transform_user_details(csv_file_name):
new_user_data = []
with open("user_details.csv", newline='') as csvfile:
user_details = csv.reader(csvfile, delimiter=",")
for user in user_details:
new_user_data.append(user)
return new_user_data
def create_new_user_data_csv(old_user_data_file,new_file_name):
new_user_data = transform_user_details(old_user_data_file)
new_file = open(new_file_name, "w")
with new_file:
csv_writer = csv.writer(new_file)
csv_writer.writerpws(new_user_data)
test_csv = transform_user_details("user_details.csv")
print(test_csv)
# create_new_user_data_csv("")
|
'''
1. 质数是只能被1和它本身整出的数,编程找出100以内全部的质数。
2. 斐波那契数列是两个1构成,从第三项开始,每一项是由前面两项的和构成,如下:1,1,2,3,5...
请通过编程得到数列的前100项,并输出99项与100项的比值。
'''
def zs(fw):
fw += 1
for i in range(2,fw):
#对于从2到fw之间的数,每个数都拿来除以从2到它自身一半(i/2)的所有数,看是否能被整除;
for k in range(2,int(fw/2)):
if i%k == 0:break
#如果2-100之间的某个数,除了1 和它本身之外,没有其他可以整除的数,则是质数
if k > int(i/2):
print(i)
print('100以内全部的质数:')
zs(100)
def fblq(len):
index0 = 1
index1 = 1
index2 = 0
index99 = 0;
index100 = 0;
for o in range(1,len):
index2 = index0 + index1
index0 = index1
index1 = index2
print(index2)
if(o == 99):
index99 = index2
if(o == 100):
index100 = index2
print("99项与100项")
print(index99/index100)
print('100斐波那契数:')
fblq(101)
|
from api.engine import Tokenizer, Languages
"""
The language detector should identify the language of the text for all the supported languages.
For other languages it should return the label OTHER
"""
def test_english_language_detector():
text = 'This language is english.'
ld = Tokenizer(Languages.ENGLISH)
assert ld.detect_language(text) == 'en'
def test_spanish_language_detector():
text = 'Este texto está en español.'
ld = Tokenizer(Languages.ENGLISH)
assert ld.detect_language(text) == 'es'
def test_portuguese_language_detector():
text = 'Este texto esta em portugues.'
ld = Tokenizer(Languages.ENGLISH)
assert ld.detect_language(text) == 'pt'
def test_french_language_detector():
text = 'Ce texte est en français.'
ld = Tokenizer(Languages.ENGLISH)
assert ld.detect_language(text) == 'fr'
def test_unknown_language_detector():
text = 'Этот текст на русском'
ld = Tokenizer(Languages.ENGLISH)
assert ld.detect_language(text) == 'ru'
text = 'Das Essen im Hotel hat ihm sehr gut geschmeckt.'
ld = Tokenizer(Languages.ENGLISH)
assert ld.detect_language(text) == 'de'
|
def is_Chinese(uchar):
"""
check whether the unicode is a Chinese character
"""
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
return True
else:
return False
def contain_Chinese(word):
"""
check whether the word contains Chinese character
"""
for uchar in word:
if is_Chinese(uchar):
return True
return False
|
from collections import Counter
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
char_counter = Counter(chars)
res = 0
for w in words:
word_counter = Counter(w)
ok = True
for c, v in word_counter.items():
if c not in char_counter or v > char_counter[c]:
ok = False
break
if ok:
res += len(w)
return res
|
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return
m, n = len(board), len(board[0])
def bfs(x, y):
nonlocal board
visit = [(x, y)]
while visit:
new = list()
for cx, cy in visit:
board[cx][cy] = 'V'
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
nx, ny = cx + dx, cy + dy
if 0 <= nx < m and 0 <= ny < n and board[nx][ny] == 'O':
board[nx][ny] = 'V'
new.append((nx, ny))
visit = new
for i in range(m):
for j in range(n):
if (i == 0 or i == m - 1 or j == 0 or j == n - 1) and board[i][j] == 'O':
bfs(i, j)
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == 'V':
board[i][j] = 'O'
|
# Default shell for a Python 3.x program
# Copy this and rename it to write your own code
#
__author__ = 'Ethan Richards'
# CIS 125
# Fahrenheit-to-Celcius
# Converts a number from Fahrenheit to Celcius.
def main():
F = eval(input("Input a temperature in Fahrenheit:"))
C = (F-32) * (5/9)
print("{} in Fahrenheit is {:.1f} in Celcius.".format(F,C))
main()
|
def encrypt_caesar(plaintext: str) -> str:
"""
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
''
"""
i = 0
ciphertext = ""
while i < len(plaintext):
if 'a' <= plaintext[i] <= 'z' or 'A' <= plaintext[i] <= 'Z':
s = ord(plaintext[i]) + 3
if s > ord('Z') and s < ord('a') or s > ord('z'):
s = s - 26
ciphertext = ciphertext + chr(s)
else:
ciphertext = ciphertext + plaintext[i]
i = i+1
return(ciphertext)
def decrypt_caesar(ciphertext: str) -> str:
"""
>>> decrypt_caesar("SBWKRQ")
'PYTHON'
>>> decrypt_caesar("sbwkrq")
'python'
>>> decrypt_caesar("Sbwkrq3.6")
'Python3.6'
>>> decrypt_caesar("")
''
"""
i = 0
plaintext = ""
while i < len(ciphertext):
if 'a' <= ciphertext[i] <= 'z' or 'A' <= ciphertext[i] <= 'Z':
s = ord(ciphertext[i]) - 3
if s < ord('a') and s > ord('Z') or s < ord('A'):
s = s + 26
plaintext = plaintext + chr(s)
else:
plaintext = plaintext + ciphertext[i]
i = i+1
return(plaintext)
plaintext = input("Enter a word: ")
ciphertext = encrypt_caesar(plaintext)
print(ciphertext)
plaintext = decrypt_caesar(ciphertext)
print(plaintext)
|
#Import pandas, numpy, matplotlib, and seaborn.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
#Read in the Ecommerce Customers csv file as a DataFrame called customers.
customers = pd.read_csv('Ecommerce Customers')
#Check the head of customers, and check out its info() and describe() methods.
print(customers.head())
print(customers.info())
print(customers.describe())
#Use seaborn to create a jointplot to compare the Time on Website and Yearly Amount Spent columns. Does the correlation make sense?
sns.jointplot(x='Time on Website', y='Yearly Amount Spent', data=customers, kind='scatter')
plt.show()
print("The correlation between [Time on Website] and [Yearly Amount Spent] does not make sense")
#Do the same but with the Time on App column instead.
sns.jointplot(x='Time on App', y='Yearly Amount Spent', data=customers, kind='scatter')
plt.show()
#Use jointplot to create a 2D hex bin plot comparing Time on App and Length of Membership.
sns.jointplot(x='Time on App', y='Length of Membership', data=customers, kind="hex", color="#4CB391")
plt.show()
#Let's explore these types of relationships across the entire data set. Use pairplot to recreate the plot below.(Don't worry about the the colors)
sns.pairplot(customers)
plt.show()
#Based off this plot what looks to be the most correlated feature with Yearly Amount Spent?
print("[Length of membership] is most correlated feature with [Yearly Amount Spent]")
#Create a linear model plot(using seaborn's lmplot) of Yearly Amount Spent vs. Length of Membership.
#customers and a variable y equal to the "Yearly Amount Spent" column.
sns.lmplot(x='Length of Membership',y='Yearly Amount Spent',data = customers)
plt.show()
#Use model_selection.train_test_split from sklearn to split the data into training and testing sets. Set test_size=0.3 and random_state=101
#Import LinearRegression from sklearn.linear_model
#Create an instance of a LinearRegression() model named lm.
X=customers[['Avg. Session Length','Time on App','Length of Membership']]
y=customers['Yearly Amount Spent']
print("[Time on Website] does not have a relationship with [Year Amount Spent], so I take it out of training set")
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
#Train/fit lm on the training data.
lm = LinearRegression().fit(X_train, y_train)
#Print out the coefficients of the model
coeff_customers = pd.DataFrame(lm.coef_, X.columns, columns=['Coefficient'])
print(coeff_customers)
#Use lm.predict() to predict off the X_test set of the data.
predictions = lm.predict(X_test)
#Create a scatterplot of the real test values versus the predicted values.
plt.scatter(y_test, predictions)
plt.show()
#Calculate the Mean Absolute Error, Mean Squared Error, and the Root Mean Squared Error. Refer to the lecture or to Wikipedia for the formulas
print('MAE:', metrics.mean_absolute_error(y_test, predictions))
print('MSE:', metrics.mean_squared_error(y_test, predictions))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))
#Plot a histogram of the residuals and make sure it looks normally distributed. Use either seaborn distplot, or just plt.hist().
sns.distplot((y_test-predictions), bins=50)
plt.show()
#Recreate the dataframe below.
sns.pairplot(customers)
plt.show()
print("[Time on Website] does not have a relationship with [Year Amount Spent], so I take it out of training set")
#How can you interpret these coefficients?
print("The coefficients of [Avg. Session Length], [Time on App] and [Length of Membership] show that they have an affect on the target")
print("These coefficients are positive that mean when numbers of feature increase, the target also increase")
print("The coefficient value represents the mean change in the response given a one unit change in the predictor")
#Do you think the company should focus more on their mobile app or on their website?
print("The company should focus more on mobile app")
# Ref: www.pieriandata.com
|
# MIT-6.00.1
counter = 0;
for i in s:
if i in 'aeiuo':
counter += 1
print ('Number of vowels: '+str(counter))
|
#!/usr/bin/env python
from copy import deepcopy
CONFIG = "settings.json"
BLOCK = -5
EMPTY = -1
HEIGHT = 8
WIDTH = 6
REDS = [(2,1), (4,2), (3,3), (5,4), (2,5), (5,5), (4,6)]
START = (3,0)
END = (HEIGHT * WIDTH) - len(REDS)
def create_board(height, width, block_list):
""" Given a height, width, and list of tuple points, creates a create_board
of zeros then places blocks as BLOCK value """
board = [[EMPTY for i in range(width)] for i in range(height)]
for point in block_list:
board[point[1]][point[0]] = BLOCK
return board
def solve(board, point, end, turns):
invalid_x = point[0] < 0 or point[0] >= len(board[0])
invalid_y = point[1] < 0 or point[1] >= len(board)
if invalid_x or invalid_y:
print("Invalid coords")
return (False, board)
value = board[point[1]][point[0]]
if value != EMPTY:
print("Hit Red block")
return (False, board)
board[point[1]][point[0]] = turns
format_board(board)
if turns == end:
return (True, board)
up = solve(deepcopy(board), (point[0], point[1] - 1), end, turns + 1)
if up[0]:
return up
down = solve(deepcopy(board), (point[0], point[1] + 1), end, turns + 1)
if down[0]:
return down
left = solve(deepcopy(board), (point[0] - 1, point[1]), end, turns + 1)
if left[0]:
return left
right = solve(deepcopy(board), (point[0] + 1, point[1]), end, turns + 1)
if right[0]:
return right
print("Trapped")
return (False, board)
def format_board(board):
""" Creates string representation of board """
print("")
for row in board:
print("[" + " ,".join(["%3d" % x for x in row]) + "]")
print("")
def main():
board = create_board(HEIGHT, WIDTH, REDS)
answer = solve(deepcopy(board), START, END, 1)[1]
format_board(answer)
if __name__ == '__main__':
main()
|
import queue
import collections
Tuple=("Red","Green","Blue")
Dictionary = {"Name": "Ansh", "Age": 16, "Class": "XI"}
Stacks=[1,2,3,4,5,6,7,8]
Queues=queue.Queue(3)
Deques=collections.deque("ABCDEF", 10)
Tuple=Tuple.__add__(("Black",))
print(Tuple)
print(Tuple.__contains__("Black"))
print(len(Tuple))
print(Dictionary.items())
print(Dictionary.keys())
Dictionary.update({"Gender": "Male"})
Dictionary["Age"]=17
del Dictionary["Class"]
print(Dictionary)
print(len(Dictionary))
Dictionary.clear()
print(Dictionary)
Stacks.append(9)
Stacks.pop()
print(Stacks)
print(Queues.empty())
Queues.put(1)
Queues.put(2)
Queues.get()
print(Queues.full())
print(Deques)
Deques.append('G')
Deques.extend("H")
Deques.pop()
Deques.appendleft('G')
Deques.extendleft("1")
Deques.popleft()
print(Deques)
|
String1 = "Hello World"
String2 = "Python is Fun!"
print(String1[0])
print(String1[0:5])
print(String1[:5])
print(String1[6:])
String3 = String1[:6] + String2[:6]
print(String3)
print(String2[:7]*5)
print()
MyString = " Hello World "
print(MyString.upper())
print(MyString.strip())
print(MyString.center(21, "*"))
print(MyString.strip().center(21, "*"))
print(MyString.isdigit())
print(MyString.istitle())
print(max(MyString))
print(MyString.split())
print(MyString.split()[0])
print()
SearchMe = "The apple is red and the berry is blue!"
print(SearchMe.find("is"))
print(SearchMe.rfind("is"))
print(SearchMe.count("is"))
print(SearchMe.startswith("The"))
print(SearchMe.endswith("The"))
print(SearchMe.replace("apple", "car").replace("berry", "truck"))
print()
Formatted = "{:d}"
print(Formatted.format(7000))
Formatted = "{:,d}"
print(Formatted.format(7000))
Formatted = "{:^15,d}"
print(Formatted.format(7000))
Formatted = "{:*^15,d}"
print(Formatted.format(7000))
Formatted = "{:*^15.2f}"
print(Formatted.format(7000))
Formatted = "{:*>15X}"
print(Formatted.format(7000))
Formatted = "{:*<#15x}"
print(Formatted.format(7000))
Formatted = "A {0} {1} and a {0} {2}."
print(Formatted.format("blue", "car", "truck"))
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
fname="Ripa"
lname='Shah'
# In[2]:
print(fname + " "+ lname)
# In[3]:
print(lname + "123")
# In[4]:
print(lname+ str(123))
# In[5]:
s1="This is a long string"
print(len(s1))
# In[6]:
s2= " Lots of spaces in here "
print(s2)
# In[7]:
print(">"+s2+"<")
# In[8]:
print(">"+s2.lstrip()+"<")
# In[9]:
print(">"+s2.rstrip()+"<")
# In[10]:
print(">"+s2.strip()+"<")
# In[11]:
s3="ABCDEF"
print("Does s3 starts with 'A'?" + str(s3.startswith("A")))
# In[12]:
print("Does s3 starts with 'B'" + str(s3.startswith("B")))
# In[13]:
print("Does s3 ends with 'Z'"+ str(s3.endswith("Z")))
# In[14]:
url="http://www.python.org"
print("Does url starts with http?"+ str(url.startswith("http")))
# In[15]:
print("Does url starts with https?" + str(url.startswith("https")))
# In[16]:
s4="This is a test"
print(s4)
# In[17]:
print(s4.upper())
# In[18]:
print(s4.lower())
# In[19]:
s5="I really should capitalize first letter of a sentence"
print(s5.capitalize())
print(s5.title())
# In[23]:
just="Justify me"
print(">"+just.ljust(25)+"<")
print(">"+just.center(25)+"<")
print(">"+just.rjust(25)+"<")
print(">"+just.ljust(9)+"<")#does not trim
# In[5]:
s6="abcdefghijklmnopqrstuvwxyza"
print(s6.find("j"))
# In[3]:
index=s6.find("8")
print(index)
# In[4]:
print(s6.rfind("j"))
# In[6]:
print(s6.rfind("a"))
# In[7]:
print(s6.rfind("a",2))
# In[8]:
print(s6.index('a'))
# In[10]:
#print(s6.index('8'))
# In[14]:
sAlpha="asphaertakk"
sNumeric="12345345234"
sMixed= sAlpha + sNumeric
print("sAlpha is alpha?" + " "+str(sAlpha.isalpha()))
# In[16]:
print("sAlpha is numeric?" +" "+ str(sAlpha.isnumeric()))
# In[17]:
print("sNumeric is alpha:"+ " "+ str(sNumeric.isalpha()))
# In[18]:
print("sNumeric is numeric:"+ " "+ str(sNumeric.isnumeric()))
# In[19]:
print("sMixed is alpha:"+" "+ str(sMixed.isalpha()))
print("sMixed is numeric:" +" "+ str(sMixed.isnumeric()))
print("sMixed is alnum:"+" "+str(sMixed.isalnum()))
# In[20]:
s7="tyres"
print(s7)
print(s7.replace("y","i"))
# In[26]:
s8="Hello World"
print(s8)
print(s8[2:])
print(s8[:2])
print(s8[2:6])
print(s8[:-2])
print(s8[:-3])
print(s8[-2:])
# In[27]:
phone="678-789-5678"
split=phone.split("-")
print(split)
# In[28]:
areaCode=split[0]
# In[29]:
print(areaCode)
# In[33]:
prefix=split[1]
lineNumber=split[2]
print(prefix)
print(lineNumber)
print("("+ areaCode+")-"+prefix+"-"+lineNumber)
# In[31]:
newPhone=".".join(split)
# In[32]:
print(newPhone)
# In[34]:
newPhone=str.join(".",split)
print(newPhone)
# In[39]:
fname = "Ripa"
lname = "Shah"
print(f"We can embed variables like '{fname}' directly in our strings!")
# In[42]:
print(f"We can also make function calls in the braces! See:{fname.upper()}")
# In[43]:
print(f"Embed multiple variables and constants {fname},{lname} age:{25}")
# In[47]:
print("What about decimal places? Sure:${25.1256:0.2f}")
# In[52]:
fname="Jamie"
lname="Williams"
salary=654321
print(f"{lname.ljust(20)} {fname} ${salary:.2f}")
print(f"{lname:<20} {fname:<15} ${salary:>12,.2f}")
fname="Ripa"
lname="Shah"
salary=85000
print(f"{lname:<20} {fname:<15} ${salary:>12,.2f}")
# In[ ]:
|
import random # import is how you tell python that you want to use a library in a script
# 'if' and 'True' are python KEYWORDs, and should NEVER EVER be used as a variable
if True:
print('Obviously...')
# False is a python KEYWORD, and should NEVER EVER be used as a variable
if False:
print('This will never be printed.')
print('') # print a blank line
my_rand_int = random.randint(1, 2) # returns a value: 1 or 2
print(f'my random int is {my_rand_int}')
# essentially: if X, do Y
if my_rand_int == 1: # the '==' operator returns True if the two elements are equal, False otherwise
print('is 1')
if my_rand_int != 1: # the '!=' operator returns 'True' if the two elements are equal, False otherwise
print('was 2')
# simulate a coin flip, which has two obvious outcomes
if my_rand_int == 1:
print('Heads')
else: # 'else' is a python KEYWORD, and should NEVER EVER be used as a variable
print('Tails')
print('') # print a blank line
# not quiiiite accurate to the real-world act, let's add a third case
BIG_RAND_INT_MAX = 200000
bigger_rand_int = random.randint(0, BIG_RAND_INT_MAX)
print(f'random integer with max {BIG_RAND_INT_MAX}: {bigger_rand_int}')
# value < Y is a special operator equivalent to (X < value) and (value < Y)
if bigger_rand_int < 80000:
print('less than 80000')
if bigger_rand_int >= (BIG_RAND_INT_MAX / 2):
print('Heads')
elif bigger_rand_int > 0:
# 'elif' is a python KEYWORD, and should NEVER EVER be used as a variable
print('Tails')
else:
# note that our elif used >, NOT >=
print('Landed on the edge, %s was zero!' % bigger_rand_int)
# each indented block MUST have at least one statement! If you want to
# represent a case in your if-elif-elif... tree
# you should use the 'pass' python keyword.
# python interprets the 'pass' to mean 'do nothing'
if -25 < 0:
pass
print('') # print a blank line
# <TRY IT OUT>
## grab a random integer between 1 and 5
## write an if-tree that will:
### print some text if the integer is 1 or 2
### print some text if the integer is 3 or 4
### print something else if it's 5
|
import os
import re
import random
# handling punctuation requires Regular Expressions, this one says
# to match on any group of what's in the square brackets. in this case,
# it's a mess of punctuation characters.
PUNCTUATION_AND_SPACES_REGEX = r'[,\.\-\;\:\"\(\)\' ]+'
def print_each_line_and_word(file_path):
assert isinstance(file_path, str)
# tell the operating system you want to read the file
file_handle = open(file_path)
# loop over each line of the file
for line in file_handle.readlines():
# strip off the 'new line' character at the end
line = line.strip('\n')
# if this doesn't seem to work, try uncommenting this one too
# line = line.strip('\r')
# for example, we can print each line
print(line)
# use Regular Expression to split on punctuation and whitespace
words_in_line = re.split(PUNCTUATION_AND_SPACES_REGEX, line)
for word in words_in_line:
print(word)
def find_longest_word(file_path):
assert isinstance(file_path, str)
# tell the operating system you want to read the file
file_handle = open(file_path)
longest_word = ''
# loop over each line of the file
for line in file_handle.readlines():
# strip off the 'new line' character at the end
line = line.strip('\n')
# if this doesn't seem to work, try uncommenting this one too
# line = line.strip('\r')
# use Regular Expression to split on punctuation and whitespace
words_in_line = re.split(PUNCTUATION_AND_SPACES_REGEX, line)
for word in words_in_line:
if len(word) > len(longest_word):
# debug code
#print(word)
longest_word = word
# this solution is incomplete, because what would happen
# if the following line was your text?
# I like peanut butter.
# Answer: peanut (len of 6) would be selected, and
# butter (also len 6) would be ignored because its not longer.
# A better solution would be to track a list of all
# words greater than or equal to some max length,
# and return the whole list.
return longest_word
def count_number_of_words(file_path):
assert isinstance(file_path, str)
# tell the operating system you want to read the file
file_handle = open(file_path)
word_count = 0
# loop over each line of the file
for line in file_handle.readlines():
# strip off the 'new line' character at the end
line = line.strip('\n')
# if this doesn't seem to work, try uncommenting this one too
# line = line.strip('\r')
words_in_line = re.split(PUNCTUATION_AND_SPACES_REGEX, line)
word_count += len(words_in_line)
return word_count
def count_specific_word(file_path, word_to_count):
assert isinstance(file_path, str)
assert isinstance(word_to_count, str)
# tell the operating system you want to read the file
file_handle = open(file_path)
lc_word_to_count = word_to_count.lower()
word_count = 0
# loop over each line of the file
for line in file_handle.readlines():
# strip off the 'new line' character at the end
line = line.strip('\n')
# if this doesn't seem to work, try uncommenting this one too
# line = line.strip('\r')
words_in_line = re.split(PUNCTUATION_AND_SPACES_REGEX, line)
for word in words_in_line:
if word.lower() == lc_word_to_count:
word_count += 1
return word_count
def get_lines_containing_word(file_path, word_to_find):
assert isinstance(file_path, str)
assert isinstance(word_to_find, str)
# tell the operating system you want to read the file
file_handle = open(file_path)
lc_word_to_find = word_to_find.lower()
matching_lines = [] # an empty list
# loop over each line of the file
for line in file_handle.readlines():
# strip off the 'new line' character at the end
line = line.strip('\n')
# if this doesn't seem to work, try uncommenting this one too
# line = line.strip('\r')
words_in_line = re.split(PUNCTUATION_AND_SPACES_REGEX, line)
for word in words_in_line:
if word.lower() == lc_word_to_find:
matching_lines.append(line)
# what happens if there are multiple of the same word?
# answer: this would append duplicate lines, one
# for each match... can you think of a way around it?
return matching_lines
def get_count_of_all_words(file_path):
assert isinstance(file_path, str)
# we'll need a different data structure to do this efficiently,
# tuples/lists are a crappy way to store this data.
# instead, let's use a dictionary
return 'dont try it without dictionaries'
# be sure to make a directory next to this script
# called 'text_files' to hold all your sample texts.
#FILE_PATH = 'text_files/file_name_to_parse.txt'
FILE_PATH = 'text_files/bible.txt'
if not os.path.isfile(FILE_PATH):
print('not a valid file path: %s' % FILE_PATH)
exit()
# TODO call your functions against the specified file text
longest_word = find_longest_word(FILE_PATH)
print('The longest word is %s' % longest_word)
num_words = count_number_of_words(FILE_PATH)
print('Total %s words' % num_words)
word_to_count = 'God'
num_of_a_word = count_specific_word(FILE_PATH, word_to_count)
print('The word %s was found %s times' % (word_to_count, num_of_a_word))
word_to_find = 'Satan'
lines = get_lines_containing_word(FILE_PATH, word_to_find)
print('Matched %s in %s lines, examples:' % (word_to_find, len(lines)))
for line in lines[:8]:
print(line)
|
# this is a little silly, but will reinforce everything
# required to start using internet-based APIs
# create a dictionary that will represent our checked bag
checked_bag = {
'sets of clothes': 5,
'passport': 1,
'toiletries bag': {
'toothbrush': 1,
'toothpaste': 1,
'conditioner': 1,
},
'books': [
'for whom the bell tolls',
'harry potter and the goblet of fire',
'captain underpants anthology',
],
}
# create a dictionary that will represent our carry-on
carry_on_bag = {
'cash': 250.00,
'books': [
'harry potter and the prisoner of azkaban',
],
'plane ticket': 1,
'pizzeria pretzel combos': 3,
'bottled water': 1,
}
import random
import pprint
## TODO YOUR CODE BELOW
# DON'T: any functions for this script
# DO: use pprint library to 'pretty print' your dictionaries
# as you work on each step to debug! look up pprint usage on the internet
# 0. if you don't have any of the following items packed, add it.
# Don't worry about iterating through the dictionary to search, you
# know where everything should be.
# passport
# plane ticket
# cash
# shampoo
exit('cancelled trip, missing: %s' % 'TODO add checks for stuff')
# 1. Don't forget to bring a towel! check your checked bag to see if you have
# one, and put one in if you don't.
# 2a. check in for your flight, do you have a passport?
# 2b. should probably put your passport in your carry-on...
# 3. board the plane (spend a ticket)
# 4. eat a bag of combos and drink half your water.
# 5a. steal 5 nips of Jack Daniels while the flight attendant isn't looking,
# drink two and put the other in your carry-on
# 5b. tip the flight attendant generously for lacking vigilance
# 6. pay up front for your hotel ($124.99)
# 7. hit the ATM to replenish your cash
# 8a. apply a bottle of sunscreen,
# 8b. take your towel and a book to the beach
# 8c. put your towel and book back
# 9. eat the local cuisine, take a 50-50 chance of feeling too terrible to
# drink the rest of the Jack Daniels.
# 10. wake up, brush your teeth with the Jack Daniels if you have
# any in your carry-on or checked bag. If not, use all your toothpaste.
# 11. almost done with the carry-on book, take a random one out of
# your checked-bag and put it in your carry on.
# ...you can continue to vacation if you like, or
# 12a. print a new ticket and put it in your carry-on
# 12b. go to the airport, check your passport
# 12c. spend your ticket to board the plane
# 12d. spend cash on a taxi to get home
print('what a great vacation!\n')
print('ended with a checked bag holding')
pprint.pprint(checked_bag)
print('')
print('ended with a carry-on holding')
pprint.pprint(carry_on_bag)
print('')
|
import socket
import pickle
import argparse
from PIL import Image
text = 'This is a client for receiving images'
parser = argparse.ArgumentParser(description=text)
parser.add_argument("-s", '--server', help='write the server and port number seperated by : to use')
parser.add_argument("-q", '--path', help='type the path to the file to download with reference to server directory or root')
args = parser.parse_args()
path = '1.png'
if args.server:
address =args.server.split(':')
print('the ip and port being useed is %s' %args.server)
port = int(address[1])
host = address[0]
path = args.path
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
"""REQUESTING IMAGE"""
name = path.split('/')
print(f'requesting image at path: {path}')
file_name = name[-1]
s.send(path.encode('utf-8'))
"""REQUESTING IMAGE"""
print('receiving image')
Msg = s.recv(2)
fullMsg = b''
while Msg:
fullMsg += Msg
Msg = s.recv(1024)
"""receiving IMAGE"""
image = open(file_name,'wb')
image.write(fullMsg)
"""END receiving IMAGE"""
print(f'Successfully Downloaded {file_name}')
else:
print("use arguments as shown with -h")
|
list_one = [2, 3, 4]
list_two = [2*i for i in list_one if i > 2]
print(list_two)
|
def avg(a, b, c):
sum = 0
for n in [a, b, c]:
sum += n
return sum / 3
print(avg(1, 3, 5))
print(avg(2, 3, 4))
print(avg(1, 6, 9))
|
for n in range(1, 11):
if n % 3 == 0:
continue
print(n, sep='\n')
|
name = input('What is your name? ')
favorite_color = input('What is you favorite color?')
print(name + ' likes ' + favorite_color)
|
def pal_perm(str1):
# palindrome must have 2 of each char plus potentially 1 of another
charmap = {}
fstr = str1.upper().replace(' ','')
for char in fstr:
val = charmap.get(char, 0)
if val == 0:
charmap.update({char: 1})
elif val == 2:
return False
else:
charmap.update({char: val+1})
# iterate through charmap
single = False
for k, v in charmap.items():
if v == 1 and not single:
single = True
elif v == 1 and single:
return False
return True
def main():
str1 = "Tact Coa"
str2 = "ABCCBA"
str3 = "ABCDEF"
print(pal_perm(str1))
print(pal_perm(str2))
print(pal_perm(str3))
if __name__ == "__main__":
main()
|
import copy
import heapq
from util import *
from node import Node
class priority_queue():
def __init__(self, query_vec, farthest=False):
self.heap = []
self.set = set()
self.query_vec = query_vec
self.farthest = farthest
def __repr__(self):
return str(self.set)
def append(self, node):
if node not in self.set:
dist = l2_dist(self.query_vec, node.vec)
if self.farthest is True:
dist = -dist
heapq.heappush(self.heap, (dist, node))
self.set.add(node)
def top(self):
return self.heap[0][1]
def pop(self):
ret = heapq.heappop(self.heap)[1]
self.set.remove(ret)
return ret
def __len__(self):
return len(self.set)
def as_set(self):
return copy.deepcopy(self.set)
def as_list(self, _sorted=False):
ret = copy.deepcopy(self.set)
if _sorted:
sorted(ret)
return ret
def rebase(self, query_vec):
ret_pq = priority_queue(query_vec, farthest=self.farthest)
for node in self.set:
ret_pq.append(node)
return ret_pq
def inverse(self):
ret_pq = priority_queue(self.query_vec, farthest=not self.farthest)
for node in self.set:
ret_pq.append(node)
return ret_pq
def list_as_pq(query_node, node_list):
pq = priority_queue(query_node.vec)
for node in node_list:
pq.append(node)
return pq
|
print("How old are you?"),
age=input("Your age?")
print("How tall are you?"),
height=input("Your height?")
print("How much do you weight?"),
weight=input("Your weight?")
print("So, you're %r old, %r tall and %r heavy." % (age,height,weight))
|
"""Helper functions to make vector manipulations easier."""
import math
def add_vec(pos, vec, dt):
"""add a vector to a position"""
px, py, pz = pos
dx, dy, dz = vec
px += dx * dt
py += dy * dt
pz += dz * dt
p = (px, py, pz)
return p
def sub_vec(v1, v2, dt=1):
x1, y1, z1 = v1
x2, y2, z2 = v2
x = x1 - x2 * dt
y = y1 - y2 * dt
z = z1 - z2 * dt
v = (x, y, z)
return v
def scale_vec(v, n):
x, y, z = v
x *= n
y *= n
z *= n
v = (x, y, z)
return v
def dist(point_a, point_b):
"""compute the absolute distance between to (x,y,z) tuples"""
x1,y1,z1 = point_a
x2,y2,z2 = point_b
return math.sqrt((x2-x1) ** 2 +(y2-y1) ** 2 +(z2-z1) ** 2)
def dot(v1, v2):
"""the dot product of two vectors"""
x1, y1, z1 = v1
x2, y2, z2 = v2
x = x1 * x2
y = y1 * y2
z = z1 * z2
return x + y + z
def cross(v1, v2):
"""the cross prodcuct of two vectors"""
x1, y1, z1 = v1
x2, y2, z2 = v2
x = y1 * z2 - z1 * y1
y = z1 * x2 - x1 * z2
z = x1 * y2 - y1 * x2
v = (x, y, z)
return v
def magnitude(v):
x, y, z = v
return math.sqrt( x ** 2 + y ** 2 + z ** 2)
def dist_line_point(l1, l2, p):
"""the shortest distance between a line (l1,l2) and a point"""
ab = sub_vec(l2, l1)
ac = sub_vec(p, l1)
area = magnitude(cross(ab, ac))
cd = area / magnitude(ab)
return cd
def dist_line_seg_point(l1, l2, p):
"""the shortest distance between a line segment (l1,l2) and a point"""
n = sub_vec(l2, l1)
pa = sub_vec(l1, p)
c = dot(n, pa)
# closest point is l1
if (c > 0.0):
return dot(pa, pa)
bp = sub_vec(p, l2)
# closest point is l2
if (dot(n, bp) > 0.0):
return dot(bp, bp)
# closest point is between l1 and l2
e = sub_vec(pa, scale_vec(n, (c / dot(n, n))))
return dot(e, e)
|
def flatten(mylist):
newlist = [y for x in mylist for y in x]
return newlist
mylist = [[1,3,4],[1,34,67],[32,1],[34,56,4]]
print(mylist)
print(flatten(mylist))
|
def sortsecond(l):
return l[1]
def sortfirst(l):
return l[0]
student = []
n = int(input("Enter No of student: "))
for i in range(n):
name = input("Enter name of Student{}: ".format(i))
per = float(input("Enter Per of student{}: ".format(i)))
student.append([name,per])
student = sorted(student,key = sortsecond)
min = student[0]
for i in student:
if min[1] != i[1]:
act = i
break
ans = []
for i in student:
if act[1] == i[1]:
ans.append(i)
ans = sorted(ans,key = sortfirst)
for i in ans:
print(i[0])
|
str = input("Enter AlphaNumeric String: ")
list = []
for x in str:
if x in "1234567890":
list.append(int(x))
print(sorted(list))
|
from random import randint
num = randint(1,100)
while True:
guess = int(input("Guess the number(from1 to 100):"))
if num == guess:
print("Congratulation! you guess it right")
break
if guess>num:
print("Number is too large! Try again")
elif guess<num and guess>0:
print("Number is too small! try again")
else:
print("Sorry! better luck next time")
|
def remove_mark(s):
return ''.join([t for t in s if t.isalpha()])
def begin_duplicate(tokens):
for f in range(1, len(tokens)):
if tokens[:f] == tokens[f:2*f]: return f
return None
def distinct(tokens):
if not tokens: return ''
duplicate = begin_duplicate(tokens)
if duplicate:
return distinct(tokens[duplicate:])
else:
return tokens[0]+ distinct(tokens[1:])
sentence1 = '这个橘子真的真的好好吃哦'
sentence2 = '你到底知不知道,到底知不知道?'
sentence3 = '这个饭馆是我吃过最好吃的饭馆,最好吃的饭馆!'
sentence4 = '你是真的不知道,真的不知道?还是假的不知道'
sentence5 = '你你你你要气死我了,你真是不可理喻'
assert distinct(remove_mark(sentence1)) == '这个橘子真的好吃哦'
assert distinct(remove_mark(sentence2)) == '你到底知不知道'
assert distinct(remove_mark(sentence3)) == '这个饭馆是我吃过最好吃的饭馆'
assert distinct(remove_mark(sentence4)) == '你是真的不知道还是假的不知道'
assert distinct(remove_mark(sentence5)) == '你要气死我了你真是不可理喻'
|
# lesson 1, what is regression?
# supervised learning, take examples of inputs and outputs,
# then take another input, and predict the output
# discrete outputs, continuous outputs,<- we are looking at continuous outputs
#
# We expect Charles' children to be between Charles' height and average height.
# lesson 2, regression and function approximation
# use a function to approximate the relationship between parent height and children
# height. This is called regression to the mean.
# lesson 3, regression in machine learning
# have to interpolate
# linear relationship, minimize linear relationship
#
# lesson 4, find the best fit line
# how to find best fit line, via the least square error
# how to solve:
# 1. hill climbing, y=mx+b, try different values of m and b
# 2. can we use calculus? yes
# 3. can we use random search? pick random values of m and b
# 4. should we ask a phsicist
#
# f(x) = c (constant)
# E(c) = sum_{i=1}^{n} (y_i-c)^2
# use calculus to find the minimum:
# dE(c)/dc = sum_{i=1}^{n} 2(y_i-c)(-1) loss function
# -sum_{i=1}^{n} 2(y_i-c) = 0
# sum_{i=1}^{n} y_i - sum_{i=1}^{n} c = 0
# nc = sum_{i=1}^{n} y_i
# c = sum_{i=1}^{n} y_i / n
# lesson 5, order of polynomial
# k=0, constant
# k=1, line
# k=2, parabola
# f(x) = c0 + c1x + c2x^2
# order of polynomial cannot exceed the #datapoints
#
# plot training error vs. order of polynomil
# lesson 6, pick the degree
# use order 3 because it looks better
# lesson 7, polynomial regression
# x|y, c0+c1x+c2x^2+c3x^3 = y
#
# [1 x1 x1^2 x1^3] [c0] = [y1]
# [1 x2 x2^2 x2^3] [c1] = [y2]
# [1 x3 x3^2 x3^3] [c2] = [y3]
# [1 x4 x4^2 x4^3] [c3] = [y4]
# [... ] [ ]
# [1 xn xn^2 xn^3] [yn]
#
# Xw ~= Y, solve using least square:
# X^T Xw ~= X^T Y
# X^T Xw ~= X^T Y
# (X^TX)^(-1) X^TXw ~= (X^TX)^(-1) X^TY
# x = (X^TX)^(-1)X^TY this is how you compute the weight
# lesson 8, error
# training data has errors in it, no modelling f but modelling f+e, where do errors
# come from?
# sensor error
# miliciously - being given bad error
# transcription error
# unmodelled influences
# lesson 9, cross validation
# training set and test set
# we want to generalize to the real world
# we want the data to be indendent, and identically distributed, this is a
# fundamental assumption.
# lesson 10, cross validation
# we want a model that is complex enough to fit the data without causing problems
# on the test set.
#
# Take some of the training set data, and use it as cross validation set.
# use 4 folds 1 2 3 4
# train on 1 2 3, test on 4
# train on 2 3 4, test on 1
# train on 3 4 1, test on 2
# train on 4 1 2, test on 3
#
# housing example revisited:
# training error improves
# cross validation error falls then rises
#
# underfit, fit, overfit, you want to be in the goldilocks zone
# 11 other inputs
# other input spaces,
# -> scalar input, continuous, x
# -> vector input, continuous, x_bararrow
# include more input features,
# size, distance from zoo, hyperplanes
# one dimensional input, line
# 2 dimension input, plane
#
# predict credit score:
# do they have a job? {0,1}
# age?
# assets
# haircolor, red, beige, brown, blonde, black, blue
# RGB, enumerate
# 12 conclusion
# what did we learn:
# historical facts
# model selection and under/overfitting
# cross validation
# linear, polynomial regression
# best constant in terms of squared error: mean
# representation for regression
|
class GradeProc:
def __init__(self):
self.data =[]
def inputData(self):
while True:
name = input('이름:')
kor = int( input('국어:') )
eng = int( input('영어:') )
math = int( input('수학:') )
self.data.append( (name, kor, eng,math) )
yn= input('계속 입력하시겠습니까(y/n)?')
if yn=='n':
break
# print(data)
def outputData(self):
print("="*30)
print('이름','국어','영어','수학',sep='\t')
print("="*30)
for n,k,e,m in self.data:
print( n,k,e,m,sep='\t\t' )
grade = GradeProc()
grade.inputData()
grade.outputData()
|
#!/usr/bin/env python3
import math
from sys import argv
HEIGHT = 450
WIDTH = 450
def ssv(iterable):
return " ".join(str(i) for i in iterable)
if __name__ == "__main__":
if len(argv) != 2:
print("usage: {} ANGLE".format(argv[0]))
exit(1)
angle = float(argv[1])
sign = math.copysign(1, angle)
angle = abs(angle)
depth = sign * HEIGHT * math.tan(math.radians(angle))
print(ssv((depth, 0, HEIGHT)))
print(ssv((0, 0, 0)))
print(ssv((0, WIDTH, 0)))
print(ssv((depth, WIDTH, HEIGHT)))
if angle != 0:
if sign < 0:
print(ssv((depth, 0, 0)))
print(ssv((depth, WIDTH, 0)))
elif sign > 0:
print(ssv((0, 0, HEIGHT)))
print(ssv((0, WIDTH, HEIGHT)))
print()
print(ssv(range(4)))
if angle != 0 and sign != 0:
print(ssv((0, 4, 1)))
print(ssv((2, 3, 5)))
|
#!/usr/local/bin/python
import sys
wort = input ("Bitte das Wort eingeben, das geprueft werden soll, ob es ein Palindrom ist: ")
# anna = palindrom
# hans != palindrom
# lagerregal = palindrom
i = 0
wortlaenge = len(wort)
while i < wortlaenge:
if
wort
i+=1
else:
print ("Das Wort \""+wort+"\" ist kein Palindrom!")
|
import random
class Lottery:
def __init__(self):
self.my_num = set() # Entered numbers
self.winning_num = set() # Winner's numbers.
self.bonus = set()
# Reset numbers.
def init(self):
self.winning_num.clear()
self.bonus.clear()
while len(self.winning_num) < 6:
self.winning_num.add(random.randrange(1, 50))
while True:
n = random.randrange(1, 49)
if not (n in self.winning_num):
self.bonus.add(n)
break
# Input lottery numbers.
def insert(self):
self.my_num.clear()
while len(self.my_num) < 6:
print(str([ len(self.my_num) + 1 ]) + "Put your number (1 ~ 49) : ", end = "")
n = int(input())
if (n < 1) or (n > 49) or (n in self.my_num): # Wrong numbers
print("You have entered a wrong number or duplicated number. Please try again with a different number.")
continue
self.my_num.add(n)
print("Entered numbers : " + str(list(self.my_num)))
# Match entered Lottery numbers.
def match(self):
if len(self.my_num) != 6:
print("Select 2 to check your number.")
return
self.print()
self.printMy_num()
match_num = len(self.winning_num.intersection(self.my_num))
if match_num == 6:
print("* Congratulations! You are the winner. *")
elif match_num == 5 and self.my_num.intersection(self.bonus):
print("* Congratulations! You won the 2nd place. *")
elif match_num == 5:
print("* Congratulations! You won the 3rd place. *")
elif match_num == 4:
print("* Congratulations! You won the 4th place. *")
elif match_num == 3:
print("* Congratulations! You won the 5th place. *")
elif match_num == 2 and self.my_num.intersection(self.bonus):
print("* Congratulations! You won the 6th place. *")
else:
print("* Sorry, maybe next time... *")
# Output my numbers.
def printMy_num(self):
print("My numbers : ", end="")
tmp = list(self.my_num)
tmp.sort()
print(tmp)
# Output this week's numbers.
def print(self):
print("This week's numbers : ", end="")
arr = list(self.winning_num)
arr.sort()
print(arr, end="")
print(" +", list(self.bonus))
print("Starting Lottery numbers generator...")
lottery = Lottery()
lottery.init()
while True: # Start messages
print("==========================================================")
print("Please choose one of the followings:")
print("1. Show winner's numbers of this week.")
print("2. Enter your lottery numbers.")
print("3. Generate new lottery numbers.")
print("4. Match winner's numbers of this week and your numbers.")
print("5. End program. ")
print("==========================================================")
num = int(input())
if num == 1:
print("Show winner's number of this week.")
lottery.print()
elif num == 2:
print("Please enter your 6 lottery numbers.")
lottery.insert()
lottery.printMy_num()
elif num == 3:
print("Generated numbers : ")
lottery.init()
lottery.print()
elif num == 4:
print("Results : ")
lottery.match()
elif num == 5:
print("Ending program...")
break
print()
|
NO_POSSIBLE_PLAY = "none"
STAIRS = "stairs"
FULL = "full"
POKER = "poker"
JATZEE = "jatzee"
plays = [NO_POSSIBLE_PLAY, STAIRS, FULL, POKER, JATZEE]
possible_numbers = [1, 2, 3, 4, 5, 6]
jatzee_hand_length = 5
def consequent_check(sorted_hand, last, x):
return x == last or x + 1 == sorted_hand[sorted_hand.index(x) + 1]
def stairs(hand):
"""Checks if the hand passed by parameter has all distinct numbers and can be placed in order"""
sorted_hand = sorted(hand)
last = max(sorted_hand)
return len(set(hand)) == jatzee_hand_length and \
all(map(lambda x: consequent_check(sorted_hand, last, x), sorted_hand))
def full(hand):
"""Checks if the hand passed by parameter is a full hand (3 equal and 2 different)"""
set_of_two = list(set(hand))
return len(set_of_two) == 2 and (
(len([number for number in hand if number == set_of_two[0]]) == 3 and len([number for number in hand if number == set_of_two[1]]) == 2) or
(len([number for number in hand if number == set_of_two[0]]) == 2 and len([number for number in hand if number == set_of_two[1]]) == 3)
)
def poker(hand):
"""Checks if the hand passed by parameter has 4 equal numbers and 1 distinct"""
set_of_two = list(set(hand))
return len(set_of_two) == 2 and (
(len([number for number in hand if number == set_of_two[0]]) == 4 and len([number for number in hand if number == set_of_two[1]]) == 1) or
(len([number for number in hand if number == set_of_two[0]]) == 1 and len([number for number in hand if number == set_of_two[1]]) == 4)
)
def jatzee(hand):
"""Checks if all numbers in the hand are the same"""
return len(set(hand)) == 1
def assert_stairs(hand):
"""Checks if the hand passed by parameter is a stairs hand (all different and subsequent)"""
return assert_play(lambda numbers: stairs(numbers), STAIRS, hand)
def assert_full(hand):
"""Checks if the hand passed by parameter is a full hand (3 equal and 2 different)"""
return assert_play(lambda numbers: full(numbers), FULL, hand)
def assert_poker(hand):
"""Checks if the hand passed by parameter is a poker hand (4 equal and 1 different)"""
return assert_play(lambda numbers: poker(numbers), POKER, hand)
def assert_jatzee(hand):
"""Checks if the hand passed by parameter corresponds to a poker hand"""
return assert_play(lambda numbers: jatzee(numbers), JATZEE, hand)
def assert_play(rule, name, hand):
"""
Generic function to assert if the hand passed by parameter satisfies the rule,
returning the value inside score array
"""
if rule(hand):
return plays.index(name)
else:
return plays.index(NO_POSSIBLE_PLAY)
def legal_hand(hand):
"""Checks if the hand corresponds to a jatzee hand"""
return all(map(lambda x: x in possible_numbers, hand)) and len(hand) == jatzee_hand_length
def play(hand):
"""Checks if the hand is legal and returns which kind of play it was"""
if legal_hand(hand):
return plays[max([assert_stairs(hand), assert_full(hand), assert_poker(hand), assert_jatzee(hand)])]
else:
return "Illegal hand!"
|
def isPrime(n):
for d in range(2, n):
if n % d == 0:
return False
return True
for prime in range(3, 18):
if isPrime(prime):
print(" \item (Modulo %d)" % prime)
print(" ", end = " ")
for i in range(2, prime):
result = (i * i) % prime
print("%d^2 \equiv %d," % (i, result), end = " ")
if result == 2:
break
print("")
|
from itertools import permutations
import unittest
class Permutation:
def __init__(self, ls):
self.ls = ls
self.n = len(ls)
def sends(self, i):
return self.ls[i]
def __eq__(self, other):
for i in range(self.n):
if self.sends(i) != other.sends(i):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self,other):
return (self.cycle_notation()<other.cycle_notation())
def __le__(self,other):
return (self.cycle_notation()<=other.cycle_notation())
def __gt__(self,other):
return (self.cycle_notation()>other.cycle_notation())
def __ge__(self,other):
return (self.cycle_notation()>=other.cycle_notation())
def cycle_notation(self):
seen = {}
result = ""
for i in range(self.n):
if i not in seen:
if i != 0 and self.ls[i] == i: continue
result += "(" + str(i + 1)
j = self.ls[i]
while j != i:
seen[j] = True
result += str(j + 1)
j = self.ls[j]
result += ")"
if len(result) >= 4 and result[0:3] == "(1)":
result = result[3:]
return result
def multiply(self, other):
product = list(range(self.n))
for i in range(self.n):
product[i] = self.sends(other.sends(i))
return Permutation(product)
def inverse(self):
inverse = list(range(self.n))
for i in range(self.n):
inverse[self.sends(i)] = i
return Permutation(inverse)
def __hash__(self):
return hash('-'.join(str(i) for i in self.ls))
class TestPermutations(unittest.TestCase):
def test_cycle_notation(self):
p = Permutation([2, 1, 0, 4, 3])
self.assertEqual(p.cycle_notation(), "(13)(45)")
p = Permutation([2, 0, 1, 4, 3])
self.assertEqual(p.cycle_notation(), "(132)(45)")
p = Permutation(list(range(5)))
self.assertEqual(p.cycle_notation(), "(1)")
def test_multiply(self):
p = Permutation([2, 1, 0, 4, 3])
q = Permutation([0, 2, 1, 3, 4])
self.assertEqual(p.multiply(q).cycle_notation(), "(132)(45)")
def test_inverse(self):
p = Permutation([1, 0, 2, 3, 4])
self.assertEqual(p.inverse().cycle_notation(), p.cycle_notation())
def test_eq(self):
p = Permutation([1, 0, 2, 3, 4])
q = Permutation([1, 0, 2, 3, 4])
self.assertEqual(p == q, True)
p = Permutation([1, 0, 2, 3, 4])
q = Permutation([0, 1, 2, 3, 4])
self.assertEqual(p == q, False)
# unittest.main()
def printgroup(ls):
res = '['
for p in ls:
if len(res) >= 2:
res += ','
res += p.cycle_notation()
res += ']'
print(res)
v = Permutation([1, 2, 0, 3])
H = [v]
allperms = list(Permutation(p) for p in list(permutations([0, 1, 2, 3])))
def findclosure(ls):
ls.append(Permutation([0, 1, 2, 3]))
for i in range(24):
products = {Permutation([0, 1, 2, 3])}
for p in ls:
for q in ls:
products.add(p.multiply(q))
if len(products) >= 13:
return sorted(allperms)
if len(ls) == len(products):
return sorted(products)
ls = sorted(products)
allsubgroups = []
d = {3:[], 6:[], 12:[], 24:[]}
for newp in allperms:
H = findclosure([v, newp])
seen = False
for subgrp in allsubgroups:
if H == subgrp:
seen = True
if not seen: allsubgroups.append(H)
for i in range(len(allperms)):
newp = allperms[i]
H = findclosure([v, newp])
seen = False
for subgrp in allsubgroups:
if H == subgrp:
seen = True
if not seen: allsubgroups.append(H)
print("%s generates a subgroup of size %d" % (newp.cycle_notation(), len(H)))
d[len(H)].append(newp.cycle_notation())
for k in d:
print("%d: %s" % (k, ", ".join(d[k])))
for subgrp in allsubgroups:
printgroup(subgrp)
|
r = float(input('Write the radius of a circle'))
p = 3.14159
d = 2 * r
c = 2 * p * r
s = p * r ** 2
print('The diameter is', d)
print('The circumference is', c)
print('The area is', s)
|
from lib import is_prime
def repeating_digits(val):
if len(set(str(val))) == len(str(val)):
return []
result = []
for d in set(str(val)):
if str(val).count(d) > 1:
result.append(int(d))
return result
i = 1
done = False
while True:
if done:
break
i += 1
if is_prime(i) and repeating_digits(i):
for digit in repeating_digits(i):
bad = 0
prostye = [i]
for j in range(10):
if digit == j:
continue
new_i = int(str(i).replace(str(digit), str(j)))
if len(str(new_i)) != len(str(i)) or not is_prime(new_i):
bad += 1
else:
prostye.append(new_i)
if bad > 2:
break
if bad <= 2:
print(i)
done = True
|
import numpy as np
import scipy.io as scipy_io
import pdb
from collections import *
import matplotlib.pyplot as plt
import sys
class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)
self.distances = {}
def add_node(self, value):
self.nodes.add(value)
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
#self.edges[to_node].append(from_node)
self.distances[(from_node, to_node)] = distance
def dijsktra(graph, initial):
visited = {initial: 0}
path = {}
nodes = set(graph.nodes)
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.remove(min_node)
current_weight = visited[min_node]
for edge in graph.edges[min_node]:
try:
weight = current_weight + graph.distances[(min_node, edge)]
if edge not in visited or weight < visited[edge]:
visited[edge] = weight
path[edge] = min_node
except:
pdb.set_trace()
return visited, path
def provide_graph(matrix,graph):
# assuming matrix is fat matrix otherwise transpose the matrix
#if matrix.shape[0]>= matrix.shape[1]:
# pass
#else:
# print "transpose matrix"
# matrix = matrix.T
#return None
width = matrix.shape[0]
height = matrix.shape[1]
# add nodes plus source and destination
for i in range(matrix.size+2):
graph.add_node(i)
#add source node connection to the first ones
for i in range(matrix.shape[0]):
graph.add_edge(0,i+1,matrix[i,0])
for j in range(matrix.shape[1]-1):
for i in range(matrix.shape[0]):
for k in range(matrix.shape[0]):
if i <=k:
graph.add_edge(j*width+i+1,(j+1)*width+k+1,matrix[k,j+1])
else :
graph.add_edge(j*width+i+1,(j+1)*width+k+1,1000000000)
for i in range(matrix.shape[0]):
graph.add_edge(matrix.size+1-i,matrix.size+1,0)
return graph
if __name__ == '__main__':
matrix = scipy_io.loadmat(sys.argv[1])['pair_matrix']
if matrix.shape[0]>= matrix.shape[1]:
pass
else:
matrix = matrix.T
original_matrix = matrix
# to avoid infinity error
matrix = -np.log(matrix +0.00001)
graph_example = Graph()
# construct the DAG graph
graph_example = provide_graph(matrix,graph_example)
# get the optimal path
visited,path = dijsktra(graph_example,0)
node = matrix.size+1
# backwards throw out the optimal path
node_list = []
while node !=0:
node = path[node]
print node
node_list.append(node)
matrix_index= np.zeros(matrix.shape)
value = 0
for i in range(1,len(node_list)):
x = np.floor(node_list[i]/matrix.shape[0])
y = node_list[i] - matrix.shape[0]*x
print 'x:' + str(x) + 'y:' + str(y)
matrix_index[int(y),int(x)] = 1
value+= matrix[int(y),int(x)]
value = np.exp(-(1.0/matrix.shape[1])*value)
plt.subplot(2,1,1)
plt.imshow(original_matrix)
plt.subplot(2,1,2)
plt.imshow(matrix_index)
file_name = sys.argv[2]+'error:'+str(float(value))+'.pdf'
plt.savefig(file_name)
|
def twoSum(nums: list, target: int) -> list:
"""
QUESTION:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to
target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
NOTES:
1. dictionary is used to store and retrieve values, the good part of this algorithm, is that it stores the
value instead and use it to retrieve the index, in that case, we just loop through once
2. emumerate returns a counter and a value
3. use d[item] = index to create new key value pair
if we say use the value to check the index itself in the list, then it will happend that we loop over the list
again(but we cannot in the below case)
"""
d = {}
for index, item in enumerate(nums):
matched = target - nums[index]
if matched in d:
return [d[matched], index]
else:
d[item] = index
if __name__ == '__main__':
output = twoSum(nums=[3, 2, 4], target=6)
print(output)
output2= twoSum(nums=[32, 3, 12, 9, 7, 8, 0, 4, 3], target=6)
print(output2)
|
def main():
field = 3 # ex: 2^(3)
powers = [1,2,3,4,5,6] #x^1, x^2, x^3, x^4 ...
classes = []
for x in powers:
c = []
c.append(x)
for y in powers:
if x != y:
if y not in c and calc(field, x, y):
c.append(y)
c.sort()
if c not in classes:
classes.append(c)
for i in range(len(classes)):
print(classes[i])
def GCD(x, y):
if x > y:
small = y
else:
small = x
for i in range(1, small+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd
def calc(field, d, e):
for i in range(field):
if(d == (2**i)*e % ((2**field)-1)):
return True
if(GCD(e, ((2**field)-1)) == 1):
for i in range(field):
if(d == ((2**i)/e) % (2**field)-1):
return True
return False
main()
|
from random import *
import time
choices = ["Rock", "Paper", "Sicssors"]
computer = choices[randint(0, 2)]
print("welcome in our game")
time.sleep(1)
print("please choose paper, rock or scissors")
time.sleep(1)
print("If you want exit type 'x'")
time.sleep(1)
P_result = 0
C_result = 0
while True:
player = input("Rock, Paper, Siccors ?")
if player == computer:
print(computer)
print("Tie")
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
elif player == "Rock":
if computer == "Paper":
print(computer)
print("computer Win")
C_result += 1
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
else:
print("player Win")
P_result += 1
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
elif player == "Paper":
if computer == "Rock":
print("Player Win")
P_result += 1
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
else:
print("Computer Win")
C_result += 1
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
elif player == "Sicssors":
if computer == "Rock":
print("computer Win")
C_result += 1
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
else:
print("player Win")
P_result += 1
print("computer: {} - Player: {}".format(C_result, P_result))
print("-------------------------------")
elif player == "x":
print("Thank you for your time ^_^")
break
else:
print("Invalid Input")
computer = choices[randint(0, 2)]
|
"""
Example of bubble sort.
"""
def float_largest_to_top(data, array_size):
changed = False
# notice we stop at array_size-2 because of expr. k+1 in loop
for k in range(array_size - 1):
if (data[k] > data[k + 1]):
data[k], data[k+1] = data[k + 1], data[k]
changed = True;
return changed
def array_sort(data, array_size):
for k in range(array_size ):
if not float_largest_to_top(data, array_size - k):
return
def print_array(data, array_size,
optional_title = "--- The Array -----------:\n"):
ITEMS_PER_LINE = 5
print( optional_title )
# new line every ITEMS_PER_LINE items, commas between
for k in range(array_size):
if (k % ITEMS_PER_LINE == 0):
print()
else:
print( ", ", end = '' )
print ( data[k], end = '' )
# client --------------------------------------------
# my_array = ["mark", "andrea", "zebra", "aardvark"]
my_array = [10.2, 56.9, -33, 12, 0, 2, 4.8, 199.9, 73, -91.2]
array_size = len(my_array)
print_array(my_array, array_size, "Our array before the sort")
array_sort(my_array, array_size)
print_array(my_array, array_size, "\n\nAnd now after the sort")
""" --------------------------- RUN ---------------------------
Our array before the sort
10.2, 56.9, -33, 12, 0
2, 4.8, 199.9, 73, -91.2
And now after the sort
-91.2, -33, 0, 2, 4.8
10.2, 12, 56.9, 73, 199.9
------------------------------------------------------------ """
|
#!/bin/python3
def convert(x):
return {
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "forteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "ninteen",
20: "twenty"
}.get(x, 0)
def timeInWords(h, m):
res = ""
if m == 0:
res = convert(h) + " o' clock"
return res
if m > 30:
m = 60 - m
h += 1
res += "to " + convert(h)
else:
res += "past " + convert(h)
if m == 15:
res = "quarter " + res
elif m == 30:
res = "half " + res
elif m < 21:
if m == 1:
res = convert(m) + " minute " + res
else:
res = convert(m) + " minutes " + res
else:
res = "twenty " + convert(m - 20) + " minutes " + res
return res
if __name__ == '__main__':
h = int(input())
m = int(input())
result = timeInWords(h, m)
print(result)
|
#!/bin/python3
from copy import deepcopy
def bomberMan(n, grid):
global r, c
if n == 0 or n == 1:
return grid
if (n - 3) % 2 == 1 or n == 2:
for row in grid:
for i in range(c):
row[i] = 'O'
return grid
result = deepcopy(grid)
states = []
for itr in range(int((n - 3) / 2) + 1):
grid = deepcopy(result)
for i in range(r):
for j in range(c):
if grid[i][j] == 'O':
result[i][j] = '1'
if i + 1 < r:
result[i + 1][j] = '1'
if i - 1 >= 0:
result[i - 1][j] = '1'
if j + 1 < c:
result[i][j + 1] = '1'
if j - 1 >= 0:
result[i][j - 1] = '1'
for i in range(r):
for j in range(c):
if result[i][j] == '.':
result[i][j] = 'O'
elif result[i][j] == '1':
result[i][j] = '.'
states.append(deepcopy(result))
if itr != 0 and result == states[0]:
return states[int((n - 3) / 2) % itr]
return result
if __name__ == '__main__':
rcn = input().split()
r = int(rcn[0])
c = int(rcn[1])
n = int(rcn[2])
grid = []
for _ in range(r):
grid_item = list(input())
grid.append(grid_item)
result = bomberMan(n, grid)
result = [''.join(x) for x in result]
print('\n'.join(result))
|
import sys
from math import sqrt
class Distance:
@staticmethod
def euclideanDistance(xCoor, yCoor):
"""This function check the euclidean distance"""
return sqrt((xCoor - 0) ** 2 + (yCoor - 0) ** 2)
try:
if __name__ == "__main__":
x = int(sys.argv[1])
y = int(sys.argv[2])
print(Distance.euclideanDistance(x, y))
except:
print("enter values")
|
from weather import Weather
from enum import Enum, auto
def getConditions():
weather = Weather()
conditions = weather.get_weather_conditions()
return conditions
# Format and print out the details for each day.
def format_condition_printout(conditions):
if not isinstance(conditions, dict):
raise Exception('Conditions must be a dictionary')
for day, values in conditions.items():
print(f"The conditions for {day} are: ")
print(f" High: {values['high']}")
print(f" Condition: {str(values['condition_name'])}")
print("")
print(f" The Optimal Outreach Method is: {str(map_conditions_to_contact_method(values))}")
print("")
# Take in the condition values (i.e high temp and the condition) and map them to to the contact type
def map_conditions_to_contact_method(condition_values):
condition_temp = int(condition_values['high'])
condition_name = condition_values['condition_name']
contact_method = ContactType.Unknown
if condition_temp > 75 and condition_name == Weather.AggregateWeatherConditions.Sunny:
contact_method = ContactType.Text
elif 55 <= condition_temp <= 75:
contact_method = ContactType.Email
elif condition_temp < 55:
contact_method = ContactType.Phone
else:
contact_method = ContactType.Email
if condition_name == Weather.AggregateWeatherConditions.Raining:
contact_method = ContactType.Phone
return contact_method
class ContactType(Enum):
Unknown = auto()
Text = auto()
Email = auto()
Phone = auto()
def __str__(self):
return self.name
if __name__ == '__main__':
print('---------------------------------------------------------')
print('-- Thank you for requesting the best engagement method --')
print('---------------------------------------------------------')
conditions = getConditions()
format_condition_printout(conditions)
|
import makeBigList
def merge_sort( thelist):
#the base case when the size of thelist =1
if len(thelist)==1:
return thelist
first_half = merge_sort(thelist[0:len(thelist)/2])
second_half = merge_sort(thelist[len(thelist)/2:len(thelist)])
return merge_2_list(first_half,second_half)
def merge_2_list(first_half, second_half):
#make the list of size= first_half+second_half
thelist=[]
list_pointer=0
pointer1=0
pointer2=0
while pointer1<len(first_half) and pointer2<len(second_half):
print pointer1
print pointer2
print list_pointer
if first_half[pointer1]<second_half[pointer2]:
thelist.append(first_half[pointer1])
pointer1+=1
list_pointer+=1
else:
thelist.append(second_half[pointer2])
pointer2+=1
list_pointer+=1
if pointer1 == len(first_half):
#copy over the second list to the final list
for i in range (pointer2, len(second_half)):
thelist.append(second_half[i])
elif pointer2 == len(second_half):
#copy over the first list to the final list
for i in range (pointer1, len(first_half)):
thelist.append(first_half[i])
return thelist
list1 =[2,7,19,25]
list2 = [3,6,8,17,21,22,30,100,120,300]
thelist = merge_2_list(list1,list2)
print str(thelist).strip('[]')
listtest= [5,1,100,2,0,3,9]
half1 = listtest[0:len(listtest)/2]
half2 = listtest[len(listtest)/2:len(listtest)]
print str(half1).strip('[]')
print str(half2).strip('[]')
print str(merge_sort(listtest)).strip('[]')
biglist = makeBigList.makeBigList(200)
print str(merge_sort(biglist)).strip('[]')
|
for i in range(1,11):
for j in range(1,i+1):
print(j,end="")
print()
for i in range(1,11):
for j in range(1,i+1):
print(1,end="")
print()
|
class Stack_Implementation:
def __init_(self,stack_old):
self.stack_old=stack_old
def push_fun(self,value):
self.stack_old=[10,20,30,40]
print("The stack before pushing new element is: ",self.stack_old)
self.stack_old.append(value)
print("The stack after pushing new element is: ",self.stack_old)
def pop_fun(self):
#print("The stack before poping new element is: ",self.stack_old)
#if(len(self.stack_old) <= 0):
# print("The stack is empty. The stack function does not work")
#else:
try:
print("The stack after poping last element is: ",self.stack_old.pop())
except:
print("sorry there is an error")
def peek_fun(self):
#n=len(self.stack_old)
print(self.stack_old[1])
stack_obj=Stack_Implementation()
stack_obj.push_fun(50)
stack_obj.push_fun(60)
stack_obj.pop_fun()
stack_obj.peek_fun()
|
w = float(input())
h = float(input())
i = w/(h*h)
if i < 20:
print('PESO BAJO')
if 20 <i < 25:
print('NORMAL')
if 25 <i < 30:
print('SOBRE PESO')
if 30 <i < 40:
print('OBESIDAD')
if i >= 40:
print('OBESIDAD MORBIDA')
|
from timeit import default_timer as timer
# Selection Sort
file2 = open('20k.txt', 'r')
sortedLines = file2.readlines()
sortedLines.sort() # Using a library Function, to sort the array, this will be used to check my implementation
start = timer()
file1 = open('20k.txt', 'r')
Lines = file1.readlines()
#Implementing Selection Sort
for i in range(0,len(Lines)):
min = i
for j in range(i+1,len(Lines)):
if(Lines[j] < Lines[min]):
min = j
Lines[i],Lines[min] = Lines[min],Lines[i]
end = timer()
print(Lines)
print(Lines == sortedLines) # Comparing to check if my implementation gives a sorted array.
print(end - start) # Finding the total time measurement
|
import hashlib
cipher = hashlib.sha3_256()
print(cipher.name)
print(cipher.digest_size)
cipher.update("hello".encode(encoding="utf-8"))
# # -- python 3 encoding --
# # string is encoded as Unicode by default
# print('1 >> ----')
# print (type('我好'))
# print(str.encode('''我好'''))
# a=b'\xe6\x88\x91'.decode()
# print(type(a))
# print(a=='我')
# print('1 << ----')
# # str.encode() is used to convert a string to bytes
# print('2 >> ----')
# print("abc".encode(encoding="utf-8"))
# print("abc".encode(encoding="cp037"))
# print('2 << ----')
# chr() is used to convert a Unicode code number to a character
# import unicodedata
# print(chr(int('6211',16))) # 我 is 6211 in hex or 25105 in decimal
# # -- python 3 encoding --
s=cipher.digest()
print(s)
rsa_pub=s+s+s+s+s+s+s+s # repeat eight times to get rsa_pub of 2048 bits
|
from random import random
from random import seed
from prompt_toolkit import prompt
class Player():
def __init__(self, name):
self.player_name = name
class Roll():
def __init__(self, name):
self.name = name
self.rolls_i_can_beat = []
self.rolls_that_beat_me = []
def __repr__(self):
return self.name
def can_defeat(self, challenge):
return challenge in self.rolls_i_can_beat
def build_the_three_rolls():
rock = Roll("Rock")
paper = Roll("Paper")
scissors = Roll("Scissors")
rock.rolls_i_can_beat = [scissors]
rock.rolls_that_beat_me = [paper]
paper.rolls_i_can_beat = [rock]
paper.rolls_that_beat_me = [scissors]
scissors.rolls_i_can_beat = [paper]
scissors.rolls_that_beat_me = [rock]
return rock, paper, scissors
def game_loop(player1, player2, rolls):
count = 1
while count < 3:
three_rolls = build_the_three_rolls()
seed()
p2_roll = three_rolls[round(random() * 2)]
p1_roll = three_rolls[round(random() * 2)]
outcome = p1_roll.can_defeat(p2_roll)
print(f"Player 1 rolled: {p1_roll}")
print(f"Player 2 rolled: {p2_roll}")
# display winner for this round
print(f"outcome is - p1 wins?: {outcome}")
count += 1
# Compute who won
def print_header():
print("Welcome to Rock, Paper, Scissors! Python edition :)")
def get_players_name():
return(prompt("Please enter your name: "))
def main():
print_header()
rolls = build_the_three_rolls()
print(rolls)
name = get_players_name()
player1 = Player(name)
player2 = Player("computer")
# Doesn't work yet :)
game_loop(player1, player2, rolls)
if __name__ == "__main__":
main()
|
""" Assignment 6
Create a dictionary of waypoints.
Each waypoint should itself be a dictionary.
Write a loop that will print the name of each city on a new line.
Location Data:
WP1
locale: London
lat: 51.5074° N
lon: 0.1278° W
WP2
locale: Paris
lat: 48.8566° N
lon: 2.3522° E
WP3
locale: New York
lat: 40.7128° N
lon: 74.0060° W
"""
# Answer
location_data = {
"WP1": {
"locale": "London",
"lat": "51.5074° N",
"lon": "0.1278° W",
},
"WP2": {
"locale": "Paris",
"lat": "48.8566° N",
"lon": "2.3522° E",
},
"WP3": {
"locale": "New York",
"lat": "40.7128° N",
"lon": "74.0060° W",
},
}
for wp in location_data.values():
print(wp['locale'])
|
""" Assignment 7
Write a short script that will get a name from the user.
Find the length of the name.
If the length is lower than 5 print "Under".
If the length is more than 5 print "Over".
If the length is exactly 5 print "Five".
Try to use 'if', 'else' and 'elif' exactly once each.
Also, try not to evaluate the length of the name more than once. """
|
""" Assignment 1
Write a short script that will get some information from the user, reformat
the information and print it back to the terminal. """
# Possible Answer
fav_movie = input("What is your favorite movie? ")
print(f"Your favorite movie is: {fav_movie}.")
|
""" Assignment 15
1. Complete the log_this decorator such that it will print the output of the
following `square` function when it is called.
Stretch
1. Make sure the help feature of `square()` still works properly.
2. Write the decorator in such a way to allow for an arbitrary number of
positional and keyword arguments for the original function.
3. Read the documentation for the functools library. """
from functools import wraps # Required for stretch goal
# Answer
def log_this(func):
""" Decorator for logging the result of a function call. """
@wraps(func) # stretch goal
def logger(*args, **kwargs):
result = func(*args, **kwargs)
print(result)
return result
return logger
@log_this
def square(x):
""" Returns the square of x """
return x**2
answer = square(10)
print(answer)
help(square)
|
trau_profile = {
'name': 'Trau',
'job': 'Thuc tap sinh',
'org': 'Trung tam khoa hoc VN',
}
william_profile = {
'name': 'William',
'job': 'Thuc tap sinh',
'org': 'Trung tam khoa hoc VN',
}
tre_profile = {
'name': 'Tre',
'job': 'Tro ly robot',
'org': 'Trung tam khoa hoc VN',
}
profiles = [trau_profile, william_profile, tre_profile]
def search_profile(keyword):
for profile in profiles:
if keyword == profile['name']:
return profile
print('== TIM KIEM HO SO ==')
keyword = input('Nhap ten: ')
profile = search_profile(keyword)
print(profile)
|
import random
# Ask the user for three adjectives
adjectives = input('Give me three adjectives to describe a cat, separated by a comma: ')
# Split the adjectives into a list separated by a comma and print the list
x = adjectives.split(", ")
# Shuffle using random
random.shuffle(x)
print(x)
# Assign three variables to x
ad1, ad2, ad3 = x
ad1 = int(ad1)
ad1 += 1
print('ad1 is now: {}'.format(ad1))
# print("The cat is "+ str(ad1) + ", " + x[1] + "," + x[2] + ".")
print("The cat is {}, {}, and {}.".format(ad1, ad2, ad3))
|
# NUMBER = 12
# snake_case = 6
# number = 'five'
# number = 5
# print(number)
# a = 1
# b = 2
# a = b
# b = 15
# a = b
# print(a)
# a, b = 1, 2
# a, b = b, a
#
# print(a)
# p = print
#
# p('this thing')
def pretty_print(x):
return '({}) {}-{}'.format(x[:3], x[3:6], x[6:])
def something():
phone1 = input('Phone Number?: ')
phone2 = input('Phone Number?: ')
print(pretty_print(phone1))
print(pretty_print(phone2))
something()
|
"""
Contains a series of functions and custom classes,\n
concerning the base of linear algebra,
Matrices and Vectors
Here are the operations:
-- Vectors :
** Vector Dot
** Vector Cross (3D ONLY)
** Vector Addition and Subtraction
** Vector-Scalar Operations
-- Matrices:
** Matrix Multiplication
** Matrix Addition and subtraction
** Matrix-Scalar Operations
** Matrix-Vector Operations
** Trace
** Identity Matrix Generator
** Determinant
** REF (Reduced Echelon Form)
** Inverse Matrix
** Cofactors
** adjugate (transpose)
** Minors
*** Various combinations of the above
"""
from .basic import isNumber,isInteger,isComplex,Number,product
from . import polynomials as pl
from .trigonometric import acos
from .powers import sqrt
from .num_theory import complex_polar
import re
from typing import Union,Any,Dict,Tuple
from . import random as rn
WHITESPACE = ' '
EXCEPTION_MSG : callable = lambda method : f"{method} method was not defined for at least one element in the Matrix.\n(Caused from performing the {method} operation on two elements whose {method} method returns NotImplemented"
EXCEPTION_MSG_v : callable = lambda method : f"{method} method was not defined for at least one element in the Vector.\n(Caused from performing the {method} operation on two elements whose {method} method returns NotImplemented"
epsilon = pl.x #epsilon = lamda
POLY = type(epsilon) #<class 'pythematics.polynomials.Polynomial'>
class Vector:
def __init__(self,array):
self.matrix = array
self.rows = len(self.matrix)
self.collumns = 1
def __str__(self):
print("")
i = 1
for item in self.matrix:
if 'deg' in str(item): #Check if polynomial
item = re.sub(r"\s+",'',str(item).split(":")[-1])
item = f'({item})'
elif 'Multivariable' in str(item): #Check if multinomial
item = re.sub(r"\s+",'',str(item).split(":")[-1])
item = f'{item}'
print(f'R{i}| {item:>3}')
i+=1
s2 = "\n{} x {} Vector array\n".format(self.rows,self.collumns)
return s2
def __repr__(self):
return self.__str__()
def getMatrix(self):
return self.matrix
def getSize(self):
return self.rows
def __getitem__(self,index):
return self.matrix[index]
def __add__(self,value):
empty = []
if type(value) == Vector:
if value.getSize() != self.getSize():
raise ValueError("Cannot multiply non equal-size collumns ({} with {})".format(value.getSize(),self.getSize()))
for i in range(self.getSize()):
empty.append(value.getMatrix()[i] + self.getMatrix()[i])
return Vector(empty)
try:
return self.forEach(lambda y : y + value)
except:
raise EXCEPTION_MSG_v('__add__')
def __radd__(self,value):
return self.__add__(value)
def __sub__(self,value):
empty = []
if type(value) == type(self):
if value.getSize() != self.getSize():
raise ValueError("Cannot multiply non equal-size collumns ({} with {})".format(value.getSize(),self.getSize()))
for i in range(self.getSize()):
empty.append(value.getMatrix()[i] - self.getMatrix()[i])
return Vector(empty)
try:
return self.forEach(lambda y : y - value)
except:
raise ValueError(EXCEPTION_MSG_v("__sub__"))
def __rsub__(self,value):
return -self + value
def __len__(self):
return self.rows
def __mul__(self,value):
"""Vector Multiplication by scalar
if other value is Vector,
the dot product is returned
"""
empty = []
#Scalar or anything else
if type(value) not in (type(self),Matrix):
try:
for item in self.matrix:
empty.append(value*item)
return Vector(empty)
except Exception:
raise ValueError(EXCEPTION_MSG_v("__mul__"))
#Vector of same dimensions
elif type(value) == type(self):
if value.getSize() != self.getSize():
raise ValueError("Cannot multiply non equal-size collumns ({} with {})".format(value.getSize(),self.getSize()))
for num in range(self.getSize()):
empty.append(value.getMatrix()[num] * self.getMatrix()[num])
return sum(empty)
#Another Matrix
elif type(value) == Matrix:
vector_to_matrix = Matrix([[item] for item in self.getMatrix()])
return vector_to_matrix * value
return NotImplemented #Redefine with __rmul__
def __div__(self,value):
try:
return (1/value)*self
except:
raise ValueError(EXCEPTION_MSG_v("__div__"))
def __truediv__(self,value):
return self.__div__(value)
def __rdiv__(self,value):
try:
return self.forEach(lambda y : value / y)
except:
raise ValueError("__rdiv__")
def __rtruediv__(self,value):
return self.__rdiv__(value)
def __pow__(self,value):
try:
return self.forEach(lambda y : y**value)
except:
raise ValueError(EXCEPTION_MSG_v("__pow__"))
def __rpow__(self,value):
try:
return self.forEach(lambda y : value**y)
except:
raise ValueError(EXCEPTION_MSG_v("__rpow__"))
def __neg__(self):
return (-1) * self
def __rmul__(self,scalar : Union[int,float]):
return self.__mul__(scalar)
def __round__(self,ndigits : int = 1):
__tmp__ : list = []
for item in self.getMatrix():
if type(item) is complex:
rounded = complex(round(item.real,ndigits),round(item.imag,ndigits))
else:
rounded = round(item,ndigits)
__tmp__.append(rounded)
return Vector(__tmp__)
def dot(self,Vector) -> Union[float,int]:
return self.__mul__(Vector)
def cross(self,Vector : 'Vector') -> 'Vector':
return cross(self,Vector)
def magnitude(self):
return magnitude(self)
def AngleVector(self,vector1 : "Vector",degrees : bool = False) -> float:
return AngleBetweenVectors(self,vector1,degrees)
def forEach(self,function : callable) -> 'Vector':
return Vector([
function(element) for element in self.getMatrix()
])
class Matrix:
"""
The as you known it from math 'Matrix'\n
It includes custom operations for the following:
** Multiplication
** Addition
** Subtraction
These are also supported not as methods but as seperate functions:
** determinant
** inverse
** Transpose (adjugate)
** Matrix of co-factors (Alternating-Chess pattern sign)
** Matrix of Minors (for each element hide the current row and collumn and find the determinant of the following)
You must pass an array of arrays,\n
Inside the base array the nested lists are considered as the rows,\n
and the collumns are determined vertically\n
Matrices shall be passed in the following format :
[
#Col1 #Col2 #Col3
#Row 1 [num1 , num2 , num3 ... numP],
#Row 2 [num4, num5 , num6 ... numP],
.......... ...
#Row n [numK,numL,numO ... numP]
]
Input :
A = Matrix([
[1,2,3],
[4,5,6],
[7,8,9]
])
Output :
C1 C2 C3
R1 | 1 2 3
R2 | 4 5 6
R3 | 7 8 9
for more specific methods you can use the dir() function
"""
def __init__(self,matrix):
"""Takes an array of arrays of numbers
The arrays inside the array as seen as the rows
"""
if type(matrix) != list:
raise ValueError("Matrix must be an array of arrays.")
self.ROW_LENGTHS = []
for row in matrix:
if type(row) == list:
self.ROW_LENGTHS.append(len(row))
else:
raise ValueError("Every argument inside the base array which is considered as a row should be of type {} (Your array had at least one element that was not of type {})".format(list,list))
if len(self.ROW_LENGTHS) != self.ROW_LENGTHS.count(self.ROW_LENGTHS[0]):
raise ValueError("All rows of a matrix shall only be of same size. not {}".format(self.ROW_LENGTHS))
self.matrix = matrix
self.rows = len(self.matrix)
self.collumns = self.ROW_LENGTHS[0]
self.isSquare = self.rows == self.collumns
self.cols = []
for _ in range(self.ROW_LENGTHS[0]):
self.cols.append([])
for row in self.matrix:
i = 0
for value in row:
self.cols[i].append(value)
i+=1
def rawMatrix(self):
"""Returns the raw array passed in (self.matrix)"""
return self.matrix
def colls(self,index : int = 0) -> list:
"""Returns a collumn when an index is specified (default is 0)"""
return self.cols[index]
def is_square(self) -> bool:
"""Wheter a matrix has the same number of rows as collumns"""
return self.isSquare
def collsAll(self) -> list:
"""Returns an array of all the collumns"""
return self.cols
def row(self,index : int = 0):
"""Returns a specific row given an index (default is 0)"""
return self.matrix[index]
def index(self,row,collumn):
"""Returns the position given the corresponding row and collumn"""
return self.matrix[row][collumn]
def __len__(self):
"""Returns a tuple containng number of rows and collumns (rows,collumns)"""
return (self.rows,self.collumns) # (number of rows,number of collumns)
def __eq__(self,value):
"""Return equality if the arrays are equal"""
if type(value) in (type(self),Vector):
array_item = value.rawMatrix() if type(value) == type(self) else value.getMatrix()
return self.rawMatrix() == array_item
return NotImplemented
def __str__(self):
"""The method called when printing a matrix"""
print("")
x = [item[:] for item in self.matrix]
k = 0
for item in x:
j = 0
if len(item) > 8:
x[k] = item[1:9]
x[k].append("...")
x[k].append(self.cols[-1][k])
j+=1
k+=1
k = 0
y = []
for iteration in range(self.collumns):
if iteration >=8:
y.append("...")
y.append(f'C{self.collumns}')
break
y.append(f"C{iteration+1}")
x.insert(0,y)
j = 1
for item in x:
if j > 9:
print("\n .........")
CACHE = []
for item in x[-1]:
if Number(item):
if type(item) == complex:
y = complex_polar(item)
NEW_ARRAY.append(f"({round(y[0],2)},{round(y[1],2)})")
continue
CACHE.append('{: <10}'.format(round(item,4)))
continue
CACHE.append('{: <10}'.format(item))
print(f' R{len(x)-1}|',*CACHE)
break
item[0] = f'\t{item[0]}'
if j==1:
cols_t = " ".join(["{: <10}" for _ in range(len(item))])
cols_t = cols_t.format(*item)
print(' CI | {}'.format(cols_t))
j+=1
continue
NEW_ARRAY = []
for val in item:
if "..." in str(val):
NEW_ARRAY.append(val)
continue
if not 'deg' in str(val) and not 'Multivariable' in str(val):
val = complex(val)
if val.imag != 0:
com_val = complex(val)
y = complex_polar(com_val)
NEW_ARRAY.append(f"({round(y[0],2)},{round(y[1],2)})")
continue
test = val.real
if test != int(test):
float_rounded = float(test)
if len(str(float_rounded)) >= 10:
value = round(float_rounded,2)
if len(str(value)) >=10:
value = f'{float(val):.2e}'
else:
value = f'{float_rounded:>4}'
else:
if len(str(val)) >= 10:
value = f'{int(test):.2e}'
else:
value = f'{int(test):>3}'
NEW_ARRAY.append(value)
continue
else:
ws_pol = str(val).split(":")[-1]
no_ws_pol = re.sub(r"\s+",r"",ws_pol)
finale = f'({no_ws_pol})'
if not 'Multivariable' in str(val):
if len(finale) <= 7:
NEW_ARRAY.append(f'({no_ws_pol})')
elif 7 < len(finale) <= 9 :
NEW_ARRAY.append(f'{no_ws_pol}')
else:
NEW_ARRAY.append(f'({no_ws_pol})')
else:
NEW_ARRAY.append(f'{no_ws_pol}')
cols_t = " ".join(["{: <10}" for _ in range(len(NEW_ARRAY))])
print(f' R{j-1} |',cols_t.format(*NEW_ARRAY))
j+=1
return f'\n{self.rows} x {self.collumns} Matrix\n'
def __repr__(self):
return self.__str__()
def __round__(self,ndigits : int = 1) -> "Matrix":
"""Method for rounding a Matrix"""
__tmp__ : list = [[] for item in self.rawMatrix()]
i = 0
for row in self.rawMatrix():
for item in row:
if type(item) is complex:
rounded = complex(round(item.real),round(item.imag))
else:
rounded = round(item,ndigits)
__tmp__[i].append(rounded)
i+=1
return Matrix(__tmp__)
def __rmul__(self,scalar):
"""Matrix multiplication by scalar or Matrix (rside)"""
#Multiply Every element of the Matrix by the scalar
if type(scalar) != type(self):
#Special case where it is a vector
if type(scalar) == Vector:
return self.__mul__(adjugate(Matrix(scalar.getMatrix())))
try:
new_matrix = [[] for i in range(self.rows)] #Add the rows
i = 0
for row in self.matrix:
for constant in row:
new_matrix[i].append(constant * scalar)
i+=1
return Matrix(new_matrix)
except:
raise ValueError(EXCEPTION_MSG("__mul__"))
#Type is Matrix
else:
return self.__mul__(scalar)
def __neg__(self):
"""return -Matrix"""
return (-1) * self
def __add__(self,Matrx):
"""
Return the sum beetween two Matrices,
Even though not Mathematically defined, adding a scalar to a Matrix will apply the .forEach method,
since it is very commonly used in operations
"""
#Scalar Operations call .forEach
if type(Matrx) != type(self):
try:
return self.forEach(lambda item : item + Matrx)
except:
raise ValueError(EXCEPTION_MSG("__add__"))
#Row-Collumn Equality (Matrix Addition)
if self.__len__() != Matrx.__len__():
raise ValueError("Rows and Collumns must be equal! {} != {}".format(self.__len__(),Matrx.__len__()))
new_matrix = [[] for row in range(self.rows)]
try:
i = 0
for row in self.matrix:
k = 0
for num in row:
new_matrix[i].append(num+Matrx.rawMatrix()[i][k])
k +=1
i+=1
return Matrix(new_matrix)
except:
raise ValueError(EXCEPTION_MSG("__add__"))
def __radd__(self,value):
return self.__add__(value)
def __rsub__(self,value):
return -self + value
def __sub__(self,Matrx):
"""
Return the difference beetween two Matrices,
Even though not Mathematically defined, subtracting a scalar from a Matrix will apply the .foreach method,
since it is very commonly used in operations
"""
#Even though not Mathematically defined subtracting a scalar from a Matrix will apply the .foreach method
if type(Matrx) != type(self):
scalar = Matrx #Identify the value as a scalar
try:
return self.forEach(lambda item : item - scalar)
except:
raise ValueError(EXCEPTION_MSG("__sub__"))
#Rows and Collumns must be equal in order to add Matrices
if self.__len__() != Matrx.__len__():
raise ValueError("Rows and Collumns must be equal! {} != {}".format(self.__len__(),Matrx.__len__()))
try:
new_matrix = [[] for row in range(self.rows)]
i = 0
for row in self.matrix:
k = 0
for num in row:
new_matrix[i].append(num-Matrx.rawMatrix()[i][k])
k +=1
i+=1
return Matrix(new_matrix)
except:
raise ValueError(EXCEPTION_MSG("__sub__"))
def __mul__(self,value):
"""
Matrix multiplication by another Matrix or scalar
"""
#Any other value or scalar
if type(value) not in (Vector,type(self)):
return self.__rmul__(value)
#Vector
elif type(value) == Vector:
vector_to_matrix = Matrix([[item] for item in value.getMatrix()])
return self * vector_to_matrix
#Matrix Multiplication
else:
row_0 = self.__len__()
col_0 = value.__len__()
if row_0[1] != col_0[0]:
raise ValueError(f"\nCannot multiply a {row_0[0]} x {row_0[1]} with a {col_0[0]} x {col_0[1]} Matrix,\nMatrix 1 must have the same number of rows as the number of collumns in Matrix 2 \n({row_0[1]} != {col_0[0]})")
try:
new_matrix = [[] for i in range(row_0[0])]
COLS_M2 = value.collsAll()
j = 0
for row in self.matrix:
for collumn in COLS_M2:
iterations = 0
total = 0
for scalar in collumn:
total += scalar*row[iterations]
iterations+=1
new_matrix[j].append(total)
j+=1
return Matrix(new_matrix)
except:
raise EXCEPTION_MSG("__mul__")
def __div__(self,scalar):
"""Division by scalar (inverse of scalar time the matrix)"""
if type(scalar) != type(self):
try:
return (1 / scalar) * self
except:
raise ValueError(EXCEPTION_MSG("__div__"))
return NotImplemented
def __rdiv__(self,value):
try:
return self.forEach(lambda x : value / x)
except:
raise ValueError(EXCEPTION_MSG("__rdiv__"))
def __truediv__(self,value):
"""Division by scalar"""
return self.__div__(value)
def __rtruediv__(self, value):
return self.__rdiv__(value)
def __pow__(self,value):
if type(value) != type(self):
try:
return self.forEach(lambda x : x**value)
except:
raise ValueError(EXCEPTION_MSG("__pow__"))
return NotImplemented
def __rpow__(self,value):
if type(value) == type(self):
return NotImplemented
try:
return self.forEach(lambda x : value**x)
except:
raise ValueError(EXCEPTION_MSG("__rpow__"))
def __getitem__(self,index):
"""Return an element of the matrix
A = Matrix([
[1,2,3],
[4,5,6],
[7,8,9]
])
In [1]: A[0][2]
Out[1]: 3
"""
return self.rawMatrix()[index]
def appendCollumn(self,collumn : list) -> None:
assert len(collumn) == len(self.colls(0)), "New Collumn must be of the same size as all the other collumns"
new_matrix = [item[:] for item in self.rawMatrix().copy()]
for i in range(len(collumn)):
new_matrix[i].append(collumn[i])
return Matrix(new_matrix)
def transpose(self):
"""Evaluates the function adjugate(self)"""
return adjugate(self)
def determinant(self):
"""Evaluates the function determinant(self)"""
return determinant(self)
def minors(self):
"""evaluates the function MatrixOfMinors(self)"""
return MatrixOfMinors(self)
def cofactors(self):
"""evaluates the function MatrixOfCofactors(self)"""
return MatrixOfCofactors(self)
def inverse(self):
"""evaluates inverse(self)"""
return inverse(self)
def trace(self):
"""evaluates Trace(self)"""
return Trace(self)
def swap(self,Row1 : int,Row2 : int):
"""Swaps 2 rows given their index"""
val_0=[item for item in self.rawMatrix()[Row1]]
val_1=[item for item in self.rawMatrix()[Row2]]
self.rawMatrix()[Row1] = val_1
self.rawMatrix()[Row2] = val_0
def solve(self,Output : Vector,unknowns : Union[tuple,list],useRef=False) -> dict:
"""Solves the system of linear equations represented by the current Matrix\n
An 'Output' Vector should be provided in order for the augmented Matrix to complete,\n
and also the Name of the unknowns should be provided in order to receive the solutions in order\n
You can also specify useRef=bool on wheter you want to use Row reduction, (if it is et to false
it uses Cramer's rule)
EXAMPLE :
A = Matrix([
[1,2],
[3,4]
])
unknowns = ('x','y')
output = Vector([5,11])
solution = A.solve(output,unknowns)
print(solution)
OUTPUT :
{'x': 1.0, 'y': 2.0}
"""
if not useRef:
return SolveCramer(self,unknowns,Output)
return solveREF(self,unknowns,Output)
def ref(self):
"""Returns the Redcued Echelon Form of the Matrix"""
return ref(self)
def CharacteristicPolynomial(self):
"""Returns a Polynomial whose Roots are
the eigenvalues of that Matrix
"""
return CharacteristicPolynomial(self)
def eigen_values(self,iterations : int = 50):
"""Find the eigenvalues of the Matrix
given that it is square\n
"""
return eigenValues(self,iterations)
def rank(self):
"""Returns the number of linearly independent rows"""
return rank(self)
def forEach(self,function : callable,applyChanges : bool = False) -> Union['Matrix',None]:
"""For each element of the matrix it performs a given function on that element\n
and it either returns a new transform matrix if applyChanges = False,\n
otherwise it returns Nothing and applies the changes to the given Matrix\n
"""
BufferArray = [[] for item in self.matrix]
i = 0
for row in self.matrix:
for num in row:
BufferArray[i].append(function(num))
i+=1
if not applyChanges:
return Matrix(BufferArray)
self.matrix = BufferArray
def removeCollumn(matrix : Matrix,index : int) -> Matrix:
"""Returns a reduced collumn version of a Matrix"""
raw_matrix = [item[:] for item in matrix.rawMatrix()]
for row in raw_matrix:
row.pop(index)
return Matrix(raw_matrix)
def determinant(matrix : Matrix) -> float:
dimensions = matrix.__len__()
if not matrix.is_square():
raise ValueError("Cannot compute determinant of non square matrix : {}".format(dimensions))
if dimensions[0] == 2:
return matrix.rawMatrix()[0][0] * matrix.rawMatrix()[-1][-1] - matrix.rawMatrix()[0][-1]* matrix.rawMatrix()[-1][0]
raw_matrix = matrix.rawMatrix()
tmp = [item[:] for item in raw_matrix]
tmp.pop(0)
i = 0
STORAGE = []
for i in range(matrix.__len__()[0]): #Loop throw the first row
y = removeCollumn(Matrix(tmp),i)
multiplier = raw_matrix[0][i] if (i+1)%2!=0 else -raw_matrix[0][i]
STORAGE.append(multiplier * determinant(y))
i+=1
return sum(STORAGE)
def MatrixOfCofactors(matrix : Matrix) -> float:
"""
Given any NxM Matrix \n :
it reutrns a new Matrix,
that follows the chessboard pattern
"""
if matrix.__len__()[0] == 2:
raise ValueError("Matrix must be more than 2 dimensional")
array = [item[:] for item in matrix.rawMatrix()]
new_array = [[] for item in matrix.rawMatrix()]
i = 0
positive = True
positive_col = True
for row in array:
j = 0
for number in row:
if positive:
new_array[i].append(number)
else:
new_array[i].append(-number)
if j+1 != len(row):
positive = not positive
else:
positive_col = not positive_col
positive = positive_col
j+=1
i+=1
return Matrix(new_array)
def adjugate(matrix : Matrix) -> float:
"""It transposes a given Matrix,"""
array = [item[:] for item in matrix.rawMatrix()]
arrays = [[] for item in matrix.collsAll()]
for row in array:
i = 0
for num in row:
arrays[i].append(num)
i+=1
return Matrix(arrays)
def MatrixOfMinors(matrix : Matrix) -> Matrix:
"""
Given an square Matrix that is not 2x2 it returns a new Matrix,\n
The new Matrix is generated by the determinants generated by the following:\n
** For each item in the Matrix :
** 'Hide' the current collumn and row
** Now compute the determinant of the remaining Matrix
"""
matrix_len = matrix.__len__()
if not matrix.is_square():
raise ValueError("Cannot perfrom Matrix of minors on non-square matrix : {}".format(matrix_len))
matrix_array = [row[:] for row in matrix.rawMatrix()]
j=0
DETERMINANTS = [[] for row in matrix.rawMatrix()]
for row in matrix_array:
i = 0
reduced = [item[:] for item in matrix_array]
reduced.pop(j)
for _ in row:
x = removeCollumn(Matrix(reduced),i)
DETERMINANTS[j].append(determinant(x))
i+=1
j+=1
return Matrix(DETERMINANTS)
def inverse(matrix : Matrix) -> Matrix:
"""
Returns the inverse of a Matrix, if it is invertible (non-zero determinant)
\n=> Find 'Matrix of Minors'; #New Matrix with the determinants of each item of the array
\n=> Find Matrix of co-factors of the previous Matrix; #Alternating chessboard sign
\n=> Transpose (adjugate) that Matrix
\n=> Multiply by 1 / determinant
"""
assert matrix.is_square() , "Cannot Invert non square matrix : {}".format(matrix.__len__())
if matrix.__len__()[0] == 2:
raw = matrix.rawMatrix()
return (1 / determinant(matrix)) * Matrix(
[[raw[-1][-1],-raw[0][-1]],
[-raw[-1][0],raw[0][0]]
])
try:
inverse_determinant = 1 / determinant(matrix)
except:
raise ZeroDivisionError("Matrix is not invertible due to it's determinant being zero")
return inverse_determinant * adjugate(MatrixOfCofactors(MatrixOfMinors(matrix)))
def cross(vector_1 : Vector,vector_2 : Vector) -> Vector:
if (type(vector_1),type(vector_2)).count(Vector) != 2:
raise TypeError("Both arguments must be Vectors not {} and {}".format(type(vector_1),type(vector_2)))
if (len(vector_1.getMatrix()),len(vector_2.getMatrix())).count(3) != 2:
raise ValueError("Cannot perform cross product on non 3-dimensional Vectors : ({},{})".format(len(vector_1.getMatrix()),len(vector_2.getMatrix())))
A = [vector_1.getMatrix(),vector_2.getMatrix()]
DETERMINANTS = []
for i in range(3):
if (i+1)%2==0:
DETERMINANTS.append(-determinant(removeCollumn(Matrix(A),i)))
continue
DETERMINANTS.append(determinant(removeCollumn(Matrix(A),i)))
return Vector(DETERMINANTS)
def IdenityMatrix(dimensions : int) -> Matrix:
if dimensions <= 1:
raise ValueError("Dimensions must be at least 2 (not {}).".format(dimensions))
matrix = []
for i in range(dimensions):
row = []
for k in range(dimensions):
if k == i:
row.append(1)
continue
row.append(0)
matrix .append(row)
return Matrix(matrix)
def Trace(matrix : Matrix) -> Union[int,float]:
"""Returns the sum of the diagnals of a matrix"""
if type(matrix) != Matrix:
raise TypeError("Cannot only perform 'Trace' operation on {} (not {})".format(Matrix,type(matrix)))
if not matrix.is_square():
raise ValueError("Cannot only perform 'Trace' operation square matrices (not {})".format(matrix.__len__()))
raw_matrix = matrix.rawMatrix()
diagnals = []
i = 0 #Track of row_matrix.index(row)
for row in raw_matrix:
j = 0
for num in row:
if j==i:
diagnals.append(num)
break
j+=1
i+=1
return sum(diagnals)
def isSwappable(row : Union[list,int]) -> bool:
for item in row:
if not isNumber(item):
return False
return True
def swap(matrix : Matrix,row1 : Union[list,int],row2 : Union[list,int]):
"""Swapws rows given a list (containg the lements of the row) or the indexes of the rows (RETURNS A COPY OF THE NEW MATRIX)\n
it DOESN'T handle duplicates\n
if you want no matter what to switch rows use the self.swap() function\n
"""
assert type(row1) in (int,list) and type(row2) in (int,list), "Row must either be a list or an index"
i = 0
for row in [row1,row2]:
if type(row) == list:
assert isSwappable(row1),"Instances of classes that are not {} or {} were found".format(int,float) #Check if it contain numbers
else:
if i == 0:
row1 = matrix[row] #Set it equal to the position
else:
row2 = matrix[row]
i+=1
rows = [item[:] for item in matrix.rawMatrix()]
is_duplicate_1 = True if rows.count(row1) > 1 else False
is_duplicate_2 = True if rows.count(row2) > 1 else False
if is_duplicate_1 or is_duplicate_2:
if is_duplicate_1 and is_duplicate_2:
duplicate = "Row 1 and Row 2 : {},{}\n were".format(row1,row2)
else:
duplicate = "Row 1 : {} was".format(row1) if is_duplicate_1 else "Row 2 : {} was".format(row2)
raise ValueError(f'{duplicate} found more than once in the Matrix.')
#Get each index
index_1 = rows.index(row1)
index_2 = rows.index(row2)
rows[index_1] = row2
rows[index_2] = row1
return Matrix(rows)
def SwapNoCopy(matrix : Matrix,row1 : list,row2 : list) -> None:
"""Swaps the rows of a matrix given a list (DOES NOT CREATE A COPY OF THE MATRIX IT THE OPERATIONS ARE PERFORMED ON THE MATRIX)"""
rows = matrix.rawMatrix()
is_duplicate_1 = True if rows.count(row1) > 1 else False
is_duplicate_2 = True if rows.count(row2) > 1 else False
if is_duplicate_1 or is_duplicate_2:
if is_duplicate_1 and is_duplicate_2:
duplicate = "Row 1 and Row 2 : {},{}\n were".format(row1,row2)
else:
duplicate = "Row 1 : {} was".format(row1) if is_duplicate_1 else "Row 2 : {} was".format(row2)
raise ValueError(f'{duplicate} found more than once in the Matrix.')
#Get each index
index_1 = rows.index(row1)
index_2 = rows.index(row2)
rows[index_1] = row2
rows[index_2] = row1
return None
def CreateMatrixPassingCollumns(array_of_arrays : list) -> Matrix:
"""
Instead of passing the rows of the matrix,
you pass the collumns and it creates the matrix
[ #C1 #C2 #C3
[1,2,3],[4,5,6],[7,8,9]
[1,4,7],
[2,5,8],
[3,6,9]
]
"""
counts = []
for row in array_of_arrays:
counts.append(len(row))
if counts.count(counts[0]) != len(counts):
raise ValueError("All arrays inside the base array must have equal lenght!")
ROWS = [[] for item in range(len(array_of_arrays[0]))]
for col in array_of_arrays:
i = 0
for num in col:
ROWS[i].append(num)
i+=1
return Matrix(ROWS)
def combine(r1, r2, scalar):
r1[:] = [x-scalar*y for x,y in zip(r1,r2)]
def divide_by_dividor(li,scalar):
li[:] = [x/scalar for x in li]
def ref(matrix : Matrix) -> Matrix:
"""Returns the reduced echelon form of a matrix (not RREF it does not handle upper diagnals)
EXAMPLE :
Y = Matrix([
[1,2,3],
[4,5,6],
[7,8,9]
])
ref(Y)
CI | C1 C2 C3
R1 | 1.0 1.14 1.29
R2 | 0.0 1.0 2.0
R3 | -0.0 -0.0 1.0
"""
copy = Matrix([item[:] for item in matrix.rawMatrix()]) #Create a copy of the matrix
matrix_copy = copy.rawMatrix()
cur_row=0 #Starting index for rows
for j in range(0,matrix.collumns): #Iterate as much as the number of collumns
max_element = abs(matrix_copy[cur_row][j]) #Find the max element
pos_max = 0
for i,x in enumerate(matrix_copy[cur_row:]):
if abs(x[j])>max_element :
max_element = abs(x[j])
pos_max = i
pos_max += cur_row
temp = matrix_copy[pos_max]
matrix_copy[pos_max]=matrix_copy[cur_row]
matrix_copy[cur_row] = temp
if matrix_copy[cur_row][j]!=0:
divide_by_dividor(matrix_copy[cur_row],matrix_copy[cur_row][j])
pivot = matrix_copy[cur_row]
for i,line in enumerate(matrix_copy[cur_row+1:]):
if line[j]!=0:
combine(line,pivot,line[j])
cur_row+=1
if cur_row==copy.__len__()[0]:
break
return Matrix(matrix_copy)
def isConsistent(coefficient_matrix : Matrix,augmented_matrix : Matrix) -> bool:
"""Determines wheter a system of equations is consistent"""
r1 : int = coefficient_matrix.rank()
r2 : int = augmented_matrix.rank()
return r1 == r2
def SolveCramer(matrix : Matrix,unknowns : Union[tuple,list],outputs : Vector, ContinueOnFail : bool = False ) -> dict:
"""
Solves a system of linear equations given The equations in Matrix format, the names of the unknowns and the desired outputs in a tuple
As the name suggest it uses cramer's rule computing the determinant's of each matrix and dividing the by the determinant of the base matrix
\nThe following system of equations:
-----------
2x+y-z=1
3x+2y-2z=13
4x-2y+3z=9
------------
\nWould be translated into this form:
# For each of the coefficients of the equations put them in a Matrix
matrix = Matrix([
[2, 1, -1],
[3, 2, 2],
[4, -2, 3]
])
# Wrap the desired outputs into a Vector
outputs = Vector([1,13,9])
#Finally wrap your unknowns in a tuple
unknowns = ('x','y','z')
#Apply cramer's rule
print(SolveCramer(matrix,unknowns,outputs))
\nThis would output the following:
{'x': 1.0, 'y': 2.0, 'z': 3.0}
\nif there are no solutions or there are infinetely many of them an Exception is raised
"""
base_determinant = matrix.determinant() #This is the determinant of the base system that always stays constant
#If it is 0 either it has no solution or infinite
if base_determinant==0:
augmented_matrix = matrix.appendCollumn(outputs.getMatrix())
assert isConsistent(matrix,augmented_matrix),"Inconsistent System : 0 Solutions (Coefficient Matrix rank != Augmented Matrix rank)"
if not ContinueOnFail:
raise RuntimeError("Root Calclulation Failed : Determinant is 0 and system has infinite solutions (stopped because ContinueOnFail was {})".format(ContinueOnFail))
return matrix.solve(outputs,unknowns,useRef=True)
raw_outputs = outputs.getMatrix()
determinants = []
for i in range(matrix.collumns): #3
new_matrix = [[] for item in matrix.rawMatrix()]
new_matrix[i].extend(raw_outputs) #Puts the outputs in the right place
not_to_push = matrix.colls(i)
j = 0
for col in matrix.collsAll():
if col != not_to_push:
new_matrix[j].extend(col)
j+=1
determinants.append(determinant(CreateMatrixPassingCollumns(new_matrix)))
variables = {}
for variable in unknowns:
variables[variable] = None
k = 0
for var in variables:
variables[var] = determinants[k] /base_determinant
k+=1
return variables
def solveREF(matrix : Matrix,unknowns : Union[tuple,list],Output: Vector, onFailSetConst : Tuple[int,str,float] = 1) -> dict:
"""Solves a system of linear equations using backsubtitution,
after performing row reduction on a given matrix
What to pass in :
- You must pass the equations in Matrix format
- you must provide the outputs in a Vector object
- You must provide a tuple or a list of the variable names for your Unknwown
\nThe following system of linear equations:
------------
2x+y-z=1
3x+2y+2z=13
4x-2y+3z=9
------------
Would be transleted into this :
Y = Matrix([ #The basic matrix
[2,1,-1],
[3,2,2],
[4,-2,3]
])
unknowns = ('x','y','z') #Each of the unknowns corresponds to a certain collumn
output = Vector([1,13,9]) #The output in Vector format
"""
copy_matrix = Matrix([row[:] for row in matrix])
collumns = [col[:] for col in copy_matrix.collsAll()]
output = Output.getMatrix()
collumns.append(output)
final_matrix = CreateMatrixPassingCollumns(collumns) #matrix from collumns
reduced_matrix = ref(final_matrix) #row reduction performed
#c*z = 0.86 => z = 0.86 / c
try:
z = reduced_matrix.index(-1,-1) / reduced_matrix.index(-1,-2)
except: #No Solutions or infinite
assert isConsistent(copy_matrix,final_matrix),"Inconsistent System : 0 Solutions (Coefficient Matrix rank != Augmented Matrix rank)"
z = onFailSetConst #NOTE : HERE IF THE MATRIX IS CONSISTENT 1 IS PICKED AS THE FINAL VALUE Z (GIVING 1 OF THE INFINITE SOLUTIONS)
VALUES = []
VALUES.append(z) #Begin by having the value of z inside the values
iterable = list(reversed([row for row in reduced_matrix.rawMatrix()]))
iterable.pop(0) #We have already found the first parameter
for row in iterable:
TMP_SUM = []
#All the non-zero elements
target = row.pop(-1)
sub_argument = [item for item in row if item != 0]
divisor = sub_argument.pop(0)
l = 0
for remaining_num in sub_argument:
TMP_SUM.append(remaining_num * list(reversed(VALUES))[l])
l+=1
VALUES.append( (target - sum(TMP_SUM)) / divisor ) #bring the constants to the other side and divide
VALUES = list(reversed(VALUES))
result = {}
m = 0
for var in unknowns:
result[var] = VALUES[m]
m+=1
return result
def Vector0(dimensions : int) -> Vector:
return Vector([0 for _ in range(dimensions)])
def rank(matrix : Matrix) -> int:
"""
The number of non-zero rows on the reduced Matrix,
(Checks if one row is a combination of the other ones)
"""
row_reducted_matrix = ref(matrix)
__rank__ = 0
for row in row_reducted_matrix.rawMatrix():
if row.count(0) != len(row):
__rank__ +=1
return __rank__
def CharacteristicPolynomial(square_maxtirx : Matrix,returnSub : bool = False) -> pl.Polynomial:
"""
Returns a Polynomial whose roots are the eigenvalues of the passed in Matrix,
if returnSub it will return square_maxtirx - lamda_identity, where the lamda
identity is the identity matrix multiplied by lamda
"""
assert square_maxtirx.is_square(), "Non square matrix attempting to find characteristic polynomial"
dim = square_maxtirx.__len__()[0] #dimensions
i_dim = IdenityMatrix(dimensions=dim) #Identity matrix of dimensions N
lamda_identity = i_dim.forEach(lambda n : n * epsilon) #Multiply lamda with Matrix
sub = square_maxtirx - lamda_identity #Subtract from base Matrix lamda multiplied
det = sub.determinant() #The Characteristic Polynomial
if not returnSub:
return det #Return only polynomial
return det,sub #Return determinant and square_matrix - lamda_identity_matrix
def eigenValues(square_maxtirx : Matrix,iterations : int = 50):
"""Returns the eigen values of a given square Matrix"""
char_pol = CharacteristicPolynomial(square_maxtirx)
return char_pol.roots(iterations) #find the roots of the Polynomial
def substitute(expression : Any,term : Union[float,complex]):
if not type(expression) == POLY:
return expression
return expression.getFunction()(term)
def EigenVectors(square_maxtirx : Matrix,iterations : int = 50) -> Dict[Union[complex,float],Vector]:
char_pol = CharacteristicPolynomial(square_maxtirx,returnSub=True)
sub = char_pol[1]
eigen_values = char_pol[0].roots(iterations=iterations) #The roots are the eigen Values
dim = square_maxtirx.__len__()[0] #dimensions
unknowns = [i for i in range(dim)]
output = Vector0(dim)
eigen_values_vectors = {}
for root in eigen_values:
m_0 = sub.forEach(lambda num : substitute(num,root)) #Substitute the Eigen Values in the Lamda scaled Identity Matrix
eigen_vector = m_0.solve(output,unknowns,useRef=True) #Solve the linear system
eigen_vector = Vector([eigen_vector.get(sol) for sol in eigen_vector])
eigen_values_vectors[root] = eigen_vector #Eigen value has a coressponding Vector
return eigen_values_vectors
def magnitude(vector : Vector) -> Union[float,int]:
components = []
for i in range(len(vector)):
components.append(vector[i]**2)
return sqrt(sum(components))
def AngleBetweenVectors(vector_0 : Vector,vector_1 : Vector, degrees : bool = False) -> Union[float,int]:
a : Vector = vector_0
b : Vector = vector_1
div : float = a.dot(b) / (magnitude(a) * magnitude(b))
return acos(div,degrees=degrees)
def randomMatrix(size : tuple) -> Matrix:
"""Generates a random matrix
given a tuple in the format
(rows,collumns)
"""
s = [[] for _ in range(size[1])]
for _ in range(size[0]):
i = 0
for __ in range(size[1]):
s[i].append(rn.random())
i+=1
return Matrix(s)
def randomVector(size : int) -> Vector:
return Vector([
rn.random() for _ in range(size)
])
if __name__ == "__main__":
pass
|
def has_negatives(a):
"""
YOUR CODE HERE
"""
# Your code here
result = []
negatives = {}
a.sort()
for num in a:
if num < 0:
negatives[-num] = num
if num > 0 and num in negatives:
result.append(num)
# print(negatives)
# print(result)
return result
if __name__ == "__main__":
print(has_negatives([-1, -2, 1, 2, 3, 4, -4]))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 15 10:13:42 2019
@author: ChemGrad
"""
"""
# Scope and lifetime of variable
def scopeFunc():
x = 10
print("The value inside function: ", x)
return x
x = 20
scopeFunc()
print("The value outside function: ", x)
def prime(n):
if n < 2:
return False
i = 2
while i**2 <= n:
if n % i == 0:
return False
i += 1
return True
n = int(input("Give an integer to test prime number: "))
print(prime(n))
def reverse(str):
s = ""
for ch in str:
output = str + s
return output
str1 = "ILoveusingComputer"
print ("Given string is: ", str1)
print("The reverse string is: ", reverse(str1))
"""
"""
myFile = open("small_hexagonal_ice.txt", "rt")
content = myFile.read()
myFile.close()
print(content)
"""
"""
mylines = []
with open("sample.txt", "rt") as myfile:
for myline in myfile:
#print(myline)
#print(myline[0:10])
mylines.append(myline)
#print(mylines)
#print(mylines[10])
for element in mylines:
#print)element)
#print(element, end = ' ')
print(mylines[4].find("H2"))
print(mylines[5].find("H2")) # -1 if does not locate substring
"""
myfile = open("create_file.txt", "w+")
myfile.write("The apple is red and the berry is blue!")
myfile.close()
myfile = open("create_file.txt", "rt")
line = myfile.read()
myfile.close()
print(line)
print(line.find("is"))
print(line.rfind("is"))
print(line.count("is"))
print(line.startswith("The"))
print(line.endswith("The"))
print(line.replace("apple", "car").replace("berry", "truck"))
|
import itertools
case_1 = [0, 3, 0, 1, -3]
# Read the input file
matrix = []
with open("input.txt", "r") as f:
for line in f:
#print(line)
tmp = int(line)
matrix.append(tmp)
#tmp = list(line)
#tmp[-1] = tmp[-1].strip()
#tmp = map(int, tmp)
#matrix.append(tmp)
#
print(matrix)
def maze_jumps(list_of_jumps):
jumps = 0
len_list = len(list_of_jumps)
idx = 0
while (idx < len_list):
tmp = list_of_jumps[idx]
list_of_jumps[idx] += 1
idx += tmp
jumps += 1
return jumps
def maze_jumps_2(list_of_jumps):
jumps = 0
len_list = len(list_of_jumps)
idx = 0
while (idx < len_list):
tmp = list_of_jumps[idx]
if tmp >= 3:
list_of_jumps[idx] += -1
else:
list_of_jumps[idx] += 1
idx += tmp
jumps += 1
return jumps
# main #####################
#print(maze_jumps(case_1))
matrix_2 = matrix
#print(maze_jumps(matrix))
print(maze_jumps_2(matrix_2))
|
def divide(sq):
x,y = shape(sq)
TWO, THREE = 2,3
if y != x:
print "ERR(NOOP): Not expecting {} by {} square.".format(x,y)
return sq
if x % 2 == 0 and y % 2 == 0:
WIDTH = TWO
elif x % 3 == 0 and y % 3 == 0:
WIDTH = THREE
sql = sq.split("/")
rows = []
for row in range(0,x,WIDTH):
new_row = []
for col in range(0,x,WIDTH):
new_square = []
for i in range(row, row+WIDTH):
new_square.append(sql[i][col:col+WIDTH])
new_row.append("/".join(new_square))
rows.append(new_row)
return rows
def stitch(rows):
to_stitch = []
x,y = shape(rows[0][0])
for row in rows:
rowm = map(lambda x: x.split("/"), row)
for i in range(x):
new_row = ""
for j in range(len(row)):
new_row += rowm[j][i]
to_stitch.append(new_row)
return "/".join(to_stitch)
def transform(sqs, rules):
for row in range(len(sqs)):
for col in range(len(sqs[0])):
m = search(sqs[row][col], rules)
if len(m) > 1: print "More than one match."
rule = m.pop()
sqs[row][col] = rules[rule]
return sqs
def search(sq, rules):
matches = set()
## search unflipped space
if sq in rules:
matches.add(sq)
r = sq
for _ in range(3):
r = rotate(r)
if r in rules:
matches.add(r)
## search flipped space
flipped = flip(sq)
if flipped in rules:
matches.add(flipped)
rf = flipped
for _ in range(3):
rf = rotate(rf)
if rf in rules:
matches.add(rf)
return matches
def square_print(sq):
print ''
for row in sq.split("/"):
print row
def shape(sq):
s = sq.split("/")
return (len(s), len(s[1]))
def flip(sq):
rows = sq.split("/")
if len(rows[0]) > 3:
print "Unexpected square size {}. No flip."
return sq
res = []
for row in rows:
x = list(row)
x[0],x[-1] = x[-1], x[0]
res.append(''.join(x))
return '/'.join(res)
def rotate(sq):
rows = sq.split("/")
if len(rows[0]) == 3:
r1 = sq[8] + sq[4] + sq[0]
r2 = sq[9] + sq[5] + sq[1]
r3 = sq[10] + sq[6] + sq[2]
return r1 + "/" + r2 + "/" + r3
else:
r1 = sq[3] + sq[0]
r2 = sq[4] + sq[1]
return r1 + "/" + r2
def amatch(sq1, sq2):
return sq1 == sq2
def load_rules(fname):
rules = {}
with open(fname, 'r') as f:
for rule in f.readlines():
key, val = rule.strip().split("=>")
rules[key.strip()] = val.strip()
return rules
def go(start, rules, num=1):
for _ in range(num):
d = divide(start)
t = transform(d, rules)
start = stitch(t)
return start
def count_on(sq):
return sum(map(lambda x: 1 if x=="#" else 0, list(sq)))
if __name__ == "__main__":
FILENAME = 'rules'
start = '.#./..#/###'
rules = load_rules(FILENAME)
res = go(start, rules, num=5)
print "part I:"
print " on after five steps:", count_on(res)
start = '.#./..#/###'
res = go(start, rules, num=18)
print "\npart II:"
print " on after five steps:", count_on(res)
|
from collections import defaultdict
def turing_machine(start, limit):
n,c = 0,0
tape = defaultdict(int)
state = start
while c < limit:
if state == 'A':
if tape[n] == 0:
tape[n] = 1
state = "B"
n+=1
else:
tape[n] = 0
state = "C"
n-=1
elif state == 'B':
if tape[n] == 0:
tape[n] = 1
state = "A"
n-=1
else:
tape[n] = 1
state = "D"
n+=1
elif state == 'C':
if tape[n] == 0:
tape[n] = 0
state = "B"
n-=1
else:
tape[n] = 0
state = "E"
n-=1
elif state == 'D':
if tape[n] == 0:
tape[n] = 1
state = "A"
n+=1
else:
tape[n] = 0
state = "B"
n+=1
elif state == 'E':
if tape[n] == 0:
tape[n] = 1
state = "F"
n-=1
else:
tape[n] = 1
state = "C"
n-=1
elif state == 'F':
if tape[n] == 0:
tape[n] = 1
state = "D"
n+=1
else:
tape[n] = 1
state = "A"
n+=1
c+=1
return tape
def turing_machine_test(start, limit):
n,c = 0,0
tape = defaultdict(int)
state = start
while c < limit:
print 'n:', n
if state == 'A':
if tape[n] == 0:
tape[n] = 1
state = "B"
n+=1
else:
tape[n] = 0
state = "B"
n-=1
elif state == 'B':
if tape[n] == 0:
tape[n] = 1
state = "A"
n-=1
else:
tape[n] = 1
state = "A"
n+=1
c+=1
return tape
if __name__ == "__main__":
STEPS = 12667664
tape = turing_machine("A", STEPS)
ones = 0
for x in tape: ones += tape[x]
print "part I:"
print " checksum: ", ones
|
#Viet cuong trinh tinh cước taxi
# Km đâu là 5000
# 200 m tiep theo là 1000
#Neu lon hon 30km thi moi km se them 3000Đ
while True:
km = int(input("nhap vao so km ma nguoi đi="))
s1 = 5000
if( km == 1):
print(" sô tiền phải trả 1km là =",float(s1))
elif( km >= 30):
print("tong so tien >30km tiếp theo là=",float(s1 + 3000)*km)
else:
print("Số tiền phải trả cho đoạn đường đó la=", float(s1 + 1000)*km)
hoi = input("bạn có muốn chạy lại không: ")
if hoi is "a":
break
print("Thôi nhé! Chúc bạn mạnh khỏe và bình an")
|
print("==============Chuong trinh cau hoi trac nghiem===================")
def switch_funcion(choice):
chi = {
1: "Ban tra loi đung",
2: "ban tra loi sai",
}
return chi.get(choice,"Moi ban chon lai")
print (switch_funcion(1))
print("===========cAU HOI TRAC NGHIE=======")
print("==Chua Gie su sinh ra o dau=====")
print("cau1: Nazzaret\n")
print("cau2: Campiuchi\n")
print("cau3: Thailan\n")
print("cau4: American\n")
a = int(input("Moi ban chon cau hoi="))
def switch(a):
return{
1:"Hoan ho ban, Ban da dung",
2:"Cau vua roi ban nhap sai",
3:" Sai luon",
4:"Xem lai nao",
}.get(a,"moi chon lai")
print(switch(a))
|
a = input(" nhap vao chuoi:")
print("chuoi duoc dao la:", a[:: -1])
#cách 2
b = input(" nhap vao ten bat ki:")
for i in range(1,len(b) + 1):
print(b[-i], end=' ')
|
#'''viet chương trin in ra hình chữ nhật có ích thước m x n'''
# m: chieu ngang - n la chieu doc
#In ra tam giac
n= int(input("nhap vao n="))
for i in range(1, n+1):
for j in range(1, i+1):
print("*", end = "")
print()
#in ra hinh chu nhât
n1= int(input("nhap vao n1="))
m= int(input("nhap vao m="))
for e in range( n1):
for r in range(m):
e = e+1
r = r+1
print("*", end ="")
print()
|
x = "phan thanh chi"
y = 'chi' in x
print(y)
print("do dai chuoi",len(x) -1 )
a =10
b =30
c = a+ b
print('Tong cua no la %d + và %d la %d ' %(a,b,c))
s = f" {a:} {b:} {c}"
print (s)
s1 = 'toi yeu'
s2 = 'lap trinh'
print('{} khong the {}'.format(s1,s2))
# Định dạng chuỗi
#chuoi
#print('Die vao a = {} dien vao b={}'.format(1,2))
print('{: <30}'.format('phan thanh chi'))
print('{: >40}'.format('phan thanh chi'))
print('{: ^50}'.format('phan thanh chi'))
|
def select_name_of_player_with_shortest_name():
return """SELECT name
FROM players
ORDER BY LENGTH(name) ASC
LIMIT 1;"""
def select_all_new_york_players_names():
return """SELECT players.name
FROM players JOIN teams ON players.team_id = teams.id
WHERE teams.name LIKE 'New York%';"""
def select_team_name_and_total_goals_scored_for_new_york_rangers():
return """SELECT teams.name, SUM(score)
FROM teams JOIN team_games ON team_games.team_id = teams.id
WHERE teams.name = "New York Rangers" """
def select_all_games_date_and_info_teams_name_and_score_for_teams_in_nhl():
return """SELECT games.date, games.info, teams.name, team_games.score
FROM teams JOIN team_games ON teams.id = team_games.team_id
JOIN games ON games.id = team_games.game_id
WHERE teams.league_id = 1"""
def select_date_info_and_total_points_for_highest_scoring_nba_game():
return """SELECT games.date, games.info, SUM(team_games.score) AS total_points
FROM team_games
INNER JOIN games, teams, leagues
ON teams.id = team_games.team_id AND games.id = team_games.game_id
AND leagues.id = teams.league_id
WHERE leagues.name = "NBA"
GROUP BY games.date
ORDER BY total_points DESC LIMIT 1;"""
|
import hashlib
text = input("Enter a String : ")
encoded_text = text.encode()
hash_object = hashlib.md5(encoded_text)
md5_hash = hash_object.hexdigest()
print("Code : ",md5_hash)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 19:08:36 2020
@author: mnm
"""
####################
## EXAMPLE: while loops
## Try expanding this code to show a sad face if you go right
## twice and flip the table any more times than that.
## Hint: use a counter
####################
#n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
#while n == "right" or n == "Right":
# n = input("You are in the Lost Forest\n****************\n****** ***\n (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
#print("\nYou got out of the Lost Forest!\n\o/")
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if n == "right" or n == "Right":
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if n == "right" or n == "Right":
n = input("You are in the Lost Forest\n****************\n****************\n :((\n****************\n****************\nGo left or right? ")
while n == "right" or n == "Right":
n = input("You are in the Lost Forest\n****************\n****** ***\n (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
print("\nYou got out of the Lost Forest!\n\o/")
|
from strings import *
from classes import *
from options import *
# User Option numbers and their meanings
QUIT_PROGRAM_NO= 0
READ_BICYCLE_INFO_NO = 1
DISPLAY_WITH_SERVICE_INFO_NO = 2
DISPLAY_SELECTED_BIKE_INFO_NO = 3
ADD_BICYCLE_NO = 4
DO_BICYCLE_MAINTENANCE_NO = 5
RIDE_A_BIKE_NO = 6
# A global State, keeps track of all the global variables such as the name of files, the list of bicycles, and whether it read the file
STATE = {
'bicycle_file_name': '',
'rides_file_name': '',
'bicycles': [],
'did_read_file': False
}
# Function to ask for the file names
def ask_for_file_names():
print_data1_directory()
bicycle_file_name = input(PROMPT_BICYCLE_FILE_NAME)
print_data2_directory()
rides_file_name = input(PROMPT_RIDE_FILE_NAME)
return bicycle_file_name, rides_file_name
# Function to update the state
def update_state():
global STATE
# If I havent read the file or file name is wrong, it will ask for user input
if not STATE['bicycle_file_name'] or not STATE['rides_file_name']:
try:
bicycle_file_name, rides_file_name = ask_for_file_names()
STATE['bicycle_file_name'] = bicycle_file_name
STATE['rides_file_name'] = rides_file_name
STATE['bicycles'] = read_files(STATE)
STATE['did_read_file'] = True
except (NameError, FileNotFoundError) as e:
print(str(e))
STATE['bicycle_file_name'] = ""
STATE['rides_file_name'] = ""
STATE['did_read_file'] = False
return update_state()
# If i Havent read the file, It will try to update_state
elif not STATE['did_read_file']:
try:
STATE['bicycles'] = read_files(STATE)
STATE['did_read_file'] = True
except (NameError, FileNotFoundError) as e:
print(str(e))
STATE['bicycle_file_name'] = ""
STATE['rides_file_name'] = ""
STATE['did_read_file'] = False
print("STATE ERROR SETTING FALSE")
return update_state()
# Function to call apppropriate method depending on user inputs
def choose_option(user_input):
global STATE
# Self Explanatory, Quits program
if (user_input == QUIT_PROGRAM_NO):
print(OPTIONS[QUIT_PROGRAM_NO])
quit()
elif (user_input == READ_BICYCLE_INFO_NO):
print(OPTIONS[READ_BICYCLE_INFO_NO])
update_state()
read_bicycle_info(STATE)
elif (user_input == DISPLAY_WITH_SERVICE_INFO_NO):
print(OPTIONS[DISPLAY_WITH_SERVICE_INFO_NO])
update_state()
display_with_service_info(STATE)
elif (user_input == DISPLAY_SELECTED_BIKE_INFO_NO):
print(OPTIONS[DISPLAY_SELECTED_BIKE_INFO_NO])
update_state()
display_selected_bike_info(STATE)
elif (user_input == ADD_BICYCLE_NO):
print(OPTIONS[ADD_BICYCLE_NO])
update_state()
STATE['bicycles'] = add_cycle(STATE)
write_bicycle_file(STATE)
STATE['did_read_file'] = False
elif (user_input == DO_BICYCLE_MAINTENANCE_NO):
print(OPTIONS[DO_BICYCLE_MAINTENANCE_NO])
update_state()
STATE['bicycles'] = do_bicycle_maintenance(STATE)
write_bicycle_file(STATE)
STATE['did_read_file'] = False
elif (user_input == RIDE_A_BIKE_NO):
print(OPTIONS[RIDE_A_BIKE_NO])
update_state()
ride = ride_a_bike(STATE)
write_ride_file(ride)
else:
raise InvalidInputException(ERROR_INPUT_WRONG)
# Main Function, runs the loop
def main():
while True:
print(MENU)
try:
user_input = int(input(PROMPT_ENTER_OPTION))
choose_option(user_input)
except ValueError as e:
print(ERROR_INPUT_WRONG)
return
except InvalidInputException as e:
print(str(e))
main()
|
board=[[0,0,0,7,0,0,0,0,3],
[0,9,6,0,0,0,0,0,0],
[2,0,0,8,5,0,0,0,0],
[1,7,0,2,0,4,0,3,6],
[0,6,0,0,7,0,0,4,0],
[0,8,2,6,0,3,5,1,0],
[0,0,0,0,1,7,0,0,8],
[0,0,0,0,0,0,2,5,0],
[9,0,0,0,0,2,0,0,0]]
def solve(grid):
find = find_empty(grid)
if not find:
return True
else:
row,col=find
for i in range(1,10):
if (valid(grid,(row,col),i)):
grid[row][col]=i
if solve(grid):
return True
grid[row][col]=0
return False
def printgrid(grid):
i=0
j=0
for i in range(0,9):
if (i%3==0):
print('_'*22)
for j in range(0, 9):
print(str(grid[i][j]),end=' ')
if(j%3==2):
print('|',end=' ')
if(j==8):
print()
break
def find_empty(grid):
for i in range(0, 9):
for j in range(0, 9):
if (grid[i][j] == 0):
return (i,j)
return None
def valid(grid,pos,a):
#check row
for i in range(len(grid)):
if grid[pos[0]][i]==a and pos[1]!=i:
return False
#check column
for i in range(len(grid)):
if grid[i][pos[1]] == a and pos[0] != i:
return False
#check cubes
box_x=pos[1]//3
box_y=pos[0]//3
for i in range (box_y*3,box_y*3+3):
for j in range(box_x*3,box_x*3+3):
if grid[i][j]==a and (i,j)!=pos:
return False
return True
printgrid(board)
solve(board)
print('_______________________________________________________________________________________________________')
print()
printgrid(board)
|
def euclidean_dist(x, y):
if (len(x) == 0 or len(y) == 0 or len(x) != len(y)):
return 0
return ((y[0]-x[0])**2 + (y[1]-x[1])**2) ** (1/2)
def manhattan_dist(x, y):
if (len(x) == 0 or len(y) == 0 or len(x) != len(y)):
return 0
answer = 0
for i in range(len(x)):
answer += abs(x[i]-y[i])
return answer
def jaccard_dist(x, y):
if (len(x) == 0 or len(y) == 0 or len(x) != len(y)):
return 0
answer1 = 0
for i in range(len(x)):
if (x[i] != y[i]):
answer1 += 1
return answer1/len(x)
def cosine_sim(x, y):
if (len(x) == 0 or len(y) == 0 or len(x) != len(y)):
return 0
ans1 = 0
ans2 = 0
ans3 = 0
for i in range(len(x)):
ans1 += x[i]*y[i]
ans2 += x[i]**2
ans3 += y[i]**2
return ans1/((ans2**(1/2)) * (ans3**(1/2)))
# Feel free to add more
|
#!/usr/bin/python
from __future__ import print_function
import sys
def StairCase(n):
for i in xrange(n+1) :
for j in xrange(n-i) :
print (' ',end='',sep='')
for k in xrange(i) :
print ('#',end='',sep='')
print ('\n',end='',sep='')
_n = int(input());
StairCase(_n)
|
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets
import matplotlib.pyplot as plt
dataset = datasets.load_digits()
clf = KNeighborsClassifier(n_neighbors=3)
X,Y = dataset.data[:-10], dataset.target[:-10]
clf.fit(X,Y)
print('Prediction:',clf.predict(dataset.data)[-9])
plt.imshow(dataset.images[-9], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
|
import random
async def get_color() -> int:
"""
Generates a random hexadecimal color.
Returns:
color: int - a hexadecimal number.
"""
# Generate a random color
color = "%06x" % random.randint(0, 0xFFFFFF)
# Convert to int for it to work
color = int(color, 16)
return color
|
def var(n,s,g):
sum=n+s+g
print(sum)
print("average",sum/3)
n=int(input("any number"))
s=int(input("any number"))
g=int(input("any number"))
var(n,s,g)
|
def divisible(limit):
i=0
sum=0
while i<=limit:
if i%3==0 and i%5==0:
sum=sum+i
i=i+1
print(sum)
limit=int(input("any number"))
divisible(limit)
|
import threading
import time
def run(n):
print('task:', n)
time.sleep(2)
print('task done:', n)
start_time = time.time()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
# t.setDaemon(True)
t.start()
print('cost:', time.time()-start_time)
print("all thread is done", threading.current_thread(), threading.active_count())
# time.sleep(2)
# print('111')
|
# importing the needed libraries
from sklearn.metrics import accuracy_score
from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pandas as pd
# reaading the data
irisData = pd.read_csv('Iris.csv')
print(irisData) # checking the imported dataset
# setting the dependent and independent variables as x and y
x = irisData[['SepalLengthCm', 'SepalWidthCm',
'PetalLengthCm', 'PetalWidthCm']].values
y = irisData['Species'].values
# using LabelEncoder to preprocess the data
le = LabelEncoder()
y = le.fit_transform(y)
print(y) # checking the preprocessed data of the Species
# splitting the dataset into training an testing data
# setting the training size to 70% and testing size to 30%
x_train, x_test, y_train, y_test = train_test_split(
x, y, test_size=0.3, train_size=0.7)
# assigning the DecisionTreeClasssifier() method to the a variable
dTreeClasssifier = tree.DecisionTreeClassifier()
# using the DecisionTreeClassifier() method to fit the training data
dTreeClasssifier.fit(x_train, y_train)
# using the DecisionTreeClassifier() method to make a prediction using the x_test data
predictions = dTreeClasssifier.predict(x_test)
# printing the accuracy of the prediction
print('The Accuracy of the Decision Tree Clasifier is: ' +
str(accuracy_score(y_test, predictions)))
|
def calculator(num1, num2, operator):
'''
recieve input from user of two numbers and an operator and compeletes the task
Asks user for an equation, each input seperated by a space. Depending on the operator the user gives,
The function will either add(+), subtract(-), multiply(*), divide(/), integer division(//), or power(**).
If anything is invalid, it will return False
Parameter
---------
num1: int
first string inputed by user
operator: str
second string inputed by user
num2: int
third string inputed by user
Returns
-------
float
the answer to the equation
Example
-------
python3 calculator.py
Enter equation: 10 + 11
21
'''
list = ['+','-','*','/','//','**']
for i in list:
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
if num2 == 0:
return False
else:
return num1 / num2
elif operator == '//':
if num2 == 0:
return False
else:
return num1 // num2
elif operator == '**':
return num1 ** num2
else:
return False
def parse_input():
num1, operator, num2 = input ("Enter equation: ").split()
return calculator(int(num1), int(num2), operator)
|
# coding:utf-8
import tkinter as tk
class Ball:
def __init__(self,x,y,dx,dy,color):
self.x=x
self.y=y
self.dx=dx
self.dy=dy
self.color=color
def move(self,canvas):
self.erase(canvas)
self.x=self.x+self.dx
self.y=self.y+self.dy
self.draw(canvas)
if self.x >= canvas.winfo_width():
self.dx=-1
if self.x <= 0:
self.dx=+1
if self.y >= canvas.winfo_height():
self.dy=-1
if self.y <= 0:
self.dy = +1
def erase(self,canvas):
canvas.create_oval(self.x-20,self.y-20,self.x+20,self.y+20,fill="white",width=0)
def draw(self,canvas):
canvas.create_oval(self.x-20,self.y-20,self.x+20,self.y+20,fill=self.color,width=0)
class Rectangle(Ball):
def erase(self,canvas):
canvas.create_rectangle(self.x-20,self.y-20,self.x+20,self.y+20,fill="white",width=0)
def draw(self,canvas):
canvas.create_rectangle(self.x-20,self.y-20,self.x+20,self.y+20,fill=self.color,width=0)
class Triangle(Ball):
def erase(self,canvas):
canvas.create_polygon(self.x-20,self.y-20,self.x+20,self.y+20,self.x-20,self.y+20,fill="white",width=0)
def draw(self,canvas):
canvas.create_polygon(self.x-20,self.y-20,self.x+20,self.y+20,self.x-20,self.y+20,fill=self.color,width=0)
balls=[
Ball(400,300,1,1,"red"),
Rectangle(400,300,-1,1,"blue"),
Triangle(400,300,1,-1,"green")
]
def loop():
for b in balls:
b.move(canvas)
root.after(10,loop)
root=tk.Tk()
root.geometry("600x400")
canvas=tk.Canvas(root,width=600,height=400,bg="white")
canvas.place(x=0,y=0)
root.after(10,loop)
root.mainloop()
|
# Strings Exercise 1: Uppercase a String
s = ("this is a string. is it upper or lower case?").upper()
print(s)
# Strings Exercise 2: Capitalize a String
s = ("this is a string. Is it upper or lower case?").capitalize()
print(s)
# Strings Exercise 3: Reverse a String
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))
# Strings Exercise 4: Leetspeak
word = input('The word: ').upper()
# A => 4
# E => 3
# G => 6
# I => 1
# O => 0
# S => 5
# T => 7
word = word.replace('A', '4')
word = word.replace('E', '3')
word = word.replace('G', '6')
word = word.replace('I', '1')
word = word.replace('O', '0')
word = word.replace('S', '5')
word = word.replace('T', '7')
print(word)
# Strings Exercise 5: Long-long Vowels
word = 'cheese'
word2 = 'Good'
word3 = 'Man'
word4 = 'Spoon'
word = word.replace('ee', 'eeeee')
word2 = word2.replace('oo', 'ooooo')
word4 = word4.replace('oo', 'ooooo')
print(word)
print(word2)
print(word3)
print(word4)
# Strings Exercise 6: Caesar Cipher
secret = "Lbh zhfg hayrnea, jung lbh unir yrnearq."
offset = 13
alphabet = 'abcdefghijklmnopqrstuvwxyz'
result = ''
for char in secret:
ascii_code = ord(char)
is_uppercase = ascii_code >= 65 and ascii_code <= 90
char = char.lower()
if char not in alphabet:
new_char = char
else:
idx = alphabet.find(char)
new_idx = idx + offset
if new_idx > 25:
new_idx = new_idx - 26
new_char = alphabet[new_idx]
if is_uppercase:
new_char = new_char.upper()
result += new_char
print(result)
|
raw_input = input("What is your name? ")
name = str(raw_input)
print ("Hello, " + raw_input +"!")
|
# encoding: UTF-8
# Autores: Irma Gómez, Victor Curiel, Francisco Arenas
# Introduction to graph theory (Binary Tree implementation)
class Nodo():
#Constructor
def __init__(self, valor):
self.valor = valor
self.nodoIzquierda = None
self.nodoDerecha = None
class BinaryTree():
#Constructor
def __init__(self):
self.root = None
#Metodo para añadir elementos. Se complementa con un metodo recursivo
def agregarNodo(self, valor):
if (self.root is None):
self.root = Nodo(valor)
else:
self.adicionRecursiva(valor, self.root)
def adicionRecursiva(self, valor, nodoActual):
if (valor < nodoActual.valor):
if (nodoActual.nodoIzquierda is None):
nodoActual.nodoIzquierda = Nodo(valor)
else:
self.adicionRecursiva(valor, nodoActual.nodoIzquierda)
elif (valor > nodoActual.valor):
if (nodoActual.nodoDerecha is None):
nodoActual.nodoDerecha = Nodo(valor)
else:
self.adicionRecursiva(valor, nodoActual.nodoDerecha)
else:
print("El valor: ", valor," ya se encuentra dentro del árbol:) ")
#Impresión basada en el código de J.V sacado de la página:
#https://stackoverflow.com/questions/34012886/print-binary-tree-level-by-level-in-python/34013268#34013268
def printTree(self):
if (self.root != None):
lineas, *_ = self._printTree(self.root)
for linea in lineas:
print(linea)
def _printTree(self, nodo_Actual):
#No hay nodos a la izquierda y a la derecha
if (nodo_Actual.nodoDerecha is None and nodo_Actual.nodoIzquierda is None):
linea = '%s' % nodo_Actual.valor
ancho = len(linea)
altura = 1
centro = ancho // 2
return [linea], ancho, altura, centro
#Nodo a la izquierda
#Las variables x,y,z reemplazan a las variables n,p,x del código original
#Las variables i,j reemplazan a la variables s,u del código original
if (nodo_Actual.nodoDerecha is None):
lineas, x, y, z = self._printTree(nodo_Actual.nodoIzquierda)
i = '%s' % nodo_Actual.valor
j = len(i)
primeraLinea = (z + 1) * ' ' + (x - z - 1) * '_' + i
segundaLinea = z * ' ' + '/' + (x - z - 1 + j) * ' '
desplazoLinea = [linea + j * ' ' for linea in lineas]
return [primeraLinea, segundaLinea] + desplazoLinea, x + j, y + 2, x + j // 2
#Nodo a la derecha
#Las variables x,y,z reemplazan a las variables n,p,x del código original
#Las variables i,j reemplazan a la variables s,u del código original
if (nodo_Actual.nodoIzquierda is None):
lineas, x, y, z = self._printTree(nodo_Actual.nodoDerecha)
i = '%s' % nodo_Actual.valor
j = len(i)
primeraLinea = i + z * '_' + (x - z) * ' '
segundaLinea = (j + z) * ' ' + '\\' + (x - z - 1) * ' '
desplazoLinea = [j * ' ' + linea for linea in lineas]
return [primeraLinea, segundaLinea] + desplazoLinea, x + j, y + 2, j // 2
#Nodos en ambos extremos (Izq. y Der.)
#Las variables x,y,z reemplazan a las variables n,p,x del código original
#Las varaibles a,b,c reemplazan a las variables m,q,y del código original
#Las variables i,j reemplazan a las variables s,u del código original
#Las variables q,r reemplazan a las variables a,b del código original
izquierda, x, y, z = self._printTree(nodo_Actual.nodoIzquierda)
derecha, a, b, c = self._printTree(nodo_Actual.nodoDerecha)
i = '%s' % nodo_Actual.valor
j = len(i)
primeraLinea = (z + 1) * ' ' + (x - z- 1) * '_' + i + c * '_' + (a - c) * ' '
segundaLinea = z * ' ' + '/' + (x - z - 1 + j + c) * ' ' + '\\' + (a - c - 1) * ' '
if (y < b):
izquierda += [x * ' '] * (b - y)
elif (b < y):
derecha += [a * ' '] * (y - b)
lineasComprimidas = zip(izquierda, derecha)
lineas = [primeraLinea, segundaLinea] + [q + j * ' ' + r for q, r in lineasComprimidas]
return lineas, x + a + j, max(y, b) + 2, x + j // 2
#Se salen de las clases y se crean funciones con las que se podrán ejecutar el programa
def userInput():
print('''
----------------------------------------------
IMPLEMENTACIÓN DE BINARY TREE:
1. Probar Binary Tree
2. Conocer quienes hicieron el programa
0. Salir
----------------------------------------------
''')
opcion = int(input('¿Qué desea hacer? '))
return opcion
def autores():
print('''
Autor: Carrera: Matrícula:
Irma Gómez (ITI) A01747743
Victor Curiel (ISC) A01747245
Francisco Arenas (ISC) A01369122
''')
def creacionLista(archivo):
lectura = open(archivo, 'r')
contenido = lectura.read()
contenido = contenido.replace("{","")
contenido = contenido.replace("\n","")
contenido = contenido.replace("}","")
lista=contenido.split(",")
lista=list(map(int,lista))
return lista
def binaryTree(inputList):
arbolBinario = BinaryTree()
for valor in inputList:
arbolBinario.agregarNodo(valor)
arbolBinario.printTree()
def main():
opcion = userInput()
while opcion != 0:
if opcion == 1:
archivo = input("Escriba el nombre del archivo con extensión .txt: ")
lista = creacionLista(archivo)
binaryTree(lista)
opcion = userInput()
elif opcion == 2:
autores()
opcion = userInput()
else:
print("Opción no disponible!")
opcion = userInput()
main()
|
import numpy as np
from sigmoid import sigmoid
def lrCostFunction(theta, X, y, _lambda):
#LRCOSTFUNCTION Compute cost and gradient for logistic regression with
#regularization
# J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using
# theta as the parameter for regularized logistic regression and the
# gradient of the cost w.r.t. to the parameters.
# Initialize some useful values
m = y.shape[0] # number of training examples
# You need to return the following variables correctly
J = 0
theta = theta.reshape((np.size(theta),1))
grad = np.zeros_like(theta)
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular choice of theta.
# You should set J to the cost.
# Compute the partial derivatives and set grad to the partial
# derivatives of the cost w.r.t. each parameter in theta
#
# Hint: The computation of the cost function and gradients can be
# efficiently vectorized. For example, consider the computation
#
# sigmoid(X * theta)
#
# Each row of the resulting matrix will contain the value of the
# prediction for that example. You can make use of this to vectorize
# the cost function and gradient computations.
#
# Hint: When computing the gradient of the regularized cost function,
# there're many possible vectorized solutions, but one solution
# looks like:
# grad = (unregularized gradient for logistic regression)
# temp = theta;
# temp(1) = 0; # because we don't add anything for j = 0
# grad = grad + YOUR_CODE_HERE (using the temp variable)
#
J = (-y.T @ np.log(sigmoid(X @ theta)) - (1-y).T @ np.log(1-sigmoid(X @ theta))) / m
J += (_lambda / (2*m)) * (theta[1:].T @ theta[1:]) #np.sum(np.square(theta)) 를 theta 끼리의 dot product 로 구할 수 있다.
#0 번 index 는 제외.
grad = (X.T @ (sigmoid(X @ theta) - y)) / m
grad[1:] += (_lambda / m) * theta[1:] #0 번 index 는 제외.
grad = grad.flatten()
return J, grad
# =============================================================
|
import numpy as np
from computeCostMulti import computeCostMulti
def gradientDescentMulti(X, y, theta, alpha, num_iters):
#GRADIENTDESCENTMULTI Performs gradient descent to learn theta
# theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by
# taking num_iters gradient steps with learning rate alpha
# Initialize some useful values
m = y.shape[0] # number of training examples
J_history = np.zeros((num_iters, 1))
for i in range(num_iters):
# ====================== YOUR CODE HERE ======================
# Instructions: Perform a single gradient step on the parameter vector
# theta.
#
# Hint: While debugging, it can be useful to print out the values
# of the cost function (computeCostMulti) and gradient here.
#
theta -= alpha * np.dot(X.T, (np.dot(X, theta) - y.reshape(m,1))) / m
# (3,m) x ((m,3) x (3,1) - (m,1)) = (3,1)
# Save the cost J in every iteration
J_history[i,0] = computeCostMulti(X, y, theta)
return theta, J_history
# ============================================================
|
import numpy as np
import math
def multivariateGaussian(X, mu, sigma2):
#MULTIVARIATEGAUSSIAN Computes the probability density function of the
#multivariate gaussian distribution.
# p = MULTIVARIATEGAUSSIAN(X, mu, Sigma2) Computes the probability
# density function of the examples X under the multivariate gaussian
# distribution with parameters mu and Sigma2. If Sigma2 is a matrix, it is
# treated as the covariance matrix. If Sigma2 is a vector, it is treated
# as the \sigma^2 values of the variances in each dimension (a diagonal
# covariance matrix)
#
'''
# case1 : Original Gaussian model
# 이것을 적용해도 잘 나온다.
p = (1 / np.sqrt(2 * math.pi * sigma2)) * np.exp(-(((X - mu) ** 2) / (2 * sigma2)))
# 각각의 feature 에 대한 p(x) 들을 구하고 이들을 전부 곱한다.(모든 열을 곱한다.)
# reduce reference : https://numpy.org/doc/stable/reference/generated/numpy.ufunc.reduce.html
p = np.multiply.reduce(p,axis=1)
'''
# case2 : MultivariateGaussian
k = np.size(mu)
if(sigma2.ndim == 1):
sigma2 = np.diag(sigma2)
# bsxfun 은 python 에서의 broadcasting. 앞선 exercise 에서 언급했었다.
# 아래 공식은 당연히 암기할 필요 x
X = X - mu
p = (2 * math.pi)**(-k / 2) * np.linalg.det(sigma2)**(-0.5) *\
np.exp(-0.5 * np.sum(X @ np.linalg.pinv(sigma2) * X, axis=1))
return p
|
from plotData_ex2 import plotData
import matplotlib.pyplot as plt
import numpy as np
from mapFeature import mapFeature
def plotDecisionBoundary(theta, X, y):
#PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
#the decision boundary defined by theta
# PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the
# positive examples and o for the negative examples. X is assumed to be
# a either
# 1) Mx3 matrix, where the first column is an all-ones column for the
# intercept.
# 2) MxN, N>3 matrix, where the first column is all-ones
# Plot Data
plotData(X[:,1:3], y)
if X.shape[1] <= 3:
# Only need 2 points to define a line, so choose two endpoints
plot_x = [np.min(X[:,1]) - 2, np.max(X[:,1]) + 2] #x축 기준 가장 작은 spot - 2, 가장 큰 spot + 2 (양 끝 x 값 설정)
# Calculate the decision boundary line
plot_y = (-1/theta[2])*(theta[1]*plot_x + theta[0]) #(theta_0 * x_0) + (theta_1 * x_1) + (theta_2 * x_2) = 0 방정식을 풀자.
# Plot, and adjust axes for better viewing
plt.plot(plot_x, plot_y)
# Legend, specific for the exercise
plt.legend(['Decision Boundary','Admitted', 'Not admitted'])
plt.axis([30, 100, 30, 100]) #축 범위 지정
else:
# Here is the grid range
u = np.linspace(-1, 1.5, 50)
v = np.linspace(-1, 1.5, 50)
z = np.zeros((np.size(u), np.size(v)))
# Evaluate z = theta*x over the grid
for i in range(np.size(u)):
for j in range(np.size(v)):
z[i,j] = mapFeature(u[i], v[j]) @ theta
z = z.T # important to transpose z before calling contour
# Plot z = 0
# Notice you need to specify the range [0, 0]
plt.contour(u, v, z, 0, linewidths=2) #중간에 0 은 등고선(line) 을 하나만 그리겠다는 의미. (n+1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.