text
stringlengths 37
1.41M
|
---|
input1=input("Enter a String: ")
def remove_odd_index(input1):
res=''
for i in input1[::2]:
res+=i
return res
val=remove_odd_index(input1)
print(val)
|
import math
from queue import Queue
# Spatial distance between two positions
def distance(pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
# Shortest path distance (BFS) between two positions on the board
def board_distance(pos1, pos2, board):
bfs_queue = Queue()
seen_set = set()
bfs_queue.put((pos1, 0))
seen_set.add(pos1)
actions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while not bfs_queue.empty():
curr_pos, dist = bfs_queue.get()
if curr_pos == pos2:
return dist
for action in actions:
dx, dy = action
x, y = curr_pos
# Note that here, we assume that pursuers can move to any
# non-obstacle space (i.e. that multiple pursuers can be at
# the same location)
next_pos = (x + dx, y + dy)
if next_pos not in seen_set and (board[x + dx][y + dy] != '|'):
bfs_queue.put((next_pos, dist + 1))
seen_set.add(next_pos)
return None
class Evader:
def __init__(self, x, y, board):
self.x = x
self.y = y
self.board = board
# decode action
def move(self, a):
if a == 1:
return -1, 0 # left
elif a == 2:
return 1, 0 # right
elif a == 3:
return 0, -1 # down
elif a == 4:
return 0, 1 # up
return 0, 0 # invalid action
# action
def action(self, a):
dx, dy = self.move(a)
if (self.board[self.x + dx][self.y + dy] != '|'):
self.x += dx
self.y += dy
# try action but don't actually update the evader's position
def try_action(self, a):
dx, dy = self.move(a)
x = self.x
y = self.y
if (self.board[self.x + dx][self.y + dy] != '|'):
x += dx
y += dy
return x, y
# policy
# The evader takes the action that would maximizes the distance
# to the closest pursuer
def policy(self, pursuer_positions):
actions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
max_distance = None
max_distance_action = None
for a in range(1, 5):
# Try each action
x, y = self.try_action(a)
min_pursuer_distance = None
# Compute distance to closest pursuer after taking the action
for pursuer_position in pursuer_positions:
dist_pursuer = distance(pursuer_position, (x, y))
# dist_pursuer = board_distance(pursuer_position, (x, y), self.board)
if min_pursuer_distance is None or dist_pursuer < min_pursuer_distance:
min_pursuer_distance = dist_pursuer
# Update maximum distance to closest pursuer and corresponding action
if max_distance is None or min_pursuer_distance > max_distance:
max_distance = min_pursuer_distance
max_distance_action = a
return max_distance_action
# return postion of the evader
def getPos(self):
return self.x, self.y
# print current position
def print(self):
print(self.x, self.y)
|
import pickle
import struct
f = open('Stu.txt','w')
n = input('Please input the number of stus:')
s = struct.pack('i',n)
f.write(s)
s2 = 'Number Name High Level Maths Lineral Math Computer Introduction'
print len(s2)
f.write(s2)
i = 0
while i < n:
num = input('Please input No.' + str(i+1) + 's number(11 bits):')
name = input('Please input No.' + str(i+1) + 's name(3 words):')
hlm = input('Please input No.' + str(i+1) + 's High level Maths:')
lm = input('Please input No.' + str(i+1) + 's Lineral Math:')
ci = input('Please input No.' + str(i+1) + 's CI:')
s = int(num) + str(name)
s = s + struct.pack('fff',hlm,lm,ci)
f.write(s)
i = i + 1
f.close()
|
#yield2
rows = [3,17]
def cols():
yield 56
yield 2
yield 1
r = ((i,j) for i in rows for j in cols())
for e in r :
print e
#ļwri,''te
import os
f = open('h.txt','w+')
x = ['1\n','2\n','3\n','4\n','5\n','6\n']
#for e in x :
# f.write(e+os.linesep)
f.writelines(x)
f.close()
#argvargc鿴
import sys
print 'you enter ', len(sys.argv), 'arguments'
print 'they are ' , str(sys.argv)
#osos.path ģʾıдݡļݡĿ¼ļ·
import os
for tmp in ('/tmp',r'c:\tmp') :
if os.path.isdir(tmp):
break
else :
print 'no temp directory available'
tmp = ''
if tmp :
os.chdir(tmp)
c = os.getcwd()
print '*** current temporary directory ***'
print c
print '*** creating example directionary ***'
os.mkdir('example')
os.chdir('example')
c = os.getcwd()
print '*** new working directory ***'
print c
print '*** original directory listing ***'
print os.listdir(c)
print '*** creating test file ***'
f = open('test','w')
f.write('f\n')
f.write('u\n')
f.write('c\n')
f.write('k\n')
f.close()
print '*** updated directory listing ***'
print os.listdir(c)
print "*** renaming 'test' to 'filetest.txt'"
os.rename('test','filetest')
print '*** updated directory listing ***'
print os.listdir(c)
path = os.path.join(c,os.listdir(c)[0])
print '*** full file pathname ***'
print path
print '*** (pathname,basename) == ***'
print os.path.split(path)
print '*** (filename,extension) == ***'
print os.path.splitext(os.path.basename(path))
print '*** displaying file contents ***'
f = open(path)
for e in f :
print e
f.close()
print '*** deleting test file ***'
os.remove(path)
print '*** updated directory listing ***'
print os.listdir(c)
os.chdir(os.pardir)
print '*** deleting test directory ***'
os.rmdir('example')
print '*** done ***'
|
# -*- coding:utf-8 -*-
'''最短子数组
对于一个数组,请设计一个高效算法计算需要排序的最短子数组的长度。
给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的长度。(原序列位置从0开始标号,若原序列有序,返回0)。保证A中元素均为正整数。
测试样例:
[1,4,6,5,9,10],6
返回:2
'''
class Subsequence:
def shortestSubsequence(self, A, n):
# write code here
minA = 0
right = 0
for i in range(n):
if A[i] > minA:
minA = A[i]
elif A[i] < minA:
right = i
maxA = 100000
left = n-1
for i in range(n-1, -1, -1):
if A[i] < maxA:
maxA = A[i]
elif A[i] > maxA:
left = i
return max(right-left+1, 0)
|
def sum(numbers):
total = 0
for x in range(0, len(numbers)):
total = total + numbers[x]
return total
def dot_product(A, B):
dot = []
if len(A) == len(B):
for x in range(0, len(A)):
num = A[x] * B[x]
dot.append(num)
else:
return None
return sum(dot)
|
# 1B1.py
# Sandis Mālnieks 193RIC058
from numpy import * # Importē skaitlisko metožu bibliotēkas funkcijas
from matplotlib import pyplot as plt
x = linspace(0, 7, 70) # Trešais arguments ir ģenerējamo elementu skaits
y = sin(x)
plt.grid()
plt.xlabel('x')
plt.ylabel('f(x)')
plt.title('Funkcija $sin(x)$')
plt.plot(x, y, color = "#006400")
y = x # f(x) = x
plt.plot(x, y)
y = x - pow(x,2)/math.factorial(3)
plt.plot(x, y)
y = x - pow(x,2)/math.factorial(3)+pow(x,5)/math.factorial(5)
plt.plot(x, y)
y = x - pow(x,2)/math.factorial(3)+pow(x,5)/math.factorial(5)-pow(x,7)/math.factorial(7)
plt.plot(x, y)
plt.show()
|
from numpy import exp,array,random,dot
def sigmoid(x,derivative=False):
if derivative==True:
return x*(1-x)
return 1/(1+exp(-x))
if __name__ == '__main__':
training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
training_set_outputs = array([[0, 1, 1, 0]]).T
random.seed(1)
synaptic_weights0 = 2*random.random((3,1)) - 1
print(synaptic_weights0)
l1=[]
for i in range(600000):
l0=training_set_inputs
l1=sigmoid(dot(l0,synaptic_weights0))
#print("l1 ",l1)
error=(training_set_outputs-l1)
#print("error",error*sigmoid(l1,True))
adjust=dot(l0.T,error*sigmoid(l1,True))
#print('adjust',adjust)
synaptic_weights0+=adjust
if i%100000==0:
print("new synaptic_weights0 ",synaptic_weights0)
print(l1)
|
"""
Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Please implement encode and decode
"""
class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single string.
"""
"""
word -> :;
: -> ::
"""
def encode(self, strs):
# write your code here
encodes = []
for str1 in strs:
if str1 == ':':
encodes.append('::')
else:
encodes.append(str1)
encodes.append(':;')
return "".join(encodes)
"""
@param: str: A string
@return: dcodes a single string to a list of strings
"""
def decode(self, str):
# write your code here
strs = []
decode = []
i = 0
while i < len(str) - 1:
if str[i] == ':':
if str[i + 1] == ':':
strs.append(str[i])
i += 2
elif str[i + 1] == ';':
strs.append("".join(decode))
decode = []
i += 2
else:
decode.append(str[i])
i += 1
return strs
|
"""
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
"""
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
dir = {}
for i in words:
if i in dir:
dir[i] += 1
else:
dir[i] = 1
heap = []
# heapq.heapify(heap)
for key in dir:
heapq.heappush(heap, (-dir[key], key))
aws = []
for i in range(k):
aws.append(heapq.heappop(heap)[1])
# aws.sort()
return aws
|
x = 0
def a():
x = 0
x +=1
print x
print "a"
x +=1
print x
yield 99
x +=1
print x
print "a2"
x +=1
print x
yield 98
x +=1
print x
b = a()
b
#print x
print "``````````"
print b.next()
#print x
#b.next()
#print x
print b
print "``````````"
for i in b:
print i
|
import math
def odd(n):
return n % 2 == 1
def generate_odd():
n = 3
while True:
yield n
n = n + 2
count = 1
prime_list = [2,]
for candidate_prime in generate_odd():
is_prime = True
for test in prime_list:
if test > math.sqrt(candidate_prime):
break
else:
if candidate_prime % test == 0:
is_prime = False
if is_prime == True:
prime_list.append(candidate_prime)
count = count + 1
if count >= 1000:
break
for item in prime_list:
print item,
|
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
h = {}
i = 0
for num in nums:
n = target - num
if n not in h:
h[num] = i
i+=1
else:
return [h[n],i]
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums,target))
|
'''
96. Unique Binary Search Trees
Question: https://leetcode.com/problems/unique-binary-search-trees/
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Solution: Dynamic Programming
- DP[i] = Number of structures using i nodes
- Given a root node, all values < root goes to the left half and all values > root goes to the right half
- Hence for example #nodes = 4, #nodes for left subtree and right subtree can be (0, 3), (1, 2), (2, 1) and (3, 0)
- here 0 corresponds to empty tree
- Hence dp[4] = dp[3]*dp[0]+dp[2]*dp[1]+dp[1]*dp[2]+dp[0]*dp[3]
Created on Jun 1, 2019
@author: smaiya
'''
class Solution:
def numTrees(self, n):
dp = [0 for i in range(n+1)]
dp[0]=dp[1]=1
for i in range(2, n+1):
for j in range(i):
dp[i] += dp[j]*dp[i-1-j]
return dp[n]
|
'''
394. Decode String
Question: Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times.
Note that k is guaranteed to be a positive integer.
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
Solution: Use stack
Created on May 12, 2019
@author: smaiya
'''
class Solution:
def decodeString(self, s):
num, pattern = '', ''
num_stack, pattern_stack = [], []
for c in s:
if c.isdigit():
num+=c
if c.isalpha():
pattern+=c
if c=='[':
num_stack.append(num)
pattern_stack.append(pattern)
num, pattern = '', ''
if c==']':
n = num_stack.pop()
p = pattern_stack.pop()
pattern = p+pattern*int(n)
return pattern
|
'''
Inorder traversal
def inorderTraversal(self, A):
if A is None:
return None
self.inorderTraversal(A.left)
self.inorderTraversal.append(A.val)
self.inorderTraversal(A.right)
return self.postorderList
Created on Jul 3, 2018
@author: smaiya
'''
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return a list of integers
def inorderTraversal(self, A):
stack = []
node = A
inOrder_list = list()
while stack or node:
if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
inOrder_list.append(node.val)
node = node.right
return inOrder_list
a = Solution()
node1, node2, node3, node4, node5 = TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4), TreeNode(5)
node6, node7, node8, node9 = TreeNode(6), TreeNode(7), TreeNode(8), TreeNode(9)
node1A, node2A, node3A, node4A, node5A = TreeNode(1), TreeNode(2), TreeNode(3), TreeNode(4), TreeNode(5)
node6A, node7A, node8A, node9A = TreeNode(6), TreeNode(7), TreeNode(8), TreeNode(9)
root = node4
node4.left = node2
node4.right = node6
node2.left = node1
node2.right = node3
node6.right = node7
node3.right = node9
out = a.inorderTraversal(root)
print('In Order Traversal = ', out)
|
'''
3. Longest Substring Without Repeating Characters
Q: Longest Substring Without Repeating Characters
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Solution: Store the latest index of the character in a hasmap
If new letter is present in the hashmap, then update the start of substring.
Update the max length and hashmap
Solution 2: Store the current sub string in hashmap and its index as value.
If new letter is present in the hashmap, then remove all the letters that came before that letter from the hashmap
'''
class Solution:
# @param A : string
# @return an integer
def lengthOfLongestSubstring(self, s):
ans, start, n = 0, 0, len(s)
map = dict()
for i, char in enumerate(s):
if char in map:
start = max(start, map[char])
ans = max(ans, i-start+1)
map[char] = i+1
return ans
def lengthOfLongestSubstring_2(self, A):
curr_len, max_len = 0, 0
substring_char = dict()
for i, char in enumerate(A):
print (substring_char, char, curr_len, max_len)
if char in substring_char:
to_remove = A[i-curr_len:substring_char[char]]
curr_len -= len(to_remove)
for char_to_remove in to_remove:
if char_to_remove in substring_char:
del substring_char[char_to_remove]
else:
curr_len += 1
max_len = curr_len if curr_len>max_len else max_len
substring_char[char] = i
return max_len
a = Solution()
inp = 'abcabcbb'
inp = 'bbbbbbb'
inp = 'abcbxysz'
inp = 'abcddaxybs'
inp = 'bbtablud'
#inp = ' '
#inp = 'aaaaaa cbd'
#inp = 'abcdefeabcds'
op = a.lengthOfLongestSubstring(inp)
print ('Length of Longest Substring = ', op)
|
'''
61. Rotate List
Given the head of a linked list, rotate the list to the right by k places.
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Input: head = [0,1,2], k = 4
Output: [2,0,1]
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def rotateRight(self, A, B):
if A is None:
return A
n = 0
Atemp = A
while Atemp:
n+=1
Atail = Atemp
Atemp = Atemp.next
rotate = B%n
if rotate ==0:
return A
Atemp = A
count = 1
while count<n-rotate:
Atemp = Atemp.next
count+=1
A_right_shift = Atemp.next
Atemp.next = None
Atail.next = A
return A_right_shift
class LinkedList:
def __init__(self, head=None):
self.head = head
def add_node(self, data):
new_node = ListNode(data)
new_node.next = self.head
self.head = new_node
def list_print(self):
node = self.head
while node:
print(node.val)
node = node.next
a = Solution()
(input, n) = ([5, 4, 3, 2 ,1], 2)
(input, n) = ([5, 4, 3, 2 ,1], 0)
(input, n) = ([5, 4, 3, 2 ,1], 5)
(input, n) = ([5, 4, 3, 2 ,1], 8)
ll = LinkedList()
for i in input:
ll.add_node(i)
print ("Input LL: ")
ll.list_print()
output = a.rotateRight(ll.head, n)
print ("Output LL: ")
while output != None:
print(output.val)
output = output.next
|
'''
56. Merge Intervals
Question: Given a collection of intervals, merge all overlapping intervals.
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18]
Solution:
- Sort the interval based on the interval start
- Starting from the first interval, keep checking if it overlaps with the following intervals
and merge them.
- Add the merged interval to the output list the moment an interval doesnt overlap with
the current merged interval
- If interval i doesnt overlap with i-1, then i+1 doesnt overlap either
Created on Jun 30, 2018
@author: smaiya
'''
# Definition for an interval.
class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution:
# @param intervals, a list of Intervals
# @return a list of Interval
def merge(self, intervals):
sorted_intervals = sorted(intervals, key=lambda interval:interval.start, reverse=False)
merged_intervals = list()
first = True
for interval in sorted_intervals:
if first:
curr_start, curr_end, first = interval.start, interval.end, False
continue
if interval.start <= curr_end:
curr_end = interval.end if interval.end>curr_end else curr_end
else:
new_interval = Interval(curr_start, curr_end)
merged_intervals.append(new_interval)
curr_start, curr_end = interval.start, interval.end
new_interval = Interval(curr_start, curr_end)
merged_intervals.append(new_interval)
return merged_intervals
a = Solution()
inp = list()
inp.append(Interval(1, 3))
inp.append(Interval(2, 7))
inp.append(Interval(3, 5))
inp.append(Interval(1, 2))
inp.append(Interval(9, 10))
inp.append(Interval(12, 16))
inp.append(Interval(13, 15))
inp.append(Interval(12, 14))
inp.append(Interval(21, 22))
out = a.merge(inp)
print('Merged Invervals: ')
for interval in out:
print ('[', interval.start, interval.end, ']')
|
'''
Created on Jun 30, 2018
Given an array, find the nearest smaller element G[i] for every element A[i] in the array
such that the element has an index smaller than i.
Input : A : [4, 5, 2, 10, 8]
Return : [-1, 4, -1, 2, 2]
Input : A : [3, 2, 1]
Return : [-1, -1, -1]
@author: smaiya
'''
class Solution:
# @param A : list of integers
# @return a list of integers
def prevSmaller(self, A):
n = len(A)
prev_smaller = None
for i in range(n):
# Initialize the first element as -1
if prev_smaller is None:
prev_smaller = [-1]
else:
# If previous element is smaller, then prev_smaller[i] = A[i-1]
if A[i] > A[i-1]:
prev_smaller.append(A[i-1])
else:
# Else, search in the prev_smaller list for the next smaller element
count = i-1
while prev_smaller[count] != -1 and prev_smaller[count]>=A[i]:
count-=1
prev_smaller.append(prev_smaller[count])
return prev_smaller
a = Solution()
inp = [4, 5, 2, 10, 8]
inp = [3, 2, 1]
inp = [4, 2, 1, 7, 6, 8, 7, 5]
inp = [7, 1, 4, 8, 3, 2, 5, 9, 8]
inp = [1, 1, 1, 1]
inp = [8, 23, 22, 16, 22, 7, 7, 27, 35, 27, 32, 20, 5, 1, 35, 28, 20, 6, 16, 26, 48, 34 ]
out = a.prevSmaller(inp)
print ('Nearest Smaller Element = ', out)
|
'''
399. Evaluate Division
Question: Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number).
Given some queries, return the answers. If the answer does not exist, return -1.0
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].
Solution:
- Store the equations as a graph.
- Each node connected to its denominator with the quotient stored as the value
- For each a/b, also store b/a
- Additionally store a self loop to check for a/a = 1
- To get the answer for the query, start with the numerator and do a breadth first search till you reach the denominator (keeping track of visited nodes)
- Store the cumulative product and push it to the queue along with the node
Created on May 7, 2019
@author: smaiya
'''
class Solution:
def calcEquation(self, equations, values, queries):
# Create the division table
table = {}
for eq, val in zip(equations, values):
num, den, ans = eq[0], eq[1], val
# Storing a/b
if num in table:
table[num].append([den, ans])
else:
table[num] = [[den, ans]]
# Storing b/a
if den in table:
table[den].append([num, 1/ans])
else:
table[den] = [[num, 1/ans]]
# Storing a/a
for var in table:
table[var].append([var, 1.0])
solution = [-1 for i in range(len(queries))]
for idx, q in enumerate(queries):
visited = {}
# Eliminating x/x queries if x is not provided among the equations
if q[0] not in table:
continue
queue = [[q[0], 1.0]]
while queue:
node, val = queue.pop(0)
visited[node]=1
if node==q[1]:
solution[idx]=val
break
for den, quotient in table[node]:
if den not in visited:
queue.append([den, val*quotient])
return solution
|
'''
743. Network Delay Time
Question:
There are N network nodes, labelled 1 to N.
Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node,
v is the target node, and w is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.
Solution: Use Dijkstra Algorithm with Heap (min heap)
- Maintain visited node list and the corresponding time to travel to that node
- Pop the node with the smallest time (top node of the heap) and extend it to all its neighbors and add those to the heap
Created on May 8, 2019
@author: smaiya
'''
from collections import defaultdict
import heapq
class Solution:
def networkDelayTime(self, times, N, K):
network = defaultdict(list)
for t in times:
network[t[0]].append([t[1], t[2]])
heap = [(0, K)]
visited = {}
while heap:
t, node = heapq.heappop(heap) # Pop the node at the top of the heap with minimum travel time
if node not in visited:
visited[node] = t
for dest in network[node]:
heapq.heappush(heap, (t+dest[1], dest[0])) # Add all values into the heap. Only the node with minimum time will be considered
return max(visited.values()) if len(visited)==N else -1
|
'''
Sadhana Amazon Assessment: 6/1/2018
Question: find the most frequented word excluding words from 'ignore_list'
'''
import re
class Solution:
# @param A : integer
# @return an integer
def mostFrequentWord(self, A, B):
exclude_map = dict()
for words in B:
exclude_map[words.lower()] = 1
literature_map = dict()
inp_word_list = re.split('[^a-zA-Z]+', A)
max_count = 0
for words in inp_word_list:
words = words.lower()
if words not in exclude_map:
literature_map[words] = literature_map.get(words, 0)+1
max_count = max(max_count, literature_map[words])
most_frequent_word_list = list()
for words in literature_map:
if literature_map[words] == max_count:
most_frequent_word_list.append(words)
return most_frequent_word_list
a = Solution()
inp1 = 'Jack and jill went to the market to get some cheese. Jack\'s and Jill\'s cheese is tasty'
inp2 = ['is', 'a', 'are', 'to']
str = a.mostFrequentWord(inp1, inp2)
print ('Most Frequent Word = ', str)
|
'''
Question: Number of inversions (swaps) required to make the array sorted
E.g., Input: [2, 4, 1, 3, 5] Output = 3
Solution: Dynamic Programming. O(nlogn) for sorting
- D(n) = D(n-1) + x
where D(n) = number of swaps required to make the first n array sorted
x = number of elements in the (n-1) elements that are greater than x
- Maintain a sorted array of (n-1). Inserting the n-th element = O(log n)
'''
class Solution:
# @param A : list of integers
# @return an integer
def countInversions(self, A):
n = len(A)
A_sorted = [];
num_inversions = 0
A_sorted.append(A[0])
for idx in range(1, n):
num_inversions += len([1 for i in A_sorted if i>A[idx]]) # Can be optimized to run in log N using Binary Search
A_sorted.append(A[idx])
A_sorted.sort()
return num_inversions
a = Solution()
#inp = [3, 2, 1, 0, 4, 6, 7, 8, 10]
#inp = [1, 3, 6, 7, 2, 11, 13, 12, 5, 2, 3, 4]
inp = [2, 4, 1, 3, 5]
#inp = [2, 1, 1, 1, 1]
str = a.countInversions(inp)
print ('Number of Inversions = ', str)
|
'''
128. Longest Consecutive Sequence
# Uber Phone Interview 6/28/2018
Given an unsorted array of integers nums, return the length of the longest
consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Solution:
- Use a Hashmap.
- For each number as key, store start and end values of the interval it falls to
- Update the start and end every time a number is added to the interval
Better Solution:
- Store all array elements in a hashmap
- For all elements in the array arr[i]
- Check if it is the starting point of an interval (or subsequence) by checking
if arr[i]-1 is present in the hash map
- if true, then keep checking if arr[i]+1, 2.. are present in the hashmap and thereby
maintaining a the interval count
'''
class Solution:
# @param A : list of integers
# @return an integer
def longestConsecutive(self, A):
n = len(A)
if n <= 1:
return n
numbers = dict()
max_range = 0
for num in A:
if num not in numbers:
start = numbers[num-1][0] if num-1 in numbers else num
end = numbers[num+1][1] if num+1 in numbers else num
numbers[start] = numbers[end] = numbers[num] = [start, end]
curr_range = end-start+1
max_range = curr_range if curr_range>max_range else max_range
return max_range
a = Solution()
inp = [3, 2, 1, 0, 4, 6, 7, 8, 10]
inp = [1, 3, 6, 7, 2, 11, 13, 12, 5, 2, 3, 4]
str = a.longestRange(inp)
print ('Longest Range = ', str)
|
'''
871. Minimum Number of Refueling Stops
Question: A car travels from a starting position to a destination which is target miles east of the starting position.
Along the way, there are gas stations. Each station[i] represents a gas station that is station[i][0] miles east of the
starting position, and has station[i][1] liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it.
It uses 1 liter of gas per 1 mile that it drives.When the car reaches a gas station, it may stop and refuel, transferring all
the gas from the station into the car.
What is the least number of refueling stops the car must make in order to reach its destination?
If it cannot reach the destination, return -1.
Solution:
- When driving past a gas station, store all the fuel capacity.
- Upon running out of fuel, fill from the the largest gas station that we have passed
- Use max_heap to store the fueling capacity of each station that we pass
- Keep track of the the 'tank', the current fuel. Once we reach a station but have negative fuel,
add capacities of the largest gas stations that we have driven past until the tank is > 0
- If this process fails, then retun -1
Created on May 27, 2019
@author: smaiya
'''
import heapq
class Solution:
def minRefuelStops(self, target, startFuel, stations):
max_heap = []
stations.append([target, float('Inf')]) # Adding the target station that we have to drive to
stops = 0 # Number of station stops for refueling
prev = 0
tank = startFuel
for location, fuel in stations:
tank -= (location-prev) # Each station, update the tank (current fuel content)
while tank<0 and max_heap: # If we run out of fuel, fill starting from the largest gas station that we have passed
tank+=-heapq.heappop(max_heap)
stops+=1
if tank<0: # Inspite of refueling from all gas stations we have passed by, if we still have <0 tank then return -1
return -1
heapq.heappush(max_heap, -fuel) # Store the station capacity in a max_heap that we are passing by
prev = location
return stops
|
'''
121. Best Time to Buy and Sell Stock
Question: What is the max profit you can make given the price array of a stock
E.g., A = [2, 1, 10, 9, 2, 6, 5] ==> Answer = 10-1 = 9
Solution: Dynamic Programming
Dn = max profit at time n
Dn+1 = max(Dn, x(n+1) - curr_min)
'''
class Solution:
def maxProfit(self, A):
n = len(A)
if n<2:
return 0
max_profit = 0
Dn = max(max_profit, A[1]-A[0])
D1 = Dn
min_price = min(A[1], A[0])
for i in range(2, n):
Dn = max(D1, A[i]-min_price)
D1 = Dn
min_price = min(min_price, A[i])
return Dn
a = Solution()
inp = [2, 1, 2, 9, 2, 6, 5]
inp = [5, 3, 2, 1]
inp = [5, 4, 1, 2, 2, 5]
inp = [5, 4]
inp = [4, 5]
inp = [5, 4, 6]
str = a.maxProfit(inp)
print ('Max Profit = ', str)
|
'''
2049. Count Nodes With the Highest Score
There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1.
You are given a 0-indexed integer array parents representing the tree, where parents[i]
is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a score. To find the score of a node, consider if the node and the edges
connected to it were removed. The tree would become one or more non-empty subtrees.
The size of a subtree is the number of the nodes in it. The score of the node is the
product of the sizes of all those subtrees.
Return the number of nodes that have the highest score.
Input: parents = [-1,2,0,2,0]
0
/ \
2 4
/ \
3 1
Output: 3
Explanation:
- The score of node 0 is: 3 * 1 = 3
- The score of node 1 is: 4 = 4
- The score of node 2 is: 1 * 1 * 2 = 2
- The score of node 3 is: 4 = 4
- The score of node 4 is: 4 = 4
The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.
Solution:
- Post order traversal since child nodes are processed before parent nodes
- dfs returns the number of nodes in the subtree
- if node is leaf node, then score = total number of nodes in the tree - 1
- if node is root, then score = num nodes in left tree * num nodes in right tree
- for any other node, score = num nodes in left tree * num nodes in right tree * num rest of the nodes - 1
Created on June 11, 2022
@author: smaiya
'''
import math
class Solution:
def countHighestScoreNodes(self, parents):
self.max_score = 0
self.count = 0
self.children = {}
self.n = len(parents)
for i, p in enumerate(parents):
if p>=0:
if p in self.children:
self.children[p].append(i)
else:
self.children[p] = [i]
self.dfs(0)
return self.count
def dfs(self, node):
children = self.children[node] if node in self.children else []
subtree_size = []
for c in children:
n = self.dfs(c)
subtree_size.append(n)
if children:
rest_size = self.n - sum(subtree_size) - 1
subtree_prod = math.prod(subtree_size)
score = subtree_prod if node==0 else rest_size * subtree_prod
else:
score = self.n-1
if score > self.max_score:
self.max_score, self.count = score, 1
elif score==self.max_score:
self.count+=1
return sum(subtree_size)+1
parents = [-1,2,0,2,0]
ans = Solution().countHighestScoreNodes(parents)
print('Count highest score nodes = ', ans)
|
'''
Preorder Traversal
def preorderTraversal(self, A):
if A is None:
return None
self.preOrderList.append(A.val)
self.preorderTraversal(A.left)
self.preorderTraversal(A.right)
return self.preOrderList
Created on Jul 3, 2018
@author: smaiya
'''
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return a list of integers
def __init__(self):
self.preOrderList = list()
def preorderTraversal(self, A):
if A is None:
return None
preOrderList = [];
stack = [A]
while stack:
curr_node = stack.pop()
preOrderList.append(curr_node.val)
if curr_node.right:
stack.append(curr_node.right)
if curr_node.left:
stack.append(curr_node.left)
return preOrderList
# Preorder traversal using recursion
def preorderTraversal_recursive(self, A):
if A is None:
return None
self.preOrderList.append(A.val)
self.preorderTraversal_recursive(A.left)
self.preorderTraversal_recursive(A.right)
return self.preOrderList
a = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
out = a.preorderTraversal(root)
print('Preorder Traversal: ', out)
|
'''
Created on Jul 7, 2018
shortest unique prefix to represent each word in the list.
Input: [zebra, dog, duck, dove]
Output: {z, dog, du, dov}
This is a tree question. Can be solved using Trie.
@author: smaiya
'''
class Solution:
# @param A : list of strings
# @return a list of strings
def prefix(self, A):
prefix_dict = dict()
for word in A:
n = len(word)
for i in range(n):
prefix_dict[word[:i+1]] = prefix_dict.get(word[:i+1], 0)+1
shortest_prefix = [];
for word in A:
n = len(word)
for i in range(n):
if prefix_dict[word[:i+1]] == 1:
shortest_prefix.append(word[:i+1])
break
return shortest_prefix
a = Solution()
inp = ['zebra', 'dog', 'duck', 'dove']
str = a.prefix(inp)
print ('Shortest Unique Prefix = ', str)
|
'''
147. Insertion Sort List
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs
within the sorted list and inserts it there.
It repeats until no input elements remain.
Input: head = [4,2,1,3]
Output: [1,2,3,4]
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def insertionSortList(self, A):
if A.next is None:
return A
Ahead, Asort_prev, Asort = A, A, A.next
while Asort:
Atemp = Ahead
if Atemp.val > Asort.val:
Asort_prev.next = Asort.next
Asort.next = Atemp
Ahead = Asort
Asort = Asort_prev.next
else:
while Atemp.next != Asort and Atemp.next.val<Asort.val:
Atemp = Atemp.next
if Atemp.next == Asort:
Asort_prev = Asort
Asort = Asort.next
else:
Asort_prev.next = Asort.next
Asort.next = Atemp.next
Atemp.next = Asort
Asort = Asort_prev.next
return Ahead
class LinkedList:
def __init__(self, head=None):
self.head = head
def add_node(self, data):
new_node = ListNode(data)
new_node.next = self.head
self.head = new_node
def list_print(self):
node = self.head
while node:
print(node.val)
node = node.next
a = Solution()
input = [4, 2, 7, 8, 1, 3, 5, 6]
#input = [3, 5, 6]
input = [4, 4, 7, 1, 1, 3, 5, 6]
ll = LinkedList()
for i in input:
ll.add_node(i)
print ("Input LL: ")
ll.list_print()
output = a.insertionSortList(ll.head)
print ("Output LL: ")
count = 0
while output != None and count < 10:
print(output.val)
output = output.next
count+=1
|
'''
287. Find the Duplicate Number
Question: https://leetcode.com/problems/find-the-duplicate-number/
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist.
Assume that there is only one duplicate number, find the duplicate one.
Input: [1,3,4,2,2]
Output: 2
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- There is only one duplicate number in the array, but it could be repeated more than once.
Solution: Floyd's Tortoise and Hare (Cycle Detection)
- Identical to finding entrance of the linked list cycle algorithm
- First use a slow and a fast pointer to find the intersection location
- Then find the entrance to the cycle by continuing the slow pointer and using a new pointer which starts from the beginning
Created on Jun 1, 2019
@author: smaiya
'''
class Solution:
def findDuplicate(self, nums):
if not nums:
return
slow, fast = nums[0], nums[0]
while True:
slow=nums[slow]
fast=nums[nums[fast]]
if slow==fast:
break
# Finding the entrance to the cycle
ptr1, ptr2 = nums[0], slow
while ptr1!=ptr2:
ptr1, ptr2 = nums[ptr1], nums[ptr2]
return ptr1
|
'''
131. Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
A palindrome string is a string that reads the same backward as forward.
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Solution
- Use dfs
- Start searching for a palindrome from the start
- If found add it into a temp list and search for the next starting from the next index
- Add the temp list into the final result array if the string ending with the last index is a palindrome
Created on July 18, 2022
@author: smaiya
'''
from typing import Dict, Any, List
from collections import defaultdict
class Solution:
def partition(self, s: str) -> List[List[str]]:
self.result = []
self.n = len(s)
self.dfs(s, 0, [])
return self.result
def is_palindrome(self, s):
for i in range(len(s)):
if s[i] != s[len(s)-i-1]:
return False
return True
def dfs(self, s, idx, temp_result):
if idx==self.n:
self.result.append(temp_result.copy())
return
for i in range(idx+1, self.n+1):
sub = s[idx:i]
if self.is_palindrome(sub):
temp_result.append(sub)
self.dfs(s, i, temp_result)
temp_result.pop()
s = "aab"
ans = Solution().partition(s)
|
'''
2265. Count Nodes Equal to Average of Subtree
Given the root of a binary tree, return the number of nodes where the value of the node
is equal to the average of the values in its subtree.
Note:
The average of n elements is the sum of the n elements divided by n and
rounded down to the nearest integer.
Input: root = [4,8,5,0,1,null,6]
4
/ \
8 5
/ \ \
0 1 6
Output: 5
Explanation:
For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
For the node with value 0: The average of its subtree is 0 / 1 = 0.
For the node with value 1: The average of its subtree is 1 / 1 = 1.
For the node with value 6: The average of its subtree is 6 / 1 = 6.
Solution:
- Post order traversal processing the child nodes before parent nodes
- dfs returns total and the number of nodes in the subtree
- calculate the average of the subtree = sum of total of the child nodes/number of nodes in the subtree
Created on June 11, 2022
@author: smaiya
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def averageOfSubtree(self, root):
if root is None:
return 0
self.result = 0
self.dfs(root)
return self.result
def dfs(self, node):
if node is None:
return 0, 0
left_total, left_n = self.dfs(node.left)
right_total, right_n = self.dfs(node.right)
total = left_total + right_total + node.val
n = left_n + right_n + 1
avg = total // n
if avg == node.val:
self.result+=1
return total, n
|
'''
162. Find Peak Element
Question:
A peak element is an element that is greater than its neighbors. Idx 0 and n-1 have just 1 neighbor
Given an input array nums, where nums[i] != nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -infty. ==> There definitely is a peak element
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
Solution: Binary Search in O(logn)
- Go to mid index. If nums[mid] > nums[mid+1], then there is a peak in the left half, hence hi=mid
Created on Apr 7, 2019
@author: smaiya
'''
class Solution:
def findPeakElement(self, nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = lo + hi >> 1
if nums[mid] > nums[mid+1]: hi = mid
else: lo = mid + 1
return lo
|
from datetime import date
from datetime import datetime
today = date.today()
dateList = []
# User story 1 - all dates should be before current date
def DatebeforeCurrentDate(indi, fam):
print("User story 1 - All dates should be before current date")
print(" ")
for i in indi:
# Checking death dates are before current dates and NA
if str(i["DEAT"]) == "NA":
pass
elif i["DEAT"].date() > today:
print(" Wrong death dates ")
# Checking for Birth dates are before current Date
if str(i["BIRT"]) == "NA":
pass
elif i["BIRT"].date() > today:
print(" These dates are after the current date: " + str(i["NAME"]) + str(i["BIRT"].date()))
for j in fam:
if j["MARR"].date() > today:
print(" Marriage date " + str(j["MARR"].date()) + " cannot be after current date " + str(today))
if str(j["DIV"]) == "NA":
pass
elif j["DIV"].date() > today:
print(" Divorce date " + str(j["DIV"].date()) +" cannot be after the current date " + str(today))
print(" ")
print(" User stroy 1 ends ")
print(" ")
# User story 10 - Marriage should be after 14 years of age
def MarriageAfter14(indi, fam):
print("User story 10 - Marriage should be after 14 years of age")
print(" ")
for j in fam:
for i in indi:
if i["INDI"] == j["WIFE"]:
days = 365.2425
age = int(((j["MARR"].date()) - (i["BIRT"].date())).days / days)
if age > 14:
pass
else:
print("Invalid marriage date ")
if i["INDI"] == j["HUSB"]:
days = 365.2425
age = int(((j["MARR"].date()) - (i["BIRT"].date())).days / days)
if age > 14:
pass
else:
print(" Invalid marriage date ")
print(" ")
print(" User story 10 Completed ")
print(" ")
|
import math
class Rectangle:
def __init__(self, a, b):
self.width = a
self.height = b
@property
def area(self):
return self.width * self.height
@area.setter
def area(self, value):
ratio = math.sqrt(value / self.area)
self.width = self.width * ratio
self.height = self.height * ratio
@property
def perimeter(self):
return 2 * (self.width + self.height)
@perimeter.setter
def perimeter(self, value):
ratio = value / self.area
self.width = self.width * ratio
self.height = self.height * ratio
rect = Rectangle(1, 5)
print(rect.width, rect.height, rect.area, rect.perimeter)
rect.area = 20
print(rect.width, rect.height, rect.area, rect.perimeter)
rect.perimeter = 40
print(rect.width, rect.height, rect.area, rect.perimeter)
|
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# sub list
sub_list = lst[1:8] # lst[1:-1]
print(sub_list)
# sub list w/ steps
sub_list = lst[1:8:2] # lst[1:-1:2]
print(sub_list)
sub_list = lst[8:1:-1]
print(sub_list)
sub_list = lst[::]
print(sub_list)
|
import math
class Square:
def __init__(self, a):
self.side = a
self.__area = self.side * self.side
@property
def area(self):
return self.__area
@area.setter
def area(self, value):
self.side = math.sqrt(value)
self.__area = self.side * self.side
sq1 = Square(10)
print(sq1.side, sq1.area)
sq1.area = 400
print(sq1.side, sq1.area)
|
import sqlite3
class Singleton:
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().__new__(cls)
cls.instance.initialized = False
return cls.instance
def __init__(self):
if not self.initialized:
self.conn = sqlite3.connect("./db.sqlite")
self.initialized = True
a = Singleton()
b = Singleton()
c = Singleton()
d = Singleton()
e = Singleton()
a.conn.execute("CREATE TABLE IF NOT EXISTS person (name TEXT, age INTEGER)")
b.conn.execute("INSERT INTO person (name, age) VALUES ('Jack', 24)")
c.conn.execute("INSERT INTO person (name, age) VALUES ('Joe', 30)")
rows = d.conn.execute("SELECT * FROM person")
for row in rows:
print(row)
|
text = "April is the cruelest month."
if len(text) % 2 == 0:
print(text.upper())
if len(text) % 2 == 1:
print(text.lower())
|
# Time complexity: O(n^2)
# Space Complexity: O(n)
# Algorithm: Sort the words and then for each word if the string upto previous character is in a set then place the word in the set.
# Sort the set and return max value (with min lexical order)
class Solution:
def longestWord(self, words: List[str]) -> str:
sorted_words = sorted(words)
word_set = set()
for i in sorted_words:
(len(i[:-1]) == 0 or (i[:-1] in word_set)) and word_set.add(i)
count = 0
result = ""
for i in sorted(word_set):
if len(i) > count:
result = i
count = len(i)
return result
|
#!/usr/bin/env python3
def word_stats(file_directory, num):
f = open(file_directory, "r")
contents = f.read()
list_of_things_in_txt = list(contents) #puts all the separate letters into a list
list_of_characters = []
for char in list_of_things_in_txt:
if char.isalnum() or char == " ": #if its a letter or number or space, append to new list
list_of_characters.append(char.lower())
all_words = ("".join(list_of_characters)) #join them back together as words using space as separator
all_word_list = all_words.split(" ") #split them back again into a list of actual words
count = {}
for word in all_word_list:
count[word] = count.get(word, 0) + 1 #dictionary to count the occurence of each word
sorted_descending_dictionary = sorted(count.items(), key=lambda x: x[1], reverse=True) #sort dictionary by descending order
return sorted_descending_dictionary[0:num] #return top 5 by splicing
if __name__ == "__main__":
print(word_stats("/Users/AaronKo/w1d2/article.txt", 5))
|
#programa que imprime todos os numeros pares de 0 a 20. Quando chegar no 5 parar o codigo
i= 0
while i <= 20:
print(i)
if (i == 5):
break
i += 1
|
h = ['head', 'body', 'left leg', 'right leg', 'left arm', 'right arm']
word = 'candy'
word_length = len(word)
dashes = ''
for i in word:
dashes += '- '
print(dashes)
u = input('Letter? ').lower()
while
if u.lower() in word:
print('True')
else:
print('You guessed wrong!')
print(h[0])
|
i=1
c=0
n=int(input("enter a number"))
while c<n:
f=0
j=1
while j<=i:
if i%j==0:
f=f+1
j=j+1
if f==2:
print(i)
c=c+1
i=i+1
|
#!/bin/env python
# Created on March 25, 2020
# by Keith Cherkauer
#
# This script serves as the solution set for assignment-10 on descriptive
# statistics and environmental informatics. See the assignment documention
# and repository at:
# https://github.com/Environmental-Informatics/assignment-10.git for more
# details about the assignment.
#
#Modified by Miriam Stevens
#May 04, 2020
#Modified from the template to calcualte monthly and annual stream flow metrics
#Calculates monthly and annual averages
#Saves annual and monthly metrics CSV files
#Saves annual and monthly averages to txt files
#
import pandas as pd
import scipy.stats as stats
import numpy as np
def ReadData( fileName ):
"""This function takes a filename as input, and returns a dataframe with
raw data read from that file in a Pandas DataFrame. The DataFrame index
should be the year, month and day of the observation. DataFrame headers
should be "agency_cd", "site_no", "Date", "Discharge", "Quality". The
"Date" column should be used as the DataFrame index. The pandas read_csv
function will automatically replace missing values with np.NaN, but needs
help identifying other flags used by the USGS to indicate no data is
availabiel. Function returns the completed DataFrame, and a dictionary
designed to contain all missing value counts that is initialized with
days missing between the first and last date of the file."""
# define column names
colNames = ['agency_cd', 'site_no', 'Date', 'Discharge', 'Quality']
# open and read the file
DataDF = pd.read_csv(fileName, header=1, names=colNames,
delimiter=r"\s+",parse_dates=[2], comment='#',
na_values=['Eqp'])
DataDF = DataDF.set_index('Date')
# quantify the number of missing values
MissingValues = DataDF["Discharge"].isna().sum()
MissingValues_dict = {'Missing Values': MissingValues}
# replace negative values with nan
DataDF.loc[DataDF['Discharge'] < 0, 'Discharge'] = np.NaN
return( DataDF, MissingValues )
def ClipData( DataDF, startDate, endDate ):
"""This function clips the given time series dataframe to a given range
of dates. Function returns the clipped dataframe and and the number of
missing values."""
#clip data
DataDF = DataDF.loc[startDate:endDate]
# quantify the number of missing values
MissingValues = DataDF["Discharge"].isnull().sum()
return( DataDF, MissingValues )
def CalcTqmean(Qvalues):
"""This function computes the Tqmean of a series of data, typically
a 1 year time series of streamflow, after filtering out NoData
values. Tqmean is the fraction of time that daily streamflow
exceeds mean streamflow for each year. Tqmean is based on the
duration rather than the volume of streamflow. The routine returns
the Tqmean value for the given data array."""
# count number of values greater than mean
vals_gt_mean = (Qvalues > Qvalues.mean()).sum()
Tqmean = vals_gt_mean / len(Qvalues)
return ( Tqmean )
def CalcRBindex(Qvalues):
"""This function computes the Richards-Baker Flashiness Index
(R-B Index) of an array of values, typically a 1 year time
series of streamflow, after filtering out the NoData values.
The index is calculated by dividing the sum of the absolute
values of day-to-day changes in daily discharge volumes
(pathlength) by total discharge volumes for each year. The
routine returns the RBindex value for the given data array."""
# absolute difference between values
Dtd_abs_diff = Qvalues.diff().abs()
# sum of differences
pathlength = Dtd_abs_diff.sum()
# total annual discharge
discharge_tot = Qvalues.sum()
RBindex = pathlength/discharge_tot
return ( RBindex )
def Calc7Q(Qvalues):
"""This function computes the seven day low flow of an array of
values, typically a 1 year time series of streamflow, after
filtering out the NoData values. The index is calculated by
computing a 7-day moving average for the annual dataset, and
picking the lowest average flow in any 7-day period during
that year. The routine returns the 7Q (7-day low flow) value
for the given data array."""
val7Q = Qvalues.rolling(7).mean().min()
return ( val7Q )
def CalcExceed3TimesMedian(Qvalues):
"""This function computes the number of days with flows greater
than 3 times the annual median flow. The index is calculated by
computing the median flow from the given dataset (or using the value
provided) and then counting the number of days with flow greater than
3 times that value. The routine returns the count of events greater
than 3 times the median annual flow value for the given data array."""
median_flow = Qvalues.median()
median3x = (Qvalues > 3*median_flow).sum()
return ( median3x )
def GetAnnualStatistics(DataDF):
"""This function calculates annual descriptive statistcs and metrics for
the given streamflow time series. Values are retuned as a dataframe of
annual values for each water year. Water year, as defined by the USGS,
starts on October 1."""
colNames = ['site_no','Mean Flow', 'Peak Flow', 'Median Flow', 'Coeff Var',\
'Skew', 'Tqmean', 'R-B Index', '7Q', '3xMedian']
# define index as dates of ressmpled data.
# data is resampled annually with end of year in September
annualIndex = DataDF.resample('AS-OCT').mean().index
# create empty dataframe
WYDataDF = pd.DataFrame(data=0, index=annualIndex, columns=colNames)
# resample data
WYData = DataDF.resample('AS-OCT')
#add metrics to dataframe
WYDataDF['site_no'] = WYData['site_no'].min()
WYDataDF['Mean Flow'] = WYData['Discharge'].mean()
WYDataDF['Peak Flow'] = WYData['Discharge'].max()
WYDataDF['Median Flow'] = WYData['Discharge'].median()
WYDataDF['Coeff Var'] = WYData['Discharge'].std() / WYData['Discharge'].mean()*100
WYDataDF['Skew'] = WYData['Discharge'].skew()
WYDataDF['Tqmean'] = WYData['Discharge'].apply(lambda x: CalcTqmean(x))
WYDataDF['R-B Index'] = WYData['Discharge'].apply(lambda x: CalcRBindex(x))
WYDataDF['7Q'] = WYData['Discharge'].apply(lambda x: Calc7Q(x))
WYDataDF['3xMedian'] = WYData['Discharge'].apply(lambda x: CalcExceed3TimesMedian(x))
return ( WYDataDF )
def GetMonthlyStatistics(DataDF):
"""This function calculates monthly descriptive statistics and metrics
for the given streamflow time series. Values are returned as a dataframe
of monthly values for each year."""
colNames = ['site_no','Mean Flow', 'Coeff Var', 'Tqmean', 'R-B Index']
# define index as dates of ressmpled data.
# data is resampled monthly
monthlyIndex = DataDF.resample('MS').mean().index
# create empty dataframe
MoDataDF = pd.DataFrame(data=0, index=monthlyIndex, columns=colNames)
# resample data
MoData = DataDF.resample('MS')
#add metrics to dataframe
MoDataDF['site_no'] = MoData['site_no'].min()
MoDataDF['Mean Flow'] = MoData['Discharge'].mean()
MoDataDF['Coeff Var'] = MoData['Discharge'].std() / MoData['Discharge'].mean()*100
MoDataDF['Tqmean'] = MoData['Discharge'].apply(lambda x: CalcTqmean(x))
MoDataDF['R-B Index'] = MoData.apply({'Discharge': lambda x: CalcRBindex(x)})
return ( MoDataDF )
def GetAnnualAverages(WYDataDF):
"""This function calculates annual average values for all statistics and
metrics. The routine returns an array of mean values for each metric
in the original dataframe."""
AnnualAverages = WYDataDF.mean()
return( AnnualAverages )
def GetMonthlyAverages(MoDataDF):
"""This function calculates annual average monthly values for all
statistics and metrics. The routine returns an array of mean values
for each metric in the original dataframe."""
MonthlyAverages = MoDataDF.groupby(MoDataDF.index.month).mean()
return( MonthlyAverages )
# the following condition checks whether we are running as a script, in which
# case run the test code, otherwise functions are being imported so do not.
# put the main routines from your code after this conditional check.
if __name__ == '__main__':
# define filenames as a dictionary
# NOTE - you could include more than jsut the filename in a dictionary,
# such as full name of the river or gaging site, units, etc. that would
# be used later in the program, like when plotting the data.
fileName = { "Wildcat": "WildcatCreek_Discharge_03335000_19540601-20200315.txt",
"Tippe": "TippecanoeRiver_Discharge_03331500_19431001-20200315.txt" }
# define blank dictionaries (these will use the same keys as fileName)
DataDF = {}
MissingValues = {}
WYDataDF = {}
MoDataDF = {}
AnnualAverages = {}
MonthlyAverages = {}
# process input datasets
for file in fileName.keys():
print( "\n", "="*50, "\n Working on {} \n".format(file), "="*50, "\n" )
DataDF[file], MissingValues[file] = ReadData(fileName[file])
print( "-"*50, "\n\nRaw data for {}...\n\n".format(file), DataDF[file].describe(), "\n\nMissing values: {}\n\n".format(MissingValues[file]))
# clip to consistent period
DataDF[file], MissingValues[file] = ClipData( DataDF[file], '1969-10-01', '2019-09-30' )
print( "-"*50, "\n\nSelected period data for {}...\n\n".format(file), DataDF[file].describe(), "\n\nMissing values: {}\n\n".format(MissingValues[file]))
# calculate descriptive statistics for each water year
WYDataDF[file] = GetAnnualStatistics(DataDF[file])
# calcualte the annual average for each stistic or metric
AnnualAverages[file] = GetAnnualAverages(WYDataDF[file])
print("-"*50, "\n\nSummary of water year metrics...\n\n", WYDataDF[file].describe(), "\n\nAnnual water year averages...\n\n", AnnualAverages[file])
# calculate descriptive statistics for each month
MoDataDF[file] = GetMonthlyStatistics(DataDF[file])
# calculate the annual averages for each statistics on a monthly basis
MonthlyAverages[file] = GetMonthlyAverages(MoDataDF[file])
print("-"*50, "\n\nSummary of monthly metrics...\n\n", MoDataDF[file].describe(), "\n\nAnnual Monthly Averages...\n\n", MonthlyAverages[file])
# save outputs
# annual metrics to csv
a_Wildcat = WYDataDF['Wildcat']
a_Wildcat['Station'] = 'Wildcat'
a_Tippe = WYDataDF['Tippe']
a_Tippe['Station'] = 'Tippe'
annualTable = a_Wildcat.append(a_Tippe)
annualTable.to_csv('Annual_Metrics.csv', sep = ',', index=True)
# monthly metrics to csv
m_Wildcat = MoDataDF['Wildcat']
m_Wildcat['Station'] = 'Wildcat'
m_Tippe = MoDataDF['Tippe']
m_Tippe['Station'] = 'Tippe'
m_Wildcat = m_Wildcat.append(m_Tippe)
m_Wildcat.to_csv('Monthly_Metrics.csv', sep = ',', index=True)
# annual averages to txt
aav_Wildcat = AnnualAverages['Wildcat']
aav_Wildcat['Station'] = 'Wildcat'
aav_Tippe = AnnualAverages['Tippe']
aav_Tippe['Station'] = 'Tippe'
aav_Wildcat = aav_Wildcat.append(aav_Tippe)
aav_Wildcat.to_csv('Average_Annual_Metrics.txt', sep = '\t', index=True)
# monthly metrics to txt
mav_Wildcat = MonthlyAverages['Wildcat']
mav_Wildcat['Station'] = 'Wildcat'
mav_Tippe = MonthlyAverages['Tippe']
mav_Tippe['Station'] = 'Tippe'
mav_Wildcat = mav_Wildcat.append(mav_Tippe)
mav_Wildcat.to_csv('Average_Monthly_Metrics.txt', sep = '\t', index=True)
|
def sum(x, y):
# print(x+y)
return x + y
print(sum(4, 5))
# default Parameter
# keyword Argument
def more_num(a, b=7, c=10):
print("a is", a, "b is", b, "c is ", c)
more_num(2)
# pass statment
def dream_home():
pass
# varArgs parameter
def total_numbers(a=7, *numbers, **phonebook):
# the single astric is for tuple and the dounle astric is for dict
print("My fav nummber is ", a)
for num in numbers:
print("num", num)
for name, phone_number in phonebook.items():
print(name, phone_number)
total_numbers(7, 1, 2, 3, Jane=2222, John=4444, Angela=5555)
# Anonymous Function(Lambda)
def a(b): return b + 4
"""" also the same
a = lambda b: b +4
print(a(4))
this called anaymoous function
"""
print(a(4))
def c(d, e): return d + e
"""
c = lambda d,e : d + e
print(c(7,8))
"""
print(c(7, 8))
def new_number(n):
return lambda f: f * n
double_num = new_number(2)
print(double_num(20))
|
from itertools import cycle
import tkinter as tk
class App(tk.Tk):
# TK window/label adjust to size of images
def __init__(self, image_file, x, y, delay):
tk.Tk.__init__(self)
self.geometry("+{}+{}".format(x, y))
self.delay = delay
self.pictures = cycle((tk.PhotoImage(file=image), image)
for image in image_file)
self.pictures_display = tk.Label(self)
self.pictures_display.pack()
def show_slides(self):
# cycle through the images and display them
img_object, img_name = next(self.pictures)
self.pictures_display.config(image=img_object)
self.title(img_name)
self.after(self.delay, self.show_slides)
def run(self):
self.mainloop()
# set milliseconds time between slides
delay = 3500
# get a series of gif images you have in the working folder
# or use full path, or set diretory to wher ther images are
image_file = [
"1.gif",
"2.gif",
"3.gif",
"4.gif",
"5.gif",
"6.gif",
"7.gif"
]
x = 100
y = 50
app = App(image_file, x, y, delay)
app.show_slides()
app.run()
|
# class Point:
# def draw(self):
# print("draw")
# point = Point()
# print(type(point))
# print(isinstance(point, Point))
# creating new constructure
class Point:
# class level attribute are accessinle all level of the class.
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x},{self.y})")
Point.default_color = "yellow"
point = Point(1, 2)
# print(point.x)
point.draw()
print(point.default_color)
print(Point.default_color)
# class and attribute refrence
another = Point(3, 4)
another.draw()
|
import sqlite3
class DataCliente:
def __init__(self):
self.conn = sqlite3.connect('basedata.db')
self.cursor = self.conn.cursor()
def insertItems(self, code, name, supp, price, cant):
sql = "INSERT INTO clientes (name, phone, mail, adress, reference ) VALUES(?,?,?,?,?)"
params = (code, name, price, supp, cant)
self.cursor.execute(sql, params)
self.conn.commit()
def returnOneItem(self, ejm):
sql = "SELECT * FROM clientes WHERE phone = '{}'".format(ejm)
self.cursor.execute(sql)
return self.cursor.fetchone()
def returnAllElements(self):
sql = "SELECT * FROM clientes ORDER BY id"
self.cursor.execute(sql)
return self.cursor.fetchall()
def delete(self, ejm):
sql = "DELETE FROM clientes WHERE phone = '{}'".format(ejm)
self.cursor.execute(sql)
self.conn.commit()
def updateItem(self, elem, pls):
sql = "UPDATE clientes SET name ='{}', phone='{}', mail='{}', adress='{}', reference='{}' WHERE phone = '{}'".format(elem[0], elem[1], elem[2], elem[3], elem[4], pls)
self.cursor.execute(sql)
self.conn.commit()
|
"""
Validate national code method for Iranian national ID Codes
"""
# Standard library imports
import re
def validate(national_code):
if national_code is None:
return False
if type(national_code) != str:
return False
national_code = national_code.replace('_','').replace('-','').replace(' ','')
valid_national_code_pattern = "[0-9]{10}"
invalid_codes = ( "0000000000", "1111111111", "2222222222", "3333333333", "4444444444", "5555555555", "6666666666", "7777777777", "8888888888", "9999999999")
if national_code in invalid_codes:
return False
if len(national_code) != 10:
return False
if re.search(valid_national_code_pattern,national_code) is None:
return False
checksum_digit = national_code[9]
main_digits = national_code[:9]
i = 10
sum = 0
for n in main_digits:
sum = sum + (int(n) * i)
i -= 1
remainder = sum % 11
if not((remainder < 2 and remainder == checksum_digit) or (remainder >= 2 and ((11 - remainder) == int(checksum_digit)))):
return False
return True
|
# Do relevant imports
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
from moviepy.editor import VideoFileClip
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def grayToColor(img):
return cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
# defining a blank mask to start with
mask = np.zeros_like(img)
# defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
# filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
# returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines, color=[255, 0, 0], thickness=2):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len,
maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + λ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, λ)
# Define the Hough transform parameters
rho = 2
theta = np.pi/90
threshold = 15
min_line_length = 200
max_line_gap = 150
# Define the canny edge detection parameters
blur_kernel = 13
canny_low_threshold = 50
canny_high_threshold = 150
# Define the detection horizon
y_cut = .62
# The coordinates of the lines
global prev_bottom_left_x
global prev_bottom_right_x
global prev_top_left_x
global prev_top_right_x
prev_bottom_left_x = 0
prev_bottom_right_x = 0
prev_top_left_x = 0
prev_top_right_x = 0
# This function processes each frame from the video individually
def process_image(image):
global prev_bottom_left_x
global prev_bottom_right_x
global prev_top_left_x
global prev_top_right_x
imshape = image.shape
vertices = np.array([[ (0, imshape[0]),
(imshape[1] * .45, imshape[0] * y_cut),
(imshape[1] * .55, imshape[0] * y_cut),
(imshape[1], imshape[0]) ]], dtype=np.int32)
## Conversion to grayscale and blurring
gray = gaussian_blur(grayscale(image),blur_kernel)
## Increase contrast
highlights = (gray[:,:] > 180)
gray[highlights] = 255
edges = canny(gray,canny_low_threshold,canny_high_threshold)
masked = region_of_interest(edges, vertices)
lines = cv2.HoughLinesP(masked, rho, theta, threshold, np.array([]),
min_line_length, max_line_gap)
line_image = np.copy(image)*0
# Iterate over the output "lines" and draw lines on the blank
left_x = []
left_y = []
right_x = []
right_y = []
if lines is not None:
for line in lines:
for x1, y1, x2, y2 in line:
slope = np.abs((y2 - y1) / (x2 - x1))
if(slope > .5):
if (x1 < x2 and y1 > y2) or (x2 < x1 and y2 > y1) :
# left line
left_x.append(x1)
left_x.append(x2)
left_y.append(y1)
left_y.append(y2)
else:
# right line
right_x.append(x1)
right_x.append(x2)
right_y.append(y1)
right_y.append(y2)
top_left_y = int(imshape[0] * y_cut)
if(len(left_x) and len(left_y)):
left_slope, left_intersect = np.polyfit(left_x, left_y, 1)
bottom_left_x = int((imshape[0] - left_intersect) / left_slope)
top_left_x = int((top_left_y - left_intersect) / left_slope)
prev_bottom_left_x = bottom_left_x
prev_top_left_x = top_left_x
else:
bottom_left_x = prev_bottom_left_x
top_left_x = prev_top_left_x
top_right_y = int(imshape[0] * y_cut)
if (len(right_x) and len(right_y)):
right_slope, right_intersect = np.poly1d(np.polyfit(right_x, right_y, 1))
bottom_right_x = int((imshape[0] - right_intersect) / right_slope)
top_right_x = int((top_right_y - right_intersect) / right_slope)
prev_bottom_right_x = bottom_right_x
prev_top_right_x = top_right_x
else:
bottom_right_x = prev_bottom_right_x
top_right_x = prev_top_right_x
draw_lines(line_image, [[[bottom_left_x, imshape[0], top_left_x, top_left_y],
[bottom_right_x, imshape[0], top_right_x, top_right_y]]], thickness=10)
# Create a "color" binary image to combine with line image
##color_edges = np.dstack((masked, masked, masked))
# Draw the lines on the edge image
full_image = cv2.addWeighted(image, 0.7 , line_image, 1, 0)
return full_image
white_output = 'solidYellowLeft-output.mp4'
clip1 = VideoFileClip("solidYellowLeft.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
white_clip.write_videofile(white_output, audio=False,fps=25,codec='mpeg4')
|
import time
import pandas as pd
from datetime import timedelta
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
MONTHS = {
'january': 1,
'february': 2,
'march': 3,
'april': 4,
'may': 5,
'june': 6
}
DAYS = {
'monday': 0,
'tuesday': 1,
'wednesday': 2,
'thursday': 3,
'friday': 4,
'saturday': 5,
'sunday': 6
}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington)
city = input_validator("Please choose one of the followings cities: Chicago, New York City, Washington \ncity: ", "city").lower()
filter_choice = input_validator("Please choose a time filter: month, day or none for no time filter \nfilter: ", "filter")
if filter_choice == "month":
# get user input for month (january, february, ... , june)
month = input_validator("Please choose a month: January, February, March, April, May, June \nmonth: ", "month").lower()
day = None
elif filter_choice == "day":
# get user input for day of week (monday, tuesday, ... sunday)
day = input_validator("Please choose a day: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday \nday: ", "day").lower()
month = None
else:
month = None
day = None
print('-'*40)
return city, month, day
def input_validator(input_str, type):
"""
Validates user input based on the type of input (e.g. month, day, filter)
Returns:
(input_value) - user input value
"""
while True:
input_value = input(input_str)
try:
if type == "month":
result = validate_month(input_value)
if type == "day":
result = validate_day(input_value)
if type == "filter":
result = validate_filter_choice(input_value)
if type == "city":
result = validate_city(input_value)
if type == "answer":
result = validate_yes_no_answer(input_value)
if not result:
raise Exception("Please type one of the values above")
except Exception as error:
print(error)
continue
break
return input_value
def validate_city(city):
for key, value in CITY_DATA.items():
if key == city.lower():
return True
return False
def validate_filter_choice(filter_choice):
filter_options = ['month', 'day', 'none']
return True if filter_choice.lower() in filter_options else False
def validate_month(month):
for key, value in MONTHS.items():
if key == month.lower():
return True
return False
def validate_day(day):
for key, value in DAYS.items():
if key == day.lower():
return True
return False
def validate_yes_no_answer(answer):
answer_options = ['yes', 'no']
return True if answer.lower() in answer_options else False
def get_dict_key(value, dict_list):
for key, val in dict_list.items():
if val == value:
return key
def load_data(city, month=None, day=None):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
df['month'] = pd.to_datetime(df['Start Time']).dt.month
df['week day'] = pd.to_datetime(df['Start Time']).dt.dayofweek
"""
Return Data Frame with month filter
"""
if month != None:
month_filter = df[df['month'] == MONTHS[month.lower()]]
return month_filter
elif day != None:
day_filter = df[df['week day'] == DAYS[day.lower()]]
return day_filter
else:
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
most_common_month = df['month'].value_counts().idxmax()
# display the most common day of week
most_common_week_day = df['week day'].value_counts().idxmax()
# display the most common start hour
df['hour'] = pd.to_datetime(df['Start Time']).dt.hour
most_common_hour = df['hour'].value_counts().idxmax()
print("Most common month: {}".format(get_dict_key(most_common_month, MONTHS).title()))
print("Most common week day: {}".format(get_dict_key(most_common_week_day, DAYS).title()))
print("Most common hour: {} (24h format)".format(most_common_hour))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
most_common_start_station = df['Start Station'].value_counts().idxmax()
# display most commonly used end station
most_common_end_station = df['End Station'].value_counts().idxmax()
# display most frequent combination of start station and end station trip
df['Start and End Station Combo'] = df['Start Station'].map(str) + ' - ' + df['End Station'].map(str)
most_common_start_end_stations_combo = df['Start and End Station Combo'].value_counts().idxmax()
print("Most common Start station: {}".format(most_common_start_station))
print("Most common End station: {}".format(most_common_end_station))
print("Most common Start - End Station Combination: {}".format(most_common_start_end_stations_combo))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
total_travel_time_seconds = df['Trip Duration'].sum()
total_travel_time_hours_mins = timedelta(seconds=int(total_travel_time_seconds))
# display mean travel time
mean_travel_time_seconds = df['Trip Duration'].mean()
mean_travel_time_hours_mins = timedelta(seconds=int(mean_travel_time_seconds))
print("Total travel time: {} (h/m)".format(total_travel_time_hours_mins))
print("Average travel time: {} (h/m)".format(mean_travel_time_hours_mins))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
count_user_type = df['User Type'].value_counts()
print("User Type counts:\n{}".format(count_user_type))
# Display counts of gender
if "Gender" in df.columns:
count_gender = df['Gender'].value_counts()
print("\nUser Gender counts:\n{}".format(count_gender))
else:
print("Unable to get count for Gender")
if "Birth Year" in df.columns:
# Display earliest, most recent, and most common year of birth
earliest_birth = df['Birth Year'].min()
most_recent_birth = df['Birth Year'].max()
most_common_birth = df['Birth Year'].value_counts().idxmax()
print("\nEarliest birth year: {}, most recent birth year: {}, and most common birth year: {}".format(earliest_birth, most_recent_birth, most_common_birth))
else:
print("Unable to get results for Birth Year")
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def print_raw_data(df):
"""
Asks the user whether s/he wants to see raw data. If yes, the script will print 5 rows each time the user types yes.
"""
raw_data_answer = input_validator("\nWould you like to view raw data? Type yes or no. \n", "answer")
if raw_data_answer.lower() != "yes":
return df
start_count = 0
while True:
end_count = start_count + 5
print(df.iloc[start_count:end_count])
more_raw_data_answer = input_validator("\nWould you like to view additional raw data? Type yes or no. \n", "answer")
if more_raw_data_answer.lower() == "yes":
start_count += 5
continue
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
print_raw_data(df)
restart = input_validator("\nWould you like to restart? Type yes or no.\n", "answer")
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
"""This program grabs a joke from the internet and if you like it, saves it in a file. You can look at the jokes you liked"""
__author__ = "Ken Vanden Branden"
__license__ = "GPL"
__version__ = "1.0.0"
__email__ = "[email protected]"
import requests # To make http requests
import sys # to exit the programm
import urllib3 #to disable certificate check on web requests
import json #to parse the jokes coming from the joke-website.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
jokesUri = "https://v2.jokeapi.dev/joke/Programming"
infinite_loop = True #infinite loop variable to redraw the menu until user exits
#Grabbing the joke
def get_Joke(jokeUri):
uri = jokeUri
print(uri)
try:
#print("\n---\nGET %s?%s"%(jokeUri))
resp = requests.get(uri,verify=False)
return resp
except:
print("Status: %s" % resp.status_code)
print("Response: %s" % resp.text)
sys.exit()
#Parsing the joke
def parse_Joke(data):
joke = data
if joke["type"] == "twopart":
jokeresp = "Question:\n {} \n\n\n\n\n\n\n\n\n\nAnswer:\n {} \n".format(joke["setup"],joke["delivery"])
return jokeresp
else:
jokeresp = "Joke:\n {} \n".format(joke["joke"])
return jokeresp
#Providing simple menu for the user
def menu():
multiline_menu= "Menu\n" \
"1: Do you want to hear a joke?\n"\
"2: Let me show you the jokes you liked\n"\
"3: Exit\n"\
"Your choice: "
val = input(multiline_menu)
return val
#Handling user input.
def menuchoice(val):
if val == "1":
resp = get_Joke(jokesUri)
json_data = resp.json()
responsemessage = parse_Joke(json_data)
print(responsemessage)
savejoke(responsemessage)
elif val =="2":
readjoke()
elif val =="3":
print("Thank you for laughing, goodbye!")
sys.exit()
else:
print("Print this is not a correct choice, please try again\n")
# Save jokes to a file
def savejoke(writejoke):
responsemessage = writejoke
question = input("Do you want to save the joke? y/n: ")
if question =="y":
print("Saving joke...\n")
with open("savedjokes.txt",'a') as file:
file.write(writejoke)
elif question =="n":
print("OK, back to main menu it is then...\n")
else:
print("Please answer with y or n:")
savejoke(responsemessage)
# Read joke from the file.
def readjoke():
print("Here are the jokes you liked: \n")
try:
with open("savedjokes.txt",'r') as file:
data = file.read()
print(data)
except:
print("Can't read or find \"savedjokes.txt\" You probably didn't save any jokes yet.\n")
#Start of the programm
while infinite_loop:
val = menu()
menuchoice(val)
|
# Ex.4 - Variables and Names
# - Write a comment above each line explaining to yourself in English what it does.
# - Read the .py file backwardç
# - Read the .py file out loud, saying even the characters
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print("There are",cars,"cars avaiable.")
print("There are only",drivers,"drivers avaiable.")
print("There will be",cars_not_driven,"Empty cars today.")
print("We can transport",carpool_capacity,"people today.")
print("We have",passengers,"to carpool today.")
print("We need to put about",average_passengers_per_car,
"in each car.")
|
trip = float(input())
puzzle_number = int(input())
doll_number = int(input())
teddy_bear_number = int(input())
minion_number = int(input())
truck_number = int(input())
puzzle_price = 2.60
doll_price = 3
teddy_bear_price = 4.10
minion_price = 8.20
truck_price = 2
total_toy_sum = (puzzle_number * puzzle_price) + (doll_number * doll_price) + (teddy_bear_number * teddy_bear_price) + (minion_number * minion_price) + (truck_number * truck_price)
toy_total_number = puzzle_number + doll_number + teddy_bear_number + minion_number + truck_number
if toy_total_number >= 50:
total_toy_sum -= total_toy_sum * 0.25
rent = total_toy_sum * 0.10
profit = total_toy_sum - rent
if profit >= trip:
print(f'Yes! {profit - trip:.2f} lv left.')
else:
print(f'Not enough money! {trip - profit:.2f} lv needed.')
|
first_number = int(input())
second_number = int(input())
for i in range(first_number, second_number + 1):
number = i
even_sum = 0
odd_sum = 0
for position in range(1, 7):
digit = number % 10
number = number // 10
if position % 2 == 0:
even_sum += digit
else:
odd_sum += digit
if even_sum == odd_sum:
print(f'{i}', end=' ')
|
n = int(input())
bus_price = 0
truck_price = 0
train_price = 0
total_weight = 0
total_weight_bus = 0
total_weight_truck = 0
total_weight_train = 0
average_weight = 0
for load in range(1, n + 1):
weight = int(input())
if weight <= 3:
bus_price = 200
total_weight_bus += weight
elif 4 <= weight <= 11:
truck_price = 175
total_weight_truck += weight
elif weight >= 12:
train_price = 120
total_weight_train += weight
total_weight += weight
average_weight = (bus_price * total_weight_bus + truck_price * total_weight_truck + train_price * total_weight_train) / total_weight
print(f'{average_weight:.2f}')
print(f'{total_weight_bus / total_weight * 100:.2f}%')
print(f'{total_weight_truck / total_weight * 100:.2f}%')
print(f'{total_weight_train / total_weight * 100:.2f}%')
|
number_dogs = int(input())
number_animals = int(input())
dog_food_price = 2.5
animal_food_price = 4
result = number_dogs * dog_food_price + number_animals * animal_food_price
print(f'{result} lv')
|
import math
number_magnolii = int(input())
number_zumbuli = int(input())
number_roses = int(input())
number_cactus = int(input())
gift_price = float(input())
price_magnolii = 3.25
price_zumbuli = 4
price_roses = 3.50
price_cactus = 8
total_sales = (number_magnolii * price_magnolii) + (number_zumbuli * price_zumbuli) + (number_roses * price_roses) + (number_cactus * price_cactus)
tax = total_sales * 0.05
profit = total_sales - tax
diff = abs(profit - gift_price)
if profit >= gift_price:
print(f'She is left with {math.floor(diff)} leva.')
else:
print(f'She will have to borrow {math.ceil(diff)} leva.')
|
n = int(input())
numbers_sum = 0
for i in range(n):
current_number = int(input())
numbers_sum += current_number
print(numbers_sum)
|
days_count = int(input())
bakers_count = int(input())
cakes_count = int(input())
waffles_count = int(input())
pancakes_count = int(input())
cake_price = 45
waffles_price = 5.80
pancakes_price = 3.20
money_per_day = ((cake_price * cakes_count) + (waffles_count * waffles_price) + (pancakes_count * pancakes_price)) * bakers_count
income = money_per_day * days_count
profit = income - (income * 1/8)
print(profit)
|
exam_hour = int(input())
exam_minutes = int(input())
arrival_hour = int(input())
arrival_minutes = int(input())
exam_time = exam_hour * 60 + exam_minutes
arrival_time = arrival_hour * 60 + arrival_minutes
diff = arrival_time - exam_time
state = ''
if diff < -30:
state = 'Early'
elif diff <= 0:
state = 'On time'
else:
state = 'Late'
result = ''
if diff != 0:
hours = abs(diff) // 60
minutes = abs(diff) % 60
if hours > 0:
if diff < 0:
result = f'{hours}:{minutes:02d} hours before the start'
else:
result = f'{hours}:{minutes:02d} hours after the start'
else:
if diff < 0:
result = f'{minutes} minutes before the start'
else:
result = f'{minutes} minutes after the start'
print(f'{state}')
if diff != 0:
print(f'{result}')
|
season = input()
distance = float(input())
price_per_km = 0
if distance <= 5000:
if season == 'Spring' or season == 'Autumn':
price_per_km = 0.75
elif season == 'Summer':
price_per_km = 0.90
else:
price_per_km = 1.05
elif 5000 < distance <= 10000:
if season == 'Spring' or season == 'Autumn':
price_per_km = 0.95
elif season == 'Summer':
price_per_km = 1.10
else:
price_per_km = 1.25
elif 10000 < distance <= 20000:
price_per_km = 1.45
total_money = price_per_km * distance * 4
salary = total_money - total_money * 0.1
print(f'{salary:.2f}')
|
import math
days = int(input())
available_food = int(input())
dog_food = float(input())
cat_food = float(input())
turtle_food = float(input())
total_dog = days * dog_food
total_cat = days * cat_food
total_turtle = days * turtle_food / 1000
total_food_needed = total_dog + total_cat + total_turtle
diff = abs(total_food_needed - available_food)
if available_food >= total_food_needed:
print(f'{math.floor(diff)} kilos of food left.')
else:
print(f'{math.ceil(diff)} more kilos of food are needed.')
|
pages_count = int(input())
pages_per_hour = int(input())
days_count = int(input())
total_time = pages_count / pages_per_hour
total_hours = total_time / days_count
print(total_hours)
|
money = float(input())
months = int(input())
interest_rate = float(input())
interest = money * interest_rate / 100
interest_per_month = interest / 12
total_money = money + (months * interest_per_month)
print(total_money)
|
budget = float(input())
video_cards = int(input())
processors = int(input())
ram_memory = int(input())
price_video_card = 250
total_video_card = price_video_card * video_cards
price_processor = total_video_card * 0.35
total_processor = price_processor * processors
price_ram_memory = total_video_card * 0.1
total_ram_memory = price_ram_memory * ram_memory
total = total_video_card + total_processor + total_ram_memory
if video_cards > processors:
total -= total * 0.15
diff = abs(total - budget)
if total <= budget:
print(f'You have {diff:.2f} leva left!')
else:
print(f'Not enough money! You need {diff:.2f} leva more!')
|
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
x = float(input())
y = float(input())
if (x == x1 or x == x2) and (y1 <= y <= y2):
print(f'Border')
elif (y == y1 or y == y2) and (x1 <= x <= x2):
print(f'Border')
else:
print(f'Inside / Outside')
|
name = input()
sum_grades = 0
average_grade = 0
level = 0
while True:
annual_grade = float(input())
if annual_grade < 4:
grade = float(input())
if annual_grade < 4:
level += 1
print(f'{name} has been excluded at {level} grade')
break
else:
level += 1
sum_grades += annual_grade
average_grade = sum_grades / level
if level == 12:
print(f'{name} graduated. Average grade: {average_grade:.2f}')
break
|
#This class models a board for the game. Includes the functionality
#for making moves
class PentagoBoard:
def __init__(self, newState = []):
if newState == []:
self.state = [["-" for x in range(6)] for y in range(6)]
else:
self.state = [[newState[y][x] for x in range(0, 6)] for y in range(0,6)]
#place a token on the board
def place(self, player, location = (0, 0)):
self.state[location[0]][location[1]] = player
#remove a token from the board
def remove(self, location = (0,0)):
self.state[location[0]][location[1]] = "-"
#print the current state of the board and write to the output file
def printBoard(self, out):
print("+-------+-------+")
out.write("+-------+-------+\n")
for x in range(6):
line = "| "
for y in range(6):
line += self.state[x][y] + " "
if y==2 or y==5:
line += "| "
print(line)
out.write(line + "\n")
if x == 2 or x == 5:
print("+-------+-------+")
out.write("+-------+-------+\n")
#check if the board is full
def boardFull(self):
for ls in self.state:
for el in ls:
if el == "-":
return False
return True
#Check if a particular square on the board is empty
def squareEmpty(self, square)->bool:
start = self.squareToIdx(square)
end = start[1]
start = start[0]
for y in range(start[0], end[0] + 1):
for x in range(start[1], end[1] + 1):
if self.state[y][x] != "-":
return False
return True
#rotate a particular square on the board left or right
def rotateSquare(self, square, dir):
if(self.squareEmpty(square) or dir == "*"):#dont do anything if trying to rotate an empty square
return
start = self.squareToIdx(square)
end = start[1]
start = start[0]
addnum = 1
if(dir == "L"):#swap start/end positions so square is read upside down and backwards
#when this is turned right, it is functionally the same as rotating left
temp = start
start = end
end = temp
addnum = -1
rows = [["", "", ""], ["", "", ""], ["", "", ""]]
ridx = 0
cidx = 0
for y in range(start[0], end[0] + addnum, addnum): #copy the elements that are going to be flipped
for x in range(start[1], end[1] + addnum, addnum):
rows[ridx][cidx] = self.state[y][x]
self.state[y][x] = "-"
cidx += 1
ridx += 1
cidx = 0
ridx = 0
cidx = 0
if(dir == "L"): #restore original start and end positions if left
temp = start
start = end
end = temp
for c in range(end[1], start[1] - 1, -1): #read rows of copy into columns of board, from last column to first
for d in range(start[0], end[0] + 1): #this essentially flips the board
self.state[d][c] = rows[ridx][cidx]
cidx += 1
ridx += 1
cidx = 0
#get the indexes of the start and end positions of a square, used by rotate function
def squareToIdx(self, square):
start = [0, 0]
end = [0, 0]
#determine where the start and end points of the square are, based on square number
if square == 1:
end = [2,2]
elif square == 2:
start = [0,3]
end = [2,5]
elif square == 3:
start = [3,0]
end = [5,2]
else:
start = [3,3]
end = [5,5]
return [start, end]
|
'''
* Python program to use contours to count the objects in an image.
*
* usage: python Contours.py <filename> <threshold>
'''
import cv2, sys
# read command-line arguments
filename = sys.argv[1]
t = int(sys.argv[2])
# read original image
image = cv2.imread(filename = filename)
# create binary image
gray = cv2.cvtColor(src = image, code = cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(src = gray,
ksize = (5, 5),
sigmaX = 0)
(t, binary) = cv2.threshold(src = blur,
thresh = t,
maxval = 255,
type = cv2.THRESH_BINARY)
# find contours
(_, contours, _) = cv2.findContours(image = binary,
mode = cv2.RETR_EXTERNAL,
method = cv2.CHAIN_APPROX_SIMPLE)
# print table of contours and sizes
print("Found %d objects." % len(contours))
for (i, c) in enumerate(contours):
print("\tSize of contour %d: %d" % (i, len(c)))
# draw contours over original image
cv2.drawContours(image = image,
contours = contours,
contourIdx = -1,
color = (0, 0, 255),
thickness = 5)
# display original image with contours
cv2.namedWindow(winname = "output", flags = cv2.WINDOW_NORMAL)
cv2.imshow(winname = "output", mat = image)
cv2.waitKey(delay = 0)
|
"""
* Program to practice with skimage drawing methods.
"""
import random
import numpy as np
import skimage
from skimage.viewer import ImageViewer
# create the black canvas
image = np.zeros(shape=(600, 800, 3), dtype="uint8")
viewer = ImageViewer(image)
viewer.show()
# mask = np.ones(shape=image.shape[0:2], dtype="bool")
# WRITE YOUR CODE TO DRAW ON THE IMAGE HERE
rr1, cc1 = skimage.draw.circle(300, 400, radius=100)
image[rr1, cc1] = [128, 25, 128]
# display the results
# Display constructed mask
viewer = ImageViewer(image)
viewer.show()
|
'''
* Python script to demonstrate Laplacian edge detection.
*
* usage: python LaplacianEdge.py <filename> <kernel-size> <threshold>
'''
import cv2
import numpy as np
import sys
# read command-line arguments
filename = sys.argv[1]
k = int(sys.argv[2])
t = int(sys.argv[3])
# load and display original image
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
cv2.namedWindow("original", cv2.WINDOW_NORMAL)
cv2.imshow("original", img)
cv2.waitKey(0)
# blur image and use simple inverse binary thresholding to create
# a binary image
blur = cv2.GaussianBlur(img, (k, k), 0)
(t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY_INV)
# WRITE YOUR CODE HERE
# perform Laplacian edge detection
# cv2.Laplacian() takes two parameters, the input image, and the data
# type used for the output image. Use the cv2.Laplacian() method to
# detect the edges in the binary image, storing the result in an image
# named edge.
# WRITE YOUR CODE HERE
# Convert the edge image back to 8 bit unsigned integer data type.
# display edges
cv2.namedWindow("edges", cv2.WINDOW_NORMAL)
cv2.imshow("edges", edge)
cv2.waitKey(0)
|
import re
def validating_name(name):
regex_name=re.compile(r'^(Mr\.|Mrs\.|Ms\.) (?P<First>[A-Z][A-Za-z]+)(?P<Second> [A-Z][A-Za-z]+)*( [A-Z][A-Za-z]+)*$')
res=regex_name.fullmatch(name)
if res:
print(res.group())
print(res.group("First"))
print(res.group('Second'))
else:
print("Invalid")
validating_name('Mr. Albus Severus Potter')
validating_name('nnnnnnMr. Albus Severus Pottermmm')
validating_name('Mr. Potter')
|
def list_less_than_ten():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
for element in a:
if element < 5:
b.append(element)
print b
def divisors():
number = int(raw_input("Enter a number: "))
divisor_list = []
divisor_range = list(range(1,number+1))
for element in divisor_range:
if number % element == 0:
divisor_list.append(element)
print divisor_list
def list_overlap():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = []
for element in a:
if element in b:
if element not in c:
c.append(element)
print c
|
import numpy as np
"""
This entire code base has been developed
by Baijayanta Roy at Medium-Article. The code
can be found at {https://github.com/BaijayantaRoy/Medium-Article}.
I do NOT claim any rights for this code as it has NOT been developed by me.
However, the code is under the GNU GENERAL PUBLIC LICENSE, thus, it is free to
copy and distribute.
"""
class Node:
"""
A node class for A* Pathfinding
parent is parent of the current Node
position is current position of the Node in the maze
g is cost from start to current Node
h is heuristic based estimated cost for current Node to end Node
f is total cost of present node i.e. : f = g + h
"""
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
#This function return the path of the search
def return_path(current_node,maze):
path = []
no_rows, no_columns = np.shape(maze)
# here we create the initialized result maze with -1 in every position
result = [[-1 for i in range(no_columns)] for j in range(no_rows)]
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
# Return reversed path as we need to show from start to end path
path = path[::-1]
start_value = 0
# we update the path of start to end found by A-star serch with every step incremented by 1
for i in range(len(path)):
result[path[i][0]][path[i][1]] = start_value
start_value += 1
return result
def search(maze, cost, start, end):
"""
Returns a list of tuples as a path from the given start to the given end in the given maze
:param maze:
:param cost
:param start:
:param end:
:return:
"""
# Create start and end node with initized values for g, h and f
start_node = Node(None, tuple(start))
start_node.g = start_node.h = start_node.f = 0
end_node = Node(None, tuple(end))
end_node.g = end_node.h = end_node.f = 0
# Initialize both yet_to_visit and visited list
# in this list we will put all node that are yet_to_visit for exploration.
# From here we will find the lowest cost node to expand next
yet_to_visit_list = []
# in this list we will put all node those already explored so that we don't explore it again
visited_list = []
# Add the start node
yet_to_visit_list.append(start_node)
# Adding a stop condition. This is to avoid any infinite loop and stop
# execution after some reasonable number of steps
outer_iterations = 0
max_iterations = (len(maze) // 2) ** 10
# what squares do we search . serarch movement is left-right-top-bottom
#(4 movements) from every positon
move = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
"""
1) We first get the current node by comparing all f cost and selecting the lowest cost node for further expansion
2) Check max iteration reached or not . Set a message and stop execution
3) Remove the selected node from yet_to_visit list and add this node to visited list
4) Perofmr Goal test and return the path else perform below steps
5) For selected node find out all children (use move to find children)
a) get the current postion for the selected node (this becomes parent node for the children)
b) check if a valid position exist (boundary will make few nodes invalid)
c) if any node is a wall then ignore that
d) add to valid children node list for the selected parent
For all the children node
a) if child in visited list then ignore it and try next node
b) calculate child node g, h and f values
c) if child in yet_to_visit list then ignore it
d) else move the child to yet_to_visit list
"""
#find maze has got how many rows and columns
no_rows, no_columns = np.shape(maze)
# Loop until you find the end
while len(yet_to_visit_list) > 0:
# Every time any node is referred from yet_to_visit list, counter of limit operation incremented
outer_iterations += 1
# Get the current node
current_node = yet_to_visit_list[0]
current_index = 0
for index, item in enumerate(yet_to_visit_list):
if item.f < current_node.f:
current_node = item
current_index = index
# if we hit this point return the path such as it may be no solution or
# computation cost is too high
if outer_iterations > max_iterations:
print ("giving up on pathfinding too many iterations")
return return_path(current_node,maze)
# Pop current node out off yet_to_visit list, add to visited list
yet_to_visit_list.pop(current_index)
visited_list.append(current_node)
# test if goal is reached or not, if yes then return the path
if current_node == end_node:
return return_path(current_node,maze)
# Generate children from all adjacent squares
children = []
for new_position in move:
# Get node position
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
# Make sure within range (check if within maze boundary)
if (node_position[0] > (no_rows - 1) or
node_position[0] < 0 or
node_position[1] > (no_columns -1) or
node_position[1] < 0):
continue
# Make sure walkable terrain
if maze[node_position[0]][node_position[1]] != 0:
continue
# Create new node
new_node = Node(current_node, node_position)
# Append
children.append(new_node)
# Loop through children
for child in children:
# Child is on the visited list (search entire visited list)
if len([visited_child for visited_child in visited_list if visited_child == child]) > 0:
continue
# Create the f, g, and h values
child.g = current_node.g + cost
## Heuristic costs calculated here, this is using eucledian distance
child.h = (((child.position[0] - end_node.position[0]) ** 2) +
((child.position[1] - end_node.position[1]) ** 2))
child.f = child.g + child.h
# Child is already in the yet_to_visit list and g cost is already lower
if len([i for i in yet_to_visit_list if child == i and child.g > i.g]) > 0:
continue
# Add the child to the yet_to_visit list
yet_to_visit_list.append(child)
if __name__ == '__main__':
maze = [[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0]]
start = [0, 0] # starting position
end = [4,5] # ending position
cost = 1 # cost per movement
path = search(maze,cost, start, end)
print(path)
|
# На вход программе подается последовательность чисел, заканчивающихся нулем.
# Сам ноль не входит в последовательность. Найти среднее значение последовательности.
# Для округления использовать функцию round(x, n). Где x - число, n - количество знаков после запятой.
# Формат входных данных
# Последовательность чисел, заканчивающихся нулем. Одно число в строку.
# Формат выходных данных
# Одно число — среднее значение. Округлить до двух цифр после запятой.
debug = False
TESTS = [([4, 8, 5], 5.67)]
def find_average(numbers: list):
numbers_sum = 0
for i in numbers:
numbers_sum += i
average = numbers_sum / len(numbers)
return round(average, 2)
if __name__ == '__main__':
for test in TESTS:
testing_function = find_average
result = testing_function(test[0])
assert result == test[1], "Ожидаемый ответ: {0}, полученный овет: {1}".format(test[1], result)
parameters = []
while True:
item = int(input())
if item != 0:
parameters.append(item)
else:
break
print(find_average(parameters))
|
def sum_numbers(n: int):
"""
Отдает сумму цифр входящего числа.
:param n:
:return:
"""
num_str = str(n)
num_sum = 0
for char in num_str:
num_sum += int(char)
return num_sum
def test_sum_numbers():
assert sum_numbers(123) == 6, 'Not pass'
assert sum_numbers(963) == 18, 'Not pass'
assert sum_numbers(253) == 10, 'Not pass'
assert sum_numbers(853) == 16, 'Not pass'
assert sum_numbers(179) == 17, 'Not pass'
if __name__ == '__main__':
test_sum_numbers()
test_num = int(input())
print(sum_numbers(test_num))
|
# Ограничение по времени работы программы: 1 секунда.
# Ограничение по памяти: 32 мегабайта.
# Ввод из стандартного потока ввода(с клавиатуры).
# Вывод в стандартный поток вывода(на экран).
# Вычислите XOR от двух чисел.
# Входные данные
# Два целых шестнадцатеричных числа меньших FF.
# Выходные данные
# Побитовый XOR этих чисел в шестнадцетиричном виде
debug = False
TESTS = [(['1', '23'], '22'),
(['f0', '0f'], 'ff')]
def calc_xor(numbers: list):
a = int(numbers[0], 16)
b = int(numbers[1], 16)
rezult = '{0:x}'.format(a ^ b)
return rezult
if __name__ == '__main__':
for test in TESTS:
testing_function = calc_xor
result = testing_function(test[0])
assert result == test[1], "Ожидаемый ответ: {0}, полученный овет: {1}".format(
test[1], result)
parameters = input().split()
print(calc_xor(parameters))
|
def cipher(text, shift, encrypt=True):
"""
Each letter is replaced by a letter some fixed number of positions down the alphabet.
Parameters
---
text: string value that you wish to encrypt or decrypt
shift: integer value of how many number positions down the alphabet you would like to shift the string
encrypt: boolean value that is 1 if you wish to encrypt or 0 if you wish to decrypt
Returns
---
string value that has been encrypted or decrypted
Examples
---
from cipher_eat2153 import cipher_eat2153
>>> cipher_eat2153.cipher(text = 'yoda', shift = 1, encrypt = True)
['zpeb']
>>>
"""
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
new_text = ''
for c in text:
index = alphabet.find(c)
if index == -1:
new_text += c
else:
new_index = index + shift if encrypt == True else index - shift
new_index %= len(alphabet)
new_text += alphabet[new_index:new_index+1]
return new_text
|
from store_data import data as store_data
from view import show_stocks
def update_product_detail():
pass
def remove_products():
pass
def add_products_to_store(*args, category=None):
if category is None:
category = input("Enter the product category(fruits, grocery, stationary): ")
item = {}
price = 0
if not args:
product = input("Enter the product name: ")
price = float(input(f"Enter price of {product}: "))
quantity = int(input(f"Enter the quantity of {product}: "))
expiry_date = input(f"Enter the expiry date of {product}: ")
product_data = {'price': price, 'stock': quantity, 'expiry_date': expiry_date}
item = {product: product_data}
else:
for product in args:
value = float(input(f"Enter price of {product}: "))
quantity = int(input(f"Enter the quantity of {product}: "))
expiry_date = input(f"Enter the expiry date of {product}: ")
product_data = {'price': value, 'stock': quantity, 'expiry_date': expiry_date}
one_product = {product: product_data}
item.update(one_product)
price = price + value
if category == 'fruits':
fruits = store_data[0]
fruits.update(item)
if category == 'stationary':
stationary = store_data[1]
stationary.update(item)
if category == 'grocery':
grocery = store_data[2]
grocery.update(item)
show_stocks(category)
return price
def validate_product_expiry():
alert_product_expiry()
def alert_product_unavailability():
pass
def alert_product_expiry():
pass
def get_data():
return store_data
if __name__ == '__main__':
add_products_to_store('Pencil', category='stationary')
get_data()
|
#!/usr/bin/env python
def day_1(file) -> int:
diff1 = diff3 = 0
input_list = []
with open(file, "r") as f:
for line in f:
line = line.strip("\n")
input_list.append(int(line))
input_list.sort()
previous = 0
for i in input_list:
if i - previous == 1:
diff1 += 1
elif i - previous == 3:
diff3 += 1
previous = i
return diff1 * (diff3 + 1)
if __name__ == '__main__':
assert day_1("test_input.txt") == 220
print(day_1("input.txt"))
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
cur_node = head
while cur_node and cur_node.next:
pre_node = cur_node.next
if cur_node.val == pre_node.val:
cur_node.next = pre_node.next
else:
cur_node = pre_node
return head
|
# Sum square difference
# ------------------------------------------------- #
# First square all the numbers from 1 to 100. Then
# sum all the numbers and square them. Then
# substract the two results from each other.
# ------------------------------------------------- #
squared, result, sum = 0,0,0
for i in range(1,101):
squared+=(i*i)
sum+=i
result = (sum*sum)-squared
print "Project Euler #6"
print "The difference between the sum of the squares and the square of the sum is", result
|
# Summation of primes
# ------------------------------------------------- #
# Reuse isPrime from Euler_7. While number is less
# than 2000000 check if the number is prime, if it is
# then add it to result.
# ------------------------------------------------- #
num, result=1,0
def isPrime(n):
if n==1: return False
elif n<4: return True
elif n%2==0: return False
elif n<9: return True
else:
d = 3
while d * d <= n:
if n%d == 0:
return False
d += 2
return True
while num < 2000000:
if isPrime(num):
result+= num
num+=1
print "Project Euler #10"
print "What is the sum of primes below two million?", result
|
import pygame
import random
import sys
import math
from pygame.locals import *
gridSize = 10
letters = ['A', 'B', 'C', 'D', 'E' ,'F', 'G', 'H' ,'I','J']
class Grid():
def __init__(self):
self.size = gridSize
self.pieces = []
self.grid = self.gridMe()
self.coord = []
a = aircraftCarrier()
b = battleShip()
c = Submarine()
d = Cruiser()
e = Destroyer()
self.pieces.append(a)
self.pieces.append(b)
self.pieces.append(c)
self.pieces.append(d)
self.pieces.append(e)
self.playerNumber = 0
self.getPieces()
def gridMe(self):
grid = [[0 for x in range(self.size)] for x in range(self.size)]
for i in range(0,self.size):
for j in range(0,self.size):
grid[i][j] = 0
return grid
def getPieces(self):
self.displayGrid()
for p in self.pieces:
go = True
while(go == True):
head = input("Please choose where the head of the "+ p.name +" will be? (letter first)\n")
p.alignment = int(input("1) Vertical\n2) Horizontal\n"))
a = str(head[0])
b = int(head[1])
b = b-1
c = letters.index(a)
if (c,b) not in self.coord:
self.coord.append((c,b))
go = False
else:
print("Not a valid placement, please try again")
p.head.append((c,b))
p.fillPiece()
def displayGrid(self):
print(' 1 2 3 4 5 6 7 8 9 10')
j=0
for i in self.grid:
print(letters[j] + ' ' + str(i))
j+= 1
## self.grid = self.lockGrid()
## def lockGrid(self):
## grid = [[0 for x in range(self.size)] for x in range(self.size)]
## for i in range(0,self.size):
## for j in range(0,self.size):
## grid[i][j] = 0
## for x,y in self.teamA:
## grid[x][y] = 3 # 3 is where a ship is
## return grid
class Piece():
def __init__(self):
self.positions = []
self.head = []
self.alignment = 0
self.placed = False
self.destroyed = False
def fillPiece(self):
x,y = self.head[0]
for i in range(0,self.size):
if self.alignment == 1:
self.positions.append((x,y+i))
else:
self.positions.append((x+i,y))
class aircraftCarrier(Piece):
def __init__(self):
super(aircraftCarrier, self).__init__()
self.size = 5
self.name = 'Aircraft Carrier'
self.color = [255,0,0]
class battleShip(Piece):
def __init__(self):
super(battleShip, self).__init__()
self.size = 4
self.name = 'Battleship'
self.color = [200,50,50]
class Submarine(Piece):
def __init__(self):
super(Submarine, self).__init__()
self.size = 3
self.name = 'Submarine'
self.color = [50,200,50]
class Cruiser(Piece):
def __init__(self):
super(Cruiser, self).__init__()
self.size = 3
self.name = 'Cruiser'
self.color = [50,100,0]
class Destroyer(Piece):
def __init__(self):
super(Destroyer, self).__init__()
self.size = 2
self.name = 'Destroyer'
self.color = [50,50,50]
player1Grid = Grid()
player1Grid.playerNumber=1
for piece in player1Grid.pieces:
print(piece.positions)
player2Grid = Grid()
player2Grid.playerNumber=1
##a = ((1,2),(3,4))
##b = ((4,5),(6,2))
##grid = Grid(a,b)
##choose = int(input("1 ) 2 Player\n2) Against Cpu\n"))
##if choose == 1:
##elif choose == 2:
##else :
## print("Sorry that wasn't a choice")
## sys.exit()
|
"""
OpenCV中图像像素读写操作
Python中的像素遍历与访问
- 数组遍历
"""
import cv2 as cv
src = cv.imread("../images/beauty.jpg")
cv.namedWindow("image",cv.WINDOW_AUTOSIZE)
cv.imshow("image",src)
# 获取彩色图片的高 宽 通道数
h,w,ch = src.shape
# 遍历像素值,对像素取反
for row in range(h):
for col in range(w):
b,g,r = src[row,col]
b = 255 - b
g = 255 - g
r = 255 - r
src[row, col] = [b, g, r]
cv.imshow("output",src)
cv.waitKey(0)
cv.destroyAllWindows()
|
t = int(input())
for _ in range(t):
n = int(input())
grid = []
for i in range(n):
l = list(input())
l = sorted(l)
grid.append("".join([x for x in l]))
flag = 0
for i in range(len(grid[0])):
temp = []
for j in range(n):
temp.append(grid[j][i])
if(temp != sorted(temp)):
print("NO")
flag = 1
break
if(flag == 0):
print("YES")
|
from tkinter import *
from PIL import Image, ImageTk
imagenary_tech_root = Tk() #create a basic gui
#gui logic
#width x height - gemetory
imagenary_tech_root.geometry("700x334")
#imagenary_tech_root.minsize(300,100) #minimize- width,height
#imagenary_tech_root.maxsize(566,300) #maxsize-width,height
a = Label(text="HAPPY BIRTHDAY")
a.pack()
#for jpg images
image = Image.open("photo.jpg")
photo = ImageTk.PhotoImage(image)
a1_label =Label(image=photo)
a1_label.pack()
imagenary_tech_root.mainloop()
|
from tkinter import *
import tkinter.messagebox as tmsg
root= Tk()
root.geometry("450x300")
root.title("Slider Gui")
def getdollar():
print(f"we have credited{myslider2.get()} dollars to your bank account")
a=tmsg.showinfo("Amount credited ",f"{myslider2.get()} dollars to your bank account")
#myslider = Scale(root,from_=0,to=100) vertical scaler
#myslider.pack()
Label(root,text ="How many dollars do you want?",font="bold",fg="red",bg="grey").pack()
myslider2 = Scale(root,from_=0,to=100,orient=HORIZONTAL,tickinterval=50)
#myslider2.set(30) #initial value
Button(root,text="Get Dollars",padx=10,pady=10,font=30,bg="yellow",command=getdollar).pack()
myslider2.pack()
root.mainloop()
|
'''
devolver los indices de dos numeros que sumados entre si son iguales a un target.
suponer que solo hay una respuesta.
suponer que no se va a usar el mismo numero.
ejemplo:
nums = [2,7,11,15]
target = 9
if nums[0] + nums[1] == target
return --> [0,1]
'''
def twoSum(nums, target):
for i in range(len(nums)):
for n in range(len(nums)):
if nums[i] != nums[n] and nums[i] + nums[n] == target: # un opcion para calcular la condicion
return [i,n]
return 'no hay suma de dos numeros que cumpla la condicion'
def twoSum2(nums,target):
for i in range(len(nums)):
for n in range(len(nums)):
if nums[i] != n and nums[n] == target - nums[i]: # otra opcion para calcular la condicion
return [i,n]
return 'no hay suma de dos numeros que cumpla la condicion'
print(twoSum([2,7,11,15],9))
print(twoSum2([2,7,11,15],9))
|
from sys import exit
from random import shuffle
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def getRandomKey()-> str:
key = list(LETTERS)
shuffle(key)
return "".join(key)
def checkValidKey(key: str)-> None:
key_list = list(key)
key_list.sort()
if key_list != list(LETTERS):
exit("Error in key!")
def getFinalMessage(key: str,message: str,mode: str)-> str:
final_msg = ""
str_A, str_B = LETTERS, key
if mode.lower().startswith('d'):
str_A, str_B = str_B, str_A
for char in message:
if char.upper() in str_A:
idx_char = str_A.find(char.upper())
if char.isupper():
final_msg += str_B[idx_char].upper()
else:
final_msg += str_B[idx_char].lower()
else:
final_msg += char
return final_msg
def main()-> None:
msg = input("Enter message:\n>>> ")
key = input("Generate Key? (y/n):\n>>> ")
mode = input("Encrypt (e) / Decrypt (d):\n>>> ")
if mode.lower().startswith('e') and key.lower().startswith('y'):
key = getRandomKey()
else:
key = input("Enter key:\n>>> ")
checkValidKey(key)
print(f"Key: {key} Message: {getFinalMessage(key,msg,mode.lower()[0])}")
if __name__ == "__main__":
main()
|
from copy import deepcopy
import numpy as np
import pandas as pd
import sys
'''
In this problem you write your own K-Means
Clustering code.
Your code should return a 2d array containing
the centers.
'''
# Configure the path to data
data_dir = 'data/data/iris.data'
# Import the dataset
df = pd.read_table(data_dir, delimiter=',')
X = df[['V1', 'V2', 'V3', 'V4']].as_matrix()
# Make 3 clusters
k = 3
# Initial Centroids
C = [[2., 0., 3., 4.],
[1., 2., 1., 3.],
[0., 2., 1., 0.]]
C = np.array(C)
print("Initial Centers: ")
print(C)
def distance(data_point, center):
"""Compute distance between data point and corresponding center.
Args:
data_point(list): single data point.
center(list): corresponding center.
Returns:
distance between data point and corresponding center.
"""
return np.linalg.norm(data_point - center)
def assign_cluster(data, centers):
"""Assign cluster index to each of data point.
Args:
data(np.ndarray): data points
centers(np.ndarray): centers
Returns:
index(list): index of which cluster each of data points belongs to
"""
index = []
num_center = centers.shape[0]
for point in data:
dist = []
for i in range(num_center):
dist.append(distance(point, centers[i]))
index.append(np.argmin(dist))
return index
def update_center(X, indx):
"""Update centers for data points.
Args:
data(np.ndarray): data points.
old_index(list): The previous/current index.
Returns:
new_centers(np.ndarray): new centers after updating.
"""
newCenters = []
for clusterNumber in range(0, k):
Cluster = X[[i for i, find in enumerate(indx) if find == clusterNumber]]
centroid = Cluster.mean(axis=0)
newCenters.append(centroid)
return np.array(newCenters)
def k_means(C):
"""Perform K-Means Algorithm on dataset.
Args:
C(np.ndarray): initial centers.
"""
# Write your code here!
# Get the initial cluster of data points
C = np.array(C)
indexofcluster = assign_cluster(X, C)
old_dist = 0
while (True):
new_centers = update_center(X, indexofcluster)
new_indexofcluster = assign_cluster(X, new_centers)
dist = 0
for i in range(X.shape[0]):
dist += distance(X[i], new_centers[new_indexofcluster[i]])
if abs(dist - old_dist) < 10e-3:
break
else:
old_dist = dist
indexofcluster = new_indexofcluster
return new_centers
new_centers = k_means(C)
print("New centers: ")
print(new_centers)
|
# Expanding circle by timer
###################################################
# Student should add code where relevant to the following.
import simplegui
WIDTH = 200
HEIGHT = 200
radius = 1
# Timer handler
def tick():
global radius
radius += 1
# Draw handler
def draw(canvas):
canvas.draw_circle([WIDTH / 2, HEIGHT / 2], radius, 1, "White", "White")
# Create frame and timer
frame = simplegui.create_frame("Expanding circle", 200, 200)
frame.set_draw_handler(draw)
timer = simplegui.create_timer(100, tick)
# Start timer
frame.start()
timer.start()
|
present_value = 1000
annual_rate = 7
years = 10
future_value = present_value * (1 + 0.01 * annual_rate) ** years
print "The future value of $" + str(present_value) + " in " + str(years),
print "years at an annual rate of " + str(annual_rate) + "% is $" + str(future_value) + "."
|
def circle_circumference(radius):
return 2 * 3.14 * radius
def test(radius):
print "A circle with a radius of " + str(radius),
print "inches has a circumference of",
print str(circle_circumference(radius)) + " inches."
test(8)
test(3)
test(12.9)
|
def rectangle_perimeter(width,height):
return 2*(width+height)
def test(width, height):
print "A rectangle " + str(width) + " inches wide and " + str(height),
print "inches high has a perimeter of",
print str(rectangle_perimeter(width, height)) + " inches."
test(4, 7)
test(7, 4)
test(10, 10)
|
# Compute the circumference of a circle, given the length of its radius.
###################################################
# Circle circumference formula
# Student should enter statement on the next line.
r=8
circumf=2*3.14*r
print circumf
###################################################
# Expected output
# Student should look at the following comments and compare to printed output.
#50.24
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.