blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d5b65c0ca0fc84a09f17f172404072d108c52afb | yuyaxiong/interveiw_algorithm | /剑指offer/和为S的连续正数序列.py | 849 | 3.546875 | 4 | """
输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。
例如:输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以打印出3个连续
序列1-5,4-6和7-8。
"""
class Solution(object):
def find_continuous_sequence(self, sum):
small, bigger = 1, 2
while small < bigger:
if (small + bigger) * (bigger - small+1) / 2 == sum:
self.print_num(small, bigger)
bigger += 1
elif (small + bigger) * (bigger - small+1) / 2 > sum:
small += 1
else:
bigger += 1
def print_num(self, small, bigger):
strings = ''
for n in range(small, bigger+1):
strings += '%s, ' % n
print(strings)
if __name__ == '__main__':
s = Solution()
s.find_continuous_sequence(15) |
e9745a6d2620ea9d036316d094c55b46be30bbeb | yuyaxiong/interveiw_algorithm | /LeetCode/链表双指针/234.py | 1,251 | 3.6875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 234.回文链表
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
n_list = []
while head is not None:
n_list.append(head.val)
head = head.next
print(n_list)
i, j = 0, len(n_list)-1
status = True
while i < j:
if n_list[i] != n_list[j]:
status = False
break
else:
i +=1
j -= 1
return status
class Solution1:
def isPalindrome(self, head: ListNode) -> bool:
p_head = head
pre_node = ListNode(p_head.val)
p_head = p_head.next
while p_head is not None:
node = ListNode(p_head.val)
node.next = pre_node
pre_node = node
p_head = p_head.next
status = True
while pre_node is not None and head is not None:
if pre_node.val == head.val:
pre_node = pre_node.next
head = head.next
else:
status = False
break
return status
|
7d2fd46534fca8d061e10b0ea73727c96631d14b | yuyaxiong/interveiw_algorithm | /剑指offer/第一个只出现一次的字符.py | 609 | 3.71875 | 4 | """
第一个只出现一次的字符。
在字符串中找出第一个只出现一次的字符。如输入:"abaccdeff",则输出"b"
"""
class Solution(object):
def first_not_repeating(self, pStrings):
if pStrings is None:
return None
s_count = {}
for s in pStrings:
if s_count.get(s) is None:
s_count[s] = 1
else:
s_count[s] += 1
for s in pStrings:
if s_count[s] == 1:
return s
if __name__ == '__main__':
s = Solution()
print(s.first_not_repeating("abaccdeff"))
|
79e0143f69a52b4379d644978551f76a90726e0c | yuyaxiong/interveiw_algorithm | /LeetCode/链表双指针/141.py | 607 | 3.84375 | 4 | # Definition for singly-linked list.
from typing import Optional
# 141.环形链表
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow, fast = head, head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
if __name__ == "__main__":
head_list = [-21,10,17,8,4,26,5,35,33,-7,-16,27,-12,6,29,-12,5,9,20,14,14,2,13,-24,21,23,-21,5] |
6a9bab008e394d48679ea4ed304c4dbe8c42ef55 | yuyaxiong/interveiw_algorithm | /LeetCode/链表双指针/21.py | 796 | 3.921875 | 4 | # Definition for singly-linked list.
# 21.合并两个有序链表
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head = ListNode()
p_head = head
while list1 is not None and list2 is not None:
if list1.val < list2.val:
head.next = list1
list1 = list1.next
else:
head.next = list2
list2 = list2.next
head = head.next
if list1 is not None:
head.next = list1
if list2 is not None:
head.next = list2
return p_head.next |
9f74d1a7787bddd889b1abb1f786edca3b769d81 | yuyaxiong/interveiw_algorithm | /剑指offer/正则表达式匹配.py | 1,455 | 3.515625 | 4 | """
请实现一个函数用来匹配包含'.'和'*'的正则表达式。
模式中的字符'.'表示任意一个字符,而'*'表示它前面的
字符可以出现任意次(含0次)。在本题中,匹配是指字符串
的所有所有字符匹配整个模式。例如,字符串"aaa"与模式
"a.a"和"ab*ac*a"匹配,但与"aa.a"和"ab*a"均不匹配。
"""
class Solution(object):
def match(self, strings, pattern):
if strings is None or pattern is None:
return False
return self.match_core(strings, pattern)
def match_core(self, strings, pattern):
if len(strings) == 0 and len(pattern) == 0:
return True
if len(strings) != 0 and len(pattern) == 0:
return False
if len(pattern) >= 2 and pattern[1] == '*':
if pattern[0] == strings[0] or (pattern[0] == '.' and len(strings) != 0):
# parttern[0] 在string[0]中出现1次, 出现N次
return self.match_core(strings[1:], pattern[2:]) or self.match_core(strings[1:], pattern)
else:
#pattern[0] 在string[0]中出现 出现0次
return self.match_core(strings, pattern[2:])
if (strings[0] == pattern[0]) or (pattern[0] == '.' and len(strings) != 0):
return self.match_core(strings[1:], pattern[1:])
return False
if __name__ == '__main__':
s = Solution()
print(s.match('aaa', 'ab*a'))
|
ef92a4e1ebdf637dc387c96ba210fcaa95b7ffde | yuyaxiong/interveiw_algorithm | /剑指offer/二叉树的深度.py | 1,525 | 4.15625 | 4 | """
输入一颗二叉树的根节点,求该树的深度。从根节点到叶节点一次经过的节点(含根,叶节点)形成树的一条路径,
最长路径的长度为树的深度。
5
3 7
2 8
1
"""
class BinaryTree(object):
def __init__(self):
self.value = None
self.left = None
self.right = None
class Solution(object):
def tree_depth(self, pRoot):
depth = 0
current = 0
return self.depth_help(pRoot, depth, current)
def depth_help(self, pRoot, depth, current):
if pRoot is None:
return depth
current += 1
depth = max(depth, current)
depth = self.depth_help(pRoot.left, depth, current)
depth = self.depth_help(pRoot.right, depth, current)
return depth
class Solution1(object):
def tree_depth(self, pRoot):
if pRoot is None:
return 0
left = self.tree_depth(pRoot.left)
right = self.tree_depth(pRoot.right)
return max(left, right) + 1
if __name__ == '__main__':
pRoot = BinaryTree()
pRoot.value = 5
pRoot.left = BinaryTree()
pRoot.left.value = 3
pl = pRoot.left
pRoot.right = BinaryTree()
pRoot.right.value = 7
pr = pRoot.right
pl.left = BinaryTree()
pl.right = BinaryTree()
pr.left = BinaryTree()
pr.right = BinaryTree()
pl.left.value = 2
pl.right.value = 4
# pr.left.value =
pr.right.value = 8
s = Solution1()
print(s.tree_depth(pRoot)) |
effff8cdf0de849a58edd641191a5c94c2b24f45 | yuyaxiong/interveiw_algorithm | /LeetCode/二分搜索/35.py | 529 | 3.6875 | 4 |
# 35. 搜索插入位置
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return self.findN(nums, target, 0, len(nums)-1)
def findN(self, nums, target, s, e):
if s > e:
return s
mid = int((s + e)/2)
if nums[mid] == target:
return mid
elif nums[mid] > target:
return self.findN( nums,target, s, mid-1)
elif nums[mid] < target:
return self.findN(nums, target, mid+1, e)
|
3a4131cff2a2fa57137ffcdecb2b51d0bb884098 | yuyaxiong/interveiw_algorithm | /剑指offer/数组中数值和下表相等的元素.py | 1,590 | 3.796875 | 4 | """
数组中数值和下标相等的元素
假设一个单调递增的数组里的每个元素都是整数并且是唯一的。
请编程实现一个函数,找出数组中任意一个数值等于其下标的元素。
例如:在数组[-3, -1, 1, 3, 5]
"""
class Solution(object):
def get_num_same_as_index(self, num, length):
if num is None or length <= 0:
return -1
left = 0
right = length -1
while left <= right:
mid = (left + right) // 2
if num[mid] == mid:
return mid
if num[mid] > mid:
right = mid -1
else:
left = mid + 1
return -1
class Solution1(object):
def get_num_same_as_index(self, num, length, s, e):
if s > e:
return -1
mid = (s + e) //2
if nList1[mid] == mid:
return mid
elif num[mid] > mid:
e = mid -1
else:
s = mid + 1
return self.get_num_same_as_index(num , length, s, e)
class Solution3(object):
def get_idx(self, nList, n):
left, right = 0, len(nList)-1
while left < right:
mid = (left + right) // 2
if nList[mid] > n:
right = mid -1
elif nList[mid] < n:
left = mid + 1
else:
return mid
return left
if __name__ == '__main__':
nList1 = [-3, -1, 1, 3, 5]
s = Solution3()
# print(s.get_num_same_as_index(nList1, len(nList1), 0,len(nList1)-1))
print(s.get_idx(nList1, 2)) |
295269c2e2f17f0aa0dbd9e75ddbdd60e240128c | yuyaxiong/interveiw_algorithm | /剑指offer/合并两个排序的链表.py | 1,538 | 3.8125 | 4 | """
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
例如, 输入图3.11中的链表1和链表2,则合并之后的升序链表如链表3所示。
1->3->5->7
2->4->6->8
1->2->3->4->5->6->7->8
"""
class ListNode(object):
def __init__(self):
self.value = None
self.next = None
class Solution(object):
def merge_list(self, pHead1, pHead2):
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
pHead = ListNode()
pNode = pHead
while pHead1 is not None and pHead2 is not None:
if pHead1.value > pHead2.value:
pNode.next = pHead2
pNode = pNode.next
pHead2 = pHead.next
else:
pNode.next = pHead1
pNode = pNode.next
pHead1 = pHead1.next
if pHead1 is not None:
pNode.next = pHead1
if pHead2 is not None:
pNode.next = pHead2
return pHead.next
class Solution1(object):
def merge(self, pHead1, pHead2):
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
pMergeHead = None
if pHead1.value < pHead2.value:
pMergeHead = pHead1
pMergeHead.next= self.merge(pHead1.next, pHead2)
else:
pMergeHead = pHead2
pMergeHead.next = self.merge(pHead1, pHead2.next)
return pMergeHead
|
6da2c66f141939606b9833e15c2a9628ee342864 | yuyaxiong/interveiw_algorithm | /LeetCode/二分搜索/1101.py | 1,177 | 3.546875 | 4 | from typing import List
# 1011. 在 D 天内送达包裹的能力
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
max_val = sum(weights)
min_val = max(weights)
return self.carrayWeight(weights, min_val, max_val, days)
def carrayWeight(self, weights, s, e, days):
if s == e:
return s
mid = (s + e) // 2
if self.carrayDays(weights, mid) > days:
return self.carrayWeight(weights, mid + 1, e, days)
else:
return self.carrayWeight(weights, s, mid, days)
def carrayDays(self, weights, limitWeight):
days = 0
cumWeight = 0
for w in weights:
if cumWeight + w > limitWeight:
days += 1
cumWeight = w
elif cumWeight + w == limitWeight:
days += 1
cumWeight = 0
else:
cumWeight += w
if cumWeight != 0:
days += 1
return days
if __name__ == "__main__":
s = Solution()
weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
limitWeight = 11
print(s.carrayDays(weights, limitWeight)) |
a0c5d2ce5d084e464205eedc1e753fcb97dcc463 | yuyaxiong/interveiw_algorithm | /剑指offer/两个链表的第一个公共节点.py | 2,125 | 3.5625 | 4 | """
输入两个链表,找出它们的第一个公共节点。
1->2->3->6->7
4->5->6->7
"""
class ListNode(object):
def __init__(self):
self.value = None
self.next = None
class Solution(object):
def find_first_common_node(self, pHead1, pHead2):
pList1, pList2 = [], []
while pHead1.next is not None:
pList1.append(pHead1)
pHead1 = pHead1.next
while pHead2.next is not None:
pList2.append(pHead2)
pHead2 = pHead2.next
p1, p2 = pList1.pop(), pList2.pop()
last = None
while p1 == p2:
last = p1
p1 = pList1.pop()
p2 = pList2.pop()
return last
class Solution1(object):
def find_first_common_node(self, pHead1, pHead2):
p1, p2 = pHead1, pHead2
counter1 = 0
counter2 = 0
while pHead1.next is not None:
counter1 += 1
pHead1 = pHead1.next
while pHead2.next is not None:
counter2 += 1
pHead2 = pHead2.next
if counter1 > counter2:
while counter1 - counter2 > 0:
counter1 -= 1
p1 = p1.next
elif counter1 < counter2:
while counter2 - counter1 > 0:
counter2 -= 1
p2 = p2.next
while p1 != p2:
p1 = p1.next
p2 = p2.next
return p1
if __name__ == '__main__':
pHead1 = ListNode()
pHead1.value = 1
pHead1.next = ListNode()
pHead1.next.value = 2
pHead1.next.next = ListNode()
pHead1.next.next.value = 3
pHead1.next.next.next = ListNode()
pHead1.next.next.next.value = 6
pHead1.next.next.next.next = ListNode()
pHead1.next.next.next.next.value = 7
pHead2 = ListNode()
pHead2.value = 4
pHead2.next = ListNode()
pHead2.next.value = 5
pHead2.next.next = pHead1.next.next.next
s = Solution()
node = s.find_first_common_node(pHead1, pHead2)
s1 = Solution1()
node1 = s1.find_first_common_node(pHead1, pHead2)
print(node.value)
print(node1.value)
|
1e9fd34c7a9f795ae1b750675d98f51a72c448c9 | yuyaxiong/interveiw_algorithm | /LeetCode/回溯算法/698.py | 1,886 | 3.609375 | 4 | #698. 划分为k个相等的子集
# leetcode 暴力搜索会超时
from typing import List
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
if k > len(nums):
return False
sum_val = sum(nums)
if sum_val % k != 0:
return False
used_list = [False for _ in nums]
target = sum_val/k
return self.backtrack(k, 0, nums, 0, used_list, target)
def backtrack(self, k, bucket, nums, start, used_list, target):
status = False
if k == 0:
status = True
return status
if bucket == target:
return self.backtrack(k -1, 0, nums, 0, used_list, target)
for i in range(start, len(nums)):
if used_list[i]:
continue
if nums[i] + bucket > target:
continue
used_list[i] = True
bucket += nums[i]
if self.backtrack(k, bucket, nums, i+1, used_list, target):
status = True
return status
used_list[i] = False
bucket -= nums[i]
return False
def testCase():
nums = [3,9,4,5,8,8,7,9,3,6,2,10,10,4,10,2]
k = 10
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
def testCase1():
nums = [10,5,5,4,3,6,6,7,6,8,6,3,4,5,3,7]
k = 8
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
def testCase2():
nums = [4,3,2,3,5,2,1]
k = 4
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
def testCase3():
nums = [3522,181,521,515,304,123,2512,312,922,407,146,1932,4037,2646,3871,269]
k = 5
sol = Solution()
ret = sol.canPartitionKSubsets(nums, k)
print(ret)
if __name__ == "__main__":
# testCase()
# testCase1()
# testCase2()
testCase3()
|
b9b1cb636e5e6168dbd58feb3f1266251d2abb7a | yuyaxiong/interveiw_algorithm | /剑指offer/二叉搜索树的后续遍历序列.py | 1,194 | 3.765625 | 4 | """
输入一个整数数组,判断该数组是否是某二叉搜索树的后续遍历结果。如果是则返回True,否则返回False。
假设输入的数组的任意两个数字都互不相同。例如,输入数组(5,7,6,9,11,10,8),则返回True,
因为这个整数序列是图4.9二叉搜索树的后续遍历结果。如果输入的数组是(7,4,6,5),则由于没有哪
颗二叉搜索树的后续遍历结果是这个序列,因此返回False。
8
6 10
5 7 9 11
"""
class Solution(object):
def verify_sequence_of_BST(self, nList):
if len(nList) == 0:
return True
root = nList[-1]
mid = 0
for idx, n in enumerate(nList):
if n >= root:
mid = idx
break
left, right = nList[:mid], nList[mid:-1]
for n in right:
if n < root:
return False
return self.verify_sequence_of_BST(left) and self.verify_sequence_of_BST(right)
if __name__ == '__main__':
s = Solution()
# nList = [5, 7, 6,9, 11, 10, 8]
nList = [7, 4, 6, 5]
print(s.verify_sequence_of_BST(nList))
|
accb77819a60ed86e64f5bf268f99662e8d40d48 | yuyaxiong/interveiw_algorithm | /剑指offer/之字形打印二叉树.py | 1,661 | 3.875 | 4 | """
请实现一个函数按照之字型顺序定二叉树,即第一行按照从左到右的顺序打印,
第二层按照从右到左的顺序打印,第三行按照从左到右的顺序打印,其他行依次类推。
例如,按之字形打印图4.8中二叉树的结构
8
| |
6 10
|| ||
5 7 9 11
"""
class BinaryTree(object):
def __init__(self):
self.value = None
self.left = None
self.right = None
class Solution(object):
# 需要NList是个栈
def print_bt(self, nList, depth):
if len(nList) == 0:
return
tmp = []
strings = ''
for node in nList:
strings += '%s\t' % node.value
if depth % 2 == 1:
if node.left is not None:
tmp.append(node.left)
if node.right is not None:
tmp.append(node.right)
else:
if node.right is not None:
tmp.append(node.right)
if node.left is not None:
tmp.append(node.left)
depth += 1
print(strings)
print('\n')
self.print_bt(tmp[::-1], depth)
if __name__ == '__main__':
pRoot = BinaryTree()
pRoot.value = 8
pRoot.left = BinaryTree()
pRoot.right = BinaryTree()
pRoot.left.value = 6
pRoot.right.value = 10
pl = pRoot.left
pr = pRoot.right
pl.left = BinaryTree()
pl.right = BinaryTree()
pr.left = BinaryTree()
pr.right = BinaryTree()
pl.left.value = 5
pl.right.value = 7
pr.left.value = 9
pr.right.value = 11
s = Solution()
s.print_bt([pRoot], 1) |
951af0dad234a397cadd2839c7695ee9397803ba | yuyaxiong/interveiw_algorithm | /LeetCode/数据结构设计/380.py | 1,412 | 3.828125 | 4 |
# 380. O(1) 时间插入、删除和获取随机元素
import random
class RandomizedSet:
def __init__(self):
self.nums = []
self.valToIdx = dict()
def insert(self, val: int) -> bool:
if self.valToIdx.get(val) is not None:
return False
self.valToIdx[val] = len(self.nums)
self.nums.append(val)
return True
def remove(self, val: int) -> bool:
if self.valToIdx.get(val) is None:
return False
idx = self.valToIdx.get(val)
last_val = self.nums[-1]
self.valToIdx[last_val] = idx
self.nums[idx] = last_val
self.nums.pop()
del self.valToIdx[val]
return True
def getRandom(self) -> int:
return self.nums[random.randint(0, len(self.nums)-1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
def testCase():
rs_sol = RandomizedSet()
# ret = [rs_sol.insert(1), rs_sol.remove(2), rs_sol.insert(2), rs_sol.getRandom(), rs_sol.remove(1), rs_sol.insert(2), rs_sol.getRandom()]
ret = [rs_sol.insert(0), rs_sol.insert(1), rs_sol.remove(0), rs_sol.insert(2), rs_sol.remove(1), rs_sol.getRandom()]
# print(rs_sol.nums)
# print(rs_sol.valToIdx)
print(ret)
if __name__ == "__main__":
testCase()
|
0de9cbdec2ec0cb42e75376e9df8a989cfd4b405 | jougs/m4light | /espmpylight/animate.py | 850 | 3.9375 | 4 |
def map(val, in_min, in_max, out_min, out_max):
"""map a value val from one interval (in) to another (out)"""
return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
def smoothstep(t, t_offs, duration, scale):
"""Function to fade smoothly from one value to another.
The canonical smoothstep equation is 3x^2-2x^3.
See https://en.wikipedia.org/wiki/Smoothstep for details.
Here, we use t - t_offs divided by duration as x to shift the
transition by t_offs into the future and stretch it to length
duration. We then multiply by it by scale to get the desired
height.
Please note that scale might be negative
"""
if t <= t_offs: return 0
if t >= t_offs + duration: return scale
t -= t_offs
t_div_d = t / duration
return (3 * t_div_d**2 - 2 * t_div_d**3) * scale
|
99f0223f2acdc0fba4a59939980b3f1e11781344 | MappingSystem/bonding | /Polygons.py | 4,144 | 4.3125 | 4 | import math
class Polygons:
""" This is the superclass."""
def number_of_sides(self):
return 0
def area(self):
return 0
def perimeter(self):
return 0
class Triangle(Polygons):
""" Models the properties of a triangle """
def number_of_sides(self):
return 3
def area(self, base, height):
return 1 / 2 * base * height
def perimeter(self, a, b, c):
if a + b > c:
return a + b + c
else:
return "Invalid input: make sure a + b > c"
def herons_formula(self, a, b, c):
""" Alternative to finding area of triangle. """
# s = semi perimeter
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
return area
class Rhombus(Polygons):
"""" Models the properties of a Rhombus."""
def number_of_sides(self):
return 4
def area(self, p, q):
""" p is a Diagonal and q is a Diagonal.
The formula is A = p*q/2. """
return p * q / 2
def perimeter(self, a):
return 4 * a
class Pentagon(Polygons):
""" Models the properties of a regular Pentagon. """
def number_of_sides(self):
return 5
def area(self, a):
""" This is area of regular pentagon"""
return 1 / 4 * math.sqrt(5 * (5 + 2 * math.sqrt(5))) * a ** 2
def perimeter(self, a):
return 5 * a
class Hexagon(Polygons):
""" Models the properties of a regular Hexagon. """
def number_of_sides(self):
return 6
def area(self, a):
""" Models area of a regular hexagon."""
return (3 * math.sqrt(3) / 2) * a ** 2
def perimeter(self, a):
return 6 * a
class Heptagon(Polygons):
""" Models the properties of a regular Heptagon. """
def number_of_sides(self):
return 7
def area(self, a):
""" Area for regular heptagon. """
# convert degrees into radians.
deg = 180 * math.pi / 180
return (7 / 4 * a ** 2) * 1 / math.tan(deg / 7)
def perimeter(self, a):
return 7 * a
class Octagon(Polygons):
""" Models the properties of a regular Octagon. """
def number_of_sides(self):
return 8
"""" Area of regular Octagon. """
def area(self, a):
return 2 * (1 + math.sqrt(2)) * a ** 2
def perimeter(self, a):
return 8 * a
class Nonagon(Polygons):
"""" Models the properties of a regular Nonagon. """
def number_of_sides(self):
return 9
def area(self, a):
""" Models area of a regular Nonagon. """
# Python expects radians, so convert 180 to radians
deg = 180 * math.pi / 180
return 9 / 4 * a ** 2 * 1 / math.tan(deg / 9)
def perimeter(self, a):
return 9 * a
class Decagon(Polygons):
"""" Models the properties of a regular Decagon. """
def number_of_sides(self):
return 10
""" Area of a regular Decagon. """
def area(self, a):
return 5 / 2 * a ** 2 * math.sqrt(5 + 2 * math.sqrt(5))
def perimeter(self, a):
return 10 * a
# Below is some test cases.
tri = Triangle()
print("Triangle Area:", tri.area(5, 10))
print("Herons formula:", tri.herons_formula(5, 4, 3))
print("Perimeter:", tri.perimeter(20, 71, 90))
print("-----------------")
rho = Rhombus()
print("Rhombus Area:", rho.area(12.3, 83.9))
print("Perimeter:", rho.perimeter(5))
print("-----------------")
pent = Pentagon()
print("Pentagon Area:", pent.area(5))
print("Perimeter:", pent.perimeter(7.5))
print("-----------------")
hex = Hexagon()
print("Hexagon Area:", hex.area(5))
print("Perimeter:", hex.perimeter(11.25))
print("-----------------")
hep = Heptagon()
print("Heptagon Area:", hep.area(10))
print("Perimeter:", hep.perimeter(8))
print("-----------------")
oct = Octagon()
print("Octagon Area:", oct.area(10))
print("Perimeter:", oct.perimeter(7))
print("-----------------")
non = Nonagon()
print("Nonagon Area:", non.area(6))
print("Perimeter", non.perimeter(5))
print("-----------------")
dec = Decagon()
print("Decagon Area:", dec.area(10))
print(dec.perimeter(11.25))
|
48554cbfb4796689c3fd8410f975c4c3177b156c | marloncard/Terminal-trader | /sql_generic.py | 597 | 3.65625 | 4 | #!/usr/bin/env python3
def create_insert(table_name, columns):
columnlist = ", ".join(columns)
qmarks = ", ".join("?" for val in columns)
SQL = """ INSERT INTO {table_name} ({columnlist})
VALUES ({qumarks})
"""
return SQL.format(table_name=table_name,
columnlist=columnlist,
qmarks=qmarks)
if __name__ == '__main__':
print(create_insert("employees",
["first_name",
"last_name",
"employee_id",
"birth_date"])) |
894c5bd3426c7d33e4c4876940b788c490ad43e9 | CrocodileCroco/LPassGen | /LPassGen.py | 985 | 3.515625 | 4 | from tkinter import *
from functools import partial
import random
root = Tk()
genrated = ''
def passgen():
genrated = ''
charlimitset = 0
charlimitset = int(entry_chlimit.get())
charlimitloop = charlimitset
print(charlimitset)
path = 'passletters.txt'
letterlist = open(path,'r')
ltrlist = letterlist.read().splitlines()
print(ltrlist)
while charlimitloop > 0 :
genrated += random.choice(ltrlist)
charlimitloop = charlimitloop - 1
entry_name.delete('0',END)
entry_name.insert('0',genrated)
print(genrated)
text = genrated
label = Label(root, text='')
entry_name = Entry(root, textvariable=text)
longtext = Label(root, text='Character Limit:')
entry_chlimit = Entry(root)
button = Button(root, text='Generate', command=passgen)
entry_name.grid(column=0, row=1)
longtext.grid(column=0, row=3)
entry_chlimit.grid(column=0, row=4)
button.grid(column=0, row=5)
root.iconbitmap('iconefulltaille.ico')
root.mainloop() |
23093aeec021225ca268b13ff12cd6cb6fdc0f7d | task-master98/ReinforcementLearning | /Environments/Trial.py | 1,096 | 3.65625 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
pos = pygame.Vector2(100, 100)
clock = pygame.time.Clock()
# speed of your player
speed = 2
# key bindings
move_map = {pygame.K_LEFT: pygame.Vector2(-1, 0),
pygame.K_RIGHT: pygame.Vector2(1, 0),
pygame.K_UP: pygame.Vector2(0, -1),
pygame.K_DOWN: pygame.Vector2(0, 1)}
while run:
for e in pygame.event.get():
if e.type == pygame.QUIT: run = False
screen.fill((30, 30, 30))
# draw player, but convert position to integers first
pygame.draw.circle(screen, pygame.Color('dodgerblue'), [int(x) for x in pos], 10)
pygame.display.flip()
# determine movement vector
pressed = pygame.key.get_pressed()
move_vector = pygame.Vector2(0, 0)
for m in (move_map[key] for key in move_map if pressed[key]):
move_vector += m
# normalize movement vector if necessary
if move_vector.length() > 0:
move_vector.normalize_ip()
# apply speed to movement vector
move_vector *= speed
# update position of player
pos += move_vector
clock.tick(60) |
7d65a6e0fef25b6351e3b8add6fb79846520bf8c | task-master98/ReinforcementLearning | /DQN_models.py | 6,102 | 3.65625 | 4 | """
@Author: Ishaan Roy
#####################
Deep Q-Learning Algorithm
Framework: Pytorch
Task: Using Reinforcement Learning to play Space Invaders
File contains: Models required for Space Invaders game
#TODO
----------------------------------
=> Implement the Agent class: same file?
=> Write the main loop
=> Move helper function to utils.py
=> Add comments to explain the action space
----------------------------------
Change Log
-----------------------------------
=> Initial Commit: Built the model
-> Deep Convolution network: model tested
=> Implementation of RL agent
-> RL agent not tested yet; to be tested in the main loop
=> Helper function to plot rewards written
-----------------------------------
"""
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
class DeepQNetwork(nn.Module):
def __init__(self, lr, ):
super(DeepQNetwork, self).__init__()
self.lr = lr
self.conv_1 = nn.Conv2d(1, 32, kernel_size=8, stride=4, padding=1)
self.conv_2 = nn.Conv2d(32, 64, 4, stride=2)
self.conv_3 = nn.Conv2d(64, 128, 3)
self.conv = nn.Sequential(
self.conv_1,
nn.ReLU(),
self.conv_2,
nn.ReLU(),
self.conv_3,
nn.ReLU(),
nn.Flatten()
)
self.fc_1 = nn.Linear(128*19*8, 512)
self.fc_2 = nn.Linear(512, 64)
self.fc_3 = nn.Linear(64, 6)
self.linear = nn.Sequential(
self.fc_1,
nn.ReLU(),
self.fc_2,
self.fc_3
)
self.optimizer = optim.RMSprop(self.parameters(), lr=self.lr)
self.loss = nn.MSELoss()
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
self.to(self.device)
def forward(self, observation):
observation = torch.Tensor(observation).to(self.device)
observation = observation.view(-1, 1, 185, 95)
feature_map = self.conv(observation)
actions = self.linear(feature_map)
return actions
class Agent:
def __init__(self, gamma, epsilon, lr,
maxMemsize, epsEnd=0.05,
replace=10000, action_space=list(range(6))):
## Parameters of Policy
self.GAMMA = gamma
self.EPSILON = epsilon
self.EPS_END = epsEnd
self.actionSpace = action_space
self.maxMemsize = maxMemsize
self.replace_target_cnt = replace
## RL tools
self.steps = 0
self.learn_step_counter = 0
self.memory = []
self.memCntr = 0
## Models
self.Q_eval = DeepQNetwork(lr=lr)
self.Q_target = DeepQNetwork(lr=lr)
def storeTransitions(self, old_state, action,
reward, new_state):
if self.memCntr < self.maxMemsize:
self.memory.append([old_state, action, reward, new_state])
else:
self.memory[self.memCntr%self.maxMemsize] = [old_state, action, reward, new_state]
self.memCntr += 1
def chooseAction(self, observation):
np.random.seed(42)
rand = np.random.random()
actions = self.Q_eval(observation)
if rand < 1 - self.EPSILON:
action = torch.argmax(actions[1]).item()
else:
action = np.random.choice(self.actionSpace)
self.steps += 1
return action
def learn(self, batch_size):
self.Q_eval.optimizer.zero_grad()
if (self.replace_target_cnt is not None and
self.learn_step_counter % self.replace_target_cnt == 0):
self.Q_target.load_state_dict(self.Q_eval.state_dict())
## Sampling from the memory bank (randomly)
if self.memCntr + batch_size < self.maxMemsize:
memStart = int(np.random.choice(range(self.memCntr)))
else:
memStart = int(np.random.choice(range(self.memCntr-batch_size-1)))
miniBatch = self.memory[memStart:memStart+batch_size]
memory = np.array(miniBatch)
Qpred = self.Q_eval.forward(list(memory[:, 0])).to(self.Q_eval.device)
Qnext = self.Q_target.forward(list(memory[:, 3])).to(self.Q_eval.device)
maxA = torch.argmax(Qnext, dim=1).to(self.Q_eval.device)
rewards = torch.Tensor(list(memory[:, 2])).to(self.Q_eval.device)
Qtargets = Qpred
Qtargets[:, maxA] = rewards + self.GAMMA*torch.max(Qnext[1])
if self.steps > 500:
if self.EPSILON - 1e-4 < self.EPS_END:
self.EPSILON -= 1e-4
else:
self.EPSILON = self.EPS_END
loss = self.Q_eval.loss(Qtargets, Qpred).to(self.Q_eval.device)
loss.backward()
self.Q_eval.optimizer.step()
self.learn_step_counter += 1
def plotLearning(x, scores, epsilons, filename=None, lines=None):
fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax.plot(x, epsilons, color="C0")
ax.set_xlabel("Game", color="C0")
ax.set_ylabel("Epsilon", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
N = len(scores)
running_avg = np.empty(N)
for t in range(N):
running_avg[t] = np.mean(scores[max(0, t-20):(t+1)])
ax2.scatter(x, running_avg, color="C1")
#ax2.xaxis.tick_top()
ax2.axes.get_xaxis().set_visible(False)
ax2.yaxis.tick_right()
#ax2.set_xlabel('x label 2', color="C1")
ax2.set_ylabel('Score', color="C1")
#ax2.xaxis.set_label_position('top')
ax2.yaxis.set_label_position('right')
#ax2.tick_params(axis='x', colors="C1")
ax2.tick_params(axis='y', colors="C1")
if lines is not None:
for line in lines:
plt.axvline(x=line)
return fig
def test_model():
img = torch.randn((185, 95))
model = DeepQNetwork(0.003)
print(model.forward(img).shape)
if __name__ == "__main__":
test_model()
|
2af2bc15f109cb2de4718386edc0f50162fd4f77 | TheReformedAlloy/py-class-examples | /clock.py | 2,077 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 11:50:38 2019
@author: Clint Mooney
"""
class Clock():
# Override Built-In Class Functions:
def __init__(self, hour=0, minutes=0, seconds=0):
self.hour = self.checkInput(hour, 0)
self.minutes = self.checkInput(minutes, 0)
self.seconds = self.checkInput(seconds, 0)
def __str__(self):
return "The time is {}:{}:{}".format(self.hour, self.minutes, self.seconds)
def __repr__(self):
return self.__str__()
# Override arithmetic operators:
def __add__(self, to_be_added):
if type(to_be_added) == Clock:
new_hour = self.hour + to_be_added.hour
new_mins = self.minutes + to_be_added.minutes
new_secs = self.seconds + to_be_added.seconds
return Clock(new_hour, new_mins, new_secs)
else:
new_hour = self.checkInput(to_be_added, 0)
return Clock(new_hour, self.minutes, self.seconds)
# Make addition communicative:
def __radd__(self, to_be_added):
return self.__add__(to_be_added)
# Function to streamline input management (Ensures input results in an int):
def checkInput(self, input_time, default):
if type(input_time) == int:
return input_time
elif type(input_time) == str:
if input_time.isdigit():
return int(input_time)
else:
print("Argument provided not a number. Setting affected input to '{}.'".format(default))
return default
elif type(input_time) == float:
return int(input_time)
else:
print("Argument provided not a number. Setting affected input to '{}.'".format(default))
return default
new_clock = Clock(5, 14, 30)
print(new_clock)
print(str(new_clock))
print(new_clock + Clock(1, 1, 10))
print(new_clock + 1)
print(new_clock + 1.0)
print(new_clock + "1")
print(new_clock + "Bop")
print(1 + new_clock)
print(1.0 + new_clock)
print("1" + new_clock)
print("Bop" + new_clock) |
ce6eceac86ea4bb06541e5fc214aed8a1aad6fa7 | amitrajhello/PythonEmcTraining1 | /inheritenceAndOverridding.py | 453 | 3.75 | 4 | from inheritence import Person
class Employee(Person):
"""Employee class extends to class Person"""
def __init__(self, eid, fn, ln):
self.eid = eid
super().__init__(fn, ln) # invoke the overridden method
def get_info(self):
print('employee id:', self.eid)
super().get_info()
if __name__ == '__main__': # calling main method
e = Employee('3242', 'Amit', 'Singh')
e.get_info()
|
3991d59a1de29307e9b9333585e679c7bd3e679b | amitrajhello/PythonEmcTraining1 | /listdemo.py | 135 | 3.6875 | 4 | # Defining a list
items = [2.2, 'pam', 3.4, 'allen', .98, 'nick', 1, 2, 3, 4]
print(items)
print(len(items))
print(type(items))
|
77c9f7f18798917cbee5e7fc4044c3a70d73bb33 | amitrajhello/PythonEmcTraining1 | /psguessme.py | 611 | 4.1875 | 4 | """The player will be given 10 chances to guess a number, and when player gives a input, then he should get a feedback
that his number was lesser or greater than the random number """
import random
key = random.randint(1, 1000)
x = 1
while x <= 10:
user_input = int(input('Give a random number to play the game: '))
if user_input > key:
print('your input is more than the number, please try again')
elif user_input < key:
print('your input is less than the number')
elif user_input == key:
print('Congratulations! you won!')
break
x += 1
|
fca48a33c99466a9c500454c2579590cd4390e5c | amitrajhello/PythonEmcTraining1 | /listRedundentEntries.py | 221 | 3.6875 | 4 | # eliminates duplicate entries
duplicates = [2.2, 3.3, 5.3, 2.2, 3.3, 5.3, 2.2, 3.3, 5.3]
print(set(duplicates)) # list type casted to set
uniq = list(set(duplicates)) # set type casted to list
print(uniq)
|
e1b50fc8a71d3bee42a9b8c02faf0128aa8e079e | amitrajhello/PythonEmcTraining1 | /iterator.py | 222 | 4 | 4 | s = 'root:x:0:0:root:/root>/root:/bin/bash'
for temp in s:
print(temp, '->', ord(temp)) # ord() is the function to print ASCII value of the character
for temp in reversed(s):
print(temp, '->', ord(temp))
|
9698a1b04749f46eb3735fe780e55880f48a2eab | amitrajhello/PythonEmcTraining1 | /inheritence.py | 419 | 3.953125 | 4 | class Person:
"""base class"""
def __init__(self, fn, ln): # self takes the reference of the current object
self.fn = fn # sets the first name of the current object
self.ln = ln
def get_info(self):
print('first name:', self.fn)
print('last name:', self.ln)
if __name__ == '__main__': # calling main method
p = Person('amit', 'raj')
p.get_info()
|
7095cca9d20fa2b15bb9afeb78cdc3af05164109 | Nosfer123/python_study | /HW_2_1.py | 494 | 4.09375 | 4 | def prepare_num(num):
while num <= 0:
print("Number should be more than zero")
num = prepare_num(int(input("Enter number: ")))
return num
def Fizz_Buzz(num):
if num % 3 == 0 and num % 5 == 0:
return "Fizz Buzz"
elif num % 3 == 0:
return "Fizz"
elif num % 5 == 0:
return "Buzz"
else:
return str(num)
def fizz_buzz_result():
num = prepare_num(int(input("Enter number: ")))
print(Fizz_Buzz(num))
fizz_buzz_result() |
84a2a5d8fd8de28f506ed71dc3634e5c815bdfbf | Nosfer123/python_study | /HW_4_1_2.py | 220 | 3.8125 | 4 | col = (input('Number of columns: '))
row = (input('Number of lines: '))
text = (input('What do you want to print? '))
def print_text():
for dummy_n in range (int(row)):
print (text*(int(col)))
print_text() |
9a9945bfd0b2e0998e4b25597fe15f6d93873245 | Nosfer123/python_study | /HW_8_1.py | 373 | 3.859375 | 4 | def is_concatenation(dictionary, key):
if not key:
return True
idx = 1
while idx <= len(key):
if key[0:idx] in dictionary and is_concatenation(dictionary, key[idx:]):
return True
idx += 1
return False
test_dict = ["world", "hello", "super"]
print(test_dict)
print("helloworld", is_concatenation(test_dict, 'helloworld')) |
0cfdbc8f80c62aa9c12efbdad639aef979675fb0 | Nosfer123/python_study | /HW_2_2.py | 212 | 3.875 | 4 | def number():
num = int(input("Enter number: "))
for number_in_list in range (num+1):
if number_in_list % 2 == 0 and number_in_list > 0:
print (number_in_list*number_in_list)
number() |
1d3bcad1638a46ff2e58a96439ed9d3a1d029510 | Nosfer123/python_study | /lesson3_9.py | 256 | 3.875 | 4 | def print_square(n):
for i in range(n):
for k in range(n):
print('*', end='')
print()
while True:
num = int(input('N: '))
print_square(num)
print()
is_done = input('One more?')
if is_done:
break |
5d0fbd2af9084c9b6b54c1b42b39dc144b0081ad | Nosfer123/python_study | /HW_3_1.py | 327 | 3.859375 | 4 | from random import randint
def dice_throw():
return randint(1,6)
def dice_sum():
counter = 0
while True:
dice1 = dice_throw()
dice2 = dice_throw()
counter += 1
if dice1+dice2 == 8:
print(dice1, dice2, counter)
break
for dummy_i in range(10):
dice_sum() |
2245707d7083ce60cbb00f9be02150a36806fba4 | SeptivianaSavitri/tugasakhir | /NER_Ika_Lib/WikiSplitType.py | 2,603 | 3.640625 | 4 | ####################################################################################
# WikiSplitType.py
# @Author: Septiviana Savitri
# @Last update: 8 Februari 2017
# Fasilkom Universitas Indonesia
#
# Objective: To filter the sentences so that meets certain criterias
# input:
# - a file contains all sentences --> output of Data3_SentencerNLTK.py
# output: a text file contains all selected sentences that meet certain criterias:
# - sentence has words > minimal number of words in a sentence
# - sentence has uppercase> minimal number of uppercase in a sentence
####################################################################################
import codecs
from function import writeListofStringToFile
##########################################################################
# M A I N
##########################################################################
#set the input and output file
folder = "dbpedia-new/original/"
#input = "dbpedia-new/cleansing/nyoba.txt"
input = "input.txt"
output1 = folder + "person.txt"
output2 = folder + "place.txt"
output3 = folder + "organization.txt"
######################### begin ################################
inputFile = codecs.open(input, 'r', errors='ignore')
flines = inputFile.readlines()
newListPerson = []
newListPlace = []
newListOrg = []
count = 1
for k in flines:
if k[0] == "<":
arrLine = k.split(" ")
arrType = arrLine[2].split("/")
arrValue = arrLine[0].split("/")
dataType = arrType[len(arrType) - 1]
dataValue = arrValue[len(arrValue) - 1]
if (dataType[:-1] == "Person") and (arrType[2]=="dbpedia.org"):
x = codecs.decode(dataValue[:-1], 'unicode_escape')
#x = dataValue[:-1]
# if count==90:
# print(x.replace('_',' '))
newListPerson.append(x.replace('_',' '))
elif (dataType[:-1] == "Place") and (arrType[2]=="dbpedia.org"):
x = codecs.decode(dataValue[:-1], 'unicode_escape')
newListPlace.append(x.replace('_',' '))
elif (dataType[:-1] == "Organisation") and (arrType[2]=="dbpedia.org") :
x = codecs.decode(dataValue[:-1], 'unicode_escape')
newListOrg.append(x.replace('_',' '))
count += 1
inputFile.close()
writeListofStringToFile(newListPerson, output1)
writeListofStringToFile(newListPlace, output2)
writeListofStringToFile(newListOrg, output3)
############################################################################
# End of file
############################################################################
|
e62ac4c465dacd0c5694a65ce2c3185c64e05419 | smritisingh26/AndrewNGPy | /LinearRegression.py | 1,064 | 3.625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
data = pd.read_csv('ex1data1.txt', header = None)
X = data.iloc[:,0]
y = data.iloc[:,1]
m = len(y)
print(data.head())
plt.scatter(X, y)
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
#plt.show()
X = X[:,np.newaxis]
y = y[:,np.newaxis]
theta = np.zeros([2,1])
iterations = 1500
alpha = 0.01
ones = np.ones((m,1))
X = np.hstack((ones, X))
def computeCost(X, y, theta):
temp = np.dot(X, theta) - y
return np.sum(np.power(temp, 2)) / (2*m)
J = computeCost(X, y, theta)
#print(J)
def gradientDescent(X, y, theta, alpha, iterations):
for _ in range(iterations):
temp = np.dot(X, theta) - y
temp = np.dot(X.T, temp)
theta = theta - (alpha/m) * temp
return theta
theta = gradientDescent(X, y, theta, alpha, iterations)
print(theta)
J = computeCost(X, y, theta)
print(J)
plt.scatter(X[:,1], y)
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.plot(X[:,1], np.dot(X, theta))
plt.show()
|
67e83fd9552337c410780198f08039044c925965 | Mickey248/ai-tensorflow-bootcamp | /pycharm/venv/list_cheat_sheet.py | 1,062 | 4.3125 | 4 | # Empty list
list1 = []
list1 = ['mouse', [2, 4, 6], ['a']]
print(list1)
# How to access elements in list
list2 = ['p','r','o','b','l','e','m']
print(list2[4])
print(list1[1][1])
# slicing in a list
list2 = ['p','r','o','b','l','e','m']
print(list2[:-5])
#List id mutable !!!!!
odd = [2, 4, 6, 8]
odd[0] = 1
print(odd)
odd[1:4] =[3 ,5 ,7]
print(odd)
#append and extend can be also done in list
odd.append(9)
print(odd)
odd.extend([11, 13])
print(odd)
# Insert an element into a list
odd = [1, 9]
odd.insert(1, 3)
print(odd)
odd[2:2] =[5,7]
print(odd)
# How to delete an element from a list?
del odd[0]
print(odd)
#remove and pop are the same as in array !!!
# Clear
odd.clear()
print(odd)
#Sort a list
numbers = [1, 5, 2, 3]
numbers.sort()
print(numbers)
# An elegant way to create a list
pow2 = [2 ** x for x in range(10)]
print(pow2)
pow2 = [2 ** x for x in range(10) if x > 5]
print(pow2)
# Membership in list
print(2 in pow2)
print(2 not in pow2)
# Iterate through in a list
for fruit in ['apple','banana','orange']:
print('i like', fruit) |
09c67af03e8d3a2219d072ac4e78b3bab4d19481 | BryanISC/b1 | /numeros primos recursivos.py | 350 | 3.875 | 4 | def numeroPrimoRecursivo(numero, c):
if(numero % c == 0 and numero > 2):
return False;
elif(c > numero / 2):
return True;
else:
return numeroPrimoRecursivo( numero, c+1 );
numero = int(input("\ningrese un numero: "))
if(numeroPrimoRecursivo(numero, 2) ):
print ("el numero es primo")
else:
print ("el numero no es primo") |
4eba19ae037e7b6ba9334c7c1d4099102c17ab5c | mycks45/DS | /Selection_sort.py | 405 | 3.734375 | 4 | def selection_sort(arr):
length = len(arr)
i = 0
while i < (length-1):
j = i+1
while j<length:
if arr[i]>arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
j +=1
i +=1
return arr
arr = [5,3,78,212,43,12,34,23,56,32,41,45,24,64,57,97,35]
print(arr)
result = selection_sort(arr)
print(result) |
c4f6294bcdffb315f9bb02e63810024ac79e97cf | mycks45/DS | /string encode.py | 429 | 3.59375 | 4 |
def encode(message, key):
new_message = ''
for i in range(len(message)):
ascii_val = ord(message[i])
val = ascii_val + key
if val >122:
k = (122-val)
k = k % 26
new_message += chr(96 + k)
else:
new_message += chr(val)
return new_message
message = 'hai'
key = 3
print(message)
mess = encode(message, key)
print(mess)
|
a744a47b4a4954fd8a718ca27e2bd3fcc799c084 | KMFleischer/PyEarthScience | /Transition_examples_NCL_to_PyNGL/xy/TRANS_bar_chart.py | 3,076 | 3.703125 | 4 | #
# File:
# TRANS_bar_chart.py
#
# Synopsis:
# Illustrates how to create a bar chart plot
#
# Categories:
# bar chart plots
# xy plot
#
# Author:
# Karin Meier-Fleischer, based on NCL example
#
# Date of initial publication:
# September 2018
#
# Description:
# This example shows how to create a bar chart plot.
#
# Effects illustrated:
# o Drawing a bar chart plot
# o Customizing a x-axis labels
#
# Output:
# A single visualization is produced.
#
# Notes: The data for this example can be downloaded from
# http://www.ncl.ucar.edu/Document/Manuals/NCL_User_Guide/Data/
#
'''
Transition Guide Python Example: TRANS_bar_chart.py
- bar chart
- x-labels
18-09-03 kmf
'''
from __future__ import print_function
import numpy as np
import Ngl
#-- function get_bar returns coordinates of a bar
def get_bar(x,y,dx,ymin,bar_width_perc=0.6):
dxp = (dx * bar_width_perc)/2.
xbar = np.array([x-dxp, x+dxp, x+dxp, x-dxp, x-dxp])
ybar = np.array([ ymin, ymin, y, y, ymin])
return xbar,ybar
#--------------
# MAIN
#--------------
#-- create random x- and y-values
x = np.arange(1,13,1)
y = [8,5,11,6,9,9,6,2,4,1,3,3]
dx = min(x[1:-1]-x[0:-2]) #-- distance between x-values
#-- define color and x-axis labels
color = 'blue'
xlabels = ["Jan","Feb","Mar","Apr","May","Jun", \
"Jul","Aug","Sep","Oct","Nov","Dec"]#-- x-axis labels
#-- open a workstation
wkres = Ngl.Resources() #-- generate an resources object for workstation
wks_type = "png" #-- output type of workstation
wks = Ngl.open_wks(wks_type,"plot_TRANS_bar_chart_py",wkres)
#-- set resources
res = Ngl.Resources() #-- generate an res object for plot
res.nglFrame = False #-- don't advance frame
res.nglPointTickmarksOutward = True #-- point tickmarks outward
res.tiXAxisString = "x-values" #-- x-axis title
res.tiYAxisString = "y-values" #-- y-axis title
res.tmXBMode = "Explicit" #-- define bottom x-axis values and labels
res.tmXBValues = x #-- x-axis values
res.tmXBLabels = xlabels #-- x-axis labels
res.tmXBLabelFontHeightF = 0.012 #-- bottom x-axis font size
res.trXMinF = 0.0 #-- x-axis min value
res.trXMaxF = 13.0 #-- x-axis max value
res.trYMinF = 0.0 #-- y-axis min value
res.trYMaxF = 12.0 #-- y-axis max value
#-- bar resources
barres = Ngl.Resources() #-- resource list for bars
barres.gsFillColor = color #-- set bar color
#-- loop through each y point and create bar
for i in range(len(y)):
xbar,ybar = get_bar(x[i], y[i], dx, res.trXMinF, 0.3)
plot = Ngl.xy(wks, xbar, ybar, res)
Ngl.polygon(wks, plot, xbar, ybar, barres) #-- filled bar
Ngl.frame(wks) #-- advance frame
Ngl.end()
|
b5f7437fcb49452d5a9214af6a79e48cdb121b49 | minhnguyenphuonghoang/AlgorithmEveryday | /EverydayCoding/0019_validate_symbols.py | 2,114 | 3.78125 | 4 | from BenchmarkUtil import benchmark_util
"""Day 53: Validate Symbols
We're provided a string like the following that is inclusive of the following symbols:
parentheses '()'
brackets '[]', and
curly braces '{}'.
Can you write a function that will check if these symbol pairings in the string follow these below conditions?
They are correctly ordered
They contain the correct pairings
They are both of the same kind in a pair
For example, () is valid. (( is not. Similarly, {{[]}} is valid. [[}} is not.
"""
NO_OF_SOLUTION = 1
def solution_01(s):
hash_map = {
'parentheses': 0,
'brackets': 0,
'curly_braces': 0
}
for a_char in s:
if a_char == "{":
hash_map['curly_braces'] += 1
elif a_char == "}":
hash_map['curly_braces'] -= 1
if hash_map['curly_braces'] < 0:
return False
elif a_char == "(":
hash_map['parentheses'] += 1
elif a_char == ")":
hash_map['parentheses'] -= 1
if hash_map['parentheses'] < 0:
return False
elif a_char == "[":
hash_map['brackets'] += 1
else:
hash_map['brackets'] -= 1
if hash_map['parentheses'] < 0:
return False
for key in hash_map:
if hash_map[key] < 0:
return False
return True
def solution_02(s):
# Todo:
# the above solution is too bad. I must think another way to solve this problem
return s
tests = ["{{[]}}", "[[}}", "{()}[]()"]
results = [True, False, True]
for i in range(len(tests)):
for sln_idx in range(1, NO_OF_SOLUTION + 1):
curr_time = benchmark_util.get_current_time()
result = eval("solution_0{}".format(sln_idx))(tests[i])
elapse_time = benchmark_util.get_elapse_time(curr_time)
# debug:
print("SOLUTION: {} took {} nanoseconds to finish test.".format(sln_idx, elapse_time))
assert result == results[i], \
"Solution {} had wrong result {}, expecting {}".format("solution_0{}".format(sln_idx), result, results[i])
|
e1fcd85babfd1971ba7bdb4a9a733ad22b250438 | minhnguyenphuonghoang/AlgorithmEveryday | /EverydayCoding/0022_find_prime_number.py | 1,265 | 3.609375 | 4 | from BenchmarkUtil import benchmark_util
"""Write a function to find a prime number of a given number
Prime number is the number that can only divide by 1 and itself.
For example: 1, 2, 3, 5, 7, 13, etc are prime numbers.
"""
from math import sqrt
NO_OF_SOLUTION = 2
def solution_01(s):
if s < 1:
return False
for i in range(2, s):
if s % i == 0:
return False
return True
def solution_02(s):
if s < 1:
return False
for i in range(2, int(sqrt(s))+1):
if s % i == 0:
return False
return True
tests = [-3, 0, 1, 2, 13, 15, 89, 100, 100003, 111111113]
results = [False, False, True, True, True, False, True, False, True, True]
for i in range(len(tests)):
for sln_idx in range(1, NO_OF_SOLUTION + 1):
curr_time = benchmark_util.get_current_time()
result = eval("solution_0{}".format(sln_idx))(tests[i])
elapse_time = benchmark_util.get_elapse_time(curr_time)
# debug:
print("SOLUTION: {} took {} nanoseconds to finish test with input {}".format(sln_idx, elapse_time, tests[i]))
assert result == results[i], \
"Solution {} had wrong result {}, expecting {}".format("solution_0{}".format(sln_idx), result, results[i])
|
b7b283a77a4c9135f5cdd904dccb4594bc58eecb | minhnguyenphuonghoang/AlgorithmEveryday | /Algorithms/greatest_common_denominator.py | 160 | 3.5625 | 4 | def euclid_alg(num1, num2):
while num2 != 0:
temp = num1
num1 = num2
num2 = temp % num2
return num1
print(euclid_alg(20, 8))
|
c7bdf0cbdf287f5d15d4d229aa787e9f3e42523d | caramelmelmel/50.003-ESC_g_3_8 | /react-app/src/test/fuzzing/testFuzzInvalidPassword.py | 3,099 | 3.65625 | 4 | import random
import string
import re
# This test allows us to check if the passwords that we expect to fail will actually fail the regex
def fuzz(valid):
# Use various methods to fuzz randomly
for i in range(3):
trim_bool = random.randint(0, 1)
duplicate_bool = random.randint(0, 1)
swap_bool = random.randint(0, 1)
temp_valid = valid
if (trim_bool == 1):
valid = trim(valid)
if (len(valid) == 0):
choices = ["badskjabsdjk", "051288324969", "USABASKDAU", "&*!#*!^*@&"]
valid = random.choice(choices)
valid = duplicate(valid)
valid = swap(valid)
if (duplicate_bool == 1):
valid = duplicate(valid)
if (swap_bool == 1):
valid = swap(valid)
return valid
def trim(valid):
# Trim front or back of random length
length_valid = len(valid)
random_length = random.randint(1, int(length_valid/2)+1)
trim_bool = random.randint(0, 1)
if (trim_bool == 1):
output = valid[random_length:]
else:
output = valid[:random_length]
return output
def swap(valid):
# Swap characters at random
for i in range(len(valid)):
char = valid[i]
random_index = random.randint(0, len(valid)-1)
swap_char = valid[random_index]
if (random_index > i):
start = valid[0:i]
middle = valid[i+1:random_index]
end = valid[random_index+1:]
valid = start + swap_char + middle + char + end
elif (random_index < i):
start = valid[0:random_index]
middle = valid[random_index+1:i]
end = valid[i+1:]
valid = start + char + middle + swap_char + end
else:
continue
output = valid
return output
def duplicate(valid):
# Duplicate substrings in valid and add to the end of valid
first_index = random.randint(0, len(valid)-1)
if (first_index == len(valid)-1):
return valid
else:
second_index = random.randint(first_index, len(valid)-1)
if (first_index != second_index):
substring = valid[first_index:second_index]
valid = valid + substring
return valid
def verify_regex(input):
# Verify if the input passes the regex
regex = r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$"
regex_obj = re.compile(regex)
check = (regex_obj.search(input) != None)
return check
# This test allows us to check if the passwords that we expect to fail will actually fail the regex
check = False
while (check == False):
valid_passwords = ['abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'my spaced password', 'CapitalAndSmallButNoSymbol', 'C@PIT@L@NDSYMBOL!', '$mall$mbol@', '1234567890', 'CapitalAndSmallButNoSymbol123456789', 'C@PIT@L@NDSYMBOL!0987654321', '$mall$mbol@0192837465',
'abcde456fg213hijklmno987pqrst0uvwxyz', 'ABCD4EFGH583IJKLM62NOP1QRS70TUVW9XYZ']
valid = random.choice(valid_passwords)
output = fuzz(valid)
check = verify_regex(output)
print("Output:")
print(output) |
c9f325732c1a2732646deadb25c9132f3dcae649 | samir-0711/Area_of_a_circle | /Area.py | 734 | 4.5625 | 5 | import math
import turtle
# create screen
screen = turtle.Screen()
# take input from screen
r = float(screen.textinput("Area of Circle", "Enter the radius of the circle in meter: "))
# draw circle of radius r
t=turtle.Turtle()
t.fillcolor('orange')
t.begin_fill()
t.circle(r)
t.end_fill()
turtle.penup()
# calculate area
area = math.pi * r * r
# color,style and position of text
turtle.color('deep pink')
style = ('Courier', 10, 'italic')
turtle.setpos(-20,-20)
# display area of circle with radius r
turtle.write(f"Area of the circle with radius {r} meter is {area} meter^2", font=style, align='center')
# hide the turtle symbol
turtle.hideturtle()
# don't close the screen untill click on close
turtle.getscreen()._root.mainloop()
|
e1b281dbeb0452fa235c5bdfcd3827a44ebd4167 | Kristjan-O-Ragnarsson/FORR3RR05DU-verk2 | /sam.py | 155 | 3.625 | 4 | n = int(input())
m = int(input())
def funct(n, m):
if m == 0:
return n
else:
return funct(m, n % m)
print(funct(n, m))
|
933775bd8c8e1c702aa390bc16ba389db0287649 | Serpinex3/rx-anon | /anon/configuration/configuration_reader.py | 1,448 | 3.5625 | 4 | """Module containing corresponding code for reading a configuration file"""
import logging
from yaml import Loader, load
from .configuration import Configuration
logger = logging.getLogger(__name__)
class ConfigurationReader:
"""Class responsible for parsing a yaml config file and initializing a configuration"""
def read(self, yaml_resource):
"""
Reads a yaml config file and returns the corresponding configuration object
Parameters
----------
yaml_resource: (str, Path)
The configuration file.
Returns
-------
Configuration
The corresponding configuration object
"""
with open(yaml_resource, 'r') as file:
doc = load(file, Loader=Loader)
logger.info("Reading configuration from %s", yaml_resource)
config = Configuration()
# Make keys lower case to match columns in lower case
config.attributes = {attr.lower(): v for attr, v in doc['attributes'].items()}
if "entities" in doc: # Overwrite default
config.entities = doc['entities']
if "parameters" in doc: # Overwrite default
config.parameters = doc['parameters']
if "nlp" in doc: # Overwrite default
config.nlp = doc['nlp']
logger.debug("Using the following configuration:\n%s", config)
return config
|
c7ac2454578be3c3497759f156f7bb9f57415433 | dawid86/PythonLearning | /Ex7/ex7.py | 513 | 4.6875 | 5 | # Use words.txt as the file name
# Write a program that prompts for a file name,
# then opens that file and reads through the file,
# and print the contents of the file in upper case.
# Use the file words.txt to produce the output below.
fname = input("Enter file name: ")
fhand = open(fname)
# fread = fhand.read()
# print(fread.upper())
#for line in fread:
# line = line.rstrip()
# line = fread.upper()
# print(line)
for line in fhand:
line = line.rstrip()
line = line.upper()
print(line)
|
acc900f9c4e91d452dccec4c9220142fd32dbd9b | AndersonCamargo20/Exercicios_python | /ex012.py | 423 | 3.765625 | 4 | print('========== DESAFIO 012 ==========')
print('LEIA O VALOR DE UM PRODUTO E INFORME O VALOR FINAL COM DESCONTO APÓS LER A PORCENTAGEM')
valor = float(input('Informe o valor do produto: R$ '))
porcent = float(input('Informe o valor da porcentagem: '))
desconto = (valor * porcent) / 100
print('O produto custava R${}, na promoção com desconto de {}%, vai custar R${}'.format(valor, porcent, round(valor-desconto,2)))
|
e514f618a3ffe08a2610ea780cf7efff8314c1fa | AndersonCamargo20/Exercicios_python | /ex032.py | 548 | 4 | 4 | print('========== DESAFIO 032 ==========')
print('LEIA UM ANO E DIGA SE ELE É BISEXTO OU NÃO')
from calendar import isleap
from datetime import datetime
now = datetime.now()
ano = int(input('Informe um ano para o calculo (Caso queira o ano atual informe ->> 0 <<-): '))
if ano == 0:
if isleap(now.year):
print('O ano atual É BISEXTO')
else:
print('O ano atual NÃO é BISEXTO')
else:
if isleap(ano):
print('O ano {} É BISEXTO'.format(ano))
else:
print('O ano {} NÃO é BISEXTO'.format(ano))
|
d05af16be3b0e6715bdc528234604e6b515b641e | AndersonCamargo20/Exercicios_python | /ex007.py | 359 | 3.953125 | 4 | print('========== DESAFIO 007 ==========')
print('FAÇA UM PROGRAMA QUE FAÇA A MÉDIA ARITIMÉTICA ENTRE TRÊS NOTAS\n')
n1 = float(input("Informe a 1º nota: "))
n2 = float(input("Informe a 2º nota: "))
n3 = float(input("Informe a 3º nota: "))
soma = n1 + n2 + n3
media = soma / 3
print("A média das notas ({}, {} , {} ) é: {}".format(n1,n2,n3,media)) |
5373667470e39443ab1191f2f523e0dc43742638 | AndersonCamargo20/Exercicios_python | /ex013.py | 489 | 3.796875 | 4 | print('========== DESAFIO 013 ==========')
print('LEIA UM SALÁRIO E A PORCENTAGEM DE AUMENTA E CALCULA O VALOR DO SALÁRIO COM AUMENTO')
salario_old = float(input('Informe o salário do funcionário: R$ '))
porcent = float(input('Informe a porcentagem de aumento: '))
aumento = (salario_old * porcent) / 100
salario_new = salario_old + aumento
print('Um funcionário ganhava R${}, mas com {}% de aumento, o seu novo salário é R${}'.format(salario_old, porcent, round(salario_new, 2)))
|
aa7452cbe83e2b4f61db6f28d244f4f4b19cb481 | AndersonCamargo20/Exercicios_python | /ex019.py | 451 | 3.84375 | 4 | print('========== DESAFIO 019 ==========')
print('LENDO O NOME DE 4 ALUNOS SORTEI UM DELES DA CHAMADA PARA APAGAR O QUADRO')
import random
list_alunos = []
num_alunos = int(input('Quantos alunos deseja salvar: '))
random = random.randint(0,num_alunos - 1)
print(random)
for i in range(0, num_alunos):
list_alunos.append(input('Informe o nome do {}º Aluno: '.format(i + 1)))
print('\n\nO aluno escolhido foi {}.'.format(list_alunos[random]))
|
acd10df184f13bb7c54a6f4a5abac553127b27af | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_create_grade_calculator.py | 830 | 4.25 | 4 | #Python code for the Grade
#Calculate program in action
#Creating a dictionary which
#consists of the student name,
#assignment result test results
#And their respective lab results
def grade(student_grade):
name=student_grade['name']
assignment_marks=student_grade['assignment']
assignment_score=sum(assignment_marks)/len(assignment_marks)
test_marks=student_grade['test']
test_score=sum(test_marks)/len(test_marks)
lab_marks=student_grade['lab']
lab_score=sum(lab_marks)/len(lab_marks)
score=0.1*assignment_score+0.7*test_score+0.2*lab_score
if score>=90 :return 'A'
elif score>=80 :return 'B'
elif score>=70 :return 'C'
elif score>=60 :return 'D'
jack={"name":"Jack Frost","assignment":[80,50,40,20],"test":[75,75],"lab":[78,20,77,20]}
x=grade(jack)
print(x)
|
968829ff7ec07aabb3dedfb89e390334b9b9ee57 | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_check_if_a_string_is_palindrome_or_not.py | 450 | 4.3125 | 4 | print("This is python program to check if a string is palindrome or not")
string=input("Enter a string to check if it is palindrome or not")
l=len(string)
def isPalindrome(string):
for i in range(0,int(len(string)/2)):
if string[i]==string[l-i-1]:
flag=0
continue
else :
flag=1
return flag
ans=isPalindrome(string)
if ans==0:
print("Yes")
else:
print("No")
|
06132de9f0dd0dfbf3138ead23bd4a936ca4a70a | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_interchange_first_and_last_elements_in_a_list_using_pop.py | 277 | 4.125 | 4 | print("This is python program to swap first and last element using swap")
def swapList(newList):
first=newList.pop(0)
last=newList.pop(-1)
newList.insert(0,last)
newList.append(first)
return newList
newList=[12,35,9,56,24]
print(swapList(newList))
|
2f2fe636142d1859b49195d440d60e6641a45bc9 | inwk6312fall2018/programmingtask2-hanishreddy999 | /crime.py | 685 | 3.515625 | 4 |
from tabulate import tabulate #to print the output in table format
def crime_list(a): #function definition
file=open(a,"r") #open csv file in read mode
c1=dict()
c2=dict()
lst1=[]
lst2=[]
for line in file:
line.strip()
for lines in line.split(','):
lst1.append(lines[-1])
lst2.append(lines[-2])
for b in lst1:
if b not in c1:
c1[b]=1
else:
c1[b]=c1[b]+1
for c in lst2:
if c not in c2:
c2[c]=1
else:
c2[c]=c2[c]+1
print(tabulate(headers=['CrimeType', 'CrimeId', 'CrimeCount']))
for k1,v in c1.items():
for k2,v in c2.items():
x=[k1,k2,v] #tabular format
print(tabulate(x))
file_name="Crime.csv"
crime_list(file_name)
|
4c84102e21f49b710bd9bd292fc816700382f811 | basile-henry/projecteuler | /Python/problem60.py | 631 | 3.59375 | 4 | import primes2 as primes
def isPairPrime(a, b):
return primes.isPrime(int(str(a) + str(b))) and primes.isPrime(int(str(b) + str(a)))
def test(l, n):
return all([isPairPrime(a, n) for a in l])
def next(l, limit):
i = primes.getIndexOf(l[-1]) + 1
p = primes.getPrimeAt(i)
while not test(l, p):
i+=1
p = primes.getPrimeAt(i)
if p > limit:
return 0
return primes.getPrimeAt(i)
def buildList(start, limit):
ret = [start]
while ret[-1] > 0:
ret.append(next(ret, limit))
return ret[:-1]
i = 0
p = []
print primes.primes[-1]
while len(p) < 5:
p = buildList(primes.getPrimeAt(i), 10000)
print p, sum(p)
i+=1 |
509351177f6f9f41f47f5508a9da26c761202806 | jrihds/pdat | /code/generators.py | 265 | 4 | 4 | #!/usr/bin/env python3
"""Generator objects."""
colours = ['blue', 'red', 'green', 'yellow']
def e_count(_list):
"""Count how many e's in a string."""
for element in _list:
yield element.count('e')
for value in e_count(colours):
print(value)
|
10880d4e6f4462c7ae0af751dd4b68b5530680fe | Mitchell55/NumericalAnalysis | /Numerical_analysis/Forward_Euler.py | 673 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 20:19:09 2019
@author: Mitchell Krouss
Method: Forward Euler
"""
import math
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sc
a = 0
b = 1
h = 0.0001
n = int((b - a) / h)
def f(x,y):
return 998*x - 1998*y
def g(x,y):
return 1000*x - 2000*y
t = np.arange(a, b+h, h)
y = np.zeros(len(t))
x = np.zeros(len(t))
y[0] = 2
x[0] = 1
for i in range(1, len(t)):
y[i] = y[i-1] + h*f(x[i-1],y[i-1])
x[i] = x[i-1] + h*g(x[i-1],y[i-1])
print(x[1000])
print(y[1000])
print(t[1000])
plt.plot(t,y)
plt.plot(t,x)
plt.legend(['y(t)','x(t)'])
plt.xlabel('t')
plt.title('Forward Euler')
plt.show()
|
3067c55a4f898411564a58baff539cd41f94a4db | amiune/projecteuler | /Problem054.py | 4,338 | 3.625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
cardValue = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'T':10,'J':11,'Q':12,'K':13,'A':14}
# In[74]:
def getHighestCardValue(cards):
cards = sorted(cards, key=lambda card: cardValue[card[0]])
return cardValue[cards[-1][0]]
# In[86]:
def maxOfAKind(cards):
maxOfAKind = []
counter = 1
cards = sorted(cards, key=lambda card: cardValue[card[0]])
for i in range(1,5):
if int(cardValue[cards[i][0]]) == int(cardValue[cards[i-1][0]]): counter += 1
else:
maxOfAKind.append((counter, int(cardValue[cards[i-1][0]])))
counter = 1
maxOfAKind.append((counter, int(cardValue[cards[4][0]])))
maxOfAKind = sorted(maxOfAKind)
return maxOfAKind[-1], maxOfAKind[-2]
# In[87]:
def onePair(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 2 and max2[0] == 1: return True, max1, max2
return False, max1, max2
# In[88]:
def twoPairs(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 2 and max2[0] == 2: return True, max1, max2
return False, max1, max2
# In[89]:
def threeOfAKind(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 3: return True, max1, max2
return False, max1, max2
# In[90]:
def straight(cards):
cards = sorted(cards, key=lambda card: cardValue[card[0]])
for i in range(1,5):
if int(cardValue[cards[i][0]]) != int(cardValue[cards[i-1][0]]) + 1: return False
return True
# In[91]:
def flush(cards):
for i in range(1,5):
if cards[i][1] != cards[i-1][1]: return False
return True
# In[92]:
def fullHouse(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 3 and max2[0] == 2: return True, max1, max2
return False, max1, max2
# In[93]:
def fourOfAKind(cards):
max1, max2 = maxOfAKind(cards)
if max1[0] == 4: return True, max1, max2
return False, max1, max2
# In[94]:
def straightFlush(cards):
if flush(cards) and straight(cards): return True
return False
# In[95]:
def getHandValue(cards):
if straightFlush(cards):
return 9_000_000 + getHighestCardValue(cards)
isFourOfAKind, max1, _ = fourOfAKind(cards)
if isFourOfAKind:
return 8_000_000 + max1[1]
isFullHouse, max1, max2 = fullHouse(cards)
if isFullHouse:
return 7_000_000 + max1[1]*100 + max2[1]
if flush(cards):
return 6_000_000 + getHighestCardValue(cards)
if straight(cards):
return 5_000_000 + getHighestCardValue(cards)
isThreeOfAKind, max1, max2 = threeOfAKind(cards)
if isThreeOfAKind:
return 4_000_000 + max1[1]*100 + max2[1]
isTwoPairs, max1, max2 = twoPairs(cards)
if isTwoPairs:
return 3_000_000 + max1[1]*100 + max2[1]
isOnePair, max1, max2 = onePair(cards)
if isOnePair:
return 2_000_000 + max1[1]*100 + max2[1]
return 1_000_000 + getHighestCardValue(cards)
# In[97]:
player1Wins = 0
with open("p054_poker.txt", "r") as f:
lineCounter = 0
for line in f:
hand1 = line[:14].split()
hand2 = line[15:29].split()
hand1Value = getHandValue(hand1)
hand2Value = getHandValue(hand2)
winner = 0
if hand1Value > hand2Value:
winner = 1
elif hand1Value < hand2Value:
winner = 2
else:
hand1 = sorted(hand1, key=lambda card: cardValue[card[0]])
hand2 = sorted(hand2, key=lambda card: cardValue[card[0]])
for i in range(5):
hand1Value = getHighestCardValue(hand1[:4-i])
hand2Value = getHighestCardValue(hand2[:4-i])
if hand1Value != hand2Value:
if hand1Value > hand2Value:
winner = 1
elif hand1Value < hand2Value:
winner = 2
break
print("{}vs{} -> Player {} wins: {} vs {}".format(sorted(hand1, key=lambda card: cardValue[card[0]]),
sorted(hand2, key=lambda card: cardValue[card[0]]), winner,
hand1Value, hand2Value))
if winner == 1:
player1Wins += 1
lineCounter += 1
print(player1Wins)
# In[ ]:
# In[ ]:
|
70db04c2a239741286b2ca8e14ad4aae7d6ed462 | amiune/projecteuler | /Problem049.py | 816 | 3.953125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
def isPrime(n):
if n == 2 or n == 3: return True
if n < 2 or n%2 == 0: return False
if n < 9: return True
if n%3 == 0: return False
r = int(n**0.5)
f = 5
while f <= r:
if n % f == 0: return False
if n % (f+2) == 0: return False
f += 6
return True
# In[9]:
def isPermutation(a,b):
if len(a) == len(b):
return sorted(a) == sorted(b)
return False
# In[18]:
for n1 in range(1001,9999+1,2):
if isPrime(n1):
for diff in range(1,int(10000/3)):
if isPermutation(str(n1),str(n1+diff)) and isPermutation(str(n1),str(n1+2*diff)):
if isPrime(n1+diff) and isPrime(n1+2*diff):
print("{},{},{}".format(n1,n1+diff,n1+2*diff))
# In[ ]:
|
998cb8e31e2065edefca18de17d6d4062d3aa564 | amiune/projecteuler | /Problem009.py | 263 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import math
# In[8]:
n = 1000
for a in range(1,n-2):
for b in range(a+1, n-1):
c = math.sqrt(a*a + b*b)
if a + b + c == 1000:
print(int(a*b*c))
break
# In[ ]:
|
d57723a50878b71814f9ecdb6e7be14687e1aed9 | amiune/projecteuler | /Problem001.py | 168 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
answer = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
answer += i
print(answer)
# In[ ]:
|
0901c75662df3c0330deb4d25087868ba0693e94 | dipesh1011/NameAgeNumvalidation | /multiplicationtable.py | 360 | 4.1875 | 4 | num = input("Enter the number to calculate multiplication table:")
while(num.isdigit() == False):
print("Enter a integer number:")
num = input("Enter the number to calculate multiplication table:")
print("***************************")
print("Multiplication table of",num,"is:")
for i in range(1, 11):
res = int(num) * i
print(num,"*",i,"=",res) |
1533e4ed87eb8d3650b5bd6998224361c83f376f | fANZYo/FrenchTestPy | /frenchPhrases.py | 2,212 | 4 | 4 | # Keep your imports at the top. It's good practice as it tells anyone reading your code what the program relies on
from sys import argv, exit
from random import randint
import json
def play(data):
"""Start the game with the list of sentences provided
data -- list of sentences
"""
while True:
sentencePick = randint(0, len(data) - 1) # Pick a random sentence index
languages = list(data[sentencePick].keys()) # Dynamically pull out the list of languages for that sentence
langPick = languages[randint(0, len(languages) - 1)] # Picks a random language
languages.remove(langPick) # Remove langPick from the list of languages
for lang in languages: # Loop over the remaining languages
userAnswer = input('What is the ' + lang + ' translation of "' + data[sentencePick][langPick] + '"?\n> ')
if userAnswer == data[sentencePick][lang]:
print('Correct')
else:
print('Wrong, the answer was: "' + data[sentencePick][lang] + '"')
exit(1)
def addSentence(path):
"""Write a new sentence to a file
path -- file to amend
"""
f = open(path, 'r') # Open file in read mode
data = json.load(f) # Get the list of sentences
f.close() # Close the file
sentence = getSentence() # See function below
data.append(sentence) # Append the list of sentences with the new sentence dictionary returned by getSentence
f = open(path, 'w+') # Open and wipe the file
f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))) # Write the amended list of sentences to the file
f.close()
exit(0)
def getSentence():
"""Return a dictionary containing a sentence in different languages"""
sentence = {}
languageCount = int(input('How many languages?\n> '))
for i in range(0, languageCount):
language = input('Enter language nb ' + str(i + 1) + '\n> ')
sentence[language] = input('What is the sentence for that language?\n> ')
return sentence
if len(argv) > 2 and argv[1] == 'add': # If user entered 'python script add filename'
addSentence(argv[2])
elif len(argv) > 1: # If user entered 'python script filename'
data = json.load(open(argv[1])) # Assign the dictionary contained in the file to data
play(data)
else:
print('Syntax: [add] filename')
exit(1)
|
7b8fb7f4e7c0a339befa3619eefe77cfbb42a4f4 | Antn-Amlrc/Calendar_2020 | /day9.py | 1,707 | 3.921875 | 4 | file = open('input9.txt', "r")
lines = file.readlines()
file.close()
# PART 1
def is_the_sum_of_two_numbers(n, preambule):
for i in range(len(preambule)):
n1 = int(preambule[i])
for j in range(i+1,len(preambule)):
n2 = int(preambule[j])
if n1+n2==n:
preambule.remove(preambule[0]) # We remove the head of the list
preambule.append(n) # We add the last valid number found
return True
return False
preambule = [line[:-1] for line in lines[:25]]
invalid_number = 0
for line in lines[25:]:
invalid_number = int(line[:-1])
if not(is_the_sum_of_two_numbers(invalid_number, preambule)):
print("The following number does not have XMAS property", invalid_number)
break
# PART 2
contiguous_list = []
for index_to_start in range(len(lines)): # For each possible start
first_number = int(lines[index_to_start]) # Start number
contiguous_list.clear()
cpt_to_search = 0 # index to see following numbers
if not(first_number == invalid_number): # Will only give at least two number set
while sum(contiguous_list)<invalid_number and index_to_start+cpt_to_search<len(lines): # While sum lower than invalid number
new_number = int(lines[index_to_start+cpt_to_search])
contiguous_list.append(new_number)
cpt_to_search += 1 # We increment to go to next number
if invalid_number == sum(contiguous_list) and len(contiguous_list)>1:
encryption_weakness = min(contiguous_list)+max(contiguous_list)
print("The encryption weakness in my list is", encryption_weakness)
|
caaee5e916ac6fdee8d1cf40556b1168b1b266a5 | darsh10/HateXplain-Darsh | /Preprocess/attentionCal.py | 5,061 | 3.90625 | 4 | import numpy as np
from numpy import array, exp
###this file contain different attention mask calculation from the n masks from n annotators. In this code there are 3 annotators
#### Few helper functions to convert attention vectors in 0 to 1 scale. While softmax converts all the values such that their sum lies between 0 --> 1. Sigmoid converts each value in the vector in the range 0 -> 1.
##### We mostly use softmax
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=0)
def neg_softmax(x):
"""Compute softmax values for each sets of scores in x. Here we convert the exponentials to 1/exponentials"""
e_x = np.exp(-(x - np.max(x)))
return e_x / e_x.sum(axis=0)
def sigmoid(z):
"""Compute sigmoid values"""
g = 1 / (1 + exp(-z))
return g
##### This function is used to aggregate the attentions vectors. This has a lot of options refer to the parameters explanation for understanding each parameter.
def aggregate_attention(at_mask,row,params):
"""input: attention vectors from 2/3 annotators (at_mask), row(dataframe row), params(parameters_dict)
function: aggregate attention from different annotators.
output: aggregated attention vector"""
#### If the final label is normal or non-toxic then each value is represented by 1/len(sentences)
if(row['final_label'] in ['normal','non-toxic']):
at_mask_fin=[1/len(at_mask[0]) for x in at_mask[0]]
else:
at_mask_fin=at_mask
#### Else it will choose one of the options, where variance is added, mean is calculated, finally the vector is normalised.
if(params['type_attention']=='sigmoid'):
at_mask_fin=int(params['variance'])*at_mask_fin
at_mask_fin=np.mean(at_mask_fin,axis=0)
at_mask_fin=sigmoid(at_mask_fin)
elif (params['type_attention']=='softmax'):
at_mask_fin=int(params['variance'])*at_mask_fin
at_mask_fin=np.mean(at_mask_fin,axis=0)
at_mask_fin=softmax(at_mask_fin)
elif (params['type_attention']=='neg_softmax'):
at_mask_fin=int(params['variance'])*at_mask_fin
at_mask_fin=np.mean(at_mask_fin,axis=0)
at_mask_fin=neg_softmax(at_mask_fin)
elif(params['type_attention'] in ['raw','individual']):
pass
if(params['decay']==True):
at_mask_fin=decay(at_mask_fin,params)
return at_mask_fin
##### Decay and distribution functions.To decay the attentions left and right of the attented word. This is done to decentralise the attention to a single word.
def distribute(old_distribution, new_distribution, index, left, right,params):
window = params['window']
alpha = params['alpha']
p_value = params['p_value']
method =params['method']
reserve = alpha * old_distribution[index]
# old_distribution[index] = old_distribution[index] - reserve
if method=='additive':
for temp in range(index - left, index):
new_distribution[temp] = new_distribution[temp] + reserve/(left+right)
for temp in range(index + 1, index+right):
new_distribution[temp] = new_distribution[temp] + reserve/(left+right)
if method == 'geometric':
# we first generate the geometric distributio for the left side
temp_sum = 0.0
newprob = []
for temp in range(left):
each_prob = p_value*((1.0-p_value)**temp)
newprob.append(each_prob)
temp_sum +=each_prob
newprob = [each/temp_sum for each in newprob]
for temp in range(index - left, index):
new_distribution[temp] = new_distribution[temp] + reserve*newprob[-(temp-(index-left))-1]
# do the same thing for right, but now the order is opposite
temp_sum = 0.0
newprob = []
for temp in range(right):
each_prob = p_value*((1.0-p_value)**temp)
newprob.append(each_prob)
temp_sum +=each_prob
newprob = [each/temp_sum for each in newprob]
for temp in range(index + 1, index+right):
new_distribution[temp] = new_distribution[temp] + reserve*newprob[temp-(index + 1)]
return new_distribution
def decay(old_distribution,params):
window=params['window']
new_distribution = [0.0]*len(old_distribution)
for index in range(len(old_distribution)):
right = min(window, len(old_distribution) - index)
left = min(window, index)
new_distribution = distribute(old_distribution, new_distribution, index, left, right, params)
if(params['normalized']):
norm_distribution = []
for index in range(len(old_distribution)):
norm_distribution.append(old_distribution[index] + new_distribution[index])
tempsum = sum(norm_distribution)
new_distrbution = [each/tempsum for each in norm_distribution]
return new_distribution
|
c7a6b2bca50c23c93ab645a0be278b4a2d7830b2 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex018.py | 500 | 4.03125 | 4 | from math import(pi , cos , sin , tan , radians)
an1 = float(input('Diga o angulo: '))
an2 = (an1 * pi) / 180
# Podemos usar tambem o math: an2 = radians(an1)
# sen = (sin(radians(an1)))
sen = sin(an2)
cos = cos(an2)
tg = tan(an2)
print('')
print('{:-^30}' .format(''))
print('O SENO do angulo {} é: {:.3f}' .format(an1 , sen))
print('O COSSENO do angulo {} é: {:.3f}' .format(an1 , cos))
print('A TANGENTE do angulo {} é: {:.3f}' .format(an1 , tg))
print('{:-^30}' .format(''))
|
bcbb9151b1274e5b0b852c1cfa1db212d322f84d | JoaolSoares/CursoEmVideo_python | /Exercicios/ex004.py | 624 | 4.09375 | 4 | n1 = input('digite algo:')
print('o tipo primitivo desse valor é:', type(n1))
print('só tem espaços?', n1.isspace())
print('pode ser um numero?', n1.isnumeric())
print('é maiusulo?', n1.islower())
print('é minusculo?', n1.isupper())
print('é alfabetico?', n1.isalpha())
print('é alfanumerico?', n1.isalnum())
print('esta capitalizada(com maiusculas e minusculas)?', n1.istitle())
# Outra forma agora com a quebra de linha /n
n1 = input('digite algo')
s = type(n1)
p = n1.isspace()
n = n1.isnumeric()
print('primitive type {} \n só tem espaços? {} \n pode ser um numero? {}' .format(s , p , n))
|
9d6b6a18e003e0c7c3fca4dd0d2712f323f7cf5c | JoaolSoares/CursoEmVideo_python | /Exercicios/ex012.py | 220 | 3.65625 | 4 | d1 = float(input('Diga o desconto aplicado: '))
p1 = float(input('Diga o preço do produto: '))
desconto = (p1 * d1) / 100
print('O preço do produto com {}% de descondo ficará: {:.2f}' .format(d1 , p1 - desconto))
|
befa116c3ae0d337ea4ce41f8732d55e0c0b105a | JoaolSoares/CursoEmVideo_python | /Exercicios/ex031.py | 253 | 3.640625 | 4 | n1 = float(input('Diga quantos KM tem a sua viagem: '))
if n1 <= 200:
print('O preço da sua passagem ficara R${}' .format(n1 * 0.50))
else:
print('O preço da sua passagem ficara R${}' .format(n1 * 0.45))
print('Tenha uma boa viagem!! ;D') |
4a6e58653632be4182d5b9183938e56ea69f376c | JoaolSoares/CursoEmVideo_python | /Exercicios/ex069.py | 720 | 3.59375 | 4 | r = 's'
id18cont = mcont = f20cont = 0
# Esta sem a validação de dados...
while True:
print('--' * 15)
print('Cadastro de pessoas')
print('--' * 15)
idade = int(input('Qual a idade? '))
sex = str(input('Qual o sexo? [M/F] ')).strip().upper()[0]
print('--' * 15)
r = str(input('Quer continuar? [S/N] ')).strip().upper()[0]
if idade > 18:
id18cont += 1
if sex in 'Mm':
mcont += 1
elif sex in 'Ff' and idade < 20:
f20cont += 1
if r in 'Nn':
break
print(f'{id18cont} pessoas tem mais de 18 anos')
print(f'{mcont} Homens foram cadastrados')
print(f'{f20cont} Mulheres com menos de 20 anos foram cadastradas')
|
93a6dccf6ecbe72702504cd62cfdc54f117ee363 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex085.py | 310 | 3.625 | 4 | lista = [[], []]
for c in range(1, 8):
n1 = int(input(f'Digite o {c}º Numero: '))
if n1 % 2 == 0:
lista[0].append(n1)
else:
lista[1].append(n1)
print('\033[1;35m-+\033[m' * 18)
print(f'Numeros pares: {sorted(lista[0])}')
print(f'Numeros impares: {sorted(lista[1])}')
|
512085f8ba8507522624dd8f0ae41c5825387ce7 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex062.py | 461 | 3.78125 | 4 | pt = int(input('Diga o primeiro termo da P.A: '))
rz = int(input('Diga a tazão dessa P.A: '))
cont = 1
termo = pt
mais = 1
while mais != 0:
while cont <= 9 + mais:
print(termo, end=' - ')
termo += + rz
cont += 1
print('Finish...')
print('--' * 25)
mais = int(input('Voce quer mostras mais quantos termos? '))
print('Finish...')
print('foi finalizado mostrando no final {} termos' .format(cont))
|
8bf302e5b3c3b91e868479e2119f49f77a2b3422 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex054.py | 364 | 3.8125 | 4 | from datetime import date
cont = 0
cont2 = 0
for c in range(1, 8):
nasc = int(input('Qual o ano de nascimento da {}º pessoa? ' .format(c)))
if date.today().year - nasc >= 18:
cont += 1
else:
cont2 += 1
print('--' * 20)
print('Existem {} pessoas MAIORES de idade.\nExistem {} pessoas MENORES de idade.' .format(cont, cont2))
|
bdbd784a551a48151d15b76bdb80a49210bee853 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex089.py | 1,138 | 3.984375 | 4 | aluno = []
lista = []
res = 'S'
print('\033[1;35m--' * 15)
print(f'{"Sistema Do Colegio":^30}')
print('--' * 15, '\033[m')
print('----')
# Coleta de dados
while res in 'Ss':
aluno.append(str((input('Nome do aluno: '))))
aluno.append(float(input('Nota 1: ')))
aluno.append(float(input('Nota 2: ')))
aluno.append((aluno[1] + aluno[2]) / 2)
lista.append(aluno[:])
aluno.clear()
res = str(input('Quer continuar? [S/N] '))
print('-=' * 25)
# Tabela
print('\033[1;35mNº ALUNO NOTA')
print('-' * 25, '\033[m')
for c, a in enumerate(lista):
print(f'{c} {a[0]:<12} {a[3]}')
print('\033[1;35m-' * 25, '\033[m')
# Notas separadas dos alunos
while res != 999:
res = int(input('Nº do aluno para saber sua nota separada [999 para finalizar]: '))
if res > (len(lista) - 1) and res != 999:
print('\033[1;31mNão encontrei este aluno... Tente novamente...\033[m')
elif res != 999:
print(f'As notas do aluno {lista[res][0]} foram {lista[res][1]} e {lista[res][2]}...')
print('-=' * 25)
print('Programa Finalizado com sucesso...')
|
546907fe45b06b4c4813f9f1d193f073b7520672 | JoaolSoares/CursoEmVideo_python | /Exercicios/ex103.py | 411 | 3.671875 | 4 | def ficha(nome='<Desconhecido>', gols=0):
print(f'O jogador {nome} marcou {gols} gols no campeonato.')
n1 = input('Nome do jogador: ')
n2 = input('Gols no campeonato: ')
print('-=' * 20)
if n2.isnumeric():
n2 = int(n2)
if n1.strip() != '':
ficha(n1, n2)
else:
ficha(gols=n2)
else:
if n1.strip() != '':
ficha(nome=n1)
else:
ficha()
|
67341965a301d547ba5422c3d1e256a2f513999b | JoaolSoares/CursoEmVideo_python | /Exercicios/ex020.py | 360 | 3.5625 | 4 | from random import shuffle
a1 = input('Diga o nome de um aluno: ')
a2 = input('Diga o nome de um aluno: ')
a3 = input('Diga o nome de um aluno: ')
a4 = input('Diga o nome de um aluno: ')
lista = [a1, a2, a3, a4]
shuffle(lista)
print('')
print('{:-^70}' .format(''))
print('A ordem escolhida foi: {}' .format(lista))
print('{:-^70}' .format(''))
|
bc0e0a3075ea950cf67bc7bfe44201842624a81f | JoaolSoares/CursoEmVideo_python | /Exercicios/ex029.py | 223 | 3.71875 | 4 | n1 = int(input('Qual foi sua velocidade: '))
if n1 <= 80:
print('PARABENS! Por nao ter utrapassado o limite de 80km/h')
else:
print('ISSO NÃO FOI LEGAL! Você recebera uma multa de R${}' .format((n1 - 80) * 7)) |
fc95289439761478c89aaef10340dd1c0c149a36 | wangchengww/great-ape-Y-evolution | /palindrome_analysis/palindrome_read_depth/calculate_copy_number/Palindrome_scripts/line_up_columns.py | 4,441 | 3.609375 | 4 | #!/usr/bin/env python
import sys
def parse_columns(s):
if (".." in s):
(colLo,colHi) = s.split("..",1)
(colLo,colHi) = (int(colLo),int(colHi))
return [col-1 for col in xrange(colLo,colHi+1)]
else:
cols = s.split(",")
return [int(col)-1 for col in cols]
# commatize--
# Convert a numeric string into one with commas.
def commatize(s):
if (type(s) != str): s = str(s)
(prefix,val,suffix) = ("",s,"")
if (val.startswith("-")): (prefix,val) = ("-",val[1:])
if ("." in val):
(val,suffix) = val.split(".",1)
suffix = "." + suffix
try: int(val)
except: return s
digits = len(val)
if (digits > 3):
leader = digits % 3
chunks = []
if (leader != 0):
chunks += [val[:leader]]
chunks += [val[ix:ix+3] for ix in xrange(leader,digits,3)]
val = ",".join(chunks)
return prefix + val + suffix
spacer = " "
inSeparator = None
outSeparator = None
passComments = []
bunchExtras = None # column number after which we no longer align
rightJustify = [] # column numbers to right-justify
columnWidth = {} # map from column number to width
commas = [] # column numbers to commatize values (numeric string is assumed)
doubleSep = [] # column numbers to give a double output separator before
barSep = [] # column numbers to give a special output separator before
for arg in sys.argv[1:]:
if ("=" in arg):
argVal = arg.split("=",1)[1]
if (arg.startswith("--spacer=")):
spacer = argVal
elif (arg.startswith("--separator=")):
inSeparator = argVal
elif (arg == "--tabs"):
inSeparator = "\t"
elif (arg == "--bars"):
outSeparator = " |"
elif (arg == "--passcomments"):
passComments += ["#"]
elif (arg.startswith("--passcomments=")):
passComments += [argVal]
elif (arg.startswith("--bunch=")):
bunchExtras = int(argVal)
elif (arg.startswith("--rightjustify=")) or (arg.startswith("--right=")):
rightJustify += parse_columns(argVal)
elif (arg.startswith("--width=")):
for spec in argVal.split(","):
assert (":" in spec), "can't understand: %s" % arg
(col,w) = spec.split(":",1)
(col,w) = (int(col)-1,int(w))
assert (col not in columnWidth)
columnWidth[col] = w
elif (arg.startswith("--commas=")) or (arg.startswith("--commatize=")):
commas += parse_columns(argVal)
elif (arg.startswith("--double=")):
doubleSep += parse_columns(argVal)
elif (arg.startswith("--bar=")):
barSep += parse_columns(argVal)
elif (arg.startswith("--")):
assert (False), "unknown argument: %s" % arg
else:
assert (False), "unknown argument: %s" % arg
if (passComments == []): passComments = None
colToWidth = {}
for col in columnWidth: colToWidth[col] = columnWidth[col]
lines = []
for line in sys.stdin:
line = line.strip()
lines += [line]
if (line == ""): continue
if (passComments != None):
isComment = False
for prefix in passComments:
if (line.startswith(prefix)):
isComment = True
break
if (isComment):
continue
if (inSeparator == None): columns = line.split()
else: columns = line.split(inSeparator)
if (bunchExtras != None) and (len(columns) > bunchExtras):
columns = columns[:bunchExtras] + [" ".join(columns[bunchExtras:])]
for col in range(len(columns)):
if (col in columnWidth): continue
if (col in commas): w = len(commatize(columns[col]))
else: w = len(columns[col])
if (col not in colToWidth): colToWidth[col] = w
else: colToWidth[col] = max(w,colToWidth[col])
for line in lines:
if (line == ""):
print
continue
if (passComments != None):
isComment = False
for prefix in passComments:
if (line.startswith(prefix)):
isComment = True
break
if (isComment):
print line
continue
if (inSeparator == None): columns = line.split()
else: columns = line.split(inSeparator)
if (bunchExtras != None) and (len(columns) > bunchExtras):
columns = columns[:bunchExtras] + [" ".join(columns[bunchExtras:])]
for col in range(len(columns)):
if (col in rightJustify): fmt = "%*s"
else: fmt = "%-*s"
val = columns[col]
if (col in commas): val = commatize(val)
val = fmt % (colToWidth[col],val)
if (outSeparator != None):
val += outSeparator
if (col+1 in barSep): val += "|"
if (col+1 in doubleSep): val += outSeparator.strip()
else:
if (col+1 in barSep): val += " |"
columns[col] = val
line = spacer.join(columns)
print line.rstrip()
|
ebbffeb694f13ec4d1d5282089eb228a9709a422 | jet76/CS-4050 | /Project 04/SumsToN.py | 346 | 3.875 | 4 | def recurse(num, sum, out):
if sum > n:
return
else:
sum += num
if sum == n:
print(out + str(num))
return
else:
out += str(num) + " + "
for i in range(num, n + 1):
recurse(i, sum, out)
n = int(input("Enter a positive integer: "))
for i in range(1, n + 1):
recurse(i, 0, "") |
d6e556e4afd34c6a8056dfa1df965ba5f6fd5c48 | Z477/concurrent-program | /2_multi_threading/demo_5_threadpoolexecutor.py | 1,533 | 3.640625 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
Use concurrent.futures to implement multi thread
Created on Jun 30, 2019
@author: siqi.zeng
@change: Jun 30, 2019 siqi.zeng: initialization
'''
import concurrent.futures
import logging
import time
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [line:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
def drink_water(name):
time.sleep(2)
logging.info("%s finish drink", name)
return "result of {}".format(name)
def eat_food(name):
time.sleep(2)
logging.info("%s finish eat", name)
return "result of {}".format(name)
def do_sports(name):
time.sleep(2)
logging.info("%s finish do sports", name)
return "result of {}".format(name)
def play_game(name):
time.sleep(2)
logging.info("%s finish play game", name)
return "result of {}".format(name)
def watch_tv(name):
time.sleep(2)
logging.info("%s finish watch TV", name)
return "result of {}".format(name)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
logging.info("start")
future_to_person = [executor.submit(drink_water, "A"), executor.submit(eat_food, "B"),
executor.submit(do_sports, "C"), executor.submit(play_game, "D"),
executor.submit(watch_tv, "E")]
concurrent.futures.wait(future_to_person, timeout=5)
for future_object in future_to_person:
result = future_object.result()
logging.info("%s", result)
logging.info("end")
|
ebd6f80484ef4a051fadde4199f8b27c366fa283 | JMSMonteiro/AED-Proj2 | /src/gui.py | 7,450 | 3.75 | 4 | from tkinter import *
from tkinter import messagebox
import main
########## FUNCTIONS JUST TO HAVE TEXT/CLEAR TEXT FROM THE ENTRIES ##########
#Still looking for a way to make all of these into 2 functions
def on_entry_click_0(event): #Cities Entry
"""function that gets called whenever entry is clicked"""
entry_cities.config(fg = 'black')
if entry_cities.get() == '# of cities':
entry_cities.delete(0, "end") #delete all the text in the entry
entry_cities.insert(0, '') #Insert blank for user input
def on_entry_click_1(event): #Cenario Entry
entry_cenario.config(fg = 'black')
if entry_cenario.get() == 'Cenario 1 or 2':
entry_cenario.delete(0, "end") #delete all the text in the entry
entry_cenario.insert(0, '') #Insert blank for user input
def on_focusout_0(event): #Cities Entry
if entry_cities.get() == '':
entry_cities.insert(0, '# of cities')
entry_cities.config(fg = 'grey')
elif not is_int(entry_cities.get()): #If the input isn't valid, the text goes red
entry_cities.config(fg = 'red')
def on_focusout_1(event): #Cenario Entry
if entry_cenario.get() == '':
entry_cenario.insert(0, 'Cenario 1 or 2')
entry_cenario.config(fg = 'grey')
elif not is_int(entry_cenario.get()): #If the input isn't valid, the text goes red
entry_cenario.config(fg = 'red')
########## CHECKBOX STUFF ###########
def on_check_cenario_1():
cenario_2_check.deselect()
def on_check_cenario_2():
cenario_1_check.deselect()
#J#M#S#M#o#n#t#e#i#r#o# THAT PART OF THE CODE THAT USES THE OTHER .py FILES AND DOES SOMETHING PRODUCTIVE #J#M#S#M#o#n#t#e#i#r#o#
def is_int(string):
try:
int(string)
return True
except ValueError:
return False
def check_values():
cities = is_int(entry_cities.get())
cenario = (cenario_1.get() or cenario_2.get())
algorithm = (brute.get() or brute_opt.get() or recursive.get() or recursive_g.get())
if cities and cenario and algorithm:
#do execute the program
#0 = brute || 1 = brute_optimised || 2 = recursive || 3 = recursive greedy
if int(entry_cities.get()) < 2:
messagebox.showerror("Invalid City Value", "The city number must be greater or equal to 2.")
return
map_graph = main.geraMapa(entry_cities.get(), [cenario_1.get(), cenario_2.get()])
if brute.get():
run('Results - Brute Force', 0, map_graph)
if brute_opt.get():
run('Results - Brute Force Optimized', 1, map_graph)
if recursive.get():
run('Results - Recursive', 2, map_graph)
if recursive_g.get():
run('Results - Recursive Greedy', 3, map_graph)
else:
if cities:
if int(entry_cities.get()) < 2:
messagebox.showerror("Invalid City Value", "The city number must be greater or equal to 2.")
if not cities:
messagebox.showerror("Invalid City Number", "The value of 'Number of cities' is not valid!")
if not cenario:
messagebox.showerror("Invalid Cenario", "Please select one of the cenarios.")
if not algorithm:
messagebox.showerror("Invalid Algorithm", "Please select at least one of the algorithms.")
def run(window_title, algorithm, map_graph):
results = main.main(map_graph, [cenario_1.get(), cenario_2.get()], algorithm)
###Popup Window with results###
pop_up = Toplevel()
pop_up.title(window_title)
#Pop-up labels
label_origin = Label(pop_up, text="City of origin: ")
label_total_dist = Label(pop_up,text="Total distance: ")
label_path = Label(pop_up, text="Route chosen: ")
label_time = Label(pop_up, text="Calculated in: ")
#Pop-up info to be displayed
grafo_info = Message(pop_up, width=400, text=str(results[0])) #Mess arround with the width parameter to fit all your needs
origin_info = Message(pop_up, width=300, text=str(results[1]))
total_dist_info = Message(pop_up, width=300, text=str(results[2]))
path_info = Message(pop_up, width=300, text=str(results[3]))
time_info = Message(pop_up, width=300, text=str(results[4]))
#Grid it!
label_origin.grid(row=10, pady=10, sticky=E)
label_total_dist.grid(row=12, pady=10, sticky=E)
label_path.grid(row=14, pady=10, sticky=E)
label_time.grid(row=16, pady=10, sticky=E)
grafo_info.grid(row=0, columnspan=4, pady=10, padx=10)
origin_info.grid(row=10, column=2, pady=10, sticky=W)
total_dist_info.grid(row=12, column=2, pady=10, sticky=W)
path_info.grid(row=14, column=2, pady=10, sticky=W)
time_info.grid(row=16, column=2, pady=10, sticky=W)
btn = Button(pop_up, text="Dismiss", command=pop_up.destroy)
btn.grid(row=100, pady=10, column=1, sticky=W)
########## ACTUAL TKINTER'S CODE STARTS HERE (Most of it anyways)##########
###Main Window with parameter and such###
root = Tk() #does stuff
root.wm_title("AED - Project #2") #Window Name
top_frame = Frame(root) #Creates top frame
top_frame.pack() #Packs the frame in the window
bottom_frame = Frame(root) #Creates bottom frame
bottom_frame.pack(side=BOTTOM) #Packs the frame in the window. under the other frame
calculate_btn = Button(bottom_frame,text="Calculate", fg="green", command=check_values) #button to start program
exit_btn = Button(bottom_frame, text="Exit", fg="green", command=root.quit) #button to exit the GUI
calculate_btn.pack(side=LEFT) #places the button as far to the left as it can
exit_btn.pack(side=LEFT) #places the button as far to the left as it can
#Grid for inputs and stuff
#sticky -> [N,S,W,E]
label_cities = Label(top_frame, text="Number of cities: ")
label_cenario = Label(top_frame, text="Cenario: ")
label_algorithm = Label(top_frame, text="Algorithm to be used: ")
label_filler = Label(top_frame, text="")
#Entry boxes text initial color and stuff
entry_cities = Entry(top_frame, fg='grey')
entry_min_dist = Entry(top_frame, fg='grey')
entry_max_dist = Entry(top_frame, fg='grey')
#entry boxes default text
entry_cities.insert(0, '# of cities')
#Var for checkboxes
cenario_1 = BooleanVar()
cenario_2 = BooleanVar()
brute = BooleanVar()
brute_opt = BooleanVar()
recursive = BooleanVar()
recursive_g = BooleanVar()
#Checkboxes for different algorithms
cenario_1_check = Checkbutton(top_frame, text="1", onvalue=True, offvalue=False, variable=cenario_1, command=on_check_cenario_1)
cenario_2_check = Checkbutton(top_frame, text="2", onvalue=True, offvalue=False, variable=cenario_2, command=on_check_cenario_2)
brute_check = Checkbutton(top_frame, text="Brute Force ", onvalue=True, offvalue=False, variable=brute)
brute_opt_check = Checkbutton(top_frame, text="Brute Force Optimized", onvalue=True, offvalue=False, variable=brute_opt)
recursive_check = Checkbutton(top_frame, text="Recursive ", onvalue=True, offvalue=False, variable=recursive)
recursive_g_check = Checkbutton(top_frame, text="Recursive Greedy", onvalue=True, offvalue=False, variable=recursive_g)
#binds
entry_cities.bind('<FocusIn>', on_entry_click_0)
entry_cities.bind('<FocusOut>', on_focusout_0)
#grid labels
label_cities.grid(row=0, pady=10, sticky=E)
label_cenario.grid(row=2, pady=10, sticky=E)
label_algorithm.grid(row=6, pady=10, sticky=E)
label_filler.grid(row=10, pady=10, sticky=E)
#grid Entries
entry_cities.grid(row=0, column=1)
#grid checkboxes
cenario_1_check.grid(row=2, column=1, sticky=W)
cenario_2_check.grid(row=2, column=1, sticky=E)
brute_check.grid(row=6, column=1, sticky=W)
brute_opt_check.grid(row=8, column=1, sticky=W)
recursive_check.grid(row=10, column=1, sticky=W)
recursive_g_check.grid(row=12, column=1, sticky=W)
root.mainloop() #required to run TkInter |
8ed94e5a5bc207a34271e2bb52029d7b6b71870d | darlenew/california | /california.py | 2,088 | 4.34375 | 4 | #!/usr/bin/env python
"""Print out a text calendar for the given year"""
import os
import sys
import calendar
FIRSTWEEKDAY = 6
WEEKEND = (5, 6) # day-of-week indices for saturday and sunday
def calabazas(year):
"""Print out a calendar, with one day per row"""
BREAK_AFTER_WEEKDAY = 6 # add a newline after this weekday
c = calendar.Calendar()
tc = calendar.TextCalendar(firstweekday=FIRSTWEEKDAY)
for month in range(1, 12+1):
print()
tc.prmonth(year, month)
print()
for day, weekday in c.itermonthdays2(year, month):
if day == 0:
continue
print("{:2} {} {}: ".format(day,
calendar.month_abbr[month],
calendar.day_abbr[weekday]))
if weekday == BREAK_AFTER_WEEKDAY:
print()
def calcium(year, weekends=True):
"""Print out a [YYYYMMDD] calendar, no breaks between weeks/months"""
tc = calendar.TextCalendar()
for month_index, month in enumerate(tc.yeardays2calendar(year, width=1), 1):
for week in month[0]: # ?
for day, weekday in week:
if not day:
continue
if not weekends and weekday in (WEEKEND):
print()
continue
print(f"[{year}{month_index:02}{day:02}]")
def calzone(year):
"""Prints YYYYMMDD calendar, like calcium without weekends"""
return calcium(year, weekends=False)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="print out a calendar")
parser.add_argument('year', metavar='YEAR', type=int, help='the calendar year')
parser.add_argument('style', metavar='STYLE', help='calendar style')
args = parser.parse_args()
style = {'calcium': calcium,
'calabazas': calabazas,
'calzone': calzone,
}
try:
style[args.style](args.year)
except KeyError:
raise(f"Calendar style {args.style} not found")
|
ab7b1bc5da6df5746bed215e196f2208301570df | jonathan-mcmillan/python_programs | /asdf;lkj.py | 1,126 | 3.5 | 4 | from cs1graphics import *
numLevels = 8
unitSize = 12
screenSize = unitSize * (numLevels + 1)
paper = Canvas(screenSize, screenSize)
for level in range(numLevels):
centerX = screenSize / 2
leftMostX = centerX - unitSize / 2 * level
centerY = (level +1) * unitSize
for blockCount in range(level +1):
block = Square(unitSize)
block.move(leftMostX + blockCount * unitSize, centerY)
block.move(centerX, centerY)
block.setFillColor('gray')
paper.add(block)
'''
from cs1graphics import *
numLevels = 8
unitSize = 12
screenSize = unitSize * (numLevels + 1)
paper = Canvas(screenSize, screenSize)
for level in range(numLevels):
width = (level +1) * unitSize
height = unitSize
block = Rectangle(width, height)
width = (level +1) * unitSize
block = Rectangle(width, unitSize)
block = Rectangle((level +1)* unitSize, unitSize)
these two do the same thing as the first set of code
centerX = screenSize/2
centerY = (level +1) * unitSize
block.move(centerX, centerY)
block.setFillColor('gray')
paper.add(block)
'''
|
e96bfc80489c56a2fef2d71ca5ae417f6738a539 | jonathan-mcmillan/python_programs | /notes_2⁄1.py | 591 | 3.671875 | 4 | groceries=['eggs','ham','toast','juice']
for item in groceries:
print item
count = 1
for item in groceries:
print str(count)+')'+item
count += 1
a = [6,2,4,3,2,4]
n=0
print a
for e in a:
a[n]= e*2
n +=1
print a
for i in range(len(a)):
a[i] *= 2
print a
m = [[3,4],[2,1]]
for i in range(2):
for j in range(2):
m[i][j] *= 3
print m
l = [[1,'eggs'],(2,'ham'),'toast',4.0]
print l[3]
print l[1]
print l[1][0]
print l[1][1]
print l[1][1][0]
t=('A','B','C','D','E')
for i in range(len(t)):
for j in range(i+1,len(t)):
print t[i], t[j]
|
7a3e2fb304cbb15c640e17841da60543e46e95eb | emrache/Python_600x | /Problem Set 9/ps9.py | 2,824 | 3.65625 | 4 | # 6.00 Problem Set 9
import numpy
import random
import pylab
from ps8b_precompiled_27 import *
#
# PROBLEM 1
#
def simulationDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 1.
Runs numTrials simulations to show the relationship between delayed
treatment and patient outcome using a histogram.
Histograms of final total virus populations are displayed for delays of 300,
150, 75, 0 timesteps (followed by an additional 150 timesteps of
simulation).
numTrials: number of simulation runs to execute (an integer)
"""
##setting up the time Steps, population variable
popAtEnd=[]
timeBegin=0
timeMiddle=75
timeEnd=timeMiddle+150
##going through all of the trials:
trialNum=0
while trialNum<numTrials:
##setting up baseline variables
numViruses=100
maxPop=1000
maxBirthProb=.1
clearProb=.05
resistances={'guttagonol': False}
mutProb=.005
##setting up the list of viruses to start
trialViruses=[]
for x in range(numViruses):
trialViruses.append(ResistantVirus(maxBirthProb, clearProb, resistances, mutProb))
##creating the test patient
testPatient=TreatedPatient(trialViruses, maxPop)
for step in range(timeBegin, timeMiddle):
testPatient.update()
testPatient.addPrescription('guttagonol')
for step in range(timeMiddle, timeEnd):
testPatient.update()
## print step
trialNum+=1
popAtEnd.append(testPatient.getTotalPop())
print popAtEnd
##create the gorram histogram
pylab.hist(popAtEnd,bins=10)
pylab.xlabel('End population if scrip added after '+ str(timeMiddle)+' steps')
pylab.ylabel('Number of Trials')
pylab.title ('End Virus Population')
pylab.show()
return
## ##create the gorram plot
## pylab.figure(1)
## pylab.plot(avgPopAtTime)
## pylab.plot(avgResistPopAtTime)
## pylab.title('Average Resistant Virus Population, drug introduced @ time')
## pylab.xlabel('Time Steps')
## pylab.ylabel('Average Virus Population')
## pylab.legend('total pop')
## pylab.show()
#
# PROBLEM 2
#
def simulationTwoDrugsDelayedTreatment(numTrials):
"""
Runs simulations and make histograms for problem 2.
Runs numTrials simulations to show the relationship between administration
of multiple drugs and patient outcome.
Histograms of final total virus populations are displayed for lag times of
300, 150, 75, 0 timesteps between adding drugs (followed by an additional
150 timesteps of simulation).
numTrials: number of simulation runs to execute (an integer)
"""
# TODO
|
85c0cb7b1fb3da5a3e4f20d60d1a55ca1576aad3 | rorjackson/Jack | /tkintergui.py | 553 | 3.9375 | 4 | from tkinter import *
win = Tk()
win.geometry('200x100')
name = Label(win, text="Name") # To create text label in window
password = Label(win,text="password")
email = Label(win, text="Email ID")
entry_1 = Entry(win)
entry_2 = Entry(win)
entry_3 = Entry(win)
# check = CHECKBUTTON(win,text ="keep me logged in")
name.grid(row=0, sticky = E)
password.grid(row=1,sticky = E)
email.grid(row=2, sticky = E)
entry_1.grid(row=0, column =1)
entry_2.grid(row=1, column =1)
entry_3.grid(row=2, column =1)
# check.grid(columnspan=2)
win.mainloop() |
d86ab402a950557261f140137b2771e84ceafbbe | priyankagarg112/LeetCode | /MayChallenge/MajorityElement.py | 875 | 4.15625 | 4 | '''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
'''
from typing import List
#Solution1:
from collections import Counter
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0]
#Solution2:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
visited = []
for i in nums:
if i in visited:
continue
if nums.count(i) > (len(nums)/2):
return i
visited.append(i)
if __name__ == "__main__":
print(Solution().majorityElement([3,1,3,2,3]))
|
92bbf967afbb85b943c9af46bde946b2d0d9fdf9 | tusshar2000/DSA-Python | /graphs/dfs_cycle_directed_graph.py | 2,502 | 3.71875 | 4 | # https://leetcode.com/problems/course-schedule/
from collections import defaultdict
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# defaultdict(list) makes work easier
graph = defaultdict(list)
# we need to have every node in our graph as a key even though there might be not
# any connection to it/ it is not a connected graph. Just a basic and easy # preparation.
graph = {node:[] for node in range(numCourses)}
# now we add the edges in reverse manner because input is given in that format.
for edge in prerequisites:
graph[edge[1]].append(edge[0])
is_possible = True
visited = [0]*(numCourses)
# note that we will be using 0,1,2 values for representing the state of our node
# in visited list.
# value 0 represents node is unprocessed.
# value 1 represents node is under process.
# value 2 represents node is processed.
def dfs(visited, node):
nonlocal is_possible
visited[node] = 1
for neighbour in graph[node]:
if visited[neighbour] == 0:
dfs(visited, neighbour)
# this is the condition where we find if a cycle exsits or not.
# if our neighbour node has a value 1 in visited list, it means that
# this node was still under process and we found another way through
# which we can access this, meaning we found a cycle.
if visited[neighbour] == 1:
is_possible = False
visited[node] = 2
# now for every node we check if it is unprocessed then call dfs for it,
# this way we are assured even if our graph in not fully connected we will
# be processing it.
for node in range(numCourses):
# I added another condition to check is_possible is still true then only
# process the node, as is_possible variable False value represents that
# our graph has cycle, so basically no need to process any node further.
if visited[node] == 0 and is_possible==True:
dfs(visited, node)
return is_possible |
5b9cd3610bf26e71e74df0a4a869b3969382b5ac | tusshar2000/DSA-Python | /graphs/word-search-using-dfs.py | 1,993 | 3.71875 | 4 | # https://leetcode.com/problems/word-search/
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
col = len(board[0])
row = len(board)
len_of_word = len(word)
is_possible = False #starting with it's not possible to form the string.
visited = set() #set for visited elements.
def dfs(visited, i, j, k):
nonlocal is_possible
# base-conditions, exit if already found a match or if trying to search out of #bounds.
if is_possible == True or i<0 or i>=row or j<0 or j>=col:
return
#add this element to visited
visited.add((i,j))
if board[i][j] == word[k]:
#we found the matching string.
if k == len_of_word - 1:
is_possible = True
return
#entering the dfs call only if that cell is unvisited.
if (i+1, j) not in visited:
dfs(visited, i+1, j, k+1)
if (i-1, j) not in visited:
dfs(visited, i-1, j, k+1)
if (i, j+1) not in visited:
dfs(visited, i, j+1, k+1)
if (i, j-1) not in visited:
dfs(visited, i, j-1, k+1)
#processing of this cell is done, so remove it from visited for next iterations.
visited.remove((i,j))
#dfs through each cell
for i in range(row):
for j in range(col):
#just return the answer if already found the solution.
if is_possible == True:
return is_possible
dfs(visited,i,j,0)
return is_possible |
78b22399df13bda1fa6519d86a1192cf358f6e87 | tusshar2000/DSA-Python | /binary tree/max_depth_of_n-ary_tree.py | 599 | 3.75 | 4 | https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
#BFS
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
queue = collections.deque([(root,1)])
while queue:
node, level = queue.popleft()
for child in node.children:
queue.append((child, level + 1))
return level
|
1e190699791483acd663a85db438602a6169e360 | kp646576/Simple-Compiler | /lexer.py | 4,596 | 3.625 | 4 | import sys
from scanner import Scanner
from token import Token
from symbolTable import symbolTable as st
def isAlpha(c):
if c:
c = ord(c)
return True if c >= 65 and c <= 90 or c >= 97 and c <= 122 else False
def isDigit(c):
if c:
c = ord(c)
return True if c <= 57 and c >= 48 else False
def isKeyword(c):
return True if c in st.keys() else False
def valKeyword(c):
return st[c] if c in st.keys() else ''
class Lexer:
def __init__(self, file):
self.line = 1
self.tokens = []
self.scanner = Scanner(file)
self.checkNext(self.scanner.read())
def checkNext(self, cur):
if cur == '\n':
self.line += 1
cur = self.scanner.read()
self.checkNext(cur)
else:
while cur == ' ' or cur == '\t':
cur = self.scanner.read()
if isDigit(cur) or cur == '.':
self.digitFSA(cur)
elif cur == '"':
self.stringFSA(cur)
elif isAlpha(cur) or cur == '_':
self.idFSA(cur)
else:
self.otherFSA(cur)
return
def digitFSA(self, n):
peek = self.scanner.read()
if n == '.':
if isDigit(peek):
n += peek
peek = self.scanner.read()
while isDigit(peek):
n += peek
self.tokens.append(Token(self.line, 'real', n))
else:
# Get digits before '.'
while isDigit(peek):
n += peek
peek = self.scanner.read()
# Is real
if peek == '.':
n += peek
peek = self.scanner.read()
while isDigit(peek):
n += peek
peek = self.scanner.read()
if peek == 'e':
n += peek
peek = self.scanner.read()
if peek == '+' or peek == '-':
n += peek
peek = self.scanner.read()
if not isDigit(peek):
self.eMessage(peek)
while isDigit(peek):
n += peek
peek = self.scanner.read()
self.tokens.append(Token(self.line, 'real', n))
elif peek == 'e':
n += peek
peek = self.scanner.read()
if peek == '+' or peek == '-':
n += peek
peek = self.scanner.read()
while isDigit(peek):
n += peek
peek = self.scanner.read()
self.tokens.append(Token(self.line, 'real', n))
# Is int
else:
self.tokens.append(Token(self.line, 'int', n))
self.checkNext(peek)
return
def stringFSA(self, c):
peek = self.scanner.read()
while peek != '"' and peek != '\n':
c += peek
peek = self.scanner.read()
if peek == '"':
c += peek
self.tokens.append(Token(self.line, 'string', c))
peek = self.scanner.read()
self.checkNext(peek)
else:
self.eMessage(c)
return
def idFSA(self, c):
peek = self.scanner.read()
# error when not num alph or _
while peek and (isAlpha(peek) or isDigit(peek) or peek == '_'):
c += peek
peek = self.scanner.read()
if peek == ' ' or peek == '\n' or isKeyword(peek):
keyword = valKeyword(c)
if keyword:
self.tokens.append(Token(self.line, keyword, c))
else:
self.tokens.append(Token(self.line, 'id', c))
else:
self.eMessage(peek)
self.checkNext(peek)
return
def otherFSA(self, c):
peek = self.scanner.read()
if peek:
k1 = valKeyword(c)
len2 = c + peek
k2 = valKeyword(len2)
# k2 first for longest prefix
if k2:
self.tokens.append(Token(self.line, k2, len2))
self.checkNext(self.scanner.read())
elif k1:
self.tokens.append(Token(self.line, k1, c))
self.checkNext(peek)
else:
self.eMessage(c)
return
def eMessage(self, e):
print >> sys.stderr, "Error on line " + str(self.line) + ": " + e + " is invalid."
|
5fbf2ff1591bdc0a50b2ad9758cf806bf7e4f6e8 | ttsiodras/VideoNavigator | /menu.py | 5,600 | 3.71875 | 4 | #!/usr/bin/env python
"""
A simple Pygame-based menu system: it scans folders and collects the single
image/movie pair within each folder. It then shows the collected pictures,
allowing you to navigate with up/down cursors; and when you hit ENTER,
it plays the related movie.
The configuration of folders, resolutions, players, etc is done with a
simple 'settings.ini' file.
"""
import sys
import os
import subprocess
from dataclasses import dataclass
from typing import List, Tuple
# pylint: disable=wrong-import-position
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame # NOQA
def panic(msg):
"""
Report error and abort.
"""
sys.stderr.write('[x] ' + msg + "\n")
sys.exit(1)
@dataclass
class Settings:
"""
Store all settings provided by user.
"""
video_folder: str
full_screen: bool
width_in_pixels: int
height_in_pixels: int
image_extensions: List[str]
movie_extensions: List[str]
command: str
def parse_settings() -> Settings:
"""
Parse 'settings.ini', return dictionary object with all settings.
"""
settings = {}
if not os.path.exists("settings.ini"):
panic("Missing settings.ini!")
for idx, line in enumerate(open("settings.ini", "r")):
if line.startswith('#'):
continue
try:
line = line.strip()
key, value = line.split('=')
key = key.strip()
value = value.strip()
except ValueError:
print("[x] Warning! Weird line", idx+1, " ignored:\n\t", line)
settings[key] = value
# Validate
if 'VideoFolder' not in settings:
panic("Did not find 'VideoFolder=' line in your settings.ini...")
for param in ['WidthInPixels', 'HeightInPixels']:
if param in settings:
try:
settings[param] = int(settings[param])
except ValueError:
panic("Invalid '%s=' line in your settings.ini..." % param)
# Default values
settings.setdefault('FullScreen', 'no')
settings['FullScreen'] = settings['FullScreen'].lower() == 'yes'
info_object = pygame.display.Info()
settings.setdefault('WidthInPixels', info_object.current_w)
settings.setdefault('HeightInPixels', info_object.current_h)
settings.setdefault(
'ImageExtensions', "jpg,jpeg,gif,png,webp")
settings['ImageExtensions'] = settings['ImageExtensions'].split(",")
settings.setdefault(
'MovieExtensions', "mkv,mp4,flv,avi,mov")
settings['MovieExtensions'] = settings['MovieExtensions'].split(",")
settings.setdefault(
'Command', r"C:\Program Files\VideoLAN\VLC\vlc.exe")
return Settings(
settings['VideoFolder'],
settings['FullScreen'],
settings['WidthInPixels'],
settings['HeightInPixels'],
settings['ImageExtensions'],
settings['MovieExtensions'],
settings['Command'])
def collect_all_videos(settings) -> List[Tuple[str, str]]:
"""
Scan the folder specified in the settings, and collect
images and movies.
Returns list of tuples containing (image,movie) paths.
"""
results = []
for root, unused_dirs, files in os.walk(
settings.video_folder, topdown=True):
found_images = [
x for x in files
if any(
x.lower().endswith(y)
for y in settings.image_extensions)
]
found_movies = [
x for x in files
if any(
x.lower().endswith(y)
for y in settings.movie_extensions)
]
if found_images and found_movies:
results.append((
root + os.sep + found_images[0],
root + os.sep + found_movies[0]))
return results
def main():
"""
The heart of the show.
"""
pygame.init()
settings = parse_settings()
args = []
args.append(
(settings.width_in_pixels, settings.height_in_pixels))
if settings.full_screen:
args.append(pygame.FULLSCREEN)
win = pygame.display.set_mode(*args)
images_and_movies = collect_all_videos(settings)
if not images_and_movies:
panic("No folders found...")
current_slot = 0
image = []
while True:
del image
image = pygame.image.load(images_and_movies[current_slot][0])
image = pygame.transform.scale(
image,
(settings.width_in_pixels, settings.height_in_pixels))
win.blit(image, (0, 0))
pygame.display.update()
while True:
evt = pygame.event.wait()
if evt.type == pygame.NOEVENT:
break
if evt.type == pygame.KEYUP:
break
if evt.key == pygame.K_SPACE or evt.key == pygame.K_RETURN:
pygame.quit()
cmd = [settings.command]
cmd.append(images_and_movies[current_slot][1])
subprocess.call(cmd)
pygame.init()
win = pygame.display.set_mode(
(settings.width_in_pixels, settings.height_in_pixels),
pygame.FULLSCREEN)
elif evt.key == pygame.K_DOWN:
current_slot = current_slot + 1
current_slot = current_slot % len(images_and_movies)
elif evt.key == pygame.K_UP:
current_slot = current_slot + len(images_and_movies) - 1
current_slot = current_slot % len(images_and_movies)
elif evt.key == pygame.K_ESCAPE:
pygame.quit()
break
if __name__ == "__main__":
main()
|
f03de31739574749ee56fabdeffdb43e0dc9229b | divannn/python | /math/sort_util.py | 71 | 3.546875 | 4 | def swap(list, i, j):
tmp = list[i]
list[i] = list[j]
list[j] = tmp
|
61329cb09135f5634b1c64baa1db566836929a26 | shivamach/OldMine | /HelloWorld/python/strings.py | 527 | 4.375 | 4 | print("trying basic stuff out")
m1 = "hello"
m2 = "World"
name = "shivam"
univ = "universe"
print(m1,", ",m2)
print(m1.upper())
print(m2.lower())
message = '{}, {}. welcome !'.format(m1,m2.upper())
print(message)
message = message.replace(m2.upper(),name.upper())
#replacing with methods should be precise
print(message)
name = "not shivam"
#trying out replace with f strings
message = f'{m1}, {m2.upper()}. welcome!'
print(message)
message = message.replace(m2.upper(),name.upper())
print(message)
#everything covered ayyay |
433027b761e728e242c5b58c11866208fe39ca23 | caesarbonicillo/ITC110 | /quadraticEquation.py | 870 | 4.15625 | 4 | #quadratic quations must be a positive number
import math
def main():
print("this program finds real solutions to quadratic equations")
a = float(input("enter a coefficient a:"))
b = float(input("enter coefficient b:"))
c = float(input("enter coefficient c:"))
#run only if code is greater or qual to zero
discrim = b * b - 4 * a *c
if(discrim < 0): #1, 2, 3
print("no real roots") # should always put the default in before any real work that way it doesn't do any unnessesary work.
elif(discrim ==0):#1, 2, 1
root = -b / (2 * a)
print("there is a double root at", root)
else:#1, 5, 6
discRoot = math.sqrt(b * b -4 *a *c)
root1 = (-b + discRoot) / (2* a)
root2 = (-b - discRoot) / (2 * a)
print ("\nThe solutions are:", root1, root2)
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.