text
stringlengths 37
1.41M
|
---|
def lcm(text1, text2):
"""
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
"""
row_length = len(text1) + 1 # height of the dp matrix
col_length = len(text2) + 1 # width of the dp matrix
cell = [[0] * col_length for _ in range(row_length)]
for row_index in range(1, row_length):
for col_index in range(1, col_length):
if text1[row_index - 1] == text2[col_index - 1]:
cell[row_index][col_index] = cell[row_index - 1][col_index - 1] + 1
else:
cell[row_index][col_index] = max(
cell[row_index][col_index - 1], cell[row_index - 1][col_index]
)
return cell[row_length - 1][col_length - 1]
|
def binary_search(arr, low, high, target):
if low == high:
return arr[low] == target
while low < high:
midpoint_index = low + ((high - low) // 2)
midpoint = arr[midpoint_index]
if midpoint == target:
return True
if midpoint < target:
low = midpoint + 1
else:
high = midpoint - 1
return False
|
# nums is always sorted
def get_index_equals_value(nums):
return binary_search_solution_recursive(nums, 0, len(nums) - 1, -1)
# return binary_search_iterative(nums)
# better solution because it's simple, fewer lines of code, and not recursive
def binary_search_iterative(arr):
left = 0
right = len(arr) - 1
while left <= right:
midpoint_index = (left + right) // 2
midpoint = arr[midpoint_index]
# We have to check for 3 main cases: the index equals its value, the index is less than its value, and the index is greater than its value
# If we found that the midpoint_index equals its value, we still have to check for three sub-cases:
if midpoint_index == midpoint:
# Sub-case 1: if the midpoint index is the first index, then it is lowest possible matching index which is the lowest possible index
if midpoint_index == 0:
return midpoint_index
# Sub-case 2: if the immediate left is not the lowest possible matching index, we are on the lowest index
if (
midpoint_index == midpoint
and midpoint_index - 1 - arr[midpoint_index - 1] != 0
):
return midpoint_index
# Sub-case 3: if the immediate left is the lowest possible matching index, we need to shrink the search space by eliminating everything to the right
if (
midpoint_index == midpoint
and midpoint_index - 1 - arr[midpoint_index - 1] == 0
):
right = midpoint_index - 1
# The second main case means that the value is greater than the current index
# in a sorted, monotonoically increasing array, this fact would hold true if we keep searching the rest of the elements to the right
# thus there is no need to search the right
# instead shrink the search space by shrinking the right side to the midpoint
elif midpoint_index < midpoint:
right = midpoint_index - 1
# The final main case is the opposite of the previous case: the value at the index is less than the index itself
# In a monotonically increasing array, all the values to the left would also be less than its index
# example, [1,2,3]; at index 2, the value 3 is less than index 2. As we go left the index will always decrease by 1, moreover the value at the index will also decrease and the lowest it can decrease is by one. At best, the index and values at the index will decrease at the same rate of 1 as we go left. And if this middle point has shown that the value at the index is greater than the index, we can never find a situation in which the index equals its value if we keep searching left. Thus shrink the search space to the right
else:
left = midpoint_index + 1
return -1
# Works, but too complicated, is recursive, and too many if statemnents and checks
def binary_search_solution_recursive(nums, start, end, current_min_index):
if not nums:
return -1
# the lowest index matching is the first index, furthest left
if start == end and start == 0 and nums[start] == 0:
return start
# the lowest index is not the first index and we are on the index that equals its value
if start == end and start == 0:
return current_min_index
# we are in section where the first index is not within the current search space. the lowest index matching is the furthest right
if start == end and nums[end] == end:
return end
if start == end:
return current_min_index
mid = (end - start) // 2
if mid == 0:
mid = start
# search left
if nums[mid] > mid:
return binary_search_solution_recursive(nums, start, mid - 1, current_min_index)
# search right
if nums[mid] < mid:
return binary_search_solution_recursive(nums, mid + 1, end, current_min_index)
# search the first index if needed, search the immediate left of midpoint
if nums[mid] == mid:
return binary_search_solution_recursive(nums, start, mid - 1, mid)
|
"""
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
"""
""" Commentary
Again, this problem tests you bit manipulation skills. In this case, the bit mask. We can use the
bit mask to grab the least significant bit and determine if it is a 1. If so, increase our counter.
Then shift the mask to the right to check the next digit. We know that the digit is 32 bits long,
so we iterate 32 times to check each bit. Very straightforward solution.
Another way to solve this, perhaps faster, is using a bit manipulation trick, namely the idea that
doing an AND operation between a number n and n - 1 will flip the least significant 1-bit to a zero.
Knowing this, we simply set up a while loop on the number, increase our counter, flip the least significant
1-bit to 0, and then repeat until all the 1's are zeroes and thus the number is zero. This avoids
visiting every bit and instead just targets the 1 bits.
"""
def hammingWeight(n):
mask = 1
bits = 0
for _ in range(32):
# check if the current position has a 1, if so, add to our counter
if n & mask != 0:
bits += 1
# shift the mask to the right by 1 to go to the next least significant digit
mask <<= 1
return bits
def bit_manipulation(n):
bits = 0
while n != 0:
bits += 1
n = n & (
n - 1
) # The Crux is that for any number n, when doing an AND operation with n and n-1, it flips the least significant 1-bit to 0
return bits
|
"""
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
"""
"""Commentary
This is a classic tree searching question that tests if you know DFS and know how to code it up quickly. The algorithm
simply is to get the height of the left and right side. Compare them. And choose the bigger height. Very simple.
The key to this is recursion. You want to use the call stack (not a stack data structure, although you can) to hold your
recursive calls. You need to know what is the base case (aka stopping point). And you need to know how to use accumulators implicitly
to get the total height of each side.
"""
def max_depth(root):
if not root:
return 0
left_depth = 1 + max_depth(root.left)
right_depth = 1 + max_depth(root.right)
return max(left_depth, right_depth)
|
"""
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
"""Commentary
The naive solution is the check every substring and determine if it is a palindrome and the largest one we have seen so far.
Verification of a palindrome in any string takes n time. Going through every substring take n^2 time. Thus the total runtime is n^3.
The dynamic programming solution uses a two dimensional matrix to keep track of computations, thus improving the naive solution. We can build a bottom
up solution by realizing that we can know the palindrome status for one and two characters. Those are our base cases and will setup our matrix. Having
the palindrome status for one and two characters will allow us to calculate the largest paindromic substring by observing the following recurrence:
If the substring is_palindrome[left + 1][right - 1] is True and the current substring s[left] == s[right], then that substring s[left:right] is a palindrome
Otherwise, it's not.
We can also arrive at a different solution by observing that palindromes are symmetrical around the center. Thus a string is a palindrome if
the substrings to the left and right of the center are the same. In fact, we can think of expanding from the center to determine if a string
is a palindrome. Expanding from the center takes n^2 runtime but at a cost of constant space because we can keep track of the pointers of the largest palindrome.
The runtime is n^2 because palindromes can have centers between two letters such as "abba" as opposed to "ava". Thus, we have to expand from the center
for every letter and for every two contiguous letters.
"""
def longest_palindrome(string):
# return expand_from_middle_solution(string)
return dynamic_programming_solution(string)
# return brute_force_solution(string)
def brute_force_solution(string):
def is_palindrome(string, i, j):
while i <= j:
if string[i] == string[j]:
i += 1
j -= 1
else:
return False
return True
max_len = 0
result = ""
for i in range(len(string)):
for j in range(i, len(string)):
if is_palindrome(string, i, j):
len_of_current_palindrome = j + 1 - i
if len_of_current_palindrome > max_len:
max_len = len_of_current_palindrome
result = string[i : j + 1]
return result
def expand_from_middle_solution(string):
def length_palindrome(string, left, right):
if not string or left > right:
return 0
# ensure that the left and right are within bounds
# the last condition will enforce the palindrome property by breaking out of the while loop and returning the length of the current palindrome
# in other words it stops expanding the window when the characters don't match
while left >= 0 and right < len(string) and string[left] == string[right]:
left -= 1
right += 1
return right - left - 1
def start_index(center, length):
return center - (
(length - 1) // 2
) # we have to subtract 1 from the length because our string array starts at index 0. If we didn't do this, we would go one over the starting position of the palindrome
def end_index(center, length):
return center + (length // 2)
max_len_palindrome_start = 0
max_len_palindrome_end = 0
max_len_palindrome = max_len_palindrome_end - max_len_palindrome_start
for center in range(len(string)):
len_palindrome_odd_length_substring = length_palindrome(string, center, center)
len_palindrome_even_length_substring = length_palindrome(
string, center, center + 1
)
current_max_len_palindrome = max(
len_palindrome_odd_length_substring, len_palindrome_even_length_substring
)
if current_max_len_palindrome > max_len_palindrome:
max_len_palindrome_start = start_index(center, current_max_len_palindrome)
max_len_palindrome_end = end_index(center, current_max_len_palindrome)
max_len_palindrome = max_len_palindrome_end - max_len_palindrome_start
return string[max_len_palindrome_start : max_len_palindrome_end + 1]
def dynamic_programming_solution(string):
if len(string) == 0:
return string
is_palindrome = [[False for _ in range(len(string))] for _ in range(len(string))]
start = 0
max_length = 1
# setup substrings of single characters
for index in range(len(string)):
is_palindrome[index][index] = True
# setup substrings of two characters
for index in range(len(string) - 1):
if string[index] == string[index + 1]:
is_palindrome[index][index + 1] = True
start = index
max_length = 2
# for substrings of length three or greater, we check if all the inner substrings are also palindromes.
# if all the inner substrings are palindromes, then the current length is also a palindrome
for substring_length in range(
3, len(string) + 1
): # we add one to the length of the string because we want to explore the substring at the last index; this is a unique to the range function, it excludes the provided stopping point
end_index = len(string) - substring_length + 1
# this is where we check all the inner substrings
for left_index in range(end_index):
right_index = left_index + substring_length - 1
# this is where we check the current inner substring
# it checks the cell block that is down and to the left in the matrix
# that spot is the palindrome status of the current substring
is_substring_a_palindrome = is_palindrome[left_index + 1][right_index - 1]
# since we are checking palindromes from left to right, we update the cache and the length and start index of the current palindrome
# in other words, our palindrome answer accumulates as we expand our palindrome to three or greater characters
if is_substring_a_palindrome and string[left_index] == string[right_index]:
is_palindrome[left_index][right_index] = True
max_length = substring_length
start = left_index
return string[start : start + max_length]
|
def find_grants_cap(grants_array, new_budget):
return solution_v1(grants_array, new_budget)
def solution_v1(grants_array, new_budget):
if sum(grants_array) <= new_budget:
return max(grants_array)
grants_array = sorted(grants_array)
grants_remaining = len(grants_array)
current_cap = new_budget / grants_remaining
for grant in grants_array:
if grant <= current_cap:
grants_remaining -= 1
new_budget -= grant
current_cap = new_budget / grants_remaining
else:
return current_cap
return current_cap
|
def quicksort(arr, low, high):
# sort only if there is more than one element in the array
if low < high:
# partition/sort the current array based on some partition
partition_index = partition(arr, low, high)
# sort the left side of the partition
quicksort(arr, low, partition_index - 1)
# sort the right side of the partition
quicksort(arr, partition_index + 1, high)
# the work of quicksort is done in the partition function
def partition(arr, low, high):
# choose some pivot
pivot_index = generate_pivot_index(low, high)
# move the value of the pivot to the far right or the box in the highest index
swap(arr, pivot_index, high)
pivot_index = high
# set a pointer on the leftmost part of the array
border = low
for index in range(low, high):
# depending on how you want to sort, change the logic in the if statement
# depending on where you isolate the pivot value will determine your logic
# if the pivot value is on the far right, then you want to operate/move elements that are less than the pivot
# if the pivot value is on the far left, then you want to operate/move elements that are greater than the pivot
if arr[index] < arr[pivot_index]:
swap(arr, index, border)
border += 1
swap(arr, border, pivot_index)
return border
def swap(arr, l, r):
arr[l], arr[r] = arr[r], arr[l]
def generate_pivot_index(low, high):
# implement any logic here
return high
|
def find_min(nums):
"""
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
"""
# handles case of a sorted array that shifted by 0
if nums[len(nums) - 1] > nums[0]:
return nums[0]
first_num = nums[0]
left = 0
right = len(nums) - 1
rotate_index = 0
while left < right:
pivot_index = (right + left) // 2
pivot = nums[pivot_index]
if pivot >= first_num:
left = pivot_index
else:
right = pivot_index
if right - left == 1:
rotate_index = right
break
return nums[rotate_index]
|
def is_fifo(takeout, dine_in, served):
"""
My cake shop is so popular, I'm adding some tables and hiring wait staff so folks can have a cute sit-down cake-eating experience.
I have two registers: one for take-out orders, and the other for the other folks eating inside the cafe. All the customer orders get combined into one list for the kitchen, where they should be handled first-come, first-served.
Recently, some customers have been complaining that people who placed orders after them are getting their food first. Yikes—that's not good for business!
To investigate their claims, one afternoon I sat behind the registers with my laptop and recorded:
The take-out orders as they were entered into the system and given to the kitchen. (take_out_orders)
The dine-in orders as they were entered into the system and given to the kitchen. (dine_in_orders)
Each customer order (from either register) as it was finished by the kitchen. (served_orders)
Given all three lists, write a function to check that my service is first-come, first-served. All food should come out in the same order customers requested it.
We'll represent each customer order as a unique integer.
As an example,
Take Out Orders: [1, 3, 5]
Dine In Orders: [2, 4, 6]
Served Orders: [1, 2, 4, 6, 5, 3]
would not be first-come, first-served, since order 3 was requested before order 5 but order 5 was served first.
But,
Take Out Orders: [1, 3, 5]
Dine In Orders: [2, 4, 6]
Served Orders: [1, 2, 3, 5, 4, 6]
would be first-come, first-served.
"""
# return is_fifo_iterative(takeout, dine_in, served)
# return is_fifo_recursive_v2(takeout, dine_in, served)
return is_fifo_recursive(takeout, dine_in, served)
def is_fifo_recursive(takeout, dine_in, served):
# this is an expensive implementation costing us time and space of n^2; do you know why?
# is_fifo_recursive_v2 is optimized for time at a cost of n
if not served and not takeout and not dine_in:
return True
elif not served and (takeout or dine_in):
return False
elif takeout and served[0] == takeout[0]:
return is_fifo_recursive(takeout[1:], dine_in, served[1:])
elif dine_in and served[0] == dine_in[0]:
return is_fifo_recursive(takeout, dine_in[1:], served[1:])
else:
return False
def is_fifo_recursive_v2(takeout, dine_in, served):
return is_fifo_recursive_v2_helper(takeout, dine_in, served, 0, 0, 0)
def is_fifo_recursive_v2_helper(
takeout, dine_in, served, takeout_index, dine_in_index, served_index
):
if (
served_index == len(served)
and takeout_index == len(takeout)
and dine_in_index == len(dine_in)
):
return True
elif served_index == len(served) and (
takeout_index < len(takeout) or dine_in_index < len(dine_in)
):
return False
elif (
takeout_index < len(takeout) and takeout[takeout_index] == served[served_index]
):
return is_fifo_recursive_v2_helper(
takeout, dine_in, served, takeout_index + 1, dine_in_index, served_index + 1
)
elif (
dine_in_index < len(dine_in) and dine_in[dine_in_index] == served[served_index]
):
return is_fifo_recursive_v2_helper(
takeout, dine_in, served, takeout_index, dine_in_index + 1, served_index + 1
)
else:
return False
def is_fifo_iterative(takeout, dine_in, served):
takeout_order = list(takeout)
dine_in_order = list(dine_in)
served_order = list(served)
for order in served_order:
if takeout_order and order == takeout_order[0]:
takeout_order.pop(0)
elif dine_in_order and order == dine_in_order[0]:
dine_in_order.pop(0)
else:
return False
if takeout_order or dine_in_order:
return False
return True
|
def valid_parenthesis(string):
stack = []
closing = {")": "(", "]": "["}
opening = set(["(", "["])
for char in string:
if char in opening:
stack.append(char)
elif char in closing:
if stack:
peek = stack[-1]
if peek == closing.get(char):
stack.pop()
else:
return False
# when we are here, we know that we have a closing parenthesis with no opening parenthesises at all, we should simply stop
# checking because at this point, this is the earliest we know that the string is invalid, going from left to right
else:
return False
else:
raise Exception("Invalid character")
return not stack
|
"""
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
"""
"""Commentary
The key to solving this problem elegantly and the most efficient way (n runtime but at a cost of n space) is to recognize
that the the product of all numbers except the current number is the same thing as saying: give me the product of the product
of numbers left of the current number and right of the current number. Visually, you can see this:
Array
4, 5, 8, 2
Product of numbers left of each box
1, 1*4, 1*4*5, 1*4*5*8
Product of numbers right of each box
1*8*2*5, 1*8*2, 1*8, 1
Then we multiply both arrays to give us the complete answer.
To arrive at the efficient solution is not intuitive. A technique to understanding the efficient solution is to
draw out an example of what the product of each number is supposed to look like. By drawing out the example, we can
get or at least glimpse the solution of using left and right total products.
The implementation simply follows that logic.
"""
def product_except_self(nums):
# return brute_force(nums)
return greedy_approach_sub_optimal_space_complexity(nums)
# return greedy_approach_optimal_space_complexity(nums)
def brute_force(nums):
products = [1] * len(nums)
for index in range(len(nums)):
for inner_index, other_num in enumerate(nums):
if index != inner_index:
products[index] = products[index] * other_num
return products
def greedy_approach_sub_optimal_space_complexity(nums):
product_left_of_index = [1] * len(nums)
current_product_left_of_index = 1
for index, current_num in enumerate(nums):
product_left_of_index[index] = current_product_left_of_index
current_product_left_of_index = current_product_left_of_index * current_num
product_right_of_index = [1] * len(nums)
current_product_right_of_index = 1
for index in range(len(nums) - 1, -1, -1):
product_right_of_index[index] = current_product_right_of_index
current_product_right_of_index = current_product_right_of_index * nums[index]
# using list comprehension to simplify the multiplication of two arrays of the same size
return [x * y for x, y in zip(product_left_of_index, product_right_of_index)]
def greedy_approach_optimal_space_complexity(nums):
product_left_of_index = [1] * len(nums)
current_product_left_of_index = 1
for index, current_num in enumerate(nums):
product_left_of_index[index] = current_product_left_of_index
current_product_left_of_index = current_product_left_of_index * current_num
products_except_self = [1] * len(nums)
current_product_right_of_index = 1
for index in range(len(nums) - 1, -1, -1):
products_except_self[index] = (
product_left_of_index[index] * current_product_right_of_index
)
current_product_right_of_index = current_product_right_of_index * nums[index]
return products_except_self
|
"""Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
"""
""" Commentary
This problem tests your ability to traverse a binary tree, specifically inorder, postorder, preorder traversals, which
are common. The recursive approach is quite intuitive and descriptive of what it does; the elegance stems from
the use of recursion and a declarative-style. Moreover, the traversal is a DFS-like traversal, searching the farthest left-side, then moves
to the right. The key to being efficient is to stop the search once you have found a node that is not
identical. There is no need to search the right subtree if the left subtree is not identitcal. The code is
refactored to reflect that optimization.
The iterative approach is more procedural and requires explicit data structures and a while loop and a helper function.
"""
def is_same_tree(p, q):
# both null
if not p and not q:
return True
# one is null
if not p or not q:
return False
# check current node
if p.val != q.val:
return False
# check left side
if not is_same_tree(p.left, q.left):
return False
# check right side
if not is_same_tree(p.right, q.right):
return False
return True
def is_same_tree_iterative(p, q):
def is_same_node(p, q):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return True
nodes_to_visit = []
nodes_to_visit.append((p, q))
while nodes_to_visit:
node1, node2 = nodes_to_visit.pop(0)
if not is_same_node(node1, node2):
return False
if node1:
nodes_to_visit.append((node1.left, node2.left))
nodes_to_visit.append((node1.right, node2.right))
return True
|
#!/usr/bin/env python
class Node(object):
def __init__(self,name):
# A list of (label,node) pairs
self.successors = set()
self.name = name
class Graph(object):
def __init__(self):
self.nodes = set()
def tarjan(self):
components = []
stack = []
indices = {}
lowlink = {}
def strongconnect(node):
i = 0
if len(indices) > 0:
i = max(v for (k,v) in indices.items())+1
indices[node] = i
lowlink[node] = i
stack.append(node)
for l,m in node.successors:
if m not in lowlink:
strongconnect(m)
lowlink[node] = min(lowlink[node],lowlink[m])
elif m in stack:
lowlink[node] = min(lowlink[node],indices[m])
if lowlink[node] == indices[node]:
component = set()
while True:
m = stack.pop()
component.add(m)
if m == node: break
components.append(component)
for n in self.nodes:
if n not in lowlink:
strongconnect(n)
return components
|
import string
import sys
import json
class JSON(object):
def __init__(self, data):
self.__dict__ = json.loads(data)
def lines(fp):
print(str(len(fp.readlines())))
def calculator(text, dict):
result = 0;
non_senti_words = []
list_of_words = text.split(' ')
for word in list_of_words:
if word in dict:
result += dict[word]
else:
non_senti_words.append(word)
return result, non_senti_words;
def correct_tweet(word):
exclude = set(string.punctuation)
word = ''.join(str(ch) for ch in word.lower() if str(ch) not in exclude)
return word
def main():
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
scores = {} # initialize an empty dictionary
for line in sent_file:
term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character"
scores[term] = int(score) # Convert the score to an integer.
for line in tweet_file:
tweet = JSON(line.encode('utf-8'))
try:
good_tweet = correct_tweet(tweet.text)
calc, words = calculator(good_tweet, scores)
for w in words:
print(w + ' ' + str(calc / float(len(good_tweet) - len(words))))
except:
pass
if __name__ == '__main__':
main()
|
# "Magic 8 Ball with a List" game
from random import shuffle # this part we will learn letter
messages = ['It is certain', 'It is decidedly so', 'Yes definitely',
'Reply hazy try again', 'Ask again later', 'Concentrate and ask again',
'My reply is no', 'Outlook not so good', 'Very doubtful']
shuffle(messages) # this function will mix the elements of the list
input("Ask a question to a ball and press any key to get your prediction")
print(messages[0])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
num = 0
numsum = 0
while num < 100:
num += 1
numsum += num
print (numsum)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
age = int(input('you age'))
if age >= 999:
print('age', age)
print('you can see av')
elif age >= 99:
print('age', age)
print('old')
else:
print('age', age)
print('fk you cant see av')
|
#A function can have multiple return statements. When any of them is executed, the function terminates.
#Bubble sort works by comparing number at index 0 to index 1. If number at index 0 is larger, then the larger number
#is swapped to index 1. And the smaller number is swapped to index 0.
#Next, the numbers at index 1 is compared to index 2. It contines again at index 2 to index 3.
#When the whole list is gone thru, the largest number will be placed at the end.
#The bubble sort starts again from beginning. At this second sort, the second largest number
#will be placed next to the largest number. This continues until the list is sorted resulting in smallest to largest number.
#My algorithm works by setting a while loop first. Inside the while loop, the for loop will go thru the list.
#If index x is larger than index x+1, the number is swapped and the count is added by one.
#The for loop repeats until the list is sorted. At this point, the count becomes zero.
#Count becoming zero means there is no more swapping at the index. This means the list is sorted.
#At this point, since count is no longer larger than 0, the while terminates. The list is returned after function call.
def bubble_sort(list):
temp=list[0]
count=1
count2=0
while count>0:
count=0
for x in range (len(list)-1):
if list[x]>list[x+1]:
temp=list[x+1]
list[x+1]=list[x]
list[x]=temp
count += 1
count2 += 1
print(count2)
return list
a=bubble_sort([4, 5, 2, 3, 1, -2, 5, 6, 0, -200, 2, 488, 900, -900, 222])
print(a)
|
import pygame # import the pygame module
import time # import the time module
import random # import the random module
pygame.init() # initialize pygame: returns a tuple or success or fail
# Setting up the RGB Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Display Variables
display_width = 800
display_height = 600
# Set the "Canvass" where our game will display: Requires tuple for resolution
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Slither') # Setting Title of the game
# Managing screen updating
clock = pygame.time.Clock()
block_size = 10 # Size of our character
fps = 30 # Creating the Frames per second variable
# Creating a font variable for use in our message_to_screen function
font = pygame.font.SysFont(None, 25)
def snake(lead_x, lead_y, block_size):
"""
Logic for drawing the snake and detecting colision
:return:
"""
pygame.draw.rect(game_display, BLACK, [lead_x, lead_y,
block_size, block_size])
def message_to_screen(msg, color):
"""
Sends a message to the user via the screen when something happens
:param msg: The contents of the message
:param color: The color that the message will be
:return:
"""
screen_text = font.render(msg, True, color)
# BLIT = Block Image Transfer, used to draw on the screen
game_display.blit(screen_text, [display_width / 2, display_height / 2])
# ------------------------ Game Loop ----------------------------- #
def game_loop():
"""
Main game Loop
:return:
"""
game_exit = False # Initializing game loop exit boolean to false
game_over = False # Some game over functionality
# Starting Position of the snake head
# The first block x (head of the snake)
# Rounding so that both the apple and snake appear at a multiple of 10
lead_x = round((display_width / 2) / 10.0 * 10.0)
lead_y = round((display_height / 2) / 10.0 * 10.0) # The first block y
# Speed and Direction of the snake head
lead_x_change = 0 # The change of the x coord
lead_y_change = 0 # The change of the y coord
# Random apple generation variables
# Rounding so that both the apple and snake appear at a multiple of 10
rand_apple_x = round(random.randrange(0, display_width - block_size)
/ 10.0) * 10.0
rand_apple_y = round(random.randrange(0, display_height - block_size)
/ 10.0) * 10.0
while not game_exit:
while game_over == True: # The game over loop
game_display.fill(WHITE)
message_to_screen('Game over, press C to play again or Q to quit',
GREEN)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# If q pressed on game over screen exit program
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT: # Checks if QUIT event is clicked
game_exit = True # Sets game_exit to True
if event.type == pygame.KEYDOWN: # Handling keypress events
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# Checks if snake hits the wall then exits if it does
if lead_x >= display_width or lead_x <= 0 or lead_y >= display_height \
or lead_y <= 0:
game_over = True
lead_x += lead_x_change # Updates x position per loop to the new pos
lead_y += lead_y_change # Updates y position per loop to the new pos
# ---------------------- Drawing Code --------------------------------- #
game_display.fill(WHITE) # Background
# Drawing the apples
pygame.draw.rect(game_display, RED, [rand_apple_x, rand_apple_y,
block_size, block_size])
# Drawing some stuff on the background
snake(lead_x, lead_y, block_size)
pygame.display.update()
if lead_x == rand_apple_x and lead_y == rand_apple_y:
print('om nom nom')
# Frames per second control
clock.tick(fps)
# Uninitialize pygame
pygame.quit()
quit() # Exits python
game_loop()
|
from collections import deque, OrderedDict
class Node(object):
def __init__(self, name, data):
self.name = name
self.data = data
self.inputs = {}
self.outputs = {}
def connect_to(self, node):
if not node in self.outputs:
self.outputs[node] = True
node.connect_from(self)
def connect_from(self, node):
if not node in self.inputs:
self.inputs[node] = True
node.connect_to(self)
def __str__(self):
return "Node '%s' (%s)"%(self.name, self.data)
class Graph(object):
def __init__(self):
self.nodes = {}
def register_node(self, node):
self.nodes[node.name] = node
def add_node(self, name, data):
node = Node(name, data)
self.register_node(node)
return node
def get_roots(self):
roots = deque()
for node in self.nodes.itervalues():
if not node.inputs:
roots.append(node)
return roots
def sort(self):
squeue = OrderedDict()
nc = {}
for node in self.nodes.itervalues():
nc[node] = 0
queue = self.get_roots()
while queue:
node = queue.popleft()
if not node in squeue and nc[node] == len(node.inputs):
squeue[node] = True
for output in node.outputs:
nc[output] += 1
queue.append(output)
return squeue
def node(self, name):
try:
return self.nodes[name]
except:
return None
def __iter__(self):
return self.nodes.itervalues()
g = Graph()
a = g.add_node('a',1)
b = g.add_node('b',1)
c = g.add_node('c',1)
d = g.add_node('d',1)
a.connect_to(b)
b.connect_to(c)
d.connect_to(b)
g.sort()
# d->
# a->b->c
|
class Node:
def __init__(self, data = None, next = None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def InsertInBegining(self, data):
node = Node(data, self.head)
self.head = node
def InsertAtTheEnd(self, data):
if self.head is None:
self.head = Node(data, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
def InsertValues(self, data_list):
self.head = None
for data in data_list:
self.InsertAtTheEnd(data)
def Print(self):
if self.head is None:
print("LinkedList is Empty")
return
itr = self.head
llstr = ""
while itr:
llstr += str(itr.data) + ' --> '
itr = itr.next
print(llstr)
def GetLength(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def RemoveAt(self, index):
if index < 0 or index >= self.GetLength():
raise Exception("Invalid Index")
if index == 0:
self.head = self.head.next
return
count = 0
itr = self.head
while itr:
if count == index-1:
itr.next = itr.next.next
break
itr = itr.next
count +=1
def InsertAt(self, index, data):
if index < 0 or index >= self.GetLength():
raise Exception("Invalid Index")
if index ==0:
self.InsertInBegining(data)
return
count = 0
itr = self.head
while itr:
if count== index -1:
node = Node(data, itr.next)
itr.next = node
break
itr = itr.next
count +=1
def InsertAfterValue(self, dataafter, data):
if dataafter is None:
raise Exception("Invalid Value")
if self.head.data==data:
self.head.next = Node(data,self.head.next)
return
itr = self.head
while itr:
if itr.data == dataafter:
node = Node(data, itr.next)
itr.next = node
break
itr = itr.next
def RemoveByValue(self, data):
if data is None:
raise Exception("Invalid Data")
if self.head.data == data:
self.head = self.head.next
return
itr = self.head
while itr.next:
if itr.next.data == data:
itr.next = itr.next.next
break
itr = itr.next
if __name__ == '__main__':
ll = LinkedList()
ll.InsertValues(["Apple", "Orange", "Banana", "Pineapple", "Grapes"])
print(ll.GetLength())
ll.Print()
ll.InsertAt(0, "figs")
ll.Print()
ll.InsertAfterValue("Banana", "Jackfruit")
ll.Print()
ll.RemoveByValue("Banana")
ll.Print()
|
number_of_shares = int(input("Enter number of shares:"))
purchase_price = float(input("Enter purchase price:"))
sale_price = float(input("Enter sale price:"))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .11)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .11)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")
import pandas as pd
#from tabulate import tabulate
import pytz
import datetime as dt
from datetime import date
# pass the API and prevDays (0 for today, 1 since yesterday...)
def report2(api, prevDays):
#
# get all closed orders and import them into a dataframe
#
orderTotal = 500
today = dt.date.today() - dt.timedelta(days=prevDays)
today = dt.datetime.combine(today, dt.datetime.min.time())
today = today.strftime("%Y-%m-%dT%H:%M:%SZ")
#print(today)
orders = api.list_orders(status='all', limit=orderTotal, after=today)
if not orders:
return
dfOrders = pd.DataFrame()
for o in orders:
# convert dot notation to dict
d = vars(o)
# import dict into dataframe
df = pd.DataFrame.from_dict(d, orient='index')
# append to dataframe
dfOrders = dfOrders.append(df, ignore_index=True)
# select filled orders with buy or sell
dfSel = dfOrders
# choose a subset (use .copy() as we are slicing and to avoid warning)
dfSel = dfSel[['submitted_at', 'filled_at', 'symbol', 'filled_qty', 'side', 'type', 'filled_avg_price', 'status']].copy()
# convert filled_at to date
dfSel['submitted_at'] = pd.to_datetime(dfSel['submitted_at'], format="%Y-%m-%d %H:%M:%S")
dfSel['filled_at'] = pd.to_datetime(dfSel['filled_at'], format="%Y-%m-%d %H:%M:%S")
# convert to our timezone
dfSel['submitted_at'] = dfSel['submitted_at'].dt.tz_convert('America/New_York')
dfSel['filled_at'] = dfSel['filled_at'].dt.tz_convert('America/New_York')
# remove millis
dfSel['submitted_at'] = dfSel['submitted_at'].dt.strftime("%Y-%m-%d %H:%M:%S")
dfSel['filled_at'] = dfSel['filled_at'].dt.strftime("%Y-%m-%d %H:%M:%S")
# Sort: https://kanoki.org/2020/01/28/sort-pandas-dataframe-and-series/
# need to sort in order to perform the proper calculations
# sort based on the following sequence of types: market then limit, then stop_limit
dfSel['type'] = pd.Categorical(dfSel['type'], categories=["market", "limit", "stop_limit"])
# sort first based on symbol, then type as per the list above, then submitted date
dfSel.sort_values(by=['symbol', 'submitted_at', 'type'], inplace=True, ascending=True)
# reset index
dfSel.reset_index(drop=True, inplace=True)
# drop the 'side' column
# dfProfit = dfSel.drop('side', 1)
dfProfit = dfSel
# add empty 'profit' column
dfProfit['profit'] = ''
totalProfit = 0.0
profitCnt = 0
lossCnt = 0
slCnt = 0
ptCnt = 0
trCnt = 0
qty = 0
profit = 0
sign = {'buy': -1, 'sell': 1}
# show header row
#print(tabulate(dfSel[:0], headers='keys', tablefmt='simple', showindex=False))
for index, row in dfSel.iterrows():
# show data row
#print(index, tabulate(dfSel[index:index+1], headers='', tablefmt='plain'))
# conditions:
# - buy/sell have the same symbol
# - a trade is considered if no new/held orders are still open
# - once qty is 0 a complete trade is confirmed and profit calculated
# - a filled_avg_price is not None
if index > 0:
if dfSel['symbol'][index - 1] != dfSel['symbol'][index]:
qty = 0
profit = 0
if dfSel['status'][index] == 'held':
continue
if dfSel['status'][index] == 'new':
continue
if dfSel['filled_avg_price'][index] is None:
continue
if dfSel['filled_avg_price'][index] == '':
continue
if dfSel['filled_avg_price'][index] == 'None':
continue
#print(index, tabulate(dfSel[index:index+1], headers='', tablefmt='plain'))
side = dfSel['side'][index]
filledQty = int(dfSel['filled_qty'][index]) * sign[side]
qty = qty + filledQty
price = float(dfSel['filled_avg_price'][index])
pl = filledQty * price
profit = profit + pl
#print(f"{dfSel['symbol'][index]}: qty {filledQty} price {price} profit {profit:.3f}")
if qty==0:
# complete trade
trCnt = trCnt + 1
# put the profit in its column
#dfProfit['profit'][index] = profit
dfProfit.loc[index, 'profit'] = round(profit, 2)
totalProfit = totalProfit + profit
if profit >= 0:
profitCnt = profitCnt + 1
if dfSel['type'][index] == 'limit':
ptCnt = ptCnt + 1
else:
lossCnt = lossCnt + 1
if dfSel['type'][index] == 'stop_limit':
slCnt = slCnt + 1
profit = 0
# append the total
dfProfit.loc["Total", "profit"] = round(totalProfit, 2) # dfProfit.profit.sum()
# print profit report
print(tabulate(dfProfit, headers='keys', tablefmt='simple', showindex=True, floatfmt=".2f"))
#print(dfProfit.to_string())
totalCnt = profitCnt + lossCnt
if totalCnt > 0:
ratio = profitCnt / totalCnt * 100.0
print('\nProfits:', profitCnt)
print('Losses :' , lossCnt)
print('Ratio :' , f'{ratio:.2f}%')
print('Trades :' , trCnt)
print('Stops :' , slCnt)
print('Targets:' , ptCnt)
|
import math
X = int(input())
Y = input()
N = int(input())
count = 0
i = 0
def isHappy(i):
s = 0
while(i > 0):
s = s + (i % 10) * (i % 10)
i = i // 10
if (s == 1):
return True
elif (s == 4):
return False
return isHappy(s)
def isPrime(i):
if (i == 1):
return False
for j in range(2, int(math.sqrt(i) + 1)):
if ((i % j) == 0):
return False
return True
if(Y == '@'):
print("Invalid Input")
else:
Y = int(Y)
if ((X > 0) or (Y > 0) or (Z > 0)):
for i in range(X, Y+1):
if(isPrime(i) and isHappy(i)):
count += 1
if (count == N):
print(i)
break
else:
print("No number is present at this index")
|
from numpy import array, amax, delete, insert
class Tetris:
def __init__(self, width, height, dict_fields):
self.width, self.height, self.dict_fields, self.piece = width, height, dict_fields, None
self.empty_field = array([["-"]*self.width]*self.height)
self.field = self.copy_field(self.empty_field)
self.offset = {"row": 0, "column": 0, "rotate": 0}
self.print_field(self.field)
self.move_piece(input())
def print_field(self, field):
count = 0
print("\n", end="")
for ar in field:
for el in ar:
count += 1
if count % self.width == 0:
print(el, end="")
continue
print(el, end=" ")
print("\n", end="")
def filling_field(self):
for el in self.dict_fields[self.piece][self.offset["rotate"] % len(self.dict_fields[self.piece])]:
el += self.offset["row"] + self.offset["column"]
self.field[el // self.width][el % self.width] = "0"
self.print_field(self.field)
def move_piece(self, act):
for column in range(self.width):
game_over = 0
for row in self.field:
if row[column] == "0":
game_over += 1
if game_over == self.height:
self.print_field(self.field)
print("\nGame Over!")
return True
if act == "break":
for row in range(len(self.field)):
if len(list(filter(lambda x: x == "0", self.field[row]))) == len(self.field[row]):
self.field = delete(self.field, row, axis=0)
self.field = insert(self.field, 0, "-", axis=0)
self.empty_field = self.copy_field(self.field)
if row + 1 == self.height:
self.print_field(self.field)
return None
if act == "piece":
self.piece = input()
self.empty_field = self.copy_field(self.field)
self.offset = {"row": 0, "column": 0, "rotate": 0}
self.field = self.copy_field(self.empty_field)
piece_position = self.dict_fields[self.piece][self.offset["rotate"] % len(self.dict_fields[self.piece])]
end_condition = amax(piece_position) + self.offset["row"] + self.offset["column"] + self.width\
< self.width * self.height
left_condition = list(filter(lambda el: el % self.width == 0,
piece_position + self.offset["row"] + self.offset["column"]))
right_condition = list(filter(lambda el: (el % self.width) % (self.width - 1) == 0 and el % self.width != 0,
piece_position + self.offset["row"] + self.offset["column"]))
for el in piece_position + self.offset["row"] + self.offset["column"]:
if not right_condition and self.field[(el + 1) // self.width][(el + 1) % self.width] == "0":
right_condition = True
if not left_condition and self.field[(el - 1) // self.width][(el - 1) % self.width] == "0":
left_condition = True
if end_condition and not right_condition\
and self.field[(el + self.width + 1) // self.width][(el + self.width + 1) % self.width] == "0":
right_condition = True
if end_condition and not left_condition\
and self.field[(el + self.width - 1) // self.width][(el + self.width - 1) % self.width] == "0":
left_condition = True
if end_condition and self.field[(el + self.width) // self.width][(el + self.width) % self.width] == "0":
end_condition = False
if end_condition:
if act == "left" and not bool(left_condition):
self.offset["column"] -= 1
self.offset["row"] += self.width
elif act == "right" and not bool(right_condition):
self.offset["column"] += 1
self.offset["row"] += self.width
elif act == "rotate" and not bool(left_condition) and not bool(right_condition):
self.offset["rotate"] += 1
self.offset["row"] += self.width
elif act == "down":
self.offset["row"] += self.width
right_condition, left_condition = False, False
self.filling_field()
@staticmethod
def copy_field(field):
return array(field)
def main():
width, height = map(int, input().split())
dict_fields = {"O": array([[4, 14, 15, 5]]),
"I": array([[4, 14, 24, 34], [3, 4, 5, 6]]),
"S": array([[5, 4, 14, 13], [4, 14, 15, 25]]),
"Z": array([[4, 5, 15, 16], [5, 15, 14, 24]]),
"L": array([[4, 14, 24, 25], [5, 15, 14, 13], [4, 5, 15, 25], [6, 5, 4, 14]]),
"J": array([[5, 15, 25, 24], [15, 5, 4, 3], [5, 4, 14, 24], [4, 14, 15, 16]]),
"T": array([[4, 14, 24, 15], [4, 13, 14, 15], [5, 15, 25, 14], [4, 5, 6, 15]])}
tetris = Tetris(width, height, dict_fields)
while True:
user_input = input()
if user_input == "exit":
break
if tetris.move_piece(user_input):
break
if __name__ == "__main__":
main()
|
print "Welcome to Pypet!"
print
cat = {
'name': 'Weiwei',
'age': 22,
'weight': 11.6,
'hungry': True,
'photo': '(=^o.o^=)__',
'happiness': 0,
}
mouse = {
'name': 'Kaikai',
'age': 26,
'weight': 20.5,
'hungry': False,
'photo': '<:3 )~~~~',
'happiness': 0,
}
pets = [cat, mouse]
print 'Hello, ' + cat['name']
print
print cat['photo']
print
print cat
print
print 'Hello, ' + mouse['name']
print
print mouse['photo']
print
print mouse
print
def feed(pet):
if pet['hungry'] == True:
pet['hungry'] = False
pet['weight'] = pet['weight'] + 1
else:
print 'The Pypet is not hungry!'
if cat['hungry'] == True or mouse['hungry'] == True:
print "One or more pets are hungry!"
print "Choose an option:"
print "1. Feed cat 2. Feed mouse 3. Feed both"
choice = input("> ")
if choice == 1:
feed(cat)
print cat
elif choice == 2:
feed(mouse)
print mouse
else:
for pet in pets:
feed(pet)
print pet
|
#CTI 110
#M5HW2_SoftwareSales
#Michael Peters
#20 November 2017
# this program will account for a bulk discount on products sold
#product is $99
#4 discounts
# 10% - 10-19 items sold
# 20% - 20-49 items sold
# 30% - 50-99 items sold
# 40% - 100+ items sold
def main():
totalPackages = float(input('total number of packages sold:' ,))
subtotal = totalPackages * 99
discount1 = subtotal * .1
subtotal1 = subtotal - discount1
discount2 = subtotal * .2
subtotal2 = subtotal - discount2
discount3 = subtotal * .3
subtotal3 = subtotal - discount3
discount4 = subtotal * .4
subtotal4 = subtotal - discount4
if totalPackages == 1 or totalPackages <= 9:
print('total due:' ,format(subtotal,'.2f'))
elif totalPackages <=10 or totalPackages <= 19:
print('subtotal:' ,format(subtotal,'.2f'))
print('10% discount:' ,format(discount1,'.2f'))
print('total due:' ,format(subtotal1,'.2f'))
elif totalPackages <=20 or totalPackages <= 49:
print('subtotal:' ,format(subtotal,'.2f'))
print('20% discount:' ,format(discount2,'.2f'))
print('total due:' ,format(subtotal2,'.2f'))
elif totalPackages <=50 or totalPackages <= 99:
print('subtotal:' ,format(subtotal,'.2f'))
print('30% discount:' ,format(discount3,'.2f'))
print('total due:' ,format(subtotal3,'.2f'))
elif totalPackages <=100 or totalPackages <=99999999:
print('subtotal:' ,format(subtotal,'.2f'))
print('40% discount:' ,format(discount4,'.2f'))
print('total due:' ,format(subtotal4,'.2f'))
main()
|
#CTI 110
#M5HW1_AgeClassifier
#Michael Peters
#20 November 2017
# this program will ask for a persons age and then classify them in an age group.
def main():
# 4 catagories of age;
# 0-1 infant
# 2-12 child
# 13-19 teenager
# 20 and older an adult
age = float(input('How old are you?' ,))
if age == 0 or age == 1:
print('You are an infant')
elif age <= 2 or age <= 12:
print('You are a child')
elif age <= 13 or age <= 19:
print('You are a teenager')
elif age <= 20 or age <= 999999:
print('You are an adult')
main()
|
class Arbol:
def __init__(self,valor):
self.valor = valor
self.izquierda = None
self.derecha = None
#Metodo para agregar nodos a la izquierda del arbol, no importando que nodo
#del arbol queremos como padre de este
def AgregaIzquierda(self,padre,dato):
if self.valor != padre:
if self.izquierda != None:
self.izquierda.AgregaIzquierda(padre,dato)
if self.derecha!=None:
self.derecha.AgregaIzquierda(padre,dato)
else:
self.izquierda=Arbol(dato)
#Metodo para agregar nodos a la derecha, no importando que nodo del arbol
#queremos como padre de este
def AgregaDerecha(self,padre,dato):
if self.valor != padre:
if self.izquierda != None:
self.izquierda.AgregaDerecha(padre,dato)
if self.derecha!=None:
self.derecha.AgregaDerecha(padre,dato)
else:
self.derecha = Arbol(dato)
#Metodo que nos permite buscar un elemento en forma recursiva
def BuscaNodo(self,dato):
if self.valor != dato:
if self.izquierda!=None:
return self.izquierda.BuscaNodo(dato)
if self.derecha!=None:
return self.derecha.BuscaNodo(dato)
else:
return self.valor
#Metodo que nos permite buscar un elemento en forma recursiva
def BuscaNodoD(self,dato):
if self.valor != dato:
if self.derecha!=None:
return self.derecha.BuscaNodoD(dato)
if self.izquierda!=None:
return self.izquierda.BuscaNodoD(dato)
else:
return self.valor
#Metodo para impresion del arbol comenzando Primero Izquierda usando recursividad
def ImprimeArbolIzq(self):
if self.valor!=None:
print self.valor
if self.izquierda!=None:
self.izquierda.ImprimeArbolIzq()
if self.derecha!=None:
self.derecha.ImprimeArbolIzq()
#Metodo para impresion del arbol comenzando primero por la derecha usando recursividad
def ImprimeArbolDer(self):
if self.valor!=None:
print self.valor
if self.derecha!=None:
self.derecha.ImprimeArbolDer()
if self.izquierda!=None:
self.izquierda.ImprimeArbolDer()
arbol= Arbol(9)
# AgregaIzquierda(padre,dato)
arbol.AgregaIzquierda(9,23)
arbol.AgregaIzquierda(23,230)
arbol.AgregaIzquierda(230,830)
arbol.AgregaDerecha(230,431)
print
print 'Impresion del arbol comenzando por la izquierda'
arbol.ImprimeArbolIzq()
print
print
print 'Impresion del arbol comenzando por la derecha'
arbol.ImprimeArbolDer()
print 'Buscando un valor'
valor = arbol.BuscaNodo(431)
print valor
print
|
# further research:
# - proof of RSA's correctness (Wikipedia)
# - coprime check
# - modular multiplicative inverse
# - primality testing
import math
from Crypto.PublicKey import RSA
from util import modexp, gen_prime
def multiplicative_inverse(a, m):
# totally naive
for i in range(m):
if a * i % m == 1:
return i
raise ValueError("No multiplicative inverse for {} (mod {})".format(a, m))
def fast_multiplicative_inverse(a, m):
_, _, t = egcd(a, m)
# print(t)
return (t + m) % m
def egcd(a, b):
# TODO: only works when a and b are coprime
# needs tests, need to think about this
if b > a:
return egcd(b, a)
if b == 1:
return a, 0, 1
q = a // b
r = a % b
# print("{}, {}".format(a, b))
# one = "{} = {}*{} + {}".format(a, q, b, r)
# print(one)
d, s_next, t_next = egcd(b, r)
t = s_next - t_next * q
s = t_next
two = "{} == {} - {} * {}".format(r, a, q, b)
tre = "{} == {} * {} + {} * {}".format(1, s, a, t, b)
check = s * a + t * b
# print("{} // {}, {}".format(two, tre, check == 1))
# print("")
return d, s, t
def gcd(a, b):
if b > a:
return gcd(b, a)
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return a * b // gcd(a, b)
def totient(p, q):
return lcm(p - 1, q - 1)
def rsa(m: int):
p = gen_prime(1024)
q = gen_prime(1024)
n = p * q
t = totient(p, q)
t_bits = int(math.floor(math.log2(t)))
print("t_bits", t_bits)
e = 3
# TODO: we should loop until this is true
assert gcd(t, e) == 1
d = fast_multiplicative_inverse(e, t)
assert d * e % t == 1
print('t', t)
print('e', e)
print('d', d)
encrypted = modexp(m, n, e)
print('enc', encrypted)
decrypted = modexp(encrypted, n, d)
print('dec', decrypted)
key = RSA.construct((n, e, d))
export_key = key.exportKey()
with open("mykey", "wb") as f:
f.write(export_key)
def main():
rsa(65)
if __name__ == '__main__':
main()
|
from programs.vowels import vowels
def test_hello():
assert vowels("hello")==2
def test_mixed_case():
assert vowels("AAAaaaBBBbbb")==6
def test_empty_string():
assert vowels("")==0
|
width=800
height=600
left_score = 0
right_score = 0
left_y = 40
right_y = 260
ball_x = 390
ball_y = 290
ball_dy = -3
ball_dx = -3
left_key = ""
right_key = ""
mode = "instruction-screen"
def reset_game():
global left_score, right_score, left_y, right_y, ball_x, ball_y, ball_dy, ball_dx
left_score = 0
right_score = 0
left_y = 40
right_y = 260
ball_x = 390
ball_y = 290
ball_dy = -3
ball_dx = -3
mode = "instruction-screen"
def ball_reset():
global ball_x, ball_y
ball_x = 390
ball_y = 290
def setup():
size(width,height)
def draw():
global ball_x, ball_y, ball_dy, ball_dx, left_score, right_score, mode
global left_y, right_y
background(200)
if mode == "instruction-screen":
text ("To start the game press one of the buttons:w,s,i,k",width/3,height/4)
elif mode == "game-over":
if right_score > left_score:
text("right player wins", 300,300)
else:
text("left player wins", 300,300)
elif mode == "game-on":
if left_key == "w":
left_y += -2
elif left_key == "s":
left_y += 2
elif right_key == "i":
right_y += -2
elif right_key == "k":
right_y += 2
ball_x = ball_x + ball_dx
ball_y = ball_y + ball_dy
if ball_y > 580 or ball_y < 0 :
ball_dy = ball_dy * - 1
if ball_x > 780:
left_score += 1
ball_reset()
elif ball_x < 0 :
right_score += 1
ball_reset()
if right_score > 0 or left_score > 0:
mode = "game-over"
if ball_x < 50 and ball_y > left_y and ball_y < (left_y + 80) :
ball_dx = ball_dx * -1
if ball_x > 740 and ball_y > right_y and ball_y < (right_y + 80) :
ball_dx = ball_dx * -1
if mode == "game-on" or mode == "game-over":
text ("PONG", 350 , 40)
text (left_score, 40, 40)
text (right_score, 760, 40)
rect(30,left_y,20,80)
rect(750,right_y,20,80)
rect(ball_x,ball_y,20,20)
def keyReleased():
global left_key, right_key
if key == "w":
left_key = ""
elif key == "s":
left_key = ""
elif key == "i":
right_key = ""
elif key == "k":
right_key == ""
def keyPressed():
global left_y, right_y, mode, left_key, right_key
if mode == "instruction-screen":
mode = "game-on"
if mode == "game-over":
print ("resent game")
mode = "game-on"
reset_game()
if key == "w":
left_key = "w"
elif key == "s":
left_key = "s"
if key == "i":
right_key = "i"
elif key == "k":
right_key = "k"
|
# Fibonacci functions
from decorator import memoized
from math import sqrt
def trivialFib(n):
'''Trivial fibonacci implementation, complexity O(2^n).
Starts getting slow with n>30
'''
if n <= 1:
return n
else:
return trivialFib(n-1) + trivialFib(n-2)
@memoized
def memoizedTrivialFib(n):
'''Memoized trivial fibonacci. Same complexity as trivialFib, but O(1) on
subsequent calls with same parameters
(depending on the lookup in memoized)
'''
return trivialFib(n)
@memoized
def memoizedFib(n):
'''Proper memoized fibonacci. Complexity probably O(n log n) since lots of
similar recursive calls will be memoized
'''
if n <= 1:
return n
else:
return memoizedFib(n-1) + memoizedFib(n-2)
def instaFib(n):
'''Closed form, complexity O(1) but gives approximate results on large
numbers because of float number inaccuracies
'''
phi = (1 + sqrt(5)) / 2
return int((phi**n - (-1/phi)**n) / sqrt(5))
def loopyFib(n):
'''A fibonacci using a loop instead of recursion. Complexity O(n)'''
counter, a, b = 0, 0, 1
while counter < n:
counter, a, b = counter+1, b, a + b
return a
print "The 10th fibonacci number is " + str(trivialFib(10 - 1))
print "The 100th fibonacci number is " + str(memoizedFib(100 - 1))
print "The 1200th fibonacci number is " + str(loopyFib(1200 - 1))
# TODO: a recursive fibonacci that gives correct results for n > 1200 without
# smashing the stack or taking too much time
|
import webbrowser
class Movie():
""" This class will hold movie information.
Attributes:
movie_title: Title of the movie.
movie_storyline: Storyline of the movie.
poster_image: Poster image of the movie.
trailer_youtbe: Youtube link to the trailer of the movie.
"""
def __init__(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
|
class Person():
def __init__(self):
self.money = 100
def getMoney(self):
return self.__money
def setMoney(self,money):
if money <= 0:
print("传入金额有误")
else:
self.__money = money
xiaoming = Person()
xiaoming.__money = -100
xiaoming.setMoney(20)
print(xiaoming.getMoney())
xiaoming.__money
|
c = 'yangzhenya'
h = '123456'
account=(input("请输入账户"))
pwd =(input("请输入密码"))
if account == c and pwd == h:
print('登录成功')
else:
print('密码或者用户名错误')
|
list = [11,22,33,44,55,44,33]
l1 = []
for i in list:
if i not in l1:
l1.append(i)
print(l1)
|
list = []
name_list=[]
count = 0
while True:
if count == 3:
break
#输入
dict = {}
#for i in list:
# name_list.append(i.get("name"))
name = input("请输入你的名字")
age = int(input("请输入你的年龄"))
sex = input("请输入你的性别")
qq = int(input("请输入你的QQ"))
weight = float(input("请输入你的体重"))
#字典赋值
if name not in name_list:
dict["name"] = name
dict["age"] = age
dict["sex"] = sex
dict["qq"] = qq
dict["weight"] = weight
#list = [{}]
#int float str bool list tuple dictionary
list.append(dict)
name_list.append(name)#一定要记录
print(list)
count+=1
else:
print("名字重了")
age_sum =0
#遍历
#lst =[{},{},{}]
for i in list:
age_sum = age_sum+i.get("age")
print(i)
print("年龄的平均值是%0.2f"%(age_sum/3(list)))
|
class Person():
def __init__ (self,money):
self._money = money
def getmoney(self):
return self._money
def setmoney(self,money):
self._money = money
if money <= 0:
print("输入有误")
else:
print("输入正确")
xiaoming = Person()
xiaoming.setmoney(20)
|
class Person():
def sleep(self):
print("睡觉")
def eat(self):
print("吃饭")
def study(self):
print("学习")
def introduce(self):
print("我的名字叫%s体重%d身高%d"%(self.name,self.weight,self.height))
yangzhenya = Person()
yangzhenya.sleep()
yangzhenya.eat()
yangzhenya.study()
yangzhenya.name = "杨振亚"
yangzhenya.weight = 80
yangzhenya.height = 180
yangzhenya.introduce()
|
count = 0
mysum = 0
while count < 100:
print("当前数字:%d"%count)
count+=1
mysum = count + mysum
print("求和是%d"%mysum)
|
import sqlite3
#Conectar a la base de datos
conexion = sqlite3.connect("Database/Personas.sqlite3")
#Seleccionar el cursor para realizar la consulta
consulta = conexion.cursor()
#Codigo sql para insertar datos a la tabla personas
sql = """
insert into personas
values (1,'Carlos Slim', 80, 1.73, 'Masculino', 'Acuario', 'Heterosexual', 'Cafe oscuro', 'Clara', 71000);
insert into personas
values (2,'Maria Aramburuzabala', 56, 1.65, 'Femenino', 'Tauro', 'Heterosexual', 'Verdes', 'Clara', 60000 );
insert into personas
values (3, 'Carlos Vela', 30, 1.77, 'Masculino', 'Piscis', 'Heterosexual', 'Cafe oscuro', 'Morena', 63000);
insert into personas
values (4, 'Deneva Cagigas', 24, 1.62, 'Femenino', 'Aries', 'Heterosexual', 'Cafe claro', 'Clara', 20000);
insert into personas
values (5, 'Erik Canales', 36, 1.70, 'Masculino', 'Escorpio', 'Heterosexual', 'Cafe claro', 'Clara', 30000);
insert into personas
values (6, 'Elizabeth Woolridge', 34, 1.70, 'Femenino', 'Cancer', 'Heterosexual', 'Verdes', 'Blanca', 65000);
insert into personas
values (7, 'Juanpa Zurita', 23, 1.80, 'Masculino', 'Aries', 'Heterosexual', 'Verdes', 'Blanca', 65000);
insert into personas
values (8, 'Mariand Castrejon', 26, 1.58, 'Femenino', 'Piscis', 'Heterosexual', 'Cafe oscuro', 'Clara', 75000);
insert into personas
values (9, 'Luis Arturo Villar', 28, 1.72, 'Masculino', 'Piscis', 'Heterosexual', 'Cafe oscuro', 'Blanca', 85000);
insert into personas
values (10, 'Miranda Ibanez', 25, 1.73, 'Femenino', 'Piscis', 'Heterosexual', 'Negros', 'Blanca', 60000);
insert into personas
values (11, 'Robin Schulz', 32, 1.82, 'Masculino', 'Tauro', 'Heterosexual', 'Cafe claro', 'Clara', 75000);
insert into personas
values (12,'Steven Morrissey', 60, 1.80, 'Masculino', 'Geminis', 'Asexual', 'Azules', 'Blanca', 61000);
insert into personas
values (13, 'Caitlyn Jenner', 70, 1.88, 'Mujer Transexual', 'Escorpio', 'Asexual', 'Cafe oscuro', 'Blanca', 40000);
insert into personas
values (14, 'Bella Thorne', 22, 1.73, 'Femenino', 'Libra', 'Pansexual', 'Cafe claro', 'Blanca', 45000);
insert into personas
values (15, 'Miley Cyrus', 27, 1.65, 'Femenino', 'Sagitario', 'Pansexual', 'Azules', 'Blanca', 100000);
insert into personas
values (16, 'Harry Styles', 26, 1.88, 'Masculino', 'Acuario', 'Heterosexual', 'Verdes', 'Blanca', 60000);
insert into personas
values (17, 'Natalie Portman', 38, 1.60, 'Femenino', 'Geminis', 'Heterosexual', 'Cafe claro', 'Blanca', 80000);
insert into personas
values (18, 'Chris Hemsworth', 36, 1.91, 'Maculino', 'Leo', 'Heterosexual', 'Azules', 'Blanca', 100000);
insert into personas
values (19, 'Zendaya', 23, 1.78, 'Femenino', 'Virgo', 'Heterosexual', 'Cafe oscuro', 'Morena', 200000);
insert into personas
values (20, 'Michael B Jordan', 32, 1.82, 'Masculino', 'Acuario', 'Heterosexual', 'Cafe oscuro', 'Negra', 50000);
insert into personas
values (21, 'Zac Efron', 32, 1.73, 'Masculino', 'Libra', 'Heterosexual', 'Azules', 'Blanca', 60000);
insert into personas
values (22, 'Alicia Vikander', 31, 1.65, 'Femenino', 'Libra', 'Heterosexual', 'Cafe Oscuro', 'Clara', 60000);
insert into personas
values (23, 'Kristen Stewart', 29, 1.66, 'Femenino', 'Aries', 'Homosexual', 'Verdes', 'Blanca', 80000);
insert into personas
values (24, 'Ellen Page', 32, 1.55, 'Femenino', 'Piscis', 'Homosexual', 'Cafe claro', 'Blanca', 30000);
insert into personas
values (25, 'Michelle Rodriguez', 41, 1.65, 'Femenino', 'Cancer', 'Homosexual', 'Cafe oscuro', 'Morena', 40000);
insert into personas
values (26, 'Ricky Martin', 48, 1.88, 'Masculino', 'Capricornio', 'Homosexual', 'Cafe claro', 'Clara', 100000);
insert into personas
values (27, 'Michael Fassbender', 42, 1.83, 'Masculino', 'Aries', 'Heterosexual', 'Azules', 'Blanca', 50000);
insert into personas
values (28, 'Tom Hiddleston', 38, 1.88, 'Masculino', 'Acuario', 'Heterosexual', 'Azules', 'Blanca', 90000);
insert into personas
values (29, 'Tom Holland', 23, 1.70, 'Masculino', 'Geminis', 'Heterosexual', 'Cafe oscuro', 'Blanca', 20000);
insert into personas
values (30, 'Jennifer Lawrence', 29, 1.75, 'Femenino', 'Leo', 'Heterosexual', 'Azules', 'Blanca', 20000);
insert into personas
values (31, 'Luis Miguel', 49, 1.78, 'Masculino', 'Aries', 'Heterosexual', 'Verdes', 'Morena', 20000);
insert into personas
values (32, 'Stefani Angelina', 33, 1.55, 'Femenino', 'Aries', 'Bisexual', 'Verdes', 'Blanca', 20000);
insert into personas
values (33, 'Robert Pattinson', 33, 1.85, 'Masculino', 'Tauro', 'Heterosexual', 'Azules', 'Blanca', 20000);
insert into personas
values (34, 'Alfredo Pacino', 79, 1.70, 'Masculino', 'Tauro', 'Heterosexual', 'Azules', 'Blanca', 20000);
insert into personas
values (35, 'Naomi Campbell', 49, 1.77, 'Femenino', 'Geminis', 'Heterosexual', 'Cafe oscuro', 'Negra', 20000);
insert into personas
values (36, 'Sandra Bullock', 55, 1.72, 'Femenino', 'Leo', 'Heterosexual', 'Cafe oscuro', 'Clara', 20000);
insert into personas
values (37, 'Rupert Grint', 31, 1.73, 'Femenino', 'Virgo', 'Heterosexual', 'Verdes', 'Blanca', 20000);
insert into personas
values (38, 'Felicity Jones', 36, 1.60, 'Femenino', 'Libra', 'Heterosexual', 'Verde', 'Blanca', 80000);
insert into personas
values (39, 'Leonardo Di Caprio', 45, 1.83, 'Masculino', 'Escorpio', 'Heterosexual', 'Azul', 'Blanca', 10000);
insert into personas
values (40, 'Brad Pitt', 56, 1.80, 'Masculino', 'Sagitario', 'Heterosexual', 'Azul', 'Blanca', 60000);
insert into personas
values (41, 'Orlando Bloom', 43, 1.80, 'Masculino', 'Capricornio', 'Heterosexual', 'Cafe oscuro', 'Blanca', 80000);
insert into personas
values (42, 'Shakira', 43, 1.57, 'Femenino', 'Acuario', 'Heterosexual', 'Cafe oscuro', 'Clara', 100000);
insert into personas
values (43, 'Rihanna', 31, 1.73, 'Femenino', 'Piscis', 'Heterosexual', 'Verde', 'Morena', 200000);
"""
#Ejecutar la consulta de insercion de datos
if(consulta.executescript(sql)):
print("Datos agregados con exito")
else:
print("Error al agregar datos")
#Terminando la consulta
consulta.close()
#Guardar cambios en la base de datos
conexion.commit()
#Cerrar conexion a la base de datos
conexion.close()
|
from random import randrange as rnd, choice
from random import randint
import pygame
from pygame.draw import *
import math
pygame.init()
screen_size_x = 1000
screen_size_y = 600
screen_size = (screen_size_x, screen_size_y)
FPS = 50
# Colors
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
LIL = (190, 0, 255)
DARK_GREEN = (0, 128, 0)
GREY = (128, 128, 128)
def quit_condition(pressed_button):
'''
Checks if [X] button was pressed
'''
final = 0
if pressed_button == pygame.QUIT:
final = 1
return final
def draw_road(width_of_pictures, distance_between_roads):
'''
Function draws three main roads according of the size of the left and rigth pictures and distance between roads
'''
width_of_road = (screen_size[0] - 2 * width_of_pictures - distance_between_roads * 2)//3
rect(screen, BLACK,( width_of_pictures, 0, screen_size[0] - 2 * width_of_pictures - 2, screen_size[1]))
for i in range(3):
rect(screen, GREY, (width_of_pictures + i * (width_of_road + distance_between_roads), 0, width_of_road, screen_size[1]))
def show_game_over_table(done):
'''
Shows "Game over" table after the hero was smashed by obstacle
'''
screen.fill(GREEN)
font = pygame.font.SysFont("dejavusansmono", 100)
over_surface = font.render("Game Over", True, WHITE)
textRect = over_surface.get_rect()
textRect.center = (screen_size[0] // 2, screen_size[1] // 2)
screen.blit(over_surface, textRect)
pygame.display.update()
while done != 1:
for event in pygame.event.get():
done = quit_condition(event.type)
class Hero():
def __init__(self, coord = [screen_size[0] // 2, 0]):
'''
Set ball's parameters and thier meanings
'''
self.coord = coord
self.is_alive = True
self.was_kicked = False
self.length = 20 #Full length of hero from top to the bottom
self.number_of_road = 2
def move(self, add_x):
'''
Move the hero to the nearby road
'''
self.coord[0] += add_x
def draw(self):
'''
Draws the hero, attention: self.coord works like coordinatese of the senter of the hero
'''
circle(screen, RED, self.coord, self.length // 2)
class Obstacle():
def __init__(self, speed, number_of_road, width, width_of_pictures, distance_between_roads):
self.is_alive = True
self.speed = speed
self.width_of_road = (screen_size[0] - 2 * (width_of_pictures + distance_between_roads))//3
self.width_of_pictures = width_of_pictures
self.distance_between_roads = distance_between_roads
self.coord = [width_of_pictures + (number_of_road - 1) * (self.width_of_road + self.distance_between_roads), 0]
self.length = self.width_of_road
self.width = width
self.number_of_road = number_of_road
time = 1
def motion(self):
'''
Move obstacles, look if they are done
'''
self.coord[1] += self.speed
if self.coord[1] >= screen_size[1] - self.width:
self.is_alive = False
def draw(self):
'''
Draws obstacles. Attention: coords are the coordinates of the left top corner
'''
rect(screen, MAGENTA, (self.coord[0], self.coord[1], self.length, self.width))
class editor():
def __init__(self, width_of_pictures, distance_between_roads):
'''
Set ball's parameters and thier meanings
'''
self.done = 0
self.step = (screen_size[0] - 2 * width_of_pictures - distance_between_roads * 2)//3 + distance_between_roads
self.hero = Hero(coord = [screen_size[0] // 2, screen_size[1] - 20])
self.time = 0
self.width_of_pictures = width_of_pictures
self.distance_between_roads = distance_between_roads
self.obstacles = []
def user_events(self, events):
'''
Analize events from keyboard, mouse, etc.
'''
self.done = 0
for event in events:
self.done = quit_condition(event.type)
if event.type == pygame.KEYUP:
self.move_hero(event)
return self.done
def move_hero(self, event):
'''
Let hero run to the nearby road, but doesn't give him permission to go out of roads' borders
'''
if (event.key == pygame.K_d or event.key == pygame.K_RIGHT) and (self.hero.number_of_road <= 2):
self.hero.move(self.step)
self.hero.number_of_road += 1
if (event.key == pygame.K_a or event.key == pygame.K_LEFT) and (self.hero.number_of_road >= 2):
self.hero.move(- self.step)
self.hero.number_of_road -= 1
def move_obstacle(self):
'''
Increase y coordinate of obstacles, user see, how they are falling
'''
dead_obstacles = []
for j, obstacle in enumerate(self.obstacles):
obstacle.motion()
if not obstacle.is_alive:#looks if the obstacle is dead, add it to the "Death book" if it's its time to die
dead_obstacles.append(j)
for j in reversed(dead_obstacles):
self.obstacles.pop(j)
def draw(self):
'''
Turns on all object's drawings processes
'''
screen.fill(WHITE)
draw_road(self.width_of_pictures, self.distance_between_roads)
self.hero.draw()
for obstacle in self.obstacles:
obstacle.draw()
def check_bumping(self):
'''
Looks if it's time for the hero to die under the obstacle
'''
for obstacle in self.obstacles:
if self.hero.coord[1] - self.hero.length <= obstacle.coord[1] + obstacle.width:
if self.hero.number_of_road == obstacle.number_of_road:
self.hero.was_kicked = True
return True
def process(self, events):
'''
Manager function for all processes in program. It creates obstacles and control their movement, closes program because of pressed [X] button
starts drawing of all process, looks if the hero was kicked
'''
self.time += 1
if self.time == 20:
self.time = 0
self.obstacles.append( Obstacle(10, randint(1, 3), 10, self.width_of_pictures, self.distance_between_roads) )
self.done = 0
self.done = self.user_events(events)
self.draw()
self.move_obstacle()
if self.check_bumping():
self.done = 2
return self.done
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
edit_events = editor(150, 6)
done = 0
pygame.mixer.music.load('Ramones_Rock_N_Roll_High_School_1.ogg')
pygame.mixer.music.play()
while done == 0:
clock.tick(15)
done = edit_events.process(pygame.event.get())
pygame.display.update()
if done == 2:
show_game_over_table(done)
pygame.quit()
|
from collections import defaultdict
import os
import json
class Graph:
def __init__(self):
self.graph = make_graph_from_json('romania.json')
# # function to add an edge to graph
# def addEdge(self, u, v):
# self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, source, goal):
visited = []
start = source
queue = []
queue.append(source)
while queue:
source = queue.pop(0)
if(source not in visited):
visited.append(source)
if source == goal:
print("The Path from {} to {} is".format(start, goal))
print("-->".join(visited))
break
for neighbours in self.graph[source]:
if neighbours not in visited:
queue.append(neighbours)
def make_graph_from_json(json_file):
# If you get a [FileNotFoundException] than uncomment any of the below two lines. The first line works on my PC but may give an exception on your end
# file_path = os.path.dirname(os.getcwd()) + \
# "\\Searching-Algorithms\\" + json_file
file_path = os.path.dirname(os.getcwd()) + \
"\\" + json_file
with open(file_path) as f:
map_data = defaultdict(list, json.load(f))
return map_data
g = Graph()
g.BFS('Arad', 'Bucharest')
|
class Sort:
def __init__(self, nums):
self.nums = nums
def BubbleSort(self):
n = len(self.nums)
for i in range(n - 1):
for j in range(n-i-1):
if self.nums[j] > self.nums[j+1]:
tmp = self.nums[j]
self.nums[j] = self.nums[j+1]
self.nums[j+1] = tmp
self.show()
def BubbleSort1(self):
n = len(self.nums)
for i in range(n - 1):
swap = False
for j in range(n-i-1):
if self.nums[j] > self.nums[j+1]:
swap = True
tmp = self.nums[j]
self.nums[j] = self.nums[j+1]
self.nums[j+1] = tmp
self.show()
# 此轮无数据交换则停止
if not swap:
break
def InsertSort(self):
for i in range(1, len(self.nums)):
value = self.nums[i]
for j in range(i-1, -1, -1):
if self.nums[j] > value:
self.nums[j + 1] = self.nums[j]
else:
break
# 此处判断j == 0是因为python的for循环中当j为0时,不会再执行j--, 而Java和C++中会在执行到j = -1
if j == 0:
self.nums[j] = value
else:
self.nums[j+1] = value
self.show()
def SelectSort(self):
for i in range(len(self.nums)-1):
m = i
for j in range(i+1, len(self.nums)):
if self.nums[m] > self.nums[j]:
m = j
if i == m:
continue
tmp = self.nums[i]
self.nums[i] = self.nums[m]
self.nums[m] = tmp
self.show()
def show(self):
for i in range(len(self.nums)):
print(self.nums[i], end=" ")
print()
if __name__ == '__main__':
# nums = [6,5,4,3,2,1]
# s = Sort(nums)
# s.BubbleSort()
nums = [2,5,1,4,6,3]
s = Sort(nums)
# s.BubbleSort1()
s.InsertSort()
# s.SelectSort()
|
class Solution:
def simplifyPath(self, path: str) -> str:
data = path.split('/')
stack = []
for d in data:
if d == '' or d == '.':
pass
elif d == '..':
stack.pop() if stack else '#'
else:
stack.append(d)
# str = '-'
# seq = ["a","b","c"]
# str.join(seq) = "a-b-c"
return "/" + "/".join(stack)
if __name__ == "__main__":
solution = Solution()
while True:
str = input()
print(solution.simplifyPath(str))
|
def solution(s):
answer = True
p = 0 # p의 개수
y = 0 # y의 개수
for a in s:
if a == "p" or a == "P":
p += 1
if a == "y" or a == "Y":
y += 1
if p != y:
answer = False
return answer
|
our_list = [1,2,1]
if len(our_list) > 2 and our_list[0] == our_list[-1]:
print(True)
|
#!/usr/bin/python
#
# ANN - Artificial Neural Network
# $Id: ann.py 2 2005-05-05 03:48:18Z $
import math, random
class Neuron:
def __init__(self, inputCount):
# Init Obj Attrs
self.inputs = inputCount
self.weights = []
self.threshold = random.random()
self.error = 0
self.actv = 0
# Prepop neuron w/ random weights
for i in range(self.inputs):
self.weights.append(random.random())
class Network:
def __init__(self, inputCount, outputCount, learningRate = 0.02):
# Seed Random
random.seed()
# Init Obj Attrs
self.inputCount = inputCount
self.outputCount = outputCount
self.learningRate = learningRate
# Init network neurons
self.inputLayer = []
self.hiddenLayer = []
self.outputLayer = []
for i in range(self.inputCount):
self.inputLayer.append( Neuron(self.inputCount) )
self.hiddenLayer.append( Neuron(self.inputCount) )
for i in range(self.outputCount):
self.outputLayer.append( Neuron(self.inputCount) )
def run(self, testPattern, desiredOut = None):
output = []
# Execute feed forward algorithm
self.feedForward(testPattern)
# Train if desired output is present
if desiredOut is not None:
self.backProp(testPattern, desiredOut)
# Prepare returned array
for neuron in self.outputLayer:
output.append(neuron.a)
return output
def feedForward(self, testPattern):
# Process Input Layer
for neuron in self.inputLayer:
sum = 0
for i in range(len(testPattern)):
sum += neuron.weights[i] * testPattern[i]
neuron.a = sigmoid(sum - neuron.threshold)
# Process Hidden Layer
for neuron in self.hiddenLayer:
sum = 0
for i in range(len(self.inputLayer)):
sum += neuron.weights[i] * self.inputLayer[i].a
neuron.a = sigmoid(sum - neuron.threshold)
# Process Output Layer
for neuron in self.outputLayer:
sum = 0
for i in range(len(self.hiddenLayer)):
sum += neuron.weights[i] * self.hiddenLayer[i].a
neuron.a = sigmoid(sum - neuron.threshold)
def backProp(self, testPattern, desiredOut):
# Calc layer errors
self.__calcOutputLayerErrors(desiredOut)
self.__calcHiddenLayerErrors()
self.__calcInputLayerErrors()
# Adjust weights and thresholds
self.__trainOutputLayer()
self.__trainHiddenLayer()
self.__trainInputLayer(testPattern)
def __calcOutputLayerErrors(self, desiredOut):
for i in range(len(self.outputLayer)):
a = self.outputLayer[i].a
self.outputLayer[i].error = (desiredOut[i] - a) * a * (1 - a)
def __calcHiddenLayerErrors(self):
for i in range(len(self.hiddenLayer)):
sum = 0
for neuron in self.outputLayer:
sum += neuron.error * neuron.weights[i]
self.hiddenLayer[i].error = sum
def __calcInputLayerErrors(self):
for i in range(len(self.inputLayer)):
sum = 0
for neuron in self.hiddenLayer:
sum += neuron.error * neuron.weights[i]
self.inputLayer[i].error = sum
def __trainOutputLayer(self):
for i in range(len(self.outputLayer)):
for j in range(len(self.hiddenLayer)):
# Calc and assign new weight
weight = self.outputLayer[i].weights[j]
weight -= self.learningRate * self.hiddenLayer[j].a
self.outputLayer[i].weights[j] = weight
# Calc and assign new threshold
threshold = self.outputLayer[i].threshold
threshold -= self.learningRate * self.outputLayer[i].error
self.outputLayer[i].threshold = threshold
def __trainHiddenLayer(self):
for i in range(len(self.hiddenLayer)):
for j in range(len(self.inputLayer)):
# Calc and assign new weight
weight = self.hiddenLayer[i].weights[j]
weight += self.learningRate * self.inputLayer[j].a
self.hiddenLayer[i].weights[j] = weight
# Calc and assign new threshold
threshold = self.hiddenLayer[i].threshold
threshold -= self.learningRate * self.hiddenLayer[i].error
self.hiddenLayer[i].threshold = threshold
def __trainInputLayer(self, testPattern):
for i in range(len(self.inputLayer)):
for j in range(len(testPattern)):
# Calc and assign new weight
weight = self.inputLayer[i].weights[j]
weight += self.learningRate * testPattern[j]
self.inputLayer[i].weights[j] = weight
# Calc and assign new threshold
threshold = self.inputLayer[i].threshold
threshold -= self.learningRate * self.inputLayer[i].error
self.inputLayer[i].threshold = threshold
def sigmoid(x):
return math.tanh(x)
|
"""
This is a sample program to show how to draw using the Python programming
language and the Arcade library.
Multi-line comments are surrounded by three double-quote marks.
Single-line comments start with a hash/pound sign. #
"""
# This is a single-line comment.
# Import the "arcade" library
import arcade
# Open up a window.
# From the "arcade" library, use a function called "open_window"
# Set the dimensions (width and height)
# Set the window title to "Drawing Example"
arcade.open_window(600, 600, "Drawing Example")
# Set the background color
arcade.set_background_color((219, 65, 15))
# Get ready to draw
arcade.start_render()
# (The drawing code will go here.)
# Finish drawing
arcade.finish_render()
# Keep the window up until someone closes it.
arcade.run()
|
#!/usr/bin/python3
import sys
import demo.demo2
import demo.demo3
# 输出语句
print("hello world!")
print(sys.version)
demo2 = demo.demo2
demo2.func1()
demo.demo3.demo3().say()
demo.demo3.demo4().say()
demo.demo3.demo4().say1()
# 元数据类型 相当于不可该的list
tup1 = ('g', 'g')
print(tup1[1:])
# fuck 代码块和块之间要间隔两行
# 函数
def func(msg):
print(msg)
# 函数调用
func("hello world")
num = 100
def func2():
num = 200
print(num)
func2()
print(num) # 没有被修改
def func3():
global num
num = 300
print(num)
func3()
print(num) # 使用global修改了全局变量
# 可变参数列表 不建议使用
def func4(*args):
result = ''
for x in args:
result += x
return result
|
"""
Script file: parse.py
Created on: September 8, 2020
Last modified on: September 8, 2020
Comments:
Main script to analyze the input JSON file and generate two files.
- watchers.json
- managers.json
Each should contain a dictionary with the manager/watcher in the key, and a list of projects in the value.
The projects in the list should be ordered by priority - from most priority to least priority.
Remember here that a lower number means a higher priority.
"""
import os
import json
def create_dir(path):
"""
create new folder
if the folder is already existing, this means the data is ready
in this case skip it
:param path: directory path
:return: none
"""
if not os.path.exists(path):
os.makedirs(path)
def read_raw_data(filename):
"""
Read raw data from a sample file
:param filename: path to the sample data file
:return: output data
"""
with open(filename) as json_file:
data = json.load(json_file)
return data
def save_json(data, filename):
"""
Write json data to a given file.
:param data: json data
:param filename: path to save file
:return: none
"""
# check the output path
dir_path = os.path.dirname(filename)
create_dir(dir_path)
# write json to a file
with open(filename, 'w') as outfile:
json.dump(data, outfile)
def update_data(output, project, key='managers'):
"""
Update output dictionary
:param output: dictionary
:param project: dictionary
:param key: key name {'managers', 'watchers'}
:return: none
"""
for i, name in enumerate(project[key]):
temp = {
'name': project['name'],
'priority': project['priority']
}
# extend data
if name in output:
output[name].append(temp)
else:
output[name] = [temp]
# sort data
output[name] = sorted(output[name], key=lambda k: k['priority'], reverse=False)
def remove_priority(data):
"""
Remove priority key in the output dictionary
:param data: dictionary
:return: none
"""
for key in data.keys():
temp = []
for item in data[key]:
temp.append(item['name'])
data[key] = temp
def parse_data(data):
"""
Parse the json data to get the list of managers, watchers
Each element is a dictionary format with project names sorted by priority
:param data: list of dictionaries
:return: none
"""
# initialize dictionaries
watchers = {}
managers = {}
# analyze the data, each project is a dictionary
for project in data:
update_data(managers, project, 'managers')
update_data(watchers, project, 'watchers')
# generate output dictionary
remove_priority(managers)
remove_priority(watchers)
# save data to json files
save_json(managers, 'result/managers.json')
save_json(watchers, 'result/watchers.json')
def run(filename='source/sample.json'):
"""
Main script to run
:param filename: input JSON filename
:return: none
"""
json_data = read_raw_data(filename)
parse_data(json_data)
if __name__ == '__main__':
run('source/source_file_2.json')
|
import sqlite3
searchInput = input("What would you like to search? \n")
connection = sqlite3.connect("sms.db")
cursor = connection.cursor()
cursor.execute("select message.text, handle.id "
"from message, handle "
"where message.text like '%" + searchInput + "%' and handle.ROWID = message.handle_id "
"order by date desc;")
results = cursor.fetchall()
counter = 0;
for r in results:
print(str(counter) + ". " + str(r))
counter += 1
cursor.close()
connection.close()
print('\n There were ' + str(len(results)) + ' results for "' + searchInput + '".\n')
# handleId = [lis[0] for lis in results]
messageText = [lis[0] for lis in results]
contactNum = [lis[1] for lis in results]
chooseResult = input("Which result number would you like to display? \n")
print(results[int(chooseResult)])
|
def bisection(f,a,b,tol):
if f(a)*f(b)>0:
print("Bisection method fails!")
return None
i = 0
while True:
c=(a+b)/2
i+=1
if f(a)*f(c)>0:
a=c
elif f(a)*f(c)<0:
b=c
elif f(c)==0:
return c
else:
print("Bisection method fails!")
return None
if abs(b-a)<tol:
return c,i
return (a+b)/2
if __name__=="__main__":
f=lambda x: x**2-x-1
approx_phi = bisection(f,1,2,0.001)
print("Solution for x^2-x-1 = 0:\nx = {:5f}\tIterations: {}".format(approx_phi[0],approx_phi[1]))
f=lambda x: x**3-x-1
sol = bisection(f,1,2,0.001)
print("Solution for x^3-x-1 = 0:\nx = {:5f}\tIterations: {}".format(sol[0],sol[1]))
|
import operator
# Define dictionary with operators
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
class PrefixOperation:
def __init__(self, expression):
self.expression = str(expression)
self.rev_elems = None
self.parse_expression()
def parse_expression(self):
"""Initialise object attribute 'rev_elems' by taking
all elements in the expression in reverse order."""
# Add a space before and after each operator to make sure elements are split correctly
expression = "".join([" {} ".format(el) if not el.isdigit() else el for el in self.expression])
# Split and reverse elements
self.rev_elems = expression.split()[::-1]
def evaluate_expression(self):
"""Compute the prefix operations by evaluating the expression in reverse order."""
# Create an empty list to store operands
operands = []
# Loop through the reversed expression elements
for element in self.rev_elems:
# Store element in the operands list if it is a digit
if element.isdigit():
operands.append(float(element))
else:
# Get operands for the operation and remove them from the list
try:
num1 = operands.pop(-1)
num2 = operands.pop(-1)
except IndexError:
return
# Compute the operation and append the result to the operands list
try:
operands.append(ops[element](num1, num2))
except (KeyError, ZeroDivisionError):
return
if len(operands) == 1:
return operands.pop()
else:
return
class InfixOperation:
def __init__(self, expression):
self.expression = str(expression)
self.elements = None
self.parse_expression()
def parse_expression(self):
"""Initialise object attribute 'elements'."""
# Add a space before and after each operator to make sure elements are split correctly
expression = "".join([" {} ".format(el) if not el.isdigit() else el for el in self.expression])
# Split and reverse elements
self.elements = expression.split()
def evaluate_expression(self):
"""Compute the infix operations."""
# Create an empty list to store operands and operators
terms = []
# Create a copy of the elements
elements = self.elements[:]
# Loop through all elements in the expression
while elements:
# Remove first element from list
el = elements.pop(0)
# Store operands and digits
if el.isdigit() or el in ops:
terms.append(el)
# When reaching a close parenthesis compute one operation
elif el == ")":
try:
num2 = float(terms.pop())
op = terms.pop()
num1 = float(terms.pop())
except (IndexError, ValueError):
return
# Compute the operation and append the result to the terms list
try:
terms.append(ops[op](num1, num2))
except (KeyError, ZeroDivisionError):
return
# Perform any outstanding operation
while len(terms) > 1:
try:
num2 = float(terms.pop())
op = terms.pop()
num1 = float(terms.pop())
except (IndexError, ValueError):
return
try:
terms.append(ops[op](num1, num2))
except (KeyError, ZeroDivisionError):
return
return terms.pop()
|
import re
mobile=input("enter the mobile no:")
x='^91[0-9]{10}'
matcher=re.fullmatch(x,mobile)
if(matcher!=None):
print("valid")
else:
print("invalid")
|
# 1 Find the probabilities of the following rocks rounded to the nearest hundredth:
rocks = {
"sedimentary": 58,
"metamorphic": 213,
"igneous" : 522,
}
# Expected ouput:
# There is 0.07 probability of the sedimentary rock
# There is 0.27 probability of the metamorphic rock
# There is 0.66 probability of the igneous rock
[ print(f" There is {round( value / sum(rocks.values() ), 2)} probability of the {key} rock ")
for key, value in rocks.items() ]
# 2 X is a discrete random variable. The table below defines a probability distribution for X. What is the expected value of X?
x = [10, 20, 30, 40]
p = [.2, .3, .15, .35]
e = 0
for x, p in zip(x, p):
print(f"{x} * {p} = {x*p} + ")
e += x*p
print(f"Expected Value: {e}")
# 3 Find standard deviation given mean and pdf
from math import sqrt
pdf = {
200 : .999,
-99800: .001,
}
e = 100
variance = 0
for rv, p in pdf.items():
variance += (rv - e)**2 * p
print(sqrt(variance))
# 4 Calculate & Plot Normal Cumulative Distribution Function
# print(norm.__doc__)
# https: //docs.scipy.org/doc/scipy/reference/tutorial/stats.html
# https: //docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.norm.html
# https: //docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.html#scipy.stats.rv_continuous
# https: //docs.scipy.org/doc/scipy/reference/generated/scipy.stats.truncnorm.html
from scipy.stats import truncnorm, norm
import matplotlib.pyplot as plt
def normalCdf(lower=truncnorm.a, upper=truncnorm.b, mean=0, sd=1):
X = truncnorm( (lower - mean) / sd,
(upper - mean) / sd,
loc=mean, scale=sd )
N = norm(loc=mean, scale=sd)
truncdf = N.cdf(upper) - N.cdf(lower)
print(truncdf)
fig, ax = plt.subplots(2, sharex=True)
ax[0].hist(N.rvs(1000000), normed=True)
ax[1].hist(X.rvs(1000000), normed=True)
xmin, xmax = plt.xlim()
ymin, ymax = plt.ylim()
plt.annotate(f"CDF= {truncdf}", xy=(upper if xmin < upper < xmax else lower, .25*ymax), # head
xytext = (upper + (xmax - xmin)/10 if xmin < upper < xmax else lower - (xmax - xmin)/4, .75*ymax), # tail
arrowprops = dict(facecolor="red", shrink=0.05, connectionstyle="angle3") )
plt.show()
normalCdf(15, 99999, 0, 12.728)
# 5 Calculate z-score
def z_score(x, mean, sd):
print(f"Given a normal distribution with:\n\
mean = {mean}, \
standard deviation = {sd}\n\
A value of x = {x} would have a z-score = {( x - mean ) / sd}")
z_score(32.2, 20.5, 3.9)
|
MIN_LENGTH = 100
APPROPRIATE_SYMBOLS = ('0', '1')
all_filtered_text = ''
triads = {}
capital = 1000
def filter_text(text):
filtered_text = [character for character in text if character in APPROPRIATE_SYMBOLS]
return ''.join(filtered_text)
def prediction(random_text):
predicted_string = random_text[:3]
test_length = len(random_text)
for j in range(test_length - 3):
last_three_chars = random_text[j:3 + j]
if triads[last_three_chars][0] >= triads[last_three_chars][1]:
appended_char = '0'
else:
appended_char = '1'
predicted_string += appended_char
return predicted_string
def prediction_probability(cut_random_text, cut_predicted_string):
number_of_same_chars = 0
cut_test_length = len(cut_random_text)
for j in range(cut_test_length):
if cut_random_text[j] == cut_predicted_string[j]:
number_of_same_chars += 1
return [number_of_same_chars, cut_test_length]
def update_triads(text):
for i in range(len(text) - 3):
triad_key = text[i:i + 3]
after_triad = text[i + 3]
if after_triad == '0':
actual_triad = {triad_key: [triads.get(triad_key, [0, 0])[0] + 1, triads.get(triad_key, [0, 0])[1]]}
else:
actual_triad = {triad_key: [triads.get(triad_key, [0, 0])[0], triads.get(triad_key, [0, 0])[1] + 1]}
triads.update(actual_triad)
print('\nPlease give AI some data to learn...\nThe current data length is 0, 100 symbols left')
while True:
user_input = input('Print a random string containing 0 or 1:\n\n')
all_filtered_text += filter_text(user_input)
all_text_length = len(all_filtered_text)
if all_text_length >= MIN_LENGTH:
print(f'\nFinal data string:\n{all_filtered_text}\n')
break
else:
left_symbols = MIN_LENGTH - all_text_length
print(f'Current data length is {all_text_length}, {left_symbols}')
update_triads(all_filtered_text)
sorted_triads_keys = list(triads.keys())
sorted_triads_keys.sort()
# for triad_key in sorted_triads_keys:
# print(f'{triad_key}: {triads[triad_key][0]},{triads[triad_key][1]}')
print('You have $1000. Every time the system successfully predicts your next press, you lose $1. '
'Otherwise, you earn $1. Print "enough" to leave the game. Let\'s go!')
while True:
print('\nPrint a random string containing 0 or 1:')
random_string = input()
if random_string == 'enough':
break
filtered_random_string = filter_text(random_string)
if len(filtered_random_string) > 3:
predicted_text = prediction(filtered_random_string)
print("prediction:")
print(predicted_text)
random_string_probability = prediction_probability(filtered_random_string[3:], predicted_text[3:])
random_string_probability_percent = round(100 * random_string_probability[0] / random_string_probability[1], 2)
print(f'\nComputer guessed right {random_string_probability[0]} out of {random_string_probability[1]} symbols '
f'({random_string_probability_percent} %)')
capital += random_string_probability[1] - 2 * random_string_probability[0]
print(f'Your capital is now ${capital}')
update_triads(filtered_random_string)
print('Game over!')
|
# Karatsuba algorithm used to multiply two integers
# together that are of equal and even length
# Implemented in Python by: Henry Dunham
import split_int_in_half as half_int
import recursive_product
import int_length
def karatsuba(int1, int2):
# Confirm length of two integers is the same
if len(str(int1)) != len(str(int2)):
return ("Length of integers must be the same!")
# Base Case: length of integers is 1
elif int_length.numLength(int1) and int_length.numLength(int2):
return int1 * int2
# Recursive Case
else:
a, b = half_int.inHalf(int1)
c, d = half_int.inHalf(int2)
p = a + b
q = c + d
ac = recursive_product.compute_product(a, c)
bd = recursive_product.compute_product(b, d)
pq = recursive_product.compute_product(p, q)
adbc = pq - ac - bd
n = len(str(int1))
result = int(((10 ** n) * ac) + ((10 ** (n / 2)) * adbc) + bd)
print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)
print("p = ", p)
print("q = ", q)
print("ac = ", ac)
print("bd = ", bd)
print("pq = ", pq)
print("adbc = ", adbc)
print("n = ", n)
print("Karatsuba says the answer is?! ")
return result
# Test Cases
print(karatsuba(123, 5678))
print(karatsuba(1, 5))
print(karatsuba(1234, 5678))
|
import turtle
turtle.shape('turtle')
def prm (n, l):
turtle.forward(l)
turtle.left(180-180//n)
return
n = 11
l = 100
turtle.left(180)
for x in range(n):
prm(n, l)
|
import turtle
turtle.shape('turtle')
def okr(l1:int, l2:int):
for _ in range(180):
turtle.forward(l1)
turtle.right(1)
for _ in range(180):
turtle.forward(l2)
turtle.right(1)
return
l1 = 0.5
l2 = 0.2
turtle.left(90)
for x in range(3):
okr(l1, l2)
|
# other-recommendations.py
# Avoid trailing whitespace anywhere because it's usually invisible, it can be
# confusing
# Always surround these binary operators with a single space on either side:
# assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=,
# <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
# If operators with different priorities are used, consider adding whitespace
# around the operators with the lowest priority(ies). Always one space.
# Correct:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# Wrong:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
# Function annoations. Always have spaces around -> if present
# Correct:
def munge(input: AnyStr): ...
def munge() -> PostInt: ...
# Wrong:
def munge(input:AnyStr): ...
def munge()->PostInt: ...
# Don't use spaces around the = sign when used to indicate a keyword argument,
# or when used to indicate a default value for an unannotated function parameter:
# Correct:
def complex(real, imag=0.0):
return magic(r=real, i=imag)
# Wrong:
def complex(real, imag = 0.0):
return magic(r = real, i = imag)
# When combining an argument annotation with a default value, however, do use
# spaces around the = sign:
# Correct:
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...
# Wrong:
def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000):...
# Compound statements (multiple statements on the same line) are generally
# discouraged:
# Correct:
if foo == 'blah':
do_blah_thing()
do_one()
do_two()
do_three()
# Rather Not:
# Wrong:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()
# While sometimes it's okay to put an if/for/while with a small body on the same
# line, never do this for multi-clause statements. Also avoid folding such long
# lines!
# Rather Not:
# Wrong:
if foo == 'blah': do_blah_thing()
for x in lst: total += x
while t < 10: t = delay()
# Definitely note
# Wrong:
if foo == 'blah': do_blah_thing()
else: do_not_blah_thing()
try: something()
finally: cleanup()
do_one(); do_two(); do_three(long, argument,
list, like, this)
if foo == 'blah': one(); two(); three()
|
class Vertex(object):
def __init__(self, vertex_id):
"""
Initialize a vertex and its neighbors dictionary.
"""
self.id = vertex_id
self.neighbors_dict = {} # id -> (obj, weight)
def add_neighbor(self, vertex_obj, weight):
"""
Add a neighbor by storing it in the neighbors dictionary.
"""
if vertex_obj.get_id() in self.neighbors_dict.keys():
return # it's already a neighbor
self.neighbors_dict[vertex_obj.get_id()] = (vertex_obj, weight)
def get_neighbors(self):
"""Return the neighbors of this vertex."""
return [neighbor for (neighbor, weight) in self.neighbors_dict.values()]
def get_neighbors_with_weights(self):
"""Return the neighbors of this vertex."""
return list(self.neighbors_dict.values())
def get_id(self):
"""Return the id of this vertex."""
return self.id
def __str__(self):
"""Output the list of neighbors of this vertex."""
neighbor_ids = [neighbor.get_id() for neighbor in self.get_neighbors()]
return f'{self.id} adjacent to {neighbor_ids}'
def __repr__(self):
"""Output the list of neighbors of this vertex."""
neighbor_ids = [neighbor.get_id() for neighbor in self.get_neighbors()]
return f'{self.id} adjacent to {neighbor_ids}'
class Graph:
def __init__(self, is_directed=True):
"""
Initialize a graph object with an empty vertex dictionary.
"""
self.vertex_dict = {}
self.is_directed = is_directed
def add_vertex(self, vertex_id):
"""
Add a new vertex object to the graph with the given key and return the vertex.
"""
if vertex_id in self.vertex_dict.keys():
return False # it's already there
vertex_obj = Vertex(vertex_id)
self.vertex_dict[vertex_id] = vertex_obj
return True
def get_vertex(self, vertex_id):
"""Return the vertex if it exists."""
if vertex_id not in self.vertex_dict.keys():
return None
vertex_obj = self.vertex_dict[vertex_id]
return vertex_obj
def add_edge(self, vertex_id1, vertex_id2, weight):
"""
Add an edge from vertex with id `vertex_id1` to vertex with id `vertex_id2`.
"""
all_ids = self.vertex_dict.keys()
if vertex_id1 not in all_ids or vertex_id2 not in all_ids:
return False
vertex_obj1 = self.get_vertex(vertex_id1)
vertex_obj2 = self.get_vertex(vertex_id2)
vertex_obj1.add_neighbor(vertex_obj2, weight)
if not self.is_directed:
vertex_obj2.add_neighbor(vertex_obj1, weight)
def get_vertices(self):
"""Return all the vertices in the graph"""
return list(self.vertex_dict.values())
def union(self, parent_map, vertex_id1, vertex_id2):
"""Combine vertex_id1 and vertex_id2 into the same group."""
vertex1_root = self.find(parent_map, vertex_id1)
vertex2_root = self.find(parent_map, vertex_id2)
parent_map[vertex1_root] = vertex2_root
def find(self, parent_map, vertex_id):
"""Get the root (or, group label) for vertex_id."""
if(parent_map[vertex_id] == vertex_id):
return vertex_id
return self.find(parent_map, parent_map[vertex_id])
|
'''
Chef and Icecream
Problem Code: CHFICRM
'''
from sys import stdin
input = stdin.readline
def process(data):
ice_cream = 5
chef_balance = {5:0,10:0,15:0}
change = 0
if data[0] != ice_cream:
return 'NO'
for i in data:
# print()
# print()
if i == 5:
chef_balance[5] += 1
else:
change = i - ice_cream
if chef_balance[change] < 1:
while change:
if chef_balance[5] !=0 and change//5 <= chef_balance[5] :
chef_balance[5] -= 1
change -= 5
continue
return 'NO'
chef_balance[i] += 1
else:
chef_balance[change] -= 1
chef_balance[i] += 1
return 'YES'
def main():
for test in range(int(input())) :
size_of_customers = int(input())
data = list(map(int,input().split()))
print(process(data))
if __name__ == "__main__":
main()
|
def half_diamond(size, row):
temp = size
# hello this is a comment
while temp > 1:
if temp > row:
print(' ', end = ' ')
temp -= 1
else:
print(temp, end = ' ')
temp -= 1
while temp <= size:
if temp > row:
print(' ', end = ' ')
temp += 1
else:
print(temp, end = ' ')
temp += 1
def diamond(size):
row = 1
while row < size:
half_diamond(size, row)
row += 1
print('')
while row > 0:
half_diamond(size, row)
row -= 1
if row != 0:
print('')
print(diamond(5))
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/21 20:21
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :简单算法
"""
"""
算法1:把字符串'a,b,c,d,e,f,g,h,i,j,k,l',变成一个字符列表,不需要逗号
算法分析:通过遍历,我们取出每一个字符,然后不要逗号,存放到列表
"""
s = 'a,b,c,d,e,f,g,h,i,j,k,l'
# 通过遍历,取出每一个字符
slist = []
for ss in s:
# 如果是逗号就不要它
if ss == ',':
pass
else:
slist.append(ss)
print(slist)
# 沿着某一个特定的字符,把一个字符串切割成子字符串列表,这个特定字符会被抛弃
print(s.split(','))
"""
算法2:'Will is young, Will is handsome'
需要把里面的Will换成Roy
算法解析:直接把Will全部替换为Roy
"""
# 替换
s = 'Will is young, Will is handsome, Will is '
s1 = s.replace('Will', 'Roy', 1)
print(s1)
# 替换第二个
s1 = s.replace('Will', 'Roy', 2)
s1 = s1.replace('Roy', 'Will', 1)
print(s1)
# 替换最后一个
s1 = s[::-1]
s1 = s1.replace('lliW','iefut',1)
s1 = s1[::-1]
print(s1)
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/23 21:49
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :递归快排
"""
import time
def quick_sort(height, left, right):
"""
我们每一轮,选取最后一个元素为基准,把元素分成左右两部分,左边都比
基准小,右边都比基准大。进行如下操作:从左往右找比基准大的,交换到
h位置, h往左移动一位;再从h位置从右往左找比基准小的,交换到之前l
的位置,l往右移动一位。反复执行前面的操作,直到l=h,因为这个时候说
明整个列表的元素都和基准进行了比较。也就达到了基准前面的元素都比基
准小,基准后面的元素都比基准大。当整个递归执行到列表只有一个元素的
时候,就可以保证整个列表是有序的。
:param height: 待排序的列表
:param left: 待排序元素的左下标
:param right: 待排序元素的右下标
:return:
"""
# 最开始判断出口
if left >= right:
return
# 最开始的时候,l和h分别指向待排序元素的开始和末尾
l = left
h = right
# 取最后一个元素为基准
base = height[h]
# 只要l小于h,就说明还没找完,需要继续找
while l < h:
# 从左往右找比基准大的
while l < h:
# 从左往右找比基准大的,交换到h位置,h往左移动一位;
if height[l] > base:
height[l], height[h] = height[h], height[l]
h -= 1
break
else:
# 如果没找到就继续往右找
l = l + 1
# 从h位置从右往左找比基准小的
while l < h:
# 从左往右找比基准大的,交换到h位置,h往左移动一位;
if height[h] < base:
height[l], height[h] = height[h], height[l]
l += 1
break
else:
# 如果没找到就继续往左找
h = h - 1
# # 左边出口
# if left >= l - 1:
# pass
# else:
# # 递归实现左边的排序
quick_sort(height, left, l - 1)
# # 右边出口
# if right <= h + 1:
# pass
# else:
# # 递归实现右边的排序
quick_sort(height, h + 1, right)
height = [144, 166, 187, 156, 144, 155, 177, 167, 153, 188, 169,144]
quick_sort(height, 0, len(height) - 1)
print(height)
# t1 = time.time()
# time.sleep(1)
# t2 = time.time()
# print(t2-t1)
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/16 20:17
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :算术运算
"""
################ 算术运算 ##################
# # 四舍五入/取整
# """
# 精度:计算机在算术运算的时候,小数是不能全部保存的,它只会保存双精度的位数
# 买一个水果:2元3个,假设买100W个
# """
# # 先算1个多少钱
# price = int((2/3) * 100) / 100
# print(price * 1000000)
#
# price = round(2/3,2)
# print(price * 1000000)
#
# # 运算符的优先级
# z = 2 + 2 ** 2 * 3 ** 3
# print(z)
# # 先算幂运算
# z = 2 + 4 * 27
# # 再算乘法
# z = 2 + 108
# # 最后算加法
# z = 110
################ 字符串算术运算 ##################
# 拼接
s1 = 'ab'
s2 = 'cd'
print(s1 + s2)
# 重复拼接
s1 = "ab"
print(s1 * 3)
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/16 20:17
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :比较运算
"""
################ 数值的比较运算 ##################
# ==,!=,>,<,>=,<=
# 和java的区别:Python里面可以连写
# x = 1
# y = 2
# z = 2
# print(x < y < z)
################ 字符串的比较运算 #################
# ascii码的比较,按位比较
# 只要一位不一样就可以确定大小,后面的位数就不比了
s1 = "abc"
s2 = "abc"
print(s1 > s2)
# 两个字符串必须一模一样
print(s1 == s2)
print(s1 != s2)
# 包含:主字符串必须有一个连续的子串和子字符串一模一样,相等也包含
print(s1.__contains__(s2))
|
# -*- coding: utf-8 -*-
"""
@Time : 2020/10/14 21:17
@Auth : Mr. William 1052949192
@Company :特斯汀学院 @testingedu.com.cn
@Function :数据类型的要点
"""
# 转义:\ (把有特殊含义的符号转成普通符号,使它失去特殊含义)
# 你要在字符串里面出现单引号和双引号怎么办?
s = "'''''''''''''"
print(s)
s = "\""
print(s)
# 转义字符:(把无特殊含义的符号转成有特殊含义的符号,使它具备符合规则的特殊含义)
print("a\ta\na")
# 类型的互斥:数字和其他类型的互斥,NoneType和所有类型互斥
i = 1
f = 1.1
s = 'aa'
# 布尔类型的本质是数字:True=1, False=0
b = True
n = None
print(i + f)
print(i + b)
# print(s+n)
# 强转:所有类型都可以强转为字符,字符串转其他类型,必须要符合其他类型的写法
print(str(i) + s)
s = '1'
print(i + float(s))
print(str(None) + s)
|
x = 5
y = "7"
# Write a print statement that combines x + y into the integer value 12
print(x + y)
#int("7") + 5 # integer 12
# Write a print statement that combines x + y into the string value 57
print(printx + y)
#"2" + str(4) # string 24
#str(5) + "7" # string 57
|
class Add:
@staticmethod
def __call__(x, y):
return x.data+y.data
@staticmethod
def vjp(dz, x, y):
x.set_grad(dz)
y.set_grad(dz)
def __str__(self):
return "Add"
class Subtract:
@staticmethod
def __call__(x, y):
return x.data-y.data
@staticmethod
def vjp(dz, x, y):
x.set_grad(dz)
y.set_grad(-dz)
def __str__(self):
return "Subtract"
class Mult:
@staticmethod
def __call__(x, y):
return x.data*y.data
@staticmethod
def vjp(dz, x, y):
x.set_grad(dz*y)
y.set_grad(dz*x)
def __str__(self):
return "Mult"
class ReLU:
@staticmethod
def __call__(x):
return max(x.data,0.)
@staticmethod
def vjp(dz, x, y):
x.set_grad(dz*(x>0))
y.set_grad(dz*(y>0))
def __str__(self):
return "ReLU"
class MatMul:
@staticmethod
def __call__(W,x):
return [email protected]
@staticmethod
def vjp(dz, W, x):
x.set_grad([email protected]())
W.set_grad([email protected]())
def __str__(self):
return "MatMul"
add = Add()
subtract = Subtract()
mult = Mult()
relu = ReLU()
matmul = MatMul()
|
# Author Loisa Kitakaya
# This is a program that will translate text from one language to another.
# The program is written in python3.
# It will use the following modules/libraries: IBM Watson™ Language Translator | Tkinter
# The program will work mainly with english to french and vice versa.
import os
import json
import tkinter
from tkinter import *
import tkinter.messagebox
import tkinter.simpledialog
import tkinter.filedialog as fdialog
import tkinter.scrolledtext as scrolltextbox
from watson_developer_cloud import LanguageTranslatorV3
# token-based Identity and Access Management (IAM) authentication
language_translator = LanguageTranslatorV3(
version='2018-05-01',
iam_apikey='-6-QG-NTBvcMI9RMbKPCHaFpXg4lKbQ9pQfq-BNSAprq',
url='https://gateway-wdc.watsonplatform.net/language-translator/api'
)
# creating a class to define window (GUI) properties
class GUI_Window:
# creating constructor to initialize window (GUI) creation
def __init__(self, master):
# naming the window
master.title("Text Translater")
# setting the size of the window
# master.geometry("800x500")
# creating the menu bar
menu_bar = Menu(master)
master.config(menu = menu_bar)
# creating sub-menu "Options"
sub_menu_1 = Menu(menu_bar)
menu_bar.add_cascade(label = "Options", menu = sub_menu_1)
# creating sub-menu "Options" commands'
sub_menu_1.add_command(label = "Edit file", command = self.open_file)
sub_menu_1.add_command(label = "Quit app", command = master.destroy)
# creating sub-menu "About"
sub_menu_2 = Menu(menu_bar)
menu_bar.add_cascade(label = "info", menu = sub_menu_2)
# creating sub-menu "About" commands'
sub_menu_2.add_command(label = "About", command = self.about)
# creating the main frame frame
frame_1 = Frame(master)
# displaying the frame
frame_1.pack(fill = "both", expand = 1)
# creating sub-frames
frame_001 = Frame(frame_1)
frame_101 = Frame(frame_1)
frame_102 = Frame(frame_1)
frame_002 = Frame(frame_1)
frame_103 = Frame(frame_1)
# displaying the sub-frames
frame_001.pack(side = TOP, fill = "both", padx=5)
frame_101.pack(fill = "both", expand = 1, padx=5, pady=5)
frame_102.pack(padx=5,)
frame_002.pack(fill = "both", padx=5)
frame_103.pack(fill = "both", expand = 1, padx=5, pady=5)
# creating labels for the language sections
label_1 = Label(frame_001, text = "Input")
label_2 = Label(frame_002, text = "Output")
# displaying the labels
label_1.pack(side = LEFT)
label_2.pack(side = LEFT)
# creating entry fields
text_box_1 = scrolltextbox.ScrolledText(frame_101, bg = "white", height = 15, wrap = WORD, relief=SUNKEN)
text_box_2 = scrolltextbox.ScrolledText(frame_103, bg = "white", height = 15, wrap = WORD, relief=SUNKEN)
# displaying the entry fields
text_box_1.pack(fill = "both")
text_box_2.pack(fill = "both")
# defining the commands for the buttons
# command for the clear button
def clear():
# clearing the text box
text_box_1.delete('1.0', END)
# command for the clear all button
def clear_all():
# clearing all the text boxes
text_box_1.delete('1.0', END)
text_box_2.delete('1.0', END)
# command to get, translate and display text
def translate():
# getting the text
source_lang = text_box_1.get('1.0', END)
# translating the text
# checking if text box is empty or not: to determine if translation will take place
if len(text_box_1.get("1.0", "end-1c")) == 0:
tkinter.messagebox.showwarning("No input!", "Please provide text to be translated in the top text box.")
else:
while True:
# selecting the kind of language translation
lang = tkinter.simpledialog.askinteger("Select output language", "How do you want your translation? \n[1: English to French] \n[2: French to English]")
if lang == 1:
# english to french translation
translation = language_translator.translate(source_lang, model_id='en-fr').get_result()
translated_text = json.dumps(translation, indent=2, ensure_ascii=False)
# displaying the output
text_box_2.insert('1.0', "\n*******************************************************************************")
text_box_2.insert('1.0', "\n", translated_text)
text_box_2.insert('1.0', translated_text)
text_box_2.insert('1.0', "\n", translated_text)
text_box_2.insert('1.0', "\n*******************************************************************************")
break
elif lang == 2:
# french to english translation
translation = language_translator.translate(source_lang, model_id='fr-en').get_result()
translated_text = json.dumps(translation, indent=2, ensure_ascii=False)
# displaying the output
text_box_2.insert('1.0', "\n*******************************************************************************")
text_box_2.insert('1.0', "\n", translated_text)
text_box_2.insert('1.0', translated_text)
text_box_2.insert('1.0', "\n", translated_text)
text_box_2.insert('1.0', "\n*******************************************************************************")
break
else:
# warning to select correct/provided options
tkinter.messagebox.showwarning("Warning", "Please select the provided options, Other language translations will be available in future versions of Text Translator.")
continue
# command to browse for file to load
def browse():
# using fdialog
global file_to_open
# openig dialog box to open text file
self.file_to_open = fdialog.askopenfilename(initialdir = "/home", title = "Open to translate a text file", filetypes = (("text files", "*.txt"),("all files","*.*")))
# loading and displaying the file and it's content to text box 1
open_f = open(self.file_to_open, "r")
read_f = open_f.read()
text_box_1.insert('1.0', read_f)
# creating the translate and clear buttons
button_1 = Button(frame_102, text = "Translate", relief = RAISED, command = translate)
button_2 = Button(frame_102, text = "Clear", relief = RAISED, command = clear)
button_3 = Button(frame_102, text = "Clear All", relief = RAISED, command = clear_all)
button_4 = Button(frame_102, text = "Browse", relief = RAISED, command = browse)
# displaying the buttons
button_4.pack(side = RIGHT, padx = 5)
button_1.pack(side = RIGHT, padx = 5)
button_3.pack(side = RIGHT, padx = 5)
button_2.pack(side = RIGHT, padx = 5)
# creating the status bar
status_bar = Frame(master)
status = Label(status_bar, text = "Version 1.0", bd = 1, relief = SUNKEN, anchor = E)
# displaying the status bar
status_bar.pack(side = BOTTOM, fill = "x", padx = 5)
status.pack(side = BOTTOM, fill = "x")
# defining the commands for the menu bar
# commands for "Open file"
def open_file(self):
# using fdialog
global file_to_open
# openig dialog box to open text file
self.file_to_open = fdialog.askopenfilename(initialdir = "/home", title = "Open to edit a text file", filetypes = (("text files", "*.txt"),("all files","*.*")))
# loading and displaying the file and it's content to text box 1
os.system("gvim " + self.file_to_open)
# commands for "About"
def about(self):
# using messagebox
tkinter.messagebox.showinfo("About Text Translater 1.0", "*********** ABOUT *********** \n\nText Translater 1.0 is a software that translates your test from one human language to another e.g. en --to--> fr \n\n********** AUTHOR ********** \n\nFreedom Loisa Kitakaya")
# creating the mainloop window and initializing it with class GUI_Window
GUI =Tk()
main_window = GUI_Window(GUI)
icon = Image("photo", file="icon.png")
GUI.tk.call('wm','iconphoto',GUI._w, icon)
GUI.mainloop()
|
FruitList = ['Apple', 'Orange','Pear','Grape','Kiwi'] #List of fruits
PriceList = [1.30,1.00,0.80,2.20,1.70] #Price list; index matches FruitList
def swap_func(a,b): #returns new a and b
a = int(a) + int(b)
b = a-int(b)
a=a-b
return str(a),str(b)
def lookup_func(fruit,qty): #returns total price
return PriceList[FruitList.index(fruit)]*float(qty)
|
import random
from brain_games.engine import run_game
def play():
RULE = "What number is missing in the progression?"
run_game(RULE, generate_data)
def generate_data():
a1 = random.randrange(20)
# a1 is the first number of arithmetic progression
d = random.randint(2, 9)
# d is the differance of successive members
missing_position = random.randrange(10)
arith_sequence = [str(a1)]
for i in range(1, 10):
arith_sequence.append(str(a1 + i * d))
correct_answer = arith_sequence[missing_position]
arith_sequence.remove(correct_answer)
arith_sequence.insert(missing_position, '..')
expression = ' '.join(arith_sequence)
return expression, str(correct_answer)
|
'''
Constructs magic square. Property of magic square is that the sums of all rows and columns are equal.
'''
#!/usr/bin/env python
size = 0
while(size%2==0):
size = int(raw_input("Enter ODD number: "))
Matrix = []
for i in xrange(size):
row = []
for j in xrange(size):
row.append(0)
Matrix.append(row)
curPos = [0,size/2]
Matrix[curPos[0]][curPos[1]] = 1
for number in xrange(2,(size*size)+1):
if (Matrix[(curPos[0]-1)%size][(curPos[1]+1)%size]==0):
Matrix[(curPos[0]-1)%size][(curPos[1]+1)%size] = number
curPos[0] = (curPos[0]-1)%size
curPos[1] = (curPos[1]+1)%size
else:
Matrix[(curPos[0]+1)%size][(curPos[1])%size] = number
curPos[0] = (curPos[0]+1)%size
for i in xrange(size):
sum = 0
for j in xrange(size):
sum = sum + Matrix[i][j]
print Matrix[i],sum
|
""" Human resources (HR) module
Data table structure:
- id (string)
- name (string)
- birth date (string): in ISO 8601 format (like 1989-03-21)
- department (string)
- clearance level (int): from 0 (lowest) to 7 (highest)
"""
from model import data_manager, util
DATAFILE = "model/hr/hr.csv"
HEADERS = ["Id", "Name", "Date of birth", "Department", "Clearance"]
#data = data_manager.read_table_from_file("model/hr/hr.csv", separator=';')
def data_read():
data = data_manager.read_table_from_file(DATAFILE, separator=';')
return data, HEADERS
def get_ID():
return util.generate_id()
def data_write(data):
data_manager.write_table_to_file(DATAFILE, data, separator=';')
|
# -*- coding: utf-8 -*-
from தமிழ் import எழுத்து
from தமிழ்.சொல் import *
def பிரம்மி(வாக்கியம்):
pass
def பண்டைய_எழுத்து(வாக்கியம் , வருடம் ):
pass
def பண்டைய_சொல் (வாக்கியம், வருடம் ):
pass
def பண்டைய_வாக்கியம்_ஆக்கு(வாக்கியம், வருடம் ):
pass
def தனிமொழி_ஆக்கு(வாக்கியம் ):
pass
def தொடர்மொழி_ஆக்கு(நிலைமொழி, வருமொழி):
தொடர்மொழி= 'அய்யொ'
நிலைமொழி_எழுத்துக்கள் = எழுத்தாக்கு(நிலைமொழி)
வருமொழி_எழுத்துக்கள் = எழுத்தாக்கு(வருமொழி)
#தனிக்குறில் முன் நின்ற மெய் உயிர்வரின் இரட்டுதல்
# மெய் + எழுத்து = மெய்யெழுத்து
if len(நிலைமொழி_எழுத்துக்கள்) == 2 and \
உயிர்மெய்_பிரி(நிலைமொழி_எழுத்துக்கள்[0])[1] in எழுத்து.குறில் and \
எழுத்து.கடையெழுத்து(நிலைமொழி) in எழுத்து.மெய் and \
எழுத்து.முதலெழுத்து(வருமொழி) in எழுத்து.உயிர்:
தொடர்மொழி = தனிக்குறில்_முன்_நின்ற_மெய்_உயிர்வரின்_இரட்டுதல்(நிலைமொழி_எழுத்துக்கள், வருமொழி_எழுத்துக்கள்)
# மெய்யின் மேல் உயிர் வந்து ஒன்றுதல்
# உயிர் + எழுத்து = உயிரெழுத்து
elif எழுத்து.கடையெழுத்து(நிலைமொழி) in எழுத்து.மெய் and \
எழுத்து.முதலெழுத்து(வருமொழி) in எழுத்து.உயிர்:
தொடர்மொழி = மெய்யின்_மேல்_உயிர்_வந்து_ஒன்றுதல்(நிலைமொழி_எழுத்துக்கள், வருமொழி_எழுத்துக்கள்)
return தொடர்மொழி
def தனிக்குறில்_முன்_நின்ற_மெய்_உயிர்வரின்_இரட்டுதல்(நிலைமொழி_எழுத்துக்கள், வருமொழி_எழுத்துக்கள்):
தொமொ = நிலைமொழி_எழுத்துக்கள் + \
list(உயிர்மெய்_ஆக்கு(நிலைமொழி_எழுத்துக்கள்[-1],வருமொழி_எழுத்துக்கள்[0])) + \
வருமொழி_எழுத்துக்கள்[1:]
தொடர்மொழி=''
for எழுத்து in தொமொ :
தொடர்மொழி = தொடர்மொழி + எழுத்து
return தொடர்மொழி
def மெய்யின்_மேல்_உயிர்_வந்து_ஒன்றுதல்(நிலைமொழி_எழுத்துக்கள், வருமொழி_எழுத்துக்கள்):
தொமொ = நிலைமொழி_எழுத்துக்கள்[:-1] + \
list(உயிர்மெய்_ஆக்கு(நிலைமொழி_எழுத்துக்கள்[-1],வருமொழி_எழுத்துக்கள்[0])) + \
வருமொழி_எழுத்துக்கள்[1:]
தொடர்மொழி=''
for எழுத்து in தொமொ :
தொடர்மொழி = தொடர்மொழி + எழுத்து
return தொடர்மொழி
|
#Sin & Cos
# I am using Python 3
from math import sin, cos, pi
x = pi/4
val = (sin(x))**2 + (cos(x))**2
print (val)
#Compute S in meters
v0 = 3 #m/s
t = 1 #s
a = 2 #m/s**2
s = v0 * t + 0.5*(a*t)**2
print (s)
#Verifying Equations
a = 3.3
b = 5.3
a2 = a**2
b2 = b**2
eq1_sum = a2 + 2*(a*b) + b2
eq2_sum = a2 - 2*(a*b) + b2
eq1_pow = (a + b)**2
eq2_pow = (a - b)**2
print ("First equation: '%g' = '%g' " % (eq1_sum, eq1_pow))
print ("Second equation: %d = %d" % (eq1_pow, eq2_pow))
|
"""
Loading output of sql querries to CSV
"""
import os
import pandas as pd
from connectivator import gsheets
def add_slash(dir_name):
"""
Adds a slash at the end of a string if not present
"""
if not dir_name.endswith('/'):
dir_name += '/'
return dir_name
def make_dir(filepath):
"""
Creates a directory from a file path if the directory does not exist
"""
file_dir = os.path.dirname(filepath)
if not os.path.exists(file_dir):
os.makedirs(file_dir)
def read_sql_data(filepath, db_conn):
"""
Load output of sql file into a data frame
"""
# tech debt: check if sql file
# Read the sql file
opened_query = open(filepath, 'r')
print('Read ' + filepath)
# connection to database
data_frame = pd.read_sql_query(opened_query.read(), db_conn)
print('Stored output of ' + filepath + ' into data frame')
return data_frame
def sql_to_csv(filepath, db_conn, output_folder='output/'):
"""
Writes output of a single sql query to CSV
"""
data_frame = read_sql_data(filepath, db_conn)
# add slash if needed
output_folder = add_slash(dir_name=output_folder)
output_filepath = output_folder + filepath.split('.')[0] + '.csv'
# create director if needed
make_dir(output_filepath)
# write to output folder
data_frame.to_csv(output_filepath, sep='\t', encoding='utf-8')
print('Wrote output to ' + output_filepath)
def sqls_to_csv(filepath, db_conn, output_folder='output/'):
"""
Writes output of sql queries to a CSV files
"""
if os.path.isdir(filepath):
file_list = os.listdir(filepath)
filepath = add_slash(dir_name=filepath)
for file in file_list:
if file.endswith(".sql"):
file = filepath + file
sql_to_csv(filepath=file, db_conn=db_conn,
output_folder=output_folder)
else:
sql_to_csv(filepath=filepath, db_conn=db_conn,
output_folder=output_folder)
def sql_to_gs(filepath, db_conn, gs_conn, output_gs_id, output_ws=None):
"""
Writes output of a single sql query to a google sheet
"""
if not output_ws:
output_ws = filepath.split('/')[-1].split('.')[0]
data_frame = read_sql_data(filepath, db_conn)
# add slash if needed
gsheets.update_ws(gs_conn, output_gs_id, output_ws, data_frame)
print('Wrote output to Google sheet id ' + output_gs_id +
', worksheet ' + output_ws)
def sqls_to_gs(filepath, db_conn, gs_conn, output_gs_id):
"""
Writes output of sql queries to a google sheet
"""
if os.path.isdir(filepath):
file_list = os.listdir(filepath)
filepath = add_slash(dir_name=filepath)
for file in file_list:
if file.endswith(".sql"):
file = filepath + file
sql_to_gs(filepath=file, db_conn=db_conn,
gs_conn=gs_conn, output_gs_id=output_gs_id)
else:
sql_to_gs(filepath=filepath, db_conn=db_conn,
gs_conn=gs_conn, output_gs_id=output_gs_id)
|
# 415. Add Strings
# Given two non-negative integers num1 and num2 represented as a string,
# return the sum of num1 and num2.
# The length of both num1 and num2 is < 5100.
# Both num1 and num2 contains only digits 0-9.
# Both num1 and num2 does not contain any leading zero.
# You must not use any built-in BigInteger library or convert
# the inputs to integer directly.
def add_strings(str1, str2):
"""Given two integers as a string return the sum of both integers."""
s1 = list(str1)
s2 = list(str2)
s1_index = len(s1) -1
s2_index = len(s2) -1
result = 0
multiple = 1
if s1[0] == "0" or s2[0] == "0":
return None
while s1_index >= 0 or s2_index >= 0:
if s1_index >= 0 and not s1[s1_index].isdigit():
return None
if s2_index >= 0 and not s2[s2_index].isdigit():
return None
last_s1 = int(s1[s1_index]) if s1_index >= 0 else 0
last_s2 = int(s2[s2_index]) if s2_index >= 0 else 0
digit = last_s1 + last_s2
result += digit * multiple
multiple *= 10
s1_index = s1_index -1
s2_index = s2_index -1
return str(result)
#convert to a string last
print(add_strings("789", "100")) #889
print(add_strings("8", "6a9")) #None
print(add_strings("05", "12")) #None
print(add_strings("7", "3")) #10
print(add_strings("7000", "3")) #7003
|
# Consider the word "abode". We can see that the letter a is in position 1 and b
# is in position 2. In the alphabet, a and b are also in positions 1 and 2.
# Notice also that d and e in abode occupy the positions they would occupy in
# the alphabet, which are positions 4 and 5.
# Given an array of words, return an array of the number of letters that
# occupy their positions in the alphabet for each word. For example,
# solve(["abode","ABc","xyzD"]) = [4, 3, 1]
# See test cases for more examples.
# Input will consist of alphabet characters, both uppercase and lowercase.
# No spaces.
def solve(arr):
"""Return an array of the number of letters that have alphabet symmetry."""
alphabet = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8,
'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15,
'p':16, 'q':17, 'r':18, 's':19, 't':20, 'u':21, 'v':22,
'w':23, 'x':24, 'y':25, 'z':26}
new = []
for string in arr:
count = 0
for position, letter in enumerate(string):
letter = letter.lower()
position = position +1
if position == alphabet[letter]:
count +=1
new.append(count)
return new
print(solve(["abode","ABc","xyzD"])) #,[4,3,1])))
print(solve(["abide","ABc","xyz"])) #,[4,3,0])))
print(solve(["IAMDEFANDJKL","thedefgh","xyzDEFghijabc"])) #,[6,5,7])))
print(solve(["encode","abc","xyzD","ABmD"])) #,[1, 3, 1, 3])))
|
# Modify the kebabize function so that it converts a camel
# case string into a kebab case.
# kebabize('camelsHaveThreeHumps') // camels-have-three-humps
# kebabize('camelsHave3Humps') // camels-have-h
def kebabize(string):
"""Given a string in camel case convert it to kebab case."""
result = ""
for char in string:
if char.isupper():
if result is not "":
result += "-{}".format(char.lower())
else:
result += char.lower()
if char.islower():
result += char
return result
print(kebabize('camelsHaveThreeHumps')) #camels-have-three-humps
print(kebabize('piratesOfTheCarribean')) #pirates-of-the-carribean
print(kebabize('camelsHave3Humps')) #camels-have-h
|
import os
import math
# Intro \o/
print("Advent of Code 2019")
print("Solution for Day 1 by Th3Shadowbroker (github.th3shadowbroker.org)")
# Required variables
masses_source = "masses.txt"
masses = []
fuel_amounts = []
fuel_total = 0
fuel_additional = 0
# Read masses from masses_source
def readMasses():
masses_file = open(os.path.dirname( os.path.realpath(__file__) ) + "/" + masses_source, "r")
while True:
l = masses_file.readline()
if not l:
break
masses.append(int(l.strip()))
masses_file.close()
print("Read " + str(len(masses)) + " masses...")
# Calculate the fuel based on the given mass
def calculateFuel(mass):
result = math.floor(mass / 3) - 2
return result
# Calculate the additional fuel required for every module sparatly
def calculateAdditionalFuel(mass):
global fuel_additional
currentFuel = calculateFuel(mass)
if currentFuel > 0:
fuel_additional += currentFuel
calculateAdditionalFuel(currentFuel)
else:
return
# Solves the task
def solve():
global fuel_total
global fuel_additional
readMasses()
for mass in masses:
fuel_amounts.append( calculateFuel(mass) )
calculateAdditionalFuel( calculateFuel(mass) )
for fuel_amount in fuel_amounts:
fuel_total += fuel_amount
print("Total required fuel calculates to " + str(fuel_total))
print("Total required fuel and the additional fuel calculates to " + str(fuel_total + fuel_additional))
# Run the script
solve()
|
from sympy import factorint
#Critère de divisibilité dans une base optimale d'un premier p
def p_bestbase(p):
"""Renvoie la période minimale du critère de divisibilité par le
premier p, étudie pour cela l'entier m tel que p=2*m+1"""
m = (p-1)//2
Lf = factorint(m) #produit un dictionnaire où chaque clé est un premier
if len(Lf)*list(Lf.values())[0]==1: #cas où m est premier {p:1}
if m == 2:
n = 4 #cas particulier p=5
else:
n = m
else: #cas où m est composé
n0 = n1 = m
for k in Lf.keys(): # détermination des deux plus petits facteurs de m
if k < n0:
n1 = n0
n0 = k
else:
n1 = min(n1,k)
if n0 == 2: # cas m est un nombre pair
n = min(4,n1) # discrimine le cas n1 =3
else:
n = n0
return n
def resolmod1(n,p):
"""cherche une base b non triviale solution de l'équation b^n=1[p]"""
for k in range(2,p-1):
if test1(k,n,p): #teste si k^n = 1 [p]
return k #renvoie la première base optimale
return False
def test1(b,n,p):
"""Teste si b^n=1[p]"""
B = b
for k in range(n-1):
B = (b*B)%p
return B == 1
def affich_best_bases(p):
"""Détermine la liste des bases optimales pour
le critère de divisibilité par p"""
n = p_bestbase(p)
b0 = resolmod1(n,p)
if (p-1)//2==n:
txt="c'est un premier sûr: "+str(b0)+": \n(1, "
CL=""
for k in range(2,n):
CL+=
else:
txt="{"
return txt
|
Decorator: is used to add additional functionalities
to the function without editing function
# ================================================================================
# Wrap function by function (closure)
def trace(func):
def wrapper():
print(func.__name__, '함수 시작')
func()
print(func.__name__, '함수 끝')
return wrapper
def hello():
print('hello')
def world():
print('world')
trace_hello = trace(hello)
trace_hello()
trace_world = trace(world)
trace_world()
# ================================================================================
# Use decorator
# func is the function which you will call
def trace(func):
def wrapper():
print(func.__name__, '함수 시작')
# Call passed func
func()
print(func.__name__, '함수 끝')
# Return wrapper()
return wrapper
@trace
def hello():
print('hello')
@trace
def world():
print('world')
hello()
world()
# ================================================================================
# Multiple decorators
def decorator1(func):
def wrapper():
print('decorator1')
func()
return wrapper
def decorator2(func):
def wrapper():
print('decorator2')
func()
return wrapper
@decorator1
@decorator2
def hello():
print('hello')
hello()
# ================================================================================
# Same code without using decorator
decorated_hello=decorator1(decorator2(hello))
decorated_hello()
# ================================================================================
|
# .-"-.
# /|6 6|\
# {/(_0_)\}
# _/ ^ \_
# (/ /^\ \)-'
# ""' '"" 하늘
# written by
# @author Wolverine 왕경민
# File Name : Halloween Sale.py
# Date Created : 13/12/2019
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the howManyGames function below.
def howManyGames(p, d, m, s):
List = [p]
while (True):
p = p-d
if (p>m):
List.append(p)
else:
break
if (sum(List) >= s):
total = 0
for i in range(len(List)):
total += List[i]
if (total >= s):
return i
else:
s -= sum(List)
count = s / m
return math.floor(len(List) + count);
# Return the number of games you can buy
if __name__ == '__main__':
pdms = input().split()
p = int(pdms[0])
d = int(pdms[1])
m = int(pdms[2])
s = int(pdms[3])
answer = howManyGames(p, d, m, s)
print (str(answer))
|
import random
secret_number = random.randint(1,101)
tries = 0
while tries < 10:
tries += 1
guess = int(input(' enter a number: '))
if guess < secret_number:
print(str(10 - tries) + ' Attempts left : Your guess is lower.. Try Again')
elif guess > secret_number:
print(str(10 - tries) + ' Attempts left : Your guess is higher.. Try Again')
else:
print( "You guessed right with " + str(10 - tries) + ' attempts stil left!')
break
if guess != secret_number and tries == 10:
print('Sorry! The correct number was: ' ,secret_number)
|
# Module that contains functions that can be used across all files
# df represents pandas DataFrame
import pandas as pd
import numpy as np
def sklearn_data_to_df(data):
'''
translate sklearn df to a pandas dataframe
dependencies: numpy, pandas
target attribute will be named "target"
'''
pandas_df = pd.DataFrame(data=np.c_[data['data'], data['target']],
columns=np.append(data['feature_names'], ['target']))
print(pandas_df.head())
return pandas_df
from sklearn.model_selection import train_test_split
def train_test_split_from_df(df, target_col, test_size=None, train_size=None, random_state=None, shuffle=True, stratify=None):
'''
split df into train and test
utilizing sklearn "train_test_split"
returns a tuple
'''
X = df.drop(target_col, axis=1)
y = df[target_col]
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=test_size,
train_size=train_size,
random_state=random_state,
shuffle=shuffle,
stratify=stratify)
return X_train, X_test, y_train, y_test
|
# Problem 1
#
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# Author: Jose Manuel Martinez Salas
entry = 1000
print(sum([num for num in range(0,entry) if (num % 3 == 0) or (num % 5 == 0)], 0))
|
A_List = CircularDoublyLinkedList()
while True:
print('1.Add Node')
print('2.Delete Node')
print('3.Display ')
print('4.Display Sorting')
print('5.Capacity ')
print('6.List_capacity')
print('7.Quit')
do = int(input('What would you like to do'))
if do == 1:
A_List.insert()
elif do == 2:
A_List.delete()
elif do == 3:
A_List.print_all()
elif do == 4:
A_List.Sorting()
elif do == 5:
print("Capacity")
print(A_List.capacity)
print("Total number of Nodes")
print(A_List.total_nodes)
print("Original Length")
print(len(A_List.list_capacity))
elif do == 6:
for i in range(A_List.total_nodes):
print(A_List.list_capacity[i].data.display_all_attributes())
elif do == 7:
print("Thanks for using Linked List")
break
else:
print("WRONG SELECTION")
break
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 10:49:31 2021
@author: Elijah
"""
#Boolean Keywords
print(type(True))
print(type(False))
print(type("True"))
David = 4.0
Elijah = 3.5
Cesar = 3.5
Gabin = 1.5
print("Who is better? Is David better than Elijah? ")
print(David > Elijah)
print("Are Elijah and Cesar of equal caliber? ")
print(Elijah == Cesar)
print("Is Cesar in between the worst and best students? ")
print(Gabin < Cesar and Cesar < David)
#Scholarship, University Calculator
y1 = float(input("What was your freshman year gpa? "))
y2 = float(input("What was your sophomore year gpa? "))
y3 = float(input("What was your junior year gpa? "))
musician = input("Are you a talented musician? ")
gpa = (y1 + y2 + y3) / 3
print("Your GPA is {:.5f}".format(gpa))
if(gpa > 3.7):
print("You are qualified for earning a scholarship")
elif(gpa > 3.4 and (musician == "yes" or musician == "Yes")):
print("You are qualified for earning a scholarship")
else:
print("You better save up for school ")
|
# cerate a method that takes one argument as a string (that string is your name)
# and if the name == "dunni" returns true, else false
def checkname(name):
return name == "dunni"
|
arr1=[1,2,3,4,5,6]
arr2=[2,3,4,6,8]
arr3=[]
def fn(arr1,arr2):
if arr1[0] <= arr2[0]:
arr3.append(arr1[0])
arr1.pop(0)
if len(arr1) >0:
fn(arr1, arr2)
else:
arr3.extend(arr2)
else:
arr3.append(arr2[0])
arr2.pop(0)
if len(arr2) >0:
fn(arr1, arr2)
else:
arr3.extend(arr1)
return
def join(arr1,arr2):
arr1.extend(arr2)
return arr1
if(len(arr1) and len(arr2)):
if arr1[-1] <= arr2[0]:
join(arr3,join(arr1,arr2))
elif arr2[-1] <= arr1[0]:
join(arr3,join(arr2,arr1))
else:
fn(arr1, arr2)
else:
join(arr3,join(arr1,arr2))
print(arr3)
|
#!/usr/bin/env python3
from functools import lru_cache
from utils import coded_colors
from utils import serial_ends_with_odd
def cut(desc):
print(f'Cut the {desc} wire.')
# @lru_cache(len(coded_colors))
# def color_of(name):
# return input(f'Color of {name}: ').lower()
# @lru_cache(len(coded_colors))
# def num(name):
# return int(input(f'Number of {name}: '))
def color_of(name):
if name == 'the last wire':
return wires[-1]
raise ValueError()
def num(wire):
wire = wire.replace('wires', '').strip()
if not wire:
return len(wires)
return wires.count(wire)
wires = [coded_colors[code] for code in input()]
if num('wires') == 3:
if num('red wires') == 0:
cut('second')
elif color_of('the last wire') == 'white':
cut('last')
elif num('blue wires') > 1:
cut('last blue')
else:
cut('last')
elif num('wires') == 4:
if num('red wires') > 1 and serial_ends_with_odd():
cut('red')
elif color_of('the last wire') == 'yellow' and num('red wires') == 0:
cut('first')
elif num('blue wires') == 1:
cut('first')
elif num('yellow wires') > 1:
cut('last')
else:
cut('second')
elif num('wires') == 5:
if color_of('the last wire') == 'black' and serial_ends_with_odd():
cut('fourth')
elif num('red wires') == 1 and num('yellow wires') > 1:
cut('first')
elif num('black wire') == 0:
cut('second')
else:
cut('first')
elif num('wires') == 6:
if num('yellow wires') == 0 and serial_ends_with_odd():
cut('third')
elif num('yellow wires') == 1 and num('white wires') > 1:
cut('fourth')
elif num('red wires') == 0:
cut('last')
else:
cut('fourth')
|
"""
Binary Search Tree:
For each node, left is less than the node's value and right is greater than the node's value
When searching through the tree, by comparing the node's value to the search value, we know
which direction down the tree to go
"""
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
return self.insert_bst(self.root, new_val)
def insert_bst(self, start, new_val):
if start.value < new_val:
if start.right:
return self.insert_bst(start.right, new_val)
else:
start.right = Node(new_val)
else:
if start.left:
return self.insert_bst(start.left, new_val)
else:
start.left = Node(new_val)
def search(self, find_val):
return self.search_bst(self.root, find_val)
def search_bst(self, start, find_val):
if start:
if start.value == find_val:
return True
elif start.value < find_val:
return self.search_bst(start.right, find_val)
else:
return self.search_bst(start.left, find_val)
else:
return False
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
print tree.search(4)
# Should be False
print tree.search(6)
|
"""
Write a function that spiral prints a matrix (a list of lists)
Given a list of lists ...
[[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
the function prints ...
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
"""
def spiralPrint(matrix):
output = []
# initialize index trackers to help reduce the matrix
col_start = 0
col_finish = len(matrix[0]) - 1
row_start = 0
row_finish = len(matrix) - 1
# 4 functions taking matrix and 4 index range arguments: h_start, h_finish, v_start, v_finish
while matrix:
if row_start > row_finish:
break
else:
## print right
for a in range(col_start, col_finish + 1):
output.append(matrix[row_start][a])
# reduce the matrix
row_start = row_start + 1
if col_start > col_finish:
break
else:
# print down
for b in range(row_start, row_finish + 1):
output.append(matrix[b][col_finish])
# reduce the matrix
col_finish = col_finish - 1
if row_start > row_finish:
break
else:
# print left
for c in range(col_finish, col_start - 1, -1):
output.append(matrix[row_finish][c])
# reduce the matrix
row_finish = row_finish - 1
if col_start > col_finish:
break
else:
# print up
for d in range(row_finish, row_start - 1, -1):
output.append(matrix[d][col_start])
# reduce the matrix
col_start = col_start + 1
return output
theInput = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
print(spiralPrint(theInput))
theInput = [[1,2,3],[5,6,7],[9,10,11],[13,14,15]]
print(spiralPrint(theInput))
"""
Decrement the index range to emulate the boundary on 4 sides closing in
Time complexity: every element in m rows and n columns; O(m*n)
Space complexity: in-place; O(1)
"""
|
import argparse
import os
"""
This script normalizes a given substitution matrix.
To normalize the matrix the diagonal values are substituted by the mean value of the diagonal values.
"""
"""
Calculate the mean value of the diagonal entries.
@:param matrix given matrix
@:param isInt boolean value indicating if matrix contains only integer values
@:return mean value of diagonal values
"""
def getMean(matrix, isInt):
sum = 0
for n in range(len(matrix)):
for m in range(len(matrix[n])):
if n == m:
sum += matrix[n][m]
if isInt:
sum = int(sum / len(matrix))
else:
sum = sum / len(matrix)
return sum
def main():
# Build an ArgumentParser to parse the command line arguments and add argument
parser = argparse.ArgumentParser()
parser.add_argument('matrix', type=str, help='Path to the unnormalized Matrix file')
# Now parse the command line arguments
arg = parser.parse_args()
mat = arg.matrix
output = ""
matrixlist = mat.split(".")
output = matrixlist[0] + "_normalized.txt"
# Now we parse the substitution matrix into a list of list.
i = 0
matrix = []
amino_acids = []
isInt = False
for line in (open(mat)).readlines():
if i == 0:
i = 1
continue
else:
linelist = line.split()
amino = linelist[0]
amino_acids.append(amino)
linelist = linelist[1:]
current_list = []
for n in range(len(linelist)):
try:
x = int(linelist[n])
isInt = True
except ValueError:
x = float(linelist[n])
current_list.append(x)
matrix.append(current_list)
# We calculate the mean value of the diagonal entries.
mean = getMean(matrix, isInt)
output_open = open(output, "w")
# We write the new matrix to the output.
for elem in amino_acids:
output_open.write(elem + " ")
output_open.write("\n")
for n in range(len(matrix)):
output_open.write(amino_acids[n] + " ")
for m in range(len(matrix[n])):
if n == m:
output_open.write(str(mean) + " ")
else:
output_open.write(str(matrix[n][m]) + " ")
output_open.write("\n")
if __name__ == '__main__':
main()
|
"""
Created by Sai Ram (31009751) for Assignment 1 of FIT9136
Start Date: 04/04/2020
End Date: 28/04/2020
Last edit: 01/05/2020
Description: Inventory system of cantilever umbrellas for a company to record the available stock and revenue for a
given year.
"""
# Input to the program
def read_data():
data_read = ['start_year', 'start_stock', 'start_revenue']
file = open('AU_INV_START.txt', 'r')
file1 = file.read().split("\n")
data_read = dict(zip(data_read, file1))
file.close()
return data_read
# Output to the program
def write_data(writing_data):
write_file = open('AU_INV_END.txt', 'w')
file = list(writing_data.values())
for i in file:
write_file.write(str(i) + '\n')
# Check if given year is leap or not
def leap_year(simulation_year):
leap = False
if simulation_year % 4 == 0:
leap = True
return leap
# Function for first occurrence of financial crisis (2009, 2010 and 2011)
def first_fin_crisis(year, qty, list_years):
lst_qty = list(qty.values())
if year == list_years[0]:
# Quantity falls to 80%(2009)
lst_qty = [round(i * 0.8) for i in lst_qty] # Quantity falls to 80%
# Price per unit is calculated from year 2000 and to 2009 and then increased by 10%
lst_rev = [round(i * (1.1 ** ((year - 2000) + 1)), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)] # Total revenue is calculated
return sum(lst_rev) # Returns the summed up revenue for 2009
# Similarly for 2010 is carried out
if year == list_years[1]:
# Quantity falls to 80%(2009),90%(2010)
lst_qty = [round(i * 0.8 * 0.9) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010)
lst_rev = [round((i * 1.05 * (1.1 ** ((year - 2000) + 1))), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Similarly for 2011 is carried out
if year == list_years[2]:
# Quantity falls to 80%(2009),90%(2010),95%(2011)
lst_qty = [round(i * 0.8 * 0.9 * 0.95) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011)
lst_rev = [round((i * 1.05 * 1.03 * (1.1 ** ((year - 2000) + 1))), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
if 2012 <= year <= 2019:
# Quantity falls to 80%(2009),90%(2010),95%(2011)
lst_qty = [round(i * 0.8 * 0.9 * 0.95) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011)
lst_rev = [round((i * 1.05 * 1.03 * (1.1 ** ((year - 2000) + 1))), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Function for second occurrence of financial crisis (2020, 2021 and 2022)
def second_fin_crisis(year, qty, list_years):
lst_qty = list(qty.values())
# Similarly for 2020 is carried out
if year == list_years[0]:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020)
lst_qty = [round(i * 0.8 * 0.8 * 0.9 * 0.95) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020)
lst_rev = [round(i * 1.05 * 1.03 * 1.1 * (1.1 ** ((year - 2000) + 1)), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Similarly for 2021 is carried out
if year == list_years[1]:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021)
lst_qty = [round(i * 0.8 * 0.9 * 0.8 * 0.9 * 0.95) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021)
lst_rev = [round(i * 1.05 * 1.05 * 1.03 * 1.1 * (1.1 ** ((year - 2000) + 1)), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Similarly for 2022 is carried out
if year == list_years[2]:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021),95%(2022)
lst_qty = [round(i * 0.8 * 0.9 * 0.95 * 0.8 * 0.9 * 0.95) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021), 3%(2022)
lst_rev = [round(i * 1.05 * 1.03 * 1.05 * 1.03 * 1.1 * (1.1 ** ((year - 2000) + 1)), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
if 2023 <= year <= 2030:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021),95%(2022)
lst_qty = [round(i * 0.8 * 0.9 * 0.95 * 0.8 * 0.9 * 0.95) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021), 3%(2022)
lst_rev = [round(i * 1.05 * 1.03 * 1.05 * 1.03 * 1.1 ** ((year - 2000) + 2), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Function for third occurrence of financial crisis (2031, 2032 and 2033)
def third_fin_crisis(year, qty, list_years):
lst_qty = list(qty.values())
# Similarly for 2031 is carried out
if year == list_years[0]:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021),95%(2022),80%(2031)
lst_qty = [round(i * 0.8 * (0.8 * 0.9 * 0.95) ** 2) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021), 3%(2022), 10%(2031)
lst_rev = [round((i * (1.05 * 1.03) * 1.05 * 1.03 * (1.1 ** ((year - 2000) + 3))), 2) for i in
rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Similarly for 2032 is carried out
if year == list_years[1]:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021),95%(2022),80%(2031),90%(2032)
lst_qty = [round(i * 0.8 * 0.9 * (0.8 * 0.9 * 0.95) ** 2) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021), 3%(2022), 10%(2031), 5%(2032)
lst_rev = [round(i * 1.05 * (1.05 * 1.03) * 1.05 * 1.03 * (1.1 ** ((year - 2000) + 3)), 2) for i in rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Similarly for 2033 is carried out
if year == list_years[2]:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021),95%(2022),80%(2031),90%(2032),95%(2033)
lst_qty = [round(i * (0.8 * 0.9 * 0.95) ** 3) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021), 3%(2022), 10%(2031), 5%(2032), 3%(2033)
lst_rev = [round(i * 1.03 * 1.05 * (1.05 * 1.03) * 1.05 * 1.03 * (1.1 ** ((year - 2000) + 3)), 2) for i in
rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
if 2034 <= year <= 2040:
# Quantity falls to 80%(2009),90%(2010),95%(2011),80%(2020),90%(2021),95%(2022),80%(2031),90%(2032),95%(2033)
lst_qty = [round(i * (0.8 * 0.9 * 0.95) ** 3) for i in lst_qty]
# Price increases to 10%(2009), 5%(2010), 3%(2011), 10%(2020), 5%(2021), 3%(2022), 10%(2031), 5%(2032), 3%(2033)
lst_rev = [round(i * 1.03 * 1.05 * (1.05 * 1.03) * 1.05 * 1.03 * (1.1 ** ((year - 2000) + 3)), 2) for i in
rev_list]
lst_rev = [round(a * b, 2) for a, b in zip(lst_rev, lst_qty)]
return sum(lst_rev) # Total revenue is calculated and returned
# Function for calculating the years in financial crisis
def total_financial_crisis_years():
# Calculate the first occurrence of the financial year e.g(2009, 2020 and 2031)
first_occurrence_crisis = [i for i in range(2000 + CRIS_RECUR_FREQUENCY, 2040, CRIS_RECUR_FREQUENCY + 2)]
# From the calculated first occurrences of financial year, calculate the remaining of them
# e .g (2009, 2010 and 2011)
first_crisis_years = [i for i in range(first_occurrence_crisis[0], first_occurrence_crisis[0] + years_in_crisis)]
second_crisis_years = [i for i in range(first_occurrence_crisis[1], first_occurrence_crisis[1] + years_in_crisis)]
third_crisis_years = [i for i in range(first_occurrence_crisis[2], first_occurrence_crisis[2] + years_in_crisis)]
return first_crisis_years, second_crisis_years, third_crisis_years
# Function for calculating the stock and revenue of the given year
def cal_stock_revenue(year_dictionary): # Argument is a dictionary from the read_data()
year = int(year_dictionary['start_year']) # Converting the year to int and taking it in a variable
available_stock = [1000] # Available stock for the year 2000
total_units_sold_per_month = 0
monthly_defective_items = 0
total_distribution_per_month = [0]
total_revenue_quarterly = 0 # Here quarter is divided as shown : Jan-Feb, Mar-Jun, Jul-Oct and Nov-Dec
total_revenue_generated = 0 # Revenue generated per year
season_dict_qty = {} # A dictionary to hold the values of quarterly sold units
season_dict_rev = {} # A dictionary to hold the values of quarterly revenue generated
# Taking the values of all the financial crisis years from the function total_financial_crisis()
first_crisis_years, second_crisis_years, third_crisis_years = total_financial_crisis_years()
# This logic will run from 2000 to 2040
if 2040 >= year >= 2000:
for loop in range(2000, year + 1): # From the year 2000, calculating the remaining revenue and stocks
if leap_year(loop): # Check if the input year is a leap year or not, if so add 1 extra day to Feb
year_dict['Feb'] = 29
else:
year_dict['Feb'] = 28
'''Calculating the number of units sold and the price of each unit from Jan-Feb, Mar-Jun, Jul-Oct and
Nov-Dec starting from 2000 until the year specified in the input '''
units_per_day_jan = round(qty_list[0] * (1.1 ** (loop - 2000)))
units_per_day_mar = round(qty_list[1] * (1.1 ** (loop - 2000)))
units_per_day_jul = round(qty_list[2] * (1.1 ** (loop - 2000)))
units_per_day_nov = round(qty_list[3] * (1.1 ** (loop - 2000)))
price_per_unit_jan = round(rev_list[0] * (1.1 ** (loop - 2000)), 2)
price_per_unit_mar = round(rev_list[1] * (1.1 ** (loop - 2000)), 2)
price_per_unit_jul = round(rev_list[2] * (1.1 ** (loop - 2000)), 2)
price_per_unit_nov = round(rev_list[3] * (1.1 ** (loop - 2000)), 2)
for i in year_dict: # Run a loop inside the dictionary for all the 12 months
for j in range(year_dict[i]): # Inside the months, run the loop on the basis of days in them
if i in ['Jan', 'Feb']:
if j > 0:
units_per_day_jan = units_per_day_jan # For days greater than 0, units is initialised
else:
total_units_sold_per_month = 0 # Start counting units sold pm for Jan and Feb, from the
# beginning
# At the same time reduce the units sold per day from the available stock
available_stock[0] = available_stock[0] - units_per_day_jan
# Make sure the available stock does not fall less than or equal to 400, if so add 600
while available_stock[0] <= 400:
available_stock[0] += 600
total_units_sold_per_month += units_per_day_jan # Accumulate the no. of units sold per month
if j == year_dict[i] - 1: # On the last day of the month, cal defective and total distribution
defective_units = round(total_units_sold_per_month * def_per)
monthly_defective_items += defective_units
total_units_sold_per_month -= defective_units
available_stock[0] += defective_units
total_distribution_per_month[0] += total_units_sold_per_month
if i == 'Feb': # On the last day of the month of Feb, cal total revenue and quantity sold
season_dict_qty.update([('Jan-Feb', total_distribution_per_month[0])])
total_revenue_quarterly = round((season_dict_qty['Jan-Feb'] * price_per_unit_jan) +
(monthly_defective_items * price_per_unit_jan * 0.8), 2)
season_dict_rev.update([('Jan-Feb', total_revenue_quarterly)])
monthly_defective_items = 0
# Doing the above mentioned method (Jan-Feb) for (Mar-Jun) as well
elif i in ['Mar', 'Apr', 'May', 'Jun']:
if j > 0:
units_per_day_mar = units_per_day_mar
else:
total_units_sold_per_month = 0 # Start counting units sold pm for Feb, from the beginning
available_stock[0] = available_stock[0] - units_per_day_mar
while available_stock[0] <= 400:
available_stock[0] += 600
total_units_sold_per_month += units_per_day_mar
if j == year_dict[i] - 1:
defective_units = round(total_units_sold_per_month * def_per)
monthly_defective_items += defective_units
total_units_sold_per_month -= defective_units
available_stock[0] += defective_units
total_distribution_per_month[0] += total_units_sold_per_month
if i == 'Jun':
season_dict_qty.update([('Mar-Jun',
round(total_distribution_per_month[0] - season_dict_qty[
'Jan-Feb']))])
total_revenue_quarterly += round((season_dict_qty['Mar-Jun'] * price_per_unit_mar) +
(monthly_defective_items * price_per_unit_mar * 0.8),
2)
season_dict_rev.update(
[('Mar-Jun', round(total_revenue_quarterly -
season_dict_rev['Jan-Feb'], 2))])
monthly_defective_items = 0
# Doing the above mentioned method (Mar-Jun) for (Jul-Oct) as well
elif i in ['Jul', 'Aug', 'Sep', 'Oct']:
if j > 0:
units_per_day_jul = units_per_day_jul
else:
total_units_sold_per_month = 0 # Start counting units sold pm for Feb, from the beginning
available_stock[0] = available_stock[0] - units_per_day_jul
while available_stock[0] <= 400:
available_stock[0] += 600
total_units_sold_per_month += units_per_day_jul
if j == year_dict[i] - 1:
defective_units = round(total_units_sold_per_month * def_per)
monthly_defective_items += defective_units
total_units_sold_per_month -= defective_units
available_stock[0] += defective_units
total_distribution_per_month[0] += total_units_sold_per_month
if i == 'Oct':
season_dict_qty.update(
[('Jul-Oct',
round(
total_distribution_per_month[0] -
season_dict_qty['Jan-Feb'] - season_dict_qty['Mar-Jun']))])
total_revenue_quarterly += round((season_dict_qty['Jul-Oct'] * price_per_unit_jul) +
(monthly_defective_items * price_per_unit_jul * 0.8),
2)
season_dict_rev.update(
[('Jul-Oct', round(total_revenue_quarterly -
season_dict_rev['Jan-Feb'] - season_dict_rev['Mar-Jun'],
2))])
monthly_defective_items = 0
# Doing the above mentioned method (Jul-Oct) for (Nov-Dec) as well
elif i in ['Nov', 'Dec']:
if j > 0:
units_per_day_nov = units_per_day_nov
else:
total_units_sold_per_month = 0 # Start counting units sold pm for Feb, from the beginning
available_stock[0] = available_stock[0] - units_per_day_nov
while available_stock[0] <= 400:
available_stock[0] += 600
total_units_sold_per_month += units_per_day_nov
if j == year_dict[i] - 1:
defective_units = round(total_units_sold_per_month * def_per)
monthly_defective_items += defective_units
total_units_sold_per_month -= defective_units
available_stock[0] += defective_units
total_distribution_per_month[0] += total_units_sold_per_month
if i == 'Dec':
season_dict_qty.update([('Nov-Dec',
round(total_distribution_per_month[0]
- season_dict_qty['Mar-Jun'] - season_dict_qty[
'Jan-Feb'] -
season_dict_qty['Jul-Oct']))])
total_revenue_quarterly += ((season_dict_qty['Nov-Dec'] * price_per_unit_nov) +
(monthly_defective_items * price_per_unit_nov * 0.8)
- (defective_units * price_per_unit_nov * 0.8))
season_dict_rev.update(
[('Nov-Dec', round(total_revenue_quarterly -
season_dict_rev['Jan-Feb'] - season_dict_rev['Mar-Jun'] -
season_dict_rev['Jul-Oct'], 2))])
total_distribution_per_month = [0]
monthly_defective_items = 0
available_stock = available_stock[0] # Makes sure the available stock is passed on to the next year
total_revenue_generated = sum(list(season_dict_rev.values())) # Calculate the revenue from revenue dictionary
if year in first_crisis_years: # Check for year in 2009, 2010 or 2011
total_revenue_generated = first_fin_crisis(year, season_dict_qty, first_crisis_years)
if 2012 <= year <= 2019: # For years between first and second financial crisis would start from 2011's value
total_revenue_generated = first_fin_crisis(year, season_dict_qty, first_crisis_years)
if year in second_crisis_years: # Check for year in 2020, 2021 or 2022
total_revenue_generated = second_fin_crisis(year, season_dict_qty, second_crisis_years)
if 2023 <= year <= 2030: # For years between second and third financial crisis would start from 2022's value
total_revenue_generated = second_fin_crisis(year, season_dict_qty, second_crisis_years)
if year in third_crisis_years: # Check for year in 2031, 2032 or 2033
total_revenue_generated = third_fin_crisis(year, season_dict_qty, third_crisis_years)
if 2034 <= year <= 2040: # For years between third financial crisis and 2040 would start from 2033's value
total_revenue_generated = third_fin_crisis(year, season_dict_qty, third_crisis_years)
return {'end_year': year + 1, 'end_stock': available_stock,
'end_revenue': round(total_revenue_generated + float(year_dictionary['start_revenue']), 2)}
if __name__ == '__main__':
# Some variables to be used in side cal_stock_revenue() function
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
year_dict = dict(zip(month, month_days)) # Dictionary containing corresponding day values for the months
rev_list = [705.00, 587.50, 587.5*1.05, 587.5*1.05*1.2] # List of quarterly revenue for the first year (2000)
qty_list = [36, 26.67, 29.7, 40.09] # List of quarterly unit quantity for year 2000
CRIS_RECUR_FREQUENCY = 9
years_in_crisis = 3 # No. of years the financial crisis lasts
NO_YEAR_SIM = 3
PER_DEF = 5
def_per = PER_DEF / 100 # Converting the PER_DEF to percentage
input_data_dict = read_data() # Reading the input and storing in a variable (input_data_dict is of Dictionary)
# Sending the dictionary as input to cal_stock_revenue and storing the dictionary in output_data_dict
output_data_dict = cal_stock_revenue(input_data_dict)
write_data(output_data_dict) # Writing the output to the file (AU_INV_END.TXT)
|
def modular(a,b,modulo):
if b == 0:
return 1
else:
result = modular(a,b//2,modulo)
if b&1 == 0:
return (result*result)%modulo
else:
return (result*a*result)%modulo
a = int(input())
b = int(input())
modulo = int(input())
print(modular(a,b,modulo))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.