text stringlengths 37 1.41M |
|---|
# ============== Set row and col to None ==========
# Time: O((mn)^2)
# Space: O(1)
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0]:
return
len_row = len(matrix)
len_col = len(matrix[0])
for row in xrange(len_row):
for col in xrange(len_col):
# If was 1, turn to 2
if matrix[row][col] == 0:
# Update entire row
for r in xrange(len_row):
if matrix[r][col] != 0:
matrix[r][col] = None
# Update entire col
for c in xrange(len_col):
if matrix[row][c] != 0:
matrix[row][c] = None
# Recover
for row in xrange(len_row):
for col in xrange(len_col):
if not matrix[row][col]:
matrix[row][col] = 0
# ================ Use first row and col to store the state of that row or col
# Time: O(mn)
# Space: O(1)
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0]:
return
col0, len_row, len_col = matrix[0][0], len(matrix), len(matrix[0])
for row in xrange(len_row):
if matrix[row][0] == 0:
col0 = 0
for col in xrange(1, len_col):
if matrix[row][col] == 0:
matrix[row][0] = matrix[0][col] = 0
for row in xrange(1, len_row):
for col in xrange(1, len_col):
if matrix[row][0] == 0 or matrix[0][col] == 0:
matrix[row][col] = 0
if matrix[0][0] == 0:
for col in xrange(len_col):
matrix[0][col] = 0
if col0 == 0:
for row in xrange(len_row):
matrix[row][0] = 0
|
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
"""
# ============= BFS ================
# Time: O(w*wl + w*c)
"""
w = len(word)
wl = len(wordList)
c = # of distinct chars
"""
# Space: O(wl + wl + c)
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
# O(len(word)*len(wordList))
d = set()
all_chars = set()
for w in wordList:
d.add(w)
for c in w:
all_chars.add(c)
if endWord not in d:
return 0
visited = set([beginWord])
level = 0
q = collections.deque([beginWord])
# O(len(wordList))
while len(q) > 0:
level += 1
print q
cur_len = len(q)
for i in xrange(cur_len):
cur_word = q.pop()
# O(len(word))
for c in xrange(len(cur_word)):
# O(distinct chars)
for next_c in all_chars:
if cur_word[c] == next_c:
continue
next_word = cur_word[:c] + next_c + cur_word[c+1:]
if next_word == endWord:
return level + 1
if next_word in d and next_word not in visited:
q.appendleft(next_word)
visited.add(next_word)
return 0
# =============== two end bfs ===================
class Solution(object):
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if not wordList:
return 0
d = set(wordList)
if endWord not in d:
return 0
begin = set([beginWord])
end = set([endWord])
visited = set([beginWord, endWord])
level = 1
while len(begin) > 0 and len(end) > 0:
if len(begin) > len(end):
begin, end = end, begin
tmp = set()
for w in begin:
for c in xrange(len(w)):
for next_c in xrange(ord('a'), ord('z') + 1):
next_char = chr(next_c)
if next_char == w[c]:
continue
next_word = w[:c] + next_char + w[c+1:]
if next_word in end:
return level + 1
if next_word in d and next_word not in visited:
tmp.add(next_word)
visited.add(next_word)
begin = tmp
level += 1
return 0
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
######## Resursion ############
# Best time: 48ms
# Time Complexity: O(n)
# Space Complexity: O(n)
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
result = []
self.helper(root, "", result)
return result
def helper(self, root, current_path, result):
if root is None:
return
current_path = current_path + "->%s" % root.val
if root.left is None and root.right is None:
result.append(current_path[2:])
return
self.helper(root.left, current_path, result)
self.helper(root.right, current_path, result) |
"""
Given an circular integer array (the next element of the last element is the first element), find a continuous subarray in it, where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number.
If duplicate answers exist, return any of them.
Have you met this question in a real interview? Yes
Example
Give [3, 1, -100, -3, 4], return [4,1].
"""
# ============= keep both max and min ==============
# Time: O(n)
# Space: O(1)
class Solution:
# @param {int[]} A an integer array
# @return {int[]} A list of integers includes the index of the
# first number and the index of the last number
def continuousSubarraySumII(self, A):
# Write your code here
if not A:
return []
min_sum, min_start, min_end = float('inf'), -1, -1
max_sum, max_start, max_end = float('-inf'), -1, -1
r_max_start, r_max_end = -1, -1
r_min_start, r_min_end = -1, -1
cur_min, cur_max = 1, -1
all_sum = 0
for i in xrange(len(A)):
a = A[i]
all_sum += a
if cur_max < 0:
cur_max = a
max_start = max_end = i
else:
cur_max += a
max_end = i
if cur_max > max_sum:
max_sum = cur_max
r_max_start, r_max_end = max_start, max_end
if cur_min > 0:
cur_min = a
min_start = min_end = i
else:
cur_min += a
min_end = i
if cur_min < min_sum:
min_sum = cur_min
r_min_start , r_min_end = min_start, min_end
# this is for the case where all are negative
# return the largest negative.
if all_sum == min_sum:
return [r_max_start, r_max_end]
# this is for max range wraps
elif all_sum - min_sum > max_sum:
return [r_min_end + 1, r_min_start - 1]
# for all other case, max is within range
return [r_max_start, r_max_end]
|
# ======== Pointers ==============
# Time: O(n)
# Space: O(n)
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
s_list = list(s)
l = 0
r = len(s_list) - 1
while l < r:
s_list[l], s_list[r] = s_list[r], s_list[l]
l += 1
r -= 1
return ''.join(s_list)
"""
cheating:
return s[::-1]
return ''.join(reversed(s))
"""
"""
def reverseString(self, s):
if len(s)<=1:
return s
n=len(s)
return self.reverseString(s[n//2:])+self.reverseString(s[:n//2])
"""
|
"""
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
"""
# ============ Binary Search ============
# Time: O(log(n))
# Space: O(1)
# Trap: mid overflow, not a python problem, but use long in JAVA
class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
if not num or num < 0:
return False
if num <= 1:
return True
left, right = 1, num
while left < right:
mid = (left + right)/2
mid_square = mid**2
if mid_square == num:
return True
if mid_square > num:
right = mid
else:
left = mid + 1
return False
|
"""
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
How we serialize an undirected graph:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
Have you met this question in a real interview? Yes
Example
return a deep copied graph.
"""
# =========== BFS ================
# Time: O(n)
# Space: O(n)
# Definition for a undirected graph node
# class UndirectedGraphNode:
# def __init__(self, x):
# self.label = x
# self.neighbors = []
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def __init__(self):
self.dict = {}
def cloneGraph(self, node):
# write your code here
if not node: return None
self.dict[node] = UndirectedGraphNode(node.label)
q = collections.deque([node])
while len(q) > 0:
cur_node = q.pop()
cur_node_copy = self.dict[cur_node]
for n in cur_node.neighbors:
if self.dict.has_key(n):
cur_node_copy.neighbors.append(self.dict[n])
else:
new_neighbor = UndirectedGraphNode(n.label)
self.dict[n] = new_neighbor
cur_node_copy.neighbors.append(new_neighbor)
q.appendleft(n)
return self.dict[node]
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
class Solution(object):
prev = TreeNode(-sys.maxint - 1)
node1 = None
node2 = None
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.helper(root)
self.node1.val, self.node2.val = self.node2.val, self.node1.val
def helper(self, root):
if not root:
return
self.helper(root.left)
if not self.node1 and self.prev.val >= root.val:
self.node1 = self.prev
if self.node1 and self.prev.val >= root.val:
self.node2 = root
self.prev = root
self.helper(root.right)
#============== Morris Traversal =======================
# Time: O(n)
# Space: O(1)
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
node1 = None
node2 = None
prev = None
while root:
if not root.left:
if not node1 and prev and root.val <= prev.val:
node1 = prev
if node1 and root.val <= prev.val:
node2 = root
prev = root
root = root.right
else:
predecessor = root.left
while predecessor.right and predecessor.right is not root:
predecessor = predecessor.right
if not predecessor.right:
predecessor.right = root
root = root.left
else:
predecessor.right = None
if not node1 and prev and root.val <= prev.val:
node1 = prev
if node1 and root.val <= prev.val:
node2 = root
prev = root
root = root.right
node1.val, node2.val = node2.val, node1.val
|
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
def gaussian(x,x0,xsig):
'''
function to calculate the gaussian probability (its normed to Pmax and given in log)
INPUT:
x = where is the data point or parameter value
x0 = mu
xsig = sigma
'''
factor = 1. / (np.sqrt(xsig * xsig * 2. * np.pi))
exponent = -np.divide((x - x0) * (x - x0),2 * xsig * xsig)
return factor * np.exp(exponent)
def likelihood_evaluation(model_error, star_error_list, abundance_list, star_abundance_list):
'''
This function evaluates the Gaussian for the prediction/observation comparison and returns the resulting log likelihood. The model error and the observed error are added quadratically
INPUT:
model_error = the error coming from the models side
star_error_list = the error coming from the observations
abundance_list = the predictions
star_abundance_list = the observations
OUTPUT:
likelihood = the summed log likelihood
'''
error = np.sqrt(np.multiply(model_error,model_error) + np.multiply(star_error_list,star_error_list))
#print(error, 'error')
#print(star_abundance_list, 'star_abundance_list')
#print(abundance_list, 'abundance_list')
list_of_likelihoods = gaussian(star_abundance_list,abundance_list,error)
#print(list_of_likelihoods, 'list_of_likelihoods')
log_likelihood_list = np.log(list_of_likelihoods)
#print(log_likelihood_list, 'log_likelihood_list')
likelihood = np.sum(log_likelihood_list)
return likelihood
def likelihood_evaluation_int(error, abundance_list, star_abundance_list):
'''
This function evaluates the Gaussian for the prediction/observation comparison and returns the resulting log likelihood. The model error and the observed error are added quadratically
INPUT:
model_error = the error coming from the models side
star_error_list = the error coming from the observations
abundance_list = the predictions
star_abundance_list = the observations
OUTPUT:
likelihood = the summed log likelihood
'''
#print(error, 'error')
#print(star_abundance_list, 'star_abundance_list')
#print(abundance_list, 'abundance_list')
#print(star_abundance_list.shape,abundance_list.shape,error.shape)
## Too slow...
#list_of_likelihoods = gaussian(star_abundance_list,abundance_list,error)
list_of_likelihoods = norm.pdf(star_abundance_list,loc=abundance_list,scale=error)
#print(list_of_likelihoods, 'list_of_likelihoods')
log_likelihood_list = np.log(list_of_likelihoods)
#print(log_likelihood_list, 'log_likelihood_list')
likelihood = np.sum(log_likelihood_list)
return likelihood
def sample_stars(weight,selection,element1,element2,error1,error2,nsample):
'''
This function samples stars along a chemical evolution track properly taking into account the SFR and the selection function of the stellar population (e.g. red-clump stars). It can be used to produce mock observations which can be compared to survey data.
INPUT
weight: The SFR of the model
selection: The age-distribution of a stellar population (e.g. red-clump stars). The time intervals need to be the same as for 'weight'.
element1 = the values of one element for the ISM of the model (same time-intervals as SFR)
element2 = the values of the other element for the ISM
error1 = the measurement error of that element
error2 = measurement error
nsample = number of stars that should be realized
'''
weight = np.cumsum(weight*selection)
weight /= weight[-1]
sample = np.random.random(nsample)
sample = np.sort(sample)
stars = np.zeros_like(weight)
for i,item in enumerate(weight):
if i == 0:
count = len(sample[np.where(np.logical_and(sample>0.,sample<=item))])
stars[i] = count
else:
count = len(sample[np.where(np.logical_and(sample>weight[i-1],sample<=item))])
stars[i] = count
sun_feh = []
sun_mgfe = []
for i in range(len(weight)):
if stars[i] != 0:
for j in range(int(stars[i])):
sun_feh.append(element1[i])
sun_mgfe.append(element2[i])
sun_feh = np.array(sun_feh)
sun_mgfe = np.array(sun_mgfe)
perturbation = np.random.normal(0,error1,len(sun_feh))
sun_feh += perturbation
perturbation = np.random.normal(0,error2,len(sun_feh))
sun_mgfe += perturbation
return sun_feh,sun_mgfe
def gaussian_1d_log(x,x0,xsig):
return -np.divide((x-x0)*(x-x0),2*xsig*xsig)
def yield_plot(name_string, yield_class, solar_class, element):
'''
This function plots [X/Fe] for the complete mass and metallicity range of a yield class.
INPUT:
name_string = a string which is included in the saved file name
yield_class = a Chempy yield class (e.g 'Nomoto2013' from SN2_Feedback, see tutorial)
solar_class = a Chempy solar class (needed for normalisation)
element = the element for which to plot the yield table
OUTPUT
the figure will be saved into the current directory
'''
elements = np.hstack(solar_class.all_elements)
solar_fe_fraction = float(solar_class.fractions[np.where(elements == 'Fe')])
solar_element_fraction = float(solar_class.fractions[np.where(elements == element)])
plt.clf()
fig = plt.figure(figsize=(13,8), dpi=100)
ax = fig.add_subplot(111)
ax.set_title('Yields of %s' %(name_string))
ax.set_xlabel(r'metallicity in $\log_{10}\left(\mathrm{Z}/\mathrm{Z}_\odot\right)$')
ax.set_ylabel('[%s/Fe]' %(element))
for item in yield_class.metallicities:
for j,jtem in enumerate(list(yield_class.table[item]['Mass'])):
ejecta_fe = yield_class.table[item]['Fe'][j]
ejecta_element = yield_class.table[item][element][j]
#print "log Z, mass, [X/Fe]"
#print np.log10(float(item)/solar_class.z), jtem, np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
if item == 0:
metallicity = np.log10(float(1e-7)/solar_class.z)
else:
metallicity = np.log10(float(item)/solar_class.z)
alpha_enhancement = np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
mass = jtem
ax.scatter(metallicity, alpha_enhancement, s=20, c=None, marker=u'o', cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None)
ax.text(metallicity, alpha_enhancement, mass)
plt.savefig('yields_%s.png' %(name_string),bbox_inches='tight')
def yield_comparison_plot(yield_name1, yield_name2, yield_class, yield_class2, solar_class, element):
'''
a function to plot a comparison between two yield sets. It is similar to 'yield_plot' only that a second yield set can be plotted.
INPUT
yield_name1 = Name of the first yield class
yield_name2 = Name of the second yield class
yield_class = a Chempy yield class (e.g 'Nomoto2013' from SN2_Feedback, see tutorial)
yield_class2 = a Chempy yield class (e.g 'Nomoto2013' from SN2_Feedback, see tutorial)
solar_class = a Chempy solar class (needed for normalisation)
element = the element for which to plot the yield table
OUTPUT
the figure will be saved into the current directory
'''
elements = np.hstack(solar_class.all_elements)
solar_fe_fraction = float(solar_class.fractions[np.where(elements == 'Fe')])
solar_element_fraction = float(solar_class.fractions[np.where(elements == element)])
plt.clf()
fig = plt.figure(figsize=(13,8), dpi=100)
ax = fig.add_subplot(111)
ax.set_title('Yields of %s in blue vs %s in red' %(yield_name1,yield_name2))
ax.set_xlabel(r'metallicity in $\log_{10}\left(\mathrm{Z}/\mathrm{Z}_\odot\right)$')
ax.set_ylabel('[%s/Fe]' %(element))
for item in yield_class.metallicities:
for j,jtem in enumerate(list(yield_class.table[item]['Mass'])):
ejecta_fe = yield_class.table[item]['Fe'][j]
ejecta_element = yield_class.table[item][element][j]
#print "log Z, mass, [X/Fe]"
#print np.log10(float(item)/solar_class.z), jtem, np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
if item == 0:
metallicity = np.log10(float(1e-7)/solar_class.z)
else:
metallicity = np.log10(float(item)/solar_class.z)
alpha_enhancement = np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
mass = jtem
ax.scatter(metallicity, alpha_enhancement, s=20*mass, c='b', marker=u'o', cmap=None, norm=None, vmin=None, vmax=None, alpha=0.5, linewidths=None, verts=None, edgecolors=None)
ax.annotate(xy = (metallicity, alpha_enhancement), s = mass, color = 'b')
for item in yield_class2.metallicities:
for j,jtem in enumerate(list(yield_class2.table[item]['Mass'])):
ejecta_fe = yield_class2.table[item]['Fe'][j]
ejecta_element = yield_class2.table[item][element][j]
#print "log Z, mass, [X/Fe]"
#print np.log10(float(item)/solar_class.z), jtem, np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
if item == 0:
metallicity = np.log10(float(1e-7)/solar_class.z)
else:
metallicity = np.log10(float(item)/solar_class.z)
alpha_enhancement = np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
mass = jtem
ax.scatter(metallicity, alpha_enhancement, s=20*mass, c='r', marker=u'o', cmap=None, norm=None, vmin=None, vmax=None, alpha=0.5, linewidths=None, verts=None, edgecolors=None)
ax.annotate(xy = (metallicity, alpha_enhancement), s = mass, color = 'r')
plt.savefig('yields_comparison_%s_vs_%s_for_%s.png' %(yield_name1,yield_name2,element),bbox_inches='tight')
def fractional_yield_comparison_plot(yield_name1, yield_name2, yield_class, yield_class2, solar_class, element):
'''
a function to plot a comparison between the fractional yield of two yield sets. The fractional yield is the mass fraction of the star that is expelled as the specific element. Depending on the yield class it will be net or total yield.
INPUT
yield_name1 = Name of the first yield class
yield_name2 = Name of the second yield class
yield_class = a Chempy yield class (e.g 'Nomoto2013' from SN2_Feedback, see tutorial)
yield_class2 = a Chempy yield class (e.g 'Nomoto2013' from SN2_Feedback, see tutorial)
solar_class = a Chempy solar class (needed for normalisation)
element = the element for which to plot the yield table
OUTPUT
the figure will be saved into the current directory
'''
plt.clf()
fig = plt.figure(figsize=(13,8), dpi=100)
ax = fig.add_subplot(111)
ax.set_title('Yields of %s in blue vs %s in red' %(yield_name1,yield_name2))
ax.set_xlabel(r'metallicity in $\log_{10}\left(\mathrm{Z}/\mathrm{Z}_\odot\right)$')
ax.set_ylabel(r'$\log_{10}$(fractional %s yield)' %(element))
for item in yield_class.metallicities:
for j,jtem in enumerate(list(yield_class.table[item]['Mass'])):
ejecta_element = yield_class.table[item][element][j]
#print "log Z, mass, [X/Fe]"
#print np.log10(float(item)/solar_class.z), jtem, np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
if item == 0:
metallicity = np.log10(float(1e-7)/solar_class.z)
else:
metallicity = np.log10(float(item)/solar_class.z)
fractional_feedback = np.log10(ejecta_element)
mass = jtem
ax.scatter(metallicity, fractional_feedback, s=20*mass, c='b', marker=u'o', cmap=None, norm=None, vmin=None, vmax=None, alpha=0.5, linewidths=None, verts=None, edgecolors=None)
ax.annotate(xy = (metallicity, fractional_feedback), s = mass, color = 'b')
for item in yield_class2.metallicities:
for j,jtem in enumerate(list(yield_class2.table[item]['Mass'])):
ejecta_element = yield_class2.table[item][element][j]
#print "log Z, mass, [X/Fe]"
#print np.log10(float(item)/solar_class.z), jtem, np.log10(ejecta_element/solar_element_fraction) - np.log10(ejecta_fe/solar_fe_fraction)
if item == 0:
metallicity = np.log10(float(1e-7)/solar_class.z)
else:
metallicity = np.log10(float(item)/solar_class.z)
fractional_feedback = np.log10(ejecta_element)
mass = jtem
ax.scatter(metallicity, fractional_feedback, s=20*mass, c='r', marker=u'o', cmap=None, norm=None, vmin=None, vmax=None, alpha=0.5, linewidths=None, verts=None, edgecolors=None)
ax.annotate(xy = (metallicity, fractional_feedback), s = mass, color = 'r')
plt.savefig('fractional_yields_comparison_%s_vs_%s_for_%s.png' %(yield_name1,yield_name2,element),bbox_inches='tight')
def elements_plot(name_string,agb, sn2, sn1a,elements_to_trace, all_elements,max_entry):
'''
This function plots the available elements for specific yield sets.
INPUT:
name_string = a string that will be added to the file name
agb = agb yield class
sn2 = sn2 yield class
sn1a = sn1a yield class
elements_to_trace = which elements do we want to follow (a list)
all_elements = Symbols of all elements (available in the solar abundances class)
max_entry = until which element number the figure should be plotted
OUTPUT:
a figure in the current directory
'''
plt.clf()
fig = plt.figure(figsize=(max_entry,10.27), dpi=100)
ax = fig.add_subplot(111)
ax.set_title('Elements in yields and processes')
ax.set_xlabel('element number')
ax.set_ylabel('groups of elements')
apogee = ['C','N','O','Na','Mg','Al','Si','S','K','Ca','Ti','V','Mn','Ni']
s_process = ['Sr','Y','Zr','Nb','Mo','Sn','Ba','La','Ce','Nd','W','Pb']
r_process = ['Ge','Ru','Rh','Pd','Ag','Pr','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu','Hf','Ta','Re','Os','Ir','Pt','Au','Bi','Th','U']
alpha = ['C','N','O','Ne','Mg','Si','S','Ar','Ca','Ti']
iron = ['V','Cr','Mn','Fe','Co','Ni','Zn']
BB = ['H','He','Li','Be']
#ax.axis([-3, 118, -3.5, 8.5])
ax.set_xlim((-3,max_entry))
ax.set_ylim((-3.5,8.5))
ax.text(-2, 3, 'elements', fontsize=15, clip_on=True)
ax.text(-2, 4, 'We trace', fontsize=15)
ax.text(-2, 8, 'SN Ia', fontsize=15)
ax.text(-2, 6, 'CC-SN', fontsize=15)
ax.text(-2, 7, 'AGB', fontsize=15)
ax.text(-2, 5, 'mutual', fontsize=15)
ax.text(-2, -3, r'$\alpha$-element', fontsize=15)
ax.text(-2, 1, 'iron-peak', fontsize=15)
ax.text(-2, 0, 's-process', fontsize=15)
ax.text(-2, -1, 'r-process', fontsize=15)
ax.text(-2, -2, 'Big Bang', fontsize=15)
ax.text(-2, 2, 'Apogee', fontsize=15)
for i, item in enumerate(all_elements['Symbol']):
ax.text(all_elements['Number'][i], 3, item, fontsize=15,bbox={'facecolor':'red', 'alpha':0.5, 'pad':10}, clip_on=True)
if item in elements_to_trace:
ax.text(all_elements['Number'][i], 4, "X", fontsize=15, clip_on=True)
if item in sn1a:
ax.text(all_elements['Number'][i], 8, "X", fontsize=15, clip_on=True)
if item in sn2:
ax.text(all_elements['Number'][i], 6, "X", fontsize=15, clip_on=True)
if item in agb:
ax.text(all_elements['Number'][i], 7, "X", fontsize=15, clip_on=True)
if item in agb and item in sn2 and item in sn1a:
ax.text(all_elements['Number'][i], 5, "X", fontsize=15, clip_on=True)
if item in BB:
ax.text(all_elements['Number'][i], -2, "X", fontsize=15, clip_on=True)
if item in iron:
ax.text(all_elements['Number'][i], 1, "X", fontsize=15, clip_on=True)
if item in alpha:
ax.text(all_elements['Number'][i], -3, "X", fontsize=15, clip_on=True)
if item in s_process:
ax.text(all_elements['Number'][i], 0, "X", fontsize=15, clip_on=True)
if item in r_process:
ax.text(all_elements['Number'][i], -1, "X", fontsize=15, clip_on=True)
if item in apogee:
ax.text(all_elements['Number'][i], 2, "X", fontsize=15, clip_on=True)
plt.savefig('elements_%s.png' %(name_string),bbox_inches='tight')
return [0.]
def cosmic_abundance_standard(summary_pdf,name_string,abundances,cube,elements_to_trace,solar,number_of_models_overplotted,produce_mock_data,use_mock_data,error_inflation):
'''
This is a likelihood function for the B-stars (a proxy for the present-day ISM) with data from nieva przybilla 2012 cosmic abundance standard paper.
INPUT:
summary_pdf = boolean, should a pdf be created?
name_string = string to be added in the saved file name
abundances = abundances of the IMS (can be calculated from cube)
cube = the ISM mass fractions per element (A Chempy class containing the model evolution)
elements_to_trace = Which elements should be used for the analysis
solar = solar abundance class
number_of_models_overplotted = default is 1, if more the results will be saved and in the last iteration all former models will be plotted at once
produce_mock_data = should the predictions be saved with an error added to them (default=False)
use_mock_data = instead of the real data use the formerly produced mock data (default = False)
error_inflation = a factor with which the mock data should be perturbed with the observational data (default = 1.0)
OUTPUT:
probabilities = each elements likelihood in a list
model_abundances = each elements model prediction as a list
elements_list = the names of the elements in a list
'''
log_abundances_cosmic = np.array([10.99,8.76,7.56,7.5,7.52,8.09,8.33,7.79])#
error_abundances = np.array([0.01,0.05,0.05,0.05,0.03,0.05,0.04,0.04])# original
elements= np.array(['He','O','Mg','Si','Fe','Ne','C','N'])
probabilities = []
probabilities_max = []
elements_list = []
error_list = []
cas_abundances = []
model_abundances = []
for i,item in enumerate(elements):
if item in elements_to_trace:
elements_list.append(item)
cas_abundances.append(log_abundances_cosmic[np.where(elements==item)]-solar['photospheric'][np.where(solar['Symbol']==item)])
model_abundances.append(abundances[item][-1])
error_list.append(error_abundances[np.where(elements==item)])
if produce_mock_data:
mock_abundance_list = list(np.random.normal(loc = list(np.hstack(model_abundances)),scale = list(error_inflation*np.hstack(error_list))))
np.save('mock_data_temp/cas_abundances' ,mock_abundance_list)
if use_mock_data:
error_list = list(np.hstack(error_list)*error_inflation)
cas_abundances = np.load('mock_data_temp/cas_abundances.npy')
for i,item in enumerate(elements_list):
probabilities.append(float(gaussian_1d_log(model_abundances[i],cas_abundances[i],error_list[i])))
probability = np.sum(probabilities)
if number_of_models_overplotted >1:
if os.path.isfile('output/comparison/cas.npy'):
old = np.load('output/comparison/cas.npy')
old = list(old)
else:
old = []
old.append(np.array(model_abundances))
np.save('output/comparison/cas',old)
if os.path.isfile('output/comparison/cas_likelihood.npy'):
old_likelihood = np.load('output/comparison/cas_likelihood.npy')
old_likelihood = list(old_likelihood)
else:
old_likelihood = []
old_likelihood.append(np.array(probabilities))
np.save('output/comparison/cas_likelihood',old_likelihood)
if summary_pdf:
plt.clf()
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.errorbar(np.arange(len(elements_list)),cas_abundances,xerr=None,yerr=error_list,mew=3,marker='x',capthick =3,capsize = 20, ms = 10,elinewidth=3,label='CAS')
plt.plot(np.arange(len(elements_list)),model_abundances,label='model after %.1f Gyr' %(cube['time'][-1]),linestyle='-')
if number_of_models_overplotted > 1:
for item in old:
plt.plot(np.arange(len(elements_list)),np.array(item),linestyle='-', color = 'g', alpha = 0.2)
for i in range(len(elements_list)):
plt.annotate(xy=(i,-0.1),s= '%.2f' %(probabilities[i]),size=12)
plt.grid("on")
elements_list1 = ['[%s/H]' %(item) for item in elements_list]
plt.ylim((-0.5,0.5))
plt.xticks(np.arange(len(elements_list1)), elements_list1)
plt.ylabel("abundance relative to solar in dex")
plt.xlabel("Element")
plt.title('ln(probability) of fulfilling cas= %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('cas_%s.png' %(name_string))
return probabilities, model_abundances, elements_list
def sol_norm(summary_pdf,name_string,abundances,cube,elements_to_trace, element_names, sol_table, number_of_models_overplotted,produce_mock_data,use_mock_data,error_inflation):
'''
This is a likelihood function for solar abundances compared to the model ISM abundances from 4.5Gyr ago.
INPUT:
summary_pdf = boolean, should a pdf be created?
name_string = string to be added in the saved file name
abundances = abundances of the IMS (can be calculated from cube)
cube = the ISM mass fractions per element (A Chempy class containing the model evolution)
elements_to_trace = which elements are tracked by Chempy
element_names = which elements should be used for the likelihood
sol_table = solar abundance class
number_of_models_overplotted = default is 1, if more the results will be saved and in the last iteration all former models will be plotted at once
produce_mock_data = should the predictions be saved with an error added to them (default=False)
use_mock_data = instead of the real data use the formerly produced mock data (default = False)
error_inflation = a factor with which the mock data should be perturbed with the observational data (default = 1.0)
OUTPUT:
probabilities = each elements likelihood in a list
model_abundances = each elements model prediction as a list
elements_list = the names of the elements in a list
'''
'''
solar abundances of the sun from the photospheric abundances of the basic_solar.table
compared to the model abundances after 7.5Gyr. If the sun travelled in the galaxy radial abundance gradiants need to be added.
'''
elements_to_trace = element_names
if 'C+N' in element_names:
new_array = np.log10( np.power(10,abundances['C']) + np.power(10,abundances['N']))
abundances = append_fields(abundances,'C+N',new_array)
time_sun = cube['time'][-1] - 4.5
cut = [np.where(np.abs(cube['time']-time_sun)==np.min(np.abs(cube['time']-time_sun)))]
if len(cut[0][0]) != 1:
cut = cut[0][0][0]
time_model = cube['time'][cut]
probabilities = []
abundance_list = []
error_list = []
sun_list = []
for i,item in enumerate(elements_to_trace):
abundance_list.append(float(abundances[item][cut]))
error = sol_table['error'][np.where(sol_table['Symbol']==item)] + 0.01 # added because of uncertainty in diffusion correction (Asplund2009)
error_list.append(error)
if item != "C+N":
if item == 'He':
sun_list.append(0.05)
else:
sun_list.append(0.04) ## add 0.04dex to get protosolar abundances (Asplund 2009)
else:
sun_list.append(np.log10(2.))
if produce_mock_data:
mock_abundance_list = list(np.random.normal(loc = list(np.hstack(abundance_list)),scale = list(error_inflation*np.hstack(error_list))))
np.save('mock_data_temp/solar_abundances' ,mock_abundance_list)
if use_mock_data:
error_list = list(np.hstack(error_list)*error_inflation)
sun_list = np.load('mock_data_temp/solar_abundances.npy')
for i,item in enumerate(elements_to_trace):
probabilities.append(float(gaussian_1d_log(abundance_list[i],sun_list[i],error_list[i])))
probability = np.sum(probabilities)
if number_of_models_overplotted > 1:
if os.path.isfile('output/comparison/sun.npy'):
old = np.load('output/comparison/sun.npy')
old = list(old)
else:
old = []
old.append(np.array(abundance_list))
np.save('output/comparison/sun',old)
if os.path.isfile('output/comparison/sun_likelihood.npy'):
old_likelihood = np.load('output/comparison/sun_likelihood.npy')
old_likelihood = list(old_likelihood)
else:
old_likelihood = []
old_likelihood.append(np.array(probabilities))
np.save('output/comparison/sun_likelihood',old_likelihood)
if summary_pdf:
text_size = 12
plt.rc('font', family='serif',size = text_size)
plt.rc('xtick', labelsize=text_size)
plt.rc('ytick', labelsize=text_size)
plt.rc('axes', labelsize=text_size, lw=2.0)
plt.rc('lines', linewidth = 2)
plt.rcParams['ytick.major.pad']='8'
plt.clf()
fig = plt.figure(figsize=(30.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.errorbar(np.arange(len(elements_to_trace)),sun_list,xerr=None,yerr=error_list,linestyle = '',mew=3,marker='x',capthick =3,capsize = 20, ms = 10,elinewidth=3,label='solar')
plt.plot(np.arange(len(elements_to_trace)),np.array(abundance_list),label='model after %.2f Gyr' %(time_model),linestyle='-')
if number_of_models_overplotted > 1:
for item in old:
plt.plot(np.arange(len(elements_to_trace)),np.array(item),linestyle='-', color = 'g', alpha = 0.2)
for i in range(len(elements_to_trace)):
plt.annotate(xy=(i,-0.4),s= '%.2f' %(probabilities[i]))
plt.grid("on")
plt.ylim((-0.5,0.5))
elements_to_trace = ['[%s/H]' %(item) for item in elements_to_trace]
plt.xticks(np.arange(len(elements_to_trace)), elements_to_trace)
plt.ylabel("abundance relative to solar in dex")
plt.xlabel("Element")
plt.title('joint probability of agreeing with the sun (normed to pmax) = %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('sol_norm_%s.png' %(name_string))
return probabilities, abundance_list, elements_to_trace
def arcturus(summary_pdf,name_string,abundances,cube,elements_to_trace, element_names, sol_table, number_of_models_overplotted, arcturus_age,produce_mock_data,use_mock_data,error_inflation):
'''
This is a likelihood function for the arcturus abundances compared to the model ISM abundances from some time ago (the age of arcturus which needs to be specified). The abundances are taken from Ramirez+ 2011 and all elements except for Fe are given in [X/Fe]
INPUT:
summary_pdf = boolean, should a pdf be created?
name_string = string to be added in the saved file name
abundances = abundances of the IMS (can be calculated from cube)
cube = the ISM mass fractions per element (A Chempy class containing the model evolution)
elements_to_trace = Which elements should be used for the analysis
sol_table = solar abundance class
number_of_models_overplotted = default is 1, if more the results will be saved and in the last iteration all former models will be plotted at once
produce_mock_data = should the predictions be saved with an error added to them (default = False)
use_mock_data = instead of the real data use the formerly produced mock data (default = False)
error_inflation = a factor with which the mock data should be perturbed with the observational data (default = 1.0)
OUTPUT:
probabilities = each elements likelihood in a list
model_abundances = each elements model prediction as a list
elements_list = the names of the elements in a list
'''
#### Arcturus abundances taken from Worley+ 2009 MNRAS all elements except Fe are given [X/Fe]
#element_list_arcturus = ['Fe', 'O', 'Na', 'Mg', 'Al', 'Si', 'Ca', 'Sc', 'Ti', 'Zn', 'Y', 'Zr', 'Ba', 'La', 'Nd', 'Eu']
#element_abundances_arcturus = [-0.60,0.57,0.15,0.34,0.25,0.24,0.19,0.24,0.34,-0.04,0.10,0.06,-0.19,0.04,0.10,0.36]
#element_errors_arcturus = [0.11,0.02,0.04,0.15,0.07,0.14,0.06,0.01,0.11,0.09,0.17,0.08,0.08,0.08,0.07,0.04]
#### Arcturus abundances and Age taken from Ramirez+ 2011 all elements except Fe given in [X/Fe]
element_list_arcturus = np.array(['Fe', 'O', 'Na', 'Mg', 'Al', 'Si', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Co', 'Ni', 'Zn'])#, 'C'
element_abundances_arcturus = np.array([-0.52, 0.50, 0.11, 0.37, 0.34, 0.33, 0.20, 0.11, 0.19, 0.24, 0.20, -0.05, -0.21, 0.09, 0.06, 0.22])#, 0.43
element_errors_arcturus = np.array([0.04, 0.03, 0.03, 0.03, 0.03, 0.04, 0.07, 0.04, 0.06, 0.05, 0.05, 0.04, 0.04, 0.04, 0.03, 0.06])#,0.07
assert len(element_list_arcturus) == len(element_abundances_arcturus) == len(element_errors_arcturus)
elements_to_trace = element_names
time_arcturus = cube['time'][-1] - arcturus_age # 7.1 +1.5 -1.2
cut = [np.where(np.abs(cube['time']-time_arcturus)==np.min(np.abs(cube['time']-time_arcturus)))]
if len(cut[0][0]) != 1:
cut = cut[0][0][0]
time_model = cube['time'][cut]
abundance_list = []
error_list = []
arcturus_list = []
elements_in_common = []
for i,item in enumerate(elements_to_trace):
if item in element_list_arcturus:
elements_in_common.append(item)
if item == 'Fe':
abundance_list.append(float(abundances[item][cut]))
else:
abundance_list.append(float(abundances[item][cut]-abundances['Fe'][cut]))
error_list.append(element_errors_arcturus[np.where(element_list_arcturus == item)])
arcturus_list.append(element_abundances_arcturus[np.where(element_list_arcturus == item)])
if produce_mock_data:
mock_abundance_list = list(np.random.normal(loc = list(np.hstack(abundance_list)),scale = list(error_inflation*np.hstack(error_list))))
np.save('mock_data_temp/arcturus_abundances' ,mock_abundance_list)
if use_mock_data:
error_list = list(np.hstack(error_list)*error_inflation)
arcturus_list = np.load('mock_data_temp/arcturus_abundances.npy')
probabilities = []
for i,item in enumerate(elements_in_common):
probabilities.append(float(gaussian_1d_log(abundance_list[i],arcturus_list[i],error_list[i])))
probability = np.sum(probabilities)
if number_of_models_overplotted > 1:
if os.path.isfile('output/comparison/arc.npy'):
old = np.load('output/comparison/arc.npy')
old = list(old)
else:
old = []
old.append(np.array(abundance_list))
np.save('output/comparison/arc',old)
if os.path.isfile('output/comparison/arc_likelihood.npy'):
old_likelihood = np.load('output/comparison/arc_likelihood.npy')
old_likelihood = list(old_likelihood)
else:
old_likelihood = []
old_likelihood.append(np.array(probabilities))
np.save('output/comparison/arc_likelihood',old_likelihood)
if summary_pdf:
text_size = 8
plt.rc('font', family='serif',size = text_size)
plt.rc('xtick', labelsize=text_size)
plt.rc('ytick', labelsize=text_size)
plt.rc('axes', labelsize=text_size, lw=1.0)
plt.rc('lines', linewidth = 1)
plt.rcParams['ytick.major.pad']='8'
plt.clf()
fig = plt.figure(figsize=(10.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.errorbar(np.arange(len(elements_in_common)),arcturus_list,xerr=None,yerr=error_list,mew=3,marker='x',capthick =3,capsize = 20, ms = 10,elinewidth=3,label='arcturus')
plt.plot(np.arange(len(elements_in_common)),np.array(abundance_list),label='model after %.2f Gyr' %(time_model),linestyle='-')
if number_of_models_overplotted > 1:
for item in old:
plt.plot(np.arange(len(elements_in_common)),np.array(item),linestyle='-', color = 'g', alpha = 0.2)
for i in range(len(elements_in_common)):
plt.annotate(xy=(i,-0.4),s= '%.2f' %(probabilities[i]))
plt.grid("on")
plt.ylim((-0.5,0.5))
element_labels = ['[%s/Fe]' %(item) for item in elements_in_common]
element_labels = np.array(element_labels)
element_labels[np.where(element_labels == '[Fe/Fe]')] = '[Fe/H]'
plt.xticks(np.arange(len(elements_in_common)), element_labels)
plt.ylabel("abundance relative to solar in dex")
plt.xlabel("Element")
plt.title('joint probability of agreeing with the sun (normed to pmax) = %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('arcturus_%s.png' %(name_string))
return probabilities, abundance_list, elements_in_common
def gas_reservoir_metallicity(summary_pdf,name_string,abundances,cube,elements_to_trace,gas_reservoir,number_of_models_overplotted,produce_mock_data,use_mock_data, error_inflation,solZ):
'''
This is a likelihood function for the present-day metallicity of the corona gas. Data is taken from the Smith cloud
INPUT:
summary_pdf = boolean, should a pdf be created?
name_string = string to be added in the saved file name
abundances = abundances of the IMS (can be calculated from cube)
cube = the ISM mass fractions per element (A Chempy class containing the model evolution)
elements_to_trace = Which elements should be used for the analysis
gas_reservoir = the gas_reservoir class containing the gas_reservoir evolution
number_of_models_overplotted = default is 1, if more the results will be saved and in the last iteration all former models will be plotted at once
produce_mock_data = should the predictions be saved with an error added to them (default=False)
use_mock_data = instead of the real data use the formerly produced mock data (default = False)
error_inflation = a factor with which the mock data should be perturbed with the observational data (default = 1.0)
solZ = solar metallicity
OUTPUT:
probabilities = each elements likelihood in a list
model_abundances = each elements model prediction as a list
elements_list = the names of the elements in a list
'''
### data from Smith cloud
log10_metallicity_at_end = -0.28
log10_std = 0.14
if produce_mock_data:
mock_data = np.random.normal(loc = np.log10(gas_reservoir['Z'][-1]/solZ), scale = log10_std*error_inflation)
np.save('mock_data_temp/metallicity_at_end' , mock_data)
if use_mock_data:
log10_std *= error_inflation
log10_metallicity_at_end = np.load('mock_data_temp/metallicity_at_end.npy')
probability = gaussian_1d_log(np.log10(gas_reservoir['Z'][-1]/solZ),log10_metallicity_at_end,log10_std)
if number_of_models_overplotted > 1:
if os.path.isfile('output/comparison/gas_reservoir.npy'):
old = np.load('output/comparison/gas_reservoir.npy')
old = list(old)
else:
old = []
old.append(np.array(np.log10(gas_reservoir['Z']/solZ)))
np.save('output/comparison/gas_reservoir',old)
if os.path.isfile('output/comparison/gas_reservoir_likelihood.npy'):
old_likelihood = np.load('output/comparison/gas_reservoir_likelihood.npy')
old_likelihood = list(old_likelihood)
else:
old_likelihood = []
old_likelihood.append(np.array(probability))
np.save('output/comparison/gas_reservoir_likelihood',old_likelihood)
if os.path.isfile('output/comparison/gas_metallicity.npy'):
old1 = np.load('output/comparison/gas_metallicity.npy')
old1 = list(old1)
else:
old1 = []
old1.append(np.array(np.log10(cube['Z']/solZ)))
np.save('output/comparison/gas_metallicity',old1)
if summary_pdf:
plt.clf()
text_size = 8
plt.rc('font', family='serif',size = text_size)
plt.rc('xtick', labelsize=text_size)
plt.rc('ytick', labelsize=text_size)
plt.rc('axes', labelsize=text_size, lw=1.0)
plt.rc('lines', linewidth = 1)
plt.rcParams['ytick.major.pad']='8'
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.plot(gas_reservoir['time'],np.log10(gas_reservoir['Z']/solZ),label = "Z_gas_reservoir %.4f" %(np.log10(gas_reservoir['Z'][-1]/solZ)))
if number_of_models_overplotted > 1:
for item in old:
plt.plot(gas_reservoir['time'],np.array(item),linestyle='-', color = 'b', alpha = 0.2)
for item in old1:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'r', alpha = 0.2)
plt.errorbar(gas_reservoir['time'][-1],log10_metallicity_at_end,xerr=None,yerr=log10_std,mew=3,marker='x',capthick =3,capsize = 20, ms = 10,elinewidth=3,label='Smith cloud')
plt.plot(cube['time'],np.log10(cube['Z']/solZ),label = "Z_gas %.4f" %(np.log10(cube['Z'][-1]/solZ)))
plt.grid("on")
plt.ylabel("log 10 metallicity in Z (mass fraction of gas in metals)")
plt.xlabel("time in Gyr")
plt.title('ln(probability) gas content (normed to pmax) = %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('gas_reservoir_%s.png' %(name_string))
return [probability],[gas_reservoir['Z'][-1]/solZ],['Corona metallicity']
def ratio_function(summary_pdf,name_string,abundances,cube,elements_to_trace,gas_reservoir, number_of_models_overplotted,produce_mock_data,use_mock_data, error_inflation):
'''
This is a likelihood function for the present-day SN-ratio. Data is approximated from Manucci+2005.
INPUT:
summary_pdf = boolean, should a pdf be created?
name_string = string to be added in the saved file name
abundances = abundances of the IMS (can be calculated from cube)
cube = the ISM mass fractions per element (A Chempy class containing the model evolution)
elements_to_trace = Which elements should be used for the analysis
gas_reservoir = the gas_reservoir class containing the gas_reservoir evolution
number_of_models_overplotted = default is 1, if more the results will be saved and in the last iteration all former models will be plotted at once
produce_mock_data = should the predictions be saved with an error added to them (default=False)
use_mock_data = instead of the real data use the formerly produced mock data (default = False)
error_inflation = a factor with which the mock data should be perturbed with the observational data (default = 1.0)
OUTPUT:
probabilities = each elements likelihood in a list
model_abundances = each elements model prediction as a list
elements_list = the names of the elements in a list
'''
log10_ratio_at_end = 0.7
log10_std = 0.37
if produce_mock_data:
mock_data = np.random.normal(loc = np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:])[-1]),scale = error_inflation*log10_std)
np.save('mock_data_temp/sn_ratio' ,mock_data)
if use_mock_data:
log10_std *= error_inflation
log10_ratio_at_end = np.load('mock_data_temp/sn_ratio.npy')
probability = gaussian_1d_log( np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:])[-1]),log10_ratio_at_end,log10_std)
if number_of_models_overplotted > 1:
if os.path.isfile('output/comparison/ratio.npy'):
old = np.load('output/comparison/ratio.npy')
old = list(old)
else:
old = []
old.append(np.array( np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:]))))
np.save('output/comparison/ratio',old)
if os.path.isfile('output/comparison/ratio_likelihood.npy'):
old_likelihood = np.load('output/comparison/ratio_likelihood.npy')
old_likelihood = list(old_likelihood)
else:
old_likelihood = []
old_likelihood.append(np.array(probability ))
np.save('output/comparison/ratio_likelihood',old_likelihood)
if os.path.isfile('output/comparison/number_sn2.npy'):
old1 = np.load('output/comparison/number_sn2.npy')
old1 = list(old1)
else:
old1 = []
old1.append(cube['sn2'])
np.save('output/comparison/number_sn2',old1)
if os.path.isfile('output/comparison/number_sn1a.npy'):
old2 = np.load('output/comparison/number_sn1a.npy')
old2 = list(old2)
else:
old2 = []
old2.append(cube['sn1a'])
np.save('output/comparison/number_sn1a',old2)
if summary_pdf:
plt.clf()
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.plot( cube['time'][2:],np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:])), label = 'sn2/sn1a of the model')
if number_of_models_overplotted > 1:
for item in old:
plt.plot(cube['time'][2:],np.array(item),linestyle='-', color = 'b', alpha = 0.2)
plt.annotate(xy=(cube['time'][-1],np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:])[-1])),s= '%.2f' %(np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:])[-1])))
plt.errorbar(cube['time'][-1],log10_ratio_at_end,xerr=None,yerr=log10_std,mew=3,marker='x',capthick =3,capsize = 20, ms = 10,elinewidth=3,label='Prantzos+11')
plt.grid("on")
plt.ylabel("sn2/sn1a")
plt.xlabel("time in Gyr")
plt.title('ln(probability) of sn ratio (normed to pmax) = %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('sn_ratio_%s.png' %(name_string))
plt.clf()
return [probability],[np.log10(np.divide(np.diff(cube['sn2'])[1:],np.diff(cube['sn1a'])[1:])[-1])],['SN-ratio']
def star_function(summary_pdf,name_string,abundances,cube,elements_to_trace,gas_reservoir,number_of_models_overplotted):
'''
!!! Should only be used for plotting purposes
A likelihood function for the stellar surface mass density. It is not updated. Should only be used for plotting purposes as it shows the infall and SFR of a Chempy model
'''
# data from... Just Jahreiss 2010
stars_at_end = 28.
std = 2.
dt = cube['time'][1] - cube['time'][0]
probability = gaussian_1d_log(cube['stars'][-1],stars_at_end,std)
if number_of_models_overplotted > 1:
if os.path.isfile('output/comparison/sfr.npy'):
old = np.load('output/comparison/sfr.npy')
old = list(old)
else:
old = []
old.append(np.array(cube['sfr']*(1./dt)))
np.save('output/comparison/sfr',old)
if os.path.isfile('output/comparison/infall.npy'):
old1 = np.load('output/comparison/infall.npy')
old1 = list(old1)
else:
old1 = []
old1.append(np.array(cube['infall']*(1./dt)))
np.save('output/comparison/infall',old1)
if os.path.isfile('output/comparison/gas_mass.npy'):
old2 = np.load('output/comparison/gas_mass.npy')
old2 = list(old2)
else:
old2 = []
old2.append(np.array(cube['gas']))
np.save('output/comparison/gas_mass',old2)
if os.path.isfile('output/comparison/star_mass.npy'):
old3 = np.load('output/comparison/star_mass.npy')
old3 = list(old3)
else:
old3 = []
old3.append(np.array(cube['stars']))
np.save('output/comparison/star_mass',old3)
if os.path.isfile('output/comparison/remnant_mass.npy'):
old4 = np.load('output/comparison/remnant_mass.npy')
old4 = list(old4)
else:
old4 = []
old4.append(np.array(cube['mass_in_remnants']))
np.save('output/comparison/remnant_mass',old4)
if os.path.isfile('output/comparison/corona_mass.npy'):
old5 = np.load('output/comparison/corona_mass.npy')
old5 = list(old5)
else:
old5 = []
old5.append(np.array(gas_reservoir['gas']))
np.save('output/comparison/corona_mass',old5)
if os.path.isfile('output/comparison/feedback_mass.npy'):
old6 = np.load('output/comparison/feedback_mass.npy')
old6 = list(old6)
else:
old6 = []
old6.append(np.array(cube['feedback']*(1./dt)))
np.save('output/comparison/feedback_mass',old6)
if summary_pdf:
plt.clf()
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.plot(cube['time'],cube['gas'],label = "gas %.2f" %(cube['gas'][-1]), color = 'b')
plt.plot(cube['time'],cube['stars'],label = "stars (only thin disc including remnants) %.2f" %(cube['stars'][-1]), color = 'r')
plt.plot(cube['time'],cube['mass_in_remnants'],label = "remnants %.2f" %(cube['mass_in_remnants'][-1]), color = 'k')
plt.plot(cube['time'],gas_reservoir['gas'], label = 'corona %.2f'%(gas_reservoir['gas'][-1]), color = 'y')
if number_of_models_overplotted > 1:
for item in old2:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'b', alpha = 0.2)
for item in old3:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'r', alpha = 0.2)
for item in old4:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'g', alpha = 0.2)
for item in old5:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'y', alpha = 0.2)
plt.grid("on")
plt.yscale('log')
plt.ylabel(r"M$_\odot$")
plt.xlabel("time in Gyr")
plt.title('ln(probability) star content (normed to pmax) = %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('stars_%s.png' %(name_string))
plt.clf()
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.plot(cube['time'],cube['infall']*(1./dt),linestyle='-', color = 'r',label = "infall %.2f" %(sum(cube['infall'])))
plt.plot(cube['time'],cube['sfr']*(1./dt),linestyle='-', color = 'b',label = "sfr %.2f" %(sum(cube['sfr'])))
if number_of_models_overplotted > 1:
for item in old:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'b', alpha = 0.2)
for item in old1:
plt.plot(cube['time'],np.array(item),linestyle='-', color = 'r', alpha = 0.2)
plt.grid("on")
plt.ylabel(r"M$_\odot$Gyr$^{-1}$")
plt.xlabel("time in Gyr")
plt.title('ln(probability) star content (normed to pmax) = %.2f' %(probability))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('infall_%s.png' %(name_string))
return [0.]
def plot_processes(summary_pdf,name_string,sn2_cube,sn1a_cube,agb_cube,elements,cube1,number_of_models_overplotted):
'''
This is a plotting routine showing the different nucleosynthetic contributions to the individual elements.
INPUT:
summary_pdf = boolean, should a pdf be created?
name_string = string to be added in the saved file name
sn2_cube = the sn2_feeback class
sn1a_cube = the sn1a_feeback class
agb_cube = the agb feedback class
elements = which elements should be plotted
cube1 = the ISM mass fractions per element (A Chempy class containing the model evolution)
number_of_models_overplotted = default is 1, if more the results will be saved and in the last iteration all former models will be plotted at once
OUTPUT:
A plotfile in the current directory
'''
probability = 0
sn2 = []
agb = []
sn1a= []
for i,item in enumerate(elements):
if item == 'C+N':
sn2_temp = np.sum(sn2_cube['C'])
sn2_temp += np.sum(sn2_cube['N'])
sn2.append(sn2_temp)
sn1a_temp = np.sum(sn1a_cube['C'])
sn1a_temp += np.sum(sn1a_cube['N'])
sn1a.append(sn1a_temp)
agb_temp = np.sum(agb_cube['C'])
agb_temp += np.sum(agb_cube['N'])
agb.append(agb_temp)
else:
sn2.append(np.sum(sn2_cube[item]))
sn1a.append(np.sum(sn1a_cube[item]))
agb.append(np.sum(agb_cube[item]))
sn2 = np.array(sn2)
agb = np.array(agb)
sn1a = np.array(sn1a)
total_feedback = sn2 + sn1a + agb
all_4 = np.vstack((sn2,sn1a,agb,total_feedback))
if number_of_models_overplotted > 1:
np.save('output/comparison/elements', elements)
if os.path.isfile('output/comparison/temp_default.npy'):
old = np.load('output/comparison/temp_default.npy')
all_4 = np.dstack((old,all_4))
np.save('output/comparison/temp_default', all_4)
else:
np.save('output/comparison/temp_default', all_4)
if number_of_models_overplotted > 1:
medians = np.median(all_4, axis = 2)
stds = np.std(all_4,axis = 2)
else:
medians = all_4
stds = np.zeros_like(all_4)
if summary_pdf:
if number_of_models_overplotted == 1:
plt.clf()
fig ,ax1 = plt.subplots( figsize = (20,10))
l1 = ax1.bar(np.arange(len(elements)),np.divide(sn2,total_feedback), color = 'b' ,label='sn2', width = 0.2)
l2 = ax1.bar(np.arange(len(elements))+0.25,np.divide(sn1a,total_feedback), color = 'g' ,label='sn1a', width = 0.2)
l3 = ax1.bar(np.arange(len(elements))+0.5,np.divide(agb,total_feedback), color = 'r' ,label='agb', width = 0.2)
ax1.set_ylim((0,1))
plt.xticks(np.arange(len(elements))+0.4, elements)
ax1.vlines(np.arange(len(elements)),0,1)
ax1.set_ylabel("fractional feedback")
ax1.set_xlabel("element")
ax2 = ax1.twinx()
l4 = ax2.bar(np.arange(len(elements)),total_feedback, color = 'k', alpha = 0.2 ,label='total', width = 1)
ax2.set_yscale('log')
ax2.set_ylabel('total mass fed back')
lines = [l1,l2,l3,l4]
labels = ['sn2', 'sn1a', 'agb', 'total']
plt.legend(lines, labels,loc='upper right',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('processes_%s.png' %(name_string))
else:
plt.clf()
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
ax1 = fig.add_subplot(111)
plt.bar(np.arange(len(elements))-0.05,medians[0], yerr=stds[0],error_kw=dict(elinewidth=2,ecolor='k'), color = 'b' ,label='sn2', width = 0.2)
plt.bar(np.arange(len(elements))+0.2,medians[1], yerr=stds[1],error_kw=dict(elinewidth=2,ecolor='k'), color = 'g' ,label='sn1a', width = 0.2)
plt.bar(np.arange(len(elements))+0.45,medians[2], yerr=stds[2],error_kw=dict(elinewidth=2,ecolor='k'), color = 'r' ,label='agb', width = 0.2)
plt.bar(np.arange(len(elements))+0.45,-medians[2], yerr=stds[2],error_kw=dict(elinewidth=2,ecolor='k'), color = 'r' ,alpha = 0.5, width = 0.2)
plt.bar(np.arange(len(elements))-0.15,medians[3], yerr=stds[3],error_kw=dict(elinewidth=2,ecolor='y'), color = 'y' ,alpha = 0.1,label = 'total', width = 1)
plt.ylim((1e-5,1e7))
plt.xticks(np.arange(len(elements))+0.4, elements)
plt.vlines(np.arange(len(elements))-0.15,0,1e7)
plt.yscale('log')
plt.ylabel("total feedback (arbitrary units)")
plt.xlabel("element")
plt.legend(loc='upper right',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('processes_%s.png' %(name_string))
return [probability]
def save_abundances(summary_pdf,name_string,abundances):
'''
a function that saves the abundances in the current directory
INPUT:
summary_pdf = boolean should the abundances be saved?
name_string = name for the saved file
abundances = the abundance instance derived from the cube_class
OUTPUT:
Saves the abundances as a npy file
'''
if summary_pdf:
np.save('abundances_%s' %(name_string),abundances)
return [0.]
def produce_wildcard_stellar_abundances(stellar_identifier, age_of_star, sigma_age, element_symbols, element_abundances, element_errors):
'''
This produces a structured array that can be used by the Chempy wildcard likelihood function.
INPUT:
stellar_identifier = name of the files
age_of_star = age of star in Gyr
sigma_age = the gaussian error of the age (so far not implemented in the likelihood function)
element_symbols = a list of the element symbols
element_abundances = the corresponding abundances in [X/Fe] except for Fe where it is [Fe/H]
element_errors = the corresponding gaussian errors of the abundances
OUTPUT:
it will produce a .npy file in the current directory with stellar_identifier as its name.
'''
names = element_symbols + ['age']
base = np.zeros(2)
base_list = []
for item in names:
base_list.append(base)
wildcard = np.core.records.fromarrays(base_list,names=names)
for i,item in enumerate(element_symbols):
wildcard[item][0] = element_abundances[i]
wildcard[item][1] = element_errors[i]
wildcard['age'][0] = age_of_star
wildcard['age'][1] = sigma_age
np.save(stellar_identifier,wildcard)
def plot_abundance_wildcard(stellar_identifier, wildcard,abundance_list, element_list, probabilities, time_model):
'''
this function plots the abundances of a stellar wildcard and the abundances of a chempy model together with the resulting likelihood values
INPUT:
stellar_identifier = str, name of the Star
wildcard = the wildcard recarray
abundance_list = the abundance list from the model
element_list = the corresponding element symbols
probabilities = the corresponding single likelihoods as a list
time_model = the time of the chempy model which is compared to the stellar abundance (age of the star form the wildcard)
OUTPUT:
This saves a png plot to the current directory
'''
star_abundance_list = []
star_error_list = []
for item in element_list:
star_abundance_list.append(float(wildcard[item][0]))
star_error_list.append(float(wildcard[item][1]))
text_size = 14
plt.rc('font', family='serif',size = text_size)
plt.rc('xtick', labelsize=text_size)
plt.rc('ytick', labelsize=text_size)
plt.rc('axes', labelsize=text_size, lw=1.0)
plt.rc('lines', linewidth = 1)
plt.rcParams['ytick.major.pad']='8'
plt.clf()
fig = plt.figure(figsize=(10.69,8.27), dpi=100)
ax = fig.add_subplot(111)
plt.errorbar(np.arange(len(element_list)),star_abundance_list,xerr=None,yerr=star_error_list,mew=3,marker='x',capthick =3,capsize = 20, ms = 10,elinewidth=3,label = stellar_identifier)
plt.plot(np.arange(len(element_list)),np.array(abundance_list),label='prediction after %.2f Gyr' %(time_model),linestyle='-')
for i in range(len(element_list)):
plt.annotate(xy=(i,-0.4),s= '%.2f' %(probabilities[i]))
element_labels = ['[%s/Fe]' %(item) for item in element_list]
element_labels = np.array(element_labels)
element_labels[np.where(element_labels == '[Fe/Fe]')] = '[Fe/H]'
plt.xticks(np.arange(len(element_list)), element_labels)
plt.ylabel("abundance relative to solar in dex")
plt.xlabel("Element")
plt.title('joint probability of agreeing with %s (normed to pmax) = %.2f' %(stellar_identifier,sum(probabilities)))
plt.legend(loc='best',numpoints=1).get_frame().set_alpha(0.5)
plt.savefig('%s.png' %(stellar_identifier))
def wildcard_likelihood_function(summary_pdf, stellar_identifier, abundances):
'''
This function produces Chempy conform likelihood output for a abundance wildcard that was produced before with 'produce_wildcard_stellar_abundances'.
INPUT:
summary_pdf = bool, should there be an output
stellar_identifier = str, name of the star
abundances = the abundances instance from a chempy chemical evolution
OUTPUT:
probabilities = a list of the likelihoods for each element
abundance_list = the abundances of the model for each element
element_list = the symbols of the corresponding elements
These list will be used to produce the likelihood and the blobs. See cem_function.py
'''
wildcard = np.load(stellar_identifier + '.npy')
star_time = abundances['time'][-1] - wildcard['age'][0]
cut = [np.where(np.abs(abundances['time'] - star_time) == np.min(np.abs(abundances['time'] - star_time)))]
if len(cut[0][0]) != 1:
cut = cut[0][0][0]
time_model = abundances['time'][cut]
abundance_list = []
element_list = []
probabilities = []
for item in list(wildcard.dtype.names):
if item in list(abundances.dtype.names):
if item != 'Fe':
abundance = abundances[item][cut]-abundances['Fe'][cut]
else:
abundance = abundances['Fe'][cut]
element_list.append(item)
abundance_list.append(float(abundance))
probabilities.append(float(gaussian_1d_log(abundance,wildcard[item][0],wildcard[item][1])))
if summary_pdf:
plot_abundance_wildcard(stellar_identifier,wildcard,abundance_list, element_list, probabilities, time_model)
return probabilities, abundance_list, element_list
def likelihood_function(stellar_identifier, list_of_abundances, elements_to_trace, **keyword_parameters):
'''
This function calculates analytically an optimal model error and the resulting likelihood from the comparison of predictions and observations
INPUT:
list_of_abundances = a list of the abundances coming from Chempy
elements_to_trace = a list of the elemental symbols
OUTPUT:
likelihood = the added log likelihood
element_list = the elements that were in common between the predictions and the observations, has the same sequence as the following arrays
model_error = the analytic optimal model error
star_error_list = the observed error
abundance_list = the predictions
star_abundance_list = the observations
'''
try:
wildcard = np.load(stellar_identifier + '.npy')
except Exception as ex:
from . import localpath
wildcard = np.load(localpath + 'input/stars/' + stellar_identifier + '.npy')
# Brings the model_abundances, the stellar abundances and the associated error into the same sequence
abundance_list = []
element_list = []
star_abundance_list = []
star_error_list = []
for i,item in enumerate(elements_to_trace):
if item in list(wildcard.dtype.names):
element_list.append(item)
abundance_list.append(float(list_of_abundances[i]))
star_abundance_list.append(float(wildcard[item][0]))
star_error_list.append(float(wildcard[item][1]))
abundance_list = np.hstack(abundance_list)
star_abundance_list = np.hstack(star_abundance_list)
star_error_list = np.hstack(star_error_list)
assert len(abundance_list) == len(star_abundance_list) == len(star_error_list), 'no equal length, something went wrong'
###################
# Introduces the optimal model error which can be derived analytically
if ('fixed_model_error' in keyword_parameters):
fixed_model_error = keyword_parameters['fixed_model_error']
elements = keyword_parameters['elements']
el_list = []
for i,item in enumerate(elements):
el_list.append(item)#.decode('utf-8'))
elements = np.hstack(el_list)
model_error = []
for i,item in enumerate(element_list):
model_error.append(fixed_model_error[np.where(elements == item)])
model_error = np.hstack(model_error)
else:
model_error = []
for i, item in enumerate(element_list):
if (abundance_list[i] - star_abundance_list[i]) * (abundance_list[i] - star_abundance_list[i]) <= star_error_list[i] * star_error_list[i]:
model_error.append(0.)
else:
model_error.append(np.sqrt((abundance_list[i] - star_abundance_list[i]) * (abundance_list[i] - star_abundance_list[i]) - star_error_list[i] * star_error_list[i]))
model_error = np.hstack(model_error)
## Uncomment next line if you do not want to use model errors
#model_error = np.zeros_like(model_error)
# This is the best model error at the median posterior of the Proto-sun (just used to see how this effects the posterior distribution)
#model_error = np.array([ 0.0780355, 0., 0.15495525, 0.00545988, 0.3063154, 0., 0.1057009, 0.05165564, 0., 0.72038212, 0., 0.08926388, 0., 0.27583715, 0.22945499, 0.09774014, 0.17965589 , 0. ,0.17686723, 0.21137374, 0.37973184, 0.2263486 ])
# Now the likelihood is evaluated
# Test to check correct abundances fed in
#print('Abundance List')
#print(abundance_list)
likelihood = likelihood_evaluation(model_error, star_error_list, abundance_list, star_abundance_list)
return likelihood, element_list, model_error, star_error_list, abundance_list, star_abundance_list
def read_out_wildcard(stellar_identifier, list_of_abundances, elements_to_trace):
'''
This function calculates analytically an optimal model error and the resulting likelihood from the comparison of predictions and observations
INPUT:
list_of_abundances = a list of the abundances coming from Chempy
elements_to_trace = a list of the elemental symbols
OUTPUT:
likelihood = the added log likelihood
element_list = the elements that were in common between the predictions and the observations, has the same sequence as the following arrays
model_error = the analytic optimal model error
star_error_list = the observed error
abundance_list = the predictions
star_abundance_list = the observations
'''
try:
wildcard = np.load(stellar_identifier + '.npy')
except Exception as ex:
from . import localpath
wildcard = np.load(localpath + 'input/stars/' + stellar_identifier + '.npy')
# Brings the model_abundances, the stellar abundances and the associated error into the same sequence
abundance_list = []
element_list = []
star_abundance_list = []
star_error_list = []
for i,item in enumerate(elements_to_trace):
if item in list(wildcard.dtype.names):
element_list.append(item)
abundance_list.append(float(list_of_abundances[i]))
star_abundance_list.append(float(wildcard[item][0]))
star_error_list.append(float(wildcard[item][1]))
abundance_list = np.hstack(abundance_list)
star_abundance_list = np.hstack(star_abundance_list)
star_error_list = np.hstack(star_error_list)
assert len(abundance_list) == len(star_abundance_list) == len(star_error_list), 'no equal length, something went wrong'
###################
return element_list, star_error_list, abundance_list, star_abundance_list
|
import numpy as np
def slope_imf(x,p1,p2,p3,kn1,kn2):
'''
Is calculating a three slope IMF
INPUT:
x = An array of masses for which the IMF should be calculated
p1..p3 = the slopes of the power law
kn1, kn2 = Where the breaks of the power law are
OUTPUT:
An array of frequencies matching the mass base array x
'''
if(x > kn2):
t = (pow(kn2,p2)/pow(kn2,p3))*pow(x,p3+1)
elif (x < kn1):
t = (pow(kn1,p2)/pow(kn1,p1))*pow(x,p1+1)
else:
t = pow(x,p2+1)
return t
def lifetime(m,Z):
"""
here we will calculate the MS lifetime of the star after Argast et al., 2000, A&A, 356, 873
INPUT:
m = mass in Msun
Z = metallicity in Zsun
OUTPUT:
returns the lifetime of the star in Gyrs
"""
# Update - trying Portinari lifetime function
lM = np.log10(m)
lZ = np.log10(Z)
params = np.array([4.0153615 , -3.91089893, 0.99947209, -0.03601771, -0.31139679,0.09109059, -0.03218365, -0.01323112])
tmp = (params[0]+lM*params[1]+np.power(lM,2.)*params[2]+lZ*params[3]+lM*lZ*params[4]+lM*lM*lZ*params[5]+lZ*lZ*params[6]+lZ*lZ*lM*params[7])+6
return np.power(10,tmp)
"""
lm = np.log10(m)
a0 = 3.79 + 0.24*Z
a1 = -3.10 - 0.35*Z
a2 = 0.74 + 0.11*Z
tmp = a0 + a1*lm + a2*lm*lm
return np.divide(np.power(10,tmp),1000)
"""
class IMF(object):
'''
This class represents the IMF normed to 1 in units of M_sun.
Input for initialisation:
mmin = minimal mass of the IMF
mmax = maximal mass of the IMF
intervals = how many steps inbetween mmin and mmax should be given
Then one of the IMF functions can be used
self.x = mass base
self.dn = the number of stars at x
self.dm = the masses for each mass interval x
'''
def __init__(self, mmin = 0.08 , mmax = 100., intervals = 5000):
self.mmin = mmin
self.mmax = mmax
self.intervals = intervals
self.x = np.linspace(mmin,mmax,intervals)
self.dx = self.x[1]-self.x[0]
def normed_3slope(self,paramet = (-1.3,-2.2,-2.7,0.5,1.0)):
'''
Three slope IMF, Kroupa 1993 as a default
'''
s1,s2,s3,k1,k2 = paramet
u = np.zeros_like(self.x)
v = np.zeros_like(self.x)
for i in range(len(self.x)):
u[i] = slope_imf(self.x[i],s1,s2,s3,k1,k2)
v = np.divide(u,self.x)
self.dm = np.divide(u,sum(u))
self.dn = np.divide(self.dm,self.x)
return(self.dm,self.dn)
def Chabrier_1(self, paramet = (0.69, 0.079, -2.3)):
'''
Chabrier IMF from Chabrier 2003 equation 17 field IMF with variable high mass slope and automatic normalisation
'''
sigma, m_c, expo = paramet
dn = np.zeros_like(self.x)
for i in range(len(self.x)):
if self.x[i] <= 1:
index_with_mass_1 = i
dn[i] = (1. / float(self.x[i])) * np.exp(-1*(((np.log10(self.x[i] / m_c))**2)/(2*sigma**2)))
else:
dn[i] = (pow(self.x[i],expo))
# Need to 'attach' the upper to the lower branch
derivative_at_1 = dn[index_with_mass_1] - dn[index_with_mass_1 - 1]
target_y_for_m_plus_1 = dn[index_with_mass_1] + derivative_at_1
rescale = target_y_for_m_plus_1 / dn[index_with_mass_1 + 1]
dn[np.where(self.x>1.)] *= rescale
# Normalizing to 1 in mass space
self.dn = np.divide(dn,sum(dn))
dm = dn*self.x
self.dm = np.divide(dm,sum(dm))
self.dn = np.divide(self.dm,self.x)
return(self.dm,self.dn)
def Chabrier_2(self,paramet = (22.8978, 716.4, 0.25,-2.3)):
'''
Chabrier IMF from Chabrier 2001, IMF 3 = equation 8 parameters from table 1
'''
A,B,sigma,expo = paramet
expo -= 1. ## in order to get an alpha index normalisation
dn = np.zeros_like(self.x)
for i in range(len(self.x)):
dn[i] = A*(np.exp(-pow((B/self.x[i]),sigma)))*pow(self.x[i],expo)
self.dn = np.divide(dn,sum(dn))
dm = dn*self.x
self.dm = np.divide(dm,sum(dm))
self.dn = np.divide(self.dm,self.x)
return(self.dm,self.dn)
def Chabrier_TNG(self,paramet=(0.852464,0.237912,0.69,0.079,-2.3)):
"""
Chabrier IMF used in Vogelsberger 2013
"""
A,B,sigma,m_c,high_mass_slope = paramet
small_m = np.where(self.x<1.)
big_m = np.where(self.x>1.)
dn = np.zeros_like(self.x)
dn[small_m] = A/self.x[small_m]*np.exp(-(np.log10(self.x[small_m]/m_c)**2.)/(2.*sigma**2.))
dn[big_m] = B*self.x[big_m]**high_mass_slope
self.dn = np.divide(dn,sum(dn))
dm = dn*self.x
self.dm = np.divide(dm,sum(dm))
self.dn = np.divide(self.dm,self.x)
return(self.dm,self.dn)
def salpeter(self, alpha = (2.35)):
'''
Salpeter IMF
Input the slope of the IMF
'''
self.alpha = alpha
temp = np.power(self.x,-self.alpha)
norm = sum(temp)
self.dn = np.divide(temp,norm)
u = self.dn*self.x
self.dm = np.divide(u,sum(u))
self.dn = np.divide(self.dm,self.x)
return (self.dm,self.dn)
def BrokenPowerLaw(self, paramet):
breaks,slopes = paramet
if len(breaks) != len(slopes)-1:
print("error in the precription of the power law. It needs one more slope than break value")
else:
dn = np.zeros_like(self.x)
self.breaks = breaks
self.slopes = slopes
self.mass_range = np.hstack((self.mmin,breaks,self.mmax))
for i,item in enumerate(self.slopes):
cut = np.where(np.logical_and(self.x>=self.mass_range[i],self.x<self.mass_range[i+1]))
dn[cut] = np.power(self.x[cut],item)
if i != 0:
renorm = np.divide(last_dn,dn[cut][0])
dn[cut] = dn[cut]*renorm
last_dn = dn[cut][-1]
last_x = self.x[cut][-1]
self.dn = np.divide(dn,sum(dn))
u = self.dn*self.x
self.dm = np.divide(u,sum(u))
self.dn = np.divide(self.dm,self.x)
def imf_mass_fraction(self,mlow,mup):
'''
Calculates the mass fraction of the IMF sitting between mlow and mup
'''
norm = sum(self.dm)
cut = np.where(np.logical_and(self.x>=mlow,self.x<mup))
fraction = np.divide(sum(self.dm[cut]),norm)
return(fraction)
def imf_number_fraction(self,mlow,mup):
'''
Calculating the number fraction of stars of the IMF sitting between mlow and mup
'''
norm = sum(self.dn)
cut = np.where(np.logical_and(self.x>=mlow,self.x<mup))
fraction = np.divide(sum(self.dn[cut]),norm)
return(fraction)
def imf_number_stars(self,mlow,mup):
cut = np.where(np.logical_and(self.x>=mlow,self.x<mup))
number = sum(self.dn[cut])
return(number)
def stochastic_sampling(self, mass):
'''
The analytic IMF will be resampled according to the mass of the SSP.
The IMF will still be normalised to 1
Stochastic sampling is realised by fixing the number of expected stars and then drawing from the probability distribution of the number density
Statistical properties are tested for this sampling and are safe: number of stars and masses converge.
'''
number_of_stars = int(round(sum(self.dn) * mass))
self.dm_copy = np.copy(self.dm)
self.dn_copy = np.copy(self.dn)
#self.dn_copy = np.divide(self.dn_copy,sum(self.dn_copy))
random_number = np.random.uniform(low = 0.0, high = sum(self.dn_copy), size = number_of_stars)
self.dm = np.zeros_like(self.dm)
self.dn = np.zeros_like(self.dn)
'''
### This could be favourable if the number of stars drawn is low compared to the imf resolution
for i in range(number_of_stars):
### the next line randomly draws a mass according to the number distribution of stars
cut = np.where(np.abs(np.cumsum(self.dn_copy)-random_number[i])== np.min(np.abs(np.cumsum(self.dn_copy)-random_number[i])))
x1 = self.x[cut][0]
#self.dn[cut] += 0.5
self.dn[cut[0]] += 1
self.dm[cut[0]] += x1 + self.dx/2.
t.append(x1 + self.dx/2.)
'''
counting = np.cumsum(self.dn_copy)
for i in range(len(counting)-1):
if i == 0:
cut = np.where(np.logical_and(random_number>0.,random_number<=counting[i]))
else:
cut = np.where(np.logical_and(random_number>counting[i-1],random_number<=counting[i]))
number_of_stars_in_mass_bin = len(random_number[cut])
self.dm[i] = number_of_stars_in_mass_bin * self.x[i]
self.dm = np.divide(self.dm,sum(self.dm))
self.dn = np.divide(self.dm,self.x)
|
import math
import random
def pow_mod(g, e, p):
''' calculate (g**e)%p efficiently '''
oe = e
result = 1
g %= p
while e > 0:
if e & 1:
result = (result *g)%p
e >>= 1
g = (g*g)%p
result %= p
return result
def gcd(a, b):
''' return the greatest common divisor between a and b '''
if b == 0:
return a
return gcd(b, a % b)
def inverse(a, n):
''' given a, n find an e s.t. a**n**e == a
uses extended euclidean algorithm straight off wikipedia'''
t = 0
newt = 1
r = n
newr = a
while newr != 0:
quotient = r / newr
t, newt = newt, t - quotient * newt
r, newr = newr, r - quotient * newr
if r > 1:
raise Exception('a is not invertible')
if t < 0:
t = t + n
return t
def sieve(size):
''' prime size of length "size" . pretty naive method '''
s = [True] * size
s[1] = False
s[0] = False
s[4::2] = [False] * (size / 2 - 2)
for i in xrange(3, int(math.sqrt(size)+1), 2):
if s[i]:
for j in xrange(2*i, size, i):
s[j] = False
for i, primeness in enumerate(s):
if primeness:
yield i
all_primes = list(sieve(10000))
stronger_primes = all_primes[300:]
def encrypt_byte(byte, public_key):
return pow_mod(byte, public_key[1], public_key[0])
def encrypt(plaintext, public_key):
''' encrypt some plaintext '''
b = map(ord, plaintext)
result = map(lambda x: encrypt_byte(x, public_key), b)
return result
def decrypt_byte(byte, private_key):
return pow_mod(byte, private_key[1], private_key[0])
def decrypt(ciphertext, private_key):
''' decrypt ciphertext '''
b = map(lambda x: decrypt_byte(x, private_key), ciphertext)
plaintext = ''.join(map(unichr, b))
return plaintext
def generate_keys():
''' generate an rsa public, private key pair '''
p = random.choice(stronger_primes)
q = random.choice(stronger_primes)
n = p * q
phi_n = (p - 1) * (q - 1)
#let's find an e
for i in xrange(2, phi_n/2):
if gcd(i, phi_n) == 1:
e = i
break
else:
raise Exception('unable to find a suitable e')
d = inverse(e, phi_n)
# (public key, private key)
bits = int(math.log(n, 2))
#assert bits >= 8
public_key = (n, e, bits)
private_key = (n, d, bits)
return public_key, private_key
if __name__ == '__main__':
# run a basic test
public_key, private_key = generate_keys()
print 'public key', public_key
print 'private key', private_key
encrypted = encrypt('a', public_key)
print 'encrypted', encrypted
decrypted = decrypt(encrypted, private_key)
print 'decrypted', decrypted
assert decrypted == 'a'
assert decrypt(encrypt('secret message', public_key), private_key) == 'secret message'
|
<<<<<<< HEAD
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_CONVERT = {
'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6,
'july': 7,
'august': 8,
'september': 9,
'october': 10,
'november': 11,
'december': 12,
'all': 13}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = input('What city would you like to see the information for? ').lower()
while city != "chicago" and city != "new york city" and city != "washington":
print('\nThe city entered was incorrect.')
city = input('What city would you like to see the information for? (Chicago, New York City, Washington)')
# TO DO: get user input for month (all, january, february, ... , june)
validMonths = ['all', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
month = input('What month would you like to see the information for? ' ).lower()
while month not in validMonths:
print('\nThe month entered is not correct.')
month = input('What month would you like to see the information for? ' )
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
validDays = ['all','monday','tuesday','wednesday','thursday','friday','saturday','sunday']
day = input('What day of the week would you like to see information see? ').lower()
while day not in validDays:
print('\nThe day you entered is not valid. ')
day = input('What day of the week would you like to see information see? ')
print('-'*40)
return city, month, day.capitalize()
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
filename = CITY_DATA[city]
df = pd.read_csv(filename)
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day'] = df['Start Time'].dt.weekday_name
if month != 'all':
int_month = MONTH_CONVERT[month]
df['month'] = df['Start Time'].dt.month
df = df[(df.month == int_month)]
if day != 'all':
df['day'] = df['Start Time'].dt.weekday_name
df = df[(df.day == day)]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
# the most popular month
popular_month = df['month'].mode()[0]
print('Most popular Start Month: ', popular_month)
# TO DO: display the most common day of week
# the most popular day
popular_day = df['day'].mode()[0]
print('Most popular Start Day: ', popular_day)
# TO DO: display the most common start hour
# extract hour from the Start Time column to create an hour column
df['hour'] = df['Start Time'].dt.hour
# the most popular hour
popular_hour = df['hour'].mode()[0]
print('Most Popular Start Hour:', popular_hour)
print("\nThis took %.03f seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
common_start = df['Start Station'].mode()
print('The most common start station is: ', common_start)
# TO DO: display most commonly used end station
common_end = df['End Station'].mode()
print('The most common end station is: ', common_end)
df['Start End'] = df['Start Station'].map(str) + '&' + df['End Station']
common_both = df['Start End'].value_counts().idxmax()
print('The most common combination of the start and end stations is: ',common_both)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_time = df['Trip Duration'].sum()
print('The total travel time is: ', total_time)
# TO DO: display mean travel time
mean_time = df['Trip Duration'].mean()
print('The average travel time is: ', mean_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
# print value counts for each user type
user_types = df['User Type'].value_counts()
print(user_types)
# TO DO: Display counts of gender
if CITY_DATA != 'washington':
gender = df['Gender'].value_counts()
else:
print ('Sorry this information is not available for Washington.')
print(gender)
# TO DO: Display earliest, most recent, and most common year of birth
birth_earliest = df['Birth Year'].min()
print('The earliest birth year is: ', birth_earliest)
birth_recent = df['Birth Year'].max()
print('The most recent birth year is: ', birth_recent)
birth_common = df['Birth Year'].mode()
print('The most common birth year is: ', birth_common)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
||||||| merged common ancestors
=======
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_CONVERT = {
'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6,
'july': 7,
'august': 8,
'september': 9,
'october': 10,
'november': 11,
'december': 12,
'all': 13}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = input('What city would you like to see the information for? ').lower()
while city != "chicago" and city != "new york city" and city != "washington":
print('\nThe city entered was incorrect.')
city = input('What city would you like to see the information for? (Chicago, New York City, Washington)')
# TO DO: get user input for month (all, january, february, ... , june)
validMonths = ['all', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
month = input('What month would you like to see the information for? ' ).lower()
while month not in validMonths:
print('\nThe month entered is not correct.')
month = input('What month would you like to see the information for? ' )
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
validDays = ['all','monday','tuesday','wednesday','thursday','friday','saturday','sunday']
day = input('What day of the week would you like to see information see? ').lower()
while day not in validDays:
print('\nThe day you entered is not valid. ')
day = input('What day of the week would you like to see information see? ')
print('-'*40)
return city, month, day.capitalize()
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
filename = CITY_DATA[city]
df = pd.read_csv(filename)
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['month'] = df['Start Time'].dt.month
df['day'] = df['Start Time'].dt.weekday_name
if month != 'all':
int_month = MONTH_CONVERT[month]
df['month'] = df['Start Time'].dt.month
df = df[(df.month == int_month)]
if day != 'all':
df['day'] = df['Start Time'].dt.weekday_name
df = df[(df.day == day)]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
# the most popular month
popular_month = df['month'].mode()[0]
print('Most popular start month: ', popular_month)
# TO DO: display the most common day of week
# the most popular day
popular_day = df['day'].mode()[0]
print('Most popular start day: ', popular_day)
# TO DO: display the most common start hour
# extract hour from the Start Time column to create an hour column
df['hour'] = df['Start Time'].dt.hour
# the most popular hour
popular_hour = df['hour'].mode()[0]
print('Most Popular Start Hour:', popular_hour)
print("\nThis took %.03f seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
common_start = df['Start Station'].mode()
print('The most common start station is: ', common_start)
# TO DO: display most commonly used end station
common_end = df['End Station'].mode()
print('The most common end station is: ', common_end)
df['Start End'] = df['Start Station'].map(str) + '&' + df['End Station']
common_both = df['Start End'].value_counts().idxmax()
print('The most common combination of the start and end stations is: ',common_both)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
total_time = df['Trip Duration'].sum()
print('The total travel time is: ', total_time)
# TO DO: display mean travel time
mean_time = df['Trip Duration'].mean()
print('The average travel time is: ', mean_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
# print value counts for each user type
user_types = df['User Type'].value_counts()
print(user_types)
# TO DO: Display counts of gender
if CITY_DATA != 'washington':
gender = df['Gender'].value_counts()
else:
print ('Sorry this information is not available for Washington.')
print(gender)
# TO DO: Display earliest, most recent, and most common year of birth
birth_earliest = df['Birth Year'].min()
print('The earliest birth year is: ', birth_earliest)
birth_recent = df['Birth Year'].max()
print('The most recent birth year is: ', birth_recent)
birth_common = df['Birth Year'].mode()
print('The most common birth year is: ', birth_common)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
>>>>>>> refactoring
|
1.
class Laptop:
def __init__(self):
battery = Battery('This is charge for battery')
self.battery = [battery]
class Battery:
def __init__(self, charge):
self.charge = charge
laptop = Laptop()
2.
class Guitar:
def __init__(self, guitarstring):
self.guitarstring = guitarstring
class GuitarString:
def __init__(self):
pass
guitarstring = GuitarString()
guitar = Guitar(guitarstring)
3.
import datetime
class Calc:
@staticmethod
def add_nums(x, y, z):
return print(x + y + z)
calc = Calc()
calc.add_nums(3, 4, 5)
4.
class Pasta:
def __init__(self, ingredients):
self.ingredients = ingredients
def __repr__(self):
return f'Pasta ({self.ingredients})'
@classmethod
def carbonara(cls):
return cls(['forcemeat', 'tomatoes'])
@classmethod
def bolognaise(cls):
return cls(['bacon', 'parmesan', 'eggs'])
print(Pasta.carbonara())
print(Pasta.bolognaise())
5
class Concert:
def __init__(self, max_visitors_num):
self.max_visitors_num = max_visitors_num
@property
def visitors_count(self):
return self._visitors_count
@visitors_count.setter
def visitors_count(self, value):
self._visitors_count = value if value < self.max_visitors_num else self.max_visitors_num
concert = Concert(50)
concert.visitors_count = 1000
print(concert.visitors_count) |
import pymysql
def connectDB():
"""Ansluter till databas"""
db = pymysql.connect(host="localhost",
user="root",
passwd="",
db="yourgeo",
cursorclass=pymysql.cursors.DictCursor)
"""Skapar en cursor för databasen"""
cursor = db.cursor()
return db, cursor
def grade_question(answer, real_question_id):
"""Funktion som räknar antal rätt i quiz"""
db, cursor = connectDB()
"""skickar en fråga för att hämta fråga och svar som hör ihop och det rätta svaret från tabellen "right_answer"""
sql2 = "SELECT right_answer from answers join questions on questions.questionID=answers.answersID WHERE QuestionID = '{}' and right_answer = '{}'".format(real_question_id, answer)
"""Kör select satsen"""
cursor.execute(sql2)
"""Hämtar all data och sparar det i variabeln "resultat"""
result = cursor.fetchall()
show_result=len(result)
return show_result
def get_quiz_north():
db, cursor = connectDB()
"""skickar en fråga för att hämta alla frågor från tabellen "questions"""
sql = "SELECT * from answers join questions on questions.questionID=answers.answersID WHERE Area='{}'".format("Norra Europa")
cursor.execute(sql)
#Får svar och sparar den i variablen "north"
north = cursor.fetchall()
return north
def get_quiz_east():
db, cursor = connectDB()
"""skickar en fråga för att hämta alla frågor från tabellen "questions"""
sql = "SELECT * from answers join questions on questions.questionID=answers.answersID WHERE Area='{}'".format("Östra Europa")
cursor.execute(sql)
"""Får svar och sparar den i variablen "East"""
east = cursor.fetchall()
return east
def get_quiz_west():
db, cursor = connectDB()
"""skickar en fråga för att hämta alla frågor från tabellen "questions"""
sql = "SELECT * from answers join questions on questions.questionID=answers.answersID WHERE Area='{}'".format("Västra Europa")
cursor.execute(sql)
"""Får svar och sparar den i variablen "West"""
west = cursor.fetchall()
return west
def get_quiz_south():
db, cursor = connectDB()
"""skickar en fråga för att hämta alla frågor från tabellen "questions"""
sql = "SELECT * from answers join questions on questions.questionID=answers.answersID WHERE Area='{}'".format("Södra Europa")
cursor.execute(sql)
#Får svar och sparar den i variablen "South"
south = cursor.fetchall()
return south
|
def create_dictionary(filename):
ratings = open(filename)
restaurants = {}
for line in ratings:
name, rating = line.rstrip().split(":")
restaurants[name] = rating
ratings.close()
return restaurants
def sort_and_print(filename):
input_dict = create_dictionary(filename)
rest_list = input_dict.keys()
rest_list.sort()
for item in rest_list:
print "Restaurant %s is rated at %s" % (item, input_dict[item])
def main():
sort_and_print("scores.txt")
if __name__ == "__main__":
main() |
# A single node of a singly linked list
class Node:
def __init__(self,data):
# constructor
self.data = data
self.next = None
# A Linked List class
class LinkedList:
# constructor
def __init__(self):
self.head = None
# Return string to representation of the object
def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.insert(0,str(node.data))
node = node.next
return " , ".join(nodes)
# returns the iterator object
def __iter__(self):
node = self.head
while node is not None:
yield node
node = node.next
# Pointer to the beginning
def add_first(self,node):
node.next = self.head
self.head = node
# Pointer to the end
def add_last(self,node):
if not self.head:
self.head = node
return
for currrent_node in self:
pass
currrent_node.next=node
def compute(n):
# First value
fiboSeries = [0,1]
node = Node(0)
llist = LinkedList()
llist.add_first(node)
node = Node(1)
llist.add_last(node)
while n-2 > 0 :
n-=1
res = fiboSeries[len(fiboSeries)-1]+fiboSeries[len(fiboSeries)-2]
fiboSeries.append(res)
# make desired list
node = Node(fiboSeries[len(fiboSeries)-1])
llist.add_last(node)
return llist
if __name__ == "__main__":
n = 100
llist = compute(n)
print(llist)
|
# https://snakify.org/en/lessons/print_input_numbers/problems/
# A school decided to replace the desks in three classrooms. Each desk sits two students. Given the number of students in each class, print the smallest
# possible number of desks that can be purchased.
# The program should read three integers: the number of students in each of the three classes, a, b and c respectively.
# In the first test there are three groups. The first group has 20 students and thus needs 10 desks. The second group has 21 students, so they can get by
# with no fewer than 11 desks. 11 desks is also enough for the third group of 22 students. So we need 32 desks in total.
# round() was rounding 10.5 to 10... so I chose to use ciel instead.
import math
a = float(input('Number of students in class a: '))
b = float(input('Number of students in class b: '))
c = float(input('Number of students in class c: '))
print(math.ceil(a/2) + math.ceil(b/2) + math.ceil(c/2))
|
# https://snakify.org/en/lessons/integer_float_numbers/problems/
# Given a positive real number, print its fractional part.
import math
a = float(input('Enter a postitive real number: '))
fractional_length = len(str(a).split('.')[1])
fractional_part = a - math.floor(a)
result = round(fractional_part, fractional_length)
print(result)
|
# https://snakify.org/en/lessons/print_input_numbers/problems/
# Write a program that reads an integer number and prints its previous and next numbers. See the examples below for the exact format your answers should take. There shouldn't be a space before the period.
# Remember that you can convert the numbers to strings using the function str.
number = int(input('Enter an integer: '))
print('The previous number is ' + str(number - 1) + '.')
print('The next number is ' + str(number + 1) + '.')
|
# Livro Ciência de Dados e Aprendizado de Máquina - https://www.amazon.com.br/dp/B07X1TVLKW
# Livro Inteligência Artificial com Python - Redes Neurais Intuitivas - https://www.amazon.com.br/dp/B087YSVVXW
# Livro Redes Neurais Artificiais - https://www.amazon.com.br/dp/B0881ZYYCJ
from rbm import RBM
import numpy as np
rbm = RBM(num_visible = 6,
num_hidden = 2)
base = np.array([[1,1,1,0,0,0],
[1,0,1,0,0,0],
[1,1,1,0,0,0],
[0,0,1,1,1,1],
[0,0,1,1,0,1],
[0,0,1,0,1,0]])
filmes = ['O Exorcista',
'American Pie',
'Matrix',
'Forrest Gump',
'Documentário X',
'O Rei Leão']
rbm.train(base,
max_epochs = 3000)
rbm.weights
usuario = np.array([[1,1,0,1,0,0]])
rbm.run_visible(usuario)
camada_oculta = np.array([[0,1]])
recomendacao = rbm.run_hidden(camada_oculta)
for i in range(len(usuario[0])):
print(usuario[0,i])
if usuario[0,i] == 0 and recomendacao[0,i] == 1:
print(filmes[i])
# Livro Python do ZERO à Programação Orientada a Objetos - https://www.amazon.com.br/dp/B07P2VJVW5
# Livro Programação Orientada a Objetos com Python - https://www.amazon.com.br/dp/B083ZYRY9C
# Livro Tópicos Avançados em Python - https://www.amazon.com.br/dp/B08FBKBC9H
# Livro Ciência de Dados e Aprendizado de Máquina - https://www.amazon.com.br/dp/B07X1TVLKW
# Livro Inteligência Artificial com Python - Redes Neurais Intuitivas - https://www.amazon.com.br/dp/B087YSVVXW
# Livro Redes Neurais Artificiais - https://www.amazon.com.br/dp/B0881ZYYCJ
# Livro Análise Financeira com Python - https://www.amazon.com.br/dp/B08B6ZX6BB
# Livro Arrays com Python + Numpy - https://www.amazon.com.br/dp/B08BTN6V7Y
|
def merge_sort(in_numbers):
if len(in_numbers) > 1:
left_part = in_numbers[:len(in_numbers)//2]
right_part = in_numbers[len(in_numbers)//2:]
merge_sort(left_part)
merge_sort(right_part)
i = 0 #index for left
j = 0 #index for right
k = 0 #index for in_numbers
while(i < len(left_part) and j < len(right_part)):
if (left_part[i] < right_part[j]):
in_numbers[k] = left_part[i]
i += 1
else:
in_numbers[k] = right_part[j]
j += 1
k += 1
if (i < len(left_part)):
in_numbers[k:] = left_part[i:]
elif (j < len(right_part)):
in_numbers[k:] = right_part[j:]
if __name__ == '__main__':
ls = [3,5,7,85,3,2,45,8]
print(ls)
merge_sort(ls)
print(ls)
|
"""
file_read.py
文件读取演示
"""
# 打开文件
f = open('Install.txt','r')
# 读取文件
# data = f.read()
# print(data)
# 循环读取文件内容
# while True:
# # 如果读到文件结尾 read()会读到空字符串
# data = f.read(1024)
# # 读到结尾跳出循环
# if not data: # 当data为None的时候返回False,所以not data为True才会执行break
# break
# print(data)
# 读取文件一行内容
# data = f.readline()
# print(data)
# data = f.readline(5) #读取5个字符
# print(data)
# 读取内容形成列表
# data = f.readlines(20) # 读取前20个字节所在的所有行
# print(data)
# 用open打开的对象为可迭代对象
# 使用for循环读取每一行
for line in f:
print(line) # 每次迭代到一行内容
# 关闭
f.close()
|
i,j,tmp = 0,0,0
list = [5,3,1,9,8,2,4]
for i in range(7):
for j in range(i+1,7):
if(list[i]>list[j]):
tmp = list[i]
list[i] = list[j]
list[j] = tmp
print(list) |
def addItUP:
sum = 0
for num in range(n+1):
sum+=num
return num |
# krok 1. pozyskanie słownictwa występującego w naszych danych
import pandas as pd
import nltk
from nltk.corpus import words
vocabulary = {}
data = pd.read_csv('emails_data.csv')
nltk.download('words')
set_words = set(words.words())
def build_vocabulery(curr_email):
i = len(vocabulary)
for word in curr_email:
if word.lower() not in vocabulary and word.lower() in set_words:
vocabulary[word] = i
i += 1
if __name__ == "__main__":
for i in range(data.shape[0]):
curr_email = data.iloc[i, 0].split()
build_vocabulery(curr_email,)
print(f'Current email is {i}/{data.shape[0]} and the length of vocab is {len(vocabulary)}')
file = open("vocabulary.txt", 'w')
file.write(str(vocabulary))
file.close()
|
f = int(input())
t = int(input())
d = int(input())
m = f
if m < t:
m = t
if m < d:
m = d
print(m) |
class Rent:
"""
Object which contains data about a particular bill, including
the amount and period of the bill.
"""
def __init__(self, amount, period):
self.amount = amount
self.period = period
class Housemate:
"""
Person who lives in the home and pays a share of the rent
based on the size of their room or living quarters (in sq-ft).
"""
def __init__(self, name, room_size):
self.name = name
self.room_size = room_size
def pays(self, rent, housemates: []):
total_size = self.room_size
for housemate in housemates:
total_size += housemate.room_size
amount_due = rent.amount * (self.room_size / total_size)
return '%.2f' %amount_due |
"""Define Franc Class."""
# for return Franc itself at method times()
from __future__ import annotations
from ch6.money import Money
class Franc(Money):
"""Define Franc Class."""
def times(self, multiplier: int) -> Franc:
"""multiplication."""
return Franc(self.amount * multiplier)
|
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
import os
def melt(df):
"""Melting the dataframe, returning a melted df, a list of species and a list of genes."""
species_columns = [x for x in df.columns if x != 'gene_name'] # getting the columns with species names
melted_df = pd.melt(df, id_vars=['gene_name'], value_vars=species_columns, var_name='Species',
value_name='Orthologues') # melting
melted_df.columns = ['Gene Name', 'Species', 'Orthologues'] # Changing column names
# species list
species = sorted(species_columns)
# genes list
genes = sorted(melted_df['Gene Name'].unique().tolist())
return melted_df, species, genes
# receives melted_df
def create_swarmplot(df, path, title, colormap, genes, species):
"""
The function creates a swarmplot using seaborn.
:param df: pandas.DataFrame object
:param path: The CSV file path.
:param title: Title for the plot.
:param colormap: Colormap
:param genes: Ordered list of genes.
:param species: Ordered list of species.
:return:
"""
print("Creating swarmplot for {}".format(path))
output_path = os.path.dirname(path)
output = join_folder(output_path, "%s_swarmplot.png" % title)
fig = plt.figure(figsize=(16, 10), dpi=180) # new figure
sns.swarmplot(x='Gene Name', y='Orthologues', hue='Species', order=genes, hue_order=species, data=df,
palette=colormap) # draw swarmplot
plt.ylabel("# Orthologues")
plt.xlabel("Gene Name")
plt.ylim(0, )
plt.yticks(fontsize=10)
plt.xticks(fontsize=10)
plt.savefig(output) # saving figure as output
plt.close()
return output
# receives melted_df
def create_barplot(df, path, title, colormap, genes, species):
"""
The function creates a bar plot using seaborn.
:param df: pandas.DataFrame object
:param path: The CSV file path.
:param title: Title for the plot.
:param colormap: Colormap
:param genes: Ordered list of genes.
:param species: Ordered list of species.
:return:
"""
print("Creating bar plot for {}".format(path))
output_path = os.path.dirname(path)
output = join_folder(output_path, "%s_barplot.png" % title)
fig = plt.figure(figsize=(16, 10), dpi=180)
sns.barplot(x='Gene Name', y='Orthologues', hue='Species', order=genes, hue_order=species, data=df,
palette=colormap)
plt.ylabel("#Orthologues")
plt.xlabel("Gene Name")
plt.ylim(0, )
# plt.suptitle(title, fontsize=16)
plt.yticks(fontsize=10)
plt.xticks(fontsize=10)
plt.savefig(output)
plt.close()
return output
# receives melted_df
def create_barplot_orthologues_by_species(df, path, title, colormap, genes, species):
"""
The function creates a bar plot using seaborn.
:param df: pandas.DataFrame object
:param path: The CSV file path.
:param title: Title for the plot.
:param colormap: Colormap
:param genes: Ordered list of genes.
:param species: Ordered list of species.
:return:
"""
print("Creating barplot by species for {}".format(path))
output_path = os.path.dirname(path)
output = join_folder(output_path, "%s_barplot_byspecies.png" % title)
fig = plt.figure(figsize=(16, 10), dpi=180)
sns.barplot(x='Species', y='Orthologues', hue='Gene Name', data=df, order=species, hue_order=genes,
palette=colormap)
plt.ylabel("#Orthologues")
plt.xlabel("Species")
plt.ylim(0, )
# plt.suptitle(title, fontsize=16)
plt.yticks(fontsize=10)
plt.xticks(fontsize=10)
plt.savefig(output)
plt.close()
return output
def create_barplot_sum(df, path, title, colormap, species):
"""
The function creates a bar plot of the sum of orthologues found using seaborn.
:param df: pandas.DataFrame object
:param path: The CSV file path.
:param title: Title for the plot.
:param colormap: Colormap
:param species: Ordered list of species.
:return:
"""
print("Creating barplot of sum for {}".format(path))
output_path = os.path.dirname(path)
output = join_folder(output_path, "%s_barplot_sum.png" % title)
fig = plt.figure(figsize=(16, 10), dpi=180)
sns.barplot(x='Species', y='Orthologues', estimator=sum, ci=None, data=df, order=species, palette=colormap)
plt.ylabel("#Orthologues")
plt.xlabel("Species")
plt.ylim(0, )
# plt.suptitle(title, fontsize=16)
plt.yticks(fontsize=10)
plt.xticks(fontsize=10)
plt.savefig(output)
plt.close()
return output
def create_heatmap(df, path, title, colormap):
"""
Creates a heatmap for the Gene/Species orthologue data.
:param title: The title of the figure
:param df: a padnas.DataFrame object (not melted)
:param path: Path for the input and output file
:param colormap: Colormap
:return:
"""
print("Creating heatmap for {}".format(path))
output_path = os.path.dirname(path)
fig = plt.figure(figsize=(16, 10), dpi=180)
plt.title(title, fontsize=16)
sns.heatmap(df, annot=True, fmt="d", cmap=colormap)
plt.yticks(fontsize=10)
plt.xticks(fontsize=10)
output = join_folder(output_path, "%s_heatmap.png" % title)
plt.savefig(output)
plt.close()
return output
def create_clustermap(df, path, title, colormap, col_cluster, dont_cluster):
"""
Creates a cluster map for the Gene/Species orthologue data.
:param dont_cluster: if True, skip clustering and return a blank image.
:param col_cluster: if True, cluster the columns.
:param title: The title of the figure
:param df: a padnas.DataFrame object (not melted)
:param path: Path for the input and output file
:param colormap: Colormap
:return:
"""
print("Creating clustermap for {}".format(path))
output_path = os.path.dirname(path)
output = join_folder(output_path, "%s_clustermap.png" % title)
fig = plt.figure(figsize=(16, 10), dpi=180)
if not dont_cluster: # if we want to cluster the columns (in case we have more than 2 columns)
sns.clustermap(df, annot=True, col_cluster=col_cluster, fmt="d", cmap=colormap, linewidths=.5)
# plt.suptitle(title, fontsize=16)
plt.yticks(fontsize=10)
plt.xticks(fontsize=10)
plt.savefig(output) # save the figure
plt.close()
return output
# generate heatmap and clustermap
def generate_visual_graphs(csv_rbh_output_filename, csv_strict_output_filename, csv_ns_output_filename):
"""
The function generates heatmap + clustermap for the output data.
:param csv_rbh_output_filename:
:param csv_strict_output_filename:
:param csv_ns_output_filename:
:return:
"""
# reading as data_frame (for heat/clustermaps)
nonstrict_data = pd.read_csv(csv_ns_output_filename, index_col=0)
strict_data = pd.read_csv(csv_strict_output_filename, index_col=0)
rbh_data = pd.read_csv(csv_rbh_output_filename, index_col=0)
# transpose data
df_nonstrict = pd.DataFrame.transpose(nonstrict_data)
df_strict = pd.DataFrame.transpose(strict_data)
df_rbh = pd.DataFrame.transpose(rbh_data)
# reading for other plots and melting them:
melt_df_nonstrict, species_list, genes_list = melt(pd.read_csv(csv_ns_output_filename))
melt_df_strict, species_list, genes_list = melt(pd.read_csv(csv_strict_output_filename))
melt_df_rbh, species_list, genes_list = melt(pd.read_csv(csv_rbh_output_filename))
print "Species list is: {}".format(species_list)
print "Genes list is: {}".format(genes_list)
# clustering enabler (( one is enough because all files contains the same amount of genes ))
dont_cluster = False
col_cluster = False
if len(df_nonstrict.columns) > 2:
col_cluster = True
elif len(df_nonstrict.columns) < 2 or len(df_nonstrict) < 2:
dont_cluster = True
# visual outputs:
viz_dict = dict()
print("Creating heatmaps and clustermpaps")
# non-strict
viz_dict['non_strict_heatmap'] = create_heatmap(df_nonstrict, csv_ns_output_filename, 'non_strict', "BuGn")
viz_dict['non_strict_clustermap'] = create_clustermap(df_nonstrict, csv_ns_output_filename, 'non_strict', "PuBu",
col_cluster, dont_cluster)
viz_dict['non_strict_barplot'] = create_barplot(melt_df_nonstrict, csv_ns_output_filename, 'non_strict', "BuGn",
genes_list, species_list)
viz_dict['non_strict_barplot_2'] = create_barplot_orthologues_by_species(melt_df_nonstrict, csv_ns_output_filename,
'non_strict', "BuGn",
genes_list, species_list)
viz_dict['non_strict_swarmplot'] = create_swarmplot(melt_df_nonstrict, csv_ns_output_filename, 'non_strict', "BuGn",
genes_list, species_list)
viz_dict['non_strict_barplotsum'] = create_barplot_sum(melt_df_nonstrict, csv_ns_output_filename,
'non_strict', "BuGn", species_list)
# strict
viz_dict['strict_heatmap'] = create_heatmap(df_strict, csv_strict_output_filename, 'strict', "Oranges")
viz_dict['strict_clustermap'] = create_clustermap(df_strict, csv_strict_output_filename, 'strict', "YlOrRd",
col_cluster, dont_cluster)
viz_dict['strict_barplot'] = create_barplot(melt_df_strict, csv_strict_output_filename, 'strict', "YlOrRd",
genes_list, species_list)
viz_dict['strict_barplot_2'] = create_barplot_orthologues_by_species(melt_df_strict, csv_strict_output_filename,
'strict', "YlOrRd", genes_list, species_list)
viz_dict['strict_swarmplot'] = create_swarmplot(melt_df_strict, csv_strict_output_filename,
'strict', "YlOrRd", genes_list, species_list)
viz_dict['strict_barplotsum'] = create_barplot_sum(melt_df_strict, csv_strict_output_filename,
'strict', "YlOrRd", species_list)
# RBH
viz_dict['RBH_heatmap'] = create_heatmap(df_rbh, csv_rbh_output_filename, 'RBH', "YlGnBu")
viz_dict['RBH_clustermap'] = create_clustermap(df_rbh, csv_rbh_output_filename, 'RBH', "YlGnBu", col_cluster,
dont_cluster)
viz_dict['RBH_barplot'] = create_barplot(melt_df_rbh, csv_rbh_output_filename, 'RBH', "YlGnBu", genes_list,
species_list)
viz_dict['RBH_barplot_2'] = create_barplot_orthologues_by_species(melt_df_rbh, csv_rbh_output_filename, 'RBH',
"YlGnBu", genes_list, species_list)
viz_dict['RBH_swarmplot'] = create_swarmplot(melt_df_rbh, csv_rbh_output_filename, 'RBH', "YlGnBu",
genes_list, species_list)
viz_dict['RBH_barplotsum'] = create_barplot_sum(melt_df_rbh, csv_rbh_output_filename, 'RBH', "YlGnBu",
species_list)
return viz_dict
join_folder = os.path.join |
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '127.0.0.1';
port = 2589;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
#Send some data to remote server
data = input("Enter Text: ");
try :
#Set the whole string
s.sendall(data)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096)
print reply
s.close() |
import turtle;
t=turtle.Turtle();
s=turtle.Screen();
s.bgcolor('black')
t.pencolor('blue')
a=0
b=0
#c=0
#d=0
t.speed(0)
t.penup()
t.goto(0,200)
t.pendown()
while True:
t.forward(a)
t.right(b)
#t.left(c)
#t.backward(d)
a+=3
b+=1
#c+=2
#d+=4
if b == 210:
break
t.hideturtle()
t.bye()
t.done() |
x_crazy_landlords = ['Cruella de Ville', 'Donald Duck', 'Popeye the Maltese']
counter = 1
print('loop started')
for landlord in x_crazy_landlords:
print(counter, '-', landlord)
counter += 1
print('loop ended')
spartans = [['shav', 'adam', 'julian', 'muji', 'ally'], ['pratheep', 'zaid', 'omid', 'payal', 'micheal']]
counter = 1
for team in spartans:
for name in team:
print('hello', name, 'you are on team', counter)
counter += 1
|
# Group 4: Trinidad Ramirez, Jerridan Bonbright, Illia Sapryga, Christopher Flores
# Team Programming Assignment 3
# CST 311
# TCPClient.py
# Why is multithreading needed to solve this assignment?
# Incorporating multiple threads in the program creates parallel execution, which
# is significantly more efficient with regards to program performance. Multithreading
# gives the server the ability to multi-task, and it allows various clients to
# connect to it simultaneously. One of the goals with multi-threading is to ensure
# program flow optimization. Some operations like send() can hinder the program's
# performance without multi-threading
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
from socket import *
message = ""
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
while True:
message = clientSocket.recv(1024).decode()
# Run this loop if message is not null
if len(message) > 0:
print('\nFrom Server: ' + message + '\n')
# Grabs input from user and sends to server
# Note: raw_input is used here. Py 3 says it doesn't support it, but it will still work when ran in Mininet
message = raw_input('Enter message to send to server: ')
clientSocket.send(message.encode())
# Decode nessage and print to console
clientSentence = clientSocket.recv(1024).decode('utf-8')
print('From Server: ' + clientSentence)
clientSocket.close() |
from pystack.exc import EmptyStackError
class Stack(object):
"""A list-based stack implementation.
Attributes:
_data (list): Private list maintaining stack elements
"""
def __init__(self):
"""Initialises an empty stack."""
self._data = []
def is_empty(self):
"""Checks if the stack is empty.
Returns:
True if the stack is empty, False otherwise.
"""
return len(self._data) == 0
def push(self, item):
"""Pushes an item onto the stack.
Returns:
The pushed item.
"""
self._data.append(item)
return item
def pop(self):
"""Removes and returns the item ontop of the stack.
Returns:
The last item added to the stack.
Raises:
EmptyStackError: given the an already empty stack.
"""
if self.is_empty():
raise EmptyStackError()
item = self._data[len(self._data) - 1]
del self._data[len(self._data) - 1]
return item
class IntStack(Stack):
"""A list-based stack implementation for `int`s."""
def push(self, item: int) -> int:
"""Pushes an `int` item onto the stack.
Returns:
The pushed `int`.
Raises:
TypeError: given the item is not an `int`.
"""
if not isinstance(item, int):
raise TypeError()
return super().push(item)
def pop(self) -> int:
return super().pop()
|
def pagination(array, page, size):
if page is not None and size is not None:
if type(page) is str and page.isnumeric():
page = int(page)
if type(size) is str and size.isnumeric():
size = int(size)
p = page - 1
start = p * size
end = page * size
return array[start:end]
else:
return array |
# -*- encoding=utf-8 -*-
"""
proxy 模式
一个常见的用法就是延迟实际的求值操作
"""
class Rectangle(object):
def __init__(self, height, width):
print 'Create a Rectangle'
self._height = height
self._width = width
def draw(self):
print 'A rectangle of size: {height}x{width} = {size}'.format(height=self._height,
width=self._width,
size=self._width*self._height)
class RectangleProxy(object):
def __init__(self, height, width):
print 'Create a Proxy'
self.height = height
self.width = width
self._last_height = height
self._last_width = width
self._instance = None
def draw(self):
if not self._instance \
or self._last_width != self.width \
or self._last_height != self.height:
self._instance = Rectangle(self.height, self.width)
self._last_height = self.height
self._last_width = self.width
self._instance.draw()
if __name__ == '__main__':
height, width = 10, 20
rectangle = RectangleProxy(height, width)
rectangle.draw()
rectangle.width = 30
rectangle.draw() |
# -*- encoding=utf-8 -*-
"""
FlyWeight 模式
用于处理大量重复的类的共享
"""
class DigitFactory(object):
def __init__(self):
self._digits = {}
def get_digit(self, key):
if key not in self._digits:
self._digits[key] = Digit(key)
return self._digits[key]
class Digit(object):
def __init__(self, name):
self.name = name
class NewDigit(object):
_digits = {}
def __new__(cls, key):
if key not in cls._digits:
cls._digits[key] = super(NewDigit, cls).__new__(cls, key)
return cls._digits[key]
def __init__(self, key):
self._key = key
if __name__ == '__main__':
factory = DigitFactory()
a1 = factory.get_digit('A')
a2 = factory.get_digit('A')
b = factory.get_digit('B')
assert id(a1) == id(a2)
assert id(a1) != id(b)
a3 = NewDigit('a')
a4 = NewDigit('a')
assert id(a3) == id(a4)
|
import random
for i in range(1,5):
random_num = random.uniform(0,1)
rounded = round(random_num)
total_heads = 0
total_tails = 0
if rounded == 1:
total_heads += 1
print "Attempt: #{} Throwing a coin.. Its a Head! got {} head(s) so far and {} tail(s) so far".format(i,total_heads, total_tails)
else:
total_tails += 1
print "Attempt: #{} Throwing a coin.. Its a Tail! got {} head(s) so far and {} tail(s) so far".format(i,total_heads, total_tails)
# x_rounded = round(x)
# y_rounded = round(y)
# print x_rounded, y_rounded |
'''
1.常用元字符
. 匹配任意除换行符"\n"外的字符
+ 匹配前一个字符1次或无限次
.+匹配多个除换行符"\n"外的字符
?匹配一个字符0次或1次,还有一个功能是可以防止贪婪匹配
^ 匹配字符串开头
$ 匹配字符串末尾
| 匹配该符号两边的一个
() 匹配括号内的表达式,也表示一个组
[] 匹配字符组中的字符
[^]匹配除了字符组中字符的所有字符
{n} 重复n次
{n,}重复n次或更多次
{n,m}重复n到m次
2.预定义字符集表
\d 匹配数字
\D 匹配非数字
\w 匹配字母或数字或下划线
\W 匹配非字母或数字或下划线
\s 匹配任意的空白符
\S 匹配非空白符
\n 匹配一个换行符
\t 匹配一个制表符
\A 仅匹配字符串开头,同^
\Z 仅匹配字符串结尾,同$
\b 匹配一个单词边界,也就是指单词和空格间的位置
'''
# 正则表达式基础
import re
str1 = 'newdream'
str2 = '''
hello123hello
hello123
hello12
12hello
hello12ho
''' # 以换行开头
# 方式一:
pattern_01 = re.compile('n\w+m')
result_01 = re.match(pattern_01,str1)
print(result_01.group())
pattern_02 = re.compile('hello\d+h')
result_02 = re.findall(pattern_02,str2)
print(result_02)
# 方式二:
result_03 = re.match('n\w+m',str1)
print(result_03.group())
# 方式三:
result_04 = pattern_01.match(str1)
print(result_04.group()) |
#-*- coding:utf-8 -*-
#startTimeStr : '2008-08-10'
#endTimeStr : '2008-09-10'
#Iteration Range : 'D' = day, 'H' = hour
#USAGE 1 : getTimeList('2008-08-01', '2008-08-10', 'H')
#USAGE 2 : getTimeList('2008-08-01', '2008-08-10', 'D')
#RESULT 1 : '2008-08-01 00:00:00', '2008-08-01 01:00:00' ...
# '2008-08-10 22:00:00', '2008-08-10 23:00:00'
#RESULT 2 : '2008-08-01 00:00:00', '2008-08-02 00:00:00' ...
# '2008-08-09 00:00:00', '2008-08-10 00:00:00'
from time import *
def getTimeList(startTimeStr, endTimeStr, rangeType):
#init vars
startTime = ''
endTime = ''
startTimeDigit = 0
endTimeDigit = 0
addRange = 0
timeList = []
#set rangeTime
if rangeType == 'H':
addRange = 60 * 60
elif rangeType == 'D':
addRange = 60 * 60 * 24
else:
return []
#set startTime, endTime
startTime = strptime(startTimeStr, '%Y-%m-%d')
startTimeDigit = mktime(startTime)
endTime = strptime(endTimeStr + " 23:59:59", '%Y-%m-%d %H:%M:%S')
endTimeDigit = mktime(endTime)
if startTimeDigit >= endTimeDigit:
timeList.append(strftime('%Y-%m-%d %H:%M:%S', localtime(startTimeDigit)))
return timeList
#set time list
while True:
if startTimeDigit > endTimeDigit:
break;
timeList.append(strftime('%Y-%m-%d %H:%M:%S', localtime(startTimeDigit)))
startTimeDigit += addRange
return timeList
def getTimeTuple(startTimeStr, endTimeStr, rangeType):
#init vars
startTime = ''
endTime = ''
startTimeDigit = 0
endTimeDigit = 0
addRange = 0
timeList = []
timeTuple = ()
#set rangeTime
if rangeType == 'H':
addRange = 60 * 60
elif rangeType == 'D':
addRange = 60 * 60 * 24
else:
return ()
#set startTime, endTime
startTime = strptime(startTimeStr, '%Y-%m-%d')
startTimeDigit = mktime(startTime)
endTime = strptime(endTimeStr + " 23:59:59", '%Y-%m-%d %H:%M:%S')
endTimeDigit = mktime(endTime)
if startTimeDigit >= endTimeDigit:
timeList.append(localtime(startTimeDigit))
return timeTuple
#set time tuple
while True:
if startTimeDigit > endTimeDigit:
break;
timeList.append(localtime(startTimeDigit))
#print localtime(startTimeDigit)
startTimeDigit += addRange
timeTuple = tuple(timeList)
return timeTuple
|
#!/usr/bin/env python
"""
Usage
for vals in rand_graph(10, 4):
print vals
"""
import random
DB_RANGE = (-60, -50)
def rand_graph(num, conn):
"Creates a random graph with n elments"
for x in range(0, num):
for y in range(x+1, num):
if random.random() * conn > 1:
val = float(random.randrange(*DB_RANGE))
yield(x, y, val)
yield(y, x, val + random.randrange(3))
# FIXME: if MAX_NODES not multiple of 4 something strange could happen
def bin_tree(dim):
"Generates a binary tree connection"
for x in range((2 ** dim) - 1):
yield (x, x * 2 + 1)
yield (x, (x+1) * 2)
def network_to_hops_parents(topo):
"""
Given a topology as a list of couples return the a dictionary
with the minimal hops and the parent
"""
parents, hops, grid = {}, {}, {}
for x, y in topo:
if x in grid:
grid[x].append(y)
else:
grid[x] = []
if y in grid:
grid[y].append(x)
else:
grid[y] = []
# we build the structure starting from node 0
for x in grid:
parents[x] = None
hops[x] = 255
idx = 0
parents[idx] = 0
hops[idx] = 0
# just use a BFS algorithm here
def sim_txt_to_png(topo_file):
topo = []
for line in open(topo_file):
vals = line.split()
topo.append((int(vals[0]), int(vals[1])))
topology_to_png(topo, topo_file.split(".")[0])
def topology_to_png(topology, filename):
try:
import pydot
except ImportError:
print "you need to install pydot for this"
return
p = pydot.Dot()
for x, y in topology:
p.add_edge(pydot.Edge(str(x), str(y)))
f = filename + ".png"
print "writing out to %s" % f
p.write_png(f)
def to_dist_dict(nodes, topo):
# they're simply all 1 in this case, when no connection use -1
d = {}
for n1 in nodes:
for n2 in nodes:
if n1 == n2:
d[(n1,n2)] = 0
elif ((n1, n2) in topo) or ((n2, n1) in topo):
d[(n1,n2)] = d[(n2,n1)] = 1
else:
d[(n1,n2)] = d[(n2,n1)] = -1
return d
# FIXME: check this algorithm is buggy in some situations
def floyd_warshall(cities, dist):
dim = len(cities)
old = new = {}
# first cycle to set the initial configuration
for c1 in cities:
for c2 in cities:
old[(c1, c2)] = [dist[(c1, c2)], [c2]]
# ranging over the distance between nodes
for k in range(1, dim):
for c1 in cities:
for c2 in cities:
diretto = old[(c1, c2)]
before = old[(c1, cities[k-1])]
after = old[(cities[k-1], c2)]
if diretto[0] <= (before[0] + after[0]):
new[(c1, c2)] = diretto
else:
new[(c1, c2)] = [before[0] + after[0], before[1]+after[1]]
old = new
return new
def hops_parent(min_dists, nodes, root_node):
"Get the ouput from floyd_warshall and compute the distance and the parent"
hops = parents = {}
# take always the before last with s[len(s)-2]
for n in nodes:
inf = min_dists[(n, root_node)]
hops[n] = inf[0]
parents[n] = inf[1][len(inf[1])-2]
return hops, parents
# nodes = [1,2,3]
# dist_dict = to_dist_dict(nodes, [(1,2), (2,3)])
# print dist_dict
# fl = floyd_warshall(nodes, dist_dict)
# print fl
# print hops_parent(fl, nodes, 1)
|
import random
from src import cell
RED = (255, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
class Maze:
"""Object used to represent a maze and the information needed to specify the dimensions, cells contained, start and finish.
"""
def __init__(self, size, scale):
self.directions = {"above":(0, -1), "below":(0, 1), "left":(-1, 0), "right":(1,0)}
self.size = size
self.scale = scale
self.start = None
self.end = None
self.grid = []
self.create_cells()
self.mesh_cells()
self.set_start_end()
def create_cells(self):
"""Method to create the required number of cells for the maze.
"""
for i in range(self.size):
temp = []
for j in range(self.size):
temp.append(cell.Cell(i, j, self.scale))
self.grid.append(temp)
def mesh_cells(self):
"""Method to mesh the cells of the grid together so they are connected for usage and manipulation.
"""
for row in self.grid:
for cell in row:
for direction, (x,y) in self.directions.items():
if cell.x + x < 0 or cell.y + y < 0:
cell.neighbors[direction] = None
elif cell.x + x == self.size or cell.y + y == self.size:
cell.neighbors[direction] = None
else:
cell.neighbors[direction] = self.grid[cell.x + x][cell.y + y]
def set_start_end(self):
"""Method to set the start and end of the maze, by randomly picking two locations and setting the corresponding information in cells chosen.
"""
start = (random.randint(0, self.size-1), random.randint(0, self.size-1))
end = start
while start == end:
end = (random.randint(0, self.size-1), random.randint(0, self.size-1))
self.start = self.grid[start[0]][start[1]]
self.end = self.grid[end[0]][end[1]]
self.start.isStart = True
self.end.isEnd = True
self.start.background = BLUE
self.end.background = RED
def update_start_end(self):
"""Method to update the start and end of the maze.
"""
for row in self.grid:
for cell in row:
if cell.isStart:
self.start = cell
elif cell.isEnd:
self.end = cell
def change_start(self, new_start):
"""Method to change the location of the start of the maze and remove the previous start location information.
Arguments:
new_start {Cell} -- The new starting location for the maze.
"""
self.start.isStart = False
self.start.background = WHITE
self.start = new_start
self.start.isStart = True
self.start.background = BLUE
def change_end(self, new_end):
"""Method to change the location of the end of the maze and remove the previous end location information.
Arguments:
new_end {Cell} -- The new ending location for the maze.
"""
self.end.isEnd = False
self.end.background = WHITE
self.end = new_end
self.end.isEnd = True
self.end.background = RED
|
import numpy as np
class QLearningAgent():
def agent_init(self, agent_info):
"""Object instance of a Q-Learning agent that utilizes a model-free algorithm to learn a policy and identify an optimal action-selection policy.
num_actions {int} -- The number of actions the agent can take in the environment
num_states {int} -- The number of states the agent can be in throughout the environment
epsilon {float} -- The rate at which the agent will choose to explore
step_size {float} -- The rate at which the agent will learn from each step
discount {float} -- The amount that a reward is discounted valuing immediate, future or intermediate rewards
rand_seed {int} -- The number of random values generated
"""
# Set the agents parameters
self.num_actions = agent_info["num_actions"]
self.num_states = agent_info["num_states"]
self.epsilon = agent_info["epsilon"]
self.step_size = agent_info["step_size"]
self.discount = agent_info["discount"]
self.rand_generator = np.random.RandomState(agent_info["seed"])
# Initialize the action-value estimates to zero
self.q = np.zeros((self.num_states, self.num_actions))
def agent_start(self, state):
"""Method called at the start of each episode to select the first action given a starting state.
Arguments:
state {int} -- The initial start state in the environment.
Returns:
action {int} -- The initial action taken by the agent.
"""
# Select the list of action-value estimates for the current state
current_q = self.q[state,:]
# Select the action that the agent will take in the current state
action = self.action_selection(state, current_q)
self.prev_state = state
self.prev_action = action
return action
def agent_step(self, reward, state):
"""Method called at each step to evaluate whether the agent will take an exploration action or a greedy action in the state-space. Then update action-value estimates for the previous state and previous action given the maximized action value estimate of the current state and action.
Arguments:
reward {float} -- The reward received for the last action taken from self.prev_action, self.prev_state
state {int} -- The state in the environment that the agent ended up in after taking the last step.
Returns:
action {int} -- The action that the agent decided to take.
"""
# Select the list of action-value estimates for the current state
current_q = self.q[state,:]
# Select the action that the agent will take in the current state
action = self.action_selection(state, current_q)
self.q[self.prev_state, self.prev_action] = self.q[self.prev_state, self.prev_action] + (self.step_size*(reward + (self.discount * np.max(current_q))-self.q[self.prev_state, self.prev_action]))
self.prev_state = state
self.prev_action = action
return action
def agent_end(self, reward):
"""Method called in the terminal state where the final action-value estimate update is performed given the previous state and action.
Arguments:
reward {float} -- The reward the agent received for entering the terminal state.
"""
self.q[self.prev_state, self.prev_action] = self.q[self.prev_state, self.prev_action] + (self.step_size*(reward - self.q[self.prev_state, self.prev_action]))
def argmax(self, q_values):
"""argmax with random tie-breaking
Args:
q_values (Numpy array): the array of action-values
Returns:
action (int): an action with the highest value
"""
top = float("-inf")
ties = []
for i in range(len(q_values)):
if q_values[i] > top:
top = q_values[i]
ties = []
if q_values[i] == top:
ties.append(i)
return self.rand_generator.choice(ties)
def action_selection(self, state, current_q):
"""Method called in choosing whether to explore or take the action which would provide a greedy action-value estimate
Arguments:
state {int} -- The current state that the agent is in
Returns:
action {int} -- The action that the agent will take in the current state
"""
# Randomly generate a number between 0 and 1
# If the number is less than epsilon, explore
if self.rand_generator.rand() < self.epsilon:
action = self.rand_generator.randint(self.num_actions)
#print("rand" + str(current_q) + " state: "+ str(state) + " action: "+ str(action))
return action
# If the number is greater than epsilon, choose the greedy option
else:
action = self.argmax(current_q)
#print("greedy" + str(current_q) + " state: "+ str(state) + " action: "+ str(action))
return action
|
#a) The password length should be in range 6-16 characters
#b) Should have atleast one number
#c) Should have atleast one special character in [$@!*]
#d) Should have atleast one lowercase and atleast one uppercase character
passwd = input("Enter password : ") #take password from user
#validate password
length = len(passwd) # get length of password
invalidLength = digityes = loweryes = upperyes = specialChar = False; #set all the boolean varabiles to false
if (length < 6 or length > 16): #check length if length invalid set invalidLength true
invalidLength = True;
for i in range(0, length):
if (passwd[i].isnumeric()): #check if cahr is numeric, set digityes to True
digityes = True;
if(passwd[i].islower()): # check if char is lower, set loweryes to True
loweryes = True;
if(passwd[i].isupper()): # check if char is upper, set upperyes to True
upperyes = True;
# if any char is special char $@!* , set specialChar to True
if( passwd[i]=='$' or passwd[i]=='@' or passwd[i]=='!' or passwd[i]=='*' ):
specialChar = True;
#if any one bollean value is False then print password is invalid
if (invalidLength or (digityes == False) or (loweryes == False) or (upperyes == False) or ( specialChar == False)) :
print("INVALID PASSWORD ")
print("The password length should be in range 6-16 characters")
print("Should have atleast one number")
print("Should have atleast one special character in [$@!*]")
print("Should have atleast one lowercase and atleast one uppercase character")
else:
print("VALID PASSWORD ENTERED") |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 21:27:30 2018
@author: Ju-Un Park
"""
#Chapter 9 CLASSES
# Creating and using a class
# Creating the dog class
class Dog():
""" A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize anme and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(self.name.title() + " is now sitting.")
def roll_over(self):
"""simulate rolling over in response to a command."""
print(self.name.title() + " rolled over!")
# Making an instance from a class
my_dog = Dog('willie', 6)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
# calling Methods
my_dog.sit()
my_dog.roll_over()
# Creating multiple instances
my_dog = Dog('willie', 6)
your_dog = Dog('lucy', 3)
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
print("\nYour dog's name is " + your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age) + " years old.")
your_dog.sit()
# 9-1
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and type attribute"""
self.name = restaurant_name
self.type = cuisine_type
def describe_restaurant(self):
"""describing the restaurant"""
print(self.name.title() + " is the " + self.type.title() + " restaurant.")
def open_restaurant(self):
"""prints a message indicating that the restaurant is open"""
print(self.name.title() + " is now open!")
first_restaurant = Restaurant('Than Brothers', 'vietnamese')
print(first_restaurant.name)
print(first_restaurant.type)
first_restaurant.describe_restaurant()
first_restaurant.open_restaurant()
# 9-2
second_restaurant = Restaurant('Gawon', 'korean')
third_restaurant = Restaurant('red robins', 'american')
second_restaurant.describe_restaurant()
third_restaurant.describe_restaurant()
# 9-3
class User():
def __init__(self, first, last, username, age, email):
self.first_name = first
self.last_name = last
self.username = username
self.age = age
self.email = email
def describe_user(self):
print("Name: " + self.first_name.title() + " " + self.last_name.title())
print("Username: " + self.username)
print("Age: " + str(self.age))
print("Email Address: " + self.email)
def greet_uesr(self):
print("Hello, " + self.username + "!")
bbakjoo = User('Ju-Un', 'Park', 'bbakjoo', 33, 'pju2000@gmail.com')
bbakjoo.describe_user()
bbakjoo.gree_uesr()
# Working with classes and instances
class Car():
""" A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""Return a neatly formateed descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
my_new_car = Car('audi' , 'a4', 2016)
print(my_new_car.get_descriptive_name())
# Setting a default value for an attribute
class Car():
""" A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formateed descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
my_new_car = Car('audi' , 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
# Modifying an attribute's value directly
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# Modifying an attribute's value through a method
class Car():
""" A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formateed descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it ateempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
my_new_car = Car('audi' , 'a4', 2016)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(50)
my_new_car.read_odometer()
# Incrementing an Attribute's Value through a method
class Car():
""" A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formateed descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it ateempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
""" Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_used_car = Car('subaru' , 'outback', 2013)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
# 9-4
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and type attribute"""
self.name = restaurant_name
self.type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""describing the restaurant"""
print(self.name.title() + " is the " + self.type.title() + " restaurant.")
def open_restaurant(self):
"""prints a message indicating that the restaurant is open"""
print(self.name.title() + " is now open!")
def read_number_served(self):
"""Print number of customers that the restaurant has served"""
print("This restaurant has served " + str(self.number_served) + " customers.")
def set_number_served(self, number_served):
""" Set the number of customers that have been served."""
self.number_served = number_served
def increment_number_served(self, increment):
""" increment the number of customers who've been served."""
self.number_served += increment
first_restaurant = Restaurant('Than Brothers', 'vietnamese')
first_restaurant.read_number_served()
first_restaurant.set_number_served(20)
first_restaurant.read_number_served()
first_restaurant.increment_number_served(10)
first_restaurant.read_number_served()
# 9-5
class User():
def __init__(self, first, last, username, age, email):
self.first_name = first
self.last_name = last
self.username = username
self.age = age
self.email = email
self.login_attempts = 0
def describe_user(self):
print("Name: " + self.first_name.title() + " " + self.last_name.title())
print("Username: " + self.username)
print("Age: " + str(self.age))
print("Email Address: " + self.email)
print("Number of login attemps: " + str(self.login_attempts))
def greet_uesr(self):
print("Hello, " + self.username + "!")
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
bbakjoo = User('Ju-Un', 'Park', 'bbakjoo', 33, 'pju2000@gmail.com')
bbakjoo.describe_user()
bbakjoo.increment_login_attempts()
bbakjoo.describe_user()
bbakjoo.reset_login_attempts()
bbakjoo.describe_user()
# Inheritance
# The __init__() Method for a child class
class Car():
""" A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formateed descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it ateempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
""" Add the given amount to the odometer reading."""
self.odometer_reading += miles
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
# Defining Attributes and Methods for the child class
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
# Override Methods from the parent class
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery_size = 70
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def fill_gas_tank(self):
"""electric cars don't have gas tanks."""
print("This car doesn't need a gas tank!")
my_tesla.fill_gas_tank()
# Instances as Attributes
class Battery():
""" A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=70):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
# 9-6
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and type attribute"""
self.name = restaurant_name
self.type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""describing the restaurant"""
print(self.name.title() + " is the " + self.type.title() + " restaurant.")
def open_restaurant(self):
"""prints a message indicating that the restaurant is open"""
print(self.name.title() + " is now open!")
def read_number_served(self):
"""Print number of customers that the restaurant has served"""
print("This restaurant has served " + str(self.number_served) + " customers.")
def set_number_served(self, number_served):
""" Set the number of customers that have been served."""
self.number_served = number_served
def increment_number_served(self, increment):
""" increment the number of customers who've been served."""
self.number_served += increment
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type = 'ice cream'):
super().__init__(restaurant_name, cuisine_type)
self.flavors = []
def show_flavor(self):
print("Following flavors are available:")
for flavor in self.flavors:
print("- " + flavor.title())
big_one = IceCreamStand('The Big One')
big_one.flavors = ['vanilla', 'chocolate', 'black cherry']
big_one.describe_restaurant()
big_one.show_flavor()
# 9-7
class User():
def __init__(self, first, last, username, age, email):
self.first_name = first
self.last_name = last
self.username = username
self.age = age
self.email = email
def describe_user(self):
print("Name: " + self.first_name.title() + " " + self.last_name.title())
print("Username: " + self.username)
print("Age: " + str(self.age))
print("Email Address: " + self.email)
def greet_user(self):
print("Hello, " + self.username + "!")
class Admin(User):
def __init__(self, first, last, username, age, email):
super().__init__(first, last, username, age, email)
self.privileges = []
def show_privileges(self):
print("\nPrivileges:")
for privilege in self.privileges:
print("- " + privilege)
juun = Admin('Ju-Un', 'Park', 'bbakjoo', 32, 'bbakjoo@gmail.com')
juun.describe_user()
juun.privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
juun.show_privileges()
# 9-8
class User():
def __init__(self, first, last, username, age, email):
self.first_name = first
self.last_name = last
self.username = username
self.age = age
self.email = email
def describe_user(self):
print("Name: " + self.first_name.title() + " " + self.last_name.title())
print("Username: " + self.username)
print("Age: " + str(self.age))
print("Email Address: " + self.email)
def greet_user(self):
print("Hello, " + self.username + "!")
class Privileges():
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
print("Privileges:")
if self.privileges:
for privilege in self.privileges:
print("- " + privilege)
else:
print("- This user has no privileges.")
class Admin(User):
def __init__(self, first, last, username, age, email):
super().__init__(first, last, username, age, email)
self.privileges = Privileges()
juun = Admin('Ju-Un', 'Park', 'bbakjoo', 32, 'bbakjoo@gmail.com')
juun.describe_user()
juun.privileges.show_privileges()
juun_privileges = [
'can reset passwords',
'can moderate discussions',
'can suspend accounts',
]
juun.privileges.privileges = juun_privileges
juun.privileges.show_privileges()
# 9-9
class Car():
""" A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formateed descriptive name."""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it ateempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
""" Add the given amount to the odometer reading."""
self.odometer_reading += miles
class Battery():
""" A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=70):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately " + str(range)
message += " miles on a full charge."
print(message)
def upgrade_battery(self):
"""Check the battery size and set the capacity to 85."""
if self.battery_size < 85:
print("Upgrading battery size in progress.")
self.battery_size = 85
else:
print("Battery size is already at max.")
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 23:57:58 2018
@author: Ju-Un Park
"""
# User input and while loops
# how the input() function works
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
# Writing clear prompts
name = input("Please enter your name: ")
print("Hello, " + name + "!")
###
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
# Using int() to accept numerical input
age = input("How old are you? ")
age = int(age)
age >= 18
###
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
# Modulo operator
4 % 3 # 1
5 % 3 # 2
6 % 3 # 0
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + str(number) + " is even.")
else:
print("\nThe number " + str(number) + " is odd.")
# 7-1
car = input("What kind of car would you like to rent?")
print("Let me see if I can find you a " + car.title())
# 7-2
number = input("How many people are in your dinner group?")
number = int(number)
if number < 8:
print("Your table is ready.")
else:
print("You'll have to wait for a table.")
# While loop
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# Letting the user choose when to quit
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
# Using a flag
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
# Using break to exit a loop
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print("I'd love to go to " + city.title() + "!")
# Using continue in a loop
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
# Avoiding infinite loops
# This loop runs forever
x = 1
while x <= 5:
print(x)
# 7-4
prompt = "\nPlease enter the pizza toppings you want to add:"
prompt += "\n(Enter 'quit' when you are done.) "
while True:
topping = input(prompt)
if topping == 'quit':
break
else:
print("I will add " + topping + " to you pizza.")
# 7-5
prompt = "\nHow old are you?"
prompt += "\n(Enter 'quit' when you are done.) "
while True:
age = input(prompt)
if age == 'quit':
break
else:
try:
age = int(age)
if age > 0:
goodinput = True
if age < 3:
print("The ticket is free.")
elif 3 <= age <= 12:
print("The ticket is $10.")
elif age > 12:
print("The ticket is $15.")
else:
print("You have entered wrong number. Try again. ")
except ValueError:
print("Please enter the number.")
# 7-6
prompt = "\nPlease enter the pizza toppings you want to add:"
prompt += "\n(Enter 'quit' when you are done.) "
active = True
while active:
topping = input(prompt)
if topping != 'quit':
print("I will add " + topping + " to you pizza.")
else:
active = False
# 7-7
x = 1
while x < 3:
print(x)
# Using a while looop with lists and dictionaries
# Moving items from one list to another
# Start with users that need to be verified.
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# Display all confirmed users.
print("\nThe follwing users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
# Removing all instances of specific values from a list
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
# Filling a dictionary with user input
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the preson's name and response.
name = input("\nWhat is your name?")
response = input("Which moutain would you like to climb someday? ")
# Store the response in the dictionary:
responses[name] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
# 7-8
sandwich_orders = ['BBQ', 'Cajun', 'Philly Steak', 'Spicy Chicken', 'Pulled Pork']
finished_sandwiches = []
while sandwich_orders:
current_sandwich = (sandwich_orders.pop(0))
print("I made your " + current_sandwich + " sandwich.")
finished_sandwiches.append(current_sandwich)
print("\nFinished sandwiches: ")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich)
# 7-9
sandwich_orders = ['BBQ', 'pastrami', 'Cajun', 'Philly Steak', 'pastrami', 'Spicy Chicken', 'Pulled Pork', 'pastrami']
finished_sandwiches = []
print ("Sorry, our deli has run out of pastrami.\n")
while sandwich_orders:
current_sandwich = (sandwich_orders.pop(0))
if current_sandwich == 'pastrami':
del current_sandwich
else:
print("I made your " + current_sandwich + " sandwich.")
finished_sandwiches.append(current_sandwich)
print("\nFinished sandwiches: ")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich)
# 7-10
responses = {}
polling_active = True
while polling_active:
name = input("\nWhat is your name? ")
place = input ("\nIf you could visit one place in the world, where would you go? ")
responses[name] = place
repeat = input("Would you like to take another poll? ")
if repeat == 'no':
polling_active = False
for name, place in responses.items():
print(name.title() + "'s dream place in the world is " + place + ".")
|
#!/usr/bin/env python3
# Created by: Wenda Zhao
# Created on: Dec 2020
# This program is check leap year
def main():
# this function is check leap year
# input
year = int(input("Enter the year: "))
print("")
# process & output
if year % 4 == 0:
if year % 100 == 0 and year % 400 != 0:
print("It is not a leap year")
else:
print("It is a leap year")
else:
print("It is not a leap year")
if __name__ == "__main__":
main()
|
''''创建列表'''
member = ["小甲鱼","小布丁","黑夜","迷途","怡静"]
print(member)
number = [1,2,3,4,5,6]
print(number)
mix = [1,"huahua",3.14,["大笨蛋","臭宝宝","小傻逼"]] #列表中可以添加不同类型的元素,甚至是另一个列表
print(mix)
#创建一个空列表
blank = []
print(type(blank))
'''向列表添加元素'''
member.append("The_zero")
print(member)
print(" 长度是"+str(len(member)))
member.extend(["花花","小小仓鼠"]) #extend把一个列表中的元素加入另一个列表里
print(member)
member.insert(1,"小怪兽") #insert将一个元素放进指定的位置
print(member)
'''获取列表元素'''
print(member[1])
temp = member[0] #交换位置
member[0] = member[1]
member[1] = temp
print(member[0])
'''从列表删除元素'''
member.remove("怡静")#通过元素删除,不需要知道位置
del member[7]
print(member)
print(member.pop())
print(member)
'''列表分片'''
print(member[1:3]) #得到1-2的元素 3不包含进来
print(member[:3]) #得到0-2的元素
print(member[3:]) #得到3-结尾的元素
print(member[:]) #得到列表的拷贝
'''比较操作符'''
list1 = [1234]
list2 = [5675]
print(list1 > list2)
list1 = [123,456] #只要有一个赢了后面的都不需要比较,跟字符串类似
list2 = [456,123]
print(list1 > list2)
list3 = [123,456]
print((list1 < list2) and (list1 == list3) )
'''运算操作符'''
list4 = list1 + list2
x = list4[:]
'''重复操作符'''
print(x)
print(x * 3)
list4 *= 3
print(list4)
'''成员关系操作符'''
print(123 in list1)
print(123 not in member)
list5 = [123,["fafa","benben"],456]
print("fafa" in list5) #看能不能判断列表中的列表的元素 答案是False
print("fafa" in list5[1])
print(list4.count(123)) #count()查看元素出现次数
print(list4.index(123)) #index()查看元素出现的位置
print(list4.index(123),3,8) #查看123出现的位置,从3开始数,到8结束
print(member)
print(member.reverse()) #将列表元素翻转
list6 = [7,4,2,8,4,9,7,8,2,3]
print(list6.sort()) #列表元素排序
print(list6.sort(reverse=True)) |
#分片
str1 = "I love fishc.com "
print(str1[6:])
#获取单个字符
print(str1[3])
#修改字符串
str1 = str1[:4]+"插入的字符串"+str1[4:]
print(str1)
'''一些常用的方法'''
str2 = " fafa"
print(str2.capitalize()) #首字母大写
print(str2.center(40)) #填充空格至40长度 并使字符串居中
print(str2.count('a')) #计算a的次数
print(str2.endswith("fa")) #检查是否以fa结尾
print(str2.find('fa')) #查找fa在字符串中的位置 如果没有找到返回-1
print(str2.index('fa')) #查找fa在字符串中的位置 如果没有找到会弹出一个异常
print(str2.islower()) #判断字符串中是否所有的字符都是小写
print(str2.isspace()) #如果有空格就返回true
print(str2.isnumeric()) #如果字符串只包含数字就返回
print(str2.isupper()) #如果字符串中至少包含一个区分大小写的字符 且这些字符都为大写则返回True
print(str2.join("OOOOOOOOOOO")) #将括号内的字符串用str2隔开
print(str2.lower()) #将str2转化为小写
print(str2.upper()) #将str2转化为大写
print(str2.lstrip()) #去掉字符串开始的空格 rstrip()去掉末尾的空格
print(str2.replace("fa","GG",1))#将str2中的‘fa’替换为GG,执行一次
str3 = " I Love Weng "
print(str3.split()) #默认按空格切片
print(str3.split("o")) #也可以指定按什么切,还有一个参数是最多切多少下
print(str3.strip()) #删除前后的所有空格 也可以给定一个字符串 删除前后出现的这个字符串
'''字符串的格式化'''
print("{0} love {1}.{2}".format("I","fishC","com")) #位置参数
print("{a} love {b}.{c}".format(a="I",b="fishC",c="com")) #关键字参数
print("{{0}} love {{1}}.{{2}}".format("I","fishC","com")) #如果过想打印{}需要将他用自己本身括起来
print('{0:.1f}{1}'.format(27.658,"GB")) #冒号表示格式化符号的开始
print('%c %c %c' % (97,98,99))
print('%s' % "I love Weng")
print('%d + %d = %d' %(4,5,4+5))
print('%X %x' %(10,10))
print('%f'% 3.1415926535)
print('%e'% 3.1415926535)
print('%g'% 3.1415926535)
print('%5.2f'% 3.1415926535)
print('%5.2e'% 3.1415926535)
print('%+8.2f'% 3.1415926535) #用于在正数前显示正号
print('%-8.2f'% 3.1415926535) #用于左对齐
print('%#o' % 13) #井号用于显示进制符号
print('%#x' % 13) #用于显示进制符号
'''
%c 格式化字符及其 ASCII 码
%s 格式化字符串
%d 格式化整数
%o 格式化无符号八进制数
%x 格式化无符号十六进制数
%X 格式化无符号十六进制数(大写)
%f 格式化浮点数字,可指定小数点后的精度
%e 用科学计数法格式化浮点数
%E 作用同 %e,用科学计数法格式化浮点数
%g 根据值的大小决定使用 %f 或 %e
%G 作用同 %g,根据值的大小决定使用 %f 或者 %E
m.n m 是显示的最小总宽度,n 是小数点后的位数
- 用于左对齐
+ 在正数前面显示加号(+)
# 在八进制数前面显示 '0o',在十六进制数前面显示 '0x' 或 '0X'
0 显示的数字前面填充 '0' 取代空格
\' 单引号
\" 双引号
\a 发出系统响铃声
\b 退格符
\n 换行符
\t 横向制表符(TAB)
\v 纵向制表符
\r 回车符
\f 换页符
\o123 八进制数代表的字符
\x123 十六进制数代表的字符
\0 表示一个空字符
\\ 反斜杠
''' |
"""生成器 生成器是一种特殊的迭代器 生成器的出现使得协同程序的概念得以实现"""
"""协同程序就是可以运行的独立函数调用,函数可以展厅或者挂起,并在需要的时候从函数离开的地方继续或者重新开始"""
def myGen():
print("生成器被执行!")
yield 1
yield 2
myG = myGen()
print(next(myG))
next(myG)
myG = myGen()
for i in myG:
print(i)
"""用生成器写一个feb数列"""
def feb():
a = 0
b = 1
while True:
a,b = b,a+b
yield a
for i in feb():
if(i < 100):
print(i ,end=" ")
else:
break
print("")
"""列表推导式"""
a = [i for i in range(100) if not(i % 2) and i % 3] #100以内可以被2整除但是不能被3整除的数
print(a)
"""字典推导式"""
b = {i:i % 2 == 0 for i in range(10)} #10因为可以被2整除的数 可以为True 不可以为False
print(b)
"""集合推导式"""
c = {i for i in [1,1,2,3,4,4,5,5,6,6,7,7,7,7,8,9,9,10,10]}
print(c)
"""元组推导式? 不! 这是生成器推导式"""
e = (i for i in range(10))
print(e)
for each in e:
print(each, end=" ")
print("")
"""生成器推导式可以直接写在函数的参数上"""
print(sum(i for i in range(100) if i % 2 )) |
from datetime import datetime, timedelta
import sys
SCHOOL = "school"
NOT_SCHOOL = "not-school"
def calculate_day_type(date):
"""Return the type of a day for a student
Parameters:
date (datetime): A day to calculate the type of
There are 2 different day types returned:
school - When student has to be in school of on TW week
not-school - When student has to be online if on TW week
"""
pass
|
# count the email from all the senders
with open("mbox-short.txt",'r')as file: #open file
emailList = {} #def as dict{}
for line in file:
if line.startswith("From ") == True: #take line starting with From
line = line.split()
email = line[1] #take out the email component
emailList[email] = emailList.get(email,0)+1 #count the email companents
print(emailList) #display the the dictory of emails and their count of occurence. |
#!/usr/bin/env python3
# Created by: Mr. Coxall
# Created on: Nov 2019
# This program prints five integers per line
def main():
# this function is the the famous Fizz-Buzz problem
for counter in range(1000, 2000 + 1):
if counter % 5 != 4:
print(counter, " ", end="")
else:
print(counter)
if __name__ == "__main__":
main()
|
import numpy as np
import copy
def print_shortest_records(record, start, destination):
if start == destination:
return 'You already there.'
path = []
previous_point = record[start][destination]
while previous_point != start:
path.append(previous_point)
previous_point = record[start][previous_point]
path.append(previous_point)
for i in reversed(path):
print(i, " -> ", end='')
print(destination)
def return_index(i, j):
# using the index starts with 1
if i > j:
return int(i * (i - 1) / 2 + j - 1)
else:
return int(j * (j - 1) / 2 + i - 1)
def find_min_index(dist, visited_vertexs):
smallest = 99
for v in range(len(dist)):
if dist[v] < smallest and v not in visited_vertexs:
smallest = dist[v]
min_index = v
return min_index
class Graph:
def __init__(self, i, connectivity, adjmatrix):
# Bug of i == 3, need to be fixed
if connectivity == 'Sparse':
self.num_of_vertex = i
self.num_of_edges = int((i + 1) * i / 2)
self.graphArray = np.full((1, self.num_of_edges), float('INF'))[0].tolist()
edge_index = []
do_not_insert = []
for k in range(self.num_of_vertex):
temp = return_index(k + 1, k + 1)
do_not_insert.append(temp)
self.graphArray[temp] = 0
ramdon_length = np.random.randint((self.num_of_vertex - 1) * (self.num_of_vertex - 2) / 2 - 1,
self.num_of_edges - len(do_not_insert) - 1)
while len(edge_index) < ramdon_length:
rindex = np.random.randint(0, self.num_of_edges - 1)
if rindex not in edge_index and rindex not in do_not_insert:
edge_index.append(rindex)
for i in edge_index:
self.graphArray[i] = np.random.randint(1, 10)
elif connectivity == 'Fully':
self.num_of_vertex = i
self.num_of_edges = (i + 1) * i / 2
self.graphArray = (np.random.rand(1, int(self.num_of_edges)) * 10 + 1).astype(int)[0].tolist()
for k in range(self.num_of_vertex):
temp = return_index(k + 1, k + 1)
self.graphArray[temp] = 0
elif connectivity == 'Customize':
self.num_of_vertex = len(adjmatrix)
self.num_of_edges = int((self.num_of_vertex + 1)*self.num_of_vertex/2)
self.graphArray = []
for i in range(len(adjmatrix)):
for j in range(i+1):
if i == j:
self.graphArray.append(0)
else:
self.graphArray.append(adjmatrix[i][j])
def get_matrix(self):
matrix = np.array([])
for i in range(self.num_of_vertex):
temp = []
for j in range(self.num_of_vertex):
if i == j:
temp.append(0)
if j > i:
temp.append(self.graphArray[return_index(j + 1, i + 1)])
if i > j:
temp.append(self.graphArray[return_index(i + 1, j + 1)])
matrix = np.append(matrix, temp)
return matrix.reshape(self.num_of_vertex, -1)
def get_list(self):
graphDict = []
for i in range(self.num_of_vertex):
temp = {}
for j in range(self.num_of_vertex):
if j > i and self.graphArray[return_index(j + 1, i + 1)] != float('INF'):
temp[j] = self.graphArray[return_index(j + 1, i + 1)]
if i > j and self.graphArray[return_index(i + 1, j + 1)] != float('INF'):
temp[j] = self.graphArray[return_index(i + 1, j + 1)]
graphDict.append(temp)
return graphDict
def dijkstra_matrix(graph):
shortest_path = []
path_records = []
number_of_vertexs = graph.num_of_vertex
matrix = graph.get_matrix()
for i in range(number_of_vertexs):
visited_vertexs = []
singe_path_record = [-1] * number_of_vertexs
temp_path = np.full((1, number_of_vertexs), float('INF'))[0].tolist()
temp_path[i] = 0
while len(visited_vertexs) < number_of_vertexs:
v = find_min_index(temp_path, visited_vertexs)
visited_vertexs.append(v)
for dest_point in range(number_of_vertexs):
if temp_path[dest_point] > matrix[v][dest_point] + temp_path[v] and dest_point not in visited_vertexs:
temp_path[dest_point] = matrix[v][dest_point] + temp_path[v]
singe_path_record[dest_point] = v
shortest_path.append(temp_path)
path_records.append(singe_path_record)
return shortest_path, path_records
def dijkstra_linkedList(graph):
shortest_path = []
path_records = []
number_of_vertexs = graph.num_of_vertex
matrix = graph.get_list()
for i in range(len(matrix)):
matrix[i][i] = 0
for i in range(number_of_vertexs):
visited_vertexs = []
singe_path_record = [-1] * number_of_vertexs
temp_path = np.full((1, number_of_vertexs), float('INF'))[0].tolist()
temp_path[i] = 0
while len(visited_vertexs) < number_of_vertexs:
v = find_min_index(temp_path, visited_vertexs)
visited_vertexs.append(v)
for dest_point in range(number_of_vertexs):
if dest_point in matrix[v] and temp_path[dest_point] > matrix[v][dest_point] + temp_path[v] and dest_point not in visited_vertexs:
temp_path[dest_point] = matrix[v][dest_point] + temp_path[v]
singe_path_record[dest_point] = v
shortest_path.append(temp_path)
path_records.append(singe_path_record)
return shortest_path, path_records
def dijkstra_array(graph):
shortest_path = []
path_records = []
number_of_vertexs = graph.num_of_vertex
matrix = graph.graphArray
for i in range(number_of_vertexs):
visited_vertexs = []
singe_path_record = [-1] * number_of_vertexs
temp_path = np.full((1, number_of_vertexs), float('INF'))[0].tolist()
temp_path[i] = 0
while len(visited_vertexs) < number_of_vertexs:
v = find_min_index(temp_path, visited_vertexs)
visited_vertexs.append(v)
for dest_point in range(number_of_vertexs):
if temp_path[dest_point] > matrix[return_index(v + 1, dest_point + 1)] + temp_path[v] and dest_point not in visited_vertexs:
temp_path[dest_point] = matrix[return_index(v + 1, dest_point + 1)] + temp_path[v]
singe_path_record[dest_point] = v
shortest_path.append(temp_path)
path_records.append(singe_path_record)
return shortest_path, path_records
def floyd_matrix(in_graph):
graph = copy.deepcopy(in_graph)
number_of_vertex = graph.num_of_vertex
path_track = []
for i in range(number_of_vertex):
path_track.append(np.full((1, number_of_vertex), i)[0].tolist())
shortest_path = graph.get_matrix()
# starts here
matrix = shortest_path
for mid in range(number_of_vertex):
for star in range(number_of_vertex):
for destination in range(number_of_vertex):
if shortest_path[star][destination] > matrix[star][mid] + matrix[mid][destination]:
shortest_path[star][destination] = matrix[star][mid] + matrix[mid][destination]
path_track[star][destination] = mid
return shortest_path, path_track
def floyd_array(graph):
number_of_vertex = graph.num_of_vertex
path_track = []
for i in range(number_of_vertex):
path_track.append(np.full((1, number_of_vertex), i)[0].tolist())
shortest_path = copy.deepcopy(graph.get_matrix())
# starts here
matrix = copy.deepcopy(graph.graphArray)
for mid in range(number_of_vertex):
for star in range(number_of_vertex):
for destination in range(number_of_vertex):
if shortest_path[star][destination] > matrix[return_index(star + 1, mid + 1)] + matrix[return_index(mid + 1, destination + 1)]:
shortest_path[star][destination] = matrix[return_index(star + 1, mid + 1)] + matrix[
return_index(mid + 1, destination + 1)]
matrix[return_index(star + 1, destination + 1)] = matrix[return_index(star + 1, mid + 1)] + matrix[
return_index(mid + 1, destination + 1)]
path_track[star][destination] = mid
return shortest_path, path_track
def floyd_linkedList(graph):
number_of_vertex = graph.num_of_vertex
path_track = []
for i in range(number_of_vertex):
path_track.append(np.full((1, number_of_vertex), i)[0].tolist())
shortest_path = copy.deepcopy(graph.get_matrix())
# starts here
matrix = copy.deepcopy(graph.get_list())
for i in range(len(matrix)):
matrix[i][i] = 0
for mid in range(number_of_vertex):
for star in range(number_of_vertex):
for destination in range(number_of_vertex):
if mid in matrix[star] and destination in matrix[mid] and shortest_path[star][destination] > \
matrix[star][mid] + matrix[mid][destination]:
shortest_path[star][destination] = matrix[star][mid] + matrix[mid][destination]
matrix[star][destination] = matrix[star][mid] + matrix[mid][destination]
path_track[star][destination] = mid
return shortest_path, path_track
testCase1 = [[float('INF'), float('INF'), float('INF'), 29, float('INF'), float('INF'), float('INF'), float('INF')],[float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), 11, 11, float('INF')],[float('INF'), float('INF'), float('INF'), 12, float('INF'), 5, 5, float('INF'),],[29, float('INF'), 12, float('INF'), 5, float('INF'), 13, float('INF')],[float('INF'), float('INF'), float('INF'), 5, float('INF'), float('INF'), 7, 11],[float('INF'), 11, 5, float('INF'), float('INF'), float('INF'), float('INF'), 17],[float('INF'), 11, 5, 13, 7, float('INF'), float('INF'), float('INF')],[float('INF'), float('INF'), float('INF'), float('INF'), 11, 17, float('INF'), float('INF')]]
testCase2 = [[float('INF'), 11, 14, float('INF'), 8, float('INF'), 29, 28, float('INF'), float('INF'), 14, float('INF'),],
[11, float('INF'), 12, float('INF'), 6, float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'),],
[14, 12, float('INF'), 18, 13, 13, float('INF'), float('INF'), 25, float('INF'), float('INF'), 16,],
[float('INF'), float('INF'), 18, float('INF'), float('INF'), float('INF'), 27, 17, 9, 25, float('INF'), float('INF'),],
[8, 6, 13, float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), 22],
[float('INF'), float('INF'), 13, float('INF'), float('INF'), float('INF'), float('INF'), 15, 5, float('INF'), float('INF'), float('INF'),],
[29, float('INF'), float('INF'), 27, float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'),],
[28, float('INF'), float('INF'), 17, float('INF'), 15, float('INF'), float('INF'), 5, 9, float('INF'), float('INF'),],
[float('INF'), float('INF'), 25, 9, float('INF'), 5, float('INF'), 5, float('INF'), float('INF'), 25, float('INF'),],
[float('INF'), float('INF'), float('INF'), 25, float('INF'), float('INF'), float('INF'), 9, float('INF'), float('INF'), float('INF'), float('INF'),],
[14, float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), 25, float('INF'), float('INF'), float('INF'),],
[float('INF'), float('INF'), 16, float('INF'), 22, float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'), float('INF'),]]
testGraph1 = Graph(8, 'Customize', testCase1)
testGraph2 = Graph(12, 'Customize', testCase2)
print('Using the dijkstra with adject matrix:')
d1, p1 = dijkstra_matrix(testGraph1)
print('The shortest distance of test case 1 is', d1)
print('The distance between v1 -v8 is', d1[0][7])
print('The path is')
print_shortest_records(p1, 0, 7)
d2, p2 = dijkstra_matrix(testGraph2)
print('The shortest distance of test case 2 is', d2)
print('The distance between v12 -v10 is', d2[11][9])
print('The path is')
print_shortest_records(p2, 11, 9)
print('-----------------------------------------------------------------------')
print('Using the dijkstra with linkedlist:')
d1, p1 = dijkstra_linkedList(testGraph1)
print('The shortest distance of test case 1 is', d1)
print('The distance between v1 -v8 is', d1[0][7])
print('The path is')
print_shortest_records(p1, 0, 7)
d2, p2 = dijkstra_linkedList(testGraph2)
print('The shortest distance of test case 2 is', d2)
print('The distance between v12 -v10 is', d2[11][9])
print('The path is')
print_shortest_records(p2, 11, 9)
print('-----------------------------------------------------------------------')
print('Using the dijkstra with 1 d array:')
d1, p1 = dijkstra_array(testGraph1)
print('The shortest distance of test case 1 is', d1)
print('The distance between v1 -v8 is', d1[0][7])
print('The path is')
print_shortest_records(p1, 0, 7)
d2, p2 = dijkstra_array(testGraph2)
print('The shortest distance of test case 2 is', d2)
print('The distance between v12 -v10 is', d2[11][9])
print('The path is')
print_shortest_records(p2, 11, 9)
print('-----------------------------------------------------------------------')
print('Using the floyd with matrix:')
d1, p1 = floyd_matrix(testGraph1)
print('The shortest distance of test case 1 is', d1)
print('The distance between v1 -v8 is', d1[0][7])
print('The path is')
print_shortest_records(p1, 0, 7)
d2, p2 = floyd_matrix(testGraph2)
print('The shortest distance of test case 2 is', d2)
print('The distance between v12 -v10 is', d2[11][9])
print('The path is')
print_shortest_records(p2, 11, 9)
print('-----------------------------------------------------------------------')
print('Using the floyd with list:')
d1, p1 = floyd_linkedList(testGraph1)
print('The shortest distance of test case 1 is', d1)
print('The distance between v1 -v8 is', d1[0][7])
print('The path is')
print_shortest_records(p1, 0, 7)
d2, p2 = floyd_linkedList(testGraph2)
print('The shortest distance of test case 2 is', d2)
print('The distance between v12 -v10 is', d2[11][9])
print('The path is')
print_shortest_records(p2, 11, 9)
print('-----------------------------------------------------------------------')
print('Using the floyd with 1d array:')
d1, p1 = floyd_array(testGraph1)
print('The shortest distance of test case 1 is', d1)
print('The distance between v1 -v8 is', d1[0][7])
print('The path is')
print_shortest_records(p1, 0, 7)
d2, p2 = floyd_array(testGraph2)
print('The shortest distance of test case 2 is', d2)
print('The distance between v12 -v10 is', d2[11][9])
print('The path is')
print_shortest_records(p2, 11, 9) |
#!/usr/bin/python3
# Standard imports
import cv2
import numpy as np;
import sys
import pprint
pprint.pprint(sys.argv)
filename = sys.argv[1]
print("Filename = " + filename)
# Read image
im = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
# Set up the detector with default parameters.
detector = cv2.SimpleBlobDetector()
# Detect blobs.
keypoints = detector.detect(im)
# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the
# circle corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)
# Show keypoints
cv2.imshow("Keypoints", im_with_keypoints)
cv2.waitKey(0)
|
n=4
def staircase(n):
# Write your code here
i=0
while i<=n-1:
column=((n-i-1)*" ")+"#"
print(column,end="")
row=i*"#"
print(row)
i +=1
staircase(n)
### |
age = input("What's you age ? \n")
if(int(age) >= 18):
print("Okay! you are old enough")
else:
print("No! you cannot buy it")
|
#Find the word that are not present in the book
f=open("20.txt","r")
print(f.read())
srch_word=input("enter any word:")
if(srch_word not in f):
print("word not found.")
else:
print("word found.")
|
# -*- coding: utf-8 -*-
import sys
class Agent(object):
def __init__(self, toys=[], LearnC=1, LearnR=1, DiscoverC=1, DiscoverR=1, ExploreProb=1, toynames=[0, 1]):
"""
toys[]: List of toy objects.
Learn (bool): Does the agent care about the learner's experience with the taught toy?
ExploreProb (float): Probability that the agent will choose to explore the other toy.
Discover (bool): does the agent care about the costs and rewards associated with discovery?
teacherreward (string): "Constant" or "Variable". Determines if teacher gets a constant reward for teaching or not.
"""
if len(toys) != 2:
print "Error: Code only supports reasoning about two toys."
return None
self.toys = toys
self.rewards = [i.reward for i in self.toys]
self.costs = [i.cost for i in self.toys]
self.ExploreProb = ExploreProb
self.UseLearnC = LearnC
self.UseDiscoverC = DiscoverC
self.UseLearnR = LearnR
self.UseDiscoverR = DiscoverR
self.toynames = toynames
def TeachToy(self, toyid):
"""
Get utility for teaching toy with id toyid
"""
if toyid < 0 or toyid > len(self.toys):
print "Error: No such toy"
return None
# If agent cares about learner's costs and rewards with taugh toy.
[c_L, r_L] = self.toys[toyid].Play(self.toys[toyid].activation)
if not self.UseLearnR:
r_L = 0
if not self.UseLearnC:
c_L = 0
# If agent cares about what the learner will do with the untaught
# toy.
[c_D, r_D] = [
self.ExploreProb*i for i in self.toys[int(not toyid)].Discover()]
if not self.UseDiscoverR:
r_D = 0
if not self.UseDiscoverC:
c_D = 0
# return costs and rewards
return [c_L + c_D, r_L + r_D]
def Teach(self, utilities=False):
"""
Choose which toy to teach.
utilities (bool): Should we return utilities as well?
"""
# option 1
[c0, r0] = self.TeachToy(0)
# option 2
[c1, r1] = self.TeachToy(1)
# Costs are already negative so you have to add them!
if (r0+c0 > r1+c1):
choice = self.toynames[0]
elif (r0+c0 < r1+c1):
choice = self.toynames[1]
else:
choice = "Either"
if utilities:
return [r0+c0, r1+c1, choice]
else:
return choice
def PrintSummary(self, header=True):
if header:
sys.stdout.write()
|
# add value to unknown object dictionary or list
a = {} # dictionary
# a = [] # list
def add_element():
if isinstance(a, dict):
a.update({1: "one"})
print "dict updated"
if isinstance(a, type({})):
a.update({1: "one"})
print "dict updated"
if isinstance(a, list):
a.append(1)
a.append("one")
print "list updated"
add_element()
print a
|
"""""""""
We can predefine b in f(a,b) using f(a,b=3)
Operator "pass" do nothing
Function always returns None in case "return" is absent
It could be written as f(b=1, a=3, c =7)
Task: Write function of sum 3 numbers tranfering arguments not different orders
"""""
a = int(input("Input A"))
b = int(input("Input B"))
c = int(input("Input C"))
def sum (a,b,c):
result = a + b + c
return result
print sum (b=a,a=b,c=c) |
from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height= 400)
user_bet = screen.textinput(title="Who will win?", prompt="Choose a turtle:").lower()
colours = ["blue", "red", "purple", "orange"]
y_start = [45, 15, -15, -45]
all_turtles = []
for turtle_index in range(0,4):
turtle = Turtle(shape="turtle")
turtle.penup()
turtle.color(colours[turtle_index])
turtle.setposition(x=-200, y=y_start[turtle_index])
all_turtles.append(turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtles:
rand_dist = random.randint(0, 10)
turtle.forward(rand_dist)
if turtle.xcor() >= 230:
if turtle.pencolor() == user_bet:
print("You win!")
else:
print("You lose")
is_race_on = False
screen.exitonclick() |
import math
funlist = ['abs', 'acos', 'atan', 'asin', 'sin', 'tan', 'cos', 'log', 'ln']
def EquationSolver(eqstr, Xvalue, Yvalue=None):
"""(str, number [, number]) -> number
solves a raw equation string with given Xvalue. Returns number solution.
>>> EquationSolver('54log(x)', 1)
0
>>> EquationSolver('34x+5^(x)(90*8/x)', 3.3)
44311.92536
>>> EquationSolver('3xpi', 88.8)
836.9202829
>>> EquationSolver('4.4x(2/3)^(2/3)', 90203)
302886.1992
"""
#print(Yvalue)
eqLst = ConvertToList(eqstr, Xvalue, Yvalue)
solLst = EquationSolver_lo(eqLst)
return solLst[0]
def ConvertToList(eqstr, Xvalue, Yvalue=None):
"""(str, number [, number]) -> list of items
Converts an equation string into a list of its individual components,
replacing 'x' with given Xvalue.
Parenthesis are listed as string
Numbers are listed as flost or int
Operations are listed as string
>>> ConvertToList('54log(x)', 1)
[54.0, 'log', '(', 1, ')']
>>> ConvertToList('3454.56x+5^x(90*8/x)', 3.3)
[3454.56, 3.3, '+', 5.0, '^', 3.3, '(', 90.0, '*', 8.0, '/', 3.3, ')']
>>> ConvertToList('3xpi', 88.8)
[3, 88.8, 3.141592653589793]
>>> ConvertToList('4.4xe^log(pi)', 90203)
[4.4, 90203, 2.718281828459045, '^', 'log', '(', 3.14159265
3589793, ')']
Examples to test negativehandler:
>>> ConvertToList('-5sinx', 4.4)
[-5, 'sin', 4.4]
>>> ConvertToList('-(5^x)/(-(-5pix))',3)
[-1, '*', '(', 5, '^', 3, ')', '/', '(', -1, '*', '(', -5, 3.14159265
3589793, 3, ')', ')']
>>> ConvertToList('(-5-5x)-(9-x)', 9.0)
['(', -5, '-', 5, 9.0, ')', '-', '(', 9, '-', 9.0, ')']
"""
eqlst = []
letters = 'qwertuioplkjhgfdsazcvbnm'
numbers = '1234567890.'
operators = '!^*-+/'
parenthesis = '()'
variables = 'xy'
numstring = ''
letterstring = ''
i = 0
length = len(eqstr)
while i < length:
## print(i)
## print(eqlst)
if eqstr[i] in letters:
while i < length and eqstr[i] in letters:
letterstring += eqstr[i]
i += 1
eqlst.append(letterstring)
letterstring = ''
elif eqstr[i] in numbers:
while i < length and eqstr[i] in numbers:
numstring += eqstr[i]
i += 1
eqlst.append(float(numstring))
numstring = ''
elif eqstr[i] in operators:
eqlst.append(eqstr[i])
i += 1
elif eqstr[i] in variables:
if eqstr[i] is 'x':
eqlst.append(Xvalue)
elif eqstr[i] is 'y':
eqlst.append(Yvalue)
i += 1
elif eqstr[i] in parenthesis:
eqlst.append(eqstr[i])
i += 1
for i in range(0, len(eqlst)):
if eqlst[i] == 'pi':
eqlst[i] = math.pi
elif eqlst[i] == 'e':
eqlst[i] = math.e
eqlst = negativehandler(eqlst)
#print(eqlst)
return eqlst
def negativehandler(eqlst):
"""(list of str) -> list of str
This function handles negative signs
If the operator is a '-', it must be diferenciated as
an operator or a negative sign.
WARNING: A negative sign must either be at the front of the equation
or be preceded by an open parenthesis.
"""
returnlst = []
letters = 'qwertyuioplkjhgfdsazcvbnm'
parenthesis = '()'
i=0
length = len(eqlst)
while i < length:
item = eqlst[i]
if str(item) not in '-':
returnlst.append(item)
i += 1
elif str(item) in '-':
if i == 0 or eqlst[i-1] == '(':
obj = eqlst[i+1]
#if the negative sign is followed by a number
if type(obj) is int or type(obj) is float:
Negative_num = -1*obj
returnlst.append(Negative_num)
i += 2
#if the negative sign is followed by a parenthesis
elif obj in parenthesis:
returnlst.append(-1)
returnlst.append('*')
returnlst.append('(')
i += 2
#if the negative sign is followed by a special letter function.
elif obj in funlist:
returnlst.append(-1)
returnlst.append('*')
returnlst.append(obj)
i += 2
else:
#not a negative sign
returnlst.append(item)
i += 1
return returnlst
def EquationSolver_lo(eqLst):
"""(list of str) -> float
Solves an equation with individual parts split into a list of str.
all parenthesis must be string
all operations must be string.
all numbers must be int or float.
>>> list = ['(', '(', 3, ')', ')']
>>> EquationSolver(list)
[3]
>>> list = [ '(', 3, '+', math.pi, ')', '/', '(',
2, '^', '(', 4, '+', 1, ')', ')']
>>> EquationSolver(list)
[0.19192477042468103]
>>> list = ['ln', '(', math.e, '^', '(', 5, '+', 1, '^',
'(', 'sin', '(', math.pi, ')', ')', ')', ')']
>>> EquationSolver(list)
[6.0]
"""
parstring = ''
while parSearch(eqLst):
#print('while')
for i in range(0, len(eqLst)):
if str(eqLst[i]) not in '()':
i += 1
#print('if')
elif str(eqLst[i]) in '()':
#print('elif')
if parstring == '':
parstring = eqLst[i]
parindex = i
i += 1
elif parstring == eqLst[i]:
parindex = i
i += 1
elif parstring != eqLst[i]:
solution = EquationSolver_np(eqLst[parindex+1:i])
#print(parindex)
#print(solution)
eqLst = lstReplace(eqLst, parindex, i+1, solution)
#print(eqLst)
parstring = ''
break
if len(eqLst) == 1:
return eqLst
solution = EquationSolver_np(eqLst)
return solution
def EquationSolver_np(eqLst):
"""(list of str) -> float
Solves an equation with individual parts split into a list of str.
all operations must be string.
all numbers must be int or float.
Parenthesis must be resolved.
>>> list = [3]
>>> EquationSolver_np(list)
[3]
>>> list = [3,'/',2]
>>> EquationSolver_np(list)
[1.5]
>>> list = [4, '+', 5.5]
>>> EquationSolver_np(list)
[9.5]
>>> list = ['sin', math.pi, 5, 6,]
>>> EquationSolver_np(list)
[0]
>>> list = [5, '^', 6, 5, '/', 5, '+', 'tan', math.pi, math.pi, 6]
>>> EquationSolver_np(list)
[15625]
>>> list = [5, '+', 5, 5, 5, '-', 5, '/',
5, '/', 5, 5, '/', 5, '+', 5, '-', 5, '+', 5, 5, 5, '/', 5, '/', 5]
>>> EquationSolver_np(list)
[134.8]
"""
if len(eqLst) == 1:
return eqLst
#Resolve special math functions.
solutionlist1 = []
i = 0
length = len(eqLst)
while i < length:
if eqLst[i] in funlist:
fun = eqLst[i]
var = eqLst[i+1]
if fun == 'abs':
value = abs(var)
elif fun == 'acos':
value = math.acos(var)
elif fun == 'asin':
value = math.asin(var)
elif fun == 'atan':
value = math.atan(var)
elif fun == 'sin':
value = math.sin(var)
elif fun == 'cos':
value = math.cos(var)
elif fun == 'tan':
value = math.tan(var)
elif fun == 'log':
value = math.log10(var)
elif fun == 'ln':
value = math.log(var)
solutionlist1.append(value)
i += 2
else:
solutionlist1.append(eqLst[i])
i += 1
#print(solutionlist1)
if len(solutionlist1) == 1:
return solutionlist1
#Resolve exponents
solutionlist2 = []
length = len(solutionlist1)
i = 0
while i < length:
if i == length - 1:
solutionlist2.append(solutionlist1[i])
break
if eqLst[i] == '^':
value = math.pow(eqLst[i-1], eqLst[i+1])
solutionlist2.append(value)
i += 2
elif eqLst[i+1] == '^':
i += 1
else:
solutionlist2.append(solutionlist1[i])
i += 1
#print(solutionlist2)
if len(solutionlist2) == 1:
return solutionlist2
#Insert '*' where nultiplication is understood.
solutionlist3 = []
length = len(solutionlist2)
i = 0
while i < length:
if i < length-1 and str(solutionlist2[i]) not in '!^*-+/' and str(solutionlist2[i+1]) not in '!^*-+/':
j = i
while i < length and str(solutionlist2[i]) not in '!^*-+/':
i += 1
for index in range(j,i-1):
solutionlist3.append(solutionlist2[index])
solutionlist3.append('*')
solutionlist3.append(solutionlist2[i-1])
else:
solutionlist3.append(solutionlist2[i])
i += 1
#print(solutionlist3)
if len(solutionlist3) == 1:
return solutionlist3
#Resolve multiplication and division.
solutionlist4 = []
length = len(solutionlist3)
i = 0
while i < length:
if i < length-1 and str(solutionlist3[i]) in '*/':
j = i
fun = solutionlist3[i]
if fun in '/':
value = solutionlist3[i-1]/solutionlist3[i+1]
elif fun in '*':
value = solutionlist3[i-1]*solutionlist3[i+1]
while i < length and solutionlist3[i] in '*/':
i += 2
if j + 2 == i:
solutionlist4.append(value)
continue
for index in range(j + 2,i,2):
fun = solutionlist3[index]
if fun in '/':
value = value/solutionlist3[index+1]
elif fun in '*':
value = value*solutionlist3[index+1]
solutionlist4.append(value)
## elif solutionlist3[i] in '/':
## value = solutionlist3[i-1]/solutionlist3[i+1]
## solutionlist4.append(value)
## i += 2
## elif solutionlist3[i+1] in '*/':
## i += 1
elif i < length-1 and str(solutionlist3[i+1]) in '*/':
i += 1
else:
solutionlist4.append(solutionlist3[i])
i += 1
#Handle negatives
## if solutionlist4[0] == '-':
## solutionlist4 = negativehandler(solutionlist4)
#print(solutionlist4)
if len(solutionlist4) == 1:
return solutionlist4
#Resolve addition and subtraction.
solutionlist = []
fun = solutionlist4[1]
if fun in '+':
#print(solutionlist4[0], '+', solutionlist4[2])
value = solutionlist4[0] + solutionlist4[2]
elif fun in '-':
value = solutionlist4[0] - solutionlist4[2]
if len(solutionlist4) == 3:
solutionlist.append(value)
return solutionlist
else:
for index in range(3,len(solutionlist4), 2):
fun = solutionlist4[index]
if fun in '+':
value = value + solutionlist4[index+1]
elif fun in '-':
value = value - solutionlist4[index+1]
solutionlist.append(value)
return solutionlist
def lstReplace(lst, iStart, iEnd, replacemt):
"""(list of items, int, item) -> list of items
Returns a corrected version of lst with
lst[iStart:iEnd] replaced with replacemt.
>>> list = [0,1,2,3,4,5]
>>> lstReplace(list,3,5, 'x')
[0,1,2,'x',5]
"""
returnList = lst[:iStart]
returnList += replacemt
if iEnd == len(lst):
return returnList
returnList += lst[iEnd:]
return returnList
def parSearch(lst):
"""(list of items) -> bool
Indicates whether there is a parenthesis in lst.
"""
for item in lst:
if str(item) in '()':
return True
return False
|
print('-----------------kaiyue---------------------')
temp = input("不妨猜一下kaiyue心里想的那个数字:")
guess = int(temp)
while guess !=8:
temp = input("不妨猜一下kaiyue心里想的那个数字:")
guess = int(temp)
if guess == 8:
print("卧槽,你是kaiyue心中的蛔虫吗?!")
print("哼,猜中了也没有奖励!")
else:
if guess >8:
print("哥,大了大了")
else:
print("哈哈哈,小了笑了")
print("游戏结束,不玩啦!")
|
#Efetua a leitura da variável inteira
A = int(input())
#Efetua a leitura da variável inteira
B = int(input())
#Efetua o produto dos valores A e B
PROD = (A*B)
#Exibe o Valor do produto
print("PROD = %i" %PROD) |
#tic tac toe game
import random
#the game board
board = [0, 1, 2,
3, 4, 5,
6, 7, 8]
def show():
print(boarrd[0],"|",board[1],"|",board[2])
print("_______________________")
print(boarrd[3],"|",board[4],"|",board[5])
print("_______________________")
print(boarrd[6],"|",board[7],"|",board[8])
while true:
input = raw_input("select the spot: ")
input = int(input)
if board[input] != "x" and board[input] != "o":
board[input] = "x"
while finding:
random.seed() # gives a random generator
opponent = random.randint(0,8)
if board[opponent] != "o" and board[opponent] != "x":
board[opponent] = "o"
finding = false
else:
print("this spot is taken!")
show()
|
#Joshua Atherton TCSS 142
napierNumber = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z']
numberList = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192,
16384, 32768, 65536, 131072, 262144,524288, 1048576, 2097152,
4194304, 8388608, 16777216, 33554432 ]
def convertNumberNapier(number): #converts number to napier
napierList = []
index = 0
negativeNumber = False
if number < 0:
number = number * -1
negativeNumber = True
number = number
while number != 0:
newNumber = number // 2
numberRemainder = number % 2
letter = numberRemainder * numberList[index]
if letter != 0:
napierList.append(napierNumber[index])
index += 1
number = newNumber
joined = ''.join(napierList)
if len(joined) == 0:
return ("''")
elif negativeNumber == True:
return '-' + joined
else:
return joined
#takes in a number. Handles negative input, result of 0, & converts to napier
def convertNapierNumber(string): #converts Napier to number
number = 0
for character in string:
index = napierNumber.index(character)
number += numberList[index]
return number
#using parallel lists like in ceasar program to convert napier to a number
def enteringNumbers(number, sequence): #gets user napier number input
number = input("Enter Napier's number: ").lower()
while not number.isalpha():
print('Something is Wrong. Try again.')
number = input("Enter Napier's number: ").lower()
print('The {} number is: {:,}'.format(sequence, convertNapierNumber(number)))
return convertNapierNumber(number)
#returns the converted napier number to variable that called the function
def arithmeticOperator(num1, num2): #gets operator and adds numbers together
operator = input('Enter the desired arithmetic operation: ')
while not operator == '+' and not operator == '-' \
and not operator == '*' and not operator == '/':
print('Something is wrong. Try again.')
operator = input('Enter the desired arithmetic operation: ')
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 // num2 # int / to eliminates long floating point answers
print('The result is {:,} or {}'.format(result, convertNumberNapier(result)))
def main():
#calling the functions to run the program
runProgram = 'Y'
while runProgram == 'Y':
number1 = enteringNumbers('first', 'first')
number2 = enteringNumbers('second', 'second')
arithmeticOperator(number1, number2)
runProgram = input('Do you want to do another conversion? Y/N ').upper()
main()
|
import adventofcode
def is_valid_password_1(password):
"""
>>> is_valid_password_1("111111")
True
>>> is_valid_password_1("223450")
False
>>> is_valid_password_1("123789")
False
"""
has_double = any(password[c] == password[c+1] for c in range(len(password)-1))
is_ascending = all(password[c] <= password[c+1] for c in range(len(password)-1))
return has_double and is_ascending
def is_valid_password_2(password):
"""
>>> is_valid_password_2("112233")
True
>>> is_valid_password_2("123444")
False
>>> is_valid_password_2("111122")
True
"""
has_only_double = any(password[c-1] != password[c] and password[c] == password[c+1] and password[c+1] != password[c+2] for c in range(1, len(password)-2)) or (password[0] == password[1] and password[1] != password[2]) or (password[-2] == password[-1] and password[-3] != password[-2])
is_ascending = all(password[c] <= password[c+1] for c in range(len(password)-1))
return has_only_double and is_ascending
def part1(puzzle_input):
return sum(is_valid_password_1(str(password)) for password in range(int(puzzle_input[0]), int(puzzle_input[1])+1))
def part2(puzzle_input):
return sum(is_valid_password_2(str(password)) for password in range(int(puzzle_input[0]), int(puzzle_input[1])+1))
def main():
puzzle_input = adventofcode.read_input(4)
pass_range = puzzle_input.split('-')
adventofcode.answer(1, 460, part1(pass_range))
adventofcode.answer(2, 290, part2(pass_range))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
|
import math
def is_permutation(n, m) -> bool:
str1 = [x for x in str(n)]
str2 = [x for x in str(m)]
if len(str1) != len(str2):
return False
a = sorted(str1)
str1 = " ".join(a)
b = sorted(str2)
str2 = " ".join(b)
for i in range(0, len(str1)):
if str1[i] != str2[i]:
return False
return True
def SieveOfEratosthenes(n) -> list:
prime = [True for i in range(n)]
p = 2
while p * p <= n:
if prime[p]:
for i in range(p * 2, n, p):
prime[i] = False
p += 1
prime[0] = False
prime[1] = False
return prime
def get_totient_minimum_permutation() -> list:
min_ratio = 999
index_min = None
phi_min = None
limit = 10 ** 7
sqrt_limit = 2 * math.floor(math.sqrt(limit))
primes = SieveOfEratosthenes(sqrt_limit)
for i in range(len(primes)):
for j in range(i + 1, len(primes)):
if primes[i] and primes[j]:
n = i * j
if n > limit:
break
phi = (i - 1) * (j - 1)
ratio = float(n) / phi
if ratio < min_ratio and is_permutation(n, phi):
min_ratio = ratio
index_min = n
phi_min = int(phi)
print(index_min, phi_min, min_ratio)
return [index_min, phi_min, min_ratio]
if __name__ == '__main__':
print(get_totient_minimum_permutation())
|
import random
a = random.randrange(0,101)
if a >= 90:
print("A+")
elif a >= 80 and a <=90:
print("A")
elif a >= 70 and a <=80:
print("B")
elif a >= 60 and a <=70:
print("C")
else:
print("F")
print(a) |
a = 11
b = 4
c = 0
c = a + b
print("Line 1 - Value of c is ", c)
c = a - b
print("Line 2 - Value of c is ", c)
c = a * b
print("Line 3 - Value of c is ", c)
c = a / b
print("Line 4 - Value of c is ", c)
c = a % b
print("Line 5 - Value of c is ", c)
a = 3
b = 4
c = a**b
print("Line 6 - Value of c is ", c)
a = 7
b = 8
c = a//b
print("Line 7 - Value of c is ", c)
|
# Define a faster fibonacci procedure that will enable us to computer
# fibonacci(36).
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
old_fib, result_fib = 1, 1
while n > 2:
old_fib, result_fib = result_fib, result_fib + old_fib
n -= 1
return result_fib
# print fibonacci(36)
# >>> 14930352
for x in range(0, 37):
print(str(x) + ': ' + str(fibonacci(x)))
|
# Dictionaries of Dictionaries (of Dictionaries)
# The next several questions concern the data structure below for keeping
# track of Udacity's courses (where all of the values are strings):
# { <hexamester>, { <class>: { <property>: <value>, ... },
# ... },
# ... }
# For example,
courses = {
'feb2012': {'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Peter C.'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian',
'assistant': 'Andy'}},
'apr2012': {'cs101': {'name': 'Building a Search Engine',
'teacher': 'Dave',
'assistant': 'Sarah'},
'cs212': {'name': 'The Design of Computer Programs',
'teacher': 'Peter N.',
'assistant': 'Andy',
'prereq': 'cs101'},
'cs253':
{'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve',
'prereq': 'cs101'},
'cs262':
{'name': 'Programming Languages - Building a Web Browser',
'teacher': 'Wes',
'assistant': 'Peter C.',
'prereq': 'cs101'},
'cs373': {'name': 'Programming a Robotic Car',
'teacher': 'Sebastian'},
'cs387': {'name': 'Applied Cryptography',
'teacher': 'Dave'}},
'jan2044': {'cs001': {'name': 'Building a Quantum Holodeck',
'teacher': 'Dorina'},
'cs003': {'name': 'Programming a Robotic Robotics Teacher',
'teacher': 'Jasper'},
}
}
try_again = {'june2043': {'cs111': {'name': 'Historical Computers - Before Voice Activation', 'teacher': 'Scotty'},
'cs312': {'assistant': 'Amy', 'name': 'Build your own Time Machine', 'teacher': 'Melody'}},
'apr2012': {'cs262': {'assistant': 'Peter C.', 'prereq': 'cs101',
'name': 'Programming Languages - Building a Web Browser', 'teacher': 'Wes'},
'cs101': {'assistant': 'Sarah', 'name': 'Building a Search Engine', 'teacher': 'Dave'},
'cs253': {'prereq': 'cs101', 'name': 'Web Application Engineering - Building a Blog',
'teacher': 'Steve'},
'cs373': {'name': 'Programming a Robotic Car', 'teacher': 'Sebastian'},
'cs212': {'assistant': 'Andy', 'prereq': 'cs101', 'name': 'The Design of Computer Programs',
'teacher': 'Peter N.'},
'cs387': {'name': 'Applied Cryptography', 'teacher': 'Dave'}}, 'jan2044': {
'cs003': {'assistant': 'Amy', 'name': 'Programming a Robotic Robotics Teacher', 'teacher': 'Jasper'},
'cs001': {'name': 'Building a Quantum Holodeck', 'teacher': 'Dorina'},
'cs312': {'assistant': 'Amy', 'name': 'Build your own Time Machine', 'teacher': 'Melody'}},
'feb2012': {'cs101': {'assistant': 'Peter C.', 'name': 'Building a Search Engine', 'teacher': 'Dave'},
'cs373': {'assistant': 'Andy', 'name': 'Programming a Robotic Car', 'teacher': 'Sebastian'}}}
# For the following questions, you will find the
# for <key> in <dictionary>:
# <block>
# construct useful. This loops through the key values in the Dictionary. For
# example, this procedure returns a list of all the courses offered in the given
# hexamester:
def courses_offered(courses, hexamester):
res = []
for c in courses[hexamester]:
res.append(c)
return res
# [Double Gold Star] Define a procedure, involved(courses, person), that takes
# as input a courses structure and a person and returns a Dictionary that
# describes all the courses the person is involved in. A person is involved
# in a course if they are a value for any property for the course. The output
# Dictionary should have hexamesters as its keys, and each value should be a
# list of courses that are offered that hexamester (the courses in the list
# can be in any order).
def involved(courses, person):
descriptions = dict()
for hexamester in courses.keys():
class_list = list()
for classes in courses[hexamester].keys():
if person in courses[hexamester][classes].values():
class_list.append(classes)
if class_list:
descriptions[hexamester] = class_list
return descriptions
# For example:
# print involved(courses, 'Dave')
# >>> {'apr2012': ['cs101', 'cs387'], 'feb2012': ['cs101']}
# print involved(courses, 'Peter C.')
# >>> {'apr2012': ['cs262'], 'feb2012': ['cs101']}
# print involved(courses, 'Dorina')
# >>> {'jan2044': ['cs001']}
# print involved(courses,'Peter')
# >>> {}
# print involved(courses,'Robotic')
# >>> {}
# print involved(courses, '')
# >>> {}
print(involved(courses, 'Dave'))
print(involved(courses, 'Peter C.'))
print(involved(courses, 'Dorina'))
print(involved(courses, 'Peter'))
print(involved(courses, 'Robotic'))
print(involved(courses, ''))
print(involved(try_again, 'Amy'))
# {'june2043': ['cs312'], 'jan2044': ['cs312', 'cs003']}
print(involved(try_again, 'Andy'))
# Incorrect. There was a TypeError running your procedure for the input 'Andy' in the dictionary...
|
# Numbers in lists by SeanMc from forums
# define a procedure that takes in a string of numbers from 1-9 and
# outputs a list with the following parameters:
# Every number in the string should be inserted into the list.
# If a number x in the string is less than or equal
# to the preceding number y, the number x should be inserted
# into a sublist. Continue adding the following numbers to the
# sublist until reaching a number z that
# is greater than the number y.
# Then add this number z to the normal list and continue.
def numbers_in_lists(number_string):
number_list = list(map(int, number_string))
big_number = 0
result_list = []
sub_list = []
for number in number_list:
if not result_list:
big_number = number
result_list.append(number)
else:
if number <= big_number:
sub_list.append(number)
else:
big_number = number
if sub_list:
result_list.append(sub_list)
sub_list = []
result_list.append(number)
if sub_list:
result_list.append(sub_list)
return result_list
# testcases
string = '543987'
result = [5, [4, 3], 9, [8, 7]]
print(repr(string), numbers_in_lists(string) == result)
string = '987654321'
result = [9, [8, 7, 6, 5, 4, 3, 2, 1]]
print(repr(string), numbers_in_lists(string) == result)
string = '455532123266'
result = [4, 5, [5, 5, 3, 2, 1, 2, 3, 2], 6, [6]]
print(repr(string), numbers_in_lists(string) == result)
string = '123456789'
result = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(repr(string), numbers_in_lists(string) == result)
|
# Write a program that returns the number of edges
# in a star network that has `n` nodes
def star_network(n):
# return number of edges
if n < 2:
return 0
return n - 1
for x in range(5):
print(x, star_network(x))
|
#!/usr/bin/env python3
# encoding: utf-8
import numpy as np
'''
Numpy copy & deep copy
Ref: https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-8-np-copy/
'''
# = 的赋值方式会带有关联性
a = np.arange(4)
b = a
c = a
d = b
a[0] = 11
print(a)
print(d[0])
print(b is a) # True
print(c is a) # True
print(d is a) # True
# 同时更改d的值,a、b、c也会改变
d[1:3] = [22, 33]
print(a) # [11 22 33 3]
print(b) # [11 22 33 3]
print(c) # [11 22 33 3]
# copy()的赋值没有关联性
b = a.copy() # deep copy
print(b) # [11 22 33 3]
a[3] = 44
print(a) # [11 22 33 44]
print(b) # [11 22 33 3]
|
# 7. Write a Python program to accept
# filename from the user and print
# the extension of that.
# Sample filename : abc.java
# Output : java
x: str = input('input file name'
'aka abc.java: ')
arr_str = x.split('.')
print(f'extension is: {arr_str[-1]}')
|
# Question 2
# Level 1
#
# Question:
# Write a program which can compute the factorial of a given numbers.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
#
# Hints:
# In case of input data being supplied to the question, it should be
# assumed to be a console input.
def fact(x):
if x == 0:
return 1
return x * fact(x - 1)
z = int(input('введите целое число : '))
print(fact(z))
|
# class : 내가 자료형을 만들어 쓰는 것(문자열 하나로도, 리스트 하나로도 표현할 수 없을 때)
class User:
pass
# 아예 비워놓으면 오류떠서 다른 내용 쓰지 않겠다는 명령어
user1 = User()
user2 = User()
print(type(user1))
# 출력결과 : <class '__main__.User'>
# __main__ : 실행 파일 이름
# .User : 클래스 이름
# 인스턴스
class User:
pass
user1 = User()
user2 = User()
print(user1 == user2)
# false 나온다 -> (list aliasing 개념 생각해보면)두 개는 다른 인스턴스(=값)이다
"""
list aliasing 개념
x = [2, 3, 5, 7]
y == x
y[2] = 4
print(x == y)
# true 이다
x = [2, 3, 5, 7]
y = [2, 3, 5, 7]
y[2] = 4
print(x == y)
# false 이다
"""
class User:
pass
user1 = User()
user2 = user1
print(user1 == user2)
# true 이다
# 인스턴스 변수 : 처음부터 초기값 설정 이렇게 해야
class User:
pass
user1 = User()
user2 = User()
user1.name = "Kang" # 인스턴스 변수
user1.email = "wjddls0626@naver.com"
user1.password = "123456"
print(user1.name, user1.email, user1.password)
# 메소드 : 클래스 내에 정의된 함수(변수 뿐만 아니라)
class User:
def say_my_name(self): # self 쓰는 게 커뮤니티 약속
print("My name is " + self.name)
user1 = User()
user2 = User()
user1.name = "Kang"
user1.email = "wjddls0626@naver.com"
user1.password = "123456"
user2.name = "JeongIn"
user2.email = "wjddls5212@gmail.com"
user2.password = "654321"
User.say_my_name(user1)
# 바로 윗줄을 파이썬에서는 이렇게도 가능
user1.say_my_name()
# 파라미터가 여러개인 경우
class User:
def introduce(self, n):
for i in range(n):
print("%s is %d years old." % (self.name, self.age))
# 이 두 줄은 같음
User.introduce(user1, 3)
user1.introduce(3)
# 이 두 줄은 같음
User.introduce(user2, 2)
user2.introduce(2)
# ex1요약하면) 모든 인스턴스 변수 초기값 설정할 때(항상 해야) __init__ 메소드 사용하자!!
# 이렇게
class User:
def initialize(self, name, email, password):
self.name = name
self.email = email
self.password = password
user1 = User("Young", "young@codeit.kr", "123456")
user2 = User("Yoonsoo", "yoonsoo@codeit.kr", "abcdef")
user3 = User("Taeho", "taeho@codeit.kr", "123abc")
user4 = User("Lisa", "lisa@codeit.kr", "abc123") |
Y = 2014
A = 7
B = 9
W = 'Wednesday'
def solution(Y, A, B, W):
# write your code in Python 3.6
month = [0,31,28,31,30,31,30,31,31,30,31,30,31]
days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
]
first_monday = 0
if W == 'Monday':
first_monday = 1
first_mondays = [1]
else:
first_mondays = [8-days.index(W)]
first_monday = 8 - days.index(W)
for x in range(1,B):
last_monday = first_monday + 28
print(last_monday)
if last_monday < month[x]:
first_monday = (last_monday + 7) - month[x]
else:
first_monday = last_monday - month[x]
first_mondays.append(first_monday)
sunday = (first_mondays[B-1] + 6) + 21
if sunday >= month[B]:
last_sunday = sunday - 7
else:
last_sunday = sunday
sum_days = first_mondays[A-1] + last_sunday
for x in range(A+1,B):
sum_days = sum_days + month[x]
return sum_days / 7
print(solution(Y,A,B,W)) |
def capitalize_all(t):
res = []
for item in t:
res.append(item.capitalize())
return res
def only_upper(t):
res = []
for item in t:
if item.isupper():
res.append(item)
return res
def nested_sum(t):
res = 0
for item in t:
if isinstance(item, list):
res += nested_sum(item)
else:
res += item
return res
def cumsum(t):
sum_list = []
for i in range(len(t)):
sum_item = 0
for j in range(i):
sum_item += t[j]
sum_list.append(sum_item)
return sum_list
a = ['H', 'e', 'l', 'L', 'o']
h = [1, 2, [3, 4], 5]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# print(capitalize_all(a))
# print(only_upper(a))
# print(nested_sum(h))
print(cumsum(b))
|
# Dada una lista de nombres, ingresada por usuario
# que regresa la cantidad de nombres en la lista
# e imprima la lista alfabeticamente
ordenador = []
nombres = int(input("Numero de nombres:"))
for i in range (nombres):
n = (input("Ingresa un nombre:"))
ordenador.append(n)
print("Arreglo antes de ordenarlo:")
print(ordenador)
print("Arreglo ordenado:")
ordenador.sort()
print(ordenador)
# Vas a recibir un número n del teclado, vas a imprirmir los números de 1 a n,
# pero cuando el número sea divisible entre 3 vas a imprimir "Fizz"
# cuando el número sea divisible entre 5 vas a imprimir "Buzz"
# cuando el número sea divisible entre 3 y entre 5 vas a imprimir "FizzBuzz"
# y cuando no, vas a imprimir el número n
n = int(input("Ingrese cantidad de números"))
for i in range (1, n+1):
if i % 3 == 0 and i % 5 != 0:
print("Fizz")
elif i % 3 != 0 and i % 5 == 0:
print("Buzz")
elif i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
else:
print(i)
# Calcula los primeros n términos de la sucesión de Fibonacci
n = int(input("Ingrese cantidad de números para la serie de Fibonacci"))
i = 0
fibo = []
while i < n:
if i == 0 or i==1:
fibo.append(1)
else:
fibo.append(fibo[i-1] + fibo[i-2])
i+=1
print(fibo)
# Lea un número del teclado y calcule su factorial
n = int(input())
factorial = 1
for i in range(1, n+1):
factorial *= i
print(factorial)
# Ordena un arreglo de menor a mayor con 15 elementos
num = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]
for i in range(len(num)):
minimo = i
for j in range(i+1, len(num)):
if num[minimo] > num[j]:
minimo = j
num[i], num[minimo] = num[minimo], num[i]
print(num)
|
# Crea una función que reciba un número y regrese un booleano indicando si es divisible entre 243
def isDivisible(num):
return num % 243 == 0
print(isDivisible(490))
print(isDivisible(486))
# Crea una función llamada multiplicarString que reciba un string y un número entero positivo.
# La función debe regresar el mismo string repetido n veces. Por ejemplo:
# “Hola” y 3 → “HolaHolaHola”
# “Adios” y 5 → “AdiosAdiosAdiosAdiosAdios”
def multiplicarString(texto, num):
return texto * num
print(multiplicarString("hola", 3))
print(multiplicarString("adios", 5))
# Crea una función que reciba 3 números como parámetros (no en arreglo)
# y regrese la suma si al menos uno de esos números es mayor que 100,
# si no regresa la multiplicación de los 3.
def checarValores(x, y, z):
if x > 100 or y > 100 or z > 100:
return x + y + z
return x * y * z
print(checarValores(1, 2, 3))
print(checarValores(100, 2, 3))
# Crea una función llamada stringsExclusivos que reciba 2 strings
# y regresa true si uno tiene puras vocales y el otro puras consonantes,
# regresa false en cualquier otro caso.
# Ejemplo:
# “aeeaei” , “qwt” → True
# “aaeac” , “ttsdf” → False
def onlyVocals(str):
vocals = "aeiou"
for c in str:
if not(c in vocals):
return False
return True
def onlyCons(str):
vocals = "aeiou"
for c in str:
if c in vocals:
return False
return True
def stringsExclusivos(text1, text2):
case1 = onlyVocals(text1) and onlyCons(text2)
case2 = onlyCons(text1) and onlyVocals(text2)
return case1 or case2
print(stringsExclusivos("aeeaei", "qwt"))
print(stringsExclusivos("aaeac", "ttsdf"))
# Crea una función que se llame esPalindromo que reciba un string cualquiera
# y regrese true si es palíndromo, y false en el caso contrario.
# Ejemplo:
# “hola” → False
# “kayak” → True
def esPalindromo(texto):
reverso = texto[::-1]
if texto.lower() == reverso.lower():
return True
return False
print(esPalindromo("Ana"))
print(esPalindromo("Raquel"))
# Challenge: Crea una función llamada aBinario que reciba un número entero positivo
# y regrese un arreglo de ceros y unos que sea la representación en el sistema numérico binario del número recibido.
# Si no estás familiarizado con el sistema binario, dale primero una leida a este artículo:
# https://www.elvisualista.com/2016/10/20/que-son-los-numeros-binarios/
# Ejemplos:
# 5 → [ 1, 0, 1 ]
# 2 → [ 1, 0 ]
# 1 → [ 1 ]
# 45 → [ 1, 0, 1, 1, 0, 1 ]
def aBinario(num):
return f'{num:08b}'
print(aBinario(5))
print(aBinario(2))
print(aBinario(1))
print(aBinario(45))
def binario(num):
lista = []
while num != 0:
bit = num % 2
lista.append(bit)
num = int(num/2)
lista.reverse()
return lista
print(binario(5))
print(binario(2))
print(binario(1))
print(binario(45)) |
# IMPORT -----------------------------------------------------------------------
import random
import sys
import time
# ------------------------------------------------------------------------------
# BINARY -----------------------------------------------------------------------
def binary(valuelist, searchval):
""" Search valuelist for searchval, narrowing
the region of interest by half with every probe.
Does require the list to be sorted.
Time complexity: best O(log(n)), worst O(log(n)), average O(log(n)).
Space complexity: O(1).
"""
# Create the bounds; lower is inclusive, upper is exclusive.
lower, upper = 0, len(valuelist)
# Loop until we return a value.
while True:
# If the ROI is empty, we couldn't find the value.
if lower == upper:
return -1
# Check the middle value.
middle = (lower+upper)//2
midval = valuelist[middle]
if midval == searchval:
return middle # We found it.
elif midval > searchval:
upper = middle # Probed too high, search the lower half.
else:
lower = middle+1 # Probed too low, search the upper half.
# ------------------------------------------------------------------------------
# LINEAR -----------------------------------------------------------------------
def linear(valuelist, searchval):
""" Search valuelist for searchval,
checking every index in order.
Does not require the list to be sorted.
Time complexity: best O(1), worst O(n), average O(n/2).
Space complexity: O(1).
"""
# Iterate through the list, probing repeatedly until we find it.
for i, val in enumerate(valuelist):
if val == searchval:
return i
return -1
# ------------------------------------------------------------------------------
# UNIT TEST --------------------------------------------------------------------
def main(argv):
my_list = [x*x for x in range(0, 10000)]
test_ind = random.randint(0, len(my_list)-1)
test_val = my_list[test_ind]
functions = [binary, linear]
for fn in functions:
start = time.clock()
index = fn(my_list, test_val)
end = time.clock()
if index == test_ind:
print("{0}: {1:.8f} seconds".format(fn, end-start))
if __name__ == "__main__":
main(sys.argv)
# ------------------------------------------------------------------------------
|
import pygame as pg
import sys
import random
#вывод текста
pg.font.init()
def draw_text(surf, text, size, x, y):
font = pg.font.SysFont('arial', size)
text = font.render(text, True, [200,200,200])
surf.blit(text, [x,y])
#проверка на смерть
def IsDead(head, body, poisonFruit):
for i in body:
if((head[0] == i[0] and head[1] == i[1]) or (head[0] >= 600 or head[0] <= 0 or head[1] >= 600 or head[1] <= 0)):
return True
if(head[0] == poisonFruit[0] and head[1] == poisonFruit[1]):
return True
return False
#перемещение змеи
def move(body, head):
new_x = body[-2][0]
new_y = body[-2][1]
new_part = [new_x, new_y]
i = len(body)-1
while i >= 1:
body[i][0] = new_x
body[i][1] = new_y
new_x = body[i-2][0]
new_y = body[i-2][1]
i -= 1
body[0][0] = head[0]
body[0][1] = head[1]
return body, new_part
#начало новой игры
def new_game():
head = [180,180]
body = [[160,180],[140,180],[120,180]]
new_part = []
score = 0
death = False
fruits()
return head, body, new_part, score, death
#генерация новых фруктов
def fruits():
fruit = [random.randint(1,29)*box, random.randint(1,29)*box]
poisonFruit = fruit
while fruit == poisonFruit:
poisonFruit = [random.randint(1,29)*box, random.randint(1,29)*box]
return fruit, poisonFruit
#инициализация окна
size = [600,600]
window = pg.display.set_mode(size)
pg.display.set_caption('snek!')
screen = pg.Surface(size)
box = 20
#инициализация змеи
snek = pg.Surface([box,box])
snek.fill([255,255,255])
head, body, new_part, score, death = new_game()
#инициализация фрукта и ядовитого фрукта
fruitIMG = pg.Surface([box,box])
fruitIMG.fill([255,255,0])
poisonFruitIMG = pg.Surface([box,box])
poisonFruitIMG.fill([0,255,0])
fruit, poisonFruit = fruits()
#направление движения
direction = "RIGHT"
to = "RIGHT"
running = True
while running:
for e in pg.event.get():
if e.type == pg.QUIT:
running = False
elif e.type == pg.KEYDOWN:
#управление
if e.key == ord('w'):
to = "UP"
if e.key == ord('s'):
to = "DOWN"
if e.key == ord('a'):
to = "LEFT"
if e.key == ord('d'):
to = "RIGHT"
if e.key == ord('n') and death == True:
head, body, new_part, score, death = new_game()
snek.fill([255,255,255])
fruit, poisonFruit = fruits()
direction = "RIGHT"
to = "RIGHT"
#проверка направления движения
if(to == "UP" and direction != "DOWN"):
direction = "UP"
if(to == "DOWN" and direction != "UP"):
direction = "DOWN"
if(to == "RIGHT" and direction != "LEFT"):
direction = "RIGHT"
if(to == "LEFT" and direction != "RIGHT"):
direction = "LEFT"
#перемещение
if direction == "UP" and death == False:
body, new_part = move(body, head)
head[1] -= box
if direction == "RIGHT" and death == False:
body, new_part = move(body, head)
head[0] += box
if direction == "LEFT" and death == False:
body, new_part = move(body, head)
head[0] -= box
if direction == "DOWN" and death == False:
body, new_part = move(body, head)
head[1] += box
#сьеден фрукт
if(head[0] == fruit[0] and head[1] == fruit[1]):
score+=1
fruit, poisonFruit = fruits()
body.append(new_part)
#смерть
death = IsDead(head, body, poisonFruit)
if death:
snek.fill([255,0,0])
#отрисовка
screen.fill([0, 0, 0])
screen.blit(poisonFruitIMG, poisonFruit)
screen.blit(snek, head)
for i in range(len(body)):
screen.blit(snek, body[i])
screen.blit(fruitIMG,fruit)
if(death):
draw_text(screen, "You lose!", 40, 200, 200)
draw_text(screen, "you score: " + str(score) +"!", 40, 180, 250)
draw_text(screen, "press N for new game!", 40, 130, 300)
else:
draw_text(screen, str(score), 20, 300, 10)
window.blit(screen, [0,0])
pg.display.flip()
pg.time.delay(150)
pg.quit() |
import math
file = open('comm_words.txt', encoding="utf8")
s = file.read()
s = s.split("\n")
word_list = dict()
med_len = float(0)
let_freq = []
total_let_freq = 0
for i in range(31):
let_freq.append(0)
for word in s: # aici o sa fie cate cuvinte bagam, inputul l-am presupus a fi de forma cuvant frecventa
new_word = word.split(" ")
#print(new_word[0], new_word[2])
real_word = new_word[0]
frequency = int(new_word[1])
med_len = med_len + len(real_word)
for l in real_word:
if l >= 'a' and l <= 'z':
let_freq[ord(l)-ord('a')] += 1
else:
if l == 'ă': let_freq[30] += 1
if l == 'â': let_freq[29] += 1
if l == 'î': let_freq[28] += 1
if l == 'ș': let_freq[27] += 1
if l == 'ț': let_freq[26] += 1
total_let_freq += len(real_word)
# print(real_word, end = '\n')
# print(frequency, end = '\n')
word_list[real_word] = frequency
med_len = med_len/8000
sum = 0
for key in word_list:
sum = sum + word_list[key]
expected_value = 0
for key in word_list:
#print(word_list[key]), "->", print(sum)
ratio = sum / word_list[key]
#print(1/ratio)
expected_value = expected_value + (1/ratio) * math.log2(ratio)
#print(len(key), "->" , word_list[key])
print("Entropia limbii române este:", expected_value)
|
# Uses python3
import sys
# Solution provided:
"""
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
"""
# Knowing that Pisano Period
# of modulo 10 is 60:
def fibonacci_sum(n):
def pisano_period(m):
previous = 1
current = 1
result = 1
while not (previous == 0 and current == 1):
previous, current = current, (previous + current) % m
result += 1
return result
pisano = pisano_period(10)
if n < 2: return n
n %= pisano
fib_arr = [1,1]
for _ in range(n):
fib_arr.append((fib_arr[-1] + fib_arr[-2]) % 10)
return (fib_arr[-1] - 1) % 10
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(fibonacci_sum(n))
|
import sys
def knapsack(n, W):
"""Recursive solution"""
arr = [[None for _ in range(W+1)] for _ in range(n+1)]
if arr[n][W] != None: return arr[n][W]
if n == 0 or W == 0:
res = 0
elif weights[n-1] > W:
res = knapsack(n-1, W)
else:
tmp1 = knapsack(n-1, W)
tmp2 = weights[n-1] + knapsack(n-1, W-weights[n-1])
res = max(tmp1, tmp2)
arr[n][W] = res
return arr[n][W]
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
W, n = data[0], data[1]
weights = data[2:]
print(knapsack(n, W))
|
from enum import Enum, unique
@unique
class TokenType(Enum):
# Single-character tokens.
LEFT_PAREN = '('
RIGHT_PAREN = ')'
LEFT_BRACE = '{'
RIGHT_BRACE = '}'
LEFT_BRACKET = '['
RIGHT_BRACKET = ']'
COMMA = ','
DOT = '.'
MINUS = '-'
PLUS = '+'
SLASH = '/'
STAR = '*'
# One or two character tokens.
BANG_EQUAL = '!='
EQUAL = '='
EQUAL_EQUAL = '=='
GREATER = '>'
GREATER_EQUAL = '>='
LESS = '<'
LESS_EQUAL = '<='
# Literals.
IDENTIFIER = '[identifier]'
STRING = '[string]'
NUMBER = '[number]'
CUSTOM_OPERATOR = '[custom operator]'
# Keywords.
AND = 'and'
BREAK = 'break'
CLASS = 'class'
ELSE = 'else'
END = 'end'
FALSE = 'False'
FOR = 'for'
FUNCTION = 'def'
GENERATOR = 'generator'
IF = 'if'
IN = 'in'
IS = 'is'
NONE = 'None'
NOT = 'not'
OPERATOR = 'operator'
OR = 'or'
PRINT = 'print'
RETURN = 'return'
SELF = 'self'
THEN = 'then'
TRUE = 'True'
UNDEFINED = 'Undefined'
WHILE = 'while'
YIELD = 'yield'
END_OF_LINE = '\n'
# End of file marker
EOF = '[EOF]'
|
'''
In this lecture we cover how optimized is binary search
And how to use AVL tree concepts to balance the binary tree's height to atmost logn
'''
class Node:
def __init__(self, val: int or float , left=None, right=None):
self.val = val
self.left = left
self.right = right
self.height = 1
self.balance_factor = 0
def __repr__(self):
return '{},{},{}'.format(self.left, self.val, self.right)
class AVL:
def __init__(self, node):
self.tree = node
def __repr__(self):
return f'{self.tree.left}(), {self.tree.val}({self.tree.height}), {self.tree.right}()'
def insert(self, val, tree=None):
if tree is None:
tree = self.tree
if val < tree.val:
if tree.left is None:
tree.left = Node(val)
else:
self.insert(val, tree.left)
elif val > tree.val:
if tree.right is None:
tree.right = Node(val)
else:
self.insert(val, tree.right)
tree.height = 1 + max(self.height(tree.right), self.height(tree.left))
tree.balance_factor = self.balance_factor(tree.left) - self.balance_factor(tree.right)
print('balance factor',tree.balance_factor)
if tree.balance_factor > 1: #right rotation
print(tree.left.balance_factor)
if tree.left.balance_factor > 0: #right-right rotation
self.tree = self.right_rotate(tree)
if tree.left.balance_factor < 0: #right-left rotation
temp_1 = tree.left.right
temp_1.height += 1
temp_2 = tree.left
temp_2.right = temp_1.left
temp_2.height -= 1
temp_1.left = temp_2
tree.left = temp_1
self.tree = self.right_rotate(tree)
if tree.balance_factor < -1: #left rotation
if tree.right.balance_factor < 0: #left-left rotation
self.tree = self.left_rotate(tree)
if tree.left.balance_factor > 0: #left-right rotation
temp_1 = tree.right.left
temp_1.height += 1
temp_2 = tree.right
temp_2.left = temp_1.right
temp_2.height -= 1
temp_1.right = temp_2
tree.right = temp_1
self.tree = self.left_rotate(tree)
return
def right_rotate(self, tree):
temp = tree.left
tree.left = temp.right
tree.height -= 1
print('xxxx', temp)
temp.right = tree
return temp
def left_rotate(self, tree):
temp = tree.right
tree.right = temp.left
tree.height -= 1
print('xxxx', temp)
temp.left = tree
return temp
def height(self, tree):
if tree is None:
return 0
print(tree)
return tree.height
def balance_factor(self, tree):
if self.height(tree) == 0:
return 0
return self.height(tree)
nums = [5, -1, 7, 4, 6, -2, 8]
root = Node(5)
tree = AVL(root)
for i in nums:
tree.insert(i)
print(tree)
print(root.left)
print(root.right) |
class First:
def __init__(self,a,b):
self.a = a
self.b = b
print("iam constructor")
def sum(self):
res=self.a+self.b
print(res)
'''def __str__(self):
print("a="+str(self.a)+"b="+str(self.b))'''
def __del__(self):
print("iam destructor")
obj=First(10,20)
print(obj)
obj.sum() |
n=;arm=0;temp=n
while n!=0:
rem=n%10
arm=arm+(rem**3)
n=n//10
print(temp,'is reverse is',arm)
if temp==arm:
print(temp,'is armstong')
else:
print(temp,'is not armstrong')
|
import random
from time import sleep
##o random.randint gera numeros inteiros
pc = random.randint(1,6)
usuario = int(input('Descubra o numero numero escolido pelo computador: '))
print('PROCESSANDO...')
sleep(3)
if pc == usuario:
print('Parabens voce acertou')
else:
print('Infelizmente voce nao acertou, o computador pensou no numero {} e voce pensou no numero {} '.format(pc, usuario)) |
import math
num = int(input('Digite um numero: '))
raiz= math.sqrt(num)
print('Araiz do numero {} é igual a {}'.format(num, raiz))
#random gera numeros aleatoorios
import random
num = random.random()
print(num) |
nome = (input('Digite o seu nome: '))
print('Prazer em te conhecer {:=^20}!'.format(nome))
n1 = int(input('Digite um numero: '))
n2 = int(input('Digite um segundo numeror: '))
print('A soma vale {}'.format(n1+n2))
n3 = int(input('Entre com um valor: '))
n4 = int(input('Entre com um outro valor: '))
s = n3 + n4
m = n3 * n4
sub = n3 - n4
d = n3 / n4
di= n3 // n4
e = n3 ** n4
print('A soma entre os valor é {}'.format(n3 + n4))
print('A mutiplicação between os values é {}'.format(n3 * n4))
print('A subtração between values é {} '.format(n3 - n4))
print('A divisão between values é {:.3f}'.format(n3 / n4))
print('A divisão inteira between values é {}'.format(n3 // n4))
print('The value da exponenciação é {}'.format(n3 ** n4)) |
import math
num = float(input('Digite o valor do cateto oposto: '))
num2 = float(input('Digite o valor do cateto adjacente:'))
#hi = (num ** 2 + num2 **2) ** (1/2)
hi= math.hypot(num, num2)
print('A hipotenusa vai medir {:.1f}'.format(hi)) |
'''通过bp算法拟合y = 2x这个函数'''
import numpy as np
x = np.array([1,2,3]).T
y = (2 * x).T
w = 10
for i in range(1000):
p_y = x * w
dy = (p_y - y)/3
dw = x.T.dot(dy)
w += -0.01 * dw
print(w)
|
def FileReader(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read()
except:
inputsent = filename.lower()
return(inputsent)
def CheckCommComb(inputsent): #The program can take any list it wants to check for the combinations, and thus this can also be used for 2 letter combination or 4 letter combinations
count = 0
common = "ing ver sch ter ste tie cht der ers ere aar ren eid nde ngs and ten ent ens eri erk rij oor ati hei gen est end eli ele rin ken sta ond lin den str aan nge eer nst ker len tel ach nte lij ege raa ijk enb erb ant gel del ena ier erd ede pro eve uit aal men lan wer per env ist aat erv eld art nin cha ger era tra sti iek ven tin rst eno eni pen din eke erg uur roe rde enk eel ite ert lie rie sto ont het een die dat wie wat hoe"
commonlist = common.split(" ") #Makes a list of the most common triplets and some 3 letter common words like "het, wat, wie, hoe, een"
inputsent = FileReader(inputsent)
inputlist = inputsent.split(" ") #Removes spaces from the input sentence
inputsent = "".join(inputlist)
for i in commonlist: #Iterates through all the common triplets
if i in inputsent.lower(): #If triplet is in the inputsent it will continue
count += inputsent.lower().count(i) #In this parts it then counts how many times the triplet is in the text and adds the amount to a counter
outcome = count/len(inputsent) #Here is the total count devided by the length of the message
return(outcome) #Outcome is usually for Dutch a constant as it devides by the length of the message
print(CheckCommComb("TextInput.txt"))
|
def FileReader(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read()
except:
inputsent = filename.lower()
return(inputsent)
def CheckMedklink(filename):
inputsent = FileReader(filename) #Reads all the items from a file or string and stores it in inputsent
splitlist = inputsent.split(" ") #Removes spaces from the sentence
inputsent = "".join(splitlist)
counter = 0 #Counter variable which counts the amount of medeklinker streaks more than 6
streak = 0 #Counter variable which counts the streak of medeklinkers in a part of the text
for i in inputsent: #Iterates through each letter of the message
if i.isalpha(): #Checks if the letter is indeed a letter and not a space or punctuation e.g.
if i in "aeoui": #If the letter is a klinker it sets the streak counter to 0
streak = 0
else: #If the letter is a medeklinker it adds 1 to the streak counter
streak += 1
if streak > 6: #If the streak counter is greater than 6 it will add 1 to the counter
counter += 1
ratio = counter/len(inputsent) #The counter is devided by the amount of letters in the text, this way the length of the text doesn't matter for the output
return(ratio)
if __name__ == "__main__":
print(CheckMedklink("TextInputDocs.txt"))
|
def LangRecog(input):
def FileReader(filename):
try:
with open(filename, "r") as reader:
inputsent = reader.read()
except:
inputsent = filename.lower()
return(inputsent)
def RatioKlinkCheck(filename):
inputsent = FileReader(filename) #Reads from the file and stores it in inputsent
klcount = 0 #Variable that counts the amount of klinkers
medklcount = 0 #Variable that counts the amount of medeklinkers
for i in inputsent: #Iterates through each item in the inputsent
if i.isalpha(): #Checks if item is a letter
if i in "aeoui": #If item is a klinker it adds one to the klinkercount
klcount += 1
else: #Else it must be a medeklinker and adds one to the medeklinkercount
medklcount += 1
ratio = klcount / medklcount #Calculates the ratio between klinkers and medeklinkers which is unique for each language
return(ratio)
def CheckMedklink(filename):
inputsent = FileReader(filename) #Reads all the items from a file or string and stores it in inputsent
splitlist = inputsent.split(" ") #Removes spaces from the sentence
inputsent = "".join(splitlist)
counter = 0 #Counter variable which counts the amount of medeklinker streaks more than 6
streak = 0 #Counter variable which counts the streak of medeklinkers in a part of the text
for i in inputsent: #Iterates through each letter of the message
if i.isalpha(): #Checks if the letter is indeed a letter and not a space or punctuation e.g.
if i in "aeoui": #If the letter is a klinker it sets the streak counter to 0
streak = 0
else: #If the letter is a medeklinker it adds 1 to the streak counter
streak += 1
if streak > 6: #If the streak counter is greater than 6 it will add 1 to the counter
counter += 1
ratio = counter/len(inputsent) #The counter is devided by the amount of letters in the text, this way the length of the text doesn't matter for the output
return(ratio)
def CheckCommComb(inputsent): #The program can take any list it wants to check for the combinations, and thus this can also be used for 2 letter combination or 4 letter combinations
count = 0
common = "ing ver sch ter ste tie cht der ers ere aar ren eid nde ngs and ten ent ens eri erk rij oor ati hei gen est end eli ele rin ken sta ond lin den str aan nge eer nst ker len tel ach nte lij ege raa ijk enb erb ant gel del ena ier erd ede pro eve uit aal men lan wer per env ist aat erv eld art nin cha ger era tra sti iek ven tin rst eno eni pen din eke erg uur roe rde enk eel ite ert lie rie sto ont het een die dat wie wat hoe"
commonlist = common.split(" ") #Makes a list of the most common triplets and some 3 letter common words like "het, wat, wie, hoe, een"
inputsent = FileReader(inputsent)
inputlist = inputsent.split(" ") #Removes spaces from the input sentence
inputsent = "".join(inputlist)
for i in commonlist: #Iterates through all the common triplets
if i in inputsent.lower(): #If triplet is in the inputsent it will continue
count += inputsent.lower().count(i) #In this parts it then counts how many times the triplet is in the text and adds the amount to a counter
outcome = count/len(inputsent) #Here is the total count devided by the length of the message
return(outcome) #Outcome is usually for Dutch a constant as it devides by the length of the message
#=====================================================================#
points = 0
input = FileReader(input)
inputlist = []
for i in input:
if i.isalpha():
inputlist.append(i)
input = "".join(inputlist) #Converts the initial input into a more common format
check1 = RatioKlinkCheck(input)
check2 = CheckCommComb(input)
check3 = CheckMedklink(input)
if 0.4 <= check1 < 0.5:
points += 10
elif 0.4 <= check1 < 0.5:
points += 20
elif 0.5 <= check1 < 0.6:
points += 30
elif 0.6 <= check1 < 0.7:
points += 40
elif 0.7 <= check1 < 0.9:
points += 30
elif 0.9 <= check1 < 1.5:
points += 10
if 0.0 <= check2 < 0.2:
points += 20
elif 0.2 <= check2 < 0.5:
points += 30
if check3 < 0.01:
points += 30
elif check3 < 0.1:
points += 10
return(points)
if __name__ == "__main__":
print(LangRecog("ajksdlfjkwjelfkjsdlkfjasldk"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.