text
stringlengths 37
1.41M
|
---|
class Solution:
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
# up[i] is the length of a longest wiggle subsequence of {nums[0],...,nums[i]}, with a
# positive difference between its last two numbers.
up = [0 for i in range(len(nums))]
# down[i] is the length of a longest wiggle subsequence of {nums[0],...,nums[i]}, with a
# negative difference between its last two numbers.
down = [0 for i in range(len(nums))]
# At i=0, there is only one number and we can use it as a subsequence, i.e up[0]=down[0]=1
up[0], down[0] = 1, 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
'''
If nums[i] > nums[i-1], then we can use nums[i] to make a longer subsequence of type U
Proof: We consider a subsequence of type D in {0,...,i-1} (its length is down[i-1]).
Let N be the last number of this subsequence.
- If nums[i] > N, then we can add nums[i] to the subsequence and it gives us a longer
valid subsequence of type U.
- If nums[i] <= N, then:
(1) N cannot be nums[i-1], because nums[i-1] < nums[i] <= N i.e. nums[i-1] < N
(2) We can replace N with nums[i-1] (we still have a valid
subsequence of type D since N >= nums[i] > nums[i-1] i.e. N > nums[i-1]),
and then add nums[i] to the subsequence, and we have a longer subsequence of type U.
Therefore up[i] = down[i-1] + 1
There is no gain in using nums[i] to make a longer subsequence of type D.
Proof: Let N be the last number of a subsequence of type U
in {0,...,i-1}.
Assume we can use nums[i] to make a longer subsequence of type D. Then:
(1) N cannot be nums[i-1], otherwise we would not be able to use nums[i]
to make a longer subsequence of type D as nums[i] > nums[i-1]
(2) Necessarily nums[i] < N, and therefore nums[i-1] < N since nums[i-1] < nums[i].
But this means that we could have used nums[i-1] already to make a longer
subsequence of type D.
So even if we can use nums[i], there is no gain in using it, so we keep the old value of
down (down[i] = down[i-1])
'''
up[i] = down[i - 1] + 1
down[i] = down[i - 1]
elif nums[i] < nums[i - 1]:
# The reasoning is similar if nums[i] < nums[i-1]
down[i] = up[i - 1] + 1
up[i] = up[i - 1]
else:
# if nums[i] == nums[i-1], we cannot do anything more than what we did with nums[i-1]
# so we just keep the old values of up and down
up[i] = up[i - 1]
down[i] = down[i - 1]
return max(up[-1], down[-1])
|
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
firstNumbers = [nums[0] for nums in matrix]
# find row
low, high = 0, len(firstNumbers) - 1
while low <= high:
mid = (low + high) // 2
if firstNumbers[mid] == target:
return True
elif firstNumbers[mid] < target:
low = mid + 1
else:
high = mid - 1
# find element in previous found row
searchNumbers = matrix[high]
low, high = 0, len(searchNumbers) - 1
while low <= high:
mid = (low + high) // 2
if searchNumbers[mid] == target:
return True
elif searchNumbers[mid] < target:
low = mid + 1
else:
high = mid - 1
return False
|
class Solution:
def asteroidCollision(self, asteroids):
"""
:type asteroids: List[int]
:rtype: List[int]
"""
asteroidStack = [] # stores the survival asteroid
for asteroid in asteroids:
asteroidStack.append(asteroid)
while len(asteroidStack) >= 2 and asteroidStack[-2] > 0 and asteroidStack[-1] < 0:
rightAsteroid, leftAsteroid = asteroidStack.pop(), asteroidStack.pop()
if abs(leftAsteroid) < abs(rightAsteroid):
survivalAsteroid = [rightAsteroid]
elif abs(leftAsteroid) > abs(rightAsteroid):
survivalAsteroid = [leftAsteroid]
else:
survivalAsteroid = []
asteroidStack += survivalAsteroid
return asteroidStack
|
class Solution:
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
def findCircleNumHelper(node):
visitedNodes.add(node)
for neighborNode in range(len(M)):
if M[node][neighborNode] == 1:
if neighborNode in visitedNodes: continue
findCircleNumHelper(neighborNode)
return 1
circleNumber = 0
visitedNodes = set()
for node in range(len(M)):
if node in visitedNodes: continue
circleNumber += findCircleNumHelper(node)
return circleNumber
|
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None
dummyNode, curNode = RandomListNode(-1), head
nodeMapping = {None: None}
while curNode:
newNode = RandomListNode(curNode.label)
newNode.next, newNode.random = curNode.next, curNode.random
nodeMapping[curNode] = newNode
curNode = curNode.next
dummyNode.next, curNode = nodeMapping[head], head
while curNode:
nodeMapping[curNode].next, nodeMapping[curNode].random = nodeMapping[curNode.next], nodeMapping[curNode.random]
curNode = curNode.next
return dummyNode.next
|
"""Unittest for linkedlist."""
import unittest
import linkedlist
class LinkedListTest(unittest.TestCase):
def test_add(self):
ll = linkedlist.LinkedList()
for i in range(10):
ll.add(i)
self.assertEqual(len(ll), 10)
def test_pop(self):
ll = linkedlist.LinkedList()
original_len = 10
for i in range(original_len):
ll.add(i)
for i in range(5):
value = ll.pop()
self.assertEqual(value, ((original_len - 1) - i))
self.assertEqual(len(ll), 5)
def test_insert(self):
ll = linkedlist.LinkedList()
original_len = 10
for i in range(original_len):
ll.add(i)
ll.insert(3, 33)
self.assertEqual(len(ll), 11)
self.assertTrue(33 in ll)
def test_remove(self):
ll = linkedlist.LinkedList()
original_len = 10
for i in range(original_len):
ll.add(i)
ll.remove(3)
self.assertEqual(len(ll), 9)
self.assertFalse(2 in ll)
def test_find(self):
ll = linkedlist.LinkedList()
original_len = 10
for i in range(original_len):
ll.add(i)
self.assertEqual(ll.find(2), 2)
if __name__ == '__main__':
unittest.main()
|
"""Defines a binary search tree."""
class Node(object):
def __init__(self, value):
self._left = self._right = None
self.value = value
def add(self, value):
if value <= self.value:
if self._left is None:
self._left = Node(value)
else:
self._left.add(value)
else:
if self._right is None:
self._right = Node(value)
else:
self._right.add(value)
def __contains__(self, value):
if self.value == value:
return True
elif self.value < value:
if self._left is not None:
return value in self._left
else:
return False
else:
if self._right is not None:
return value in self._right
else:
return False
def traverse_inorder(self, callback_fn):
if self._left is not None:
self._left.traverse_inorder(callback_fn)
callback_fn(self.value)
if self._right is not None:
self._right.traverse_inorder(callback_fn)
def traverse_preorder(self, callback_fn):
callback_fn(self.value)
if self._left is not None:
self._left.traverse_preorder(callback_fn)
if self._right is not None:
self._right.traverse_preorder(callback_fn)
def traverse_postorder(self, callback_fn):
if self._left is not None:
self._left.traverse_postorder(callback_fn)
if self._right is not None:
self._right.traverse_postorder(callback_fn)
callback_fn(self.value)
def get_height(self):
if self._right is None or self._right is None:
return 1
elif self._right is not None:
return 1 + self._right.get_height()
elif self._left is not None:
return 1 + self._left.get_height()
else:
return 1 + max(self._left.get_height(), self._right.get_height())
@property
def is_balanced(self):
return abs(self._left.get_height() - self._right.get_height()) <= 1
def rebalance(self):
if self.is_balanced:
return
sorted_data = []
self.traverse_inorder(sorted_data.append)
return self._rebalance(sorted_data, 1, len(sorted_data) - 1)
def _rebalance(self, arr, left, right):
if left > right:
return
mid = (left + right) // 2
self = Node(arr[mid])
self._left = self._rebalance(arr, left, mid - 1)
self._right = self._rebalance(arr, mid + 1, right)
return self
|
import math
def SubarrayProduct(numbers, k):
subsets = []
for i in range(len(numbers)):
subsets.append([numbers[i]])
for j in range(i + 1, len(numbers)):
subset = subsets[-1]
curr_subset = subset + [numbers[j]]
subsets.append(curr_subset)
counter = 0
for subset in subsets:
if math.prod(subset) <= k:
counter += 1
print(subset)
return counter
if __name__ == '__main__':
print(SubarrayProduct([2, 3, 4], 6))
|
import sqlite3
conn = sqlite3.connect('customer.db')
c = conn.cursor() #creating a cursor
#creating a table
c.execute("""CREATE TABLE customers (
first_name text,
last_name text,
email text
)""")
#DATYPES (NULL,INTEGER,REAL,TEXT,BLOB)
conn.commit()
conn.close()
|
#!/usr/bin/env python
languages = ['python', 'java', 'C++', 'PHP']
for language in languages:
print language, "rocks!"
dict = {"name":"Jesse","location":"Denver","favorite site":"tutsplus"}
for key in dict:
print "His ", key, "is", dict[key]
print range(10)
for int in range(10):
print "int =", int
if int == 5:
break
print "done looping"
count = 0
while count < 10:
print count, "count is less than 10"
count +=1
for i in range(2):
print "this is before continue"
continue
print "this is after the continue statement"
for i in range(2):
pass
|
import sys
# https://stackoverflow.com/questions/5324647/how-to-merge-a-transparent-png-image-with-another-image-using-pil
image1 = '8fe92c97.jpg'
image2 = 'botgarden_watermark_520x520_trans_white.png'
from PIL import Image
if 'paste' in sys.argv:
background = Image.open(image1)
foreground = Image.open(image2)
# foreground.convert('RGBA')
background.paste(foreground, (0, 0), foreground)
#background.show()
background.save(filename='watermark.jpg')
print('save paste %s' % 'watermark.jpg')
sys.exit(0)
# https://stackoverflow.com/questions/32034160/creating-a-watermark-in-python
from wand.image import Image
with Image(filename=image1) as background:
with Image(filename=image2) as watermark:
background.watermark(image=watermark, transparency=0.60)
background.save(filename='watermark.jpg')
print(f'main image {image1}')
print(f'watermark image {image2}')
print(f'saved watermarked image as "watermarked.jpg"')
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None or l2 is None:
return l1 or l2
node1 = l1
node2 = l2
if l1.val <= l2.val:
head = l1
node1 = node1.next
else:
head = l2
node2 = node2.next
curr_node = head
while node1 and node2:
if node1.val <= node2.val:
curr_node.next = node1
node1 = node1.next
else:
curr_node.next = node2
node2 = node2.next
curr_node = curr_node.next
curr_node.next = node1 if node1 else node2
return head
|
# 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
def dfs(root, level, results=[]):
if not root:
return []
# recursive dfs
if len(results) < level + 1:
results.insert(0, [])
results[-(level + 1)].append(root.val)
if root.left:
dfs(root.left, level + 1, results)
if root.right:
dfs(root.right, level + 1, results)
res = []
dfs(root, 0, res)
return res
"""
Results:
Recursive DFS way
Runtime: 40 ms, faster than 30.78% of Python3 online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 14.6 MB, less than 7.31% of Python3 online submissions for Binary Tree Level Order Traversal II.
"""
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
head_copy = head
if head is None or head.next is None:
return head
prev_node = head
curr_node = head.next
next_node = curr_node.next
while next_node:
curr_node.next = prev_node
prev_node = curr_node
curr_node = next_node
next_node = next_node.next
curr_node.next = prev_node
head_copy.next = None
return curr_node
s = Solution()
node_1 = ListNode(1)
node_2 = ListNode(2)
node_3 = ListNode(3)
node_1.next = node_2
node_2.next = node_3
node = s.reverseList(node_1)
while node:
print(node.val)
node = node.next
|
# 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
# bfs + queue
if not root:
return []
my_queue = []
res = []
# initialize
my_queue.append(root)
while my_queue:
nodes = len(my_queue) # this level of nodes
tmp_res = []
for _ in range(nodes):
node = my_queue.pop(0)
tmp_res.append(node.val)
if node.left:
my_queue.append(node.left)
if node.right:
my_queue.append(node.right)
res.insert(0, tmp_res)
return res
"""
Results:
BFS + queue way
Runtime: 36 ms, faster than 59.13% of Python3 online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 14 MB, less than 84.72% of Python3 online submissions for Binary Tree Level Order Traversal II.
"""
|
# 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 sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
results = []
def dfs(root):
if not root:
return
if is_leaf(root.left):
results.append(root.left.val)
dfs(root.left)
dfs(root.right)
def is_leaf(root):
if not root:
return False
if not root.left and not root.right:
return True
return False
dfs(root)
return sum(results)
"""
Results
Runtime: 28 ms, faster than 91.31% of Python3 online submissions for Sum of Left Leaves.
Memory Usage: 14.5 MB, less than 30.36% of Python3 online submissions for Sum of Left Leaves.
"""
|
# 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 postorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
my_stack = []
results = []
visited = set()
# initialize
my_stack.append(root)
visited.add(root)
while my_stack:
curr_top = my_stack[-1]
if not curr_top.left and not curr_top.right:
my_stack.pop(-1)
results.append(curr_top.val)
else:
left_done, right_done = False, False
if curr_top.right and curr_top.right not in visited:
my_stack.append(curr_top.right)
visited.add(curr_top.right)
else:
right_done = True
if curr_top.left and curr_top.left not in visited:
my_stack.append(curr_top.left)
visited.add(curr_top.left)
else:
left_done = True
if left_done and right_done:
my_stack.pop(-1)
results.append(curr_top.val)
return results
"""
Results
自研解法
Runtime: 32 ms, faster than 53.05% of Python3 online submissions for Binary Tree Postorder Traversal.
Memory Usage: 14.1 MB, less than 9.12% of Python3 online submissions for Binary Tree Postorder Traversal.
"""
|
class Solution:
def sortedSquares(self, A: List[int]) -> List[int]:
if len(A) == 0 or len(A) == 1:
return [x ** 2 for x in A]
left = 0
right = len(A) - 1
tmp = []
while left <= right:
if A[left] ** 2 <= A[right] ** 2:
tmp.append(A[right] ** 2)
right -= 1
else:
tmp.append(A[left] ** 2)
left += 1
return reversed(tmp)
"""
Results:
Runtime: 316 ms, faster than 11.32% of Python3 online submissions for Squares of a Sorted Array.
Memory Usage: 15.4 MB, less than 5.95% of Python3 online submissions for Squares of a Sorted Array.
"""
|
# Actually same with solution_1, but it's more concise
# 实际上和solution_1很相似,只是更简洁
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
# save next node first
next_node = curr.next
# then change the direction/reverse
curr.next = prev
prev = curr
curr = next_node
return prev
|
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
results = []
length = len(nums)
def back_track(tmp_result):
if len(tmp_result) == length:
results.append(tmp_result[:])
return
for num in nums:
if num in tmp_result:
continue
tmp_result.append(num)
back_track(tmp_result)
tmp_result.pop(-1)
back_track([])
return results
"""
Results:
Runtime: 36 ms, faster than 89.51% of Python3 online submissions for Permutations.
Memory Usage: 14.4 MB, less than 5.05% of Python3 online submissions for Permutations.
"""
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# 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 sortedListToBST(self, head: ListNode) -> TreeNode:
def find_mid_node(head):
if not head or not head.next:
return head
slow = head
fast = head
prev = head
while fast.next and fast.next.next:
fast = fast.next.next
prev = slow
slow = slow.next
return prev
if not head:
return None
if not head.next:
return TreeNode(head.val)
prev_node = find_mid_node(head)
# if not prev_node:
# return None
mid_node = prev_node.next
# if not mid_node:
# return None
root_node = TreeNode(mid_node.val)
r_head = mid_node.next
prev_node.next = None
l_root = self.sortedListToBST(head)
r_root = self.sortedListToBST(r_head)
root_node.left = l_root
root_node.right = r_root
return root_node
"""
Results:
Runtime: 164 ms, faster than 30.50% of Python3 online submissions for Convert Sorted List to Binary Search Tree.
Memory Usage: 17.4 MB, less than 86.25% of Python3 online submissions for Convert Sorted List to Binary Search Tree.
"""
|
# using two pointers
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast_p = slow_p = head
while fast_p and fast_p.next:
slow_p = slow_p.next # move 1 step
fast_p = fast_p.next.next # move 2 steps
if slow_p == fast_p:
return True
return False
|
# 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
def in_order(root):
if not root:
return []
lefts = in_order(root.left)
rights = in_order(root.right)
return lefts + [root.val] + rights
root1_in_order = in_order(root1)
root2_in_order = in_order(root2)
if not root1_in_order or not root2_in_order:
return root1_in_order or root2_in_order
p1, p2 = 0, 0
results = []
while p1 < len(root1_in_order) and p2 < len(root2_in_order):
if root1_in_order[p1] <= root2_in_order[p2]:
results.append(root1_in_order[p1])
p1 += 1
else:
results.append(root2_in_order[p2])
p2 += 1
if p1 < len(root1_in_order):
remaining = root1_in_order[p1:]
else:
remaining = root2_in_order[p2:]
results += remaining
return results
"""
Results:
Runtime: 520 ms, faster than 28.69% of Python3 online submissions for All Elements in Two Binary Search Trees.
Memory Usage: 22.7 MB, less than 5.00% of Python3 online submissions for All Elements in Two Binary Search Trees.
"""
|
# 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 constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:
if not pre:
return None
root_val = pre[0]
root = TreeNode(root_val)
if len(pre) == 1:
return TreeNode(root_val)
left_root_val = pre[1]
post_idx = post.index(left_root_val)
left_len = post_idx + 1
left_pre = pre[1:1 + left_len]
right_pre = pre[1 + left_len:]
left_post = post[:left_len]
right_post = post[left_len:-1]
root.left = self.constructFromPrePost(left_pre, left_post)
root.right = self.constructFromPrePost(right_pre, right_post)
return root
"""
Results
Runtime: 52 ms, faster than 81.41% of Python3 online submissions for Construct Binary Tree from Preorder and Postorder Traversal.
Memory Usage: 14.2 MB, less than 5.19% of Python3 online submissions for Construct Binary Tree from Preorder and Postorder Traversal.
"""
|
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
def bfs(start_node):
visited = set()
my_queue = [start_node]
visited.add(start_node)
results = []
while my_queue:
curr_top = my_queue.pop(0)
results.append(curr_top)
for neighbor in rooms[curr_top]:
if neighbor not in visited:
visited.add(neighbor)
my_queue.append(neighbor)
return results
results = bfs(0)
return len(results) == len(rooms)
"""
Results:
BFS
Runtime: 68 ms, faster than 79.44% of Python3 online submissions for Keys and Rooms.
Memory Usage: 14.2 MB, less than 46.62% of Python3 online submissions for Keys and Rooms.
"""
|
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
"""
Results:
Runtime: 60 ms, faster than 36.37% of Python3 online submissions for Intersection of Two Arrays.
Memory Usage: 13.9 MB, less than 78.12% of Python3 online submissions for Intersection of Two Arrays.
"""
|
# 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 zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
def bfs(root):
queue = []
reverse = False
results = []
queue.append(root)
while queue:
level_num = len(queue)
tmp_list = []
for _ in range(level_num):
curr_node = queue.pop(0)
tmp_list.append(curr_node.val)
if curr_node.left:
queue.append(curr_node.left)
if curr_node.right:
queue.append(curr_node.right)
if reverse:
tmp_list.reverse()
reverse = not reverse
results.append(tmp_list)
return results
if not root:
return []
results = bfs(root)
return results
"""
Results:
BFS
Runtime: 48 ms, faster than 29.71% of Python3 online submissions for Binary Tree Zigzag Level Order Traversal.
Memory Usage: 14.1 MB, less than 27.60% of Python3 online submissions for Binary Tree Zigzag Level Order Traversal.
"""
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# Recursive DFS
if not root:
return 0
max_depth = 1
def dfs(root, depth):
nonlocal max_depth
if depth > max_depth:
max_depth = depth
if root.left:
dfs(root.left, depth + 1)
if root.right:
dfs(root.right, depth + 1)
dfs(root, 1)
return max_depth
"""
Results:
Recursive DFS
Runtime: 48 ms, faster than 26.68% of Python3 online submissions for Maximum Depth of Binary Tree.
Memory Usage: 15.9 MB, less than 10.35% of Python3 online submissions for Maximum Depth of Binary Tree.
"""
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if not head:
return []
sub_result = self.reversePrint(head.next)
sub_result.append(head.val)
return sub_result
|
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
my_stack = []
my_dict = {}
for num in nums2:
while my_stack and my_stack[-1] < num:
top_num = my_stack.pop(-1)
my_dict[top_num] = num
my_stack.append(num)
for num in my_stack:
my_dict[num] = -1
my_list = [my_dict[num] for num in nums1]
return my_list
"""
Results:
Runtime: 48 ms, faster than 65.35% of Python3 online submissions for Next Greater Element I.
Memory Usage: 13.2 MB, less than 77.78% of Python3 online submissions for Next Greater Element I.
"""
|
#!/usr/bin/env python
# coding: utf-8
# # Exploratory Data Analysis: SuperStore Dataset
# # Anika Bizla
# # Task 3
# In[51]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# ## Reading the Dataset
# In[52]:
df=pd.read_csv("/Users/anikabizla/Downloads/SampleSuperstore.csv")
df.head()
# In[53]:
#checking the data types
df.dtypes
# In[54]:
#checking the shape of dataset
df.shape
# In[55]:
df.describe()
# In[56]:
df.describe(include="all")
# # Univariate Analysis
# In[57]:
#Analysing the segment of people buying from the supermarket.
df['Segment'].value_counts()
# In[58]:
df['Segment'].value_counts()/len(df['Segment'])*100
# In[59]:
S=(df['Segment'].value_counts()/len(df['Segment'])*100).plot(kind='bar',color='r')
# #### Following conclusions can be made from the graph:
# #### 1. 50% of people belongs to consumer class.
# #### 2.20-30% people belongs to Corporate and Home Offices.
# In[60]:
#Analysing Ship Mode for the SuperMart
df['Ship Mode'].value_counts()
# In[61]:
M=(df['Ship Mode'].value_counts())/len(df['Ship Mode'])*100
M
# In[62]:
M.plot(kind="bar")
# In[63]:
#Analysing Category of Items in the SuperMart
df['Category'].value_counts()
# In[64]:
C=(df['Category'].value_counts())/len(df['Category'])*100
C.plot(kind="bar",color="g")
# In[65]:
#Analysing the Sub-Category of items in the SuperMart
((df['Sub-Category'].value_counts())/len(df['Sub-Category'])*100).plot(kind='bar')
# # Bivariate Analysis
# In[66]:
fig,ax=plt.subplots()
colors={'Consumer':'red','Corporate':'blue','Home Office':'green'}
ax.scatter(df['Sales'],df['Profit'],c=df['Segment'].apply(lambda x:colors[x]))
plt.show()
# ##### We can conclude that there is more profit in consumer segment
# In[67]:
df.pivot_table(values='Sales',index='Segment',columns='Discount',aggfunc='median')
# In[68]:
df.pivot_table(values='Profit',index='Segment',columns='Discount',aggfunc='median')
# #### We can conclude that the SuperStore was going on loss for Discount more than 30% and for items having discount b/w 0 to 20% the sales of superstore was average
# In[69]:
temp_df=df.loc[(df['Segment']=='Consumer')&(df['Discount']==0.1)]
temp_df['Profit'].plot.hist(bins=50)
# In[70]:
temp_df=df.loc[(df['Segment']=='Consumer')&(df['Discount']==0.2)]
temp_df['Profit'].plot.hist(bins=50)
# In[71]:
temp_df=df.loc[(df['Segment']=='Corporate')&(df['Discount']==0.8)]
temp_df['Profit'].plot.hist(bins=50)
# In[72]:
temp_df=df.loc[(df['Segment']=='Consumer')&(df['Discount']==0.8)]
temp_df['Profit'].plot.hist(bins=50)
# #### For all the segments when superstore is offering discount less than 40% its going on Profit as depicted by above graphs and if discount>50% like we have taken discount=80% ,superstore is going on loss
# In[73]:
temp_df=df.loc[(df['Category']=='Furniture')&(df['Discount']==0.2)]
temp_df['Profit'].plot.hist(bins=50)
# In[74]:
temp_df=df.loc[(df['Category']=='Technology')&(df['Discount']<=0.3)]
temp_df['Profit'].plot.hist(bins=50)
# In[75]:
temp_df=df.loc[(df['Category']=='Technology')&(df['Discount']>=0.3)]
temp_df['Profit'].plot.hist(bins=50)
# In[76]:
temp_df=df.loc[(df['Category']=='Office Supplies')&(df['Discount']<=0.3)]
temp_df['Profit'].plot.hist(bins=50)
# In[77]:
temp_df=df.loc[(df['Category']=='Office Supplies')&(df['Discount']>=0.3)]
temp_df['Profit'].plot.hist(bins=50)
# #### We conclude that when Discount<=30% in items, Sales was going into Profit and when Discount>=30% in items, SuperStore is experiencing a huge loss
#
# In[78]:
temp=df.groupby(['Segment','Discount']).Profit.median()
temp.plot(kind='bar',stacked=True)
# #### This shows the Scenario of Profit of all the segments when following Discount was offered by SuperStore
# ## ThankYou!
|
#Uses python3
import sys, functools
def largest_number(a):
res = ""
a = sorted(a, key=functools.cmp_to_key(compare))
for x in a:
res += x
return res
def compare(x, y):
xy = int(str(x) + str(y)); yx = int(str(y) + str(x))
if xy > yx:
return -1
elif yx > xy:
return 1
else:
return 0
if __name__ == '__main__':
input = sys.stdin.read()
data = input.split()
a = data[1:]
print(largest_number(a))
|
array = [3,7,8,1,5,9,6,10,2,4]
def quick_sort(arr):
print("초기 입력값 : " , arr)
if len(arr) < 2:
return arr
pivot = arr[len(arr) // 2]
left_arr, equal_arr, right_arr = [], [], []
for i in arr:
if i < pivot :
left_arr.append(i)
elif i == pivot:
equal_arr.append(i)
else :
right_arr.append(i)
print("left_arr : ", left_arr)
print("equal_arr : ", equal_arr)
print("right_arr : ", right_arr)
return quick_sort(left_arr) + quick_sort(equal_arr) + quick_sort(right_arr)
a = quick_sort(array)
print(a)
|
class Animal():
def __init__(self):
self.__name = "晨波"
def getname(self):
return self.__name
def eat(self):
print('吃吃吃')
def sleep(self):
print("睡睡睡")
def __money(self):
print('私有财产')
def askmoney(self):
self.__money()
class Dog(Animal):
pass
class Cat(Animal):
pass
taidi = Dog()
taidi.eat()
taidi.sleep()
taidi.askmoney()
print(taidi.getname())
mao = Cat()
mao.eat()
mao.sleep()
mao.askmoney()
print(mao.getname())
|
from threading import Thread
import time
import threading
num = 100
def work1():
global g_num
for i in range(100):
num += 1
print(num)
def work2():
global g_num
for i in range(100):
num += 1
print("%st %d"%num)
print("---线程创建之前g_num is %d---"%num)
t1 = Thread(target=work1)
t1.start()
time.sleep(1)
t2 = Thread(target=work2)
t2.start()
|
from queue import PriorityQueue
import math
class Node:
def __init__(self,intersection_num):
self.intersection_num = intersection_num
self.cumulative_g = None
self.f = None
self.parent = None
self.children = []
self.index = None
def get_intersection_number(self):
return self.intersection_num
def add_child(self,child):
self.children.append(child)
def get_children(self):
return self.children
def get_parent(self):
return self.parent
def set_parent(self,node):
self.parent = node
def set_cumulative_g(self,g):
self.cumulative_g = g
def get_cumulative_g(self):
return self.cumulative_g
def set_f(self,f):
self.f = f
def get_f(self):
return self.f
def set_index(self,index):
self.index = index
def get_index(self):
return self.index
class Tree:
def __init__(self):
self.root = None
def set_root(self,node):
self.root = node
def get_root(self):
return self.root
# Helper function to calculate straight line distance between two intersections
def cal_displacement(M, int1, int2):
return math.sqrt((M.intersections[int1][0]-M.intersections[int2][0])**2 + \
(M.intersections[int1][1]-M.intersections[int2][1])**2)
# Helper function to add children node
def add_children(M,node):
for intersection in M.roads[node.intersection_num]:
node.add_child(Node(intersection))
# Helper function to generate a list from the root to specified node
# Only use at the end to generate a solution list
def get_path_list(node):
path_list = [None for _ in range(node.get_index()+1)]
while node is not None:
path_list[node.get_index()] = node.get_intersection_number()
node = node.get_parent()
return path_list
# Main function for A* Algorithm
def shortest_path(M, start, goal):
# Create start node and populate with its chidren, g, and f
start_node = Node(start)
add_children(M,start_node)
start_node.set_cumulative_g(0)
start_node.set_f(cal_displacement(M, start, goal))
start_node.set_index(0)
# Setup tree as data structure to explore paths
tree = Tree()
tree.set_root(start_node)
# Setup frontier priority queue to keep track of node
# frontier that has the lowest f = g + h
# Add the start node to the queue
frontier_queue = PriorityQueue()
frontier_queue.put((start_node.get_f(),start_node))
# Setup dictionary to keep track of nodes that we have
# already visited with the lowest f = g + h
# Populate with the start point
visited_dic = {}
visited_dic[start_node.get_intersection_number()] = start_node.get_f()
# Main loop for A* algorithm
while frontier_queue.qsize() > 0:
# Pop the node that has the lowest estimated f
_, parent_node = frontier_queue.get()
# Base case when the solution is found
# Goal has the lowest estimated f
if parent_node.get_intersection_number() == goal:
return get_path_list(parent_node)
# Expand all children nodes and set cumulative g and f value
for child_node in parent_node.get_children():
# Set parent and add children for each child node
child_node.set_parent(parent_node)
add_children(M,child_node)
# Set g value for each child node
# Child node g value = cumulative parent g +
# straigh line distance from parent to child
child_node.set_cumulative_g(parent_node.get_cumulative_g() + \
cal_displacement(M, parent_node.get_intersection_number(), \
child_node.get_intersection_number() \
))
# Set f value for each child node
# Child node f value = child node g value+
# straigh line distance from child to goal
child_node.set_f(child_node.get_cumulative_g() + \
cal_displacement(M, child_node.get_intersection_number(), \
goal \
))
# Set index value for each child node (for creating list at the end)
child_node.set_index(parent_node.get_index() + 1)
# Update visited dictionary and add child to the frontier queue only
# when the node is never visited OR the node has a lower estimated
# f than previously visited
if child_node.get_intersection_number() not in visited_dic:
visited_dic[child_node.get_intersection_number()] = child_node.get_f()
frontier_queue.put((child_node.get_f(),child_node))
elif child_node.get_f() < visited_dic[child_node.get_intersection_number()]:
visited_dic[child_node.get_intersection_number()] = child_node.get_f()
frontier_queue.put((child_node.get_f(),child_node))
else:
pass
# If the queue is empty and the path has never been found, return None
return None
|
#! /usr/bin/env python2
"""
generate square sequence number
simply checking isPrime
"""
class square():
def __init__(self):
self.s = 1
self.l = 2
self.i = 0
def next(self):
"""
>>> sq= square()
>>> [sq.next() for i in range(12)]
[3, 5, 7, 9, 13, 17, 21, 25, 31, 37, 43, 49]
"""
if self.i == 4:
self.i = 0
self.l += 2
self.i += 1
self.s += self.l
return self.s
def length(self):
return self.l + 1
if __name__ == "__main__":
from common import mymath
# start with cnt as 1, as first number 1
primecnt, cnt = 0, 1
sq = square()
while 1:
num = sq.next()
cnt += 1
if mymath.isPrime(num):
primecnt += 1
if primecnt * 10 < cnt:
# print num, primecnt, cnt, primecnt / (cnt + 0.), sq.length()
print sq.length()
break
|
def sqrt2expan():
a, b = 3, 2
while 1:
yield (a, b)
a, b = a + 2 * b, a + b
def cntDigit(n):
cnt = 0
while n > 0:
cnt += 1
n /= 10
return cnt
sqrt2 = sqrt2expan()
cnt = 0
for i in range(10**3):
a, b = sqrt2.next()
if cntDigit(a) > cntDigit(b):
cnt += 1
print cnt
|
import math
def isPrime(n):
if n==1 or n==2:
return True
i=2
thres = math.sqrt(n)
while i<=thres:
if n%i==0:
return False
i += 1
return True
def isCons(lst,i,n):
for j in range(n-1):
if(lst[i+j]+1==lst[i+j+1]):
pass
else:
return False
return True
import operator
def prod(factors):
return reduce(operator.mul,factors,1)
def isPytha(a,b,c):
if a * a + b * b == c * c:
return True
return False
#(a, b, c) = (1, 2, 1000-1-2)
def next(a,b,c):
if b+1<=c-1:
return (a,b+1,c-1)
else:
if a+2<1000-a-a-3:
return (a+1,a+2,1000-a-a-3)
else:
raise Exception("no next")
lst = []
while 1:
try:
line = raw_input()
except:
break
line = [int(i) for i in line.split()]
lst.append(line)
print lst
|
def isPrime(n):
r = 2
while 1:
if r * r > n:
return True
if n % r == 0:
return False
r += 1
def oldSln():
print sum((i for i in xrange(2, 2000 * 1000) if isPrime(i)))
def sieve(m):
for i in xrange(1, m):
|
N = 10**18
from math import sqrt
def isTarget(n):
n = n / 100
rn = 9
while n:
r = n % 10
if r != rn:
return False
rn -= 1
n = n / 100
if rn == 0:
return True
else:
return False
for i in xrange(int(sqrt(N)) / 10 * 10, int(sqrt(N * 2)), 10):
t = (i / 10) % 10
if t == 3 or t == 7:
v = i ** 2
print i,v
if isTarget(v):
print i
break
|
"""
Defines the Organism class.
"""
from curdl import CURDL_code
from resources import ResourcesStock
from cells.cell import CentralCell
from cells.cell_types import _cell_types
class Organism:
"""
An organism is a set of cells organised in a 2D grid by its CURDL code, and capable of
gathering and spending resources.
"""
def __init__(self, env, curdl_code=None):
"""
-- env: simulation Environment object
-- curdl_code: Defines the CURDL code of the organism. Defaults to a single central unit.
"""
self.curdl_code = CURDL_code(['', '', '', ''])
if curdl_code is not None:
self.curdl_code = curdl_code
if not self.curdl_code.check_validity():
print("ERROR: invalid code: ", self.curdl_code)
exit(-1)
# Declare the Cells() objects
self.cells = self.build_cells()
self.stock = ResourcesStock()
self.env = env
self.age = 0
def build_cells(self):
"""
Builds the cells list from the curdl code.
"""
# For each cell code in the CURDL code, create the corresponding Cell object
return [CentralCell(self)] +\
[_cell_types[cell_code](self) for cell_code in self.curdl_code if cell_code != '']
def function(self):
"""
Updates the organism by activating all of its cells sequentially.
Returns True iff the organism survives.
-- env: simulation Environment object
"""
# Resets all temporary resources to zero
self.stock.clear()
self.age += 1
# Update all cells
dead_cells = []
for cell in self.cells:
if cell.update():
# cell.update() == True means the cell has died of age
dead_cells.append(cell)
# Remove all dead cells
for cell in dead_cells:
self.cells.remove(cell)
# Activate all cells
for cell in self.cells:
cell.function()
# Checks if some resources are missing. If so, the organism loses its last cell
if self.cells and len(self.missing_resources()) > 0:
del self.cells[-1]
return self.cells != []
def missing_resources(self):
"""
Returns the list of resources that the organism is missing
"""
missing = []
for resource, amount in self.stock.get_resources().items():
if amount < 0:
missing.append(resource)
return missing
def add_resource(self, resource_name, amount):
"""
Adds a resource to the organism.
--resource_name: codename of the resource such as 'O2' for dioxygen
--amount: Amount of the said resource to add to the organism's stock. Can be negative,
but in this case prefer to use remove_resource for semantic.
Returns the amount of the said resource AFTER it was added.
"""
return self.stock.add(resource_name, amount)
def remove_resource(self, resource_name, amount):
"""
Removes a resource from the organism's stock.
Returns the amount of the said resource AFTER it was removed.
"""
return self.stock.remove(resource_name, amount)
def number_of_cells(self):
"""
Returns the amount of cells of the organism, central cell included.
"""
return 1 + self.curdl_code.number_of_cells()
def __repr__(self):
return str(self.curdl_code)
|
'''
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together.
Twelve is written as, XII, which is simply X + II.
The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right.
However, the numeral for four is not IIII.
Instead, the number four is written as IV.
Because the one is before the five we subtract it making four.
The same principle applies to the number nine, which is written as IX.
There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: 3
Output: "III"
Example 2:
Input: 4
Output: "IV"
Example 3:
Input: 9
Output: "IX"
Example 4:
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
'''
class Solution:
def intToRoman(self, num: int) -> str:
if not (num >= 1 and num <= 3999): return 'Exceed Range'
# rom_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# rom_dict2 = {1000: 'M', 900 : 'CM', 500: 'D', 400: 'CD', 100: 'C',
# 90: 'XC', 50: 'L', 40: 'XL', 10: 'X',
# 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
div_list = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
rom_list = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
ans = ''
int_ = out = 0
for i in range(len(div_list)):
div = div_list[i]
int_,out = divmod(num, div)
if int_ == 0: continue
ans = ans + int_ * rom_list[i]
num = out
return ans
num = 1983
ans = Solution().intToRoman(num)
print(ans)
|
'''
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element. ==> * wildcard 萬用字元
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
'''
# Without a Kleene star *, our solution would look like this:
# 遞迴 Recursion
def match_(text, pattern):
# if pattern: return text
if not pattern: return not text # when pattern & text are '' empty strings ==> if True: return True
A = bool(text) # bool(text) = True, else = False when text = '' empty string
B = {text[0], '.'} # set{}
C = pattern[0] # str
D = C in B # bool
first_match = A and D
return first_match and match_(text[1:], pattern[1:])
# return first_match STOPS when first_match is False
# Without a Kleene star *, our solution would look like this:
# 簡潔厲害寫法
def match(text, pattern):
if not pattern: return not text
'''
等於: if not bool(pattern): return not bool(text)
等於: if bool(pattern) == False: return not bool(text)
# if pattern = empty string, return not bool(text)
# if pattern = empty string AND text = empty string, return True
# 檢查如果pattern是否為空字串,text也是空字串,則兩者match回傳True
# 如果如果pattern不是空字串,這行程式碼就會被跳過去
'''
first_match = bool(text) and pattern[0] in {text[0], '.'}
return first_match and match(text[1:], pattern[1:])
t = 'lennox'
p = 'le..ox'
# print(match_(t,p))
# https://leetcode.com/articles/regular-expression-matching/
class Solution:
def isMatch(self, text: str, pattern: str) -> bool:
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return (self.isMatch(text, pattern[2:]) or
first_match and
self.isMatch(text[1:], pattern))
# isMatch(text[1:], pattern) *重複一次前個字母後,是否相等於text[1]
# 運算時,先 and 後 or
# 對於, 1 or 5 and 4:先算5 and 4, 5為真,值為4.再算1 or 4, 1為真, 值為1
# 對於, (1 or 5) and 4:先算1 or 5, 1為真,值為1.再算1 and 4, 1為真, 值為4
else:
return first_match and self.isMatch(text[1:], pattern[1:])
S = Solution().isMatch
text = 'nnnnnn'
pattern = 'n*n'
print(S(text,pattern))
|
'''
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
'''
# class Solution:
# def longestPalindrome(self, s: str) -> str:
# n = len(s)
# new_s = ''
# for i in range(n):
# new_s = new_s + s[i] + ' '
# new_s = new_s[:2*n-1]
#
# return new_s
#
# s = "cbbd"
# S = Solution()
# ans = S.longestPalindrome(s)
# print(ans)
# print(len(ans))
# class Solution:
# def longestPalindrome(self, s: str) -> str:
# sLen = len(s)
# dict = {} # {i:pLen}
#
# if sLen > 1000:
# print('Should contain input string length within 1000.')
# else:
# for i in range(sLen): # set i as Palindrome central index
# right_Len = sLen - i
# roof = min(i+1, right_Len)
# for j in range(roof):
# try:
# if s[i-j] == s[i+1+j]: # 偶數迴文
# pLen = 2 + 2*j
# dict[i] = pLen
# else:
# break
# except:
# break
#
# try:
# for k in range(1, roof):
# if s[i-k] == s[i+k]: # 基數迴文
# pLen = 2*k +1
# dict[i] = pLen
# else:
# break
# except:
# dict[0] = 1
#
# pLen_list = list(dict.values())
# pLen_max = max(pLen_list)
# idx = pLen_list.index(pLen_max)
# if pLen_max % 2 == 0:
# start = idx - pLen_max/2 + 1
# result_str = s[start : start + pLen_max]
# elif pLen_max % 2 == 1:
# start = idx - pLen_max//2
# result_str = s[start: start + pLen_max]
#
# return result_str
#
# s = "cbbd"
# S = Solution()
# ans = S.longestPalindrome(s)
# print(ans)
##########
# 以下正解
##########
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
list_ = [1]*len(s)
for i in range(len(s)):
count1 = count2 = 1
# 偶數迴文
if i+1<len(s) and s[i] == s[i+1]:
mid = 1 # 確認下一步是否也迴文的進位量
count1 = 2 # 目前最大回文長度
# while條件式:確認兩個字母是否相同&確認兩個字母都沒有超過range
while i-mid>=0 and i+1+mid<len(s) and s[i-mid] == s[i+1+mid]:
count1 += 2
mid += 1
# 基數迴文
if i-1>=0 and i+1<len(s) and s[i-1] == s[i+1]:
mid = 1 # 確認下一步是否也迴文的進位量
count2 = 1 # 目前最大回文長度
# while條件式:確認兩個字母是否相同&確認兩個字母都沒有超過range
while i-mid>=0 and i+mid<len(s) and s[i-mid] == s[i+mid]:
count2 += 2
mid += 1
# 第i個idx中最長的迴文,記錄list到裡面
list_[i] = max(count1,count2)
max_ = index = 0
# 找出list中的max以及他的index
for j in range(len(list_)):
if max_ < list_[j]:
max_ = list_[j]
index = j
if max_ % 2 == 0:
# 回傳偶數迴文
return s[index-max_//2+1:index+1+max_//2]
else:
# 回傳基數迴文
return s[index-(max_+1)//2+1:index+(max_+1)//2]
s = "cbbd"
S = Solution()
ans = S.longestPalindrome(s)
print(ans)
|
from tkinter import *
a = 0
b = 0
def chageText(num):
lab["text"] = lab["text"] + num
window = Tk()
window.title("cool")
window.geometry("400x350+100+50")
window.config(bg="lightgreen")
window.rowconfigure(1,weight = 1)
window.rowconfigure(2,weight = 1)
window.rowconfigure(3,weight = 1)
window.rowconfigure(4,weight = 1)
window.columnconfigure(0,weight =1)
window.columnconfigure(1,weight =1)
window.columnconfigure(2,weight =1)
lab = Label(window, text='0' ,justify=RIGHT, anchor=E, font=("Monaco", 26, "bold"), bg="LIGHTblue")
lab.grid(row =0 ,column=0, columnspan=3 ,sticky=EW)
btn1 = Button(window, text="1", font=("Monaco", 30, "bold"),command=lambda:chageText('1'))
btn1.grid(row=1, column=0 , sticky=NSEW)
btn2 = Button(window, text="2", font=("Monaco", 30, "bold"),command=lambda:chageText('2'))
btn2.grid(row=1, column=1 , sticky=NSEW)
btn3 = Button(window, text="3",font=("Monaco", 30, "bold"),command=lambda:chageText('3'))
btn3.grid(row=1, column=2 , sticky=NSEW)
btn4 = Button(window, text="7", font=("Monaco", 30, "bold"),command=lambda:chageText('4'))
btn4.grid(row=2, column=0 , sticky=NSEW)
btn5 = Button(window, text="8", font=("Monaco", 30, "bold"),command=lambda:chageText('5'))
btn5.grid(row=2, column=1 , sticky=NSEW)
btn6 = Button(window, text="9",font=("Monaco", 30, "bold"),command=lambda:chageText('6'))
btn6.grid(row=2, column=2 , sticky=NSEW)
btn7 = Button(window, text="7", font=("Monaco", 30, "bold"),command=lambda:chageText('7'))
btn7.grid(row=3, column=0 , sticky=NSEW)
btn8 = Button(window, text="8", font=("Monaco", 30, "bold"),command=lambda:chageText('8'))
btn8.grid(row=3, column=1 , sticky=NSEW)
btn9 = Button(window, text="9",font=("Monaco", 30, "bold"),command=lambda:chageText('9'))
btn9.grid(row=3, column=2 , sticky=NSEW)
btn10 = Button(window, text="0",font=("Monaco", 30, "bold"),command=lambda:chageText('0'))
btn10.grid(row=4, column=0 , sticky=NSEW)
btn11 = Button(window, text="+",font=("Monaco", 30, "bold"),command=lambda:chageText('+'))
btn11.grid(row=4, column=1 , sticky=NSEW)
btn12 = Button(window, text="-",font=("Monaco", 30, "bold"),command=lambda:chageText('-'))
btn12.grid(row=4, column=2 , sticky=NSEW)
btn13 = Button(window, text="=",font=("Monaco", 30, "bold"),command=lambda:chageText('='))
btn13.grid(row=5, column=0 , sticky=NSEW)
btn14 = Button(window, text="*",font=("Monaco", 30, "bold"),command=lambda:chageText('*'))
btn14.grid(row=5, column=1 , sticky=NSEW)
btn15 = Button(window, text="/",font=("Monaco", 30, "bold"),command=lambda:chageText('/'))
btn15.grid(row=5, column=2 , sticky=NSEW)
window.mainloop()
|
# the symbol of element
def make_sentence_as_list_of_elemnts(text: str):
return {i: word[0] if i+1 in [1, 5, 6, 7, 8, 9, 15, 16, 19] else word[:2]
for i, word in enumerate(text.strip('.').split(' '))}
if __name__ == '__main__':
text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. " \
"Arthur King Can."
print(make_sentence_as_list_of_elemnts(text))
|
# Make an if statement to go to the end of the game.
x = input("")
if x == "a":
Game()
else:
print("e")
class Game:
def __init__(self):
# End Frame
self.end_box = Toplevel()
self.end_frame = Frame(self.end_box)
self.end_frame.grid(row=0)
# Heading row 0
self.end_heading = Label(self.end_frame, text="Thanks for playing!", font="Calibri 20 bold")
self.end_heading.grid(row=0)
|
"""
Performs hybrid filtering based upon a list of movies supplied
by the app user.
Parameters
----------
movie_list : list (str)
Favorite movies chosen by the app user.
top_n : type
Number of top recommendations to return to the user.
Returns
-------
list (str)
Titles of the top-n movie recommendations to the user.
"""
import streamlit as st
#Importing the required libraries
import pandas as pd
import numpy as np
import random
import re
from surprise import Reader, Dataset, SVD
from sklearn.metrics.pairwise import cosine_similarity
#importing the dataset
movies = pd.read_csv('~/unsupervised_data/unsupervised_movie_data/movies.csv', sep = ',',delimiter=',')
ratings = pd.read_csv('~/unsupervised_data/unsupervised_movie_data/train.csv')
movies = movies[:20000]
#movies = movies.reset_index(drop=True)
ratings = ratings.sample(frac=0.05)
ratings = ratings.reset_index(drop=True)
def explode(df, lst_cols, fill_value='', preserve_index=False):
import numpy as np
# make sure `lst_cols` is list-alike
if (lst_cols is not None
and len(lst_cols) > 0
and not isinstance(lst_cols, (list, tuple, np.ndarray, pd.Series))):
lst_cols = [lst_cols]
# all columns except `lst_cols`
idx_cols = df.columns.difference(lst_cols)
# calculate lengths of lists
lens = df[lst_cols[0]].str.len()
# preserve original index values
idx = np.repeat(df.index.values, lens)
# create "exploded" DF
res = (pd.DataFrame({
col:np.repeat(df[col].values, lens)
for col in idx_cols},
index=idx)
.assign(**{col:np.concatenate(df.loc[lens>0, col].values)
for col in lst_cols}))
# append those rows that have empty lists
if (lens == 0).any():
# at least one list in cells is empty
res = (res.append(df.loc[lens==0, idx_cols], sort=False)
.fillna(fill_value))
# revert the original index order
res = res.sort_index()
# reset index if requested
if not preserve_index:
res = res.reset_index(drop=True)
return res
movies.genres = movies.genres.str.replace('|', ' ')
movies['year'] = movies.title.str.extract('(\(\d\d\d\d\))',expand=False)
#Removing the parentheses
movies['year'] = movies.year.str.extract('(\d\d\d\d)',expand=False)
movies.to_csv('hybrid_movies.csv')
'''Applying the Cotent_Based Filtering'''
#Applying Feature extraction
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf=TfidfVectorizer(stop_words='english')
#matrix after applying the tfidf
matrix=tfidf.fit_transform(movies['genres'])
#Compute the cosine similarity of every genre
from sklearn.metrics.pairwise import cosine_similarity
cosine_sim=cosine_similarity(matrix,matrix)
'''Applying the Collaborative Filtering'''
#Intialising the Reader which is used to parse the file containing the ratings
reader=Reader()
#Making the dataset containing the column as userid itemid ratings
#the order is very specific and we have to follow the same order
rating_dataset = Dataset.load_from_df(ratings[['userId','movieId','rating']],reader)
#Intialising the SVD model and specifying the number of latent features
#we can tune this parameters according to our requirement
svd=SVD(n_factors=25)
#making the dataset to train our model
training = rating_dataset.build_full_trainset()
#training our model
svd.fit(training)
#Making a new series which have two columns in it
#Movie name and movie id
movies_dataset = movies.reset_index()
titles = movies_dataset['title']
indices = pd.Series(movies_dataset.index, index=movies_dataset['title'])
#Function to make recommendation to the user
def recommendation(movie_list,top_n):
result=[]
#Getting the id of the movie for which the user want recommendation
ind=indices[movie_list[0]].tolist()
ind1=indices[movie_list[1]].tolist()
ind2=indices[movie_list[2]].tolist()
#Getting all the similar cosine score for that movie
sim_scores=list(enumerate(cosine_sim[ind]))
sim_scores1=list(enumerate(cosine_sim[ind1]))
sim_scores2=list(enumerate(cosine_sim[ind2]))
# Calculating the scores
score_series_1 = pd.Series(sim_scores).sort_values(ascending = False)
score_series_2 = pd.Series(sim_scores1).sort_values(ascending = False)
score_series_3 = pd.Series(sim_scores2).sort_values(ascending = False)
sim_scores_1 =score_series_1.append(score_series_2).append(score_series_3).sort_values(ascending = False)
#Sorting the list obtained
sim_scores=sorted(sim_scores_1,key=lambda x:x[1],reverse=True)
#Getting all the id of the movies that are related to the movie Entered by the user
movie_id=[i[0] for i in sim_scores]
#Varible to print only top 10 movies
count=0
for id in range(0,len(movie_id)):
#to ensure that the movie entered by the user is doesnot come in his/her recommendation
if((ind != movie_id[id])&(ind1 !=movie_id[id])&(ind2 !=movie_id[id])):
rating=ratings[ratings['movieId']==movie_id[id]]['rating']
avg_ratings=round(np.mean(rating),2)
#To print only those movies which have an average ratings that is more than 3.5
if(avg_ratings >3.5):
#id_movies=movies_dataset[movies_dataset['title']==titles[movie_id[id]]]['movieId'].iloc[0]
#predicted_ratings=round(svd.predict(movie_id[id]).est,2)
result.append(titles[movie_id[id]])
result = list(set(result))
if(len(result) >=top_n):
break
return result
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
print 'Exercise 1'
keimeno=raw_input ("Πληκτρολογήστε το κείμενό σας:")
while len(keimeno)==0:
keimeno=raw_input ("Πληκτρολογηστε το κείμενό σας:")
print "Το κείμενό σας είναι: " +keimeno
x=list(keimeno)
y=len(x)
for i in range (y):
if(x[i]== '!') and (x[y-1]!='!'):
del x[i]
l=' '.join(x)
print l
else:
if(x[i]!='!') and (x[y-1]=='!'):
l=' '.join(x)
print l
|
def compute_time(absolute_seconds):
# compute days, hours, and minutes from seconds.
absolute_minutes = absolute_seconds / 60
days = absolute_minutes / 1440
hours = absolute_minutes / 60 - (days * 24)
minutes = absolute_minutes - (hours * 60) - (days * 24 * 60)
return {'days': days, 'hours': hours, 'minutes': minutes}
|
# DEBEN DE PONERLE ANOTACION DE TIPO A TODAS LAS FUNCIONES
# 7. Implemente una función que cuente la frecuencia de palabras en una lista.
# La función debe de recibir una lista
# y retornar un diccionario con la palabra (en minúscula) como llave y la cantidad de ocurrencias como valor.
# No se debe de distinguir entre mayúsculas y minúsculas. Cada elemento de la lista es una palabra (6%)
# Ejemplo:
# Entrada: [“hola”, “Hola”, “BYE”]
# Salida: {“hola”: 2, “bye”: 1}
from typing import List, Dict
def cuenta_palabras(lista_palabras: List[str]) -> Dict[str, int]:
res = {}
for palabra in lista_palabras:
palabra = palabra.lower()
if palabra not in res:
res[palabra] = 0
res[palabra] += 1
return res
|
# -*- coding: utf-8 -*-
from itertools import chain
from atores import ATIVO
VITORIA = 'VITORIA'
DERROTA = 'DERROTA'
EM_ANDAMENTO = 'EM_ANDAMENTO'
class Ponto():
def __init__(self, x, y, caracter):
self.caracter = caracter
self.x = round(x)
self.y = round(y)
def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.caracter == other.caracter
def __hash__(self):
return hash(self.x) ^ hash(self.y)
def __repr__(self, *args, **kwargs):
return "Ponto(%s,%s,'%s')" % (self.x, self.y, self.caracter)
class Fase():
def __init__(self, intervalo_de_colisao=1):
"""
Método que inicializa uma fase.
:param intervalo_de_colisao:
"""
self.intervalo_de_colisao = intervalo_de_colisao
self._passaros = []
self._porcos = []
self._obstaculos = []
def adicionar_obstaculo(self, *obstaculos):
"""
Adiciona obstáculos em uma fase
:param obstaculos:
"""
pass
def adicionar_porco(self, *porcos):
"""
Adiciona porcos em uma fase
:param porcos:
"""
pass
def adicionar_passaro(self, *passaros):
"""
Adiciona pássaros em uma fase
:param passaros:
"""
pass
def status(self):
"""
Método que indica com mensagem o status do jogo
Se o jogo está em andamento (ainda tem porco ativo e pássaro ativo), retorna essa mensagem.
Se o jogo acabou com derrota (ainda existe porco ativo), retorna essa mensagem
Se o jogo acabou com vitória (não existe porco ativo), retorna essa mensagem
:return:
"""
return EM_ANDAMENTO
def lancar(self, angulo, tempo):
"""
Método que executa lógica de lançamento.
Deve escolher o primeiro pássaro não lançado da lista e chamar seu método lançar
Se não houver esse tipo de pássaro, não deve fazer nada
:param angulo: ângulo de lançamento
:param tempo: Tempo de lançamento
"""
pass
def calcular_pontos(self, tempo):
"""
Lógica que retorna os pontos a serem exibidos na tela.
Cada ator deve ser transformado em um Ponto.
:param tempo: tempo para o qual devem ser calculados os pontos
:return: objeto do tipo Ponto
"""
pontos=[self._transformar_em_ponto(a) for a in self._passaros+self._obstaculos+self._porcos]
return pontos
def _transformar_em_ponto(self, ator):
return Ponto(ator.x, ator.y, ator.caracter())
|
"""
// Time Complexity : o(n)
// Space Complexity : o(1)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
"""
class Solution:
def rev(self, nums, l, h): #function to reverse
while l < h:
tmp = nums[l]
nums[l] = nums[h]
nums[h] = tmp
l += 1
h -= 1
return nums
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums) - 2
j = len(nums) - 1
while nums[i] >= nums[i+1] and i >= 0: #checking for ascending order from RHS
i -= 1
if i == -1: #if entire array is in ascending order, reverse the entire list
nums = self.rev(nums,0, len(nums)-1)
else:
while nums[j] <= nums[i]: #else, find a number in right subarra that is just bigger than nums[i]
j -= 1
tmp = nums[i] #swap the numbers
nums[i] = nums[j]
nums[j] = tmp
nums = self.rev(nums, i+1, len(nums)-1) #reverse numbers till end from i+1 location
|
import random
HANGMAN = (
"""
------
| |
|
|
|
|
|
|
|
----------
""",
"""
------
| |
| O
|
|
|
|
|
|
----------
""",
"""
------
| |
| O
| -+-
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-/
|
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-/
| |
|
|
|
|
----------
""",
"""
------
| |
| O
| /-+-/
| |
| |
| |
| |
|
----------
""",
"""
------
| |
| O
| /-+-/
| |
| |
| | |
| | |
|
----------
""")
word = "dog lion pig deer tiger shark dinosaur python titan".split()
def getRandomWord(wordList):
# function that displays a random string from a string passed in
wordIndex = random.randint(0, len(wordList)-1)
return word[wordIndex]
def displayBoard(HANGMAN, missedLetters, correctLetters, secretWord):
print (HANGMAN[len(missedLetters)])
print("missed letters : , end = " "")
for letter in missedLetters:
print ("letter, end = " "")
blanks = "_" * len(secretWord)
for i in range (len(secretWord)):#replaces blanks with correctly guessed letters
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # show the secret word with spaces between each letter
print(letter, end = " ")
def getGuess(alreadyGuessed):
#returns the players letters entered, this function makes sure that the player enters a single letter
while True:
guess = input("Guess a Letter")
guess = guess.lower()
if len(guess) != 1:
print("Please Enter a single letter")
elif guess is alreadyGuessed:
print("You have already guessed that letter, Choose again")
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print("Please enter a letter")
else:
return guess
def playAgain():
playAgain = input("Do you want to play again (Yes or No)")
return playAgain.lower().startwith("y")
print(" H A N G M A N ")
missedLetters = ""
correctLetters = ""
secretWord = getRandomWord(word)
gameisDone = False
while True:
displayBoard(HANGMAN, missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print("You Have WON the game, the secret word is " + secretWord)
else:
missedLetters = missedLetters + guess
if len(missedLetters) == len(HANGMAN)-1:
displayBoard(HANGMAN, missedLetters, correctLetters, secretWord)
print("You hav run out of guesses!!!" + str(len(missedLetters)) + " missed guesses and " + str(len(correctLetters)) + " correct guesses, and the word is" + secretWord + "\"")
gameisDone = True
if gameisDone:
if playAgain():
missedLetters = ""
correctLetter = ""
gameisDone = False
secretWord = getRandomWord(words)
else:
print("Game Has Ended")
|
def sumIntervals(lista):
mhkos=len(lista) #μετραει το μηκος της λιστας
athr=0
lista.sort() #ταξινομει την λιστα
print(lista)
for i in range (0,mhkos):#συγκριση της λιστας μεσα στην for και επιστρεφει το αθροισμα
x1=max(lista[i])
y1=min(lista[i])
athr=athr+(x1-y1)
if i!=0:
if (y1>lista[i-1][0] and x1<lista[i-1][1]):
athr=athr-(x1-y1)
else:
if y1<lista[i-1][1]:
athr=athr-(lista[i-1][1]-y1)
print (athr)
lista=[[1,5], [10, 20], [1, 6], [16, 19], [5, 11]]
sumIntervals(lista)#καλεσμα συναρτησης με ορισμα την λιστα με τα διαστηματα
|
class Planet(object):
names = ["Mercury","Venus","Earth","Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
diameters = ["3031.9", "7520.8", "7917.5", "4212.3","86881", "72367", "31518", "30599"]
distances = ["1st","2nd","3rd","4th","5th","6th","7th","8th"]
def __init__(self, name, diameter, distance):
self.nameIndex = name
self.diameterIndex = diameter
self.distanceIndex = distance
def __str__(self):
name=Planet.names[self.nameIndex]
diameter=Planet.diameters[self.diameterIndex]
distance=Planet.distances[self.distanceIndex]
return "Planet: "+ name + ", " + "Diameter: " + diameter + " mi, " + distance + " from Sun"
|
def swap_case_worst(s):
s=list(s)
new_string=[]
for i in range(0,len(s)):
if s[i]==' ':
new_string=new_string+[s[i]]
elif s[i] in "!@#$%^&*()><?}{[].,123456789\"":
new_string=new_string+[s[i]]
elif s[i] in '\"qqwertypasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789"':
if s[i].isupper()==True:
new_string=new_string+[s[i].lower()]
elif s[i].islower()==True:
new_string=new_string+[s[i].upper()]
elif s[i].isupper()==True:
new_string=new_string+[s[i].lower()]
elif s[i].islower()==True:
new_string=new_string+[s[i].upper()]
else:
return -1
'''
print(new_string)
string=[str(i) for i in new_string]
print(string)
'''
res = "".join(new_string)
return res
def swap_case(s):#Best and smaller code
s=list(s)
new_string=[]
for i in range(0,len(s)):
if s[i].isalpha()==False:
new_string=new_string+[s[i]]
elif s[i].isupper()==True:
new_string=new_string+[s[i].lower()]
elif s[i].islower()==True:
new_string=new_string+[s[i].upper()]
else:
return -1
new_string = "".join(new_string)
return new_string
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
'''
if __name__ =='__main__':
s = input()
result = swap_case(s)
result="".join(result)
print(result)
#HackerRank.com presents "Pythonist 2".
#output-->hACKERrANK.COM PRESENTS "pYTHONIST 2".
'''
'''
elif s[i] in '\"qwertypasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&*()><?}{[].,+-_"':
if s[i].isupper()==True:
new_string=new_string+[s[i].lower()]
print("i and here")
elif s[i].islower()==True:
new_string=new_string+[s[i].upper()]
'''
|
class Product():
def __init__(self,name,price,weight,discount):
self.name=name
self.price=price
self.weight=weight
self.discount=discount
def __repr__(self):
return repr((self.name,self.price,self.weight))
def discountPrice(self):
return self.price-(self.price*self.discount)
if __name__=="__main__":
prodList=[
Product("widget",50,10,0.05),
Product("Doohickey",40,8,0.15),
Product("Thingamabob",35,12,0.0),
Product("Gadget",65,7,0.20)
]
print(prodList)
'''
def prodsort(Product):
return Product.price
print(sorted(prodList,key=prodsort))
'''
print(sorted(prodList,key=lambda p:p.price))
|
>>> import collections
>>> d=collections.deque('abcdefg')
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> d.appendleft(1)
>>> a
[2, 3, 5]
>>> d
deque([1, 'a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> d.append(2)
>>> d
deque([1, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 2])
>>> d.pop()
2
>>> d
deque([1, 'a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>>
>>> d.popleft()
1
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> d.rotate()
>>> d
deque(['g', 'a', 'b', 'c', 'd', 'e', 'f'])
>>> d.rotate()
>>> d
deque(['f', 'g', 'a', 'b', 'c', 'd', 'e'])
>>> d.rotate()
>>> d
deque(['e', 'f', 'g', 'a', 'b', 'c', 'd'])
>>> d.maxlen()
>>> d.count('e')
1
>>> for elem in d:
print(elem,end=',')
e,f,g,a,b,c,d,
>>> for elem in d:
print(elem.upper(),end=',')
E,F,G,A,B,C,D,
>>> for elem in range(len(d)):
print(d[elem],end=',')
e,f,g,a,b,c,d,
>>> for elem in range(len(d)):
print(d[elem].upper(),end=',')
E,F,G,A,B,C,D,
>>> len(d)
7
|
#!/bin/python3
import os
import sys
from datetime import time,datetime,date
import datetime
import time
#
# Complete the timeConversion function below.
#strptime
def timeConversion(s):
c=s.split(":")
hour=int(c[0])
minute=int(c[1])
if "AM" in c[2]:
new_second=c[2].rstrip("AM")
if hour==12:
hour=0
elif "PM" in c[2]:
new_second=c[2].rstrip("PM")
if hour==12:
hour=12
elif hour<12:
hour=hour+12
if minute<10:
minute="0"+str(minute)
if hour<10:
hour="0"+str(hour)
return ("%s:%s:%s"%(hour,minute,new_second))
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = timeConversion(s)
f.write(result+"\n")
f.close()
|
co = float(input('Informe o cateto oposto : '))
ca = float(input('Informe o cateto adjacente : '))
hi = ((ca ** 2) + (co ** 2)) ** (1 / 2)
print('Hipotenusa = {:.2f}' .format(hi))
|
import math
num = float(input("Digite um numero : "))
# inteiro = math.floor(num)
# inteiro = math.trunc(num)
# print("A parte inteira eh = {}" .format(inteiro))
print("A parte inteira eh = {}" .format(int(num)))
|
nome = input('Digite seu nome completo : ').strip()
print('Seu nome transformado para Maiusculo eh :', end=' ')
print(nome.upper())
print('Seu nome transformado para minusculo eh : ', end='')
print(nome.lower())
# print('Seu nome tem {} letras validas'.format(len(''.join(nome.split()))))
print('Seu nome tem {} letras validas' .format(len(nome) - nome.find(' ')))
print('Seu primeiro nome eh : {}'.format(nome.split()[0]))
|
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, room):
self.name = name
self.room = room
self.inventory = []
def __str__(self):
return f"Name: {self.name}\tLocation: {self.room}"
def move_to(self, direction):
move_room = getattr(self.room, f"{direction}_to")
if (move_room != ""):
self.room = move_room
else:
print(f'\n{"*" * 58}\n')
print("You may not go in this direction!".center(58, ' '))
def check_inventory(self):
if len(self.inventory) > 0:
print(f'\n{"*" * 58}\n')
print(f"Your inventory currently contains:".center(58, ' '))
for i in self.inventory:
item = i
print(f'{i}'.center(58, ' '))
else :
print(f'\n{"*" * 58}\n')
print(f"Your inventory is currently empty".center(58, ' '))
def on_take(self, command, item):
if command == 'take' or 'get':
self.inventory.append(self.room.get_item(item.lower()))
def on_drop(self, command, item):
if command == 'drop':
for i in self.inventory:
if i.name.lower() == item.lower():
self.inventory.remove(i)
self.room.add_item(i)
break
else:
print(f'\n{"*" * 58}\n')
print(f"The item you tried to drop is not in your inventory".center(58, ' '))
|
input_shape= input("Enter your shape:Triangle ? Rectangle ? Circle ? \n")
input_func= input("Enter your function: Enviroment ? Area \n")
if input_shape== "Rectangle":
tool = float(input("Enter tool\n"))
arz = float(input("Enter arz\n"))
dastoor= input_func
def mostatil (tool, arz, dastoor):
if dastoor== "Enviroment" :
return (tool+arz)*2
elif dastoor== "Area" :
return (tool*arz)
else:
return "Amaliyat na moatabar"
result1 = mostatil (tool, arz, dastoor)
print (result1)
elif input_shape== "Triangle" and input_func == "Area":
ertefa = float(input("Enter ertefa\n:"))
ghaede = float(input("Enter ghaede\n:"))
dastoor= input_func
def mosalas_masahat ( ertefa, ghaede, dastoor):
if dastoor == "Area" :
return (.5*ertefa*ghaede)
else : print("tt")
result3= mosalas_masahat (ertefa, ghaede, dastoor)
print (result3)
elif input_shape== "Triangle" and input_func == "Enviroment":
zel1 = float(input("Enter zel1\n:"))
zel2 = float(input("Enter zel2\n:"))
ghaede = float(input("Enter ghaede\n:"))
dastoor= input_func
def mosalas_mohit(ghaede , zel1, zel2, dastoor):
if dastoor == "Enviroment" :
return (zel1+zel2+ghaede)
else:
return "Amaliyat na moatabar"
result2 = mosalas_mohit (ghaede, zel1, zel2, dastoor)
print (result2)
elif input_shape == "Circle":
shoaa= float(input("Enter Shoaa:\n"))
dastoor= input_func
def dayere (shoaa , dastoor):
if dastoor == "Enviroment" :
return (2*3.14*shoaa)
elif dastoor == "Area" :
return (3.14*shoaa*shoaa)
else :
return "Amaliyat na moatabar"
result4 = dayere (shoaa , dastoor)
print(result4)
|
import random
chosenNumber = random.randint(1, 10)
def guessNumber():
guessedNumber = input("Guess a number between 1 and 10: ")
if str(chosenNumber) == guessedNumber:
print("You guessed right, great job!")
elif guessedNumber.lower() == 'exit':
exit()
elif str(chosenNumber) != guessedNumber:
print("You guessed wrong :(")
guessNumber()
guessNumber()
|
#!/usr/bin/env python
"""
Based on https://github.com/opencv/opencv/blob/master/samples/python/mouse_and_match.py
Read in the images in a directory one by one
Allow the user to select two points and then draw a line between them.
When done with the current image press SPACE to show next image. When pressing SPACE it saves the annotation image as
a jpg in the save path and also moves the previous image to a subfolder in the image path where the images which have
been annotated are stored.
SPACE for next image
ESC to exit
"""
# Python 2/3 compatibility
from __future__ import print_function
import argparse
import glob
# built-in modules
import os
import cv2 as cv
import numpy as np
drag_start = None
sel = (0, 0, 0, 0)
nr_clicked = 0
drag_end = None
save_path='C:\\Users\\Samuel\\GoogleDrive\\Master\\Python\\thesis_project\\computer_vision\\images\\training_data'
image_path='C:\\Users\\Samuel\\GoogleDrive\\Master\\Python\\thesis_project\\computer_vision\\images\\cropped_images\\*'
move_path= '/home/saming/thesis_project/computer_vision/images/cropped_images/Annotated/'
drags = []
i=1
def onmouse(event, x, y, flags, param):
global drag_start, sel, nr_clicked, drag_end
if event == cv.EVENT_LBUTTONDOWN and nr_clicked < 2:
if nr_clicked == 0:
drag_start = x, y
sel = 0, 0
nr_clicked += 1
else:
drag_end = x, y
nr_clicked += 1
elif drag_start and drag_end:
if flags & cv.EVENT_FLAG_LBUTTON:
cv.line(img, drag_start, drag_end, (0, 255, 255), 5)
cv.imshow("Annotation", img)
else:
# print("selection is complete")
drags.append([drag_start, drag_end])
drag_start = None
drag_end = None
nr_clicked = 0
if __name__ == '__main__':
print(__doc__)
parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images')
parser.add_argument("-i", "--input",
default=image_path,
help="Input directory.")
args = parser.parse_args()
path = args.input
cv.namedWindow("Annotation", 1)
cv.setMouseCallback("Annotation", onmouse)
'''Loop through all the images in the directory'''
print(path)
allfiles=glob.glob(path)
print(len(allfiles))
for infile in allfiles:
ext = os.path.splitext(infile)[1][1:] # get the filename extension
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
img = cv.imread(infile, 1)
if img is None:
continue
sel = (0, 0, 0, 0)
drag_start = None
cv.imshow('Annotation', img)
if cv.waitKey() == 27:
break
blank_image = np.zeros((500, 350, 3), np.uint8)
blank_image[:, :] = (100, 0, 0)
for d in drags:
cv.line(blank_image, d[0], d[1], (255, 255, 255), 10)
oldimg = infile.split('cropped_images/')
print(i)
i+=1
cv.imwrite(save_path + oldimg[1], blank_image)
drags = []
drag_start = None
drag_end = None
nr_clicked = 0
a = infile.split("cropped_images/")
new_move_path = move_path + a[1]
os.rename(infile, new_move_path)
cv.destroyAllWindows()
|
l1=list(input("Enter the list"))
k=int(input('Enter the subarray length'))
l2=[]
for i in range(0,len(l1)-k+1):
l3=list(l1[i:i+k])
l2.append(max(l3))
print(l2)
|
import re
__author__ = 'davidabrahams'
def get_string_from_file(file_name):
"""
:param file_name: a string of the file name to read
:return:= a string of the text within than file
"""
return open(file_name).read()
def is_word_before_all_caps(string, index_of_colon):
"""
>>> is_word_before_all_caps('HARRY: I love magic', 5)
True
>>> is_word_before_all_caps("Flamel: I'm immortal", 6)
False
>>> is_word_before_all_caps('Now space : I love magic', 10)
False
:param string: the string to check
:param index_of_colon: the index of the colon to look before
:return: if the word directly before the colon is in all caps
"""
index = index_of_colon
while index >= 0 and not string[index].isspace():
index -= 1
return string[index+1:index_of_colon].isupper()
def char_name(string, index_of_colon):
"""
The name of the character starts right after the first '\n' before the ':' that follows his name
:param string: the string to look through
:param index_of_colon: the index of the colon to look before
:return: the name of the character preceding the ':"
>>> char_name("he said.\\nDUMBLEDORE: Stuff", 19)
'DUMBLEDORE'
>>> char_name("end quote. \\nProf Mc: Stuff", 19)
'Prof Mc'
"""
# Look backward for the first whitespace occurrence to determine the character's name
first_whitespace = index_of_colon
while first_whitespace >= 0 and not string[first_whitespace] == '\n':
first_whitespace -= 1
return string[first_whitespace + 1:index_of_colon]
def find_quote(string, index_of_colon):
"""
>>> find_quote("HARRY: Good job!\\nDUMBLEDORE: Second, to Mr. Ronald ", 5)
'Good job!'
>>> find_quote("LEE JORDAN: We won!\\n---------\\nScene", 10)
'We won!'
>>> find_quote("HARRY: I'm not going home. Not really.\\n----------\\nScene 35: End Credits.\\n\\n -The End-\\n\\n", 5)
"I'm not going home. Not really."
:param string: the string to look through
:param index_of_colon: the index of the colon that indicates the start of a quote
:return: a string of the quote the character said
"""
# look for the next speaking character and section break
next_colon = string.find(': ', index_of_colon + 2)
while next_colon != -1 and not char_name(string, next_colon).isupper():
next_colon = string.find(': ', next_colon + 2)
next_break = string.find('---------', index_of_colon + 2)
# if there is no next speaking character or section break, assume the quote spans the rest of the file
if next_break == -1 and next_colon == -1:
end_of_quote = len(string)
else:
# if we didn't find either a colon or a break, the quote ends at the one we found
if next_colon == -1:
end_of_quote = next_break
elif next_break == -1:
end_of_quote = next_colon
# if we found both, the quote ends at the first one
else:
end_of_quote = min(next_colon, next_break)
# end the character's quote at the next new line
while end_of_quote >= 0 and string[end_of_quote] != '\n':
end_of_quote -= 1
# extract the quote and strip leading and trailing whitespace
quote = string[index_of_colon + 2:end_of_quote].strip()
# replace characters like \n, \t, with spaces
quote = re.sub("[\s]+", " ", quote)
# return it!
return quote
def file_to_chars_and_quotes(file_name):
"""
:param file_name: the name of the file to get quotes from
:return: a list of tuples [(char_name, quote), (char_name, quote)]
"""
# get the text from the file
string = get_string_from_file(file_name)
# initialize the return variable and where we will be searching
char_quote_pairs = []
start_looking_at = 0
# search until we cannot find another ': '
while string.find(': ', start_looking_at) != -1:
colon_loc = string.find(': ', start_looking_at)
# The name of the character starts right after the first whitespace before the ':' that follows his name
char = char_name(string, colon_loc)
# It's only a character name if it only contains capital letters
if char.isupper():
# find the quote
quote = find_quote(string, colon_loc)
# append the character name and quote to the return variable
char_quote_pairs.append((char, quote))
# increment the loop control
start_looking_at = colon_loc + len(quote)
else:
# if this ': ' does not indicate a character, quote pair, keep looking
start_looking_at = colon_loc + 2
return char_quote_pairs
if __name__ == '__main__':
import doctest
doctest.testmod()
|
def intersection(arrays):
dic = {}
for i in range(0, len(arrays)):
index = 0
while index != len(arrays[i]):
if arrays[i][index] not in dic.keys():
dic[arrays[i][index]] = 1
else:
number = dic[arrays[i][index]]
number += 1
dic[arrays[i][index]] = number
index += 1
num_list = list(dic.items())
num_list.sort(reverse=True, key=lambda tupl: tupl[1])
index = 0
biggest = num_list[index][1]
result = []
while biggest == len(arrays):
result.append(num_list[index][0])
index += 1
if index == len(num_list):
break
biggest = num_list[index][1]
return result
if __name__ == "__main__":
arrays = []
arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])
arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])
arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])
print(intersection(arrays))
|
import pandas as pd
def load():
filename = "hotel/sample_hotel_data.csv"
df = pd.read_csv(filename)
data = {
"df": df,
"keys": ["home_city", "dest_city"],
}
data["types"] = {
"distance": float,
"home_pop": int,
"dest_pop": int,
"hotel_size": int,
"conversion": int,
}
return data
|
from random import shuffle
#générateur de pharse
#demander en console une chaine de la forme "mot1/mot2/mot3/mot4
chaine_word = input("Entrer une de la forme mot1/mot2/mot3/mot4")
#transformer cette chaine en liste
word = chaine_word.split("/")
#melanger la phrase
shuffle(word)
#récupérer le nombre d'éléments
word_len = len(word)
#si le nombre d'éléments de la liste est inférieur a 10
if word_len < 10:
#afficher les 2 premier mots
print(word[0], word[1])
#ou print(word[0:1]
else:
#afficher les 3 derniers
print(word[2:3])
|
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: 花菜
# @File: 整数反转.py
# @Time : 2020/12/7 22:18
# @Email: [email protected]
class Solution(object):
"""
>>> s = Solution()
>>> s.reverse(1534236469)
0
>>> s.reverse(123)
321
>>> s.reverse(120)
21
>>> s.reverse(-123)
-321
>>> s.reverse(0)
0
>>> s.reverse(-1230)
-321
"""
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
ans = 0
if x == 0:
return ans
s = str(x)
if x > 0:
s = s[::-1]
ans = int(s.lstrip('0'))
else:
s = s.replace('-', '')[::-1]
ans = -int(s.lstrip('0'))
MAX = 2**31 - 1
MIN = -2 ** 31
if MIN > ans or ans > MAX:
ans = 0
return ans
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
|
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: 花菜
# @File: 柠檬水找零.py
# @Time : 2020/12/10 00:12
# @Email: [email protected]
from typing import List
class Solution:
"""
>>> s = Solution()
>>> s.lemonadeChange([5,5,5,10,20])
True
>>> s.lemonadeChange([5,5,10])
True
>>> s.lemonadeChange([10, 10])
False
"""
def lemonadeChange(self, bills: List[int]) -> bool:
d = {5: 0, 10: 0, 20: 0}
ans = True
for i in bills:
if i == 5:
d[5] += 1
elif i == 10:
if d[5] < 1:
ans = False
break
else:
d[5] -= 1
d[10] += 1
else:
if d[5] >= 1 and d[10] >= 1:
d[5] -= 1
d[10] -= 1
elif d[5] >= 3:
d[5] -= 3
else:
ans = False
break
return ans
class Solution1:
"""
不需要使用哈希表来存储变量,直接使用单个变量即可
>>> s = Solution1()
>>> s.lemonadeChange([5,5,5,10,20])
True
>>> s.lemonadeChange([5,5,10])
True
>>> s.lemonadeChange([10, 10])
False
"""
def lemonadeChange(self, bills: List[int]) -> bool:
five, ten = 0, 0
for i in bills:
if i == 5:
five += 1
elif i == 10:
if five < 1:
return False
else:
five -= 1
ten += 1
else:
if five >= 1 and ten >= 1:
five -= 1
ten -= 1
elif five >= 3:
five -= 3
else:
return False
return True
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
|
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:梨花菜
# @File: LinkList.py
# @Time : 2020/9/3 22:10
# @Email: [email protected]
# @Software: PyCharm
import time
def bubble(arr):
"""
>>> arr = [3,1,2,4]
>>> bubble(arr)
>>> arr == [1, 2, 3, 4]
True
"""
if len(arr) <= 1:
return arr
length = len(arr)
for i in range(length):
for j in range(length - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# return arr
def quick_sort(arr):
if len(arr) <= 1:
return arr
min_part = []
max_part = []
flag = arr[0]
for i in arr[1:]:
if i < flag:
min_part.append(i)
else:
max_part.append(i)
return quick_sort(min_part) + [flag] + quick_sort(max_part)
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
|
from math import exp
def f(x):
return x*exp(-x)
#Numerically Integrate f(x) from 0 to 50
intgrl = 0.0
x = 0
xmax = 50
dx = 0.0001
while x<xmax:
intgrl += dx*f(x)
x += dx
print("Integral=", intgrl, "error=", abs(1-intgrl))
# dx has to be smaller than 10**-4 to yield error 10**-10
|
#!/usr/bin/env python3
"""Flip Me Over"""
def matrix_transpose(matrix):
"""transpose a matrix"""
new_matrix = []
for i in range(len(matrix[0])):
new_row = []
for j in range(len(matrix)):
new_row.append(matrix[j][i])
new_matrix.append(new_row)
return new_matrix
|
from utils import enumerate_combinations as ec
import unittest
import sys
sys.path.append('..')
class TestFunction(unittest.TestCase):
"""
Test utils.enumerate_combinations
"""
def setUp(self):
self.lst = [1, 2]
def test(self):
expected_result3 = set()
expected_result2 = {(1, 2), (2, 1)}
expected_result1 = {(2,), (1,)}
expected_result0 = {()}
# test is a set
self.assertIsInstance(ec(self.lst, 2), set)
# test output is correct, containing all combinations for n=3, 2, 1, 0
self.assertEqual(expected_result3, ec(self.lst, 3))
self.assertEqual(expected_result2, ec(self.lst, 2))
self.assertEqual(expected_result1, ec(self.lst, 1))
self.assertEqual(expected_result0, ec(self.lst, 0))
if __name__ == '__main__':
unittest.main()
|
# cook your dish here
def minutes_converter(time,spell):
t=time.split(':')
hr=int(t[0])
minutes=int(t[1])
total_minutes=0
if hr==12:
if spell=='AM':
total_minutes=minutes
else:
total_minutes=(minutes)+12*60
else:
if spell=='AM':
total_minutes=hr*60+minutes
else:
total_minutes=(hr*60+minutes)+12*60
return total_minutes
# print(minutes_converter('12:00','AM'))
t=int(input())
while(t!=0):
p=input().split()
sum_p=minutes_converter(p[0],p[1])
n=int(input())
ans=''
while n!=0:
f_time=input().split()
if minutes_converter(f_time[0],f_time[1])<=sum_p<=minutes_converter(f_time[2],f_time[3]):
ans=ans+'1'
else:
ans=ans+'0'
n-=1
if ans=='':
print('-1')
else:
print(ans)
t-=1
|
#!/usr/bin/env python3.9
"""
Classe responsável por executar a regra de negócio RN1 para descobrir o destino
da espaçonave
RN1:O local de chegada pode ser conhecido sabendo que as vogais do nome da estrela
são atribuídas à uma sequência Fibonacci que começa em 1 e termina em 8,
onde A = 1, E = 2, I = 3, O = 5 e U = 8.
Se a multiplicação das vogais der o mesmo número
que a quantidade de engenheiros, a estrela de destino será conhecida.
"""
from typing import List
from src.metricas import Balanca, Calculadora
from src.viagem import Nave, SistemaEstelar
class Avaliador:
@staticmethod
def avalia(numero_de_passageiros: int, relacao_estrelas: List[str]):
# instanciando a nave do problema
nave = Nave(numero_de_passageiros=numero_de_passageiros)
# instanciando o sistema estelar do problema
sistema_estelar = SistemaEstelar(estrelas=relacao_estrelas)
# instanciando a Calculadora para avaliação
calculadora = Calculadora()
# instanciando a Balança
balanca = Balanca()
for estrela in sistema_estelar.estrelas:
# para cada elemento da lista de destino, comparar com o número de passageiros n
# retorna o nome da estrela cujo processamento pela RN1 é igual a n
if balanca.compara(calculadora.calcula(estrela), nave.numero_de_passageiros):
return estrela
|
#Short Substrings
n = int(input())
for _ in range(n):
s = input()
r = s[0]
for i in range(1,len(s),2):
r = r+s[i]
print(r)
|
#In Search of an Easy Problem
n = int(input())
l = input().split()
if l.count('1'):
print("HARD")
else:
print("EASY")
|
### write your solution below this line ###
class Stack:
def __init__(self, size):
self.size = size
self.data = [None]* self.size
self.top = -1
def push(self,val):
if not self.isFull():
self.data.append(val)
self.top += 1
def isFull(self):
if self.top >= self.size-1:
return 1
return 0
def pop(self):
poped = None
if not self.isEmpty():
poped = self.data.pop()
self.top -= 1
return poped
def peek(self):
return self.data[-1]
def isEmpty(self):
if self.top <= -1:
return 1
return 0
if __name__ == "__main__":
test_cases=int(input()) # number of test cases
size=int(input()) # size of Stack
stack=Stack(size) # creating new stack object
while(test_cases>0):
instruction=input().split()
val=0
if len(instruction)>1:
val=int(instruction[1])
instruction=int(instruction[0])
if(instruction==1):
print(f'push:{val}')
stack.push(val)
elif (instruction==2):
print(f'pop:{stack.pop()}')
elif (instruction==3):
print(f'peek:{stack.peek()}')
elif(instruction==4):
print(f'isEmpty:{stack.isEmpty()}')
elif(instruction==5):
print(f'isFull:{stack.isFull()}')
test_cases=test_cases-1
|
#Anton and Letters
n =[each for each in input() if each !=" " and each !="}" and each !="{" and each !=","]
print(len(set(n)))
|
import pyautogui
from time import sleep
pyautogui.PAUSE = 1
sleep(5)
# this pyautogui.position() returns the x and y coordinates of the mouse
# one you start the execution of the file, you have 5 seconds to position the mouse on a point who's coordinates you need
# for example: if i place the mouse on top of the google chrome icon in my taskbar,I'll get the coordinates of the icon
x, y = pyautogui.position()
print(x, y)
# pyautogui.moveTo(x,y) is used to move the mouse from any position to the point x,y pyautogui.click() is used to simulate a
# mouse click over here.
# w.r.t this example, the mouse will move on its own to the google chrome icon and open it
pyautogui.moveTo(x, y)
pyautogui.click()
# repeat this program to find the coordinates of all the places where you'll have to do a mouse click to open an application in the web
|
from sys import argv
#open and parse file
#M,N are 2 integers: number of rows and columns
#maze is a list of strings
with open(argv[1]) as f:
M,N=map(int,(f.readline()).split())
maze=[x.strip() for x in f.readlines()]
#find left and right immediate exits, mark them with '1'
#find up and down immediate exits, mark them with '1'
#maze is now a 2d list
maze=[['1' if ((c=='L'and j==0) or (c=='R' and j==N-1)) else c for j,c in enumerate(row)] for row in maze]
maze=[['1' if c=='U' else c for c in row] if i==0 else ['1' if c=='D' else c for c in row] if i==M-1 else row for i,row in enumerate(maze)]
#function that checks the path starting from grid[r][c]
#follows the path and stores each passing tile in set current
#all tiles in current set to '2'
#if an exit '1' is reached set all tiles in path to '1'
#if a loop '0' is reached or loop on self '2' then set all tiles in path to '0'
def path(grid,r,c):
#set of tiles in path starting from grid[r][c]
current=set()
while 1:
#add tile to path
current.add((r,c))
if grid[r][c]=='L':
if grid[r][c-1]=='1':
for a in current:
grid[a[0]][a[1]]='1'
return
elif grid[r][c-1]=='2' or grid[r][c-1]=='0':
for a in current:
grid[a[0]][a[1]]='0'
return
else:
grid[r][c]='2'
c=c-1
elif grid[r][c]=='R':
if grid[r][c+1]=='1':
for a in current:
grid[a[0]][a[1]]='1'
return
elif grid[r][c+1]=='2' or grid[r][c+1]=='0':
for a in current:
grid[a[0]][a[1]]='0'
return
else:
grid[r][c]='2'
c=c+1
elif grid[r][c]=='U':
if grid[r-1][c]=='1':
for a in current:
grid[a[0]][a[1]]='1'
return
elif grid[r-1][c]=='2' or grid[r-1][c]=='0':
for a in current:
grid[a[0]][a[1]]='0'
return
else:
grid[r][c]='2'
r=r-1
elif grid[r][c]=='D':
if grid[r+1][c]=='1':
for a in current:
grid[a[0]][a[1]]='1'
return
elif grid[r+1][c]=='2' or grid[r+1][c]=='0':
for a in current:
grid[a[0]][a[1]]='0'
return
else:
grid[r][c]='2'
r=r+1
#return immediately if grid[r][c] is already '0' or '1'
else:
return
#call path for every tile
for i in range(M):
for j in range(N):
path(maze,i,j)
#count all '0'
looprooms=sum(row.count('0') for row in maze)
print(looprooms)
|
num1 = float(input("Digite o primeiro numero: "))
num2 = float(input("Digite o segundo numero: "))
num3 = float(input("Digite o terceiro numero: "))
print(max(num1, num2, num3))
|
# operador igualdade == (x == y)
# operador diferente != (x != y)
# a=(100!=100) a receberá FALSE
# > operador maior que (1 > 0) retorna TRUE
# < operador menor que (1 < 0) retorna FALSE
# >= operador maior ou igual (1 >= 1) retorna TRUE
# <= operador menor ou igual (1 <= 2) retorna TRUE
'''
tste
'''
print(10*'-')
|
#Fatiando listas
#lista = [start:stop:step]
#start = indice inicial, default = 0
#stop = indice final, default = numElementosLista
#step = incremento de indice, default = 1
lista = "Bem vindo ao curso de python"
print(lista[10])
print(lista[:20])
print(lista[10:20])
print(lista[::2])
print(lista[::3])
print(lista[::-1])
|
num1 = float(input("Digite o primeiro numero: "))
num2 = float(input("Digite o segundo numero: "))
num3 = float(input("Digite o terceiro numero: "))
valores = [num1, num2, num3]
valores.sort(reverse=True)
for i in valores:
print(i)
|
a = 25.4
if(float(a).is_integer()):
print("O numero e inteiro!")
else:
print("O numero nao e inteiro!")
|
i = 0
while (i < 1):
print("Estou em loop")
if(input("Digite uma letra: ")=="q"):
break
|
"""
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970.
It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) square array of cells.
We calculate N - the sum of live cells in C's eight-location neighbourhood, then cell C is alive or dead in the next generation based on the following table:
C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren
Assume cells beyond the boundary are always dead.
The "game" is actually a zero-player game, meaning that its evolution is determined by its initial state, needing no input from human players. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
Task
Although you should test your implementation on more complex examples such as the glider in a larger universe, show the action of the blinker (three adjoining cells in a row all alive), over three generations, in a 3 by 3 grid.
"""
import random
import math
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
ON = 255
OFF = 0
vals = [ON, OFF]
class Grid:
def __init__(self, size=3):
self.x = size
self.y = size
self.grid = [[0 for x in range(self.x)] for y in range(self.y)]
self.coords = [[(x,y) for x in range(self.x)] for y in range(self.y)]
def __eq__(self, other):
return self.grid == other.grid
def __str__(self):
return '\n'.join([' '.join([str(x) for x in self.grid[y]]) for y in range(len(self.grid))]) + '\n'
def set_random_starting_position(self, n=5):
for i in range(n):
x = math.floor(random.random() * self.x)
y = math.floor(random.random() * self.y)
self.set_val_to_coord(1, (x,y))
def set_val_to_coord(self, val, coord):
if self.coord_in_grid(coord):
x=coord[0]
y=coord[1]
self.grid[y][x] = val
else:
return
def get_val_from_coord(self, coord):
if self.coord_in_grid(coord):
x = coord[0]
y = coord[1]
return self.grid[y][x]
def get_all_coordinates(self):
return [item for y in self.coords for item in y]
def coord_in_grid(self, coord):
return coord in self.get_all_coordinates()
def is_neighbour(self, coord1, coord2):
return abs(coord1[0] - coord2[0]) <= 1 and abs(coord1[1] - coord2[1]) <= 1
def get_all_neighbours(self, coord):
return [neighbour for neighbour in self.get_all_coordinates() if self.is_neighbour(coord, neighbour)
and coord != neighbour
]
def get_score(self, coord):
return sum([self.get_val_from_coord(neighbour) for neighbour
in self.get_all_neighbours(coord)])
def get_next_state(self, current_state, score):
""" C N new C
1 0,1 -> 0 # Lonely
1 4,5,6,7,8 -> 0 # Overcrowded
1 2,3 -> 1 # Lives
0 3 -> 1 # It takes three to give birth!
0 0,1,2,4,5,6,7,8 -> 0 # Barren"""
if current_state == 1:
if score <= 1:
return 0
elif score <=3:
return 1
else:
return 0
else:
if score == 3:
return 1
else:
return 0
def next(self):
for coord in self.get_all_coordinates():
current_state = self.get_val_from_coord(coord)
score = self.get_score(coord)
self.set_val_to_coord(self.get_next_state(current_state, score), coord)
return self
def next(self, grid, img):
for coord in grid.get_all_coordinates():
current_state = grid.get_val_from_coord(coord)
score = grid.get_score(coord)
grid.set_val_to_coord(grid.get_next_state(current_state, score), coord)
img.set_data(grid.grid)
return grid
def plot_image(grid, update, updateInterval):
fig, ax = plt.subplots()
img = ax.imshow(grid.grid, interpolation='nearest')
ani = animation.FuncAnimation(fig, update, fargs=(grid, img),
frames=10,
interval=updateInterval,
save_count=50)
plt.show()
def main():
updateInterval = 500
t2 = Grid(20)
t2.set_random_starting_position(1000)
# print(t2)
plot_image(t2, next, updateInterval)
# t3 = Grid()
# t3.set_val_to_coord(1, (0,0))
# t3.set_val_to_coord(1, (1, 1))
# print(t3)
# t3.set_val_to_coord(1, (1, 0))
# t3.set_val_to_coord(1, (2, 0))
#
# print(t3)
# t3.next()
# print('\n')
# print(t3)
#
# for i in range(3):
# t3.next()
# print(t3)
if __name__ =='__main__':
main()
|
'''
This problem finds all elements that are bigger than all elements
on its right
keep pushing the elements on the stack...
before pushing an element, check if there top of stack is smaller
than the current element
if smaller, then keep poping until you find an element bigger than
current and then push current element
at the end, the stack contains the elements we needed
'''
def find_elements_bigger_than_all_right(input_array):
if type(input_array) != list:
raise('Incorrect input')
if not input_array or len(input_array) == 1:
return input_array
stack = []
for element in input_array:
while stack:
head = stack.pop()
if head <= element:
continue
stack.append(head)
break
stack.append(element)
return stack
print find_elements_bigger_than_all_right([1,100,50,60,70, 30, 20, 5,6, 1])
print find_elements_bigger_than_all_right([1,2,3])
print find_elements_bigger_than_all_right([1,2,1])
print find_elements_bigger_than_all_right([])
print find_elements_bigger_than_all_right([1])
|
'''
Move the zeros to the end,
If zeros to move to the start,
we should start from the end of the
array for efficiency
'''
def move_zero(arr):
if len(arr) < 2:
return
i = len(arr)
j = 0
start_zero = -1
while j < i:
if arr[j] != 0:
if start_zero != -1:
arr[start_zero] = arr[j]
arr[j] = 0
start_zero += 1
else:
if start_zero == -1:
start_zero = j
j += 1
def move_zero_first(arr):
if len(arr) < 2:
return
i = len(arr)
j = i - 1
start_zero = -1
while j > -1:
if arr[j] != 0:
if start_zero != -1:
arr[start_zero] = arr[j]
arr[j] = 0
start_zero -= 1
else:
if start_zero == -1:
start_zero = j
j -= 1
x = [0,0,1,2, 0, 4, 5, 0, 6, 7, 0]
y = [0,0,1,2, 0, 4, 5, 0, 6, 7, 0]
move_zero(x)
print(x)
move_zero_first(y)
print(y)
|
from copy import copy
def print_permute(input, lst, printed):
if len(input) == 1:
lst.append(input[0])
word = ''.join(lst)
if word not in printed:
printed.add(word)
print(word)
lst.pop()
else:
i = 0
while i < len(input):
newinput = copy(input)
x = newinput.pop(i)
lst.append(x)
print_permute(newinput, lst, printed)
lst.pop()
i += 1
string = 'abcda'
print_permute(list(string), [], set())
|
'''
In an array, if a particular element is happenning more than
N/2 times where N is the size of the array, then that is the
majority element.
Start with the first element and mark that is majority and
set it's count at 1. If subsequent elements equal to that element,
increment count and if not equal decrement the count. If the
count becomes 0, then change the majority element to the current
element and set count to 0.
At the end go throgh the array again to
check if the element is really the majority element.
'''
def find_majority_elem(array):
if len(array) == 0:
return False, 0
if len(array) == 1:
return True, array[0]
found = True
majority_elem = array[0]
count = 1
i = 1
while i < len(array):
if array[i] == majority_elem:
count += 1
else:
count -= 1
if count == 0:
majority_elem = array[i]
count = 1
i += 1
count = 0
for elem in array:
if elem == majority_elem:
count += 1
if count > (len(array) / 2):
return True, majority_elem
else:
return False, -1
# Test run
print find_majority_elem([1,1,2,0,2,3,0,1,2,1,3,1])
print find_majority_elem([1,2,3,4,3,5,3,3,1,3,3,3,5])
|
#-------------------------------------------------------------------------------
# Author: NTalukdar
#
# Created: 30-01-2014
# Copyright: (c) NTalukdar 2014
#-------------------------------------------------------------------------------
def max_subarray(arr):
max_sofar = 0
max_ending_here = 0
for i in arr:
max_ending_here = max(0, max_ending_here + i)
max_sofar = max(max_sofar, max_ending_here)
print(max_sofar)
def main():
max_subarray([0, -1, -2 , 3, -1, -1,3])
if __name__ == '__main__':
main()
|
#-------------------------------------------------------------------------------
# Name: quicksort
# Purpose:
#
# Author: NTalukdar
#
# Created: 27-01-2014
# Copyright: (c) NTalukdar 2014
#-------------------------------------------------------------------------------
def quicksort(array, start, end):
if len(array) <= 1:
return
pivotindex = start + int((end - start + 1) / 2)
pivotel = array[pivotindex]
temp = array[end]
array[end] = pivotel
array[pivotindex] = temp
i = start
pivotindex = start
while i < end:
if array[i] <= pivotel:
temp = array[i]
array[i] = array[pivotindex]
array[pivotindex] = temp
pivotindex = pivotindex + 1
i = i + 1
temp = array[end]
array[end] = array[pivotindex]
array[pivotindex] = temp
if pivotindex - start > 1:
quicksort(array, start, pivotindex - 1)
if end -pivotindex > 1:
quicksort(array , pivotindex + 1, end)
#example run of the quicksort
def main():
array = [100, 34, 3,1,3,4,0,67,78]
quicksort(array, 0, len(array) - 1)
print(array)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.