text stringlengths 37 1.41M |
|---|
def last_room(route):
result = 1 + 6 * (route - 1) * route / 2
return int(result)
n = int(input())
route = 1
while last_room(route) < n:
route += 1
print(route)
|
# 미해결 (시간초과)
class Queue():
def __init__(self):
self.position = []
self.time = []
def put(self, pos, t):
self.position.append(pos)
self.time.append(t)
def get(self):
return (self.position.pop(0), self.time.pop(0))
def is_empty(self):
if len(self.position) > 0:
return False
else:
return True
def find_way(f,s,g,u,d):
pos = s
button = 0
if pos == g:
return button
elif u > f or d > f:
return 'use the stairs'
visit_hash = {}
pos_queue = Queue()
pos_queue.put(pos,button)
visit_hash[pos] = button
while pos != g:
if pos_queue.is_empty() is True:
break
pos, button = pos_queue.get()
if button > abs(g - s):
break
if (pos + u) <= f and (pos + u) not in visit_hash:
pos_queue.put(pos + u, button + 1)
visit_hash[pos + u] = button + 1
if (pos - d) >= 0 and (pos - d) not in visit_hash:
pos_queue.put(pos - d, button + 1)
visit_hash[pos - d] = button + 1
if g in visit_hash:
return visit_hash[g]
else:
return 'use the stairs'
line_input = input()
line_input = line_input.split(' ')
line_input = [int(ch) for ch in line_input]
f = line_input[0]
s = line_input[1]
g = line_input[2]
u = line_input[3]
d = line_input[4]
print(find_way(f,s,g,u,d))
#f, s, g, u, d
# test_input = [
# [10, 1, 10, 2, 1],
# [100, 2, 1, 1, 0],
# [10, 1, 10, 1, 0]
# ]
#
# for line_input in test_input:
# f = line_input[0]
# s = line_input[1]
# g = line_input[2]
# u = line_input[3]
# d = line_input[4]
#
# print(find_way(f,s,g,u,d))
|
# stack implementation practice
class Stack(object):
def __init__(self):
self.size = 0
self.data = []
def push(self, value):
self.data.append(value)
self.size += 1
def pop(self):
if self.is_empty():
print("the stack is empty")
else:
self.size -= 1
if self.size <= 0:
print("no data any more after this value")
return self.data.pop()
def check_size(self):
return self.size
def is_empty(self):
if self.size <= 0:
return True
else:
return False
def peek(self):
if self.is_empty():
print('the stack is empty')
return None
else:
return self.data[self.size-1]
def print_stack(self):
if self.is_empty():
print('the stack is empty')
else:
print(self.data)
# implementation test
# uncomment each line to test
#
# test_stack = Stack()
#
# print("the stack is empty now? : ", test_stack.is_empty())
# print("check size : ", test_stack.check_size())
#
# print("push 7 now")
# test_stack.push(7)
# print ("")
#
# print("the stack is empty now? : ", test_stack.is_empty())
# print("peek value : ", test_stack.peek())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
#
# print("push 8,4,12,-7,0,55")
# for i in [8, 4, 12, -7, 0, 55]:
# test_stack.push(i)
# print("check peek value : ", test_stack.peek())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
#
# print("pop : ", test_stack.pop())
# print("check peek value : ", test_stack.peek())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
#
# print("pop : ", test_stack.pop())
# print("pop : ", test_stack.pop())
# print("pop : ", test_stack.pop())
# print("check peek value : ", test_stack.peek())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
#
# print("pop : ", test_stack.pop())
# print("pop : ", test_stack.pop())
# print("pop : ", test_stack.pop())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
#
# print("pop : ", test_stack.pop())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
#
# print("push 27,1,-8")
# for i in [27, 1, -8]:
# test_stack.push(i)
# print("check peek value : ", test_stack.peek())
# print("check size : ", test_stack.check_size())
# test_stack.print_stack()
# print ("")
|
def space_to_20(str):
output_arr = []
for start in range(len(str)):
if str[start] != ' ':
break
for end in range(len(str)-1, -1, -1):
if str[end] != ' ':
break
for i in range(start,end+1):
ch = str[i]
if ch == ' ':
ch = '%20'
output_arr.append(ch)
result = ''.join(output_arr)
return result
str = ' AT YZZ ' # to 'AT%20YZZ', outer space is removed
print(space_to_20(str)) |
for _ in range (10):
n = int(input())
if n == -1:
break
result = 0
c = 0
for _ in range(n):
a, b = input().split()
a = int(a)
b = int(b)
result += (a * (b-c))
c = b
print(result, "miles") |
# Analysis
#
# If the network is initialized to zero weights, the activations of the hidden
# layers are always set to zero, whatever the value of the inputs. The gradient
# is always zero for all training samples and no learning can happen with any
# gradient-based optimizer (SGD, Adam...): the loss stays constant.
#
# A network with null weights has null gradients but this not a local minimum
# (nor a local maximum): it is a saddle point at the center of a neighborhood
# with very low gradients.
#
# This phenomenom only exists because of the presence of one or more hidden
# layers: a logistic regression model (just a single Dense layer with softmax
# activations) can bit fit with SGD from 0 initialized weights without any
# problem.
#
# For neural nets when the scale of a random initializations of the weights is
# too small, SGD has a hard time evading that area of low gradients. Adding
# momentum can help but especially for deep networks it can take many epochs to
# evade the area.
#
# Initializing the weights with large random values will make the output
# distribution (softmax) very peaky: the network is very "confident" of its
# predictions even if they are completely random. This leads to a very high
# initial loss value.
#
# The softmax function does not saturate (bad classification always have a
# non-zero gradient). However the intermediate tanh layers can saturate,
# therefore squashing the gradient of the loss with respect to the parameters
# of the first "Dense" layer and making the network train much slower.
#
# The Glorot uniform init uses a scale that depends on the dimensions of the
# weight matrix so has to preserve the average norm of activations and flowing
# gradients so as to make learning possible. Keras provides alternatives that
# can be better in some cases. Please refer to the references in the Keras
# documentation to learn more on the theoretical justifications behind those
# schemes.
#
# Adam tends to be more robust when it comes to bad initialization thanks to
# its per-weight learning rate adjustments but still benefits from a good
# initialization.
#
# More on this in a later class on optimization issues. For now just remember
# that if you network fails to learn at all (the loss stays at its initial
# value):
#
# - ensure that the weights are properly initialized,
# - inspect the per-layer gradient norms to help identify the bad layer,
# - use Adam instead of SGD as your default go to initializer.
#
# https://stackoverflow.com/questions/50033312/how-to-monitor-gradient-vanish-and-explosion-in-keras-with-tensorboard
|
# -*- coding: utf-8 -*-
"""
时间:2019-05-06
作者:哥哥
题号:0067
题目:
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
"""
class Solution(object):
"""
:type a: str
:type b: str
:rtype: str
"""
# 方法1 使用python特性
def addBinary1(self, a, b):
return bin(int(a,2)+int(b,2))[2:]
def addBinary2(self, a, b):
# 结果字符串
result = ''
# 进位
cin = 0
# 分别从a和b的尾开始循环
indexA = len(a)-1
indexB = len(b)-1
# 循环到a和b都结束才退出循环
while indexA>=0 or indexB>=0:
# 当前位a的值,若a已经结束b未结束,补0
if indexA >= 0:
bitA = int(a[indexA])
else:
bitA = 0
# 当前位b的值,若b已经结束a未结束,补0
if indexB >= 0:
bitB = int(b[indexB])
else:
bitB = 0
# 当前位相加和
s = bitA + bitB + cin
# 进位
cin = s // 2
# 当前为结果值
s %= 2
# 当前位结果值存入
result = str(s) + result
# 循环递减
indexA -= 1
indexB -= 1
# 若仍有进位,再补一个1
if cin:
result = '1' + result
# 返回结果
return result
# 测试用例
testA = '11'
testB = '11'
# 测试结果
slu = Solution()
print(testA,'+',testB,'的运行结果为',slu.addBinary1(testA, testB))
print(testA,'+',testB,'的运行结果为',slu.addBinary2(testA, testB))
|
# -*- coding: utf-8 -*-
"""
Created on Thu May 9 10:22:26 2019
@author: liusi
"""
class Solution(object):
def searchInsert(self, nums, target):
if target in nums:
return nums.index(target)
else:
for i in range(len(nums)):
if nums[i] > target: #target is not biggest
return i
return len(nums)
|
# -*- coding: utf-8 -*-
"""
时间:2019-04-28
作者:哥哥
题号:0021
题目:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# 方法1 双循环处理
def mergeTwoLists1(self, l1, l2):
# 特殊处理,其中一个链表为空,直接返回另一个链表
if l1 == None:
return l2
if l2 == None:
return l1
# 根节点
root = ListNode(None)
node = root
# 循环添加节点
while l1 and l2:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
else:
node.next = l2
l2 = l2.next
node = node.next
# 剩余处理
if l1:
node.next = l1
if l2:
node.next = l2
# 返回
return root.next
#方法2 递归处理
def mergeTwoLists2(self, l1, l2):
if l1 == None:
return l2
if l2 == None:
return l1
if l1.val <= l2.val:
l1.next = self.mergeTwoLists2(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists2(l1, l2.next)
return l2
|
# -*- coding: utf-8 -*-
'简化路径'
# Given an absolute path for a file (Unix-style), simplify it.
# For example,
# path = "/home/", => "/home"
# path = "/a/./b/../../c/", => "/c"
def simplify_path(path):
path_lst = [item for item in path.split('/') if item not in ('.', '')]
stack = []
for item in path_lst:
if stack and item == '..':
stack.pop()
else:
stack.append(item)
return '/' + '/'.join(stack)
path = "/a/./b/../..///c/"
print simplify_path(path)
|
# -*- coding: utf-8 -*-
'蛇形打印二叉树结构'
class Node(object):
'二叉树节点定义'
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def get_tree_list(root):
stack = []
stack.append(root)
results = []
while stack:
node = stack.pop(0)
results.append(node.data)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return results
for i in xrange(1, 9):
locals()['node{}'.format(i)] = Node(i)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node8
tree_list = get_tree_list(node1)
tree_list = [str(i) for i in tree_list]
print tree_list
s = ''
for i in xrange(3):
count = 2**i
if i % 2 == 0:
s += ' '.join(tree_list[:count]) + '\n'
else:
s += ' '.join(tree_list[:count][::-1]) + '\n'
tree_list = tree_list[count:]
print s
|
# my first python program
# print prints a blank line
print
# remove the # to print the line
# this prints Hello World!
#print "Hello World!"
# this prints Hello again
#print "Hello again"
# this prints I like typing this
#print "I like typing this."
# this prints This is fun.
#print "This is fun."
# this prints Yay! Printing.
print 'Yay! Printing.'
# This prints I'd rather you 'not'.
#print "I'd rather you 'not'."
#print 'I "said" do not touch this.'
#print "another line."
print |
"""Each ListNode holds a reference to its previous node
as well as its next node in the List."""
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
"""Wrap the given value in a ListNode and insert it
after this node. Note that this node could already
have a next node it is point to."""
def insert_after(self, value):
current_next = self.next
self.next = ListNode(value, self, current_next)
if current_next:
current_next.prev = self.next
"""Wrap the given value in a ListNode and insert it
before this node. Note that this node could already
have a previous node it is point to."""
def insert_before(self, value):
current_prev = self.prev
self.prev = ListNode(value, current_prev, self)
if current_prev:
current_prev.next = self.prev
"""Rearranges this ListNode's previous and next pointers
accordingly, effectively deleting this ListNode."""
def delete(self):
if self.prev:
self.prev.next = self.next
if self.next:
self.next.prev = self.prev
"""Our doubly-linked list class. It holds references to
the list's head and tail nodes."""
class DoublyLinkedList:
def __init__(self, node=None):
self.head = node # Each node is a ListNode and inherits the methods from that class.
self.tail = node
self.length = 1 if node is not None else 0
def __len__(self):
return self.length
def add_to_head(self, value):
# need to handle two types of activity. Adding when I have a head and when head is currently none.
if not self.head: # Adding to head when there is no head yet.
self.head = ListNode(value) # Create the head node.
self.tail = self.head # Also set the head node as the tail address.
else: # Add to head (normal)
self.head.insert_before(value) # Select the head then insert value before.
self.head = self.head.prev # Change the head address to the inserted value.
self.length +=1
def remove_from_head(self):
# Need to handle size Zero, size 1, and size N lists...
removed = None # Defining a variable that will hold the ListNode.value we'll remove.
if self.length > 0: # Checks that list is greater than 0
removed = self.head.value # Grabs the value we're pulling out.
if self.length == 1: # If a size 1 DLL....
self.head = None # Set the head to None.
self.tail = None # Set the tail to None, we just removed the last item.
else:
self.head.delete()
self.length -= 1 # Subtract one for the deleted object.
return removed # If there is no list and we run then return none...
def add_to_tail(self, value):
# Need to handle size zero and size N
if not self.tail: #Size Zero
self.tail = ListNode(value)
self.head = self.tail
else:
self.tail.insert_after(value)
self.tail = self.tail.next # Move the tail reference to the new tail address.
self.length +=1
def remove_from_tail(self):
removed = None
if self.length > 0:
removed = self.tail.value
if self.length == 1:
self.tail = None
self.head = None
else:
self.tail.delete
self.length -= 1
return removed
def move_to_front(self, node):
# First need to make sure I'm not moving the head
if self.head != node:
node.delete() # "Delete" the node, still have the object in this function for reference.
self.head.insert_before(node.value) # Take the node value and insert it before the head.
self.head = self.head.prev # Same as add to head.
def move_to_end(self, node):
# First need to make sure I'm not moving the tail
if self.tail != node:
node.delete()
self.tail.insert_after(node.value)
self.tail = self.tail.next
def delete(self, node):
# Need 3 conditions, when deleting head, tail or other.
if self.head == node: # Head Case
self.head = self.head.next
elif self.tail == node: # Tail Case
self.tail = self.tail.prev
else: # Other case
node.delete()
self.length -= 1 # In all cases
def get_max(self):
cursor = self.head # Cursor starts at the head.
max_value = cursor.value
while cursor != self.tail:
cursor = cursor.next
if max_value < cursor.value: # Check if the new cursor location value is bigger.
max_value == cursor.value
return max_value
|
No= int(input("Enter a number: "))
def DivNumber(No):
if(No % 5==0):
print("True")
else:
print("False")
if __name__ == '__main__':
DivNumber(No) |
import itertools
num_nodes = 0 # record number of nodes the algorithm traverse
visited = {} # store the baord the algorithm has already traversed
max_depth = 100 # maximum search depth
def iddfs_queue(root_node):
print("="*10+"IDDFS (QUEUE)"+"="*10)
global num_nodes
num_nodes = 0
for depth in itertools.count():
if(depth >= max_depth):
print("Out of Search Space")
return
queue = [root_node]
visited = {}
# check all elements if the queue is not empty
while len(queue) > 0:
node = queue.pop() # get element from tail
visited[node.tilehash()] = node.moves
num_nodes+=1
# whether the algorithm find the goal board or not
if node.is_goal():
print("RESULT:")
print(node.tiles)
print("Total Moves:")
print(node.moves)
print("Total Nodes IDDFS (QUEUE) Traverse:")
print(num_nodes)
if(node.parent): # show the results step by step
print(node.parent)
return
# collect all next possible boards
if node.moves < depth:
new_node_list = []
for child in node.possible_moves():
if child.tilehash() not in visited or visited[child.tilehash()] > child.moves:
new_node_list.append(child)
queue.extend(new_node_list)
return
def dfs(node,depth):
global visited
global num_nodes
visited[node.tilehash()] = node.moves
num_nodes += 1
# whether the algorithm find the goal board or not
if(node.is_goal()):
print("RESULT:")
print(node.tiles)
print("Total Moves:")
print(node.moves)
print("Total Nodes IDDFS (RECURSION) Traverse:")
print(num_nodes)
if(node.parent): # show the results step by step
print(node.parent)
return node
# collect all next possible boards
if node.moves < depth:
for child in node.possible_moves():
if child.tilehash() not in visited or visited[child.tilehash()] > child.moves:
ret = dfs(child,depth) # recursive call with next node as current node for depth search
if ret:
if ret.is_goal():
return ret
return None
def iddfs_recursion(root_node):
print("="*10+"IDDFS (RECURSION)"+"="*10)
global num_nodes
global visited
num_nodes = 0
for depth in itertools.count():
if(depth >= max_depth):
print("Out of Search Space")
break
visited = {}
if dfs(root_node,depth):
break
return |
import unittest
from src.card import Card
from src.card_game import CardGame
class TestCardGame(unittest.TestCase):
def setUp(self):
self.ace = Card('Hearts', 1)
self.two = Card('Diamonds', 2)
self.card_game = CardGame()
self.cards = [self.ace, self.two]
def test_check_for_is_ace(self):
self.assertEqual(True, self.card_game.check_for_ace(self.ace))
def test_check_for_is_not_ace(self):
self.assertEqual(False, self.card_game.check_for_ace(self.two))
def test_for_highest_card(self):
self.assertEqual(self.two, self.card_game.highest_card(self.ace, self.two))
def test_for_total(self):
self.assertEqual("You have a total of 3", self.card_game.cards_total(self.cards))
|
aa=input()
aa=aa.split()
a=int(aa[0])
b=int(aa[1])
c=int(aa[2])
if a>b:
if a>c:
print (a)
elif b>c:
print (b)
else:
print (c)
|
# Medium
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
# perfect binary tree :
# 1. all leaves are on same level
# 2. every parent has two children
# Runtime: 129 ms, faster than 16.13% (T^T) of Python3 online submissions for Populating Next Right Pointers in Each Node.
# Memory Usage: 15.5 MB, less than 96.98% of Python3 online submissions for Populating Next Right Pointers in Each Node.
class Solution:
def connect(self, root: "Optional[Node]") -> "Optional[Node]":
if not root:
return root
leftmost = root
while leftmost.left:
head = leftmost
while head:
head.left.next = head.right
if head.next:
head.right.next = head.next.left
head = head.next
leftmost = leftmost.left
return root
# # perfect binary tree is always 2^n + 1
# # where n is level
# self.track(root, None, 1, True)
# return root
#
# def track(self, node: 'Optional[Node]', parent: 'Optional[Node]', level: int, amIRightChild: bool):
# if not node:
# return
#
# if not amIRightChild: # leftnode
# node.next = parent.right
# elif parent and not parent.right:
# node.next = None
# elif parent:
# node.next = parent.next.left if parent.next else None
# if node.left:
# self.track(node.left, node, level+1, False)
# if node.right:
# self.track(node.right, node, level+1, True)
## ---------
## LEVEL ORDER TRAVERSAL
## Solution
## while (!Q.empty())
## {
## size = Q.size()
## for i in range 0..size
## {
## node = Q.pop()
## Q.push(node.left)
## Q.push(node.right)
## }
## }
##
##
##
# 1. Makes Queue. (Tuple, NULL, nested loop)
# 2. adding root of the tree in the queue (1) -> (2,3)/ 1 was poped
# 3. first while loop iterates over each level one by one and and the inner loop over all the nodes
# 4. (2,3) -> (3, 4, 5). also, the element at the head of the queue is the `next element` in order.
# 5. (3, 4, 5) -> (4, 5, 6, 7)
###
"""
import collections
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return root
# Initialize a queue data structure which contains
# just the root of the tree
Q = collections.deque([root])
# Outer while loop which iterates over
# each level
while Q:
# Note the size of the queue
size = len(Q)
# Iterate over all the nodes on the current level
for i in range(size):
# Pop a node from the front of the queue
node = Q.popleft()
# This check is important. We don't want to
# establish any wrong connections. The queue will
# contain nodes from 2 levels at most at any
# point in time. This check ensures we only
# don't establish next pointers beyond the end
# of a level
if i < size - 1:
node.next = Q[0]
# Add the children, if any, to the back of
# the queue
if node.left:
Q.append(node.left)
if node.right:
Q.append(node.right)
# Since the tree has now been modified, return the root node
return root
"""
|
class Solution:
# returns subtrees last node
previous = None
inorder_successor_node = None
def iter(self, node: TreeNode, p: TreeNode):
if not node:
return
self.iter(node.left, p)
if self.previous == p and not self.inorder_successor_node:
self.inorder_successor_node = node
return
self.previous = node
self.iter(node.right, p)
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]:
# in order: left -> node -> right
self.iter(root, p)
return self.inorder_successor_node
|
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
now = head
length = 0
while now:
length += 1
now = now.next
now = head
# addition = 0 if length % 2 else 1 # len is odd: 0, even: 1
addition = 0
for i in range(length // 2 + addition):
now = now.next
return now
|
from queue import Queue
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
# rooms: key that is placed in room
# enter from room 0, can you open all the rooms?
s = [False] * len(rooms)
q = Queue()
q.put(0)
while q.qsize() > 0:
e = q.get()
s[e] = True
for r in rooms[e]:
if not s[r]:
q.put(r)
return all(s)
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
def iter(fst, snd):
if not fst and not snd:
return True
elif not fst or not snd:
return False
elif fst.val != snd.val:
return False
return iter(fst.left, snd.left) and iter(fst.right, snd.right)
if not root:
return False
elif iter(root, subRoot):
return True
else:
return self.isSubtree(root.left, subRoot) or self.isSubtree(
root.right, subRoot
)
|
#!/usr/bin/env python
# coding: utf-8
# In[15]:
"""NUI Galway CT5132/CT5148 Programming and Tools for AI (James McDermott)
Skeleton/solution for Assignment 1: Numerical Integration
By writing my name below and submitting this file, I/we declare that
all additions to the provided skeleton file are my/our own work, and that
I/we have not seen any work on this assignment by another student/group.
Student name(s): Yashitha Agarwal, Morgan Reilly, Akanksha
Student ID(s): 20230091, 20235398, 20231242
"""
import numpy as np
import sympy
import itertools
import math
def numint_py(f, a, b, n):
"""Numerical integration. For a function f, calculate the definite
integral of f from a to b by approximating with n "slices" and the
"lb" scheme. This function must use pure Python, no Numpy.
>>> round(numint_py(math.sin, 0, 1, 100), 5)
0.45549
>>> round(numint_py(lambda x: 1, 0, 1, 100), 5)
1.0
>>> round(numint_py(math.exp, 1, 2, 100), 5)
4.64746
"""
A = 0
w = (b - a) / n # width of one slice
import decimal
def Finput(a, b, w): # function to get list of input points to be passed to the function
while a < b:
yield float(a)
a += decimal.Decimal(w)
x = list(Finput(a, b, str(w))) # create input list
for i in x:
A += f(i) * w # # using lb scheme: calculate f(x) * dx for each value in input list and increment A
return A
def numint(f, a, b, n, scheme='mp'):
"""Numerical integration. For a function f, calculate the definite
integral of f from a to b by approximating with n "slices" and the
given scheme. This function should use Numpy, and eg np.linspace()
will be useful.
>>> round(numint(np.sin, 0, 1, 100, 'lb'), 5)
0.45549
>>> round(numint(lambda x: np.ones_like(x), 0, 1, 100), 5)
1.0
>>> round(numint(np.exp, 1, 2, 100, 'lb'), 5)
4.64746
>>> round(numint(np.exp, 1, 2, 100, 'mp'), 5)
4.67075
>>> round(numint(np.exp, 1, 2, 100, 'ub'), 5)
4.69417
"""
# STUDENTS ADD CODE FROM HERE TO END OF FUNCTION
A = 0
w = (b - a) / n # width of one slice
x = np.arange(a,b,w) # create list of input points to be passed to the function
for i in x:
if scheme == 'mp':
A += f((i + (i + w)) / 2) * w # using mp scheme: calculate f((x + (x+1) / 2)) * dx for each value in input list and increment A
elif scheme == 'lb':
A += f(i) * w # using lb scheme: calculate f(x) * dx for each value in input list and increment A
elif scheme == 'ub':
A += f(i + w) * w # using ub scheme: calculate f(x) * dx for each value in input list and increment A
return A
def true_integral(fstr, a, b):
"""Using Sympy, calculate the definite integral of f from a to b and
return as a float. Here fstr is an expression in x, as a str. It
should use eg "np.sin" for the sin function.
This function is quite tricky, so you are not expected to
understand it or change it! However, you should understand how to
use it. See the doctest examples.
>>> true_integral("np.sin(x)", 0, 2 * np.pi)
0.0
>>> true_integral("x**2", 0, 1)
0.3333333333333333
STUDENTS SHOULD NOT ALTER THIS FUNCTION.
"""
x = sympy.symbols("x")
# make fsym, a Sympy expression in x, now using eg "sympy.sin"
fsym = eval(fstr.replace("np", "sympy"))
A = sympy.integrate(fsym, (x, a, b)) # definite integral
A = float(A.evalf()) # convert to float
return A
def numint_err(fstr, a, b, n, scheme):
"""For a given function fstr and bounds a, b, evaluate the error
achieved by numerical integration on n points with the given
scheme. Return the true value, absolute error, and relative error
as a tuple.
Notice that the relative error will be infinity when the true
value is zero. None of the examples in our assignment will have a
true value of zero.
>>> print("%.4f %.4f %.4f" % numint_err("x**2", 0, 1, 10, 'lb'))
0.3333 0.0483 0.1450
"""
f = eval("lambda x: " + fstr) # f is a Python function
A = true_integral(fstr, a, b)
# STUDENTS ADD CODE FROM HERE TO END OF FUNCTION
T = numint(f, a, b, n, scheme)
AE = abs(A - T)
RE = abs(AE / A)
return (A, AE, RE)
def make_table(f_ab_s, ns, schemes):
"""For each function f with associated bounds (a, b), and each value
of n and each scheme, calculate the absolute and relative error of
numerical integration and print out one line of a table. This
function doesn't need to return anything, just print. Each
function and bounds will be a tuple (f, a, b), so the argument
f_ab_s is a list of tuples.
Hint 1: use print() with the format string
"%s,%.2f,%.2f,%d,%s,%.4g,%.4g,%.4g", or an equivalent f-string approach.
Hint 2: consider itertools.
>>> make_table([("x**2", 0, 1), ("np.sin(x)", 0, 1)], [10, 100], ['lb', 'mp'])
x**2,0.00,1.00,10,lb,0.3333,0.04833,0.145
x**2,0.00,1.00,10,mp,0.3333,0.0008333,0.0025
x**2,0.00,1.00,100,lb,0.3333,0.004983,0.01495
x**2,0.00,1.00,100,mp,0.3333,8.333e-06,2.5e-05
np.sin(x),0.00,1.00,10,lb,0.4597,0.04246,0.09236
np.sin(x),0.00,1.00,10,mp,0.4597,0.0001916,0.0004168
np.sin(x),0.00,1.00,100,lb,0.4597,0.004211,0.009161
np.sin(x),0.00,1.00,100,mp,0.4597,1.915e-06,4.167e-06
"""
# STUDENTS ADD CODE FROM HERE TO END OF FUNCTION
for f_ab_s, ns, schemes in itertools.product(f_ab_s, ns, schemes):
res = numint_err(f_ab_s[0], f_ab_s[1], f_ab_s[2], ns, schemes)
print("%s,%.2f,%.2f,%d,%s,%.4g,%.4g,%.4g" % (f_ab_s[0], f_ab_s[1], f_ab_s[2], ns, schemes, res[0], res[1], res[2]))
def main():
"""Call make_table() as specified in the pdf."""
# STUDENTS ADD CODE FROM HERE TO END OF FUNCTION
make_table([("np.cos(x)", 0, math.pi/2), ("np.sin(2*x)", 0, 1), ("np.exp(x)", 0, 1)], [10, 100, 1000], ['lb', 'mp'])
# uncomment to run the numint_nd function
# print(round(numint_nd([np.sin, np.cos],[0, 1],[1, 2],[100, 100]), 5))
# print(round(numint_nd([np.exp, np.exp, np.exp],[0, 1, 0],[1, 2, 3],[1000, 1000, 1000]), 5))
"""
On comparing the results of each function with the 'lb' and 'mp' schemes, 'mp' scheme has better results than 'lb' scheme.
We can also infer that as the number of slices 'n' increases, the Relative error decreases for the same scheme.
For example, in the function, "sin(2x)" when 'n = 10', the difference between the relative error of the 'lb' and 'mp' scheme
is 0.06587. Whereas, when 'n = 1000', the difference between the relative error of the 'lb' and 'mp' scheme is 0.000642.
Therefore, the results of the 'mp' scheme with higher value of 'n' is closest to the value of the True Integral.
"""
def numint_nd(f, a, b, n):
"""numint in any number of dimensions.
f: a function of m arguments
a: a tuple of m values indicating the lower bound per dimension
b: a tuple of m values indicating the upper bound per dimension
n: a tuple of m values indicating the number of steps per dimension
STUDENTS ADD DOCTESTS
>>> round(numint_nd([np.sin, np.cos],[0, 1],[1, 2],[100, 100]), 5)
0.03113
>>> round(numint_nd([np.exp, np.exp, np.exp],[0, 1, 0],[1, 2, 3],[1000, 1000, 1000]), 5)
153.30086
"""
# My implementation uses Numpy and the mid-point scheme, but you
# are free to use pure Python and/or any other scheme if you prefer.
# Hint: calculate w, the step-size, per dimension
w = [(bi - ai) / ni for (ai, bi, ni) in zip(a, b, n)]
# STUDENTS ADD CODE FROM HERE TO END OF FUNCTION
# create a list of input points for each dimension
points = [np.linspace(ai, bi, ni) for (ai, bi, ni) in zip(a, b, n)]
integrals = []
for p, f, w in zip(points, f, w):
R = 0
for x in p:
R += (f(x)) * w # Calculate the f(x) * dx for each dimension
integrals.append(R) # List of all f(x) * dx values
Final = np.prod(integrals) # Product of all f(x) * dx values. Eg: For double integral: f(x) * dx * f(y) * dy
return Final
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
# In[ ]:
|
# -*- coding: utf-8 -*-
# ###################
# input : one file that contains the names in the format(other things can be present)
# # f <first name>
# # m <second name>
# # l <last name>
# one file that contains only emails in the format
# #e <email>
# with a blank line separating 2 papers
# output: one file with names as #n <full name>
# one file with mapping as <full name> ---> <email>
# ####################
author = "barno"
import codecs
import unicodedata
from itertools import izip
# latin_dict = {
# ord(u"À"): u"A", ord(u"Á"): u"A", ord(u"Â"): u"A", ord(u"Ã"): u"A",
# ord(u"Ä"): u"A", ord(u"Å"): u"A", ord(u"Æ"): u"Ae",ord( u"Ç"): u"C", ord(u"È"): u"E",
# ord(u"É"): u"E", ord(u"Ê"): u"E", ord(u"Ë"): u"E", ord(u"Ì"): u"I", ord(u"Í"): u"I",
# ord(u"Î"): u"I", ord(u"Ï"): u"I", ord(u"Ð"): u"D", ord(u"Ñ"): u"N", ord(u"Ò"): u"O",
# ord(u"Ó"): u"O", ord(u"Ô"): u"O", ord(u"Õ"): u"O", ord(u"Ö"): u"O", ord(u"×"): u"*",
# ord(u"Ø"): u"O", ord(u"Ù"): u"U", ord(u"Ú"): u"U", ord(u"Û"): u"U", ord(u"Ü"): u"U",
# ord(u"Ý"): u"Y", ord(u"Þ"): u"p", ord(u"ß"): u"b", ord(u"à"): u"a", ord(u"á"): u"a",
# ord(u"â"): u"a", ord(u"ã"): u"a", ord(u"ä"): u"a", ord(u"å"): u"a", ord(u"æ"): u"ae",
# ord(u"ç"): u"c", ord(u"è"): u"e", ord(u"é"): u"e", ord(u"ê"): u"e", ord(u"ë"): u"e",
# ord(u"ì"): u"i", ord(u"í"): u"i", ord(u"î"): u"i", ord(u"ï"): u"i", ord(u"ð"): u"d",
# ord(u"ñ"): u"n", ord(u"ò"): u"o", ord(u"ó"): u"o", ord(u"ô"): u"o", ord(u"õ"): u"o",
# ord(u"ö"): u"o", ord(u"÷"): u"/", ord(u"ø"): u"o", ord(u"ù"): u"u", ord(u"ú"): u"u",
# ord(u"û"): u"u", ord(u"ü"): u"u", ord(u"ý"): u"y", ord(u"þ"): u"p", ord(u"ÿ"): u"y",
# ord(u"’"): u"'", ord(u"-"):u"",
# }
track = 0
f = open('/home/barno/Desktop/nlp/files/names.txt','w')
with open('/home/barno/Desktop/nlp/files/title_author.txt','r') as fi:
for line in fi:
abc = line.split()
if len(abc) >= 1:
if abc[0] == "#f":
track = 0
names = ""
names = names + " " + abc[1]
track = track + 1
if abc[0] == "#m":
names = names + " " + abc[1]
track = track + 1
if abc[0] == "#l":
names = names + " " + abc[1]
track = track + 1
f.write("#n " + names + "\n")
else:
f.write("\n")
f.close()
track = 0
author = []
mail = []
ma = []
fullmail = []
found = 0
with open('/home/barno/Desktop/nlp/files/names.txt','r') as f1, open('/home/barno/Desktop/nlp/files/emails.txt','r') as f2:
for line1,line2 in izip(f1,f2):
x = line1.split()
y = line2.split()
if len(x) >= 1 and len(y) >= 1:
x.remove("#n")
y.remove("#e")
fullmail.insert(track,y[0])
y1 = y[0].split("@")
y1 = y1[0]
author.insert(track,x)
mail.insert(track,y[0])
ma.insert(track,y[0])
track = track + 1
else:
#Check if name is a substring of the mail
for mai in ma:
found = 0
m = mai.split("@")
m = m[0]
for a in author:
l = a
for ao in a:
ao = ao.replace("-","")
for n in a:
if n.lower() in m:
for na in l:
print na,
author.remove(l)
mail.remove(mai)
found = 1
break
if found == 1:
break
s = 0
i = 0
an = ""
del ma[:]
for m in mail:
ma.insert(s,m)
s = s + 1
s = 0
#Check if every character in mail occurs the same number of time is the name
if len(mail) > 0 and len(author) > 0:
for mai in ma:
m = mai.split("@")
m = m[0]
for a in author:
l = a
for n in a:
an = an + n
while s<len(m):
if m[s] in an.lower():
if m[s] in an:
indexx = an.index(m[s])
else:
indexx = an.index(m[s].upper())
s = s + 1
an = an[0:indexx] + an[indexx+1:]
else:
break
if s == len(m):
for na in l:
print na,
author.remove(l)
mail.remove(mai)
an = ""
s = 0
ma[0:] = mail[0:]
if len(mail) >= 10:
mail[0:10] = mail[-10:]
del mail[10:]
author[0:10] = author[-10:]
del author[10:]
ma[0:10] = ma[-10:]
del ma[10:]
track = 10
|
# = равно
# == соответствует
# >= больше равно
# <= меньше равно
# != неравно
if 1:
print ("True")
print ("All is ok")
# При значении 0, проверка функции не произойдет и значение не выведутся.
if 0:
print ("False")
print ("Error. Check log file")
print("All is cool!")
num = input ("Введите ваше имя: ")
if num == "Max":
print ("hello Max! Welcome to pythoncode")
elif num == "v":
print ("V means Vendetta\nWelcome Guy Fawkes ")
else:
print ("Alejandro")
#A = "Hello.\nThank you for collaboration" if num != "Test" else "Congratulations! At last we have found you!"
#print (A) |
import time
import random
print "Welcome to Russian Roulette!!"
time.sleep(2)
number = raw_input('Enter a number from 1 to 6 ')
print ('you entered %s !' % number)
q = raw_input ('ARE you ready ?! y or n ' )
if q == 'y':
x = random.randrange(1,6)
for i in range(20):
print "BE READY !!"
time.sleep(4)
print ("my number is %x" % x)
if x != int(number):
print 'you are lucky'
else:
print ' BAAAAAAAAAAAAANGG !!!!!you`re dead! '
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-27 08:44:15
LastEditors: yangyuxiang
LastEditTime: 2021-05-27 08:57:16
FilePath: /leetcode/145.二叉树的后序遍历.py
'''
#
# @lc app=leetcode.cn id=145 lang=python
#
# [145] 二叉树的后序遍历
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def reverse(self, nums):
left = 0
right = len(nums) - 1
while left <= right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
算法:迭代
后序遍历顺序:左右中
先中右左,再反转数组
"""
if not root:
return []
stack = []
res = []
cur = root
stack.append(cur)
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
# 反转数组
res = self.reverse(res)
return res
def postorderTraversal1(self, root):
"""
:type root: TreeNode
:rtype: List[int]
算法:递归
"""
if not root:
return []
res = []
def traverse(root, res):
if not root:
return
traverse(root.left, res)
traverse(root.right, res)
res.append(root.val)
traverse(root, res)
return res
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-06 22:12:18
LastEditors: yangyuxiang
LastEditTime: 2021-06-19 09:32:47
FilePath: /leetcode/二分插入.py
'''
def insert(nums, val):
left = 0
right = len(nums)
while left < right:
mid = left + (right - left) // 2
if nums[mid] == val:
return mid
elif nums[mid] > val:
right = mid
else:
left = mid + 1
return left
nums = [1,2,3,5,7,8]
target = 0
idx = insert(nums, target)
nums.insert(idx, target)
print(nums)
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-15 09:31:13
LastEditors: yangyuxiang
LastEditTime: 2021-06-23 22:25:59
FilePath: /leetcode/15.三数之和.py
'''
#
# @lc app=leetcode.cn id=15 lang=python
#
# [15] 三数之和
#
# @lc code=start
class Solution(object):
def threeSum0(self, nums):
"""
双指针法
"""
nums = sorted(nums)
n = len(nums)
res = []
i = 0
for i in range(n):
if nums[i] > 0:
break # 因为是有序的,所以后面不可能存在三元组使得和为0
if nums[i] == nums[i-1] and i >= 1:
continue
lo, hi = i+1, n-1
while lo < hi:
left, right = nums[lo], nums[hi]
target = 0 - nums[i]
if left + right < target:
lo += 1
elif left + right > target:
hi -= 1
else:
res.append([nums[i], left, right])
while lo < hi and nums[lo] == left:
lo += 1
while lo < hi and nums[hi] == right:
hi -= 1
return res
def twoSum(self, nums, target):
lo, hi = 0, len(nums)-1
res = []
while lo < hi:
sum = nums[lo]+nums[hi]
left, right = nums[lo], nums[hi]
if sum < target:
lo += 1
elif sum > target:
hi -= 1
else:
res.append([left, right])
while lo < hi and nums[lo] == left:
lo += 1
while lo < hi and nums[hi] == right:
hi -= 1
return res
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 3:
return []
nums = sorted(nums)
res = []
i = 0
while i < len(nums) :
if nums[i] > 0:
break
other = 0 - nums[i]
tmp = self.twoSum(nums[i+1:], other)
for l in tmp:
l.append(nums[i])
res.append(l)
while i < len(nums)-1 and nums[i] == nums[i+1]:
i += 1
i+=1
return res
if __name__ == "__main__":
nums = [0,0,0]
print(Solution().threeSum(nums))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-09-04 21:54:45
LastEditors: Yuxiang Yang
LastEditTime: 2021-09-04 23:24:41
FilePath: /leetcode/剑指 Offer II 101. 分割等和子串.py
Description:
给定一个非空的正整数数组 nums ,请判断能否将这些数字分成元素和相等的两部分。
输入:nums = [1,5,11,5]
输出:true
解释:nums 可以分割成 [1, 5, 5] 和 [11] 。
'''
class Solution(object):
def canPartition0(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# 背包问题
if len(nums) == 1:
return False
sum_ = sum(nums)
if sum_ % 2 == 1:
return False
target = sum_ // 2
dp = [[False] * (target + 1) for _ in range(len(nums)+1)]
for i in range(len(nums)+1):
dp[i][0] = True
for i in range(1, len(nums)+1):
for j in range(1, target+1):
if j - nums[i-1] < 0:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = dp[i-1][j] or dp[i-1][j-nums[i-1]]
return dp[-1][-1]
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# 背包问题, 状态压缩
if len(nums) == 1:
return False
sum_ = sum(nums)
if sum_ % 2 == 1:
return False
target = sum_ // 2
dp = [False] * (target + 1)
dp[0] = True
for i in range(len(nums)):
for j in range(target, -1, -1):
if j - nums[i] >= 0:
dp[j] = dp[j] or dp[j-nums[i]]
return dp[-1]
if __name__ == '__main__':
nums = [1,2,3,6,4]
print(Solution().canPartition(nums))
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-12 10:28:49
LastEditors: yangyuxiang
LastEditTime: 2021-05-12 10:36:07
FilePath: /leetcode/77.组合.py
'''
#
# @lc app=leetcode.cn id=77 lang=python
#
# [77] 组合
#
# @lc code=start
class Solution(object):
def __init__(self):
self.res = []
def backtrace(self, n, k, start, trace):
if len(trace) == k:
self.res.append(trace[:])
return
for i in range(start, n+1):
trace.append(i)
self.backtrace(n, k, i+1, trace)
trace.pop()
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
if n <= 0 and k <= 0:
return []
trace = []
start = 1
self.backtrace(n, k, start, trace)
return self.res
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-24 07:51:33
LastEditors: yangyuxiang
LastEditTime: 2021-05-24 07:58:19
FilePath: /leetcode/20.有效的括号.py
'''
#
# @lc app=leetcode.cn id=20 lang=python
#
# [20] 有效的括号
#
# @lc code=start
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
r_l = {')': '(', ']': '[', '}': '{'}
for i in range(len(s)):
if s[i] in ['(', '[', '{']:
stack.append(s[i])
else:
if stack and r_l[s[i]] == stack[-1]:
stack.pop()
else:
return False
return len(stack) == 0
if __name__ == '__main__':
s = '()'
print(Solution().isValid(s))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-13 14:21:21
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-13 15:16:57
FilePath: /leetcode/剑指 Offer 28. 对称的二叉树.py
Description:
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric0(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if not root.left and not root.right:
return True
if not root.left or not root.right:
return False
deque = []
cur = root
deque.append(cur)
while deque:
n = len(deque)
stack = []
for i in range(n):
cur = deque.pop(0)
if cur:
stack.append(str(cur.val))
else:
stack.append("null")
deque.append(cur.left)
deque.append(cur.right)
l ,r = 0, len(stack)-1
while l <= r:
if stack[l] != stack[r]:
return False
l += 1
r -= 1
return True
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def helper(left, right):
if not left and not right:
return True
if not left or not right or left.val != right.val:
return False
return helper(left.left, right.right) and helper(left.right, right.left)
if not root:
return True
return helper(root.left, root.right)
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-20 08:37:41
LastEditors: yangyuxiang
LastEditTime: 2021-05-20 09:01:58
FilePath: /leetcode/1011.在-d-天内送达包裹的能力.py
'''
#
# @lc app=leetcode.cn id=1011 lang=python
#
# [1011] 在 D 天内送达包裹的能力
#
# @lc code=start
class Solution(object):
def shipWithinDays(self, weights, days):
"""
:type weights: List[int]
:type days: int
:rtype: int
最大一次运载量为所有包裹的总重量,
因为不能拆开,所以最小也要一次运走包裹里重量最大的
从max(weights)到sum(weights)二分搜索
"""
left = max(weights)
right = sum(weights)
while left < right:
mid = left + (right - left) // 2
if self.isValid(mid, weights, days):
right = mid
else:
left = mid + 1
return left
def isValid(self, k, weights, days):
# sum = 0
# c = 1
# for i in range(len(weights)):
# sum += weights[i]
# if sum > k:
# sum = weights[i]
# c += 1
# if c > days:
# return False
# return True
i = 0
for j in range(days):
maxCap = k
while maxCap - weights[i] >= 0:
maxCap -= weights[i]
i+=1
if i == len(weights):
return True
return False
if __name__ == "__main__":
weights = [1,2,3,4,5,6,7,8,9,10]
D = 5
print(Solution().shipWithinDays(weights, D))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description: leetcode
Author: yangyuxiang
Date: 2021-05-13 10:23:48
LastEditors: yangyuxiang
LastEditTime: 2021-06-28 06:54:02
FilePath: /leetcode/22.括号生成.py
'''
#
# @lc app=leetcode.cn id=22 lang=python
#
# [22] 括号生成
#
# @lc code=start
class Solution(object):
def __init__(self):
self.res = []
def backtrace(self, left, right, trace):
if left == 0 and right == 0:
self.res.append("".join(trace))
return
if left > right: # '(' 剩得比 ')' 多
return
if left > 0:
trace.append("(")
self.backtrace(left - 1, right, trace)
trace.pop()
if right > 0:
trace.append(")")
self.backtrace(left, right - 1, trace)
trace.pop()
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
if n == 0:
return []
trace = []
self.backtrace(n, n, trace)
return self.res
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-24 10:35:31
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-24 10:38:53
FilePath: /leetcode/剑指 Offer II 083. 没有重复元素集合的全排列.py
Description:
给定一个不含重复数字的整数数组 nums ,返回其 所有可能的全排列 。可以 按任意顺序 返回答案。
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
'''
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
visited = [False] * len(nums)
def helper(nums, path):
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if visited[i] == True:
continue
visited[i] = True
path.append(nums[i])
helper(nums, path)
path.pop()
visited[i] = False
helper(nums, 0, [])
return res
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-12 21:40:45
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-12 22:14:24
FilePath: /leetcode/剑指 Offer 13. 机器人的运动范围.py
Description:
地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。
一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。
请问该机器人能够到达多少个格子?
'''
class Solution(object):
def __init__(self):
self.count = 0
def sums(self, num):
res = 0
while num != 0:
res += num % 10
num //= 10
return res
def movingCount(self, m, n, k):
"""
:type m: int
:type n: int
:type k: int
:rtype: int
"""
# directions = [[0,1], [0,-1], [1,0], [-1,0]]
directions = [[0,1], [1,0]]
visited = [[False] * n for _ in range(m)]
def dfs(m, n, i, j, k, visited):
if i < 0 or j < 0 or i >= m or j >= n:
return
if self.sums(i) + self.sums(j) > k:
return
if visited[i][j] == True:
return
visited[i][j] = True
self.count += 1
for direction in directions:
new_i, new_j = i+direction[0], j+direction[1]
dfs(m, n, new_i, new_j, k, visited)
dfs(m, n, 0, 0, k ,visited)
return self.count
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-23 22:11:07
LastEditors: yangyuxiang
LastEditTime: 2021-07-06 08:55:13
FilePath: /leetcode/45.跳跃游戏-ii.py
'''
#
# @lc app=leetcode.cn id=45 lang=python
#
# [45] 跳跃游戏 II
#
# @lc code=start
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
解法:贪心
"""
n = len(nums)
if n <= 1:
return 0
farthest = end = nums[0]
jump = 1
for i in range(1, n - 1):
farthest = max(farthest, nums[i] + i)
if end == i:
end = farthest
jump += 1
return jump
def jump1(self, nums):
"""
:type nums: List[int]
:rtype: int
解法:动态规划
"""
n = len(nums)
memo = [n for _ in range(n)] # 最多跳n-1次,这里置为n,相当于float('inf')
def dp(nums, p):
if p >= len(nums) - 1:
return 0
if memo[p] < n:
return memo[p]
steps = nums[p]
for i in range(1, steps + 1):
sub = dp(nums, p + i)
memo[p] = min(memo[p], sub + 1)
return memo[p]
return dp(nums, 0)
if __name__ == '__main__':
nums = [2, 3, 1, 1, 4]
print(Solution().jump1(nums))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-23 22:58:40
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-23 23:22:04
FilePath: /leetcode/剑指 Offer 46. 把数字翻译成字符串.py
Description:
给定一个数字,我们按照如下规则把它翻译为字符串:0 翻译成 “a” ,1 翻译成 “b”,……,11 翻译成 “l”,……,25 翻译成 “z”。
一个数字可能有多个翻译。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
'''
class Solution(object):
def translateNum0(self, num):
"""
:type num: int
:rtype: int
"""
num = str(num)
n = len(num)
if n <= 1:
return n
dp = [0] * n
dp[0] = 1
if int(num[:2]) > 25:
dp[1] = 1
else:
dp[1] = 2
for i in range(2, n):
if int(num[i-1:i+1]) <= 25 and int(num[i-1]) != 0:
dp[i] = dp[i-1] + dp[i-2]
else:
dp[i] = dp[i-1]
return dp[n-1]
def translateNum(self, num):
"""
:type num: int
:rtype: int
"""
num = str(num)
n = len(num)
if n <= 1:
return n
a, b = 1, 1
if int(num[:2]) <= 25:
b = 2
for i in range(2, n):
if int(num[i-1:i+1]) <= 25 and int(num[i-1]) != 0:
a, b = b, a + b
else:
a, b = b, b
return b
if __name__ == '__main__':
num = 506
print(Solution().translateNum(num))
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-23 16:02:22
LastEditors: yangyuxiang
LastEditTime: 2021-05-23 17:20:56
FilePath: /leetcode/82.删除排序链表中的重复元素-ii.py
'''
#
# @lc app=leetcode.cn id=82 lang=python
#
# [82] 删除排序链表中的重复元素 II
#
# @lc code=start
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def deleteDuplicates1(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
dummy = cur = ListNode(0, head)
while head and head.next:
if head.val == head.next.val:
while head and head.next and head.val == head.next.val:
head = head.next
head = head.next
cur.next = head
else:
cur = cur.next
head = head.next
return dummy.next
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
dummy = cur = ListNode(0, head)
while cur.next and cur.next.next:
if cur.next.val == cur.next.next.val:
x = cur.next.val
while cur.next and cur.next.val == x:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-04-20 16:24:47
LastEditors: yangyuxiang
LastEditTime: 2021-04-20 16:32:33
FilePath: /leetcode/509.斐波那契数.py
'''
#
# @lc app=leetcode.cn id=509 lang=python
#
# [509] 斐波那契数
#
# @lc code=start
class Solution(object):
def __init__(self):
self.memo = dict()
def fib(self, n):
"""
:type n: int
:rtype: int
"""
if n in self.memo:
return self.memo[n]
if n == 0:
return 0
if n == 1:
return 1
self.memo[n] = self.fib(n-1) + self.fib(n-2)
return self.memo[n]
# @lc code=end
|
#
# @lc app=leetcode.cn id=150 lang=python
#
# [150] 逆波兰表达式求值
#
# @lc code=start
class Solution(object):
def calc(self, x, y, f):
if f == "+":
return y + x
elif f == "-":
return y - x
elif f == "*":
return y * x
else:
return int(float(y)/x)
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
if not tokens:
return 0
stack = []
funcs = ['+', '-', '*', '/']
for token in tokens:
if token not in funcs:
stack.append(int(token))
else:
res = self.calc(stack.pop(), stack.pop(), token)
stack.append(res)
return stack[-1]
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
print(Solution().evalRPN(tokens))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-15 08:50:35
LastEditors: yangyuxiang
LastEditTime: 2021-05-15 09:30:15
FilePath: /leetcode/653.两数之和-iv-输入-bst.py
'''
#
# @lc app=leetcode.cn id=653 lang=python
#
# [653] 两数之和 IV - 输入 BST
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
BFS+HashSet
"""
hs = set()
q = []
q.append(root)
# hs.add(root.val)
while q:
sz = len(q)
for i in range(sz):
cur = q.pop(0)
if k - cur.val in hs:
return True
hs.add(cur.val)
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
return False
def findTarget1(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
先中序遍历,再双指针
"""
res = []
def help(root):
if not root:
return
help(root.left)
res.append(root.val)
help(root.right)
help(root)
# print(res)
left, right = 0, len(res)-1
while left < right:
if res[left] + res[right] == k:
return True
elif res[left] + res[right] < k:
left = left + 1
else:
right = right - 1
return False
# @lc code=end
|
#
# @lc app=leetcode.cn id=112 lang=python
#
# [112] 路径总和
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def hasPathSum1(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值,
如果要搜索其中一条符合条件的路径,递归函数就需要返回值,
因为遇到符合条件的路径了就要及时返回。
"""
if not root:
return False
if not root.left and not root.right:
return root.val == targetSum
left = self.hasPathSum(root.left, targetSum-root.val)
right = self.hasPathSum(root.right, targetSum-root.val)
return left or right
def hasPathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值,
如果要搜索其中一条符合条件的路径,递归函数就需要返回值,
因为遇到符合条件的路径了就要及时返回。
"""
if not root:
return False
def traverse(root, count):
if not root.left and not root.right:
return count == 0
if root.left:
if traverse(root.left, count-root.left.val):
return True
if root.right:
if traverse(root.right, count-root.right.val):
return True
return False
return traverse(root, targetSum-root.val)
def hasPathSum2(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
层次遍历
"""
if not root:
return False
stack = []
stack.append((root, root.val))
while stack:
n = len(stack)
for i in range(n):
cur = stack.pop(0)
node, tmp = cur
if not node.left and not node.right:
if tmp == targetSum:
return True
if node.left:
stack.append((node.left, tmp+node.left.val))
if node.right:
stack.append((node.right, tmp+node.right.val))
return False
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2)
print(Solution().hasPathSum(root, 2))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-04-22 23:07:22
LastEditors: yangyuxiang
LastEditTime: 2021-06-17 23:07:28
FilePath: /leetcode/76.最小覆盖子串.py
'''
#
# @lc app=leetcode.cn id=76 lang=python
#
# [76] 最小覆盖子串
#
# @lc code=start
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
from collections import Counter
need = Counter(t) # 记录字符串t中的字符出现次数
n = len(s)
left = right = 0 # 滑动窗口边界
window = {} # 记录滑动窗口中的字符频次
valid = 0 # 记录window中满足要求的字符个数
start = 0
min_length = n + 1
while right < n:
c = s[right]
right += 1
if c in window:
window[c] += 1
else:
window[c] = 1
if c in need:
if window[c] == need[c]:
valid += 1
while valid == len(need): # 需要缩小滑动窗口
if right - left < min_length:
min_length = right - left
start = left
c = s[left]
left += 1
if c in need:
if window[c] == need[c]:
valid -= 1
window[c] -= 1
return s[start: start+min_length] if min_length <= n else ""
if __name__ == "__main__":
s = 'ADOBECODEBANC'
t = 'ABC'
print(Solution().minWindow(s, t))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-24 08:33:13
LastEditors: yangyuxiang
LastEditTime: 2021-05-24 08:58:11
FilePath: /leetcode/56.合并区间.py
'''
#
# @lc app=leetcode.cn id=56 lang=python
#
# [56] 合并区间
#
# @lc code=start
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
n = len(intervals)
if n <= 1:
return intervals
intervals = sorted(intervals, key=lambda x: x[1])
stack = []
stack.append(intervals[0])
for i in range(1, n):
start = intervals[i][0]
while stack and stack[-1][1] >= start:
start = min(stack[-1][0], intervals[i][0])
stack.pop()
stack.append([start, intervals[i][1]])
# stack.append(intervals[i])
return stack
if __name__ == '__main__':
intervals = [[1, 3], [2, 6], [4,5], [8, 10], [15, 18]]
print(Solution().merge(intervals))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-26 11:18:54
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-26 11:22:13
FilePath: /leetcode/剑指 Offer II 012. 左右两边子数组的和相等.py
Description:
给你一个整数数组 nums ,请计算数组的 中心下标 。
数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。
如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。
如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1 。
输入:nums = [1,7,3,6,5,6]
输出:3
解释:
中心下标是 3 。
左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。
'''
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
left, right = [0] * n, [0] * n
for i in range(1, n):
left[i] = left[i-1] + nums[i-1]
for j in range(n-2, -1, -1):
right[j] = right[j+1] + nums[j+1]
for i in range(n):
if left[i] == right[i]:
return i
return -1
if __name__ == '__main__':
nums = [1,7,3,6,5,6]
print(Solution().pivotIndex(nums))
|
#
# @lc app=leetcode.cn id=912 lang=python
#
# [912] 排序数组
#
# @lc code=start
class Solution(object):
def sortArray(self, nums):
def merge_sort(nums, l, r):
"""
:type nums: List[int]
:rtype: List[int]
归并排序, inplace
"""
if l >= r:
return
mid = l + (r - l) // 2
merge_sort(nums, l, mid)
merge_sort(nums, mid+1, r)
tmp = []
# 利用两个指针分别遍历左右两个数组
i, j = l, mid+1
while i <= mid and j <= r:
if nums[j] < nums[i]:
tmp.append(nums[j])
j += 1
else:
tmp.append(nums[i])
i += 1
while j <= r:
tmp.append(nums[j])
j += 1
while i <= mid:
tmp.append(nums[i])
i += 1
nums[l:r+1] = tmp
merge_sort(nums, 0, len(nums)-1)
return nums
if __name__ == '__main__':
nums = [5,2,3,1]
print(Solution().sortArray(nums))
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-30 22:00:20
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-30 23:06:31
FilePath: /leetcode/剑指 Offer II 029. 排序的循环链表.py
Description:
'''
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
"""
class Node(object):
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class Solution(object):
def insert(self, head, insertVal):
"""
:type head: Node
:type insertVal: int
:rtype: Node
"""
if not head:
head = Node(insertVal)
head.next = head
return head
min_val, max_val = head.val, head.val
cur = head
count = 0
while cur.next != head:
count += 1
cur = cur.next
min_val = min(min_val, cur.val)
max_val = max(max_val, cur.val)
print(min_val, max_val)
if insertVal <= min_val or insertVal >= max_val:
# 比最小值小或者比最大值大,插到最大值的后面
cur = head
k = 0
while cur.val == cur.next.val or cur.next.val != min_val:
k += 1
cur = cur.next
if k > count:
break
else:
# 比最小值大,比最大值小
cur = head
while not (cur.val <= insertVal and cur.next.val >= insertVal):
cur = cur.next
tmp = cur.next
cur.next = Node(insertVal)
cur.next.next = tmp
return head |
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-09-03 07:52:34
LastEditors: Yuxiang Yang
LastEditTime: 2021-09-03 08:24:17
FilePath: /leetcode/剑指 Offer II 048. 序列化与反序列化二叉树.py
Description:
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
# 前序遍历
nodes = []
stack = [root]
cur = root
while cur or stack:
cur = stack.pop()
if cur:
nodes.append(str(cur.val))
else:
nodes.append('null')
if cur:
stack.append(cur.right)
stack.append(cur.left)
return nodes
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def helper(data):
if not data:
return None
val = data.pop(0)
if val == 'null':
return None
root = TreeNode(int(val))
root.left = helper(data)
root.right = helper(data)
return root
root = helper(data)
print(self.serialize(root))
return root
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
data = Codec().serialize(root)
print(data)
print(Codec().deserialize(data))
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-19 22:31:32
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-19 23:36:18
FilePath: /leetcode/剑指 Offer 53 - I. 在排序数组中查找数字 I.py
Description:
统计一个数字在排序数组中出现的次数。
输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
'''
class Solution(object):
def searchLeftBound(self, nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
if left == len(nums) or nums[left] != target:
return -1
else:
return left
def searchRightBound(self, nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
if nums[right] != target or right == -1:
return -1
else:
return left - 1
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if not nums:
return 0
left = self.searchLeftBound(nums, target)
right = self.searchRightBound(nums, target)
return right - left + 1 if left != -1 and right != -1 else 0
def search0(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left, right = 0, len(nums)-1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
res = 1
i = mid + 1
while i <= right and nums[i] == target:
res += 1
i += 1
i = mid - 1
while i >= left and nums[i] == target:
res += 1
i -= 1
return res
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return 0
if __name__ == '__main__':
nums = [1]
target = 1
print(Solution().searchLeftBound(nums, target))
print(Solution().searchRightBound(nums, target))
|
#!/usr/bin/env python
# coding=utf-8
'''
Description:
Author: yangyuxiang
Date: 2021-05-11 10:07:35
LastEditors: yangyuxiang
LastEditTime: 2021-05-11 11:26:08
FilePath: /leetcode/234.回文链表.py
'''
#
# @lc app=leetcode.cn id=234 lang=python
#
# [234] 回文链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import copy
class Solution(object):
def reverse(self, root):
if not root or not root.next:
return root
re = None
# cur = copy.deepcopy(root)
cur = root
while cur:
tmp = cur
cur = cur.next
tmp.next = re
re = tmp
return re
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast:
slow = slow.next
left = head
right = self.reverse(slow)
while right:
if left.val != right.val:
return False
left = left.next
right = right.next
return True
# re = self.reverse(head)
# while head and re and head.val == re.val:
# head = head.next
# re = re.next
# if head or re:
# return False
# return True
def isPalindrome1(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return True
tmp = []
while head:
tmp.append(head.val)
head = head.next
left = 0
right = len(tmp)-1
while left <= right:
if tmp[left] != tmp[right]:
return False
left += 1
right -=1
return True
# @lc code=end
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
size1 = size2 = 0
cur1, cur2 = headA, headB
while cur1:
size1 += 1
cur1 = cur1.next
while cur2:
size2 += 1
cur2 = cur2.next
if size1 > size2:
d = size1 - size2
while d > 0:
headA = headA.next
d -= 1
else:
d = size2 - size1
while d > 0:
headB = headB.next
d -= 1
while headA is not None and headB is not None:
if headA == headB:
return headA
headA = headA.next
headB = headB.next
return None |
#
# @lc app=leetcode.cn id=88 lang=python
#
# [88] 合并两个有序数组
#
# @lc code=start
class Solution(object):
def find_position(self, nums, m, target):
if not nums:
return
left, right = 0, m
while left < right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
right = mid
elif nums[mid] < target:
left = mid+1
return left
def merge0(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
for num in nums2:
idx = self.find_position(nums1, m, num)
nums1[idx+1:] = nums1[idx:-1]
nums1[idx] = num
m += 1
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
while m > 0 and n > 0:
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]
if __name__ == '__main__':
nums1 = [1,0,0,0]
m = 1
nums2 = [2,2,3]
n = 3
Solution().merge(nums1, m, nums2, n)
print(nums1)
# @lc code=end
|
#!/usr/bin/env python
# coding=utf-8
'''
Author: Yuxiang Yang
Date: 2021-08-30 08:42:32
LastEditors: Yuxiang Yang
LastEditTime: 2021-08-30 08:51:26
FilePath: /leetcode/剑指 Offer II 025. 链表中的两数相加.py
Description:
给定两个 非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
可以假设除了数字 0 之外,这两个数字都不会以零开头。
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
n_l1, n_l2 = self.reverseList(l1), self.reverseList(l2)
carry = 0
dummy = cur = ListNode(0)
while n_l1 or n_l2:
if not n_l1:
val1 = 0
else:
val1 = n_l1.val
if not n_l2:
val2 = 0
else:
val2 = n_l2.val
val = val1 + val2 + carry
if val >= 10:
carry = 1
else:
carry = 0
val = val % 10
cur.next = ListNode(val)
cur = cur.next
if n_l1:
n_l1 = n_l1.next
if n_l2:
n_l2 = n_l2.next
if carry:
cur.next = ListNode(1)
res = self.reverseList(dummy.next)
return res
|
"""Convert integer to roman numerals
Riza Marjadi"""
def integer_to_roman(num):
values = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
symbol = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
for _ in range(num // values[i]):
roman_num += symbol[i]
num -= values[i]
i += 1
return roman_num
more = 'y'
while more == 'y':
while True:
try:
integervalue = int(input("\nEnter an integer value from 0 to 10000: "))
if integervalue < 0 or integervalue > 10000:
raise ValueError
else:
break
except ValueError:
print("\nInvalid value! Please enter an integer value from 0 to 10000.")
print("Roman numeric for " + str(integervalue) + " is: " + integer_to_roman(integervalue))
more=str(input("\nMore? (y/n): "))
|
"""Coin changes
Riza Marjadi"""
print("This program will return numbers of quarters, dimes, nickels, and pennies for a dollar value")
more='y'
while more=='y':
while True:
try:
regularPrice=float(input("\nEnter the regular retail price: $"))
break
except ValueError:
print("\nInvalid value! Please enter a numerical value.")
print("\nWith 15% discount, the discounted price is: " + '${:,.2f}'.format(.85*regularPrice))
print("\nThat is a saving of: " + '${:,.2f}'.format(.15*regularPrice))
more=str(input("\nDo you want to convert more distance values? (y/n): "))
|
import data_processing
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from matplotlib import pyplot as plt
x, y = data_processing.load_car_price('car_price2.csv')
x_train = x[:120]
y_train = y[:120]
X = np.expand_dims(x, -1)
X_train = np.expand_dims(x_train, -1)
colors = ['red', 'blue', 'green']
plt.scatter(X, y, color='black', label='real')
for count, degree in enumerate([2, 3, 4]):
model = make_pipeline(PolynomialFeatures(degree), Ridge())
# model = PolynomialFeatures(degree)
model.fit(X_train, y_train)
y_predict = model.predict(X)
plt.plot(X, y_predict, color=colors[count], label="degree {}".format(degree))
plt.legend(loc='lower left')
plt.xlabel('Miles')
plt.ylabel('Price ($)')
plt.show()
|
# --*-- encoding:utf-8 --*--
#! usr/bin/env python3
students = ['小明', '小红', '小兰']
for student in students:
print('%s%s' %(student, '吃了一个苹果!'))
students = ['小明', '小红', '小兰']
for student in students:
if student == '小红':
continue
print('%s%s' %(student, '吃了一个苹果!'))
|
#!/usr/bin/env python3
import math
def dectobin(number):
li = []
while number > 0:
li.append(number % 2)
number = math.floor(number / 2)
return li[::-1]
def main():
a = 156
print(dectobin(a))
#############################################################################
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
def spiral(length):
mainli = [[None] * length for j in range(length)]
pos_x = 0
pos_y = 0
incr_x = 1
incr_y = 0
for i in range(1, length*length + 1):
mainli[pos_x][pos_y] = i
temp_x = pos_x + incr_x
temp_y = pos_y + incr_y
if 0 <= temp_x < length and 0 <= temp_y < length and mainli[temp_x][temp_y] is None:
pos_x = temp_x
pos_y = temp_y
else:
incr_x, incr_y= - incr_y, incr_x
pos_x += incr_x
pos_y += incr_y
print_spiral(mainli)
def print_spiral(array):
for y in range(len(array)):
for x in range(len(array)):
if array[x][y] > 9:
print(f" {array[x][y]} ", end="")
else:
print(f" {array[x][y]} ", end="")
print()
def main():
spiral(5)
#############################################################################
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
# encoding: utf-8
def main():
s = """Cbcq Dgyk!
Dmeybh kce cew yrwyg hmrylyaqmr:
rylsjb kce y Nwrfml npmepykmxyqg lwcjtcr!
Aqmimjjyi:
Ynyb"""
s1 = """"""
i = 0
while i < len(s):
if s[i].isalpha():
if s[i] == 'y':
s1 += 'a'
elif s[i] == 'z':
s1 += 'b'
elif s[i] == 'Y':
s1 += 'A'
elif s[i] == 'Z':
s1 += 'B'
else:
s1 += chr(ord(s[i])+2)
else:
s1 += s[i]
i += 1
print(s1)
##############################################################################
if __name__ == "__main__":
main()
|
''' 1000-digit Fibonacci number - Problem 25
INPUT: The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
'''
n_1 = 1
n_2 = 1
count = 2
while len(str(n_2)) < 1000:
n_1, n_2 = n_2, n_1 + n_2
count += 1
print(count)
|
''' Counting Sundays - Problem 19
INPUT:
Information:
- 01/12/1900 was a Monday.
- April, June, September and November - 30 days
- All the rest have - 31 days
- February - 28 days
Leap year
- February - 29 days
- Leap year if % 4 == 0
- ХХ00 if % 400 == 0
PROBLEM:
How many Sundays fell on the first of the month during the twentieth century (01/01/1901 to 31/12/2000)?
OUTPUT: 171
DOCSTRING:
'''
def count_sunday_1900_to_n(N):
count = 0
rest = 0
for year in range(1900, N+1):
months = ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
month_30 = ('April', 'June', 'September', 'November')
for i in months:
if i == 'February':
if year % 100 == 0:
if year % 400 == 0:
feb = 29
else:
feb = 28
elif year % 4 == 0:
feb = 29
else:
feb = 28
if rest == 6:
count += 1
# print(f'{count = } {year = } , February')
days = feb + rest
rest = days % 7
elif i in month_30:
if rest == 6:
count += 1
# print(f'{count = } {year = } , {i}')
days = 30 + rest
rest = days % 7
else:
if rest == 6:
count += 1
# print(f'{count = } {year = } , {i}')
days = 31 + rest
rest = days % 7
return count
start_year = 1900
finish_year = 2000
start = count_sunday_1900_to_n(start_year)
finish = count_sunday_1900_to_n(finish_year)
print(start, finish)
resalt = finish - start
print(resalt)
|
''' Largest palindrome product
Problem 4
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
'''
num_1 = 1000
num_2 = 1000
palindome = []
while num_1 >= 100:
while num_1 >= 100:
resalt = num_1 * num_2
resalt_str = str(resalt)
num_1 -= 1
if resalt_str == resalt_str[::-1]:
palindome.append(resalt)
num_2 -= 1
num_1 = num_2
print(palindome)
print(max(palindome)) |
import RPi.GPIO as IO #calling header file which helps us use GPIO’s of PI
import time #calling time to provide delays in program
IO.setwarnings(False) #do not show any warnings
IO.setmode (IO.BCM) #we are programming the GPIO by BCM pin numbers. (PIN35 as ‘GPIO19’)
IO.setup(19,IO.OUT) # initialize GPIO19 as an output.
p = IO.PWM(19,25000) #GPIO19 as PWM output, with 25000Hz frequency
p.start(0) #generate PWM signal with 0% duty cycle
print("Running")
#put in code to press enter to continue
time.sleep(10)
p.ChangeDutyCycle(30)
time.sleep(20)
p.ChangeDutyCycle(0)
|
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
money = float(input("Введите количество денег "))
v = list(per_cent.values())
v = list(map(lambda x: x* money*0.01, v))
print(v)
print(max(v)) |
import random
class Monty(object):
def __init__(self, numIterations, switch):
self.choices = ["0", "1", "2"]
self.wins = 0
self.losses = 0
self.iterations = numIterations
self.isSwitch = switch
random.seed()
def RunGame(self):
for i in range(self.iterations):
# randomize the choices
random.shuffle(self.choices)
# randomly pick a winner
self.choiceWinner = random.choice(self.choices)
# user picks a random choice
self.choiceUser = random.choice(self.choices)
# find a loser that's not the user's choice or the winning choice
while (True):
# grab a random item from choices and dub that as the temp loser
tempLoser = random.choice(self.choices)
# make sure the temp loser doesn't match the user's choice or the winning choice
if (tempLoser != self.choiceUser and tempLoser != self.choiceWinner):
# store the temp loser for later use and break from infinite loop
self.choiceLoser = tempLoser
break
#self.isSwitch = random.choice([True, False])
# if desired, user switches their choice
if (self.isSwitch):
# grab the only remaining choice, increasing your chances of winning
while (True):
# grab a random item from choices and dub that as the temp choice
tempChoice = random.choice(self.choices)
# make sure the temp choice doesn't match the user's choice or the revealed losing choice
if (tempChoice != self.choiceUser and tempChoice != self.choiceLoser):
# store the temp choice as the new user's choice and break from infinite loop
self.choiceUser = tempChoice
break
# increment wins/losses
if (self.choiceUser == self.choiceWinner):
self.wins += 1
else:
self.losses += 1
# main method
def main():
# print title
print "Monty Hall Paradox - CS5300 Final Project - Andy Ladd, Matt Layher"
print "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
# set parameters
numIterations = 100000
switch = True
# run game
print "[main] running {0} iterations...".format(numIterations)
game = Monty(numIterations, switch)
game.RunGame()
print "[main] iterations complete!"
# print results
print "[main] results:"
print "\twins: ", game.wins
print "\tlosses:", game.losses
# run it!
main()
|
# polynomial (linear) regression by 2blam
# import the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# import dataset
dataset = pd.read_csv("Position_Salaries.csv")
X = dataset.iloc[:, 1].values # Level column
y = dataset.iloc[:, 2].values # Salary column
# prefer using matrix representation, instead of vector (e.g. (10, ))
X = np.reshape(X, (X.shape[0], 1)) # e.g. (10, ) -> (10, 1)
#another approach - using 1:2 in the column index
# X = dataset.iloc[:, 1:2].values # Level column
# linear regression vs polynomial regression
# linear regression
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)
# polynomial regression
from sklearn.preprocessing import PolynomialFeatures
polyFeat = PolynomialFeatures(degree=2) #create the polynomial features with degree = 2
# b_0*x_0 + b_1*x_1 + b_2*x_1^2
X_poly = polyFeat.fit_transform(X)
poly_reg = LinearRegression()
poly_reg.fit(X_poly, y)
# plot
plt.scatter(X, y, color="red")
plt.plot(X, lin_reg.predict(X), color="blue") #regression line
plt.title("Position Level vs Salary (Linear regression)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape(len(X_grid), 1)
plt.scatter(X, y, color="red")
plt.plot(X_grid, poly_reg.predict(polyFeat.fit_transform(X_grid)), color="blue") #smoother curve with more data point X_grid
plt.title("Position Level vs Salary (Polynomial regression)")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
# predict salary with position level 6.5
lin_reg.predict(6.5)
poly_reg.predict(polyFeat.fit_transform(6.5)) #degree = 2; salary = 189498
|
def sapa(name):
print(f"Hello, {name}")
sapa("Luke Skywalker")
def tanya(nama, hal):
print(f"Hello, {nama}, anda sedang berada di halaman {hal}")
tanya("Luke","user admin")
def printNegative(index, length):
if index == "" and length == "":
return
while index < length:
if index %2 == 1:
print(index)
index += 1
printNegative(0,10)
def sum_two_numbers(a, b)
return a + b
sum_two_numbers("2", "3") |
#创建coachdata.sqlite数据库
import sqlite3
connection=sqlite3.connect('coachdata.sqllite')
cursor=connection.cursor()
cursor.execute("""CREATE TABLE athletes(
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
name TEXT NOT NULL,
dob DATE NOT NULL)""")
cursor.execute("""CREATE TABLE timing_data(
athlete_id INTERGER NOT NULL,
value TEXT NOT NULL,
FOREIGN KEY (athlete_id)REFERENCES athletes)""")
connection.commit()
connection.close() |
import pickle
from athletelist import AthleteList
from athletelist import get_coach_data
def put_to_store(files_list):
all_athletes={}
for each_file in files_list:
ath=get_coach_data(each_file) #将各个文件转换为AthleteList对象实例
all_athletes[ath.name]=ath #把对象实例存储到字典中,对象实例的键名与实例的name属性相同;对象实例是值
# print(all_athletes[ath.name].name)
try:
with open('athletes.pickle','wb')as athf: #'wb' 二进制写方式
pickle.dump(all_athletes,athf)
except IOError as ioerr:
print('File error(put_to_store):'+str(ioerr))
return(all_athletes)
def get_from_store():
all_athletes={}
try:
with open('athletes.pickle','rb')as athf: #二进制读方式
pickle.load(athf)
except IOError as ioerr:
print('File error(put_to_store):'+str(ioerr))
return(all_athletes)
#查看当前命名空间下所有可用的方法,确认导入成功
# print(dir())
the_files=['james2.txt','julie2.txt','mikey2.txt','sarah2.txt']
#条用put_to_store()函数 将文件列表中的数据转换为一个字典,存储在一个pickle文件中
data=put_to_store(the_files)
#遍历字典查看选手的名字和出生日期
for each_athlete in data:
print(data[each_athlete].name+' '+data[each_athlete].birthday)
#通过get_from_store()函数将pickle中的腌制数据加载到一个字典中,遍历查看各个选手的名字、出生日期
data2=get_from_store()
for each_athlete in data:
print(data[each_athlete].name+' '+data[each_athlete].birthday)
|
import tkinter as tk
window = tk.Tk()
window.geometry("306x245")
window.minsize(306, 245)
window.title('calculator')
window.configure(bg='gray20')
expression = ''
input_text = tk.StringVar()
def btn_click(item):
"""function continuously updates the input field whenever you enters a number"""
global expression
expression = expression + str(item)
input_text.set(expression)
def btn_clear():
"""function clears the input field"""
global expression
expression = ""
input_text.set("")
def btn_equal():
"""calculates the expression present in input field"""
global expression
result = str(eval(expression))
input_text.set(result)
expression = ""
# frame for the result and input field
input_frame = tk.Frame(window, bd=0, highlightbackground="gray15")
input_frame.pack(side='top', fill='both', padx=5, pady=(10, 3))
input_field = tk.Entry(input_frame, font=('monospace', 20, 'bold'),
textvariable=input_text, bg='gray15', fg='white', bd=0, justify='center')
input_field.pack(fill='both')
# buttons frame
btns_frame = tk.Frame(window, bg="gray17", bd=0)
btns_frame.pack(padx=3, pady=5)
# first row
btn_7 = tk.Button(btns_frame, text="7", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('7')).grid(row=0, column=0, padx=1, pady=1)
btn_8 = tk.Button(btns_frame, text="8", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('8')).grid(row=0, column=1, padx=1, pady=1)
btn_9 = tk.Button(btns_frame, text="9", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('9')).grid(row=0, column=2, padx=1, pady=1)
divide = tk.Button(btns_frame, text="➗", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('/')).grid(row=0, column=3, sticky='EWNS', padx=(10, 1), pady=1)
clear = tk.Button(btns_frame, text="clear", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_clear()).grid(row=0, column=4, columnspan=2, sticky='EWNS', padx=1, pady=1)
# second row
btn_4 = tk.Button(btns_frame, text="4", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('4')).grid(row=1, column=0, padx=1, pady=1)
btn_5 = tk.Button(btns_frame, text="5", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('5')).grid(row=1, column=1, padx=1, pady=1)
btn_6 = tk.Button(btns_frame, text="6", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('6')).grid(row=1, column=2, padx=1, pady=1)
multiply = tk.Button(btns_frame, text="✖", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('*')).grid(row=1, column=3, sticky='EWNS', padx=(10, 1), pady=1)
square = tk.Button(btns_frame, text="𝑥²", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('**2')).grid(row=1, column=4, sticky='EWNS', padx=1, pady=1)
cube = tk.Button(btns_frame, text="𝑥³", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('**3')).grid(row=1, column=5, sticky='EWNS', padx=1, pady=1)
# third row
btn_1 = tk.Button(btns_frame, text="1", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('1')).grid(row=2, column=0, padx=1, pady=1)
btn_2 = tk.Button(btns_frame, text="2", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('2')).grid(row=2, column=1, padx=1, pady=1)
btn_3 = tk.Button(btns_frame, text="3", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('3')).grid(row=2, column=2, padx=1, pady=1)
minus = tk.Button(btns_frame, text="‒", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('-')).grid(row=2, column=3, sticky='EWNS', padx=(10, 1), pady=1)
open_brkt = tk.Button(btns_frame, text="(", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('(')).grid(row=2, column=4, sticky='EWNS', padx=1, pady=1)
close_brkt = tk.Button(btns_frame, text=")", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click(')')).grid(row=2, column=5, sticky='EWNS', padx=1, pady=1)
# forth row
btn_0 = tk.Button(btns_frame, text="0", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('0')).grid(row=3, column=0, sticky='EWNS', padx=1, pady=1)
dot = tk.Button(btns_frame, text="・", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('.')).grid(row=3, column=1, sticky='EWNS', padx=1, pady=1,)
mod = tk.Button(btns_frame, text="ᶬ", fg="white", bd=0, bg="gray20", font=('monospace, bold', 20),
command=lambda: btn_click('%')).grid(row=3, column=2, sticky='EWNS', padx=1, pady=1)
add = tk.Button(btns_frame, text="✚", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_click('+')).grid(row=3, column=3, sticky='EWNS', padx=(10, 1), pady=1)
equal = tk.Button(btns_frame, text="=", fg="white", bd=0, bg="gray20", font=('monospace, 20'),
command=lambda: btn_equal()).grid(row=3, column=4, columnspan=2, sticky='EWNS', padx=1, pady=1)
window.mainloop()
|
#!/usr/bin/env python
# coding: utf-8
# In[3]:
#In order to check if a string contain specific suffix like car
print('user_car'.endswith('car'))
# In[4]:
# check from index 4 to end of string
print('user_car'.endswith('car', 4))
# In[5]:
#To check from index 5 to 7
print('user_car'.endswith('car', 5, 8))
# In[6]:
#To check from index 4 to 8
print('user_car'.endswith('car',4, 8))
# In[7]:
#In order to use a tuple of suffixes as we check from index 4 to 8
print('user_car'.endswith(('car', 'ar'), 4, 8))
# In[ ]:
|
import math
print(math.exp(3)) #Esta funcion es mucho mas precisa
print(math.e**3) #Que invocar la variable e y exponer
print(math.pow(math.e,3)) #Que invocar la variable e y exponer
print(math.log(12)) #Si no le especificas toma logaritmo base e
print(math.log(12,2))
print(math.log2(32))
print(math.log10(100))
print(math.sqrt(100))
print(math.sin(180)) #El argumento tiene que estar en radianes, no son 180 grados, si no, 180 Radianes
print(math.cos(math.pi))
print(math.tan(math.pi/2))
print(math.asin(1))
print(math.acos(0))
print(math.atan(1)) #= 0.7853981633974483
#Ahora, hay una funciona math.degrees que convierte de ranidanes a grados
print(math.degrees(0.7853981633974483)) #= 0.7853981633974483 = 45°
print(math.radians(60)) #= 60° = 1.0471975511965976 Radianes
print(math.cos(math.radians(60))) #= 60° = 1.0471975511965976 Radianes
#Longitud de un vector
print(math.hypot(3,4)) #Hipotenusa
print(math.atan2(4,3)) #El angulo que forma con el eje x, está girado (y,x) resultado en radianes
print(math.degrees(math.atan2(4,3))) #El angulo que forma con el eje x, está girado (y,x) resultado en radianes
#Funciones hiperbolicas
print(math.sinh(0)) #
print(math.cosh(0)) #
print(math.tanh(0)) #
#unas que no entendí muy bien, pero tienen que ver con estadistica y campanas de gauss
print(math.erf(math.pi)) #
print(math.erfc(math.pi)) # Lo que le falta a la funcion anterior para llegar a 1
print(math.erfc(math.pi)+math.erf(math.pi)) # Lo que le falta a la funcion anterior para llegar a 1
print(math.gamma(2)) # Factorial de n-1
print(math.lgamma(2)) # Factorial de n-1
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
x = [1,2,3,4,5,6,7,8,9,10]
print(1 in set(x), 15 in set(x),20 in set(x))
# In[2]:
numbers = [1,2,5,6,12,15,20]
num_set = set(numbers)
print(num_set)
# In[3]:
my_colors = {"red","yellow","orange","green","blue"}
print("yellow" in my_colors)
# In[4]:
print(my_colors.pop())
# In[5]:
print(my_colors)
# In[ ]:
#get the result of the union the next two sets:
a = {'red', 'yellow','orange','green'}
b = {'red','orange','black'}
print(a.union(b))
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
user_name_and_car_color = {'David':'red','John':'green','Sara':'yellow'}
# In[ ]:
user_name_and_car_color['Kate'] = 'black'
print(user_name_and_car_color)
# In[ ]:
#In order to remove the item with key = “Kate” and print dictionary:
del user_name_and_car_color['Kate']
# In[ ]:
#In order to print the item with key = “David” code as following:
print(user_name_and_car_color['David'])
# In[ ]:
print(user_name_and_car_color['Sara'])
# In[ ]:
print(user_name_and_car_color['John'])
# In[ ]:
user_name_and_car_color.get('John')
# In[ ]:
'David' in user_name_and_car_color
# In[ ]:
'Kate' in user_name_and_car_color
# In[ ]:
'red'in user_name_and_car_color.values()
# In[ ]:
'black'in user_name_and_car_color.values()
# In[ ]:
user_name_and_car_color.clear()
# In[ ]:
print(user_name_and_car_color)
# In[ ]:
user_name_and_car_color = {'David':'red','John':'green','Sara':'yellow'}
user_name_and_car_color.pop('John')
# In[ ]:
user_name_and_car_color = {'David':'red','John':'green','Sara':'yellow'}
user_name_and_car_color.items()
# In[ ]:
#Write a python code to arrange the following dictionary
values = {'key_1': [20, 80, 50], 'key_2': [200, 10, 100], 'key_3': [300, 20, 400]}
arregloNumeros = []
arregloValues = []
arregloFinal = []
for i in values.values():
for y in i:
arregloNumeros.append(y)
arregloNumeros.sort()
print(arregloNumeros)
arregloValues = []
contadorPosicion = -1
for i in arregloNumeros:
arregloFinal.append(i)
if(len(arregloFinal) == 3):
arregloValues.append(arregloFinal)
for i, j in zip(arregloFinal, values.keys()):
values.update({j:i})
arregloFinal = []
print(values)
print(arregloValues)
|
from enum import Enum
def convert_to_enum(item, enum, prefix='', to_upper=False):
if isinstance(item, Enum):
return item
elif isinstance(item, (int, float)):
try:
return enum(item)
except ValueError:
raise ValueError('Cannon convert int/float to enum')
elif isinstance(item, str):
member = item.replace(' ', '_')
if to_upper:
member = member.upper()
if prefix and not member.startswith(prefix):
member = prefix + member
try:
return enum[member]
except KeyError:
raise KeyError('Invalid key in converting enum')
else:
raise ValueError('Invalid type for enum')
def check(result):
if result != 0:
raise ValueError('Function failed')
else:
return result |
# Import Mods
import os
import csv
#set path for file
csvpath = os.path.join("Resources" , "PyBank_budget_data.csv")
# Open the CSV file
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# ignore first row - header
csvheader = next(csvfile)
# print(f"header:{header}")
# set counters to 0
Total_Profit = 0.00
Total_Months = 0
Avg_Change = 0
# store values in empty list for the variables
Months = []
Profit = []
Avg_Change = []
for row in csvreader:
# total amount of "Profit/Losses"
Total_Profit = (Total_Profit + float(row[1]))
# total number of months
Total_Months = int(Total_Months+1)
# find the increase in profits in the amount list
Profit.append(float(row[1]))
# find the increase in profits in the months list
Months.append(str(row[0]))
# going through the profits in order to get the monthly change
for i in range(len(Profit)-1):
# getting the difference (decrease) between the two numbers and add to monthly profit change list
Avg_Change.append(Profit[i+1]-Profit[i])
increase_value = max(Avg_Change)
decrease_value = min(Avg_Change)
# finding max and min in the months using the month list and index from max and min
increase_month = Avg_Change.index(max(Avg_Change)) + 1
decrease_month = Avg_Change.index(min(Avg_Change)) + 1
#display results
print("Financial Analysis")
print("...........................")
print(f"Total months: {Total_Months}")
print(f"Total profit: ${Total_Profit}")
print(f"Average change: ${round(sum(Avg_Change)/len(Avg_Change),2)}")
print(f"Greatest Increase in Profits: {Months[increase_month]} ${increase_value}")
print(f"Greatest Decrease in Profits: {Months[decrease_month]} ${decrease_value}")
# Output results to a file
output_file = os.path.join("analysis", "analysis_results.txt")
with open (output_file, "w") as file:
file.write("Financial Analysis")
file.write("\n")
file.write("...........................")
file.write("\n")
file.write(f"Total months: {Total_Months}")
file.write("\n")
file.write(f"Total profit: ${Total_Profit}")
file.write("\n")
file.write(f"Average change: ${round(sum(Avg_Change)/len(Avg_Change),2)}")
file.write("\n")
file.write(f"Greatest Increase in Profits: {Months[increase_month]} ${increase_value}")
file.write("\n")
file.write(f"Greatest Decrease in Profits: {Months[decrease_month]} ${decrease_value}") |
a = list('hello')
print(f'Made list from string hello, {a}')
a.append(100)
print(f'Can append integer (100) to list of strings, {a}')
a.extend((1, 2, 3))
print(f'Can be extended using tuples, {a}')
a.extend('...')
print(f'Extended by a string (...), {a}') |
"""Provides corresponding single or plural values
"""
plurals = {
'Opportunities':'Opportunity',
'CPQ Quotes':'CPQ Quote'
}
def get_single_or_plural(name):
"""Return corresponding to ``name`` single or plural value form global ``plurals`` dictionary
"""
print(name)
for k, v in plurals.items():
if k == name:
return v
if v == name:
return k
|
import csv
import glob
import os
from pathlib import Path
#get name of csv file in same path as script
targetfile = os.path.dirname(os.path.abspath(__file__))+"\*.csv"
filename = glob.glob(targetfile)[0]
fields = []
rows = []
results = []
nopattern = []
#read csv file
with open (filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
fields = next(csvreader)
for row in csvreader:
rows.append(row)
for row in rows:
#split comment to parse # of ticket and check that it is a ticket
words = row[5][27:].replace('-', "").split(' ')
print(row[5][27:])
#iterate through comment to find integers
numbers = []
number = ""
tickets = "0"
for element in row[5][27:]:
if element.isnumeric():
if len(number) > 0:
number = number + element
else:
number = element
else:
if len(number) > 0:
if int(number) <= 10 and int(number) > 0:
numbers.append(number)
number = ""
#check that comment includes keyword ticket and only has 1 valid integer
if ("ticket" in row[5][27:].lower()) == True and len(numbers) == 1:
isticket = True
tickets = numbers[0]
else:
isticket = False
#check if row is a charge
#if it is add it to the result list and had a valid # of tickets
if row[2] == "incoming" and row[3] == "purchase" and isticket == True:
row.append(tickets)
#next line needed i
for i in range(int(tickets)):
results.append(row)
#create seperate list of transactions that dont have a comment that starts with
#an integer then keyword ticket, but the transaction type could be ticket sale with a bad comment ie. for the #
elif row[2] == "incoming" and row[3] == "purchase" and ("membership" in row[5][27:].lower()) == False:
nopattern.append(row)
elif row[2] == "outgoing" and row[3] == "transfer" and ("win" in row[5].lower()) == True:
break
#write results to text file for the randomizer
f = open("result.txt", "w")
for el in results:
f.write(str(int((int(el[4])/int(el[8]))))+'\t'+el[5][27:].replace('\n', " ")+'\n')
#write the non matching records to new csv file for review
f = open("mismatches.csv", "w")
for el in nopattern:
f.write(el[4]+','+el[5][27:].replace('\n', " ")+'\n')
|
# Алгоритм вычисления значения функции F(n), где n – натуральное число, задан следующими соотношениями:
# F(n) = n + 15, при n ≤ 5
# F(n) = F(n//2) + n*n*n - 1, при чётных n > 5
# F(n) = F(n-1) + 2*n*n + 1, при нечётных n > 5
# Здесь // обозначает деление нацело. Определите количество натуральных значений n из отрезка [1; 1000], для которых значение F(n) содержит не менее двух цифр 8.
def workMan(num):
if num <= 5:
return num + 15
elif num % 2 == 0:
return workMan(num // 2) + num ** 3 - 1
else:
return workMan(num - 1) + 2 * (num ** 2) + 1
def isNumRight(num):
num = str(workMan(num))
return num.count('8') >= 2
counter = 0
for num in range(1, 1001):
if isNumRight(num):
counter += 1
print(counter) # 164
|
'''
Argument: Argument is input that you feed to the program or command to respond.
Parsing: When you hit ls -l the OS parses it in a certain way under the hood.
Reference Link: https://www.datacamp.com/community/tutorials/argument-parsing-in-python
'''
# arg_demo.py
import argparse
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
return parser.parse_args()
if __name__ == '__main__':
get_args()
'''
Adding More Arguments
'''
# arg_demo2.py
import argparse
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
# required argument
parser.add_argument('-x', action="store", required=True,
help='Help text for option X')
# optional arguments
parser.add_argument('-y', help='Help text for option Y', default=False)
parser.add_argument('-z', help='Help text for option Z', type=int)
print(parser.parse_args())
if __name__ == '__main__':
get_args()
'''
Adding a Long Option '--execute'
'''
parser.add_argument('-x', '--execute', action='store', required=True,
help='Help text for option X')
'''
Adding constraint where one option cannot be passed with another option
group = parser.add_mutually_exclusive_group()
'''
import argparse
def get_args():
""""""
parser = argparse.ArgumentParser(
description="A simple argument parser",
epilog="This is where you might put example usage"
)
group = parser.add_mutually_exclusive_group()
group.add_argument('-x', '--execute', action="store",
help='Help text for option X')
group.add_argument('-y', help='Help text for option Y', default=False)
parser.add_argument('-z', help='Help text for option Z', type=int)
print(parser.parse_args())
if __name__ == '__main__':
get_args() |
## APPROACH : LINKED LISTS ##
## LOGIC : GREEDY ##
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
self.prev = None
class BrowserHistory:
def __init__(self, homepage: str):
self.root = ListNode(homepage)
def visit(self, url: str) -> None:
node = ListNode(url)
node.prev = self.root
self.root.next = node
self.root = self.root.next
def back(self, steps: int) -> str:
while (steps and self.root.prev):
self.root = self.root.prev
steps -= 1
return self.root.val
def forward(self, steps: int) -> str:
while (steps and self.root.next):
self.root = self.root.next
steps -= 1
return self.root.val
# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)
#Approach: stack
class BrowserHistory:
def __init__(self, homepage: str):
self.stack = [homepage]
self.ptr = 0
def visit(self, url: str) -> None:
self.stack = self.stack[:self.ptr+1] + [url]
self.ptr = len(self.stack) - 1
def back(self, steps: int) -> str:
self.ptr = max(0, self.ptr - steps)
return self.stack[self.ptr]
def forward(self, steps: int) -> str:
self.ptr = min(len(self.stack) - 1, self.ptr + steps)
return self.stack[self.ptr] |
'''
You are given a string that represents time in the format hh:mm.
Some of the digits are blank (represented by ?).
Fill in ? such that the time represented by this string is the maximum possible.
Maximum time: 23:59, minimum time: 00:00. You can assume that input string is always valid.
Example1:
Input: "?4:5?"
Output: "14:59"
Example2:
Input: "23:5?"
Output: "23:59"
Example3:
Input: "2?:22"
Output: "23:22"
Example4:
Input: "0?:??"
Output: "09:59"
Example5:
Input: "??:??"
Output: "23:59"
'''
# def maxTime(time):
# if s[0] == "?":
# if s[1] != "?":
# if int(s[1]) > 3:
# s = "1" + s[1:]
# else:
# s = "2" + s[1:]
# else:
# s = "2" + s[1:]
# if s[1] == "?":
# if (s[0] == "2"):
# s = s[:1] + "3" + s[2:]
# else:
# s = s[:1] + "9" + s[2:]
# if s[3] == "?":
# s = s[:3] + "5" + s[4:]
# if s[4] == "?":
# s = s[:4] + "9"
# return s
def maxTime(time):
hh,mm = time.split(":")
if hh == "??":
hh = "23"
else:
for i in range(9,-1,-1):
h = hh
h = h.replace('?',str(i))
if int(h) <= 23:
hh = str(h)
break
if mm == "??":
mm = "59"
else:
for j in range(9,-1,-1):
m = mm
m = m.replace('?',str(j))
if int(m) <= 59:
mm = str(m)
break
print (hh + ":" + mm)
maxTime("?4:5?")
maxTime("23:5?")
maxTime("2?:22")
maxTime("??:??")
maxTime("0?:??")
|
'''
Given an Array A, find the minimum amplitude you can get after changing up to 3 elements.
Amplitude is the range of the array (basically difference between largest and smallest element).
Example1:
Input: [-1, 3, -1, 8, 5 4]
Output: 2
Explanation: we can change -1, -1, 8 to 3, 4 or 5
Example2:
Input: [10, 10, 3, 4, 10]
Output: 0
Explanation: change 3 and 4 to 10
'''
'''
Method1: Sliding Window
TC: O(nlogn)
SC: O(n)
'''
def minAplitude(nums):
n = len(nums)
if n <= 4:
return 0
nums.sort()
ans = float('inf')
for i in range(4):
ans = min(ans, nums[i+n-4]-nums[i])
print(ans)
minAplitude([-1,3,-1,8,5,4])
minAplitude([10,10,3,4,10])
'''
Method2: Two Heap
TC: nlogn
SC: n
'''
import heapq
def minDifference(self, nums: List[int]) -> int:
if len(nums) < 5:
return 0
small = heapq.nsmallest(4, nums)
big = heapq.nlargest(4, nums)
return min(big[3] - small[0], big[2] - small[1], big[1] - small[2], big[0] - small[3])
|
'''
Method: Recursive BFS
TC: O(N)
SC: O(N)
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
def inorder(r):
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
return inorder(root)[k - 1]
'''
Method2: Iterative
TC: O(H+k)
SC: O(H)
'''
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
stack = deque()
n = 0
if root is None:
return
node = root
while True:
while node:
stack.append(node)
node = node.left
node = stack.pop()
n += 1
if n == k:
return node.val
node = node.right
|
'''
ChainMap: A ChainMap is a class that provides the ability to link multiple mappings together such that they end up being a single unit.
'''
import argparse
import os
from collections import ChainMap
def main():
app_defaults = {'username':'admin', 'password':'admin'}
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username')
parser.add_argument('-p', '--password')
args = parser.parse_args()
command_line_arguments = {key:value for key, value
in vars(args).items() if value} #vars(args) equals args.__dict__.
chain = ChainMap(command_line_arguments, os.environ,
app_defaults)
print(chain['username'])
if __name__ == '__main__':
main()
os.environ['username'] = 'test'
main() |
'''
collections: Container datatypes
namedtuple():factory function for creating tuple subclasses with named fields
deque: list-like container with fast appends and pops on either end
ChainMap: dict-like class for creating a single view of multiple mappings
Counter: dict subclass for counting hashable objects
OrderedDict: dict subclass that remembers the order entries were added
defaultdict: dict subclass that calls a factory function to supply missing values
UserDict: wrapper around dictionary objects for easier dict subclassing
UserList: wrapper around list objects for easier list subclassing
UserString: wrapper around string objects for easier string subclassing
'''
import collections
dict1 = {'day1': 'Mon', 'day2': 'Tue'}
dict2 = {'day3': 'Wed', 'day4': 'Thu'}
res = collections.ChainMap(dict1, dict2)
# Creating a single dictionary
print(res.maps,'\n')
print('Keys = {}'. format(list(res.keys())))
print('Values = {}'.format(list(res.values())))
print()
# Print all the elements from the result
print('elements:')
for key, val in res.items():
print('{} = {}'.format(key, val))
print()
# Find a specific value in the result
print('day3 in res: {}'.format(('day3' in res)))
print('day4 in res: {}'.format(('day4' in res)))
dict2['day4'] = 'Fri'
print(res.maps,'\n')
|
'''
Time complexity #
Since, at the most, all the projects will be pushed to both the heaps once, the time complexity of our algorithm is
O(NlogN+KlogN), where ‘N’ is the total number of projects and ‘K’ is the number of projects we are selecting.
Space complexity #
The space complexity will be
O(N) because we will be storing all the projects in the heaps.
'''
from heapq import *
def find_maximum_capital(capital, profits, numberOfProjects, initialCapital):
minCapitalHeap = []
maxProfitHeap = []
# insert all project capitals to a min-heap
for i in range(0, len(profits)):
heappush(minCapitalHeap, (capital[i], i))
# let's try to find a total of 'numberOfProjects' best projects
availableCapital = initialCapital
for _ in range(numberOfProjects):
# find all projects that can be selected within the available capital and insert them in a max-heap
while minCapitalHeap and minCapitalHeap[0][0] <= availableCapital:
capital, i = heappop(minCapitalHeap)
heappush(maxProfitHeap, (-profits[i], i))
# terminate if we are not able to find any project that can be completed within the available capital
if not maxProfitHeap:
break
# select the project with the maximum profit
availableCapital += -heappop(maxProfitHeap)[0]
return availableCapital
def main():
print("Maximum capital: " +
str(find_maximum_capital([0, 1, 2], [1, 2, 3], 2, 1)))
print("Maximum capital: " +
str(find_maximum_capital([0, 1, 2, 3], [1, 2, 3, 5], 3, 0)))
main()
|
'''
A struct is basically a complex data type that groups a list of variables under one name.
namedtuple which you can use to replace Python’s tuple.
'''
from collections import namedtuple
Parts = namedtuple('Parts', 'id_num desc cost amount')
auto_parts = Parts(id_num='1234', desc='Ford Engine',
cost=1200.00, amount=10)
print(auto_parts.id_num)
'''
Python dict into object
'''
from collections import namedtuple
Parts = {'id_num':'1234', 'desc':'Ford Engine',
'cost':1200.00, 'amount':10}
parts = namedtuple('Parts', Parts.keys())(**Parts) #**(**Parts)**. The double asterisk means that we are calling our class using keyword arguments, which in this case is our dictionary.
print (parts)
#Parts(amount=10, cost=1200.0, id_num='1234', desc='Ford Engine')
'''
Same as above
'''
parts = namedtuple('Parts', Parts.keys())
print (parts)
#<class '__main__.Parts'>
auto_parts = parts(**Parts)
print (auto_parts)
#Parts(amount=10, cost=1200.0, id_num='1234', desc='Ford Engine')
|
<<<<<<< HEAD
# from collections import defaultdict
# import math
# def digitAnagrams(a):
# count = 0
# dict = defaultdict(list)
# for i in range(len(a)):
# s="".join(sorted(str(a[i])))
# dict[s].append(a[i])
#
# for k in dict:
# n = len(dict[k])
# if n>= 2:
# pair = math.factorial(n) // (2*(math.factorial(n-2)))
# count += pair
# print (count)
#
# a = [25,35,872,228,53,278,872]
# digitAnagrams(a)
# def stringAnagrams(s1, s2):
# if (sorted(s1) == sorted(s2)):
# print ("Anagrams")
# else:
# print ("Not Anagrams")
#
# s1 = "listen"
# s2 = "silent"
# stringAnagrams(s1, s2)
# from collections import defaultdict
#
# def printAnagramsTogether(words):
# groupedWords = defaultdict(list)
#
# # Put all anagram words together in a dictionary
# # where key is sorted word
# for word in words:
# groupedWords["".join(sorted(word))].append(word)
#
# # Print all anagrams together
# for group in groupedWords.values():
# print(" ".join(group))
#
#
# if __name__ == "__main__":
# arr = ["cat", "dog", "tac", "god", "act"]
# printAnagramsTogether(arr)
=======
# from collections import defaultdict
# import math
# def digitAnagrams(a):
# count = 0
# dict = defaultdict(list)
# for i in range(len(a)):
# s="".join(sorted(str(a[i])))
# dict[s].append(a[i])
#
# for k in dict:
# n = len(dict[k])
# if n>= 2:
# pair = math.factorial(n) // (2*(math.factorial(n-2)))
# count += pair
# print (count)
#
# a = [25,35,872,228,53,278,872]
# digitAnagrams(a)
# def stringAnagrams(s1, s2):
# if (sorted(s1) == sorted(s2)):
# print ("Anagrams")
# else:
# print ("Not Anagrams")
#
# s1 = "listen"
# s2 = "silent"
# stringAnagrams(s1, s2)
from collections import defaultdict
def printAnagramsTogether(words):
groupedWords = defaultdict(list)
# Put all anagram words together in a dictionary
# where key is sorted word
for word in words:
groupedWords["".join(sorted(word))].append(word)
# Print all anagrams together
for group in groupedWords.values():
print(" ".join(group))
if __name__ == "__main__":
arr = ["cat", "dog", "tac", "god", "act"]
printAnagramsTogether(arr)
>>>>>>> 6a511d70a9044aa21ff457120200837581634c3b
|
'''
Question: Given a list of video clips with start and end positions, write a program to find out the missing video segments in a given interval
Each video clip comes with two elements start and end which is an integer that indeces into position of clip.
Clips are not ordered.They can overlap.
example of
input: [s = 1, e = 3], [s = 3, e = 5], [s = 2, e = 6], [s = 7, e = 9], [s = 11, e = 13]
output: [s = 6, e = 7], [s = 9, e = 11]
'''
video_clips= [[2,6],[7,9],[1,3],[11,13],[3,5]]
'''
output = [[6,7],[9,11]]
'''
def find_gaps(video_clips):
video_clips.sort(key=lambda x: x[0])
prev_start, prev_end = video_clips[0] # initialised [1,3]
result = []
for i in range(1,len(video_clips)):
current_start, current_end = video_clips[i]
if prev_end < current_start: # if prev_end is less than current_start --> GAP
result.append((prev_end, current_start))
prev_start = current_start
prev_end = current_end
else:
prev_start = min(prev_start, current_start)
prev_end = max(prev_end, current_end)
return result
print(find_gaps(video_clips)) |
'''
employee_info
{
"id": "10"
"first_name":"Marie_inn"
"last_name":""
"email":""
"gender":""
"age":""
"salary":""
"job_title":""}
'''
import pandas as pd
from csv import DictReader
employee_info = []
with open("employee.csv", newline="") as f:
reader = DictReader()
for row in reader:
row["age"] = int(row["age"])
row("salary") = float(row["salary"])
employee_info.append(row)
'''Task1: Unique Number of Job Titles'''
columns = employee_info[0].keys()
employee_frame = pd.DataFrame.from_records(employee_info, columns=columns)
print(f"Number of Unique Job Titles: {employee_frame.job_title.value_counts().count()}")
'''
Use a Pivot Table to Determine the Salary Difference Depending on Gender
'''
#To determine the average pay difference between men and women with the same job title, we'll first need to determine which jobs have both men and women doing them:
job_title_unique_gender_count = employee_frame.groupby('job_title')['gender'].nunique()
job_titles_with_two_genders = job_title_unique_gender_count.where(job_title_unique_gender_count == 2).dropna().index
job_title_gender_frame = employee_frame[employee_frame.job_title.isin(job_titles_with_two_genders)]
'''The last bit of code we use creates a column for each gender in our table, and also adds a column to the table to hold the pay difference between female and male employees:
'''
gender_difference_table = pd.pivot_table(job_title_gender_frame, columns='gender', values=['salary'], index=['job_title'])
gender_difference_table[('salary', 'difference')] = gender_difference_table[('salary', 'Female')] - gender_difference_table[('salary', 'Male')]
print(gender_difference_table)
'''Task 3'''
employee_frame['age_range'] = pd.cut(employee_frame.age, [18, 41, 80], labels=['18 - 40', '41 - 80'])
employee_frame.age_range.cat.add_categories(['difference'], inplace=True)
'''Next, we need to determine while job titles have at least one employee from each of the age ranges:
'''
job_title_unique_age_range_count = employee_frame.groupby('job_title')['age_range'].nunique()
job_titles_with_two_age_ranges = job_title_unique_age_range_count.where(job_title_unique_age_range_count == 2).dropna().index
job_title_age_range_frame = employee_frame[employee_frame.job_title.isin(job_titles_with_two_age_ranges)]
'''Now that we have a new data frame, we're ready to create our pivot table and populate a new difference column:
'''
age_difference_table = pd.pivot_table(job_title_age_range_frame, columns='age_range', values=['salary'], index=['job_title'])
age_difference_table[('salary', 'difference')] = age_difference_table[('salary', '18 - 40')] - age_difference_table[('salary', '41 - 80')]
print(age_difference_table) |
"""Question1: Minimum Path in Unix"""
class Solution:
def simplifyPath(self, path: str) -> str:
if not str:
return str
s = []
for i in path.split('/'):
if i == '.' or not i:
continue
elif i == '..':
if s:
s.pop()
else:
s.append(i)
final = '/' + '/'.join(s)
return final
"""Time Complexity: O(n) and Space Complexity O(2n)""" |
'''
Method: Brute Force
Time Complexity: O(n^3)
Space Complexity: O(min(n,m))
'''
class Solution:
def allUnique(self, s, start, end):
set_list = {}
set_list = defaultdict(lambda: 0, set_list)
for i in range(start, end):
ch = s[i]
set_list[ch] += 1
if set_list[ch] > 1:
return False
return True
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
ans = 0
for i in range(n):
for j in range(i + 1, n + 1):
if self.allUnique(s, i, j):
ans = max(ans, j - i + 1)
return ans
'''
Method: Brute Force (OrderedDict)
Time Complexity: O(n^3)
Space Complexity: O(min(n,m))
'''
from collections import OrderedDict
def allUnique_OrderedDict(s):
x = ''.join(OrderedDict.fromkeys(s).keys())
if x == s:
return True
return False
def lengthOfLongestSubstring(s: str) -> int:
n = len(s)
ans = 0
for i in range(n):
for j in range(i + 1, n + 1):
if allUnique_OrderedDict(s[i:j]):
ans = max(ans, j - i)
return ans
'''
Method: Sliding Window
Time Complexity: O(2n)
Space Complexity: O(min(n,m))'''
from collections import defaultdict
def lengthOfLongestSubstring_SlidingWindow(s:str):
set_list = {}
set_list = defaultdict(lambda: 0, set_list)
left,right,result = 0,0,0
while (right < len(s)):
r = s[right]
set_list[r] += 1
while (set_list[r] > 1):
l = s[left]
set_list[l] -= 1
left += 1
result = max(result, right - left + 1)
right += 1
return result
'''
Method: Sliding Window Optimised
Time Complexity: O(n)'''
def lengthOfLongestSubstring_slidingWindow_Optimised(s: str) -> int:
set_list = {}
result, right = 0, 0
for idx, value in enumerate(s):
if value in set_list:
right = max(right, set_list[value] + 1)
result = max(result, idx - right +1)
set_list[value] = idx
return result
print(lengthOfLongestSubstring_slidingWindow_Optimised("abcabcbb"))
def lengthOfLongestSubstring_neetcode(s:str):
result = 0
left = 0
charSet = set()
for right in range(len(s)):
while s[right] in charSet:
charSet.remove(s[left])
left+=1
charSet.add(s[right])
result = max(result, right - left + 1)
return result
|
#!/usr/bin/env python
class NullDecl (object):
def __init__ (self, func):
print self.__class__.__name__, "__init__"
self.func = func
##for n in set(dir(func)) - set(dir(self)):
## setattr(self, n, getattr(func, n))
def __call__ (self, * args):
print self.__class__.__name__, "__call__"
return self.func (*args)
def __repr__(self):
print self.__class__.__name__, "__repr__"
return self.func
# The descriptor protocol is the mechanism for binding a thing to an instance.
# It consists of __get__, __set__ and __delete__, which are called when
# the thing is got, set or deleted from the instances dictionary.
# In this case when the thing is got from the instance we are binding
# the first argument of it's __call__ method to the instance, using partial.
# This is done automatically for member functions when the class is constructed,
# but for a synthetic member function like this we need to do it explicitly.
# - tolomea
def __get__(self, obj, objtype):
"""Support instance methods."""
import functools
return functools.partial(self.__call__, obj)
class NullDecl1(NullDecl):
pass
class NullDecl2(NullDecl):
pass
# You need to make the decorator into a descriptor -- either by ensuring
# its (meta)class has a __get__ method, or, way simpler, by using a decorator
# function instead of a decorator class (since functions are already descriptors).
# - Alex Martelli
def dec_check(f):
def deco(self):
print 'In deco'
f(self)
return deco
class MyCls:
def __init__ (self, vv):
self.v = vv
@NullDecl1
@NullDecl2
def decoratedMethod(self, * args):
print " v in decoratedMethod %d \n" % self.v
pass
@dec_check
def decoratedMethod2(self):
print " v in decoratedMethod %d \n" % self.v
pass
def pureMethod(self):
print " v in pureMethod %d \n" % self.v
pass
@NullDecl1
@NullDecl2
def decorated():
pass
def pure():
pass
# results in set(['func_closure', 'func_dict', '__get__', 'func_name',
# 'func_defaults', '__name__', 'func_code', 'func_doc', 'func_globals'])
print set(dir(pure)) - set(dir(decorated));
if __name__ == "__main__":
pure()
decorated()
print dir(pure)
print dir(decorated);
print "\n Ok 1...\n"
pure()
decorated()
print "\n Ok 2...\n"
mycls = MyCls(333)
mycls.pureMethod()
mycls.decoratedMethod()
mycls.decoratedMethod2()
|
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# Loading the dataset.
df=pd.read_csv("iris-species.csv")
# Adding a column in the Iris DataFrame to resemble the non-numeric 'Species' column as numeric using the 'map()' function.
# Creating the numeric target column 'Label' to 'iris_df' using the 'map()' function.
df["Label"]=df["Species"].map({"Iris-setosa":0,"Iris-virginica":1,"Iris-versicolor":2})
# Creating a model for Support Vector classification to classify the flower types into labels '0', '1', and '2'.
# Creating features and target DataFrames.
x=df[["SepalLengthCm","SepalWidthCm","PetalLengthCm","PetalWidthCm"]]
y=df["Label"]
# Splitting the data into training and testing sets.
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=42)
# Creating the SVC model and storing the accuracy score in a variable 'score'.
s=SVC(kernel="linear")
s.fit(x_train,y_train)
score=s.score(x_train,y_train)
@st.cache()
def prediction(sep_len,sep_wid,pet_len,pet_wid):
pred=s.predict([[sep_len,sep_wid,pet_len,pet_wid]])
var=pred[0]
if var==0:
return "iris-setosa"
elif var==1:
return "iris-virginica"
elif var==2:
return "iris-versicolor"
st.title("Iris Flower Species Prediciton App")
# Add 4 sliders and store the value returned by them in 4 separate variables.
sl1=st.slider("Sepal Length",0.0,10.0)
sl2=st.slider("Sepal Width",0.0,10.0)
sl3=st.slider("Petal Length",0.0,10.0)
sl4=st.slider("Petal Width",0.0,10.0)
# When 'Predict' button is pushed, the 'prediction()' function must be called
# and the value returned by it must be stored in a variable, say 'species_type'.
if st.button("Predict"):
pr=prediction(sl1,sl2,sl3,sl4)
st.write("Species predicted is",pr)
# Print the value of 'species_type' and 'score' variable using the 'st.write()' function.
st.write("Accuracy of this model is",score)
|
class Stack:
""" Stack: Class implementation """
def __init__(stack):
""" Initializes new stack """
stack.elements = []
def push(stack, elem):
""" Pushes 'elem' to stack 'stack' """
stack.elements.append(elem)
def pop(stack):
""" Removes head of stack 'stack' and returns it """
elem = stack.elements[-1]
del stack.elements[-1]
return elem
def empty(stack):
""" Checks whether stack 'stack' is empty """
return len(stack.elements) == 0
if __name__ == '__main__':
n = 5
print("stack:")
stack = Stack()
for i in range(n):
Stack.push(stack, i ** 3)
while not Stack.empty(stack):
elem = Stack.pop(stack)
print(elem)
print("otherstack:")
otherstack = Stack()
for i in range(n):
otherstack.push(1 / (i + 1))
while not otherstack.empty():
elem = otherstack.pop()
print(elem)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.