text stringlengths 37 1.41M |
|---|
'''
Given a list of non-overlapping axis-aligned rectangles rects,
write a function pick which randomly and uniformily picks an integer point in the space covered by the rectangles.
Note:
- An integer point is a point that has integer coordinates.
- A point on the perimeter of a rectangle is included in the space covered by the rectangles.
- ith rectangle = rects[i] = [x1,y1,x2,y2], where [x1, y1] are the integer coordinates of the bottom-left corner,
and [x2, y2] are the integer coordinates of the top-right corner.
- pick return a point as an array of integer coordinates [p_x, p_y]
'''
from leetcode import *
class Solution:
# We assume that there is at least one rectangle in the list.
# Time: O(|rects|), Space: O(|rects|).
# We must iterate through all the rectangles in order to obtain the total number of points
# and we must use O(|rects|) space in order to save the numbers of points in the rectangles.
def __init__(self, rects: List[List[int]]):
self.rects = rects
# This is the total number of points:
total_num_points = 0
# The number of points of all the rectangles except the last one:
nums_points = []
num_rects = len(rects)
for i in range(num_rects):
r = rects[i]
# We are adding 1 to the difference because the random point can be on the boundary of the rectangle.
num_points = (r[2] - r[0] + 1) * (r[3] - r[1] + 1)
total_num_points += num_points
if i < (num_rects - 1):
nums_points.append(total_num_points)
self.total_num_points = total_num_points
self.nums_points = nums_points
# Time: O(log(|rects|)) to pick a rectangle, Space: O(1).
def pick(self) -> List[int]:
# Pick which rectangle to choose point from:
rand_rect = self.total_num_points * random.random()
# Search for the last element in the list that is greater than rand_rect in O(log(|rects|)) time:
nums_points = self.nums_points
start = 0
end = len(nums_points) - 1
# By default we choose the last rectangle:
rect_ind = len(nums_points)
while start <= end:
mid = (start + end) // 2
if rand_rect < nums_points[mid]:
rect_ind = mid
end = mid - 1
else:
start = mid + 1
# Choose the x-y coordinates from the picked rectangle:
rect = self.rects[rect_ind]
x_coord = int((rect[2] - rect[0] + 1) * random.random()) + rect[0]
y_coord = int((rect[3] - rect[1] + 1) * random.random()) + rect[1]
return [x_coord, y_coord]
# A simple summation of my algorithm:
# 1) randomly sample the rectangles weighted by the area
# 2) randomly sample the integer points given a rectangle is selected
obj = Solution([[1,1,5,5]])
print(obj.pick())
print(obj.pick())
print(obj.pick())
obj = Solution([[-2,-2,-1,-1],[1,0,3,0]])
print(obj.pick())
print(obj.pick())
print(obj.pick())
print(obj.pick())
print(obj.pick())
# THIS CODE WAS USED TO DEBUG THE PROGRAM:
# I generated 10,000 random points and checked if the resulting histogram displayed a uniform distribution across all the points.
# obj = Solution([[82918473, -57180867, 82918476, -57180863], [83793579, 18088559, 83793580, 18088560], [66574245, 26243152, 66574246, 26243153], [72983930, 11921716, 72983934, 11921720]])
# freq = {}
# for i in range(10000):
# rand_point = tuple(obj.pick())
# freq[rand_point] = freq.get(rand_point, 0) + 1
# import matplotlib.pyplot as plt
# points = []
# freqs = []
# for i, j in enumerate(freq):
# points.append(i)
# freqs.append(freq[j])
# plt.bar(points, freqs)
# plt.show() |
'''
Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's,
and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
'''
class Solution:
# Time: O(n)
# Space: O(1)
def countBinarySubstrings(self, s: str) -> int:
zeros = 0
ones = 0
ans = 0
for i in range(len(s) - 1):
if s[i] == "0":
zeros += 1
else:
ones += 1
if s[i] != s[i + 1]:
ans += min(zeros, ones)
if s[i] == "0":
ones = 0
else:
zeros = 0
if s[-1] == "0":
zeros += 1
else:
ones += 1
ans += min(zeros, ones)
return ans
solution = Solution()
# Expected: 6
print(solution.countBinarySubstrings("00110011"))
# Expected: 4
print(solution.countBinarySubstrings("10101"))
|
'''
You are given the head of a linked list, and an integer k.
Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
'''
from leetcode import *
# Time: O(n). From Leetcode, this can be done in a single pass by maintaining a node k nodes behind the current node.
# Space: O(1).
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
length = 0
ptr = head
while ptr != None:
length += 1
ptr = ptr.next
ptr = head
index = 1
kStart = kEnd = None
while ptr != None:
if index == k:
kStart = ptr
if index == (length - k + 1):
kEnd = ptr
ptr = ptr.next
index += 1
if kStart != None and kEnd != None:
temp = kStart.val
kStart.val = kEnd.val
kEnd.val = temp
return head
|
from typing import List, Tuple, Set, Any, Optional, Dict
from collections import deque, Counter, defaultdict
import threading
import math
import random
import heapq
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# Definition for singly-linked list:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val)
def print_bin_tree_bfs(root: TreeNode) -> None:
queue = deque([root])
while len(queue) != 0:
# Popleft is O(1) for deques.
node = queue.popleft()
if node is not None:
print(node.val, end=' ')
left_node = node.left
right_node = node.right
if (left_node is not None) or (right_node is not None):
queue.append(node.left)
queue.append(node.right)
else:
print('null', end=' ')
print()
def construct_bin_tree_bfs_array(arr: List[Any]) -> TreeNode:
if len(arr) == 0:
return None
root = TreeNode(arr[0])
pos = 1
queue = deque([root])
while len(queue) != 0:
node = queue.popleft()
if node is None or pos >= len(arr):
continue
else:
if arr[pos] is None:
node.left = None
else:
node.left = TreeNode(arr[pos])
queue.append(node.left)
pos += 1
if arr[pos] is None:
node.right = None
else:
node.right = TreeNode(arr[pos])
queue.append(node.right)
pos += 1
return root
# To create a cycle, pos is used to denote the index of the node that tail's next pointer is connected to.
def construct_linked_list_array(arr: List[Any], pos = -1) -> ListNode:
if len(arr) == 0:
return None
head = ListNode(arr[0])
ptr = head
cyclePtr = head if (pos == 0) else None
for i in range(1, len(arr)):
ptr.next = ListNode(arr[i])
ptr = ptr.next
if pos == i:
cyclePtr = ptr
ptr.next = cyclePtr
return head
def print_linked_list(head: ListNode) -> None:
ptr = head
while ptr != None:
print(ptr.val, end=' ')
ptr = ptr.next
print()
|
'''
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.
The population of some year x is the number of people alive during that year.
The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1].
Note that the person is not counted in the year that they die.
Return the earliest year with the maximum population.
'''
from leetcode import *
class Solution:
# Brute force approach
# Time: O(n^2)
# Space: O(1)
def maximumPopulation(self, logs: List[List[int]]) -> int:
maxPop = 0
maxPopYear = 0
for i in range(len(logs)):
pop = 1
for j in range(len(logs)):
if (logs[i][0] < logs[j][1]) and (logs[i][0] >= logs[j][0]):
pop += 1
if pop > maxPop:
maxPop = pop
maxPopYear = logs[i][0]
elif pop == maxPop and logs[i][0] < maxPopYear:
maxPopYear = logs[i][0]
return maxPopYear
# Combo of ideas from Leetcode discussion section.
# Time: O(n) where n is the number of logs because we know the minYear and maxYear are within the range of 1950 to 2050.
# Space: O(1) because the pop array's length will be no greater than 101.
def maximumPopulation2(self, logs: List[List[int]]) -> int:
minYear = math.inf
maxYear = 0
for birth, death in logs:
minYear = min(minYear, birth, death)
maxYear = max(maxYear, birth, death)
pop = [0]*(maxYear - minYear + 1)
for birth, death in logs:
pop[birth - minYear] += 1
pop[death - minYear] -= 1
currentPop = 0
maxPop = 0
maxPopYear = 0
for i in range(len(pop)):
currentPop += pop[i]
if currentPop > maxPop:
maxPop = currentPop
maxPopYear = i + minYear
return maxPopYear
solution = Solution()
assert solution.maximumPopulation([[1993,1999],[2000,2010]]) == 1993
assert solution.maximumPopulation2([[1993,1999],[2000,2010]]) == 1993
assert solution.maximumPopulation([[1950,1961],[1960,1971],[1970,1981]]) == 1960
assert solution.maximumPopulation2([[1950,1961],[1960,1971],[1970,1981]]) == 1960
|
'''
Given a string s and a dictionary of strings wordDict,
return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
'''
from leetcode import *
class Solution:
# DP with top-down approach
# Time: O(n^3) because for each position we iterate through the string and within each iteration we perform a substring action, so overall n*n*n.
# Space: O(n + D) where n is the length of the string because of the memoization table which contains n possible prefixes
# and where D is the number of words in the dictionary because we convert the list into a set.
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
self.words = set(wordDict)
self.memo = {}
def dfs(s):
if s in self.memo:
return self.memo[s]
ret = False
prefix = s[0]
for i in range(1, len(s)):
if prefix in self.words and dfs(s[i:]):
ret = True
break
prefix += s[i]
if prefix in self.words:
ret = True
self.memo[s] = ret
return ret
return dfs(s)
# From Leetcode, the bottom-up approach is a little tricky here.
def wordBreak2(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
dp = [False] * (len(s) + 1)
# Null string
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in words:
dp[i] = True
break
return dp[len(s)]
solution = Solution()
# Expected: True
print(solution.wordBreak(s = "leetcode", wordDict = ["leet","code"]))
# Expected: True
print(solution.wordBreak(s = "applepenapple", wordDict = ["apple","pen"]))
# Expected: False
print(solution.wordBreak(s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]))
|
import sys
import re
# Look at the images showing what these regexes do for more details.
# It's not as complex as it looks.
def detect(html):
# (?is): i means regex should be case-insensitive
# and s means '.' could stand for a newline character as well
# '?' after * means be non-greedy (i.e. don't go as far as you can go)
# (?: ... ) means that the group is non-capturing (i.e. not back-referenced)
# this regex just finds all the valid anchor tags
regex_links = r"(?is)(<a(?:\s|(?:\s.*?\s))href=\s*(?:([\"']).*?\2.*?>|[^\"'][^\s]*(?:\s.*?>|>)).*?</a>)"
a_tags = [i[0] for i in re.findall(regex_links, html)]
# this regex gets the href from the anchor tag
regex_href = r"(?is)(?<=href=)\s*(?:([\"']).*?(?=\1)|[^\"'][^\s]*(?=\s|>))"
# I'm not dealing with the following case for getting the anchor tag's text:
# <a href="#"><strong>asdf</strong> hack</a> (the text is: "asdf hack")
# but I'm dealing with <a href="#"><em>asdf hack</em></a>
regex_text = r"(?<=>)[^>]*?(?=</)"
for tag in a_tags:
href = (re.search(regex_href, tag).group(0)).strip()
if href[0] == '"':
href = href[1:]
text = (re.search(regex_text, tag).group(0)).strip()
print(href + "," + text)
def main():
num_lines = int(sys.stdin.readline())
if num_lines >= 100:
return 1
char_count = 0
html_fragment = ""
for i in range(num_lines):
line = sys.stdin.readline()
# reached end of file before reading N lines
if line == '':
break
char_count += len(line)
if char_count > 10000:
return 1
html_fragment += line
detect(html_fragment)
if __name__ == '__main__':
main()
|
'''
Implement pow(x, n), which calculates x raised to the power n.
'''
class Solution:
# Recursive approach
# Time: O(log(n))
# Space: O(log(n))
def myPow(self, x: float, n: int) -> float:
def helper(x, n):
if n == 0:
return 1
result = helper(x, n // 2)
result *= result
if n % 2 != 0:
result *= x
return result
ans = helper(x, abs(n))
if n < 0:
return 1/ans
return ans
# Iterative approach
# Time: O(log(n))
# Space: O(1)
def myPow2(self, x: float, n: int) -> float:
i = abs(n)
result = 1
product = x
while i > 0:
if i & 1 != 0:
result *= product
product *= product
i >>= 1
if n < 0:
return 1/result
return result
solution = Solution()
# Expected: 1024
print(solution.myPow(x = 2.00000, n = 10))
print(solution.myPow2(x = 2.00000, n = 10))
# Expected: 9.261
print(solution.myPow(x = 2.10000, n = 3))
print(solution.myPow2(x = 2.10000, n = 3))
# Expected: 0.25
print(solution.myPow(x = 2.00000, n = -2))
print(solution.myPow2(x = 2.00000, n = -2))
|
# Global variable to store the vowels.
vowels = ['a', 'e', 'i', 'o', 'u']
# Time complexity: O(n*log(n)) where n is the length of the string S.
# Space complexity: O(n) where n is the length of the string S.
def solution(S):
N = len(S)
# Base cases
if N == 0:
return 0
elif N == 1:
return 1
numVowels = 0
for i in S:
if i in vowels:
numVowels += 1
numConsonants = N - numVowels
return abs(numConsonants - numVowels) + solution(S[:N//2]) + solution(S[N//2:])
print(solution("sample"))
print(solution("leetcode"))
print(solution(""))
print(solution("le")) |
'''
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
'''
from leetcode import *
class Solution:
# Bottom-up DP approach
# Time: O(n^2)
# Space: O(n)
def findNumberOfLIS(self, nums: List[int]) -> int:
dp = [(1, 1)]*len(nums)
for i in range(1, len(nums)):
lenLIS, numLIS = dp[i]
for j in range(i):
if nums[i] > nums[j]:
lenIS = dp[j][0] + 1
if lenIS > lenLIS:
numLIS = dp[j][1]
lenLIS = lenIS
elif lenIS == lenLIS:
numLIS += dp[j][1]
dp[i] = (lenLIS, numLIS)
maxLength = 0
maxLengthNum = 0
for length, num in dp:
if length > maxLength:
maxLength = length
maxLengthNum = num
elif length == maxLength:
maxLengthNum += num
return maxLengthNum
solution = Solution()
assert solution.findNumberOfLIS([1,3,5,4,7]) == 2
assert solution.findNumberOfLIS([2,2,2,2,2]) == 5
|
'''
Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that
every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
'''
from leetcode import *
# From leetcode, there's an O(n) time and O(1) space solution using Morris in-order traversal.
class Solution:
# Recursion
# Time: O(n)
# Space: O(H)
def convertBST(self, root: TreeNode) -> TreeNode:
if root is None:
return None
self.runningTotal = 0
def inOrder(root: TreeNode) -> None:
if root.right != None:
inOrder(root.right)
self.runningTotal += root.val
root.val = self.runningTotal
if root.left != None:
inOrder(root.left)
inOrder(root)
return root
# Iterative
# Time: O(n)
# Space: O(H)
def bstToGst(self, root: TreeNode) -> TreeNode:
stack = []
node = root
while node != None:
stack.append(node)
node = node.right
runningTotal = 0
while len(stack) != 0:
node = stack.pop()
runningTotal += node.val
node.val = runningTotal
if node.left != None:
node = node.left
while node != None:
stack.append(node)
node = node.right
return root
|
#!/usr/bin/env python
def P(gc):
"""
Returns the chance that two randomly chosen letters are equal, taken from
two strings with equal GC-content.
"""
CG = gc/2.0;
AT = (1.0-gc)/2.0;
return 2.0 * (CG*CG + AT*AT)
def E(gc,m,n):
"""
Given two strings of lengths m and n, m<n, returns the expected number of
substring matches where m is found inside n.
"""
pm = P(gc)**m # small string
s = 0.0
for i in xrange(0,n-m+1):
s += pm
return s
if __name__ == "__main__":
line = raw_input().split()
m = int(line[0])
n = int(line[1])
A = [float(f) for f in raw_input().split()]
for gc in A:
print E(gc, m, n),
|
#!/usr/bin/env python
import yaml
import json
def printlist(nm,lst):
'''
This function prints a list after a banner with the list name using pprint
the list and name are passes as parameters
'''
from pprint import pprint as pp
banner = "*"*10
nl="\n"
print banner*5,nl
print banner,"Printing %s list "%(nm),nl
print banner*5,nl
pp(lst)
print nl*2
def main():
'''
this function requests a file and a file type yaml or json from the user
it then prints the file using pretty print
'''
yamf = ""
jf = ""
while ".yml" not in yamf:
yamf = raw_input("\nEnter name of yaml file: ")
print "\nYou entered:",yamf
while ".json" not in jf:
jf = raw_input("\nEnter name of json file: ")
print "\nYou entered: ",jf
alist = []
l=[yamf,jf]
for x in l:
with open(x,"r") as fh:
if ".yml" in x:
alist = yaml.load(fh)
printlist(x,alist)
elif ".json" in x:
alist = json.load(fh)
printlist(x,alist)
else:
print "\nFile type error."
if __name__ == "__main__":
main()
|
def sort(array):
if len(array) <= 1:
return array
else:
firsthalf = array[:len(array)/2]
secondhalf = array[len(array)/2:]
return merge(sort(firsthalf), sort(secondhalf))
def merge(array1, array2):
p1, p2 = 0, 0
array3 = []
while True:
if array1[p1] <= array2[p2]:
array3.append(array1[p1])
p1 += 1
elif array1[p1] > array2[p2]:
array3.append(array2[p2])
p2 += 1
if p1 == len(array1):
array3.extend(array2[p2:])
break
if p2 == len(array2):
array3.extend(array1[p1:])
break
return array3
|
#!/usr/bin/env python
# return the index of first pairs that add up to target
def complementary_pair(target, data):
memo = {}
for idx, num in enumerate(data):
com = target - num
memo[com] = idx
if num in memo:
if memo[num] == idx: continue
return "%s + %s = %s at [%s, %s] of %s" % (com, num, target, memo[num], idx, data)
print(complementary_pair(8, [4, 3, 9, 2, 5, 7, 2, 6]))
# 3 + 5 = 8 at [1, 4] of [4, 3, 9, 2, 5, 7, 2, 6]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class PostingsListNode:
def __init__(self, label, nxxt=None, jump=None):
self.label = label
self.order = -1
self.next = nxxt
self.jump = jump
def to_string(self):
memo = "[%s:%d]→ " % (self.label, self.order)
if self.next:
memo += self.next.to_string()
else:
memo += 'x'
return memo
@classmethod
def set_jump_order_recursive(self, node, order=0):
if node and node.order == -1:
order +=1
node.order = order
self.set_jump_order_recursive(node.jump, order)
self.set_jump_order_recursive(node.next, order)
@staticmethod
def set_jump_order_iterative(head):
stack = []
order = 0
stack.append(head)
while len(stack) > 0:
node = stack[-1]
stack.pop()
if node and node.order == -1:
order +=1
node.order = order
stack.append(node.next)
stack.append(node.jump)
# ↱-------↘
# [a]→ [b]→ [c]→ [d]→ x
# ↳-------↗ | ↑↓
# ↖___↙
def example_list():
_d = PostingsListNode('d')
_c = PostingsListNode('c', _d)
_b = PostingsListNode('b', _c, _d)
_a = PostingsListNode('a', _b, _c)
_d.jump = _d
_c.jump = _b
return _a
e1 = example_list()
PostingsListNode.set_jump_order_recursive(e1)
print e1.to_string()
e2 = example_list()
PostingsListNode.set_jump_order_iterative(e2)
print e2.to_string()
"""
[a:1]→ [b:3]→ [c:2]→ [d:4]→ x
[a:1]→ [b:3]→ [c:2]→ [d:4]→ x
"""
|
s=input()
rev = s[::-1]
even = s[::2]
print('Here is the reverse:',rev)
print('Here are chars with even index:',even) |
class Shape(object):
def __init__(self):
pass
def area(self):
return 88
class Square(Shape):
def __init__(self, l):
Shape.__init__(self) # do you need that?
self.length = l
def area(self):
return self.length * self.length # overwriting the area method from super class
try:
aSquare = Square(int(input('Enter the number: ')))
print(f'An area method of Square class returns: {aSquare.area()}')
except Exception as err:
print('Caught an exception')
finally:
print(' --- End of the script execution. --- ')
# Raise RuntimeError('something wrong')
|
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
n = int(input("Give me the number: "))
print("Here is the list of firts %d finobacci numbers: " %n)
list_fib = [str(fib(x)) for x in range(1, n+1)]
print(','.join(list_fib))
print("Here is enumerate list of fibonnaci numbers: ",[(x,y) for (x,y) in enumerate(list_fib)])
#print(fib(n))
|
def check(str):
tmp = 0
for c in str:
if c == '(':
tmp +=1
elif c == ')':
tmp -=1
if tmp < 0:
return 'NO'
if tmp == 0:
return 'YES'
else:
return 'NO'
for i in range(int(input())):
print(check(input())) |
from collections import deque
d = deque()
dic = {'size':lambda x:print(len(d)),
'empty':lambda x:print(0 if d else 1),
'front':lambda x:print(d[0] if d else -1),
'back':lambda x:print(d[-1] if d else -1),
'push_front':d.appendleft,
'push_back':d.append,
'pop_front':lambda x:print(d.popleft() if d else -1),
'pop_back':lambda x:print(d.pop() if d else -1)}
for _ in range(int(input())):
x = list(input().split())
dic[x[0]](x[-1])
|
N = int(input())
for i in range(1,10):
print("{N} * {i} = {Ni}".format(N=N,i=i,Ni=N*i))
|
from gcd_iter import GCD_iter
from functools import reduce
def LCM(a, b):
"""returns the least common multiple (LCM) of two integers a & b"""
assert isinstance(a, int) and isinstance(b, int), "Given arguments have to be integer!"
assert a > 0 and b > 0, "Both arguments need to be different than zero"
lcm = a*b/GCD_iter(a, b)
return int(lcm)
def LCM_n(*l):
"""returns the least common multiple of n integers: a1, a2, ..., an
(recursive way)"""
try:
if len(l) == 2:
return LCM(l[0], l[1])
return reduce(LCM, l)
except TypeError:
print("Given arguments are the wrong type!")
|
def fac_iter(n):
"""returns a factorial (n!) of the natural number n (iterative way)"""
assert isinstance(n, int), "The given number has to be integer!"
assert n >= 0, "Factorial is defined for natural numbers!"
n_factorial = 1
for i in range(1, n+1):
n_factorial *= i
return n_factorial
|
# Solution for: https://www.hackerrank.com/challenges/string-validators/problem?isFullScreen=true&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
def has_alphanumeric(string):
if(len(string) == 1):
return string.isalnum()
if(string.isalnum()):
return True
center = len(string)//2
s1 = string[0:center]
print(s1)
s2 = string[center+1:-1]
print(s2)
return has_alphanumeric(s1) or has_alphanumeric(s2)
def has_alphabetic(string):
pass
if(len(string) == 1):
return string.isalpha()
if(string.isalpha()):
return True
s1 = string[0:len(string)//2]
s2 = string[(len(string)//2)+1:-1]
return has_alphabetic(s1) or has_alphabetic(s2)
def has_digit(string):
pass
def has_lower(string):
pass
def has_upper(string):
pass
if __name__ == '__main__':
s = input()
print(has_alphanumeric(s))
|
# ===================
# Imports
# ===================
import pandas as pd
import numpy as np
import seaborn as sb
from seaborn import countplot
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure,show
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
# ===================
# ML Operation
# ===================
def TitanicLogistic():
#print("Inside logistic function")
#step 1 - Load Data
titanic_data = pd.read_csv("TitanicDataset.csv")
# Data Analysis
print("First five records of dataset : ")
print(titanic_data.head())
"""print("Total Number of records are : ",len(titanic_data))
print(titanic_data.info())"""
#Step 2 - Analyse the data
"""print("Visualization of survived and non survived passengers : ")
figure()
countplot(data=titanic_data,x="Survived").set_title("Survived v/s Non-Survived")
show()
print("Visualization according to gender : ")
figure()
countplot(data=titanic_data,x="Survived",hue="Sex").set_title("Visualization according to Sex")
show()
print("Visualization according to Passenger Class : ")
figure()
countplot(data=titanic_data,x="Survived",hue="Pclass").set_title("Visualization according to Passenger class")
show()
print("Survived v/s Unsurvived based on Age : ")
figure()
titanic_data["Age"].plot.hist().set_title("Visualization according to Age")
show()"""
#Step 3- Data Cleaning (Data Wrangling)
titanic_data.drop("zero",axis=1,inplace=True)
print("Data after column removal : ")
print(titanic_data.head())
Sex = pd.get_dummies(titanic_data["Sex"])
print(Sex.head())
Sex = pd.get_dummies(titanic_data["Sex"],drop_first=True)
print("Ssx column after updation : ")
print(Sex.head())
Pclass = pd.get_dummies(titanic_data["Pclass"])
print(Pclass.head())
Pclass = pd.get_dummies(titanic_data["Pclass"],drop_first=True)
print("Pclass column after updation : ")
print(Pclass.head())
#Concat Sex and P class field in our dataset
titanic_data = pd.concat([titanic_data,Sex,Pclass],axis=1)
print("Data after concatination : ")
print(titanic_data.head())
#Removing uneccesary fields
titanic_data.drop(["Sex","sibsp","Parch","Embarked"],axis=1,inplace=True)
print(titanic_data.head())
#Divide the dataset into X and Y
x = titanic_data.drop("Survived",axis=1)
y = titanic_data["Survived"]
#split the data for training and testing purpose
x_train,x_test,y_train,y_test = train_test_split( x, y, test_size = 0.5, random_state = 0 )
obj = LogisticRegression(max_iter=2000)
#Step 4 - Train the dataset
obj.fit(x_train,y_train)
#Step 5 - Testing
output = obj.predict(x_test)
print("Accuracy of the given dataset is : ")
print(accuracy_score(output,y_test)*100)
print("Confusion Matrix is : ")
print(confusion_matrix(y_test,output))
# =============
# Entry Point
# =============
def main():
print("-------------Logistic Case Study--------------")
TitanicLogistic()
# ==========
# Starter
# ==========
if __name__ == '__main__':
main()
|
###########################################################################
#
#Author:Manali Milind Kulkarni
#Date:15 June 2021
#About: Wine Predictor using K Nearest Neighbour Algorithm.
#
###########################################################################
#Required Python Package
from sklearn import metrics
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
###########################################################################
#Required Functions:
def WinePredictor():
#Load datase
#Here we are using the inbuilt dataset instead of using CSV
wine = datasets.load_wine()
#printing features names
print(wine.feature_names)
#printing target names
print(wine.target_names)
#printing top 5 records
print(wine.data[0:5])
#print the wine labels(0:class_0,1:class_1,2:class_2)
print(wine.target)
#Split the dataset into training dataset and testing dataset
x_train, x_test, y_train, y_test = train_test_split(wine.data,wine.target,test_size=0.3)
#70% tarining and 30% testing data
#Create KNN classifier
knn = KNeighborsClassifier(n_neighbors=3)
#Train the Model using train set
knn.fit(x_train,y_train)
#Predict the response for the test data
y_pred = knn.predict(x_test)
#Model Accuracy, How Often the Model is Correct
print("Accuracy: ",metrics.accuracy_score(y_test,y_pred))
############################################################################
#Main function
def main():
print("-----------------------------Manali Kulkarni-----------------------")
print("------------Machine Learning Application---------------------")
print("--------------Wine Predictor using K Nearest Neighbor Algorith----------------")
WinePredictor()
############################################################################
#Starter
if __name__ == '__main__':
main()
|
contas = []
depositos= []
saldo = []
while True:
def saquei(s):
print('voce recebeu seu dinheiro com nota(s)')
nota_cem = s // 100
s = s % 100
nota_cinquenta = s // 50
s = s % 50
nota_dez = s // 10
s = s % 10
nota_cinco = s // 5
s = s % 5
nota_dois = s // 2
s = s % 2
nota_um = s // 1
if nota_cem > 0:
print(nota_cem,'nota(s) de cem reais')
if nota_cinquenta > 0:
print(nota_cinquenta,'nota(s) de cinquenta reais')
if nota_dez > 0:
print(nota_dez,'nota(s) de dez reais')
if nota_cinco >0:
print(nota_cinco,'nota(s) de cinco reais')
if nota_dois > 0:
print(nota_dois,'nota(s) de dois reais')
if nota_um > 0:
print(nota_um,'nota(s) de um real')
cont = -1
def cria():
ok = bool(int(input('deseja criar uma conta ?. sim digite"1". nao digite "0" ')))
if ok == True:
num = int(input('crie o seu numero da conta: '))
while num in contas:
print('numero ja existente:')
num = int(input(' crie o seu numero da conta: '))
contas.append(num)
saldo.append(0)
def deposito():
num = int(input('digite o numero da sua conta:'))
while num in contas:
global saldo
dep = input('digite "deposito" para depositar e "saque" para saque ')
if dep == 'deposito':
deposito = int(input('digite o valor do seu deposito:'))
depositos.append(deposito)
cont = -1
for a in contas:
cont = cont +1
if a == num:
saldo[cont] = saldo[cont] +deposito
if dep == 'saque':
saque = int(input('digite o valor do seu saque:'))
cont = -1
for a in contas:
cont = cont +1
if a == num:
saldo[cont] = saldo[cont] -saque
saquei(saque)
opp = bool(int(input('deseja ver seu saldo?. sim digite"1". nao digite "0" ')))
while opp:
print('saldo',saldo)
print('contas',contas)
print('depositos', depositos)
break
break
while True:
cria()
deposito()
|
class Element(object):
"""
This class defines a dataset element.
Attributes:
- values (list): Element values.
"""
def __init__(self, values):
self.values = values
@property
def values(self):
"""Get or set the element values."""
return self._values
@values.setter
def values(self, values):
assert isinstance(values, list), \
"The values must be in a list."
self._values = [str(x) for x in values]
|
class ProvenanceObject(object):
"""
This class defines a basic provenance object with
a tag and a json representation.
Attributes:
- tag (str): ProvenanceObject tag.
"""
def __init__(self, tag):
self._tag = tag.lower()
def get_specification(self, prefix="_"):
""" Get the provenance json representation.
Args:
prefix (str): A prefix used to define which variables should be used.
"""
json = {}
for key in self.__dict__.keys():
if key[0] != prefix:
continue
name = key.split(prefix)[1]
value = self.__dict__[key]
if(value is not None):
if(len(value) > 0):
json[name] = value
if isinstance(value, str):
json[name] = value
return json
|
import random
number = random.randint(1, 9)
chances = 0
print("❓🧠The Number Guesser - a math riddle based game🎲🧮")
print("Welcome to The Number Guesser. Here you will be shown a riddle and solving it will give you a numerical answer. Type that in the space given and pass the test. You have 5 chances to guess the correct number. Good Luck!!!")
if number == 1:
print("✖️ ➕What three numbers, none of which is zero, give the same result whether they’re added or multiplied? Type in the least number in them? ➖ ➗")
if number == 2:
print("🍎🍎If there are three apples and you take away two, how many apples do you have?🍏🍏")
if number == 3:
print("👧🏼👧🏽👩🦰A man describes his daughters, saying, “They are all blonde, but two; all brunette but two; and all redheaded but two.” How many daughters does he have?👧🏼👧🏽👩🦰")
if number == 4:
print("🐢🐠Leon works at the aquarium. When he tries to put each turtle in its own tank, he has one turtle too many. But if he puts two turtles per tank, he has on tank too many. How many turtles and how many tanks does Leon have? Type in the number of turtles he has🐢🐠")
if number == 5:
print("👩👧👧Mary has four daughters, and each of her daughters has a brother. How many children does Mary have?👩👧👧")
if number == 6:
print("🚴♂️🦟Two cyclists began a training run, one starting from Moscow and the other starting from Simferopol. When the riders were 180 miles apart, a fly took an interest. Starting on one cyclists shoulder, the fly flew ahead to meet the other cyclist. After reaching him the fly then turned around and yet back. The restless fly continued to shuttleback and fourth until the pair met; then settled on the nose of one rider. The flys speed was 30 mph. Each cyclist speed was 15 mph. How many miles did the fly travel?🚴🏽♂️🦟")
if number == 7:
print("🧮🔢I am an odd number. Take away a letter and I become even. What number am I?🔢🧮")
if number == 8:
print("⚖️🥔How much is this bag of potatoes?' asked the man. '32lb divided by half its own weight,' said the green grocer. How much did the potatoes weigh?🥔⚖️")
if number == 9:
print("👨👧🔞Charlotte is 13 years old. Her father Montague is 40 years old. How many years old was Charlotte when her father was four times as old as Charlotte?🔞👨👧")
while chances<5:
guess = int(input("enter a num 🔢:-"))
if guess == number:
print("🏆Congrats you won🏆")
break
elif guess<number:
print("⛔guess was too low⛔")
else:
print("⛔guess was too high⛔")
chances +=1
if not chances < 5:
print("🙁Aw man. You were so close! The number was : ", number)
print("😃Do you want to play again and discover more math riddles. Type '1' to play again. If you want to exit, type '2' 😃")
choice = int(input("🤔What do you choose. Yes or No🤔 :" ))
if choice <2:
print("💐Welcome back. Press the up arrow key and hit enter to join in again.💐")
else:
print("👋Goodbye. See you later👋")
|
def read_file():
"""
Converts file in list of lines and checks size of field
>read_file()
>> %lines%, True
"""
temp = False
i = 0
with open("file.txt", "r") as f:
lines = f.readlines()
if len(lines) > 10:
return temp
else:
while i < 10:
if len(lines[i]) > 10:
return temp
else:
i += 1
return lines, temp
def has_ship(x, y):
"""
Checks content of that coordinate. If there is normal or damaged ship - returns True.
>has_ship(0, 0)
>> False
"""
temp = False
lines = read_file()
if lines[x][y] == "*" or lines[x][y] == "X":
temp = True
return temp
def ship_size(x, y):
"""
Checks content of coordinate. If there is any ship, than returns its size.
>ship_size(0,0)
>>3
"""
size = 0
if has_ship(x, y):
size += 1
if has_ship(x-1, y):
size += 1
if has_ship(x - 2, y):
size += 1
if has_ship(x - 3, y):
size += 1
elif has_ship(x+1, y):
size += 1
if has_ship(x+2, y):
size += 1
if has_ship(x+3, y):
size += 1
elif has_ship(x, y-1):
size += 1
if has_ship(x, y-2):
size += 1
if has_ship(x, y-3):
size += 1
elif has_ship(x, y+1):
size += 1
if has_ship(x, y+2):
size += 1
if has_ship(x, y+3):
size += 1
return size
def is_valid():
"""
Checks number of ships on the field
>is_valid()
>>True
"""
temp = False
i = 0
j = 0
cap_ship = 0 #size 4
large_ship = 0 #size 3
mid_ship = 0 #size 2
small_ship = 0 #size 1
while i < 11:
while j < 11:
if ship_size(i, j) == 4:
cap_ship += 1
j += 1
elif ship_size(i, j) == 3:
large_ship += 1
j += 1
elif ship_size(i, j) == 2:
mid_ship += 1
j += 1
elif ship_size(i, j) == 1:
small_ship += 1
j += 1
i += 1
j = 0
if (cap_ship == 4) and (large_ship == 6) and (mid_ship == 6) and (small_ship == 4):
temp = True
return temp
|
numero=input('Digite um número de 3 algarismos:')
c=int(numero)/100
if int(c)%2==0:
print('O algarimos das centenas é par',c)
else:
print('O algarismo das centenas é impar',c)
|
print ('10:00')
Min=10
Seg=60
while int(Min)!=9:
Min=int(Min)-1
while int(Seg)!=30:
Seg=int(Seg)-1
print (Min,':',Seg)
|
tipo=input('Seleccione o tipo de carro(A/B/C)')
percurso=input('Insira o número de Km que deseja efectuar:')
if str(tipo)=='C' or str(tipo)=='c':
consumo=int(percurso)/12
elif str(tipo)=='B' or str(tipo)=='b':
consumo=int(percurso)/10
elif str(tipo)=='A' or str(tipo)=='a':
consumo=int(percurso)/8
else:
consumo=0
if consumo !=0:
print('Consumo estimado em litros:',consumo)
else:
print('Modelo inexistente')
|
saldo=input('Introduza o saldo:')
nsaldo=float(saldo)*1.01
print('O novo saldo é:',int(nsaldo))
|
c=input('Introduza o valor em graus centigrados:')
f=(9*float(c)+160)/5
print('Graus farenheit= ',int(f))
|
print('Introduza dois valores')
a=input('a:')
b=input('b:')
quadif=(float(a)-float(b))**2
print('O quadrado da diferença=',int(quadif))
|
factorial=1
i=1
numero= input('Digite um numero:')
while i<(int(numero)+1):
factorial=factorial*i
i=i+1
print(numero,'!=',factorial)
|
n=input('Introduza um número: ')
j=n
i=0
while int(i)<int(n) and int(j)>=1:
i=int(i)+1
j=int(j)-1
print(i,j)
|
preco=input('Digite o valor do produto:')
npreco=float(preco)*0.91
print('Preço com desconto:',float(npreco))
|
num=input('Introduza um número:')
soma=0
produto=1
n=1
while int(n)<=int(num):
soma=soma+n
n=n+1
while int(n)<=int(num):
produto=produto*n
n=n*1
break
print('Soma=',soma,'Produto=',produto)
|
# # Lists
#
# Earlier when discussing strings we introduced the concept of a "sequence" in
# Python. Lists can be thought of the most general version of a "sequence" in
# Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!
#
# In this section we will learn about:
#
# 1.) Creating lists
# 2.) Indexing and Slicing Lists
# 3.) Basic List Methods
# 4.) Nesting Lists
# 5.) Introduction to List Comprehensions
#
# Lists are constructed with brackets [] and commas separating every element in the list.
#
# Let's go ahead and see how we can construct lists!
# Assign a list to an variable named my_list
my_list = [1,2,3]
# We just created a list of integers, but lists can actually
# hold different object types. For example:
my_list = ['A string',23,100.232,'o']
# Just like strings, the len() function will tell you how
# many items are in the sequence of the list.
len(my_list)
##############################
#### Indexing and Slicing ####
##############################
# Indexing and slicing works just like in strings. Let's make a new list to
# remind ourselves of how this works:
my_list = ['one','two','three',4,5]
# Grab element at index 0
my_list[0]
# Grab index 1 and everything past it
my_list[1:]
# Grab everything UP TO index 3
my_list[:3]
# We can also use + to concatenate lists, just like we did for strings.
my_list + ['new item']
# Note: This doesn't actually change the original list!
my_list
# You would have to reassign the list to make the change permanent.
# Reassign
my_list = my_list + ['add new item permanently']
my_list
# We can also use the * for a duplication method similar to strings:
# Make the list double
my_list * 2
# Again doubling not permanent
my_list
#############################
#### Basic List Methods #####
#############################
#
# If you are familiar with another programming language, you might start to draw
# parallels between arrays in another language and lists in Python. Lists in
# Python however, tend to be more flexible than arrays in other languages for a
# two good reasons: they have no fixed size (meaning we don't have to specify
# how big a list will be), and they have no fixed type constraint (like we've seen above).
#
# Let's go ahead and explore some more special methods for lists:
# Create a new list
l = [1,2,3]
# Use the .append() method to permanently add an item to the end of a list:
# Append
l.append('append me!')
# Show
l
# Use "pop" to "pop off" an item from the list. By default pop takes off the last
# index, but you can also specify which index to pop off. Let's see an example:
# Pop off the 0 indexed item
l.pop(0)
# Show
l
# Assign the popped element, remember default popped index is -1
popped_item = l.pop()
popped_item
# Show remaining list
l
# It should also be noted that lists indexing will return an error if there is
# no element at that index. For example:
l[100]
# We can use the **sort** method and the **reverse** methods
# to also effect your lists:
new_list = ['a','e','x','b','c']
#Show
new_list
# Use reverse to reverse order (this is permanent!)
new_list.reverse()
new_list
# Use sort to sort the list (in this case alphabetical order,
# but for numbers it will go ascending)
new_list.sort()
new_list
#######################
#### Nesting Lists ####
#######################
# A great feature of of Python data structures is that they support nesting.
# This means we can have data structures within data structures.
# For example: A list inside a list.
#
# Let's see how this works!
# Let's make three lists
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
# Make a list of lists to form a matrix
matrix = [lst_1,lst_2,lst_3]
# Show
matrix
# Now we can again use indexing to grab elements, but now there are two levels
# for the index. The items in the matrix object, and then the items inside that list!
# Grab first item in matrix object
matrix[0]
# Grab first item of the first item in the matrix object
matrix[0][0]
###########################
### List Comprehensions ###
###########################
# Python has an advanced feature called list comprehensions. They allow for
# quick construction of lists. To fully understand list comprehensions we need
# to understand for loops. So don't worry if you don't completely understand
# this section, and feel free to just skip it since we will return to this topic later.
#
# But in case you want to know now, here are a few examples!
# Build a list comprehension by deconstructing a for loop within a []
first_col = [row[0] for row in matrix]
first_col
# We used list comprehension here to grab the first element of every row in the
# matrix object. We will cover this in much more detail later on!
|
# You are given two integer arrays nums1 and nums2, sorted in non-decreasing order,
# and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
#
# # Merge nums1 and nums2 into a single array sorted in non-decreasing order.
#
# # The final sorted array should not be returned by the function, but instead be stored inside the array nums1.
# To accommodate this, nums1 has a length of m + n,
# where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
def merge_list(nums1, m, nums2, n):
last = m + n -1
while m > 0 and n > 0:
if nums1[m-1] > nums2[n-1]:
nums1[last] = nums1[m-1]
m-=1
else:
nums1[last] = nums2[n-1]
n-=1
last-=1
while n > 0:
nums1[last] = nums2[n]
n, last = n -1, last -1
# print(nums1)
# if nums1[m - 1] > nums2[n - 1]:
# nums1[m + n - 1] = nums1[m - 1]
# m -= 1
# else:
# nums1[m + n - 1] = nums2[n - 1]
# n -= 1
#
# # nums1[:n] = nums2[:n]
#
# print(nums1)
#
# return nums1
if __name__ == '__main__':
nums1 = [1,2,3,0,0,0]
nums2 = [2,5,6]
merge_list(nums1, 3 , nums2, 3) |
# Given an integer array nums and an integer val, remove all occurrences of val in nums in-place.
# The relative order of the elements may be changed.
# Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums.
# More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result.
# It does not matter what you leave beyond the first k elements.
# Return k after placing the final result in the first k slots of nums.
# Do not allocate extra space for another array.
# You must do this by modifying the input array in-place with O(1) extra memory.
def removeElement(nums, val):
count = 0
#判斷nums 是否為空
if nums == None or len(nums) == 0:
return 0;
else:
for i in range(len(nums)):
#判斷是否為符合刪除值
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(nums)
return count
if __name__ == '__main__':
nums_list = [3, 2, 2, 3]
val = 3
removeElement(nums_list, val)
|
def create():
stack = []
return stack
def isEmpty(stack):
return len(stack)==0
def push(stack,value):
stack.append(value)
return stack
def pop(stack):
if(isEmpty(stack)):
return "Empty"
stack.pop()
if __name__ == "__main__":
stack = create()
push(stack,1)
push(stack,2)
print(stack)
pop(stack)
print(stack)
|
import math
result1 = 0
result2 = 0
result3 = 0
for a in range (1,101):
result1 += a
result1 = result1 ** 2
for a in range (1,101):
result2 += a ** 2
result3 = result1 - result2
print(result1)
print(result2)
print(result3) |
"""
algorithms.py
Prime number generation algorithms
@author: Dan Batiste
"""
import random as rand
from math import *
import time
import numpy as np
# Prime checker
def is_prime(n):
"""Checks all possible factors up to floor(sqrt(n))"""
if n == 2:
return True
upperbound = sqrt(n)//1
x = 2
while n % x != 0 and not x == n and not x > upperbound:
if x == 2:
x += 1 # x is 2
continue
x += 2 # x is odd
if x > upperbound:
return True
return False
# Naive algorithm
def naive_algorithm(start, end):
return [x for x in range(start, end+1) if is_prime(x)]
## Sieves
""" DEPRACATED
def sieve_of_eratosthenes(start, end):
# Starts at 1 but only returns from `start` to `end`
sieve = list(range(1, end+1)) # interval [start, end] (inclusive)
# I only need to check up to floor(sqrt(end))
upperbound = int(sqrt(end)//1)
for x in range(1, upperbound):
if x == 1: # If the sieve filtering starts at 1, all numbers will be filtered out.
continue
sieve = [s for s in sieve if (not s%x == 0) or (s == x)]
return list(filter(lambda x: x >= start, sieve))
"""
def sieve_of_eratosthenes(start, n):
# Source: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
# Create a boolean array
# "prime[0..n]" and initialize
# all entries it as true.
# A value in prime[i] will
# finally be false if i is
# Not a prime, else true.
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
# If prime[p] is not
# changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
# Print all prime numbers
results = []
for p in range(2, n+1):
if prime[p] and p >= start:
results.append(p)
return results
def sieve_of_sundaram(start, n):
# Taken from https://en.wikipedia.org/wiki/Sieve_of_Sundaram
# Half written by me
k = (n - 2) // 2
integers_list = [True] * (k + 1)
for i in range(1, k + 1):
j = i
while i + j + 2 * i * j <= k:
integers_list[i + j + 2 * i * j] = False
j += 1
"""
if n > 2:
print(2, end=' ')
for i in range(1, k + 1):
if integers_list[i]:
print(2 * i + 1, end=' ')
"""
check = lambda i, b: b and (i > 0) and ((2*i + 1) >= start)
if n > 2:
integers_final = [2*i + 1 for i, b in enumerate(integers_list) if check(i, b)]
if start <= 2:
integers_final.insert(0,2)
return integers_final
return [2*i + 1 for i, b in enumerate(integers_list) if check(i, b)] |
import collections
# Named tuples for holding add, change, and remove operations
Add = collections.namedtuple('Add', ['path', 'newval'])
Change = collections.namedtuple('Change', ['path', 'oldval', 'newval'])
Remove = collections.namedtuple('Remove', ['path', 'oldval'])
def paths(data, base=None):
'''Walk a data structure and return a list of (path, value) tuples, where
each path is the path to a leaf node in the data structure and the
value is the value it points to. Each path will be a tuple.
'''
if base is None:
base = ()
result = []
if isinstance(data, dict):
for key, val in sorted(data.items()):
result.extend(paths(val, base + (key,)))
elif isinstance(data, list):
for i, val in enumerate(data):
result.extend(paths(val, base + (i,)))
elif base:
result.append((base, data))
return result
def diff(oldstate, newstate):
'''Compare two states, returning a list of Add, Change, and Remove
objects.
Add(path, newval) means path exists in newstate but not oldstate and
its value in newstate is newval.
Change(path, oldval, newval) means that path exists in both oldstate
and newstate but has different values. oldval is the val in oldstate
and newval is the value in newstate.
Remove(path, oldval) means the path exists in oldstate but not in
newstate, and the value in oldstate is oldval.
'''
# Convert oldstate and newstate from a deeply nested dict into a
# single-level dict, mapping a path to a value.
olddict = dict(paths(oldstate))
newdict = dict(paths(newstate))
# Build the list of all paths in both oldstate and newstate to iterate
# over.
all_paths = set()
all_paths.update(set(olddict.keys()))
all_paths.update(set(newdict.keys()))
result = []
for path in sorted(all_paths):
if path in olddict:
if path in newdict:
if olddict[path] == newdict[path]:
pass # Don't emit anything if values are the same
else:
result.append(Change(path, olddict[path], newdict[path]))
else:
result.append(Remove(path, olddict[path]))
else:
result.append(Add(path, newdict[path]))
return result
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python weekend Kiwi.com - Entry task
https://gist.github.com/martin-kokos/6ccdeeff45a33bce4849567b0395526c
Usage: python find_combinations.py < flights.csv > output.txt
cat flights.csv | find_combinations.py
"""
__author__ = "Jan Kammermayer"
__email__ = "honza.kammermayer@gmail.com"
import sys
from datetime import datetime, timedelta
import csv
class Flight(object):
""" Class flight """
def __init__(self, source, destination, departure, arrival, flight_number, price, bags_allowed, bag_price):
self.source = source
self.destination = destination
self.departure = datetime.strptime(departure, '%Y-%m-%dT%H:%M:%S')
self.arrival = datetime.strptime(arrival, '%Y-%m-%dT%H:%M:%S')
self.flight_number = flight_number
self.price = int(price)
self.bags_allowed = int(bags_allowed)
self.bag_price = int(bag_price)
def find_all_possibilities(self, all_flights, bags):
""" Find all possibilities of flight """
return [flight for flight in all_flights if self.check_flight(flight, bags)]
def check_flight(self, next_flight, bags):
""" Check if flight is from source, transfer time and bags """
return self.destination == next_flight.source and \
(next_flight.departure - self.arrival > timedelta(hours=1)) and \
(next_flight.departure - self.arrival < timedelta(hours=4)) and \
(next_flight.bags_allowed >= bags)
def __str__(self):
return self.flight_number
def itinerary(flight, bags, all_flights, path = []):
""" Find all possible paths for flight """
path.append(flight)
possibilities = flight.find_all_possibilities(all_flights, bags)
if validate_path(path):
print_path(path, bags)
if possibilities:
for next_flight in possibilities:
itinerary(next_flight, bags, all_flights, path)
path.pop(len(path) - 1)
def load_data(csv_file):
""" Load data from file and create objects Flight """
next(csv_file) # Skip header
return [Flight(*flight) for flight in csv.reader(csv_file)]
def validate_path(path):
""" Check if path is valid """
if len(path) < 2:
return False
for x, a in enumerate(path):
for b in path[x + 1:]:
if a.source == b.source and a.destination == b.destination:
return False
return True
def print_path(path, bags):
""" Print path """
price = 0
print('{} -> '.format(path[0].source), end='')
for flight in path:
print('{} ({})-> '.format(flight.destination, flight.flight_number), end='')
price += flight.price + bags * flight.bag_price
print("{}".format(price))
if __name__ == '__main__':
file = open('flights.csv')
else:
file = sys.stdin
all_flights = load_data(file)
for bags in range(0, 3):
print('### {} bags ###'.format(bags))
flights_by_bags = [flight for flight in all_flights if flight.bags_allowed >= bags]
for flight in flights_by_bags:
itinerary(flight, bags, all_flights, [])
|
# Ejercicio 11:
# Crear un programa que almacene la cadena de caracteres contraseña en una variable,
# pregunte al usuario por la contraseña e imprima por pantalla si la contraseña
# introducida por el usuario coincide con la guardada en la variable.
password = "calabaza"
passwd_pedido = input("Enter your password: ").lower()
def pwd():
if passwd_pedido != password:
print("La contraseña es incorrecta.")
else:
print("La contraseña es correcta.")
#Estudiar este a ver si consigo que pida el input nuevamente.
def contra():
while passwd_pedido != password:
print("La contraseña es incorrecta.")
print(input("Ingrese su contraseña nuevamente: "))
if passwd_pedido == password:
print("La contraseña es correcta.")
pwd() |
# Ejercicio 8:
# Crear un programa que pregunte al usuario una cantidad a invertir, el interés anual y el
# número de años, y muestre por pantalla el capital obtenido en la inversón.
inversion = float(input("Ingrese la cantidad a invertir: "))
interes = float(input("Ingrese el interés anual: "))
anos = int(input("Ingrese la cantidad de años: "))
def plazo():
total1 = (inversion * interes * anos)
total2 = total1 - inversion
print("De acuerdo a la información suministrada, usted ganará", total1, "lo que incrementa su capital en", total2)
plazo() |
# Ejercicio 19:
# Crear un programa en el que se pregunte al usuario por una frase y una letra, y
# muestre por pantalla el número de veces que aparece la letra en la frase.
frase = input("Ingrese una frase: ")
letra = input("Ingrese una letra a buscar: ")
def busqueda():
print("La letra", letra, "aparece", frase.count(letra), "veces.")
busqueda() |
from book import Book
import json
def get_menu():
print('Press 1 to add a new book')
print('Press 2 to save books')
print('Press 3 to load books')
print('Press 4 to find a book')
print('Press 5 to issue a book')
print('Press 6 to return a book')
print('Press 7 to show books')
print('Press x to exit')
print('\nEnter your choice :', end=' ')
def create_book():
id=int(input('ID: '))
name=input("Name of the book: ")
description=input('Description: ')
isbn=input('ISBN: ')
page_count=int(input('Page count: '))
issued=False
author=input('Author name: ')
year=input('Year of publication: ')
book=Book(id,name,description,isbn,page_count,issued,author,year)
return book
def save_books(book_store):
books_dicts=[book.to_dict() for book in book_store]
try:
with open('library.dat','w') as file:
file.write(json.dumps(books_dicts,indent=5))
print('Saved successfully...')
except:
print('Something went wrong!')
def load_books():
try:
with open('library.dat','r') as file:
book_dicts=json.loads(file.read())
books=[Book(book['id'],book['name'],book['description'],book['isbn'],book['page_count'],book['issued'],book['author'],book['year']) for book in book_dicts]
return books
except:
print('Something went wrong!')
def find_book():
id=int(input('Enter ID: '))
try:
with open('library.dat','r') as file:
book_dicts=json.loads(file.read())
for book in book_dicts:
if book['id']==id:
return Book(book['id'],book['name'],book['description'],book['isbn'],book['page_count'],book['issued'],book['author'],book['year'])
return 'Book with id {id} not found'.format(id=id)
except:
print('Something went wrong!')
def issue_book(books):
id=int(input('Enter ID: '))
for book in books:
if book.id==id:
if book.issued==False:
book.issued=True
print('Issued successfully...')
else:
print('Book is already issued to someone else!')
return
print('Book with id {id} not found'.format(id=id))
def return_book(books):
id=int(input('Enter ID: '))
for book in books:
if book.id==id:
if book.issued==True:
book.issued=False
print('Returned successfully...')
return
print('Book with id {id} not found'.format(id=id))
def show_books(books):
for book in books:
print('ID: ',book.id)
print('Name :',book.name)
print('Author: ',book.author)
print('-------------------------------') |
"""
practical week 7
"""
from Programming_Language import ProgrammingLanguage
ruby = ProgrammingLanguage("Ruby", "Dynamic", True, 1995)
python = ProgrammingLanguage("Python", "Dynamic", True, 1991)
visual_basic = ProgrammingLanguage("Visual Basic", "Static", False, 1991)
print(ruby.is_dynamic()) # testing the is_dynamic function
print(python.is_dynamic())
print(visual_basic.is_dynamic())
print(ruby) # testing the __str__ function
print(python)
print(visual_basic)
language_list = [ruby, python, visual_basic] # looping through the list
print("the dynamically typed languages are:")
for language in language_list:
if language.is_dynamic() is True:
print(language.name)
|
import nltk,re
def f1(h,t):
'''
Check if first is capital
'''
if (h[2][h[3]].istitle()) and (t == "PERSON" or t == "ORGANIZATION" or t == "GPE"):
return 1
else:
return 0
def f2(h,t):
'''
use dictionary for organization enumeration
'''
dic = ["alcatel","amazon","apple","asus","blackberry","byond","coolpad","gionee","google","hp","honor","htc","huawei","iball","infocus","intex","jolla","karbonn","lava","lenovo","lg","micromax","microsoft","motorola","nokia","oneplus","samsung","oppo","panasonic","penta","phicomm","philips","sony","spice","vivo","wickedleak","xiaomi","xolo","yu","zte","kingston","pebble","strontium","sunstrike","sandisk"]
# print h[2][h[3]]
if (h[2][h[3]].lower() in dic) and (t == "ORGANIZATION"):
return 1
else:
return 0
def f3(h,t):
'''
GPE if previous is "in" or "at"
'''
if (h[2][h[3]-1] in ["in","at"]) and t == "GPE":
return 1
else:
return 0
def f4(h,t):
'''
Money regex
'''
dic = []
print re.match(r'\d+',h[2][h[3]]), h[2][h[3]]
if(re.match(r'\d+',h[2][h[3]]) and(h[2][h[3]-1] in ["$","Rs"] or h[2][h[3]-2] in ["$","Rs"])) and t == "MONEY":
return 1
else:
return 0
def f5(h,t):
'''
Organization followed by inc or corp
'''
#print h[2][h[3]+1]
if(h[3]+1<len(h[2]) and h[2][h[3]+1] in ["inc.","corp","inc","corp."]) and t == "ORGANIZATION":
return 1
else:
return 0
def f6(h,t):
if(re.search('^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$',h[2][h[3]]) or re.search('^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$',h[2][h[3]])) and t == "DATE":
return 1
else:
return 0
def f7(h,t):
'''
Organization followed by product model
'''
for i in range(1,4):
if h[3]+i<len(h[2]) and (re.match(r'\d*\[a-zA-Z]+\d+',h[2][h[3]+i])) and t == "ORGANIZATION":
return 1
else:
return 0
def f8(h,t):
'''
City, State/Country eg: Bangalore, India
'''
if(h[0]=="GPE" and h[2][h[3]-1]==",") and t == "GPE":
return 1
else:
return 0
def f9(h,t):
'''
Person if next word is said,rebutted .....
'''
if(h[3]+1<len(h[2]) and h[2][h[3]+1] in ["said","rebutted","told"]) and t == "PERSON":
return 1
else:
return 0
def f10(h,t):
'''
if in a window of 5 there is a stem with cost or price
'''
porter_stemmer = nltk.PorterStemmer()
#print 'sent : ',h[2]
if len(h[2]) >= 5:
for i in range(h[3]-5,h[3]):
#print h[2]
if (porter_stemmer.stem(h[2][i]) in ["price","pay","paid","cost","payment","buy","bought"]) and (t == "MONEY"):
return 1
else:
return 0
def f11(h,t):
'''
for OTHER
'''
if (not h[2][h[3]].istitle() or h[2][h[3]-1]==".") and (t == "OTHER"):
return 1
else:
return 0
if __name__=="__main__":
print f10(("LOCATION","t1",nltk.word_tokenize("Hello there Ashwin is in Bangalore, India Microsoft bought X50 for Rs. 100."),14),"MONEY") |
# increase_5
print("Addition of 5 to 3 numbers you enter...")
input("If ok, press RETURN ")
i = 0
j = 0
k = 0
while i == 0:
try:
a = int(input("Enter the first number : "))
i += 1
except ValueError:
print("It's not a number. Try again ")
first = a
while j == 0:
try:
b = int(input("Enter the second number: "))
j += 1
except ValueError:
print("Look better, you made it wrong again. Enter a number ")
second = b
while k == 0:
try:
c = int(input("Enter the third number: "))
k += 1
except ValueError:
print("Not number. Enter a number: ")
third = c
if first == second or second == third or first == third:
first = first+5
second = second+5
third = third+5
print("All three numbers are increased by 5. " + "\n" + "See them below: ")
print("First = {}".format(first) + "\n" + "Second = {}".format(second) + "\n" + "Third = {}".format(third))
else:
print("No two equal numbers found")
|
import math
def MaxRectange(lenstr):
"""
Base on the original string, it will be divided into
a rectange with the max column and row
"""
MAXROW = math.sqrt(lenstr)
if MAXROW > int(math.sqrt(lenstr)):
MAXCOL = int(math.sqrt(lenstr)) + 1
MAXROW = int(math.sqrt(lenstr))
# print(MAXROW,MAXCOL) # Check MAXROW and MAXCOL
return (MAXROW,MAXCOL)
else:
MAXCOL = int(math.sqrt(lenstr))
MAXROW = int(math.sqrt(lenstr))
# print(MAXROW, MAXCOL) # Check MAXROW and MAXCOL
return (MAXROW, MAXCOL)
def addListWord(row, col, lenstr, string):
"""
:param row: MaxROW from MaxRectange function
:param col: MaxCOL from MaxRectange function
:param string: the original string without space
:return: new listword []
"""
count = 0
word = ""
listword = [] # Add the new word after divided in term of MAXCOL
SupplySpace = col * row - lenstr # Add more space to word if length of string is not equal the square
for i in string:
# print(i,end="")
word += i
count += 1
if count % col == 0:
# print()
listword.append(word)
word = ""
if SupplySpace > 0:
listword.append(word + ((" ") * SupplySpace)) # Add more space
print("List Word: {}".format(listword)) # Check the new list word
return listword
def encode(length, listword):
"""
Encoded the message is obtained by
reading down the column going left to right
"""
for i in range(0,length):
for word in listword:
print(word[i], end="")
print()
def main():
#text = "if man was meant to stay on the ground god would have given us roots"
while True:
text = input("Enter: ")
newstring = text.replace(" ","")
lenstr = len(newstring)
if lenstr <= 81:
break
row, col = MaxRectange(lenstr)
listword = addListWord(row, col, lenstr, newstring)
encode(col, listword)
main() |
#!/usr/bin/python
"""This is a utility program to help anonymize dates within a dataset. The
concept is that the relationships between events in a clinical trial are
important, but it creates an opportunity for patient re-identification if
correlated with external data that includes dates and times. This tool finds
the earliest time in a CSV file and then references all of the other times
based on that index time. This retains the relationships between events
without pinning that timeline to a specific date and time that can be used
to re-identify patients.
NOTE: This is brittle, in that any time that is disambiguated will then expose
the entire timeline. Because of this, a 'fuzz' factor is specified, creating
a random noise parameter for each value. Please note that long periods of
high-resolution measurements will make this approach unworkable."""
import datetime
import random
def interval(indexDateTime , targetDateTime , fuzzFactor):
"""Provide a datetime object for the index time, the time that needs the
interval after the index time measures (again, as a Python datetime
object), and a fuzz factor in seconds, which will be an integer defining
the size of the fuzzing window, in seconds."""
intervalDays = 0
intervalHours = 0
intervalMinutes = 0
intervalSeconds = 0
ff = random.randint(0 , fuzzFactor)
intervalSeconds = datetime.timedelta.total_seconds\
(targetDateTime - indexDateTime) + ff
# Here we also generate, selectively, appropriate other measures
if (intervalSeconds > 60):
intervalMinutes = intervalSeconds / 60
else:
intervalMinutes = 0
if (intervalSeconds > 60 * 60):
intervalHours = intervalSeconds / 60 / 60
else:
intervalHours = 0
if (intervalSeconds > 60 * 60 * 24):
intervalDays = intervalSeconds / 60 / 60 / 24
else:
intervalDays = 0
i = (intervalDays , intervalHours , intervalMinutes, intervalSeconds)
return i
|
def int_num(n_num):
x = (int(str(n_num) + str(n_num))) + (int(str(n_num) + str(n_num) + str(n_num)))
return x + n_num
n_num = int(input("please input something: "))
print(int_num(n_num)) |
user_input = int(input("items count you want: "))
user_items = []
market_stock = ["item1", "item2", "item3"]
available_items = []
for i in range(user_input):
it_em = input("enter name: ")
user_items.append(it_em)
for it_em in user_items:
if it_em in market_stock:
available_items.append(it_em)
print(available_items)
|
user_name = input("Please enter your name: ")
print(user_name)
user_age = input("Please enter your age: ")
print(user_age)
var_age = int(user_age)
var_years_old = 100 - var_age
var_year = 2020 + var_years_old
print("In", var_year, "you will be 100 years old.")
|
import sqlite3
conn = sqlite3.connect('bank_account.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS bank_account (
name text,
social integer,
account_number integer PRIMARY KEY,
balance integer
)""")
c.execute("""CREATE TABLE IF NOT EXISTS credit_card (
name text,
social integer,
account_number integer PRIMARY KEY,
balance integer,
card_no integer,
credit_limit integer
)""")
c.execute("""CREATE TABLE IF NOT EXISTS savings_account (
name text,
social integer,
account_number integer PRIMARY KEY,
balance integer,
rate real
)""")
print(c.fetchall())
conn.commit()
conn.close()
|
num1 = int(input('Введите первое число: '))
num2 = int(input('Введите второе число: '))
arith_arg = input('Что с ними делать? (+ для сложения, - для вычитания, * для умножения, / для деления, % для выделения целого остатка): ')
if arith_arg == '+':
final = num1+num2
print('Ответ: '+str(final))
elif arith_arg == '-':
final = num1-num2
print('Ответ: '+str(final))
elif arith_arg == '*':
final = num1*num2
print('Ответ: '+str(final))
elif arith_arg == '/':
final = num1/num2
print('Ответ: '+str(final))
elif arith_arg == '%':
final = num1%num2
print('Ответ: '+str(final))
else:
print('Неизвестная операция')
xcxc=input('Enter для выхода')
|
# 문제 01. 2단 출력
def GuGu(n):
result = []
for i in range(9):
result.append(n*(i+1))
return result
print(GuGu(2))
# 문제 02. 3과 5의 배수 합하기
def sumAll(number):
sumi = []
sumj = []
i = number // 3
j = number // 5
for i in range(i):
sumi.append(3*(i+1))
for j in range(j):
sumj.append(5*(j+1))
sumset = set(list(sumi + sumj))
a = 0
for k in sumset:
a += k
return a
print(sumAll(1000))
# 선생님 풀이
result = 0
for n in range(1,1000):
if n % 3 == 0 or n % 5 == 0: # or로 연결해야 중복되지 않음
result += n
print(result)
# 문제 03. 게시판 페이징하기
def getTotalPage(m, n):
if (m%n == 0):
return (m // n)
else:
return (m // n)+1
print(getTotalPage(12,5))
|
print("hello world")
station = ["사당", "신도림", "인천공항"]
num=[0,1,2]
for i in num:
print(station[i]+"행 열차가 들어오고 있습니다.") |
import turtle
#Define the functino squal
#Crate n squares increasing the angle
def draw_square(form):
i = 1
while i < 5:
form.forward(100)
form.right(90)
i = i +1
def draw_art():
window = turtle.Screen()
window.bgcolor("navy")
angie = turtle.Turtle()
angie.shape("turtle")
angie.color("white")
angie.speed(1000)
for i in range(380):
draw_square(angie)
angie.right(13)
draw_art()
|
a = int(input())
fat = 1
for x in range(1,a+1):
fat*=x
print(fat) |
a = 21
b = 10
c = 0
print (a ** c)
print (a // b)
print (a % b)
print (a / b)
#Python logical operators
print (a and b)
print (c and b)
print (a or b)
print (c or b)
print (not(c or b))
i = 2
j = 2
print(i % j)
print(i % j == 0)
print (not(i % j))
#If Loop
var = 100
if ( var == 100 ):
print ("变量 var 的值为100")
else:
print ("Good bye!")
#range & len
fruits = ['banana', 'apple', 'mango']
print (len(fruits)) #3
print (range(len(fruits))) #range(0,3)
range(3)
range(0,1,2)
#Python3 iterators and generators
list=[1,2,3,4]
it = iter(list)
print(next(it)) #next(iterator[, default]) #out put =1
print(next(it)) #function 2 times, iter mannually, using for loop
class JustCounter:
__secretCount = 0 # 私有变量
publicCount = 0 # 公开变量
def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount) |
# str = input("Please input a long string: ")
# str = "Tina Love Bobby"
# new_str = str.split(" ")
# output_list = []
# i = len(new_str) -1
# while i >= 0:
# output_list.append(new_str[i])
# i -= 1
# a = [0,1,2]
# print(output_list)
# print(" ".join(output_list[i] for i in a))
def reverse_string():
str = input("Please input a long string: ")
#split the string into single word
new_str = str.split(" ")
#reverse the list
output_list = []
i = len(new_str) -1
while i >= 0:
output_list.append(new_str[i])
i -= 1
#prepare list for generator expression
i = 0
a = []
while i < len(output_list):
a.append(i)
i += 1
#output
print(" ".join(output_list[i] for i in a))
reverse_string()
# output_list=["Bobby","Love","Tina"]
# i = 0
# a = []
# while i < len(output_list):
# a.append(i)
# i += 1
# print(a)
|
import csv
from collections import Counter
with open("data.csv") as f:
reader=csv.reader(f)
file_data=list(reader)
file_data.pop(0)
#print(file_data)
# sorting data to get the height of people
new_data=[]
for i in range(len(file_data)):
n_num=file_data[i][2]
new_data.append(float(n_num))
#calculating mode
data=Counter(new_data)
mode_data_for_range={ "50-60":0,"60-70":0,"70-80":0}
#height=key, occurrence=value in (key,value) pair
for height,occurrence in data.items():
if 50< float(height) <60:
mode_data_for_range["50-60"] += occurrence
elif 60< float(height) <70:
mode_data_for_range["60-70"] += occurrence
elif 70< float(height) <80:
mode_data_for_range["70-80"] += occurrence
mode_range,mode_occurrence=0,0
for range,occurrence in mode_data_for_range.items():
if occurrence>mode_occurrence:
mode_range,mode_occurrence =[int(range.split("-")[0]),int(range.split("-")[1])],occurrence
mode=float((mode_range[0]+mode_range[1])/2)
print(f"Mode is : {mode:2f}" )
|
#!/usr/bin/env python
"""
modified from https://github.com/bozhu/RC4-Python
"""
import binascii
class rc4:
""" Class for RC4"""
def __init__(self):
"""
The constructor
@param self The object
"""
self.key = 'Key' # default key is 'Key'
self.infile = ''
self.outfile = ''
def KSA(self,key):
"""
Completes the key-scheduling algorithm
@param self The object
@param key String containing the key to use
@return list S
"""
keylength = len(key)
S = range(256)
j = 0
for i in range(256):
j = (j + S[i] + key[i % keylength]) % 256
S[i], S[j] = S[j], S[i] # swap
# return list S
return S
def PRGA(self,S):
"""
Completes the pseudo-random generation algorithm
@param self The object
@param S the list created from the key
@returns a generator K
"""
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i] # swap
K = S[(S[i] + S[j]) % 256]
yield K
def RC4(self,key):
"""
Runs both parts of the RC4 cipher
@param self The object
"""
S = self.KSA(key)
return self.PRGA(S)
def convert_key(self,key):
"""
Returns the decimal value of the characters in the key
@param self The object
@param key The string containing the key
@return a generator containing values from the key
"""
return [ord(c) for c in key]
def rc4main(self,infile,outfile):
"""
Starts the main processing of RC4 for the specified file (infile)
Writes out the encrypted result to (outfile)
@param self The object
@param infile String containing the input filename
@param outfile String containing the output filename
"""
# read the infile in
with open(infile,"rb") as f:
plaintext = f.read()
# key is a list containing the key
key = self.convert_key(self.key)
# this is a generator variable
keystream = self.RC4(key)
# open the file to write the encrypted contents to
f = open(outfile,"wb")
for c in plaintext:
val = str(hex(ord(c) ^ keystream.next())).split('x')[1]
# if the hex value only has one character (ex. 0x9), add a 0 before it
# this fixes the binascii "odd length string" error
if 1 == len(val):
val = "0" + str(val)
f.write(binascii.a2b_hex(val))
f.close()
|
"""Class definitions for musical objects"""
from lib import defineChord as dc
"""
Matrix = [measure][voice][Cell]
getNotes() composes for Cells, not measure by measure, and not beat by beat
for now, the matrix isn't broken into beats, cells are the smallest part, each cell has 1 chord
Class Hierarchy
Music = key, major, timeSig
Chord = root, tonality, seventh, inversion, secondary, secondaryRoot
Note = pitch, distance, rhythm, tied
Cell = chord, beats, notes, rhythms
"""
class Music:
def __init__(self, key = 'c', major = True, timeSig = None):
self.key = key # string: root, with s = sharp, f = flat. 'c', 'cs', etc
self.major = major # boolean: True or False
self.timeSig = timeSig # [int, int] array: index 0 = beats, index 1 = rhythmic base value
if timeSig is None:
self.timeSig = [4,4] # default is [4,4]
class Chord(Music):
def __init__(self, root, tonality = 0, seventh = False, inversion = 0, secondary = False, secondaryRoot = 0, key = 'c', major = True, timeSig = None):
Music.__init__(self, key, major, timeSig)
self.root = root # int: chord root, represents Roman numeral number (key/accidentals are irrelevant)
self.tonality = tonality # int: represents moving from tonal triad up/down (ie. minor v to V = 1, IV to minor iv = -1)
self.seventh = seventh # boolean: False = triad, True = 7th
self.inversion = inversion # int: 0 = None, 1 = 1st, 2 = 2nd, 3 = 3rd
self.secondary = secondary # boolean: False = no, True = secondary
self.secondaryRoot = secondaryRoot # int: 1-7, represents Roman numeral number root of secondary (dominant) chord
def getPitches(self):
return dc.defineChord(self)[0]
class Note(Chord):
def __init__(self, pitch, distance, rhythm, tied, root, tonality = 0, seventh = False, inversion = 0, secondary = False, secondaryRoot = 0, key = 'c', major = True, timeSig = None):
Chord.__init__(self, root, tonality, seventh, inversion, secondary, secondaryRoot, key, major, timeSig)
self.pitch = pitch # string: lowercase char plus "s" for sharp, "f" for flat, "ss", or "ff" - 'r' for rest
self.distance = distance # int: 0-88, distance from lowest pitch "A0" = 0, "C4" = 39 (middle C), "C8" = 87, rest = 88
self.rhythm = rhythm # int: 1 = whole note, 2 = half, 4 = quarter, 8 = 8th, 16 = 16th
self.tied = tied # boolean: False = not tied to next note, True = tied to next note
def inChord(self):
return [chordPitch for chordPitch in self.getPitches()] # inherited from Chord class
def getIntervalFrom(self, note2):
return self.distance - note2.distance
def getIntervalTo(self, note2):
return note2.distance - self.distance
class Cell:
def __init__(self, chord, nextChord, beats, notes, destination, voice):
self.chord = chord # Chord class: see definition above
self.nextChord = nextChord # Chord class: the next chord so we know where to start the next Cell
self.beats = beats # [int] array: contains the beats that this cell covers, ie. [1, 2], max size is 1 measure
self.notes = notes # [Note] array: see Note definition above, contains data including pitch and rhythm
self.destination = destination # int: 'distance' 0-87 of destination
self.voice = voice # int: 0 = bass, voice numbers ascend, ie. soprano = 2 in 3-voice harmony
|
"""Converts distance value (0-87, 88=rest) to pitch ('a','cs','ef', etc)"""
def distanceToPitch(distance):
# if a rest
if distance == 88:
return 'r'
# if not a rest
else:
distance %= 12
pitchArray = ['a','bf','b','c','cs','d','ef','e','f','fs','g','af']
return pitchArray[distance]
|
# node colors
RED = 'red'
BLACK = 'black'
class Node(object):
def __init__(self, data, parent = None, color = RED):
self.color = color
self.data = data
self.leftChild = None
self.rightChild = None
self.parent = parent
def changeColor(self):
if self.color == RED:
self.color = BLACK
else:
self.color = RED
print(' in changeColor %s ' % self.color)
# node = Node(12)
# print(' color %s ' % node.color)
# node.changeColor()
# print(' color %s ' % node.color)
class RedBlackTree(object):
def __init__(self):
self.root = None
def insert(self, data, color = RED):
self.root = self.insertNode(data, self.root, None, color, True)
def insertWithoutValidation(self, data, color = RED):
self.root = self.insertNode(data, self.root, None, color, False)
def insertNode(self, data, node, parent, color, validate):
if not node: # если подДерево пустое, то Вернем новую ноду
# print(' * new node %d %s' % (data, color))
if parent:
return Node(data, parent, color)
else:
return Node(data, parent, BLACK) # корень дерева BLACK
if node.data < data: # идем в правое подДерево
# print(' >>> ')
node.rightChild = self.insertNode(data, node.rightChild, node, color, validate)
if validate:
self.validateTree(node.rightChild)
return node
elif node.data > data: # идем в левое подДерево
# print(' <<< ')
node.leftChild = self.insertNode(data, node.leftChild, node, color, validate)
if validate:
self.validateTree(node.leftChild)
return node
# прошли вставку ноды и теперь нужно провалидировать подДерево на правила
if validate:
return self.validateTree(node)
return node
# проверка дерева на соответствие правилам
def validateTree(self, node):
# case 1 левый правый
if node.color == RED and node.parent:
# B
# / \
# R R
# \
# xR
# recolor grandPa and his children =>
# xR
# / \
# B B
# \
# R
parent = node.parent
if (
parent.color == RED
and parent.parent and node.parent.parent
and node.parent.parent.color == BLACK
and node.parent.parent.leftChild and node.parent.parent.leftChild.color == RED
and node.parent.parent.rightChild and node.parent.parent.rightChild.color == RED
):
print('case 1 !!!')
print(' %d parent => %d => grandPa => %d ' % (node.data, node.parent.data, node.parent.parent.data))
grandPa = parent.parent
# перекрасить нужно дедушку и его детей
grandPa.changeColor()
grandPa.leftChild.changeColor()
grandPa.rightChild.changeColor()
return self.validateTree(grandPa) # запускаем валидацию от дедушки
# case 2
if node.color == RED and node.parent:
# 5B
# / \
# 3R 6B
# \
# x4R
# rotateLeft 3R =>
# 5B
# / \
# 4R 6B
# /
# x3R
parent = node.parent
# вот тут проверяем для левого поддерева!
# TODO: сделать для grandPa.leftChild
if (
parent.color == RED
and parent.rightChild and parent.rightChild == node # node in parent.right
and parent.parent and parent.parent.color == BLACK # grandPa
and parent.parent.rightChild and parent.parent.rightChild.color == BLACK # rightChild GrandPa
and parent.parent.leftChild == parent # leftChild GrandPa
):
print('CASE 2 / left subTree / in grandPa')
print(' %d parent => %d => grandPa => %d ' % (node.data, parent.data, parent.parent.data))
grandPa = parent.parent
# повернуть налево отца и вернуть его обратно
print('rotateLeft', node.parent.data)
self.rotateLeft(node.parent)
print('grandPa.leftChild.leftChild %d' % grandPa.leftChild.leftChild.data)
return self.validateTree(grandPa.leftChild.leftChild) # запускаем валидацию от ребенка
return node
def rotateLeft(self, node):
parent = node.parent
tempRight = node.rightChild
print('tempRight %s' % tempRight.data)
tempRightLeft = tempRight.leftChild
print('tempRightLeft %s' % tempRightLeft)
tempRight.leftChild = node
node.rightChild = tempRightLeft
# переприсваиваем родителей
tempRight.parent = node.parent
tempRight.leftChild.parent = tempRight
if node.rightChild and node.rightChild.parent:
node.rightChild.parent = node
print('parent', parent)
if parent and parent.leftChild and parent.leftChild.data == node.data:
print('parent.leftChild')
parent.leftChild = tempRight
print(parent.leftChild.data, parent.leftChild.parent.data)
print(parent.leftChild.leftChild.data, parent.leftChild.leftChild.parent.data)
else:
print('parent.rightChild')
parent.rightChild = tempRight
return tempRight
def rotateRight(self, node):
tempLeft = node.leftChild
tempLeftRight = tempLeft.rightChild
tempLeft.rightChild = node
node.leftChild = tempLeftRight
# переприсваиваем родителей
tempLeft.parent = node.parent
node.parent = tempLeft
if node.leftChild and node.leftChild.parent:
node.leftChild.parent = node
return tempLeft
def traverse(self):
if self.root:
return self.traverseInOrder(self.root, [])
return []
###
def traverseInOrder(self, node, array):
if node.leftChild:
array = self.traverseInOrder(node.leftChild, array)
parentData = None
if node.parent:
parentData = node.parent.data
print(' => %d|%s /up %s' % (node.data, node.color, parentData))
array.append([node.data, node.color, parentData]) # для проверки
if node.rightChild:
array = self.traverseInOrder(node.rightChild, array)
return array
# rb = RedBlackTree()
# rb.insert(5)
# rb.insert(3)
# rb.insert(6)
# rb.insert(4)
# # 5
# # / \
# # 3 6
# # \
# # 4
# print(rb.traverse())
# case1 = [[3, 'black'], [4, 'red'], [5, 'red'], [6, 'black']]
# assertEqual(rb.traverse(), case1)
# import sys
# sys.stdout.write('.')
# sys.stdout.write(' ,,,, \n')
# print(' ,,,,', end='')
# print(' ,,,,', end='', flush=True)
|
"""
Advent of Code 2020 - Day 9 Part 1 - December 16, 2020
"""
# initialized variables
nums = []
previousNums = []
difference = 0
counter = 0
invalid = 0
# reads text file of input
data = open('Raw Data\Day09input.txt', 'r')
# stores each line of text file in a list
for line in data:
nums.append(line[:-1])
# iterate through each number in the data list
for number in nums[25:]:
previousNums = nums[0+counter:25+counter]
check = False
# iterate through each of the previous 25 number
# if the difference between the number and one of the previous numbers
# is within the list of the previous 25, then break and move on to next
for previousNum in previousNums:
difference = int(number)-int(previousNum)
if str(difference) in previousNums:
check = True
break
# if the number was not a sum of two of the previous 25,
# break out of loop and set invalid = number
if not check:
invalid = number
break
counter += 1
print("The number that does not follow the pattern is:", invalid)
|
"""
Advent of Code 2020 - Day 9 Part 2 - December 16, 2020
"""
# initialized variables
nums = []
previousNums = []
difference = 0
counter = 0
sum = 0
total = 0
elementsList = []
answer = 0
count = 0
search = True
# reads text file of input
data = open('Raw Data\Day09input.txt', 'r')
# stores each line of text file in a list
for line in data:
nums.append(line[:-1])
# iterate through each number in the data list
for number in nums[25:]:
previousNums = nums[0+counter:25+counter]
check = False
# iterate through each of the previous 25 number
# if the difference between the number and one of the previous numbers
# is within the list of the previous 25, then break and move on to next
for previousNum in previousNums:
difference = int(number)-int(previousNum)
if str(difference) in previousNums:
check = True
break
# if the number was not a sum of two of the previous 25,
# break out of loop and set invalid = number
if not check:
sum = number
break
counter += 1
# iterate through each number and grow a total,
# when total > sum, break and go to next number starting value
# if total == sum, break
while search:
for number in nums[count:]:
total += int(number)
elementsList.append(number)
if total == int(sum):
break
elif total > int(sum):
total = 0
elementsList = []
break
if elementsList != []:
search = not search
count += 1
# sort list of nums numerically and add smallest and largest numbers
elementsList.sort()
answer = int(elementsList[0])+int(elementsList[-1])
print(answer)
|
#Author: SanipRijal
#this program fetches the live data from the nepalstockmarket.com.np
from bs4 import BeautifulSoup as soup
import urllib.request
import urllib.parse as uparse
from pandas import DataFrame, read_csv
import pandas as pd
from datetime import datetime
import time
#define the columns for the pandas Dataframe
col = ['Date', 'Name', 'LTP', 'LTV', 'PointChange', 'Open', 'High', 'Low', 'Volume', 'PrevClosing']
#set the display option of the Dataframe
pd.set_option('display.max_rows', 20)
pd.set_option('display.max_columns', 10)
pd.set_option('display.width', 1000)
#get the html pageof the url
def getHtml():
#fetch the html from the url provided
class AppURLOpener(urllib.request.FancyURLopener):
version = "Mozilla/5.0"
opener = AppURLOpener()
url = "http://nepalstock.com.np/stocklive"
uClient = opener.open(url)
html = uClient.read()
uClient.close()
return html
#fetches the live data from each row
def getTableData(trow):
rows_list = []
#loop for each found row
for data in trow:
att = data.find_all('td')[1] #take the second data
title = att.get('title') #fetch the title of the element
att = data.find_all('td')[2] #the third data
ltp = att.text.strip() #ltp
att = data.find_all('td')[3] #the fourth data
ltv = att.text.strip() #ltv
att = data.find_all('td')[4] #the fifth data
pointChange = att.text.strip() #change in point
att = data.find_all('td')[6]
opened = att.text.strip()
att = data.find_all('td')[7]
high = att.text.strip()
att = data.find_all('td')[8]
low = att.text.strip()
att = data.find_all('td')[9]
volume = att.text.strip()
att = data.find_all('td')[10]
prevClosing = att.text.strip()
#set the date to current date and time
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#create a dataset for the dataframe
dataSet = [date,title, ltp, ltv, pointChange, opened, high, low, volume, prevClosing]
#update the list
rows_list.append(dataSet)
return rows_list
#get the data from the html page
def getData():
html = getHtml()
page_soup = soup(html, "html.parser")
try:
#find the element with id 'home-contents'
home_contents = page_soup.find(id = 'home-contents')
except AttributeError as e:
print("No element with id 'home-contents' found, exiting")
return 1
try:
#fetch the div with class name as mentioned
table = page_soup.find('div', attrs = {"class": "col-xs-12 col-md-9 col-sm-9"})
except AttributeError as e:
print("No div found with the provided attributes, exiting")
return 1
try:
#get the table body
tbody = table.find('tbody')
except AttributeError as e:
print('No table body found, exiting')
return 1
try:
#find all the rows in the table body
trow = tbody.findAll('tr')
except AttributeError as e:
print("No table row found, exiting")
return 1
#get the live data from the table
live_data = getTableData(trow)
return live_data
def main():
#set now as the current datetime
now = datetime.now()
#set end as the time '15:00:00' i.e. 3:00 pm
end = datetime.strptime('15:00:00', '%H:%M:%S')
#loop until true
while True:
data = getData()
#add the data to the dataframe
df = pd.DataFrame(data)
#open 'data.csv' file for appending
with open('data.csv', 'a') as f:
#add the dataframe to the file
df.to_csv(f, header = False, sep = '\t', encoding = 'utf-8')
#if current time exceeds end time then break the loop
if now.time() > end.time():
break
#sleep for 30 seconds
time.sleep(30)
if __name__ == "__main__":
main()
|
#alphabitical order
n=int(input())
l=list(map(str,input().split()))[:n]
dic={}
for i in range(n):
dic[l[i]]=list(map(int,input().split()))
for i in sorted(dic.keys()):
for j in range(len(dic[i])):
print(dic[i][j],end=' ')
print('') |
#!/usr/bin/python3
import cgi
import HTML
print("Content-type: text/html\n\n")
HTML.getHead("Process")
HTML.getHeader()
print("""
<div class="container-float">
<div class="row">
<div class="col-xs-12">
<div class="row">
<div class="col-xs-1 col-md-2">
<a name="content"></a>
</div>
<div id="Main" class="col-xs-10 col-md-8">
<br>
<h1>Process</h1>
<p>Solution development is more about the process than the coding. 80% of the process comes before you build anything. You need to start with a big box of questions and a good problem to sit down with.</p>
<div class="col-xs-1">
</div>
<div class="col-xs-10">
<br>
<div class="row">
<div class="col-xs-1">
</div>
<div class="col-xs-11">
<p><b>Step One:</b> Define the problem. Every problem needs to be well defined. It is important that you only define a problem. Dont start trying to solve it yet.</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-11">
<p><b>Step Two:</b> You need to take that well defined problem and break it down. You need to chunk it out into sub problems that can be solved all by themselves.</p>
</div>
<div class="col-xs-1">
</div>
</div>
<br>
<div class="row">
<div class="col-xs-1">
</div>
<div class="col-xs-11">
<p><b>Step Three:</b> Next, I think of tests. I break <u>one</u> sub problem down into testable chunks. There is no mistake in breaking problems down that show up twice.</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-11">
<p><b>Step Four: </b>Time to really flesh out one testable chunk. This is also the time you will need to choose what tools you want to use and what should be included when you release Version 1 of your project. (If you forget to set a release point now your solution will never be released due to scope creep. When you revisit this step keep the scope from growing.)</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-1">
</div>
<div class="col-xs-11">
<p><b>Step five:</b> Ask 3 questions. What does this code need to do? How does this code interface with the rest of the project and the user? What does this code need in order to do what it is designed to do?</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-11">
<p><b>Step Six:</b> : Use the answers to the previous questions to break up the task again. Focus on one piece at a time. Map out large connections or a sight map and document data and necessary functions.</p>
</div>
<div class="col-xs-1">
</div>
</div>
<br>
<div class="row">
<div class="col-xs-1">
</div>
<div class="col-xs-11">
<p><b>Step Seven:</b> Time to write some pseudo code. Make diagrams and plan your approach. Talk to people and make sure you have a clear path.</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-11">
<p><b>Step Eight: </b>Write the code testing as you go. Document before you code then remove documentation as necessary. Try not to put the cart before the horse. Redesigning can take longer than doing it right the first time.</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-1">
</div>
<div class="col-xs-11">
<p><b>Step Nine:</b> Repeat steps four through eight as needed. As you do this beware of scope creep, the number one killer of solutions. You can add versions with your great ideas after the first release.</p>
</div>
</div>
<br>
<div class="row">
<div class="col-xs-11">
<p><b>Step Ten: </b>: Finally, check to see if that solution works and move on to another sub problem or add features to the problem you have been working on.</p>
</div>
</div>
<a name="eg"></a>
<br>
<br>
</div>
<div class="row">
<h1>Example Coming Soon</h1>
</div>
</div>
</div>
</div>
</div>
</div>
""")
HTML.getFoot() |
stringVariable = "hello";
strinSingleQuote = 'Strings can have single quotes';
#print(stringVariable);
def myPrintMethod (myParameter):
print(myParameter)
print('World')
myPrintMethod('Puta')
def myMultiplyMethod(arg1, arg2):
return arg1 * arg2
print(myMultiplyMethod(5, 3))
grades = [5, 10, 25, 30, 35]
tupla = (5, 10, 25, 30, 35) # The tuple is inmutable
setOfgrades = {5, 10, 25, 30, 35, 35} #unique and unordered
set1 = {1,2,3,4,5}
set2 = {1,3,5,7,9,11}
print(set1.intersection(set2))
print(set1.union(set2))
print(set1.difference(set2)) |
def printMove(fr, to):
print("move from " + str(fr) + " to " + str(to))
def towersn(n, fr, to, spare):
if n == 1:
return printMove(fr, to)
else:
towersn(n-1, fr, spare, to)
towersn(1, fr, to, spare)
towersn(n-1, spare, to, fr)
print(str(towersn(3, 2, 1, 3))) |
def oweAmount(b0, r, m):
return (b0-(b0*m))*(1+(r/12))
total = 0
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
for month in range(12):
print("Month: " + str(month+1))
z = oweAmount(balance, annualInterestRate, monthlyPaymentRate)
print("Minimum monthly payment: " + str(round(balance*monthlyPaymentRate,2)))
print("Remaining balance: " + str(round(z,2)))
total += balance*monthlyPaymentRate
balance = z
print("Total paid: " + str(round(total,2)))
print("Remaining balance: " + str(round(balance,2)))
|
import math
def lcm(a, b):
return abs(a*b) // math.gcd(a, b)
for _ in range(int(input())):
s1 = input()
s2 = input()
l = lcm(len(s1), len(s2))
if s1 * (l // len(s1)) == s2 * (l // len(s2)):
print(s1 * (l // len(s1)))
else:
print(-1) |
import math
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
for _ in range(int(input())):
n = int(input())
while math.gcd(n, sum_digits(n)) <= 1:
n += 1
print(n)
|
print 'enter grade'
grade = raw_input()
str(grade)
marks = {}
marks['4+'] = '97'
marks['4'] = '90'
marks['4-'] = '83'
marks['3+'] = '76'
marks['3'] = '74'
marks['3-'] = '71'
marks['2+'] = '68'
marks['2'] = '64'
marks['2-'] = '61'
marks['1+'] = '58'
marks['1'] = '54'
marks['r'] = '30'
marks['1-'] = '51'
marks['ne'] = '0'
marks['4++'] = '100'
if grade == '4+' or grade == '4' or grade == '4-' or grade == '3+' or grade == '3' or grade == '3-' or grade == '2+' or grade == '2' or grade == '2-' or grade == '1+' or grade == '1' or grade == '1-' or grade == 'r' or grade == 'ne' or grade == '4++':
print 'your mark is: ' + marks[grade] + '%'
else:
print("You have to input level grades only!")
|
def is_prime(n):
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
numbers = []
num = 1
while (len(numbers) < 10001):
s = str(num)
if(is_prime(num) == True):
numbers.append(num)
num += 1
else:
num +=1
print(numbers[-1])
|
def isEven(n):
if(n % 2 == 0):
return True
else:
return False
def CollatzSeq(n):
CollatzSeq = []
CollatzSeq.append(n)
Flag = False
while (n != 1):
if(isEven(n)):
n = n // 2
CollatzSeq.append(n)
else:
n = (3 * n) + 1
CollatzSeq.append(n)
return CollatzSeq
LongestCollatz = 1
LongestCollatzList = []
number = 1
for i in range (1, 1000000):
if(len(CollatzSeq(i)) > LongestCollatz):
number = i
LongestCollatz = len(CollatzSeq(i))
LongestCollatzList = CollatzSeq(i)
print(number)
|
# https://www.interviewbit.com/problems/matrix-median/
# Matrix Median
# Given a matrix of integers A of size N x M in which each row is sorted.
# Find an return the overall median of the matrix A.
# class Solution:
# # @param A : list of list of integers
# # @return an integer
# def findMedian(self, A):
# if len(A)==0:
# return []
# arr = []
# for row in A:
# arr.extend(row)
# arr = sorted(arr)
# median_index = (len(arr)+1)//2
# return arr[median_index-1]
class Solution:
# @param A : list of list of integers
# @return an integer
def findMedian(self, A):
def arr_median(arr):
arr = sorted(arr)
median_index = (len(arr)+1)//2
return arr[median_index-1]
if len(A)==0:
return []
arr = []
for row in A:
arr.extend(row)
return arr_median(arr) |
# https://www.interviewbit.com/problems/repeat-and-missing-number-array/
# Repeat and Missing Number Array
# Input:[3 1 2 5 3] Output:[3, 4] A = 3, B = 4
class Solution:
# @param A : tuple of integers
# @return a list of integers
def repeatedNumber(self, arr):
repeated =0
missing =0
aux = [-1]*len(arr)
for item in arr:
if aux[item-1]==1:
repeated = item
break
else:
aux[item-1]=1
n = len(arr)
missing = int((n*(n+1)/2)-sum(arr)+repeated) # Using summation property to find the missing (Nice)
return [repeated,missing] |
# https://www.interviewbit.com/problems/all-factors/
# All Factors
import math
def printDivisors(self,n) :
l = []
i = 1
while i <= math.sqrt(n):
if (n % i == 0) :
if (n / i == i) :
l.append(i)
else :
l.append(i)
l.append(int(n/i))
i = i + 1
l.sort()
return l |
# https://www.interviewbit.com/problems/max-sum-contiguous-subarray/
# Max Sum Contiguous Subarray
class Solution:
# @param A : list of integers
# @return a list of integers
def maxset(A):
i = 0;
maxi = -1;
index = 0;
a = []
while i < len(A):
while i < len(A) and A[i] < 0:
i+=1
l = []
index = i
while i < len(A) and A[i] >= 0:
l.append(A[i])
i+=1
if (sum(l) > maxi):
a = l
maxi = sum(l)
return a |
# https://www.interviewbit.com/problems/set-matrix-zeros/
# Set Matrix Zeros
# Input 1:
# [ [1, 0, 1],
# [1, 1, 1],
# [1, 1, 1] ]
# Output 1:
# [ [0, 0, 0],
# [1, 0, 1],
# [1, 0, 1] ]
# Input 2:
# [ [1, 0, 1],
# [1, 1, 1],
# [1, 0, 1] ]
# Output 2:
# [ [0, 0, 0],
# [1, 0, 1],
# [0, 0, 0] ]
class Solution:
# @param A : list of list of integers
# @return the same list modified
def setZeroes(A):
m = len(A[0])
n = len(A)
list_row = []
list_col = []
for i in range(n):
for j in range(m):
if A[i][j] == 0:
if i not in list_row:
list_row.append(i)
if j not in list_col:
list_col.append(j)
#print list_row, list_col
row = [0]*m
for i in range(n):
if i in list_row:
A[i] = row
for j in range(m):
if j in list_col:
A[i][j] = 0
return A |
# https://www.interviewbit.com/problems/prime-numbers/
# Prime Numbers
class Solution:
# @param A : integer
# @return a list of integers
def sieve(self,A):
prime = [1] * A
prime[0] = 0
prime[1] = 0
for i in range(2,A):
if prime[i] == 1:
j = 2
while(i*j<A):
if i*j<A:
prime[i*j] = 0 # Multiples of i are set to zeros
j += 1
a = []
for i in range(len(prime)):
if prime[i] == 1:
a.append(i)
return a
|
# https://www.interviewbitcom/problems/grid-unique-paths/
# Grid Unique Path
# Input : A = 2, B = 2
# Output : 2
# 2 possible routes : (0, 0) -> (0, 1) -> (1, 1)
# OR : (0, 0) -> (1, 0) -> (1, 1)
class Solution:
# @param A : integer
# @param B : integer
# @return an integer
def uniquePaths(self,rows, cols):
if rows==1 or cols == 1:
return 1
a = [[1] + [0]*(cols-1)]*rows
a[0] = [1]*cols
for i in range(1,rows):
for j in range(1,cols):
a[i][j] = a[i-1][j] + a[i][j-1]
return a[rows-1][cols-1]
|
import re
def hey(text):
word = re.sub('[^a-zA-Z0-9?]+', '', text)
if not word:
return 'Fine. Be that way!'
elif word.isupper():
return 'Whoa, chill out!'
elif word.endswith('?'):
return 'Sure.'
else:
return 'Whatever.'
|
import datetime
from calendar import monthrange, day_name
def meetup_day(year, month, name, desc):
day = next(number for number, day_n in enumerate(day_name, start=1)
if day_n == name)
description = {
'teenth': 13,
'1st': 1,
'2nd': 8,
'3rd': 15,
'4th': 22,
'5th': 29,
'last': monthrange(year, month)[1] - 6
}
start_day = description[desc]
while datetime.date(year, month, start_day).isoweekday() != day:
start_day += 1
return datetime.date(year, month, start_day)
|
# import the pygame module, so you can use it
import pygame
# define a main function
def main():
# initialize the pygame module
pygame.init()
# load and set the logo
logo = pygame.image.load("Logo.PNG")
pygame.display.set_icon(logo)
pygame.display.set_caption("Scott Chang looks for his son")
# create a surface on screen that has the size of 240 x 180
screenWidth = 1800
screenHeight = 800
screen = pygame.display.set_mode((screenWidth, screenHeight))
background = pygame.image.load("background.png")
screen.blit(background, (0, 0))
# define the position of the smily
ScottX = 250
ScottY = 250
# how many pixels we move our smily each frame
stepX = 50
stepY = 50
# check if the smily is still on screen, if not change direction
Scott = pygame.image.load("SC.PNG")
screen.blit(Scott, (ScottX, ScottY))
pygame.display.flip()
clock = pygame.time.Clock()
# define a variable to control the main loop
running = True
# main loop
while running:
# event handling, gets all event from the eventqueue
for event in pygame.event.get():
# only do something if the event if of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
# check for keypress and check if it was Esc
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
# check if the smily is still on screen, if not change direction
if ScottX > screenWidth - 50 or ScottX < 0:
stepX = -stepX
if ScottY > screenHeight - 50 or ScottY < 0:
stepY = -stepY
# update the position of the smily
ScottX += stepX # move it to the right
ScottY += stepY # move it down
# now blit the smily on screen
screen.blit(background, (0,0))
Jager = pygame.image.load("Jager.PNG")
screen.blit(Jager, (100, 400))
screen.blit(Scott, (ScottX, ScottY))
# and update the screen (dont forget that!)
pygame.display.flip()
# this will slow it down to 10 fps, so you can watch it,
# otherwise it would run too fast
clock.tick(10)
# run the main function only if this module is executed as the main script
# (if you import this as a module then nothing is executed)
if __name__ == "__main__":
# call the main function
main()
|
#Solving simulataneous equations with 3 unknowns
def three_x_three():
print("Type in first equation in format below")
a1 = int(input("X coefficient:"))
b1 = int(input("Y Coefficient:"))
c1 = int(input("Z Coefficient:"))
ans1 = int(input("Answer:"))
print("Now the second equation")
a2 = int(input("X coefficient:"))
b2 = int(input("Y Coefficient:"))
c2 = int(input("Z Coefficient:"))
ans2 = int(input("Answer:"))
print("Now for the third equation")
a3 = int(input("X Coefficient:"))
b3 = int(input("Y Coefficient:"))
c3 = int(input("Z Coefficient:"))
ans3 = int(input("Answer:"))
det1 = (b2 * c3) - (b3 * c2)
det2 = (a2 * c3) - (a3 * c2)
det3 = (a2 * b3) - (a3 * b2)
det = (a1 * det1) - (b1 * det2) + (c1 * det3)
cofactorA1 = (b2 * c3) - (b3 * c2)
cofactorA2 = -((b1 * c3) - (b3 * c1))
cofactorA3 = (b1 * c2) - (b2 * c1)
cofactorB1 = -((a2 * c3) - (a3 * c2))
cofactorB2 = (a1 * c3) - (a3 * c1)
cofactorB3 = -((a1 * c2) - (a2 * c1))
cofactorC1 = (a2 * b3) - (a3 * b2)
cofactorC2 = -((a1 * b3) - (a3 * b1))
cofactorC3 = (a1 * b2) - (a2 * b1)
x = 1/det * (cofactorA1 * ans1 + cofactorA2 * ans2 + cofactorA3 * ans3)
y = 1/det * (cofactorB1 * ans1 + cofactorB2 * ans2 + cofactorB3 * ans3)
z = 1/det * (cofactorC1 * ans1 + cofactorC2 * ans2 + cofactorC3 * ans3)
print("x =", x, "y =", y, "z =", z)
three_x_three()
|
# coding=utf-8
# 日期:2020-03-12
# 作者:YangZai
# 功能:测试employee.py代码
import unittest
from employee import Employee
# Employee类测试
class TestEmployee():
"""针对Employee类测试"""
def setUp(self):
self.employee_1 = Employee('Guang', 'Chen', 6000)
self.salary = 6000
def test_give_default_raise(self):
self.employee_1.give_raise()
self.assertEqual(self.salary + 5000, self.employee_1.annual_salary)
def test_give_custom_raise(self):
self.employee_1.give_raise(3000)
self.assertEqual(self.salary + 3000, self.employee_1.annual_salary)
unittest.main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.