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 |
|---|---|---|---|---|---|---|
80082f949d1589ddc0a79a9067b95413e873b4f4 | wulinlw/leetcode_cn | /leetcode-vscode/406.根据身高重建队列.py | 1,933 | 3.546875 | 4 | #
# @lc app=leetcode.cn id=406 lang=python3
#
# [406] 根据身高重建队列
#
# https://leetcode-cn.com/problems/queue-reconstruction-by-height/description/
#
# algorithms
# Medium (62.74%)
# Likes: 272
# Dislikes: 0
# Total Accepted: 21.8K
# Total Submissions: 34.2K
# Testcase Example: '[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]'
#
# 假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。
# 编写一个算法来重建这个队列。
#
# 注意:
# 总人数少于1100人。
#
# 示例
#
#
# 输入:
# [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
#
# 输出:
# [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
#
#
#
from typing import List
# @lc code=start
class Solution:
# you题意可知
# 身高越高的人,前面比他高的人数,就是当前队列的索引。比如上述people->[[7,0] [7,1]]
# 如果比他(身高最高的人)矮的人,如[5,0],前面比他高的人-0,应是当前插入队列索引下前面的一个数,如[[5,0],[7,0] [7,1]]
# 因此总结规律如下:
# 1. 队列应从身高降序排列。如果身高相同者,升序排序
# 然后依次遍历,按当前比他高身高人数为索引插入新建队列
# 注意,身高最高者,他的索引"必定"有0,并列才有1,意味着(身高比他矮的,且索引相同时,必定在他前面)
# 因此从身高降序排列,不会影响身高矮插入队列是,出现队列乱序的错误。
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x:(-x[0], x[1]))
# print(people)
re = []
for p in people:
re.insert(p[1], p)
return re
# @lc code=end
people = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
o = Solution()
print(o.reconstructQueue(people))
|
e727d73d45d67bf07c8a7cf7bcf3103d8acd75b4 | wulinlw/leetcode_cn | /数组和字符串/array_6.py | 939 | 3.75 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/featured/card/array-and-string/202/conclusion/792/
# 杨辉三角 II
# 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
# 在杨辉三角中,每个数是它左上方和右上方的数的和。
# 示例:
# 输入: 3
# 输出: [1,3,3,1]
# 进阶:
# 你可以优化你的算法到 O(k) 空间复杂度吗?
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if(rowIndex==0):
return [1]
dp=[1,1]#第二行的dp
for i in range(3,rowIndex+2):
cur=[0]*(i)#当前行dp初始化为0
cur[0]=cur[-1]=1#首尾设为0
for j in range(1,i-1):
cur[j]=dp[j-1]+dp[j]
dp=cur#更新dp
return dp
rowIndex = 3
s = Solution()
n = s.getRow(rowIndex)
print(n) |
e17240c468f25e13762598f4f7c18bb9fbacd888 | wulinlw/leetcode_cn | /二叉树/search-tree_1_2.py | 1,994 | 4.09375 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/64/introduction-to-a-bst/172/
# 二叉搜索树迭代器
# 实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
# 调用 next() 将返回二叉搜索树中的下一个最小的数。
# 示例:
# BSTIterator iterator = new BSTIterator(root);
# iterator.next(); // 返回 3
# iterator.next(); // 返回 7
# iterator.hasNext(); // 返回 true
# iterator.next(); // 返回 9
# iterator.hasNext(); // 返回 true
# iterator.next(); // 返回 15
# iterator.hasNext(); // 返回 true
# iterator.next(); // 返回 20
# iterator.hasNext(); // 返回 false
# 提示:
# next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
# 你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。
class TreeNode(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
from collections import deque
class BSTIterator:
def __init__(self, root: TreeNode):
self.head = root
self.stack = deque()
while root:
self.stack.append(root)
root = root.left
def next(self) -> int:
"""
@return the next smallest number
"""
cur = self.stack.pop()
root = cur.right
while root: # 使用了循环,复杂度不应该为O(1)?
self.stack.append(root)
root = root.left
return cur.val
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return len(self.stack) > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext() |
1926f0d51153da212fbfd132588b7547ca9b9e9d | wulinlw/leetcode_cn | /初级算法/linkedList_4.py | 1,718 | 4.25 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/6/linked-list/44/
# 合并两个有序链表
# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
# 示例:
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
# 新建链表,对比两个链表指针,小的放新链表中,直到某条链表结束,
# 将另一条链表剩余部分接入新链表
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
newHead = ListNode(0)
pre = newHead
while l1 and l2:
if l1.val<l2.val:
pre.next = l1
l1 = l1.next
else:
pre.next = l2
l2 = l2.next
pre = pre.next
if l1:
pre.next = l1
elif l2:
pre.next = l2
return newHead.next
def createListnode(self, list):
head = ListNode(list[0])
p = head
for i in list[1:]:
node = ListNode(i)
p.next = node
p = p.next
return head
def dump(self, head):
while head:
print (head.val),
head = head.next
print("")
s = Solution()
# 有序链表
head1 = s.createListnode([1,2,3])
head2 = s.createListnode([4,5,6])
s.dump(head1)
s.dump(head2)
res = s.mergeTwoLists(head1,head2)
s.dump(res) |
1270af1e1c684481ba5488a2fcff3aa3ca656284 | wulinlw/leetcode_cn | /leetcode-vscode/637.二叉树的层平均值.py | 1,670 | 3.703125 | 4 | #
# @lc app=leetcode.cn id=637 lang=python3
#
# [637] 二叉树的层平均值
#
# https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/
#
# algorithms
# Easy (63.16%)
# Likes: 98
# Dislikes: 0
# Total Accepted: 14.5K
# Total Submissions: 22.9K
# Testcase Example: '[3,9,20,15,7]'
#
# 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
#
# 示例 1:
#
# 输入:
# 3
# / \
# 9 20
# / \
# 15 7
# 输出: [3, 14.5, 11]
# 解释:
# 第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
#
#
# 注意:
#
#
# 节点值的范围在32位有符号整数范围内。
#
#
#
from typing import List
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:return []
stack = [root]
re = []
while stack:
cursum, cnt = 0,0
for _ in range(len(stack)):
n = stack.pop(0)
cursum += n.val
cnt += 1
if n.left:
stack.append(n.left)
if n.right:
stack.append(n.right)
re.append(cursum/cnt)
return re
# @lc code=end
# 1
# 2 3
# 4 5
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(3)
t4 = TreeNode(4)
t5 = TreeNode(5)
root = t1
root.left = t2
root.right = t3
t2.left = t4
t2.right = t5
o = Solution()
# print(o.levelOrder(t))
print(o.averageOfLevels(root)) |
096fdd8e7212763ede543a13cdad2240dd9f91ae | wulinlw/leetcode_cn | /dynamic-programming/dynamic-programming_63.py | 2,054 | 3.75 | 4 | #!/usr/bin/python
#coding:utf-8
# 63. 不同路径 II
# 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
# 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
# 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
# 网格中的障碍物和空位置分别用 1 和 0 来表示。
# 说明:m 和 n 的值均不超过 100。
# 示例 1
# 输入:
# [
# [0,0,0],
# [0,1,0],
# [0,0,0]
# ]
# 输出: 2
# 解释:
# 3x3 网格的正中间有一个障碍物。
# 从左上角到右下角一共有 2 条不同的路径:
# 1. 向右 -> 向右 -> 向下 -> 向下
# 2. 向下 -> 向下 -> 向右 -> 向右
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/unique-paths-ii
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type m: int
:type n: int
:rtype: int
"""
if obstacleGrid[0][0] ==1:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
obstacleGrid[0][0] = 1
for i in range(1,m):
obstacleGrid[i][0] = int(obstacleGrid[i][0] == 0 and obstacleGrid[i-1][0] == 1)#true=1 ,false=0
for j in range(1, n):
obstacleGrid[0][j] = int(obstacleGrid[0][j] == 0 and obstacleGrid[0][j-1] == 1)
# print(obstacleGrid)
for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j] == 0:
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
else:
obstacleGrid[i][j] = 0
# print(obstacleGrid)
return obstacleGrid[-1][-1]
obstacleGrid = [
[0,0,0],
[0,1,0],
[0,0,0]
]
s = Solution()
r = s.uniquePathsWithObstacles(obstacleGrid)
print(r)
|
ecaa303c54ccfc6abc2d3e1c76799df9dabe7794 | wulinlw/leetcode_cn | /程序员面试金典/面试题04.01.节点间通路.py | 2,549 | 3.765625 | 4 | # #!/usr/bin/python
# #coding:utf-8
#
# 面试题04.01.节点间通路
#
# https://leetcode-cn.com/problems/route-between-nodes-lcci/
#
# 节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
# 示例1:
#
# 输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
# 输出:true
#
#
# 示例2:
#
# 输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
# 输出 true
#
#
# 提示:
#
#
# 节点数量n在[0, 1e5]范围内。
# 节点编号大于等于 0 小于 n。
# 图中可能存在自环和平行边。
#
#
#
# Medium 53.2%
# Testcase Example: 3
# [[0, 1], [0, 2], [1, 2], [1, 2]]
# 0
# 2
#
# 提示:
# 有两个众所周知的算法可以做到这一点。其利弊是什么?
#
#
from typing import List
import collections
class Solution:
# dfs
def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
def dfs(start, visited):
if start == target:
return True
if visited[start]: #防止死循环
return False
visited[start] = True
for i in index[start]:
if dfs(i, visited):
return True
return False
visited = [False] * n #访问过的记录,防止死循环
index = collections.defaultdict(list)
for i in graph: #构建邻接表
index[i[0]].append(i[1])
return dfs(start, visited)
#bfs
def findWhetherExistsPath2(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
# 构建邻接表
link_table = [[] for _ in range(n)]
for i, j in graph:
link_table[i].append(j)
visted = [0] * n # 访问数组
# BFS
que = [start]
while que:
cur_node = que.pop()
if target in link_table[cur_node]: return True
for node in link_table[cur_node]:
if visted[node]==0:
que.insert(0,node)
visted[cur_node] = 1
return False
n = 3 #N个点
graph = [[0, 1], [0, 2], [1, 2], [1, 2]]
start = 0
target = 2
n = 5
graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]]
start = 0
target = 4
o = Solution()
print(o.findWhetherExistsPath(n, graph, start, target))
|
1ffbfbbbc0ea0c6f4725b89363464d734a17cd94 | wulinlw/leetcode_cn | /剑指offer/3_数组中重复的数字.py | 935 | 3.8125 | 4 | #!/usr/bin/python
#coding:utf-8
# 数组中重复的数字
# 在一个长度为n的数组里的所有数字都在0到n-1的范围内。
# 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。
# 请找出数组中任意一个重复的数字。
# 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3。
class Solution(object):
def duplicate(self, nums):
if len(nums)== 0:
return False
re = []
for i in range(len(nums)):
while i != nums[i]:
if nums[i] == nums[nums[i]]:
re.append(nums[i])
break
else:
index = nums[i]
nums[index],nums[i] = nums[i],nums[index]
return re
nums = [2,3,1,0,2,5,3]
obj = Solution()
re = obj.duplicate(nums)
print(re)
|
bb2dd47c253fd1d7226b49f6a73d0f93658334c8 | wulinlw/leetcode_cn | /top-interview-quesitons-in-2018/string_3.py | 1,781 | 3.65625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/featured/card/top-interview-quesitons-in-2018/275/string/1138/
# 单词拆分
# 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
# 说明:
# 拆分时可以重复使用字典中的单词。
# 你可以假设字典中没有重复的单词。
# 示例 1:
# 输入: s = "leetcode", wordDict = ["leet", "code"]
# 输出: true
# 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
# 示例 2:
# 输入: s = "applepenapple", wordDict = ["apple", "pen"]
# 输出: true
# 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
# 注意你可以重复使用字典中的单词。
# 示例 3:
# 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
# 输出: false
# https://blog.csdn.net/weixin_42771166/article/details/85320822
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
if len(s) == 0 or not wordDict:
return False
max_stride = max([len(x) for x in wordDict])#字典最长值
print max_stride
res = [0] * (len(s) + 1)
res[0] = 1
for i in range(1, len(s) + 1):
for j in range(i-max_stride, i):
# for j in range(i):#不减枝
if res[j] == 1 and s[j:i] in wordDict:
res[i] = 1
if res[-1] == 1:
return True
else:
return False
ss = "applepenapple"
wordDict = ["apple", "pen"]
s = Solution()
res = s.wordBreak(ss, wordDict)
print(res)
|
7799a49165b44fdc5f7c6064432c6204f384286b | wulinlw/leetcode_cn | /leetcode-vscode/563.二叉树的坡度.py | 1,736 | 3.875 | 4 | #
# @lc app=leetcode.cn id=563 lang=python3
#
# [563] 二叉树的坡度
#
# https://leetcode-cn.com/problems/binary-tree-tilt/description/
#
# algorithms
# Easy (53.09%)
# Likes: 54
# Dislikes: 0
# Total Accepted: 8.9K
# Total Submissions: 16.7K
# Testcase Example: '[1,2,3]'
#
# 给定一个二叉树,计算整个树的坡度。
#
# 一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
#
# 整个树的坡度就是其所有节点的坡度之和。
#
# 示例:
#
#
# 输入:
# 1
# / \
# 2 3
# 输出: 1
# 解释:
# 结点的坡度 2 : 0
# 结点的坡度 3 : 0
# 结点的坡度 1 : |2-3| = 1
# 树的坡度 : 0 + 0 + 1 = 1
#
#
# 注意:
#
#
# 任何子树的结点的和不会超过32位整数的范围。
# 坡度的值不会超过32位整数的范围。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findTilt(self, root: TreeNode) -> int:
if not root:return 0
tilt=0
def findTiltHelp(root):
nonlocal tilt
if not root:return 0
l = findTiltHelp(root.left)
r = findTiltHelp(root.right)
tilt += abs(l-r) #每个节点的坡度
return l+r+root.val #每个节点的左,根,右的和
findTiltHelp(root)
return tilt
# @lc code=end
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(3)
root = t1
root.left = t2
root.right = t3
o = Solution()
# print(o.levelOrder(t))
print(o.findTilt(root)) |
66fbee2c03751ac6ca76c7b9e1b1449cc609597d | wulinlw/leetcode_cn | /leetcode-vscode/98.验证二叉搜索树.py | 4,208 | 3.8125 | 4 | #
# @lc app=leetcode.cn id=98 lang=python3
#
# [98] 验证二叉搜索树
#
# https://leetcode-cn.com/problems/validate-binary-search-tree/description/
#
# algorithms
# Medium (29.10%)
# Likes: 543
# Dislikes: 0
# Total Accepted: 103.5K
# Total Submissions: 340.3K
# Testcase Example: '[2,1,3]'
#
# 给定一个二叉树,判断其是否是一个有效的二叉搜索树。
#
# 假设一个二叉搜索树具有如下特征:
#
#
# 节点的左子树只包含小于当前节点的数。
# 节点的右子树只包含大于当前节点的数。
# 所有左子树和右子树自身必须也是二叉搜索树。
#
#
# 示例 1:
#
# 输入:
# 2
# / \
# 1 3
# 输出: true
#
#
# 示例 2:
#
# 输入:
# 5
# / \
# 1 4
# / \
# 3 6
# 输出: false
# 解释: 输入为: [5,1,4,null,null,3,6]。
# 根节点的值为 5 ,但是其右子节点值为 4 。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 层次遍历
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# 从根开始遍历,每层写入一个新数组
# 在将left ,right写入下次需要巡皇的数组
# 循环完成即可得到每层的数组
queue = [root]
res = []
if not root:
return []
while queue:
templist = []#此层的数组
templen =len(queue)
for i in range(templen):
temp = queue.pop(0)
templist.append(temp.val)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
# print(templist)
res.append(templist)
return res
# 递归
def isValidBST(self, root: TreeNode) -> bool:
if not root:return True
def dfs(root, small, big): #需要带上最大值,最小值取到下一次比较
if not root:return True
val = root.val
if val <= small or val >= big:
return False
if not dfs(root.left, small, val):
return False
if not dfs(root.right, val, big):
return False
return True
return dfs(root, float('-inf'), float('inf'))
# 中序遍历
def isValidBST(self, root: TreeNode) -> bool:
stack, inorder = [], float('-inf')
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
# 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
if root.val <= inorder:
return False
inorder = root.val
root = root.right
return True
# @lc code=end
# 5
# 1 4
# 3 6
# t1 = TreeNode(5)
# t2 = TreeNode(1)
# t3 = TreeNode(4)
# t4 = TreeNode(3)
# t5 = TreeNode(6)
# root = t1
# root.left = t2
# root.right = t3
# t3.left = t4
# t3.right = t5
def stringToTreeNode(input):
inputValues = [s.strip() for s in input.split(',')]
print(inputValues)
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
input = "5,1,4,null,null,3,6"
input = "10,5,15,null,null,6,20"
root = stringToTreeNode(input)
o = Solution()
# print(o.levelOrder(root))
print(o.isValidBST(root)) |
d8ee8504bbeea0dc8d222d93e9a13c16ff5ca4d8 | wulinlw/leetcode_cn | /leetcode-vscode/820.单词的压缩编码.py | 4,185 | 3.796875 | 4 | #
# @lc app=leetcode.cn id=820 lang=python3
#
# [820] 单词的压缩编码
#
# https://leetcode-cn.com/problems/short-encoding-of-words/description/
#
# algorithms
# Medium (40.03%)
# Likes: 70
# Dislikes: 0
# Total Accepted: 14.1K
# Total Submissions: 32.8K
# Testcase Example: '["time", "me", "bell"]'
#
# 给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。
#
# 例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0,
# 2, 5]。
#
# 对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。
#
# 那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
#
#
#
# 示例:
#
# 输入: words = ["time", "me", "bell"]
# 输出: 10
# 说明: S = "time#bell#" , indexes = [0, 2, 5] 。
#
#
#
#
# 提示:
#
#
# 1 <= words.length <= 2000
# 1 <= words[i].length <= 7
# 每个单词都是小写字母 。
#
#
#
import collections,functools
from typing import List
# @lc code=start
#前缀树 Trie树
class TrieNode:
def __init__(self):
self.children = {} #记录下一个节点,注意是字典,查找0(1)
self.dept = 0 #深度
def addWord(self, word, idx):
if idx>=len(word):return #递归终止条件,超过长度时结束。 下面有就返回,没有就创建
tmpNode = self.children[word[idx]] if self.children.__contains__(word[idx]) else TrieNode()
tmpNode.dept = idx + 1 #深度+1
tmpNode.addWord(word, idx+1) #递归下一个字符
self.children[word[idx]] = tmpNode #记录当前字符
def count(self): #这个是递归函数
rst = 0
for k in self.children: #循环当前的节点
rst += self.children[k].count() #迭代他的子节点,一直迭代到最底层
if not self.children: #到最后深度+1,这样rst就是所有分支的深度总和
return self.dept + 1
return rst
class Solution:
#存储后缀,循环去除相同后缀
# https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
def minimumLengthEncoding2(self, words: List[str]) -> int:
s = set(words) #先去重
for word in words: #依次循环每个单词
for j in range(1, len(word)): #截取子串,取后缀,
if word[j:] in s: #存在的后缀都删掉
s.remove(word[j:])
length = 0 #计算总长
for i in s:
length += len(i) + 1 #单词长度+#的一个长度
return length
def minimumLengthEncoding3(self, words: List[str]) -> int:
words = list(set(words)) #remove duplicates
#Trie is a nested dictionary with nodes created
# when fetched entries are missing
Trie = lambda: collections.defaultdict(Trie)
trie = Trie()
#reduce(..., S, trie) is trie[S[0]][S[1]][S[2]][...][S[S.length - 1]]
nodes = [functools.reduce(dict.__getitem__, word[::-1], trie)
for word in words]
print(nodes)
#Add word to the answer if it's node has no neighbors
return sum(len(word) + 1
for i, word in enumerate(words)
if len(nodes[i]) == 0)
# 看这个,前缀树 Trie
# https://leetcode-cn.com/problems/short-encoding-of-words/solution/3chong-fang-fa-python3-by-zhenxiangsimple/
def minimumLengthEncoding(self, words: List[str]) -> int:
words = [word[::-1] for word in set(words)]
trie = TrieNode()
for word in words:
trie.addWord(word, 0)
return trie.count()
# @lc code=end
words = ["time", "me", "bell"]
o = Solution()
print(o.minimumLengthEncoding(words)) |
15acb129012387c2a2c05e982a16a9e2d454660a | wulinlw/leetcode_cn | /leetcode-vscode/897.递增顺序查找树.py | 2,420 | 3.9375 | 4 | #
# @lc app=leetcode.cn id=897 lang=python3
#
# [897] 递增顺序查找树
#
# https://leetcode-cn.com/problems/increasing-order-search-tree/description/
#
# algorithms
# Easy (65.76%)
# Likes: 58
# Dislikes: 0
# Total Accepted: 8K
# Total Submissions: 12.1K
# Testcase Example: '[5,3,6,2,4,null,8,1,null,null,null,7,9]'
#
# 给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
#
#
#
# 示例 :
#
# 输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]
#
# 5
# / \
# 3 6
# / \ \
# 2 4 8
# / / \
# 1 7 9
#
# 输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
#
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# \
# 7
# \
# 8
# \
# 9
#
#
#
# 提示:
#
#
# 给定树中的结点数介于 1 和 100 之间。
# 每个结点都有一个从 0 到 1000 范围内的唯一整数值。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 中序遍历 + 构造新的树
def increasingBST(self, root: TreeNode) -> TreeNode:
if not root:return None
re = []
def dfs(root):
nonlocal re
if not root:return None
dfs(root.left)
re.append(root.val)
dfs(root.right)
return root
dfs(root)
ans = p = TreeNode(0)
for i in re:
p.right = TreeNode(i)
p = p.right
return ans.right
# 中序遍历 + 更改树的连接方式
def increasingBST2(self, root):
def inorder(node):
if node:
inorder(node.left)
node.left = None
self.cur.right = node
self.cur = node
inorder(node.right)
ans = self.cur = TreeNode(None)
inorder(root)
return ans.right
# @lc code=end
t1 = TreeNode(5)
t2 = TreeNode(3)
t3 = TreeNode(6)
t4 = TreeNode(2)
t5 = TreeNode(4)
t6 = TreeNode(8)
root = t1
root.left = t2
root.right = t3
t2.left = t4
t2.right = t5
t3.right = t6
o = Solution()
t = o.increasingBST(root)
# print(o.increasingBST(root))
re = []
while t:
re.append(t.val)
t = t.right
print(re) |
3192958328b62328c5bcc2c89a2ef2fc53ba001b | wulinlw/leetcode_cn | /leetcode-vscode/606.根据二叉树创建字符串.py | 2,203 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=606 lang=python3
#
# [606] 根据二叉树创建字符串
#
# https://leetcode-cn.com/problems/construct-string-from-binary-tree/description/
#
# algorithms
# Easy (52.76%)
# Likes: 98
# Dislikes: 0
# Total Accepted: 9.4K
# Total Submissions: 17.7K
# Testcase Example: '[1,2,3,4]'
#
# 你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
#
# 空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
#
# 示例 1:
#
#
# 输入: 二叉树: [1,2,3,4]
# 1
# / \
# 2 3
# /
# 4
#
# 输出: "1(2(4))(3)"
#
# 解释: 原本将是“1(2(4)())(3())”,
# 在你省略所有不必要的空括号对之后,
# 它将是“1(2(4))(3)”。
#
#
# 示例 2:
#
#
# 输入: 二叉树: [1,2,3,null,4]
# 1
# / \
# 2 3
# \
# 4
#
# 输出: "1(2()(4))(3)"
#
# 解释: 和第一个示例相似,
# 除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
#
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree2str(self, root: TreeNode) -> str:
if not root: return ""
re = ""
def convert(root):
if not root:
return ""
elif not root.left and not root.right:
return str(root.val)
#注意这里elif,只能选一条路走
elif root.right:
return str(root.val) + "(" + convert(root.left) + ")" + "(" + convert(root.right) + ")"
else:
return str(root.val) + "(" + convert(root.left) + ")"
#没有右节点时,这里会省去右节点的()
re += convert(root)
return re
# @lc code=end
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(3)
t4 = TreeNode(4)
root = t1
root.left = t2
root.right = t3
t2.left = t4
o = Solution()
print(o.tree2str(root)) |
940b4d34f8c3c69f861cb1073cb9935f503835bf | wulinlw/leetcode_cn | /leetcode-vscode/350.两个数组的交集-ii.py | 1,630 | 3.765625 | 4 | #
# @lc app=leetcode.cn id=350 lang=python3
#
# [350] 两个数组的交集 II
#
# https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/description/
#
# algorithms
# Easy (48.66%)
# Likes: 315
# Dislikes: 0
# Total Accepted: 103.1K
# Total Submissions: 205.9K
# Testcase Example: '[1,2,2,1]\n[2,2]'
#
# 给定两个数组,编写一个函数来计算它们的交集。
#
# 示例 1:
#
# 输入: nums1 = [1,2,2,1], nums2 = [2,2]
# 输出: [2,2]
#
#
# 示例 2:
#
# 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
# 输出: [4,9]
#
# 说明:
#
#
# 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
# 我们可以不考虑输出结果的顺序。
#
#
# 进阶:
#
#
# 如果给定的数组已经排好序呢?你将如何优化你的算法?
# 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
# 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
#
#
#
# @lc code=start
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
m = collections.Counter()
for num in nums1:
m[num] += 1
intersection = list()
for num in nums2:
if (count := m.get(num, 0)) > 0:
intersection.append(num)
m[num] -= 1
if m[num] == 0:
m.pop(num)
return intersection
# @lc code=end
|
2d2c4fe3cd12f51c41aeb1dea6920d4d2752bb53 | wulinlw/leetcode_cn | /剑指offer/43_从1到n整数中1出现的次数.py | 3,313 | 3.640625 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题43:从1到n整数中1出现的次数
# // 题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数。例如
# // 输入12,从1到12这些整数中包含1 的数字有1,10,11和12,1一共出现了5次。
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
# https://blog.csdn.net/ggdhs/article/details/90311852
# 如果要计算百位上1出现的次数,它要受到3方面的影响:百位上的数字,百位以下(低位)的数字,百位以上(高位)的数字。
# ① 如果百位上数字为0,百位上可能出现1的次数由更高位决定。比如:12013,则可以知道百位出现1的情况可能是:100-199,1100-1199,2100-2199,……,11100-11199,一共1200个。正好等于更高位数字(12)乘以 当前位数(100)。
# ② 如果百位上数字为1,百位上可能出现1的次数不仅受更高位影响还受低位影响。比如:12113,则可以知道百位受高位影响出现的情况是:100-199,1100-1199,2100-2199,…,11100-11199,一共1200个。等于更高位数字(12)乘以 当前位数(100)。但同时由于低位为13,百位出现1的情况还可能是:12100~12113,一共14个,等于低位数字(113)+1。
# ③ 如果百位上数字大于1(2-9),则百位上出现1的情况仅由更高位决定,比如12213,则百位出现1的情况是:100-199,1100-1199,2100-2199,…,11100-11199,12100-12199,一共有1300个,等于更高位数字+1(12+1)乘以当前位数(100)。
# 从最低位开始,逐位遍历,
res = 0
i = 1 # 个位开始
while n // i != 0:
high = n//(i*10) # 高位数
current = (n//i) % 10 # 第i位数
low = n - (n//i) * i # 低位数
if current == 0:
res += high * i
elif current == 1:
res += high * i + low + 1
else:
res += (high+1) * i
i *= 10
return res
#书上的,
def NumberOf1Between1AndN(self, nums):
nums = str(nums)
n = len(nums)
first = int(nums[0])
if n==1 and first==0:
return 0
if n==1 and first>0: #个位数中,只有一个1
return 1
# // 假设strN是"21345"
# // numFirstDigit是数字10000-19999的第一个位中1的数目
if first>1:
begin1 = pow(10, n-1)
elif first==1:
begin1 = int(nums[1:])+1
# // numOtherDigits是01346-21345除了第一位之外的数位中1的数目
other1 = first * (n-1) * pow(10, n-2)
# print(nums,begin1 , other1)
# // numRecursive是1-1345中1的数目
recursion1 = self.NumberOf1Between1AndN(int(nums[1:]))
return begin1 + other1 + recursion1
def test(self, num):
# 常规方法用来比较
ret = 0
for n in range(1, num+1):
for s in str(n):
if s == '1':
ret += 1
return ret
n=21345
obj = Solution()
print(obj.test(n))
print(obj.NumberOf1Between1AndN_Solution(n))
# print(obj.NumberOf1Between1AndN(n))
|
db50eae1594cc0bc7ee8f331ca3b6383a3217288 | wulinlw/leetcode_cn | /递归/recursion_5_3.py | 4,062 | 3.9375 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/orignial/card/recursion-i/260/conclusion/1233/
# 不同的二叉搜索树 II
# 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
# 示例:
# 输入: 3
# 输出:
# [
# [1,null,3,2],
# [3,2,null,1],
# [3,1,null,null,2],
# [2,1,3],
# [1,null,2,null,3]
# ]
# 解释:
# 以上的输出对应以下 5 种不同结构的二叉搜索树:
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# / / \ \
# 2 1 2 3
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class B_Tree(object):
def __init__(self, node=None):
self.root = node
def add(self, item=None):
#如果输入item是None 则表示一个空节点
node = TreeNode(x=item)
#如果是空树,则直接添到根
#此时判断空的条件为,
if not self.root or self.root.val is None:
self.root = node
else:
#不为空,则按照 左右顺序 添加节点
my_queue = []
my_queue.append(self.root)
while True:
cur_node = my_queue.pop(0)
#即如果该当前节点为空节点则直接跳过它,起到一个占位的作用
if cur_node.val is None:
continue
if not cur_node.left:
cur_node.left = node
return
elif not cur_node.right:
cur_node.right = node
return
else:
my_queue.append(cur_node.left)
my_queue.append(cur_node.right)
def build(self, itemList):
for i in itemList:
self.add(i)
def preTraverse(self, root):
'''
前序遍历
根在最前
从上到下,最左边的val,左、右
'''
if root==None:
return
print(root.val)
self.preTraverse(root.left)
self.preTraverse(root.right)
def midTraverse(self, root):
'''
中序遍历
根在中间
最左边的从左、val、右,...根...最右边的从左、val、右
'''
if root==None:
return
self.midTraverse(root.left)
print(root.val)
self.midTraverse(root.right)
def afterTraverse(self, root):
'''
后序遍历
根在最后
最左边的左、右,val,依次排列,最后是根
'''
if root==None:
return
self.afterTraverse(root.left)
self.afterTraverse(root.right)
print(root.val)
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
# 链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii/solution/bu-tong-de-er-cha-sou-suo-shu-ii-by-leetcode/
def generate_trees(start, end):
if start > end:
return [None,]
all_trees = []
for i in range(start, end + 1): # 当前数为root
left_trees = generate_trees(start, i - 1) #i是root,剩余 i - 1 个元素可用于左子树,n - i 个元素用于右子树。
right_trees = generate_trees(i + 1, end)
# 链接左右树
for l in left_trees:
for r in right_trees:
current_tree = TreeNode(i)
current_tree.left = l
current_tree.right = r
all_trees.append(current_tree)
return all_trees
return generate_trees(1, n) if n else []
n=3
S = Solution()
deep = S.generateTrees(n)
print("deep:",deep)
|
b43fa3334180039300923931d9259fe5a6ba832e | wulinlw/leetcode_cn | /leetcode-vscode/69.x-的平方根.py | 1,050 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#
# https://leetcode-cn.com/problems/sqrtx/description/
#
# algorithms
# Easy (37.57%)
# Likes: 364
# Dislikes: 0
# Total Accepted: 126.8K
# Total Submissions: 335.5K
# Testcase Example: '4'
#
# 实现 int sqrt(int x) 函数。
#
# 计算并返回 x 的平方根,其中 x 是非负整数。
#
# 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
#
# 示例 1:
#
# 输入: 4
# 输出: 2
#
#
# 示例 2:
#
# 输入: 8
# 输出: 2
# 说明: 8 的平方根是 2.82842...,
# 由于返回类型是整数,小数部分将被舍去。
#
#
#
# @lc code=start
class Solution:
#二分法 O(log(n))
def mySqrt(self, x: int) -> int:
l, r = 0, x
re = 0
while l<=r:
mid = (l + r) // 2
if mid * mid <= x:
re = mid
l = mid + 1
else:
r = mid - 1
return re
# @lc code=end
x = 4
o = Solution()
print(o.mySqrt(x)) |
72aadd6ad7c82acd94fd6500aea2f08d406da84e | wulinlw/leetcode_cn | /哈希表/hash-table_1_1.py | 2,228 | 3.984375 | 4 | #!/usr/bin/python
# coding:utf-8
# https://leetcode-cn.com/explore/learn/card/hash-table/203/design-a-hash-table/799/
# 设计哈希集合
# 不使用任何内建的哈希表库设计一个哈希集合
# 具体地说,你的设计应该包含以下的功能
# add(value):向哈希集合中插入一个值。
# contains(value) :返回哈希集合中是否存在这个值。
# remove(value):将给定值从哈希集合中删除。如果哈希集合中没有这个值,什么也不做。
# 示例:
# MyHashSet hashSet = new MyHashSet()
# hashSet.add(1)
# hashSet.add(2)
# hashSet.contains(1)
# // 返回 true
# hashSet.contains(3)
# // 返回 false(未找到)
# hashSet.add(2)
# hashSet.contains(2)
# // 返回 true
# hashSet.remove(2)
# hashSet.contains(2)
# // 返回 false(已经被删除)
# 注意:
# 所有的值都在[1, 1000000]的范围内。
# 操作的总数目在[1, 10000]范围内。
# 不要使用内建的哈希集合库。
class Node:
def __init__(self, val, nex):
self.val = val
self.nex = nex
class MyHashSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 1000
self.h = [Node(None, None) for _ in range(self.size)]
def add(self, key: int) -> None:
p = self.h[key % self.size]
node = p.nex
while node:
if node.val == key:
break
p = node
node = node.nex
else:
p.nex = Node(key, None)
def remove(self, key: int) -> None:
p = self.h[key % self.size]
node = p.nex
while node:
if node.val == key:
p.nex = node.nex
break
p = node
node = node.nex
def contains(self, key: int) -> bool:
"""
Returns true if this set contains the specified element
"""
node = self.h[key % self.size]
while node:
if node.val == key:
return True
node = node.nex
return False
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# obj.remove(key)
# param_3 = obj.contains(key)
|
54cd0bace7d37beaf42ea3520896257a5bd3d19b | wulinlw/leetcode_cn | /中级算法/sorting-and-searching_5.py | 2,508 | 3.765625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/50/sorting-and-searching/100/
# 在排序数组中查找元素的第一个和最后一个位置
# 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
# 你的算法时间复杂度必须是 O(log n) 级别。
# 如果数组中不存在目标值,返回 [-1, -1]。
# 示例 1:
# 输入: nums = [5,7,7,8,8,10], target = 8
# 输出: [3,4]
# 示例 2:
# 输入: nums = [5,7,7,8,8,10], target = 6
# 输出: [-1,-1]
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
re = [-1,-1]
if len(nums)==1:
if nums[0] == target:
return [0,0]
else:
return re
for i in range(0,len(nums)):
if nums[i] < target:
continue
if nums[i] == target and re[0] == -1:
re[0] = i
if i == len(nums)-1:
return [i,i]
for j in range(i+1,len(nums)):
if nums[j] == target:
re[1] = j
else:
break
if re[1] != -1:
return re
elif re[0] != -1 and re[1] == -1:
re[1] = re[0]
return re
else:
return [-1,-1]
return re
# 二分法
def searchRange2(self, nums, target):
if not nums:
return [-1,-1]
left, right = 0, len(nums)-1
while left<=right:
mid=left+(right-left)//2
if nums[mid]==target:#刚好找到,但不确定是头还是尾
l=r=mid
while l>=0 and nums[l]==target:#向左移动找到头
l-=1
while r<=len(nums)-1 and nums[r]==target:#想右移动找到尾
r+=1
return [l+1,r-1]
if nums[mid]<target:
left=mid+1
else:
right=mid-1
return [-1,-1]
# nums = [5,7,7,8,8,10]
# target = 8
# nums = [5,7,7,8,8,10]
# target = 6
# nums = [2,2]
# target = 2
# nums = [1,3]
# target = 1
nums = [1,3]
target = 3
s = Solution()
r = s.searchRange(nums, target)
print(r)
|
5f492700d7482fa2df271ec9088f8f06fbeeb568 | Bhavya-Tripathi/ComputerNetworks | /Assignment-3/test.py | 1,245 | 3.765625 | 4 | import socket,sys
print("Setting up server: ")
#Get hostname,IP
sock = socket.socket()
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
port = 6969
sock.bind((hostname,port)) #binds IP of localhost to port
print(hostname, '({})'.format(ip))
name = input('Enter your name:')
sock.listen(1) #to locate using socket
print("Waiting for incoming connection. Please run the client program...")
conn,addr = sock.accept() #To accept the incoming connection.
#Code only allows for one client to be connected. Chat happend between server and client.
print('Recieved connection... Connected to {},({})'.format(addr[0],addr[1]))
#The .format thingy helps make code look neat, instead of having multiple string concatenations.
client = conn.recv(4096)
client = client.decode() # Receives the connection and gets the name.
print(client, "has connected.\nType 'exit' to exit the chat room")
conn.send(name.encode())
#Begin the infinite chat loop
while True:
message = input('Me: ')
if message == 'exit':
message = "K bye then..."
conn.send(message.encode())
print("")
break
conn.send(message.encode())
message = conn.recv(4096)
message = message.decode()
print(client,":",message) |
efa5b93f22db52d9dfe98f8a95f3c8da4866aa24 | VictorSHJ/fundamentos-python | /palindroma.py | 1,116 | 4.125 | 4 | # GRUPO 2:
# Crea una funcion que dado una palabra diga si es palindroma o no.
def palindroma(palabra):
print(f"Palabra Normal: {palabra}, Palabra Invertida: {palabra[::-1]}")
if palabra == palabra[::-1]:
print("Es palindroma")
else:
print("No es palindroma")
print("Ingrese una palabra :")
palabra=input()
palindroma(palabra)
palabra="CursodePython"
print(palabra[0:3])
print(palabra[2:5])
# OTRO:
# - Crea una función que tome una lista y devuelva el primer y el último valor de la lista.
# Si la longitud de la lista es menor que 2, haga que devuelva False.
def recorrerlista(lista):
if len(lista)<2:
return False
else:
print(lista[0])
print(lista[len(lista)-1])
print(recorrerlista([7]))
print(recorrerlista([7,2,4,6,8]))
# - Crea una función que tome una lista y devuelva un diccionario con su mínimo, máximo, promedio y suma.
def devuelvedic(lista):
dic={"Minimo":min(lista),"Maximo":max(lista),"Promedio":sum(lista)/len(lista),"Suma":sum(lista)}
return dic
lista=[1,21,3,44,-15,6]
print("Diccionario:", devuelvedic(lista))
|
893ad93e796a1e7ac5fd1df23c8ab4a4c432a454 | SebastianStaab/AEMLproject | /tetris/testing.py | 806 | 3.515625 | 4 | cols = 10
rows = 20
board = [
[ 0 for x in range(cols) ]
for y in range(rows)
]
board += [[ 1 for x in range(cols)]]
def join_matrixes(mat1, mat2, mat2_off):
off_x, off_y = mat2_off
for cy, row in enumerate(mat2):
for cx, val in enumerate(row):
mat1[cy+off_y-1 ][cx+off_x] += val
return mat1
tetrimonio = [[1,1,1],[0,1,0]]
def check_collision(board, shape, offset):
off_x, off_y = offset
for cy, row in enumerate(shape):
for cx, cell in enumerate(row):
try:
if cell and board[ cy + off_y ][ cx + off_x ]:
return True
except IndexError:
return True
return False
print(join_matrixes(board,tetrimonio,(9,3)))
print(check_collision(board, tetrimonio,(9,3))) |
b7908c0d09dd1a60a6c355b67ad4d7f2b5b324a6 | jamesdschmidt/exercises-for-programmers | /23-troubleshooting-car-issues/troubleshooting_car_issues.py | 1,024 | 3.984375 | 4 | answer = input("Is the car silent when you turn the key? ")
if answer.lower().startswith("y"):
answer = input("Are the battery terminals corroded? ")
if answer.lower().startswith("y"):
print("Clean terminals and try starting again.")
else:
print("Replace cables and try again.")
else:
answer = input("Does the car make a clicking noise? ")
if answer.lower().startswith("y"):
print("Replace the battery.")
else:
answer = input("Does the car crank up but fail to start? ")
if answer.lower().startswith("y"):
print("Check spark plug connections.")
else:
answer = input("Does the engine start and then die? ")
if answer.lower().startswith("y"):
answer = input("Does your car have fuel injection? ")
if answer.lower().startswith("y"):
print("Get it in for service.")
else:
print("Check to ensure the choke is opening and closing.")
|
df0d8ad8924c8948c854619cef38c87f90a74e7e | jamesdschmidt/exercises-for-programmers | /11-currency-conversion/currency_conversion.py | 309 | 3.875 | 4 | DOLLAR_RATE = 100
euros = int(input("How many euros are you exchanging? "))
exchange_rate = float(input("What is the exchange rate? "))
dollars = round((euros * exchange_rate) / DOLLAR_RATE, 2)
print(f"{euros} euros at an exchange rate of {exchange_rate:,.2f} is\n"
f"{dollars:,.2f} U.S. dollars.")
|
a81d2c7a6c3213eb61126ec23759d462e0b6862c | jamesdschmidt/exercises-for-programmers | /14-tax-calculator/tax_calculator.py | 305 | 3.75 | 4 | TAX_RATE = 0.055
amount = float(input("What is the order amount? "))
state = input("What is the state? ")
total = amount
output = ""
if "wi" == state.lower():
tax = amount * TAX_RATE
output = f"The tax is ${tax:,.2f}.\n"
total += tax
output += f"The total is ${total:,.2f}"
print(output)
|
e75d330b5e9e8fa368266108785fad07875ffd97 | jamesdschmidt/exercises-for-programmers | /16-legal-driving-age/legal_driving_age.py | 119 | 4.09375 | 4 | age = int(input("What is your age? "))
print("You", "are not" if age < 16 else "are", "old enough to legally drive.")
|
bbf1b7caf79ccf7f09fa42a45915a12feb88eb8d | jamesdschmidt/exercises-for-programmers | /13-determining-compound-interest/determining_compound_interest.py | 503 | 3.734375 | 4 | principal = float(input("What is the principal amount? "))
rate = float(input("What is the rate? "))
years = int(input("What is the number of years? "))
compound = int(input("What is the number of times the interest\n"
"is compounded per year?"))
amount = round(principal * ((1 + (rate / 100) / compound) **
(compound * years)), 2)
print(f"${principal:.2f} invested at {rate}% for {years} years\n"
f"compounded {compound} times per year is ${amount:.2f}.")
|
14a129dab9189feff13e5be95e38aae5fefb5b36 | dwighthubbard/ipython_embedded_notebooks | /intro/3_tail.py | 754 | 3.828125 | 4 | # Blink an LED on pin 18.
# Connect a low-ohm (like 360 ohm) resistor in series with the LED.
import RPi.GPIO as GPIO
import time
# A variable so we can change the PIN number for this script in once place
# if we move the LED to a different pin.
PIN = 7
# Set the pin to do output
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.OUT)
# Loop forever turning our power outlet off and on
# WARNING: A relay is a physical device which can wear out if cycled
# many times quickly. So short sleep times (less than a few seconds)
# in this loop are probably not a good idea.
while True:
# Switch the pin off for half of a second
GPIO.output(PIN, 0)
time.sleep(5)
# Now turn it back on
GPIO.output(PIN, 1)
time.sleep(5)
GPIO.cleanup() |
b107480b098897c85a77f5bfa88ea20a4f78a497 | AlNiLo/LearnPython | /HomeW/!!!!L2_test_classroom_list.py | 1,326 | 3.875 | 4 | quest = input('По какому классу вывести оценки? ')
school = [
{'class':[
{'1':[
{'a':[1, 3, 4, 4, 3, 5, 3],
'b':[1, 2, 4, 4, 3, 4, 4],
'c':[1, 2, 2, 5, 4, 5, 5]
}
],
'2':[{'a':[2, 3, 3, 4, 3, 5, 3],
'b':[1, 2, 4, 4, 4, 4, 4],
'c':[1, 3, 2, 5, 4, 4, 2]
}
]
}
]
}
]
if quest == '2':
a = school[0]['class'][0]['2'][0]['a']
b = school[0]['class'][0]['2'][0]['b']
c = school[0]['class'][0]['2'][0]['c']
#for score in a, b ,c:
for score in a:
# print(school[0]['class'][0]['2'][0]) #- как вывести значение по ключам списка в списке?
print(score)
# for score in b:
# print(score)
# for score in c:
# print(score)
sum(i for i in a)
print(sum)
#if quest = '2':
# for score in school[0]['class'][0]['2'][0]:
# print(score)
#school_clsss = [{'school_class':'a'}]
# school = [{'class':[{'1':[{'a':[записать переменную с формулой подсчета оценок]','2','3','4','5'}] |
e5f82bbb3538305b49f22f9c1e8530a0e87a20fa | kardeepak/protostar | /format0.py | 228 | 3.609375 | 4 | import struct
# padding will pad and print an integer fron the stack. It will print 64 integers
padding = "%64d"
# Value that will be written to the target variable
value = struct.pack("I", 0xdeadbeef)
print(padding + value)
|
498cdb043ed9f878303fedb8d72019ce27d8faa0 | CodecoolBP20173/game_enhancement | /tictac_test.py | 6,627 | 3.71875 | 4 | import string
field = []
player_x_win = 0
player_o_win = 0
def print_field(): # print empty field with nested lists
alphabet = string.ascii_lowercase
print("\n" * 50)
for i in range(field_size):
field.append([" "])
for j in range(field_size):
field[i].append(" ")
line = "| "
letters = " "
for i in range(field_size):
letters += alphabet[i] + " "
print(letters)
for j in range(field_size):
for i in range(field_size):
line = line + str(field[i][j]) + " | "
line = line + str(j + 1)
print(line)
line = "| "
def move_interpreter(m):
alphabet = string.ascii_lowercase
x = int(alphabet.index(m[0]))
y = int(m[1]) - 1
coordinates = [x, y]
return coordinates
def check_empty(m):
if m == "start":
check_empty = False
else:
check_empty = False
coordinates = move_interpreter(m)
if field[coordinates[0]][coordinates[1]] == " ":
check_empty = True
return check_empty
def full_check():
full = True
for i in range(field_size):
for j in range(field_size):
if field[i][j] == " ":
full = False
return full
def move(player, m):
coordinates = move_interpreter(m)
field[coordinates[0]][coordinates[1]] = player
def win_check():
winner = " "
won = False
for i in range(field_size):
for j in range(field_size):
if field[i][j] == "X" or field[i][j] == "O":
try:
if field[i][j] == field[i+1][j] and field[i][j] == field[i+2][j]:
won = True
elif field[i][j] == field[i][j+1] and field[i][j] == field[i][j+2]:
won = True
elif field[i][j] == field[i+1][j+1] and field[i][j] == field[i+2][j+2]:
won = True
elif field[i][j] == field[i+1][j-1] and field[i][j] == field[i+2][j-2]:
won = True
except IndexError:
continue
return won
def clear_board():
for i in range(field_size):
for j in range(field_size):
field[i][j] = " "
def load_game():
global field_size
global player_x_win
global player_o_win
while True:
field_size = input("\nSet field size (3x3 - 8x8). Enter only one digit: ")
if field_size.isnumeric() == True:
field_size = int(field_size)
if field_size in range(3, 9):
break
else:
print("Please enter a valid value!")
continue
else:
print("Please enter a digit between 3 and 8!")
continue
print_field()
winner = " "
m = "start"
while True:
while check_empty(m) == False:
while True:
m = str(input(player_x + " move? (X) -- for exit press \"r\" "))
if m == "r":
print("\nThe final score is: " + player_x + ": " + str(player_x_win) + " - " + player_o + ": " + str(player_o_win))
print("Thank you for playing. Good bye!")
exit()
else:
if len(m) == 2 and m[0].isalpha() and m[1].isnumeric():
coordinates = move_interpreter(m)
if coordinates[0] < field_size and coordinates[1] < field_size:
break
else:
print("Please enter a valid field position!")
continue
else:
print("Please enter a valid field position!")
print("This position is already taken. Please choose another one.")
move("X", m)
print_field()
if win_check() == True:
player_x_win += 1
print(player_x + " won!")
print(player_x + ": " + str(player_x_win) + " - " + player_o + ": " + str(player_o_win))
clear_board()
display_menu()
if full_check() == True:
print("DRAW")
clear_board()
display_menu()
while check_empty(m) == False:
while True:
m = str(input(player_o + " move? (O) -- for exit press \"r\" "))
if m == "r":
print("\nThe final score is: " + player_x + ": " + str(player_x_win) + " - " + player_o + ": " + str(player_o_win))
print("Thank you for playing. Good bye!")
exit()
else:
if len(m) == 2 and m[0].isalpha() and m[1].isnumeric():
coordinates = move_interpreter(m)
if coordinates[0] < field_size and coordinates[1] < field_size:
break
else:
print("Please enter a valid field position!")
continue
else:
print("Please enter a valid field position!")
print("This position is already taken. Please choose another one.")
move("O", m)
print_field()
if win_check() == True:
player_o_win += 1
print(player_o + " won!")
print(player_x + ": " + str(player_x_win) + " - " + player_o + ": " + str(player_o_win))
clear_board()
display_menu()
if full_check() == True:
print("Draw.")
clear_board()
display_menu()
def display_menu():
while True:
print("\ns: Start game")
print("q: Quit game\n")
user_input = str(input("Select menu item: "))
if user_input == "s":
load_game()
elif user_input == "q":
print("\nThe final score is: " + player_x + ": " + str(player_x_win) + " - " + player_o + ": " + str(player_o_win))
print("Good bye!")
exit()
elif user_input == "r":
continue
def add_name():
global player_x
global player_o
player_x = input("Please enter Player X name: ")
while True:
player_o = input("Please enter Player O name: ")
if player_o == player_x:
print("This name is occuped. Please enter another one.")
continue
else:
break
display_menu()
add_name() |
cfba2c4ac2beb767417b1e8e46486dea23cdf26e | adamcharnock/repose | /repose/validators.py | 1,626 | 3.703125 | 4 | from booby.validators import *
import six
class Range(Integer):
"""This validator forces fields values to be within a given range (inclusive)"""
def __init__(self, min=None, max=None):
self.min = min
self.max = max
@nullable
def validate(self, value):
if self.max is not None:
try:
invalid = value > self.max
if six.PY2:
# Python 2 allows strings to be compared to ints, so
# do some type checking here too
invalid = invalid or not isinstance(value, type(self.max))
except TypeError:
raise errors.ValidationError('Invalid input data')
if invalid:
raise errors.ValidationError(
'Value {} exceeds maximum of {}'.format(value, self.max))
if self.min is not None:
try:
invalid = value < self.min
if six.PY2:
# Python 2 allows strings to be compared to ints, so
# do some type checking here too
invalid = invalid or not isinstance(value, type(self.min))
except TypeError:
raise errors.ValidationError('Invalid input data')
if invalid:
raise errors.ValidationError(
'Value {} is below the minimum of {}'.format(value, self.min))
class Dictionary(Validator):
@nullable
def validate(self, value):
if not isinstance(value, dict):
raise errors.ValidationError('value must be a dictionary')
|
5a0be252fff51c358f1360716f892c69078c98a1 | mirzaevolution/Python-Basics | /PythonApplication2/Statements.py | 790 | 3.890625 | 4 | import constant
"""
Python Program #1
"""
#line continuation statement
number1 = 1 + 2 + \
3 + 4 + \
5 + 6
number2 = (1 + 2 +
3 + 4 +
5 + 6)
print(number1)
print(number2)
# One line assignment
var1,var2,var3 = 1,12.4,"Mirza Ghulam Rasyid"
print(var1)
print(var2)
print(var3)
print(constant.PI)
constant.PI = 123;
print(constant.PI)
binary = 0b10100
octal = 0o37
hexadecimal = 0xaf123
print(binary,octal,hexadecimal)
#myName = input("Input your name: ")
#print("Your name is: ", myName)
#age = int(input("Input your age: "))
#print("You are ", age, " years old",sep="")
myMultiLineString = "This is Mirza. " + \
"Mirza is a developer."
print(myMultiLineString)
rawString = r"this is \n raw string \n\f\u"
print(rawString)
|
ca5941b7b2355135eb03c3d8880a741db9a221f2 | November29th/ObjectedOrientedCards | /objectOrientedCards.py | 1,719 | 3.796875 | 4 | from random import*
class Card(object):
def __init__(self, suit = None, value = None):
self.value = value
class Diamond(Card):
def __init__(self):
super(Diamond, self).__init__("Diamond", 4)
class Heart(Card):
def __init__(self):
super(Heart, self).__init__("Heart", 3)
class Club(Card):
def __init__(self):
super(Club, self).__init__("Club", 2)
class Spade(Card):
def __init__(self):
super(Spade, self).__init__("Spade", 1)
class SuitGame(object):
"""Contain methods for playing suit game"""
def __init__(self):
self.cards = []
def populate_deck(self):
self.cards += [Diamond() for i in range(13)]
self.cards += [Spade() for i in range(13)]
self.cards += [Heart() for i in range(13)]
self.cards += [Club() for i in range(13)]
return self.cards
def remove_card(self, card):
if card in self.cards:
self.cards.remove(card)
return self.cards
def deal_hand(self):
"""Returns a list of 4 randomly picked cards from our cards list"""
# initialize a new card list
new_cards = []
for i in range(4):
index = randint(0,51)
new_card = self.cards[index]
self.remove_card(new_card)
new_cards.append(new_card)
return new_cards
def calculate_score(self):
"""returns calculated value of cards"""
new_cards = self.deal_hand()
values = [c.value for c in new_cards]
print values
score = sum(values)
print score
return score
deck = SuitGame()
deck.populate_deck()
deck.deal_hand()
deck.calculate_score()
|
20bb2a14fbb695fa1d1868147e8e2afc147cecc3 | fatychang/pyimageresearch_examples | /ch10 Neural Network Basics/perceptron_example.py | 1,157 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 12:56:47 2019
This is an example for runing percenptron structure to predict bitwise dataset
You may use AND, OR and XOR in as the dataset.
A preceptron class is called in this example.
An example from book deep learning for computer vision with Python ch10
@author: fatyc
"""
from perceptron import Perceptron
import numpy as np
# construct the dataset
dataset_OR = np.asanyarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
dataset_AND = np.asanyarray([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
dataset_XOR = np.asanyarray([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]])
# extract the input and output
dataset = dataset_XOR
x = dataset[:,0:2]
y = dataset[:,-1]
# define the preceptron
print("[INFO] training preceptron...")
p = Perceptron(x.shape[1], alpha = 0.1)
p.fit(x, y, epochs=20)
# test the preceptron
print("[INFO] testing preceptron...")
# loop over the data point
for(x, target) in zip(x, y):
# make the prediction on the data point
pred = p.predict(x)
# print out the result
print("[INFO] data={}, ground-trut={}, pred={}".format(
x, target, pred))
|
fd608e74e03f957482ac06f6b55b9f2f3363434a | fatychang/pyimageresearch_examples | /barcode-detection-guide/detect_barcode.py | 2,746 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 13:04:46 2020
This script demonstrates the technique to detect the barcode
using computer vision and image processing technique
A edge detection approach is implemented in this script with opencv
This sample is inspired by the post from pyinagesearch
@author: jschang
"""
#import the packages
import numpy as np
import cv2
#input arguments
dir_input_image = "D:\\Jen\\_Documents\\eLearning\\Computer Vision\\pyimagesearch\\barcode-detection-guide\\detecting-barcodes-in-images\\images\\barcode_01.jpg"
#load the image via cv2
image = cv2.imread(dir_input_image)
#convert the image to gray scale
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#construct the gradient magnitude representation in the horizontal and vertical direction
#compute the Scharr gradient magnitude representation of the image in both x, y direction
gradX = cv2.Sobel(gray_img, ddepth= cv2.CV_32F, dx=1, dy=0, ksize=-1)
gradY = cv2.Sobel(gray_img, ddepth= cv2.CV_32F, dx=0, dy=1, ksize=-1)
#substract the y-gradient from the x-gradient
#left the region that have high horizontal and low vertical gradient
gradient = cv2.subtract(gradX, gradY)
#calculate absoulute values and converts the result to 8bit
gradient = cv2.convertScaleAbs(gradient)
#blur and threshold the image
#smooth out the high frequency noise in the gradient image
blurred = cv2.blur(gradient, (9,9))
#threshold the image to ignore the gradient less than 225
#set the ignored pixel to 0 (black), others to 255 (black)
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
#morphological operation to close the gaps by constructing a closing kernel
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21,7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
#remove the small blobs by perfoming a series of erosions and dilations
closed_erosion = cv2.erode(closed, None, iterations=4)
closed_dilation = cv2.dilate(closed_erosion, None, iterations=4)
#find the contours in the thresholded image, then sort the contours
#by their area, keeping only the largest
(cnts, _) = cv2.findContours(closed_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key=cv2.contourArea, reverse = True)[0]
#compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
box = np.int0(cv2.boxPoints(rect))
#draw a bounding box around the detected barcode
cv2.drawContours(image, [box], -1, (0, 255,0), 3)
#display the images
cv2.imshow("image", image)
cv2.imshow("gray", gray_img)
cv2.imshow("gradient", gradient)
cv2.imshow("blurred", blurred)
cv2.imshow("threshold", thresh)
cv2.imshow("closed", closed)
cv2.imshow("erosion", closed_erosion)
cv2.imshow("dilation", closed_dilation)
|
b7c3cf717dea0f7c9b95599c99e691e6b0fe16ea | amcatlin/CSCI156-ExceptionHandling | /ExceptionHandling answers.py | 1,155 | 3.859375 | 4 | __author__ = 'Alicia'
y = 'Enter SS#: '
inputstring = 'Please enter a valid social security number of the form ###-##-#### including the dashes: '
def question(s):
social = input(s).strip()
try:
AAA, GG, SSSS = social.split('-')
area = int(AAA)
group = int(GG)
serial = int(SSSS)
if len(AAA) == 3 and len(GG) == 2 and len(SSSS) == 4:
if AAA == '078' and GG == '05' and SSSS == '1120':
return None
elif 1 <= area < 900 and area != 666:
if 1 <= group <= 99:
if 1 <= serial <= 9999:
return AAA, GG, SSSS
else:
return None
else:
return None
else:
return None
else:
return None
except ValueError:
return None
def SS(s):
while True:
x = question(s)
if x is not None:
return x
else:
print('That was an invalid social security number, please re-enter.\n')
return SS(s)
print(SS(inputstring))
#print(SS(y)) |
84f18c6f127360133af6802d2cd698551d6a6665 | rarafa/crypto-course | /rot13.py | 778 | 3.765625 | 4 | #!/usr/bin/python3
import sys
def rot13(input):
output=""
for i in input:
if i.isalpha():
if i.islower():
if (ord(i)+13)%ord('z') < ord('a'):
output += chr( ((ord(i)+13)%ord('z'))+ord('a') )
else:
output += chr( (ord(i)+13)%ord('z') )
else:
if (ord(i)+13)%ord('Z') < ord('A'):
output += chr( ((ord(i)+13)%ord('Z'))+ord('A') )
else:
output += chr( (ord(i)+13)%ord('Z') )
return output
if len(sys.argv) < 2:
print("Usage:\t %s \"<input text>\"" % sys.argv[0], file=sys.stderr) #no can do, amigo
sys.exit()
print( sys.argv[1], rot13(sys.argv[1]), sep="\n" )
print("lorem ipsum")
|
c83a41d51e6061033feaf6054f63c3f570c1f03b | junejunejune/numpy_practice | /sort.py | 460 | 3.671875 | 4 | import numpy as np
def selection_sort(x):
for i in range(len(x)):
swap = i + np.argmin(x[i:])
(x[i], x[swap]) = (x[swap], x[i])
return x
def bogosort(x):
while np.any(x[:-1] > x[1:]):
np.random.shuffle(x)
return x
x = np.array([2,1,4,3,5])
print(selection_sort(x))
x = np.array([2,1,4,3,5])
print(bogosort(x))
x = np.array([2,1,4,3,5])
print(np.sort(x))
x = np.array([7,2,3,1,6,5,4])
print(np.partition(x,3))
|
b7a04a3f5513cfa9d6aca9f3cb548726ec953326 | Hegerstrand/energyMapperOld | /Python/venv/Lib/site-packages/copyfile/copyfile.py | 1,403 | 3.625 | 4 | import os
import shutil
import logging
def touch(fname, times=None):
"""Creates an empty file at fname, creating path if necessary
Answer taken from Stack Overflow http://stackoverflow.com/a/1160227
User: ephemient http://stackoverflow.com/users/20713
License: CC-BY-SA 3.0 https://creativecommons.org/licenses/by-sa/3.0/
"""
fpath, f = os.path.split(fname)
if not os.path.exists(fpath):
os.makedirs(fpath)
with open(fname, 'a'):
os.utime(fname, times)
def copyFile(src, dest):
"""Copies a source file to a destination whose path may not yet exist.
Keyword arguments:
src -- Source path to a file (string)
dest -- Path for destination file (also a string)
"""
#Src Exists?
try:
if os.path.isfile(src):
dpath, dfile = os.path.split(dest)
if not os.path.isdir(dpath):
os.makedirs(dpath)
if not os.path.exists(dest):
touch(dest)
try:
shutil.copy2(src, dest)
# eg. src and dest are the same file
except shutil.Error as e:
logging.exception('Error: %s' % e)
# eg. source or destination doesn't exist
except IOError as e:
logging.exception('Error: %s' % e.strerror)
except:
logging.exception('Error: src to copy does not exist.')
|
f2e5accccddc156ccc92d48cca4b7bc2a1f50d4f | szwagiers/sqlite | /ccsqlite/lesson3.py | 319 | 3.96875 | 4 | import sqlite3
conn = sqlite3.connect("database.db")
# put cursor
c = conn.cursor()
# execute sql directly to database
c.execute("CREATE TABLE IF NOT EXISTS books (title TEXT,pages INTEGER)")
c.execute('INSERT INTO books VALUES("The Count of Monte Cristo",1316)')
conn.commit()
c.execute('SELECT * FROM books')
|
2423751e0607aa434d00d5e909e19126ac366ee9 | PPCCCSCS/Flippant | /FlippantTutor.py | 91,171 | 4.28125 | 4 | """
File: FlippantTutor.py
The program teaches users how to play the dice game Flippant
via a simulated game with one to three computer-controlled
opponents. Their choices are chosen randomly, so players
shouldn't expect to learn strategies for competing with skilled
players, but this program should provide an excellent primer
for basic gameplay and scoring.
Flippant was developed Neil Austin and Shannon Benton.
Code written by Neil Austin, except where noted.
Dice graphics adapted from original art
by Lonnie Tapscott from the Noun Project
"""
###
### The code in this version is a mess; NO REFUNDS!
###
import re
import tkinter as tk
from tkinter import ttk, messagebox
import random
class FlippantGame:
def __init__(self,parent):
self._top = parent
self._top.geometry("+100+100")
self._top.title("Flippant Tutorial")
self.popUp = tk.Tk()
self.popUp.geometry("+100+100")
self.popUp.title("Default Title")
# Initialize variables, load images
self._InitVariables()
self._InitImages()
self._InitSwitches()
# Initialize frames in advance
self._InitAllFrames()
self._InitTitle()
self._InitNav()
self._InitControls()
self._InitCommentator()
# Load just the frames needed at the start
self._LoadTitle()
self._LoadMainFrame()
self.ScreenOne()
# ██╗ ██╗ █████╗ ██████╗ ██╗ █████╗ ██████╗ ██╗ ███████╗███████╗
# ██║ ██║██╔══██╗██╔══██╗██║██╔══██╗██╔══██╗██║ ██╔════╝██╔════╝
# ██║ ██║███████║██████╔╝██║███████║██████╔╝██║ █████╗ ███████╗
# ╚██╗ ██╔╝██╔══██║██╔══██╗██║██╔══██║██╔══██╗██║ ██╔══╝ ╚════██║
# ╚████╔╝ ██║ ██║██║ ██║██║██║ ██║██████╔╝███████╗███████╗███████║
# ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚══════╝╚══════╝
def _InitVariables(self):
# Some variables we'll need in multiple screens
self._isTraditional = True
self.styleVar = tk.BooleanVar(value=self._isTraditional)
self._opponents = 1
self.numOpponentsVar = tk.IntVar(value=self._opponents)
# Lists to contain each player's selection of dice
self.p1D = []
self.p2D = []
self.p3D = []
self.p4D = []
# Prepopulate those lists with the correct number of (impossible) dice
#for i in range(7):
# self.p1D.append("d0")
# self.p2D.append("d0")
# self.p3D.append("d0")
# self.p4D.append("d0")
# Each player's dice difference, before score calculation
self.p1Diff = 0
self.p2Diff = 0
self.p3Diff = 0
self.p4Diff = 0
# Each player's score
self.p1Score = 0
self.p2Score = 0
self.p3Score = 0
self.p4Score = 0
# Each player's name
self.p1Name = tk.StringVar()
self.p1Name.set("Player 1")
self.stayAnon = tk.BooleanVar(value=False)
self.Round = 1
# Need this on screen 5 / Game Board
self.isFlip = False
self.diceDepressed = 0
self.p1DiceInHand = []
# These really should be a class, but maybe next version
self.p2DiceAvailable = []
self.p2DiceInHand = []
self.p2DiceDiscards = []
self.p2DiceButtons = []
self.p2Name = tk.StringVar()
self.p2Name.set("Player 2")
self.p2Twins = False
self.CPU1 = [self.p2DiceAvailable,
self.p2DiceInHand,
self.p2DiceDiscards,
self.p2DiceButtons,
self.p2Name,
self.p2Twins
]
self.p3DiceAvailable = []
self.p3DiceInHand = []
self.p3DiceDiscards = []
self.p3DiceButtons = []
self.p3Name = tk.StringVar()
self.p3Name.set("Player 3")
self.p3Twins = False
self.CPU2 = [self.p3DiceAvailable,
self.p3DiceInHand,
self.p3DiceDiscards,
self.p3DiceButtons,
self.p3Name,
self.p3Twins
]
self.p4DiceAvailable = []
self.p4DiceInHand = []
self.p4DiceDiscards = []
self.p4DiceButtons = []
self.p4Name = tk.StringVar()
self.p4Name.set("Player 4")
self.p4Twins = False
self.CPU3 = [self.p4DiceAvailable,
self.p4DiceInHand,
self.p4DiceDiscards,
self.p4DiceButtons,
self.p4Name,
self.p4Twins
]
self.inRecovery = False
self.rolledTwins = False
# Need this to close up shop at endgame.
self.allButtons = []
# ███████╗██╗ ██╗██╗████████╗ ██████╗██╗ ██╗███████╗███████╗
# ██╔════╝██║ ██║██║╚══██╔══╝██╔════╝██║ ██║██╔════╝██╔════╝
# ███████╗██║ █╗ ██║██║ ██║ ██║ ███████║█████╗ ███████╗
# ╚════██║██║███╗██║██║ ██║ ██║ ██╔══██║██╔══╝ ╚════██║
# ███████║╚███╔███╔╝██║ ██║ ╚██████╗██║ ██║███████╗███████║
# ╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚══════╝
def _InitSwitches(self):
# These switches allow images and labels to be loaded when the window
# is first built and whenever they are changed by class methods
self.listDice = ("d4","d6","d8","d10","d100","d12","d20")
self.dieSwitch = {"d4":4,
"d6":6,
"d8":8,
"d10":10,
"d100":10,
"d12":12,
"d20":20}
self.imgSwitch = {"d4":self.imgD4,
"d6":self.imgD6,
"d8":self.imgD8,
"d10":self.imgD10,
"d100":self.imgD100,
"d12":self.imgD12,
"d20":self.imgD20}
self.greyedOut = {self.imgD4:self.imgD4g,
self.imgD6:self.imgD6g,
self.imgD8:self.imgD8g,
self.imgD10:self.imgD10g,
self.imgD100:self.imgD100g,
self.imgD12:self.imgD12g,
self.imgD20:self.imgD20g}
self.restoredD = {self.imgD4g:self.imgD4,
self.imgD6g:self.imgD6,
self.imgD8g:self.imgD8,
self.imgD10g:self.imgD10,
self.imgD100g:self.imgD100,
self.imgD12g:self.imgD12,
self.imgD20g:self.imgD20}
# ██╗███╗ ███╗ █████╗ ██████╗ ███████╗███████╗
# ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝██╔════╝
# ██║██╔████╔██║███████║██║ ███╗█████╗ ███████╗
# ██║██║╚██╔╝██║██╔══██║██║ ██║██╔══╝ ╚════██║
# ██║██║ ╚═╝ ██║██║ ██║╚██████╔╝███████╗███████║
# ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝
def _InitImages(self):
# Load Images
self.imgD0 = tk.PhotoImage(file="images\\d0.gif")
self.imgD4 = tk.PhotoImage(file="images\\d4.gif")
self.imgD6 = tk.PhotoImage(file="images\\d6.gif")
self.imgD8 = tk.PhotoImage(file="images\\d8.gif")
self.imgD10 = tk.PhotoImage(file="images\\d10.gif")
self.imgD100 = tk.PhotoImage(file="images\\d100.gif")
self.imgD12 = tk.PhotoImage(file="images\\d12.gif")
self.imgD20 = tk.PhotoImage(file="images\\d20.gif")
self.imgD4g = tk.PhotoImage(file="images\\d4g.gif")
self.imgD6g = tk.PhotoImage(file="images\\d6g.gif")
self.imgD8g = tk.PhotoImage(file="images\\d8g.gif")
self.imgD10g = tk.PhotoImage(file="images\\d10g.gif")
self.imgD100g = tk.PhotoImage(file="images\\d100g.gif")
self.imgD12g = tk.PhotoImage(file="images\\d12g.gif")
self.imgD20g = tk.PhotoImage(file="images\\d20g.gif")
# ███████╗██████╗ █████╗ ███╗ ███╗███████╗███████╗
# ██╔════╝██╔══██╗██╔══██╗████╗ ████║██╔════╝██╔════╝
# █████╗ ██████╔╝███████║██╔████╔██║█████╗ ███████╗
# ██╔══╝ ██╔══██╗██╔══██║██║╚██╔╝██║██╔══╝ ╚════██║
# ██║ ██║ ██║██║ ██║██║ ╚═╝ ██║███████╗███████║
# ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝
def _InitAllFrames(self):
# frames definitions and geometry
self._frmMain = tk.Frame(self._top)
self._frmTitle = tk.Frame(self._frmMain)
self._frmNav = tk.Frame(self._frmMain)
self._frmPlay = tk.Frame(self._frmMain)
self._frmMenu1 = tk.Frame(self._frmMain)
self._frmMenu2 = tk.Frame(self._frmMain)
self._frmMenu3 = tk.Frame(self._frmMain)
self._frmMenu4 = tk.Frame(self._frmMain)
self._frmBoard = tk.Frame(self._frmMain)
self._frmNav.grid(
row=2,
column=0,
pady=5,
sticky="SE")
def _LoadMainFrame(self):
self._frmMain.grid(
row=1,
column=0,
padx=5,
pady=5,
sticky="W"
)
def _LoadCommentator(self):
self.Commentator.grid(row=4,column=0)
self.Scrollbar.grid(row=4,column=1)
self.Scrollbar.config(command=self.Commentator.yview)
self.Commentator.config(yscrollcommand=self.Scrollbar.set)
def _InitCommentator(self):
# Commentator is the scrollable text box at the bottom of the screen
# where information about each new event is posted.
self.Commentator = tk.Text(
self._frmMain,
height=6,
width=74,
font="Verdana 12"
)
self.Scrollbar = tk.Scrollbar(self._frmMain)
# ██████╗ ██████╗ ███╗ ██╗████████╗██████╗ ██████╗ ██╗ ███████╗
# ██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██╔══██╗██╔═══██╗██║ ██╔════╝
# ██║ ██║ ██║██╔██╗ ██║ ██║ ██████╔╝██║ ██║██║ ███████╗
# ██║ ██║ ██║██║╚██╗██║ ██║ ██╔══██╗██║ ██║██║ ╚════██║
# ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║ ██║╚██████╔╝███████╗███████║
# ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝
#
def _LoadControls(self):
self.btnNext.grid_forget()
self.btnRecover.grid(
row=0,
column=0,
sticky="SE"
)
self.btnRoll.grid(
row=0,
column=1,
sticky="SE"
)
self.btnClear.grid(
row=0,
column=2,
sticky="SE"
)
def _InitControls(self):
# Actual game controls in _frmPlay
self.btnRecover = tk.Button(
self._frmNav,
text="Recover",
#command=Recover,
width=7,
font="Verdana 12 bold",
bg="green",
fg="white",
state="disabled"
)
self.btnRoll = tk.Button(
self._frmNav,
text="Roll",
#command=pass,
width=4,
font="Verdana 12 bold",
bg="green",
fg="white",
state="disabled"
)
self.btnClear = tk.Button(
self._frmNav,
text="Clear",
width=5,
font="Verdana 12 bold",
bg="green",
fg="white",
state="disabled"
)
# ███╗ ██╗ █████╗ ██╗ ██╗██╗ ██████╗ █████╗ ████████╗███████╗
# ████╗ ██║██╔══██╗██║ ██║██║██╔════╝ ██╔══██╗╚══██╔══╝██╔════╝
# ██╔██╗ ██║███████║██║ ██║██║██║ ███╗███████║ ██║ █████╗
# ██║╚██╗██║██╔══██║╚██╗ ██╔╝██║██║ ██║██╔══██║ ██║ ██╔══╝
# ██║ ╚████║██║ ██║ ╚████╔╝ ██║╚██████╔╝██║ ██║ ██║ ███████╗
# ╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝
#
def _LoadNav(self,state="normal"):
self.btnNext.grid(
row=1,
column=0,
sticky="SE"
)
if state == "disabled":
self.btnNext["state"] = "disabled"
self.popUp.focus()
def _InitNav(self):
# Where the NEXT button lives
self.btnNext = tk.Button(
self._frmNav,
text="Next",
#command=self.Next,
width=8,
font="Verdana 12 bold",
bg="green",
fg="white"
)
# ████████╗██╗████████╗██╗ ███████╗
# ╚══██╔══╝██║╚══██╔══╝██║ ██╔════╝
# ██║ ██║ ██║ ██║ █████╗
# ██║ ██║ ██║ ██║ ██╔══╝
# ██║ ██║ ██║ ███████╗███████╗
# ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝
#
def _LoadTitle(self):
self._frmTitle.grid(
row=0,
column=0,
padx=5,
pady=10,
columnspan=7,
sticky="NEWS"
)
self.lblTitleL1.grid(
row=0,
column=0,
columnspan=1,
sticky="NEWS"
)
self.lblTitleL2.grid(
row=0,
column=1,
columnspan=1,
sticky="NEWS"
)
def _InitTitle(self):
# TKinter doesn't want to space politely, so here's a hack
self.lblTitleL1 = tk.Label(
self._frmTitle,
text="",
#width=15,
)
self.lblTitleL2 = tk.Label(
self._frmTitle,
text="",
#width=15,
)
# The actual Title portion of this Frame
self.lblTitleFLIP = tk.Label(
self._frmTitle,
text="FLIP",
anchor="e",
width=5,
bg="green",
fg="white",
font="Verdana 16 bold"
).grid(
row=0,
column=2,
columnspan=1,
sticky="NES"
)
self.lblTitlePANT = tk.Label(
self._frmTitle,
text="PANT",
anchor="w",
width=5,
bg="white",
fg="green",
font="Verdana 16 bold"
).grid(
row=0,
column=3,
columnspan=1,
sticky="NES"
)
self.lblTitleTutor = tk.Label(
self._frmTitle,
text="Game Tutorial",
width=12,
font="Verdana 14",
anchor="w"
).grid(
row=0,
column=4,
columnspan=1,
sticky="NEWS"
)
self.lblTitleR1 = tk.Label(
self._frmTitle,
text="",
#width=15,
).grid(
row=0,
column=5,
columnspan=1,
sticky="NEWS"
)
self.lblTitleR2 = tk.Label(
self._frmTitle,
text=""
).grid(
row=0,
column=6,
columnspan=1,
sticky="NEWS"
)
def Cheat(self):
tk.messagebox.showwarning("Hey!","Cheating not yet implemented")
def Next(self, event=None):
self._scrSwitch[self._nextScreen]()
self._nextScreen+=1
# ██████╗ ██████╗ ██████╗ ██╗ ██╗██████╗ ███████╗
# ██╔══██╗██╔═══██╗██╔══██╗██║ ██║██╔══██╗██╔════╝
# ██████╔╝██║ ██║██████╔╝██║ ██║██████╔╝███████╗
# ██╔═══╝ ██║ ██║██╔═══╝ ██║ ██║██╔═══╝ ╚════██║
# ██║ ╚██████╔╝██║ ╚██████╔╝██║ ███████║
# ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝
#
def Messages(self, title="PopUp Window", txt="Message Failed", h=10, hide=True):
self.popUp.geometry("+100+100")
self.popUp.title(title)
f = tk.Frame(self.popUp)
f.grid(column=0,row=0)
t = tk.Text(self.popUp,
padx=20,
width=60,
height=h,
wrap="word",
font="Verdana 12")
t.grid(column=0,row=0)
t.insert('1.0',"\n"+txt)
def HidePopUp(e='<None>'):
self.popUp.withdraw()
t.destroy()
f.destroy()
self._top.deiconify()
self.btnNext.focus()
def ShowPopUp(hide=False):
if hide == True:
self._top.withdraw()
self.popUp.deiconify()
self.popUp.focus()
btnClose = tk.Button(
self.popUp,
text="Close",
command=HidePopUp,
width=8,
font="Verdana 12 bold",
bg="green",
fg="white")
self.popUp.bind('<Return>',HidePopUp)
btnClose.grid(row=1,column=0)
ShowPopUp(hide)
# Big Text from: http://patorjk.com/software/taag/#p=display&f=ANSI%20Shadow
# ██╗ ██╗███╗ ██╗████████╗██████╗ ██████╗
#███║██╗ ██║████╗ ██║╚══██╔══╝██╔══██╗██╔═══██╗
#╚██║╚═╝ ██║██╔██╗ ██║ ██║ ██████╔╝██║ ██║
# ██║██╗ ██║██║╚██╗██║ ██║ ██╔══██╗██║ ██║
# ██║╚═╝ ██║██║ ╚████║ ██║ ██║ ██║╚██████╔╝
# ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝
# This seems redundant, but I guess if I need to reload the name screen,
# I can go straight back to it, instead of throwing the popup window again
def ScreenOne(self):
aboutText = \
"Flippant is a dice game for two or more players, designed to be played with \
standard table-top gaming (TTG) dice. This program will teach you how the \
rules of Flippant work for each player, and how your choices affect the \
outcome of the game.\n\
\n\
But before we begin, would you like to introduce yourself?"
self.Messages("Introduction",aboutText,8)
self._scrIntro()
def _scrIntro(self):
# Begin Layout
self._frmMenu1.grid(row=1,column=0)
self._LoadNav()
## ROW 0
# Moved to its own frame.
## ROW 1
self.lblWhatIsYourName = tk.Label(
self._frmMenu1,
font="Verdana 12",
text="Enter your name: "
)
self.lblWhatIsYourName.grid(
row=1,
column=0,
sticky="NEWS"
)
self.ntrWhatYourNameIs = tk.Entry(
self._frmMenu1,
width=10,
textvariable = self.p1Name,
)
self.ntrWhatYourNameIs.grid(
row=1,
column=1,
sticky="NEWS"
)
## ROW 2
self.chkAnonymous = ttk.Checkbutton(
self._frmMenu1,
text='I want to remain anonymous',
variable=self.stayAnon,
onvalue=True,
offvalue=False
)
self.chkAnonymous.grid(
row=2,
column=0,
columnspan=3,
sticky="NES"
)
def SetNextStateCHK(e):
# If not checked BEFORE this click
if self.stayAnon.get() == False:
self.ntrWhatYourNameIs['state'] = "disabled"
self.btnNext['state'] = "normal"
self.btnNext.bind('<Button-1>', self.ScreenTwo)
self.btnNext.bind('<Return>', self.ScreenTwo)
else:
self.ntrWhatYourNameIs['state'] = "normal"
if len(self.p1Name.get()) > 0:
self.btnNext['state'] = "normal"
self.btnNext.bind('<Button-1>', self.ScreenTwo)
self.btnNext.bind('<Return>', self.ScreenTwo)
else:
self.btnNext['state'] = "disabled"
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
def SetNextStateNTR(e):
if self.stayAnon.get() == False:
if len(self.p1Name.get()) == 0:
self.btnNext['state'] = "disabled"
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
else:
self.btnNext['state'] = "normal"
self.btnNext.bind('<Button-1>', self.ScreenTwo)
self.btnNext.bind('<Return>', self.ScreenTwo)
else:
if len(self.p1Name.get()) > 0:
self.btnNext['state'] = "disabled"
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
else:
self.btnNext['state'] = "normal"
self.btnNext.bind('<Button-1>', self.ScreenTwo)
self.btnNext.bind('<Return>', self.ScreenTwo)
# I'm not sure if this is a solid solution, but horseshoes/hand grenades
self.ntrWhatYourNameIs.bind('<KeyRelease>', SetNextStateNTR)
self.chkAnonymous.bind('<Button-1>', SetNextStateCHK)
self.btnNext.bind('<Button-1>', self.ScreenTwo)
self.btnNext.bind('<Return>', self.ScreenTwo)
#██████╗ ███████╗████████╗██╗ ██╗██╗ ███████╗
#╚════██╗██╗ ██╔════╝╚══██╔══╝╚██╗ ██╔╝██║ ██╔════╝
# █████╔╝╚═╝ ███████╗ ██║ ╚████╔╝ ██║ █████╗
#██╔═══╝ ██╗ ╚════██║ ██║ ╚██╔╝ ██║ ██╔══╝
#███████╗╚═╝ ███████║ ██║ ██║ ███████╗███████╗
#╚══════╝ ╚══════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝
def ScreenTwo(self,e):
aboutText = ""
if self.stayAnon.get() == True:
self.p1Name.set("Player 1")
aTH = 11
else:
aboutText += "Welcome " + self.p1Name.get() + ",\n\n"
aTH = 13
self.ntrWhatYourNameIs.unbind('<KeyRelease>')
self.chkAnonymous.unbind('<Button-1>')
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
aboutText += \
"There are two variations of Flippant that you'll need to decide between in a \
moment. Traditional Flippant is played with a hand of six standard dice, namely \
one each of d4, d6, d8, d10, d12, and d20, and one duplicate die of the player's \
choice. In the variant form of the game, each player may choose any combination \
of those dice, so, for example, a hand of seven d20 dice would be acceptable. \n\
\n\
On the next screen, you will choose which variation you wish to play."
self.Messages("Flippant Variations",aboutText,aTH)
self._scrGameMode()
def _scrGameMode(self):
# Begin Layout
self._frmMenu1.destroy()
self._frmMenu2.grid(row=1,column=0)
## ROW 2
# I kinda wanted to center this, but it's not worth the time right now.
self.rdoTraditional = tk.Radiobutton(
self._frmMenu2,
text="Traditional",
indicatoron=1,
variable=self.styleVar,
value=True,
font="Verdana 12"
).grid(
row=0,
column=0,
sticky="NSW"
)
self.rdoFreeCombo = tk.Radiobutton(
self._frmMenu2,
text="Freehand",
indicatoron=1,
variable=self.styleVar,
value=False,
font="Verdana 12"
).grid(
row=1,
column=0,
sticky="NSW"
)
self.btnNext.bind('<Button-1>', self.ScreenThree)
self.btnNext.bind('<Return>', self.ScreenThree)
#██████╗ ██████╗ ██╗ ██████╗██╗ ██╗ ██████╗ ██╗ ██████╗███████╗
#╚════██╗██╗ ██╔══██╗██║██╔════╝██║ ██╔╝ ██╔══██╗██║██╔════╝██╔════╝
# █████╔╝╚═╝ ██████╔╝██║██║ █████╔╝ ██║ ██║██║██║ █████╗
# ╚═══██╗██╗ ██╔═══╝ ██║██║ ██╔═██╗ ██║ ██║██║██║ ██╔══╝
#██████╔╝╚═╝ ██║ ██║╚██████╗██║ ██╗ ██████╔╝██║╚██████╗███████╗
#╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝╚══════╝
def ScreenThree(self,e):
if self.styleVar.get() == True:
aboutText = \
"Since each player has most of the same dice in their hand, Traditional \
Flippant puts a greater emphasis on chance and intuition. An observant player \
will know which dice are still in play after each round, and choose their own \
next roll accordingly.\n\
\n\
Right now, you just need to choose one die to complete your hand."
aTH = 8
else:
aboutText = \
"Freehand Flippant brings an added element of randomness to each game. Unless \
house rules require each player to choose their hand openly, there is no way to \
know in advance what dice you should choose to counter your opponent's hand. \
If they've chosen to play seven d20s, you already know that they'll never flip \
play, and are expecting to win with big numbers. You could choose a similar \
hand, and let fate decide, or build your hand with d4s and d6s in an attempt \
to flip the scoring?\n\
\n\
Your opponents today will be randomly generated, without any real strategy, so \
feel free to try out any combination of dice you can think of."
aTH = 14
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
self.Messages("Selecting Dice",aboutText,aTH)
self._scrPickDice()
def _scrPickDice(self):
# Begin Layout
self._frmMenu2.destroy()
self._frmMenu3.grid(row=1,column=0)
self.btnNext['state'] = "disabled"
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
tempList = []
self.urDice = []
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(0)))
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(1)))
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(2)))
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(3)))
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(4)))
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(5)))
self.urDice.append(tk.Button(self._frmMenu3,
text="??",
compound="top",
image=self.imgD0,
command=lambda: RemoveADie(6)))
def UpdateUrDice():
for i in range(7):
if self.urDice[i]['text'] != '??':
self.urDice[i].grid(row=5,column=i)
else:
self.urDice[i].grid_forget()
def AddADie(choice):
if len(tempList) < 7:
tempList.append(choice)
self.urDice[len(tempList)-1]['text'] = choice
self.urDice[len(tempList)-1]['image'] = self.imgSwitch[choice]
updated = True
else:
updated = False
if len(tempList) == 7:
self.btnNext['state'] = "normal"
self.btnNext.bind('<Button-1>', self.ScreenFour)
self.btnNext.bind('<Return>', self.ScreenFour)
UpdateUrDice()
def RemoveADie(choice):
self.btnNext['state'] = "disabled"
tempList.remove(self.urDice[choice]['text'])
i = choice
while i < 6:
self.urDice[i]['text'] = self.urDice[i+1]['text']
self.urDice[i]['image'] = self.urDice[i+1]['image']
i += 1
self.urDice[6]['text'] = '??'
# If you've removed a die, don't go to the next screen!
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
UpdateUrDice()
self._lblAvailableDice = tk.Label(
self._frmMenu3,
text="Available Dice: (Click to Add)",
font="Verdana 12 bold")
self._lblAvailableDice.grid(
row=0,
column=0,
columnspan=3)
# ROW 1
# d4
self.btnChooseD4 = tk.Button(
self._frmMenu3,
text="d4",
image=self.imgD4,
compound="top",
command=lambda: AddADie("d4")
)
self.btnChooseD4.grid(row=2,column=0)
# d6
self.btnChooseD6 = tk.Button(
self._frmMenu3,
text="d6",
image=self.imgD6,
compound="top",
command=lambda: AddADie("d6")
)
self.btnChooseD6.grid(row=2,column=1)
# d8
self.btnChooseD8 = tk.Button(
self._frmMenu3,
text="d8",
image=self.imgD8,
compound="top",
command=lambda: AddADie("d8")
)
self.btnChooseD8.grid(row=2,column=2)
# d10
self.btnChooseD10 = tk.Button(
self._frmMenu3,
text="d10",
image=self.imgD10,
compound="top",
command=lambda: AddADie("d10")
)
self.btnChooseD10.grid(row=2,column=3)
# d100
self.btnChooseD100 = tk.Button(
self._frmMenu3,
text="d100",
image=self.imgD100,
compound="top",
command=lambda: AddADie("d100")
)
self.btnChooseD100.grid(row=2,column=4)
# d12
self.btnChooseD12 = tk.Button(
self._frmMenu3,
text="d12",
image=self.imgD12,
compound="top",
command=lambda: AddADie("d12"),
)
self.btnChooseD12.grid(row=2,column=5)
# d20
self.btnChooseD20 = tk.Button(
self._frmMenu3,
text="d20",
image=self.imgD20,
compound="top",
command=lambda: AddADie("d20")
)
self.btnChooseD20.grid(row=2,column=6)
# ROW 2
self._lblYourDice = tk.Label(
self._frmMenu3,
text="Your Dice: (Click to Remove)",
font="Verdana 12 bold"
)
self._lblYourDice.grid(
row=4,
column=0,
columnspan=3
)
if self.styleVar.get() == True:
self.btnChooseD4.invoke()
self.urDice[0]['state'] = "disabled"
self.btnChooseD6.invoke()
self.urDice[1]['state'] = "disabled"
self.btnChooseD8.invoke()
self.urDice[2]['state'] = "disabled"
self.btnChooseD10.invoke()
self.urDice[3]['state'] = "disabled"
self.btnChooseD12.invoke()
self.urDice[4]['state'] = "disabled"
self.btnChooseD20.invoke()
self.urDice[5]['state'] = "disabled"
#██╗ ██╗ ██╗ ██╗███████╗██████╗ ███████╗██╗ ██╗███████╗
#██║ ██║██╗ ██║ ██║██╔════╝██╔══██╗██╔════╝██║ ██║██╔════╝
#███████║╚═╝ ██║ ██║█████╗ ██████╔╝███████╗██║ ██║███████╗
#╚════██║██╗ ╚██╗ ██╔╝██╔══╝ ██╔══██╗╚════██║██║ ██║╚════██║
# ██║╚═╝ ╚████╔╝ ███████╗██║ ██║███████║╚██████╔╝███████║
# ╚═╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚══════╝
def ScreenFour(self,e):
aboutText = \
"Flippant can be played with as few as two players, and as many players as you \
can find dice and table space for. Just to keep things simple while you are \
learning to play, we'll limit the number of opponents you can choose to two, \
three, or four. Your strategies may change subtly as more players are added to \
the game, but for now, just focus on learning how scoring changes with each roll."
aTH = 8
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
self.Messages("Selecting Dice",aboutText,aTH)
self._scrNumberOpps()
def _scrNumberOpps(self):
# Begin Layout
for i in range(7):
self.p1D.append(self.urDice[i]['text'])
self._frmMenu3.destroy()
self._frmMenu4.grid(row=1,column=0)
tk.Label(self._frmMenu4,
text="How many opponents?",
font="Verdana 12 bold").grid(
row=0,
column=0,
columnspan=4,
sticky="NSW")
self.rdoOneOpponent = tk.Radiobutton(
self._frmMenu4,
text="One",
indicatoron=1,
variable=self.numOpponentsVar,
value=1,
font="Verdana 12"
).grid(
row=1,
column=0,
sticky="NSW"
)
self.rdoTwoOpponents = tk.Radiobutton(
self._frmMenu4,
text="Two",
indicatoron=1,
variable=self.numOpponentsVar,
value=2,
font="Verdana 12"
).grid(
row=1,
column=1,
sticky="NSW"
)
self.rdoThreeOpponents = tk.Radiobutton(
self._frmMenu4,
text="Three",
indicatoron=1,
variable=self.numOpponentsVar,
value=3,
font="Verdana 12"
).grid(
row=1,
column=2,
sticky="NSW"
)
self.btnNext.bind('<Button-1>', self.ScreenFive)
self.btnNext.bind('<Return>', self.ScreenFive)
#███████╗ ██████╗ ██╗ █████╗ ██╗ ██╗██╗
#██╔════╝██╗ ██╔══██╗██║ ██╔══██╗╚██╗ ██╔╝██║
#███████╗╚═╝ ██████╔╝██║ ███████║ ╚████╔╝ ██║
#╚════██║██╗ ██╔═══╝ ██║ ██╔══██║ ╚██╔╝ ╚═╝
#███████║╚═╝ ██║ ███████╗██║ ██║ ██║ ██╗
#╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝
def ScreenFive(self,e):
aboutText = \
"Okay, " + self.p1Name.get() + ", it's time to play some Flippant!\n\
\n\
For the first three rounds, pick two dice, then click the 'roll' button. If you \
roll two of the same number, you'll get to reclaim one of your discarded dice, \
and if two or more players have the same winning score at the end of the third \
round, they'll get to pick one of their remaining dice to roll until there is a \
definite winner.\n\
\n\
Once you've finished your first game, you'll be able to change all of the \
options we've just gone through (in a single popup, no worries!) and try again \
with different choices."
aTH = 14
self.btnNext.unbind('<Button-1>')
self.btnNext.unbind('<Return>')
self.Messages("Time to Play!",aboutText,aTH)
self._scrGameBoard()
def _scrGameBoard(self):
# Begin Layout
self._frmMenu4.destroy()
self._frmBoard.grid(row=1,column=0)
self._LoadControls()
self.opponents = []
if self.numOpponentsVar.get() >= 1:
self.opponents.append(self.CPU1)
if self.numOpponentsVar.get() >= 2:
self.opponents.append(self.CPU2)
if self.numOpponentsVar.get() >= 3:
self.opponents.append(self.CPU3)
self.allButtons.extend([self.btnRecover,self.btnNext,self.btnClear])
if self.styleVar.get():
for i in self.opponents:
i[0].append("d4")
i[0].append("d6")
i[0].append("d8")
i[0].append("d10")
i[0].append("d12")
i[0].append("d20")
i[0].append(random.choice(self.listDice))
else:
for i in self.opponents:
for j in range(7):
i[0].append(random.choice(self.listDice))
self.lblPlayerName = tk.Label(
self._frmBoard,
text="Player\nName",
font="Verdana 12 bold"
)
self.lblRound = tk.Label(
self._frmBoard,
text="Round: ",
font="Verdana 12 bold"
)
self.lblRoundNum = tk.Label(
self._frmBoard,
text=str(self.Round),
font="Verdana 12",
bg="white"
)
self.lblStyle = tk.Label(
self._frmBoard,
text="Style: ",
font="Verdana 12 bold"
)
self.lblStyleName = tk.Label(
self._frmBoard,
text=("Traditional" if self.styleVar.get() == True else "Freehand"),
font="Verdana 12",
bg="white"
)
self.lblMode = tk.Label(
self._frmBoard,
text="Count/Flip: ",
font="Verdana 12 bold"
)
self.lblModeName = tk.Label(
self._frmBoard,
text=("Flip" if self.isFlip == True else "Count"),
font="Verdana 12",
bg=("black" if self.isFlip == True else "white"),
fg=("lime" if self.isFlip == True else "black")
)
self.lblDieOne = tk.Label(
self._frmBoard,
text="Larger\nDIE",
font="Verdana 12 bold"
)
self.lblDieTwo = tk.Label(
self._frmBoard,
text="Smaller\nDIE",
font="Verdana 12 bold"
)
self.lblRoundScore = tk.Label(
self._frmBoard,
text="Round\nScore",
font="Verdana 12 bold"
)
self.lblTotalScore = tk.Label(
self._frmBoard,
text="Total\nScore",
font="Verdana 12 bold"
)
self.lblPlayerName.grid(column=0,row=0)
self.lblRound.grid(column=1,row=0)
self.lblRoundNum.grid(column=2,row=0)
self.lblStyle.grid(column=3,row=0)
self.lblStyleName.grid(column=4,row=0)
self.lblMode.grid(column=5,row=0)
self.lblModeName.grid(column=6,row=0)
self.lblDieOne.grid(column=8,row=0)
self.lblDieTwo.grid(column=9,row=0)
self.lblRoundScore.grid(column=10,row=0)
self.lblTotalScore.grid(column=11,row=0)
# ___ _ __ _ ____ ___ ___ _ ____
# | |_) | | / /\ \ \_/ | |_ | |_) / / \ | |\ | | |_
# |_| |_|__ /_/--\ |_| |_|__ |_| \ \_\_/ |_| \| |_|__
#
self.lblP1Name = tk.Label(
self._frmBoard,
text=self.p1Name.get(),
font="Verdana 16 bold",
)
# Dice for Player 1
self.btnP1Die1 = tk.Button(
self._frmBoard,
text=self.p1D[0],
image=self.imgSwitch[self.p1D[0]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(0)
)
self.btnP1Die2 = tk.Button(
self._frmBoard,
text=self.p1D[1],
image=self.imgSwitch[self.p1D[1]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(1)
)
self.btnP1Die3 = tk.Button(
self._frmBoard,
text=self.p1D[2],
image=self.imgSwitch[self.p1D[2]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(2)
)
self.btnP1Die4 = tk.Button(
self._frmBoard,
text=self.p1D[3],
image=self.imgSwitch[self.p1D[3]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(3)
)
self.btnP1Die5 = tk.Button(
self._frmBoard,
text=self.p1D[4],
image=self.imgSwitch[self.p1D[4]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(4)
)
self.btnP1Die6 = tk.Button(
self._frmBoard,
text=self.p1D[5],
image=self.imgSwitch[self.p1D[5]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(5)
)
self.btnP1Die7 = tk.Button(
self._frmBoard,
text=self.p1D[6],
image=self.imgSwitch[self.p1D[6]],
compound="top",
relief="raised",
bd=3,
command=lambda: Toggle(6)
)
self.lblP1D1Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP1D2Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP1scrRound = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP1scrTotal = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP1Name.grid(column=0,row=1)
self.btnP1Die1.grid(column=1,row=1)
self.btnP1Die2.grid(column=2,row=1)
self.btnP1Die3.grid(column=3,row=1)
self.btnP1Die4.grid(column=4,row=1)
self.btnP1Die5.grid(column=5,row=1)
self.btnP1Die6.grid(column=6,row=1)
self.btnP1Die7.grid(column=7,row=1)
self.allButtons.extend([self.btnP1Die1,
self.btnP1Die2,
self.btnP1Die3,
self.btnP1Die4,
self.btnP1Die5,
self.btnP1Die6,
self.btnP1Die7]
)
self.lblP1D1Rolled.grid(column=8,row=1)
self.lblP1D2Rolled.grid(column=9,row=1)
self.lblP1scrRound.grid(column=10,row=1)
self.lblP1scrTotal.grid(column=11,row=1)
# Only used by Player 1. CPU players recover in-line.
def Recover():
dice = [self.btnP1Die1,
self.btnP1Die2,
self.btnP1Die3,
self.btnP1Die4,
self.btnP1Die5,
self.btnP1Die6,
self.btnP1Die7
]
# This for loop flips disabled and normal buttons
# so the player can choose from previously chosen
# dice, but not dice that haven't been used yet.
for die in dice:
if die['state'] == "disabled":
die['state'] = "normal"
die['relief'] = "raised"
else:
if die['relief'] == "raised":
die['state'] = "disabled"
die['relief'] = "flat"
else:
die['relief'] = "raised"
# Recovery is one-and-done per round, so reset it now.
self.btnRecover['state'] = "disabled"
self.inRecovery = False
self.diceDepressed = 0
self.p1DiceInHand.clear()
# Attach the command to the button after it has been defined.
self.btnRecover['command'] = Recover
def Roll():
self.lblP1D1Rolled['text'] = ""
self.lblP1D2Rolled['text'] = ""
dice = [self.btnP1Die1,
self.btnP1Die2,
self.btnP1Die3,
self.btnP1Die4,
self.btnP1Die5,
self.btnP1Die6,
self.btnP1Die7
]
# Dice selected in the previous round were indicated by using
# "ridge" for relief. Those should be reset to flat now
if self.Round < 5:
for die in dice:
if die['relief'] == "ridge":
die['relief'] = "flat"
# Opponents all need to choose dice to roll at this point.
for opps in self.opponents:
opps[3][8]['text'] = ""
opps[3][9]['text'] = ""
if self.Round < 5:
# Reset button ridges indicating choices from last round
for b in range(1,8):
if opps[3][b]['relief'] == "ridge":
opps[3][b]['relief'] = "flat"
tDie = random.choice(opps[0]) # randomly choose 1 die from available
opps[0].remove(tDie) # remove that die from available
opps[1].append(tDie) # add that die to hand
opps[2].append(tDie) # add that die to discards
# Before Round 4, a second die must be rolled for each opponent
if self.Round < 4:
tDie = random.choice(opps[0]) # randomly choose another die from available
opps[0].remove(tDie) # remove that die from available
opps[1].append(tDie) # add that die to hand
opps[2].append(tDie) # add that die to discards
# Set Twins flag for opponent if two of the same die are chosen
if self.dieSwitch[opps[1][0]] == self.dieSwitch[opps[1][1]]:
opps[5] = True
else:
opps[5] = False
# Get the number of sides of the smaller die
rDieSides = min(self.dieSwitch[opps[1][0]],
self.dieSwitch[opps[1][1]])
# 'roll' that smaller die
rDieRoll = random.randint(1,rDieSides)
# Write the result of that roll to the screen
opps[3][9]['text'] = rDieRoll
# Find a matching die in the opponent's hand
# and disable it (not guaranteed to be the
# same die randomly chosen, but who will know?
for b in range(1,8):
if opps[3][b]['text'] == opps[1][1] and\
opps[3][b]['state'] == "normal":
opps[3][b]['state'] = "disabled"
opps[3][b]['relief'] = "ridge"
break
# Get the number of sides of the larger die
lDieSides = max(self.dieSwitch[opps[1][0]],
self.dieSwitch[opps[1][1]])
# if both dice are the same, set the Twins flag
if lDieSides == rDieSides:
opps[5] = True
else:
opps[5] = False
# In round 4, each player picks their tiebreaker die
elif self.Round == 4:
lDieSides = self.dieSwitch[opps[1][0]]
# FOR OPPONENTS
# Find the unused die matching the click
# disable it, but highlight it with a ridge
for b in range(1,8):
if opps[3][b]['text'] == opps[1][0] and\
opps[3][b]['state'] == "normal":
opps[3][b]['state'] = "disabled"
opps[3][b]['relief'] = "ridge"
break
# Set all remaining opponent dice to disabled
for b in range(1,8):
opps[3][b]['state'] = "disabled"
# in Rounds 1-4 only
lDieRoll = random.randint(1,lDieSides)
opps[3][8]['text'] = lDieRoll
# If CPU rolls the same number on each die, return
# a randomly chosen die to their available dice list.
if self.Round < 4:
if lDieRoll == rDieRoll:
# List maintenance; important!
temp = random.choice(opps[2])
opps[2].remove(temp)
opps[0].append(temp)
# Update the button state for the selected die.
for b in range(1,8):
if opps[3][b]['text'] == temp and \
opps[3][b]['state'] == "disabled":
opps[3][b]['state'] = "normal"
# Rounds 1-4 only (dice don't change after Round 4)
for b in range(1,8):
if opps[3][b]['text'] == opps[1][0] and\
opps[3][b]['state'] == "normal":
opps[3][b]['state'] = "disabled"
opps[3][b]['relief'] = "ridge"
break
#
# Highlight score display based on roll results.
# ONLY changes highlights for CPU players. Player 1
# must be updated separately below.
#
if self.Round < 4:
# Highlight YELLOW if duplicate numbers rolled
# (CPU RECOVERS A DIE)
if lDieRoll == rDieRoll:
opps[3][8]['fg'] = "black"
opps[3][8]['bg'] = "yellow"
opps[3][9]['fg'] = "black"
opps[3][9]['bg'] = "yellow"
# Highlight GREY if same dice were rolled
# (NO FLIP, SCORE MULTIPLIERS APPLIED)
elif lDieSides == rDieSides:
opps[3][8]['fg'] = "SystemButtonFace"
opps[3][8]['bg'] = "grey"
opps[3][9]['fg'] = "SystemButtonFace"
opps[3][9]['bg'] = "grey"
# Highlight BLACK if larger die rolled lower
# (FLIP CONDITION!)
elif lDieRoll < rDieRoll:
self.isFlip = not self.isFlip
opps[3][8]['fg'] = "lime"
opps[3][8]['bg'] = "black"
opps[3][9]['fg'] = "lime"
opps[3][9]['bg'] = "black"
# Normal display. BLACK on GREY
else:
opps[3][8]['fg'] = "black"
opps[3][8]['bg'] = "SystemButtonFace"
opps[3][9]['fg'] = "black"
opps[3][9]['bg'] = "SystemButtonFace"
opps[1].clear()
# Show only one die roll after first three rounds.
# Set once in Round 4 then never change.
elif self.Round == 4:
opps[3][8]['fg'] = "black"
opps[3][8]['bg'] = "SystemButtonFace"
opps[3][9]['fg'] = "SystemButtonFace"
opps[3][9]['bg'] = "SystemButtonFace"
# For rounds 5+
else:
lDieSides = self.dieSwitch[opps[1][0]]
lDieRoll = random.randint(1,lDieSides)
opps[3][8]['text'] = lDieRoll
if self.Round <= 4:
# FOR PLAYER
# Disable all dice, set the chosen die to ridge
# and all other dice to flat
for die in dice:
if self.Round == 4:
die['state'] = "disabled"
if die['relief'] == "sunken":
die['state'] = "disabled"
die['relief'] = "ridge"
elif self.Round == 4:
die['relief'] = "flat"
# ALL ROUNDS NOW
# Flatten and disable used dice buttons
for die in dice:
if die['relief'] == "sunken":
die['relief'] = "flat"
die['state'] = "disabled"
# All players roll, do some math, update scoreboard
if len(self.p1DiceInHand) == 2:
lDieSides = max((self.dieSwitch[self.p1DiceInHand[0]],
self.dieSwitch[self.p1DiceInHand[1]]))
lDieRoll = random.randint(1,lDieSides)
self.lblP1D1Rolled['text'] = lDieRoll
rDieSides = min((self.dieSwitch[self.p1DiceInHand[0]],
self.dieSwitch[self.p1DiceInHand[1]]))
rDieRoll = random.randint(1,rDieSides)
self.lblP1D2Rolled['text'] = rDieRoll
# Set Twins flag for Player 1
if lDieSides == rDieSides:
self.rolledTwins = True
else:
self.rolledTwins = False
# YELLOW highlight for duplicate roll by Player 1
if lDieRoll == rDieRoll:
self.lblP1D1Rolled['bg'] = "yellow"
self.lblP1D1Rolled['fg'] = "black"
self.lblP1D2Rolled['bg'] = "yellow"
self.lblP1D2Rolled['fg'] = "black"
# Player 1 rolled twins, gets grey highlights
elif self.rolledTwins == True:
self.lblP1D1Rolled['fg'] = "white"
self.lblP1D1Rolled['bg'] = "grey"
self.lblP1D2Rolled['fg'] = "white"
self.lblP1D2Rolled['bg'] = "grey"
# FLIP/Inverted display colors on scoreboard for Player 1
elif lDieRoll < rDieRoll and not self.rolledTwins:
self.lblP1D1Rolled['bg'] = "black"
self.lblP1D1Rolled['fg'] = "lime"
self.lblP1D2Rolled['bg'] = "black"
self.lblP1D2Rolled['fg'] = "lime"
# Normal display colors on scoreboard for Player 1
else:
self.lblP1D1Rolled['bg'] = "SystemButtonFace"
self.lblP1D1Rolled['fg'] = "black"
self.lblP1D2Rolled['bg'] = "SystemButtonFace"
self.lblP1D2Rolled['fg'] = "black"
# Player 1's raw roll difference. **SIGNED**
self.p1Diff = lDieRoll - rDieRoll
# Flip the Flip flag if Player 1 rolls less on larger die
if self.p1Diff < 0 and not self.rolledTwins:
self.isFlip = not self.isFlip
# When Player 1 rolls the same value on two dice,
# Player 1 can recover one die from discards or last roll
if self.p1Diff == 0:
self.inRecovery = True
self.p1DiceInHand.clear()
# Flip normal/disabled for all dice in hand so Player 1
# can choose one previously played die to recover
for die in [self.btnP1Die1,
self.btnP1Die2,
self.btnP1Die3,
self.btnP1Die4,
self.btnP1Die5,
self.btnP1Die6,
self.btnP1Die7
]:
if die['state'] == "disabled":
die['state'] = "normal"
die['relief'] = "raised"
else:
die['state'] = "disabled"
die['relief'] = "flat"
else:
# Reset the Recovery mode flag if different numbers were rolled.
self.inRecovery = False
# If roll was clicked after Round 3, only display one die
else:
# Normal display for one die after Round 4
if self.Round == 4:
self.lblP1D1Rolled['bg'] = "SystemButtonFace"
self.lblP1D1Rolled['fg'] = "black"
self.lblP1D2Rolled['bg'] = "SystemButtonFace"
self.lblP1D2Rolled['fg'] = "SystemButtonFace"
oDieSides = self.dieSwitch[self.p1DiceInHand[0]]
oDieRoll = random.randint(1,oDieSides)
self.lblP1D1Rolled['text'] = oDieRoll
self.lblP1D2Rolled['text'] = ""
self.p1Diff = oDieRoll
# Reset button states and temp variables
if self.Round < 4:
self.diceDepressed = 0
self.p1DiceInHand = []
self.btnRoll['state'] = "disabled"
self.btnClear['state'] = "disabled"
# Update the player's score after player and cpus have rolled
if self.Round < 4:
if self.rolledTwins == True:
if self.isFlip == False:
self.lblP1scrRound['text'] = abs(self.p1Diff) * 2
else:
self.lblP1scrRound['text'] = abs(self.p1Diff) // 2
else:
self.lblP1scrRound['text'] = abs(self.p1Diff)
else:
self.lblP1scrRound['text'] = self.p1Diff
self.lblP1scrTotal['text'] = int(self.lblP1scrTotal['text']) + \
int(self.lblP1scrRound['text'])
self.lblP1scrRound['fg'] = "black"
self.lblP1scrRound['bg'] = "SystemButtonFace"
self.lblP1scrTotal['fg'] = "black"
self.lblP1scrTotal['bg'] = "SystemButtonFace"
# Update each CPU's score after everyone has rolled
for opps in self.opponents:
if self.Round < 4:
if opps[5] == True:
if self.isFlip == False:
opps[3][10]['text'] = abs(opps[3][8]['text'] - \
opps[3][9]['text']) * 2
else:
opps[3][10]['text'] = abs(opps[3][8]['text'] - \
opps[3][9]['text']) // 2
else:
opps[3][10]['text'] = abs(opps[3][8]['text'] -
\
opps[3][9]['text'])
else:
opps[3][10]['text'] = opps[3][8]['text']
opps[3][11]['text'] = int(opps[3][11]['text']) + \
int(opps[3][10]['text'])
# Reset Display Colors before setting Winner Colors
opps[3][10]['fg'] = "black"
opps[3][10]['bg'] = "SystemButtonFace"
opps[3][11]['fg'] = "black"
opps[3][11]['bg'] = "SystemButtonFace"
# Change Count/Flip indicator box
self.Round += 1
self.lblRoundNum['text'] = str(self.Round)
self.lblModeName['text'] = ("Flip" if self.isFlip == True else "Count")
self.lblModeName['fg'] = ("lime" if self.isFlip == True else "black")
self.lblModeName['bg'] = ("black" if self.isFlip == True else "white")
# All scores should be calculated by this point
# Count/Flip should be calculated by this point
# Look through all player scores, highlight round winner
## If round is 3 or higher, check for a winner
buttonList = [self.lblP1scrRound]
totalList = [self.lblP1scrTotal]
for opps in self.opponents:
buttonList.append(opps[3][10])
totalList.append(opps[3][11])
ShowBestScores(buttonList)
gameWon = ShowBestScores(totalList)
# If somebody won, pop up a message (congratulatory, if it was
# Player 1, and disable all of the buttons (for now) so it's clear
# that the game is over. Consider adding a 'play again' button later
if self.Round > 3 and gameWon:
theWinner = "Nobody"
if self.lblP1scrTotal['bg'] == "green":
theWinner = "Congratulations " + self.p1Name.get() + ", you"
elif self.lblP2scrTotal['bg'] == "green":
theWinner = self.CPU1[4].get()
elif self.lblP3scrTotal['bg'] == "green":
theWinner = self.CPU2[4].get()
elif self.lblP4scrTotal['bg'] == "green":
theWinner = self.CPU3[4].get()
if self.isFlip == True:
explainer = "In Flip mode, the player with the single lowest score after Round 3 wins.\n\n"
else:
explainer = "In Count mode, the player with the single highest score after Round 3 wins.\n\n"
for btn in self.allButtons:
btn['state'] = "disabled"
self.Messages("GAME OVER", explainer + theWinner + " won!",6,False)
self.btnRoll['command'] = Roll
def Clear():
self.p1DiceInHand = []
self.diceDepressed = 0
self.btnRecover['state'] = "disabled"
self.btnRoll['state'] = "disabled"
self.btnClear['state'] = "disabled"
dice = [self.btnP1Die1,
self.btnP1Die2,
self.btnP1Die3,
self.btnP1Die4,
self.btnP1Die5,
self.btnP1Die6,
self.btnP1Die7
]
for die in dice:
if die['state'] == "normal":
die['relief'] = "raised"
self.btnClear['command'] = Clear
def Toggle(die):
dice = [self.btnP1Die1,
self.btnP1Die2,
self.btnP1Die3,
self.btnP1Die4,
self.btnP1Die5,
self.btnP1Die6,
self.btnP1Die7
]
# One die when recovering dice
# Two dice rounds 1-3
# One die in round 4
# Same die in subsequent rounds
if self.inRecovery:
limit = 1
elif self.Round < 4:
limit = 2
elif self.Round == 4:
limit = 1
else:
limit = 0
if dice[die]['relief'] == "raised":
if self.diceDepressed < limit:
self.diceDepressed += 1
dice[die]['relief'] = "sunken"
self.p1DiceInHand.append(dice[die]['text'])
elif dice[die]['relief'] == "sunken":
self.diceDepressed -= 1
dice[die]['relief'] = "raised"
self.p1DiceInHand.remove(dice[die]['text'])
if len(self.p1DiceInHand) == limit:
if self.inRecovery:
self.btnRecover['state'] = "normal"
self.btnRoll['state'] = "disabled"
else:
self.btnRoll['state'] = "normal"
self.btnRecover['state'] = "disabled"
else:
self.btnRoll['state'] = "disabled"
self.btnRecover['state'] = "disabled"
if len(self.p1DiceInHand) > 0:
self.btnClear['state'] = "normal"
else:
self.btnClear['state'] = "disabled"
def cmp_text(i):
return int(i['text'])
def ShowBestScores(lblList):
if self.isFlip:
rWin = min(lblList, key=cmp_text)
else:
rWin = max(lblList, key=cmp_text)
if [cmp_text(x) for x in lblList].count(int(rWin['text'])) == 1:
rWin['bg'] = "green"
rWin['fg'] = "white"
return True
else:
for b in lblList:
if b['text'] == rWin['text']:
b['bg'] = "white"
b['fg'] = "green"
return False
# ___ _ __ _ ____ ___ _____ _ ___
# | |_) | | / /\ \ \_/ | |_ | |_) | | \ \ // / \
# |_| |_|__ /_/--\ |_| |_|__ |_| \ |_| \_\/\/ \_\_/
#
self.lblP2Name = tk.Label(
self._frmBoard,
text=self.p2Name.get(),
font="Verdana 16 bold",
)
# Dice for Player 2
self.btnP2Die1 = tk.Button(
self._frmBoard,
text=self.CPU1[0][0],
image=self.imgSwitch[self.CPU1[0][0]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[0])
)
self.btnP2Die2 = tk.Button(
self._frmBoard,
text=self.CPU1[0][1],
image=self.imgSwitch[self.CPU1[0][1]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[1])
)
self.btnP2Die3 = tk.Button(
self._frmBoard,
text=self.CPU1[0][2],
image=self.imgSwitch[self.CPU1[0][2]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[2])
)
self.btnP2Die4 = tk.Button(
self._frmBoard,
text=self.CPU1[0][3],
image=self.imgSwitch[self.CPU1[0][3]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[3])
)
self.btnP2Die5 = tk.Button(
self._frmBoard,
text=self.CPU1[0][4],
image=self.imgSwitch[self.CPU1[0][4]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[4])
)
self.btnP2Die6 = tk.Button(
self._frmBoard,
text=self.CPU1[0][5],
image=self.imgSwitch[self.CPU1[0][5]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[5])
)
self.btnP2Die7 = tk.Button(
self._frmBoard,
text=self.CPU1[0][6],
image=self.imgSwitch[self.CPU1[0][6]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p2D[6])
)
self.lblP2D1Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP2D2Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP2scrRound = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP2scrTotal = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.CPU1[3].extend([self.lblP2Name,
self.btnP2Die1,
self.btnP2Die2,
self.btnP2Die3,
self.btnP2Die4,
self.btnP2Die5,
self.btnP2Die6,
self.btnP2Die7,
self.lblP2D1Rolled,
self.lblP2D2Rolled,
self.lblP2scrRound,
self.lblP2scrTotal
])
self.lblP2Name.grid(column=0,row=2)
self.btnP2Die1.grid(column=1,row=2)
self.btnP2Die2.grid(column=2,row=2)
self.btnP2Die3.grid(column=3,row=2)
self.btnP2Die4.grid(column=4,row=2)
self.btnP2Die5.grid(column=5,row=2)
self.btnP2Die6.grid(column=6,row=2)
self.btnP2Die7.grid(column=7,row=2)
self.allButtons.extend([self.btnP2Die1,
self.btnP2Die2,
self.btnP2Die3,
self.btnP2Die4,
self.btnP2Die5,
self.btnP2Die6,
self.btnP2Die7]
)
self.lblP2D1Rolled.grid(column=8,row=2)
self.lblP2D2Rolled.grid(column=9,row=2)
self.lblP2scrRound.grid(column=10,row=2)
self.lblP2scrTotal.grid(column=11,row=2)
# ___ _ __ _ ____ ___ _____ _ ___ ____ ____
# | |_) | | / /\ \ \_/ | |_ | |_) | | | |_| | |_) | |_ | |_
# |_| |_|__ /_/--\ |_| |_|__ |_| \ |_| |_| | |_| \ |_|__ |_|__
#
if self.numOpponentsVar.get() > 1:
self.lblP3Name = tk.Label(
self._frmBoard,
text=self.p3Name.get(),
font="Verdana 16 bold",
)
# Dice for Player 1
self.btnP3Die1 = tk.Button(
self._frmBoard,
text=self.CPU2[0][0],
image=self.imgSwitch[self.CPU2[0][0]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[0])
)
self.btnP3Die2 = tk.Button(
self._frmBoard,
text=self.CPU2[0][1],
image=self.imgSwitch[self.CPU2[0][1]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[1])
)
self.btnP3Die3 = tk.Button(
self._frmBoard,
text=self.CPU2[0][2],
image=self.imgSwitch[self.CPU2[0][2]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[2])
)
self.btnP3Die4 = tk.Button(
self._frmBoard,
text=self.CPU2[0][3],
image=self.imgSwitch[self.CPU2[0][3]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[3])
)
self.btnP3Die5 = tk.Button(
self._frmBoard,
text=self.CPU2[0][4],
image=self.imgSwitch[self.CPU2[0][4]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[4])
)
self.btnP3Die6 = tk.Button(
self._frmBoard,
text=self.CPU2[0][5],
image=self.imgSwitch[self.CPU2[0][5]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[5])
)
self.btnP3Die7 = tk.Button(
self._frmBoard,
text=self.CPU2[0][6],
image=self.imgSwitch[self.CPU2[0][6]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p3D[6])
)
self.lblP3D1Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP3D2Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP3scrRound = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP3scrTotal = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.CPU2[3].extend([self.lblP3Name,
self.btnP3Die1,
self.btnP3Die2,
self.btnP3Die3,
self.btnP3Die4,
self.btnP3Die5,
self.btnP3Die6,
self.btnP3Die7,
self.lblP3D1Rolled,
self.lblP3D2Rolled,
self.lblP3scrRound,
self.lblP3scrTotal
])
self.lblP3Name.grid(column=0,row=3)
self.btnP3Die1.grid(column=1,row=3)
self.btnP3Die2.grid(column=2,row=3)
self.btnP3Die3.grid(column=3,row=3)
self.btnP3Die4.grid(column=4,row=3)
self.btnP3Die5.grid(column=5,row=3)
self.btnP3Die6.grid(column=6,row=3)
self.btnP3Die7.grid(column=7,row=3)
self.allButtons.extend([self.btnP3Die1,
self.btnP3Die2,
self.btnP3Die3,
self.btnP3Die4,
self.btnP3Die5,
self.btnP3Die6,
self.btnP3Die7]
)
self.lblP3D1Rolled.grid(column=8,row=3)
self.lblP3D2Rolled.grid(column=9,row=3)
self.lblP3scrRound.grid(column=10,row=3)
self.lblP3scrTotal.grid(column=11,row=3)
# ___ _ __ _ ____ ___ ____ ___ _ ___
# | |_) | | / /\ \ \_/ | |_ | |_) | |_ / / \ | | | | |_)
# |_| |_|__ /_/--\ |_| |_|__ |_| \ |_| \_\_/ \_\_/ |_| \
#
if self.numOpponentsVar.get() > 2:
self.lblP4Name = tk.Label(
self._frmBoard,
text=self.p4Name.get(),
font="Verdana 16 bold",
)
# Dice for Player 1
self.btnP4Die1 = tk.Button(
self._frmBoard,
text=self.CPU3[0][0],
image=self.imgSwitch[self.CPU3[0][0]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[0])
)
self.btnP4Die2 = tk.Button(
self._frmBoard,
text=self.CPU3[0][1],
image=self.imgSwitch[self.CPU3[0][1]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[1])
)
self.btnP4Die3 = tk.Button(
self._frmBoard,
text=self.CPU3[0][2],
image=self.imgSwitch[self.CPU3[0][2]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[2])
)
self.btnP4Die4 = tk.Button(
self._frmBoard,
text=self.CPU3[0][3],
image=self.imgSwitch[self.CPU3[0][3]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[3])
)
self.btnP4Die5 = tk.Button(
self._frmBoard,
text=self.CPU3[0][4],
image=self.imgSwitch[self.CPU3[0][4]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[4])
)
self.btnP4Die6 = tk.Button(
self._frmBoard,
text=self.CPU3[0][5],
image=self.imgSwitch[self.CPU3[0][5]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[5])
)
self.btnP4Die7 = tk.Button(
self._frmBoard,
text=self.CPU3[0][6],
image=self.imgSwitch[self.CPU3[0][6]],
compound="top",
relief="flat",
bd=3,
#command=lambda: PickADie(self.p4D[6])
)
self.lblP4D1Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP4D2Rolled = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP4scrRound = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.lblP4scrTotal = tk.Label(
self._frmBoard,
text="0",
width=4,
height=4,
font="Verdana 16 bold",
)
self.CPU3[3].extend([self.lblP4Name,
self.btnP4Die1,
self.btnP4Die2,
self.btnP4Die3,
self.btnP4Die4,
self.btnP4Die5,
self.btnP4Die6,
self.btnP4Die7,
self.lblP4D1Rolled,
self.lblP4D2Rolled,
self.lblP4scrRound,
self.lblP4scrTotal
])
self.lblP4Name.grid(column=0,row=4)
self.btnP4Die1.grid(column=1,row=4)
self.btnP4Die2.grid(column=2,row=4)
self.btnP4Die3.grid(column=3,row=4)
self.btnP4Die4.grid(column=4,row=4)
self.btnP4Die5.grid(column=5,row=4)
self.btnP4Die6.grid(column=6,row=4)
self.btnP4Die7.grid(column=7,row=4)
self.allButtons.extend([self.btnP4Die1,
self.btnP4Die2,
self.btnP4Die3,
self.btnP4Die4,
self.btnP4Die5,
self.btnP4Die6,
self.btnP4Die7]
)
self.lblP4D1Rolled.grid(column=8,row=4)
self.lblP4D2Rolled.grid(column=9,row=4)
self.lblP4scrRound.grid(column=10,row=4)
self.lblP4scrTotal.grid(column=11,row=4)
def main():
root = tk.Tk()
game = FlippantGame(root)
root.mainloop()
if __name__=="__main__":
main()
|
feea22a9815e0067f55718d5c59f90f16a5c4c69 | hannahmok/webhax_samples | /04-shellsanitization-better/index.py | 810 | 3.515625 | 4 | #!/usr/bin/env python3
import os
import sys
import urllib.parse
# parse the query string (?x=1&y=2) into the parameters dict {'x': ['1'], 'y': ['2']}
parameters = urllib.parse.parse_qs(os.environ['QUERY_STRING'])
# handle ?query=xx to search for text
if 'query' in parameters:
print('Content-type: text/plain\n')
sys.stdout.flush()
os.system('grep "' + parameters['query'][0].replace('"', '\\"').replace('\\', '\\\\') + '" books/*')
print('<end of results>')
# show form
else:
print('Content-type: text/html\n')
print('<html><body>')
print('<p>Input text to search:</p>')
print('<form action="index.py" method="GET">')
print('<input placeholder="search term" name="query" /> <button type="submit">Search</button><br />')
print('</form>')
print('</body></html>')
|
f963c5c6e26976b826456b634c80ed388d7cde55 | ptsteadman/qfo-algo-console | /strategy/monkey.py | 370 | 3.6875 | 4 | import random
class Monkey(object):
""" Silly monkey strategy every freq tick roll the dice
To instantiate a 30 tick monkey:
>>> monkey = Monkey(30)
"""
def __init__(self, freq):
self.freq = freq
def __call__(self, tick):
if tick.index % self.freq:
return None
return random.choice(('buy', 'sell', None))
|
a73e83cd06a469cbbea8440e836f359715d1ff08 | ptsteadman/qfo-algo-console | /strategy/bollinger.py | 920 | 3.53125 | 4 | class Bollinger(object):
""" Bollinger's band trading strategy, for Mean Reversion or Breakout
Bollinger's band take 2 parameters the period N of the underlying moving
average and the widht of the band K.
To instantiate a 20 days, 2 standard dev:
>>> bollinger = Bollinger(20, 2, reversion)
"""
def __init__(self, n, k, strategy="reversion"):
self.n = n
self.k = k
self.strategy = strategy
def __call__(self, tick):
if self.strategy == "breakout":
if tick.close > tick.upper_bb(self.n, self.k):
return 'buy'
elif tick.close < tick.lower_bb(self.n, self.k):
return 'sell'
elif self.strategy == "reversion":
if tick.close > tick.upper_bb(self.n, self.k):
return 'sell'
elif tick.close < tick.lower_bb(self.n, self.k):
return 'buy'
|
847ace6bebef81ef053d6a0268fa54e36072dd72 | chenshaobin/python_100 | /ex2.py | 1,113 | 4.1875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.Suppose the following input is supplied to the program: 8 Then, the output should be:40320
"""
# 使用while
"""
n = int(input())
fact = 1
i = 1
while i <= n:
fact = fact * i
i = i + 1
print(fact)
print("------")
"""
# 使用for
"""
n = int(input())
fact = 1
for i in range(1, n+1):
fact = fact * i
print(fact)
print("------")
"""
# 使用 Lambda函数
"""
n = int(input())
def shortFact(x): return 1 if x <= 1 else x * shortFact(x)
print(shortFact(n))
"""
# solution 4
"""
while True:
try:
num = int(input("Please enter a number:"))
break
except ValueError as err:
print(err)
n = num
fact = 1
while num:
fact = num * fact
num = num - 1
print(f'the factorial of {n} is {fact}')
"""
# solution 5
from functools import reduce
def fuc(acc, item):
return acc * item
num = int(input("Please enter one number:"))
print(reduce(fuc, range(1, num + 1), 1))
|
baa5ff5f08103e624b90c7a754f0f5cc60429f0e | chenshaobin/python_100 | /ex9.py | 581 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# Write a program that accepts sequence of lines as input
# and prints the lines after making all characters in the sentence capitalized.
"""
# solution1
"""
lst = []
while True:
x = input("Please enter one word:")
if len(x) == 0:
break
lst.append(x.upper())
for line in lst:
print(line)
"""
# solution2
def userInput():
while True:
s = input("Please enter one word:")
if not s:
return
yield s
for line in map(lambda x: x.upper(), userInput()):
print(line)
|
04d0d49313ad3fd020a1dd5364f663819160c825 | wongxinjie/python-tools | /profile/timer.py | 1,177 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""程序片函数运行时间测量模块
usage:
from timer import Timer
...
with Timer():
...
"""
import gc
import timeit
class Timer(object):
def __init__(self, timer=None, disable_gc=False,
verbose=False, program=None):
if timer is None:
timer = timeit.default_timer
self.timer = timer
self.disable_gc = disable_gc
self.verbose = verbose
self.start = self.end = self.interval = None
self.program = program
def __enter__(self):
if self.disable_gc:
self.gc_state = gc.isenabled()
gc.disable()
self.start = self.timer()
return self
def __exit__(self, *args):
self.end = self.timer()
if self.disable_gc and self.gc_state:
gc.enable()
self.interval = (self.end - self.start)*1000
if self.verbose:
if self.program:
s = ''.join([self.program, 'takes {0} ms'.format(
self.interval)])
else:
s = 'Takes {0} ms'.format(self.interval)
print(s)
|
fd3a3adc3b657f5f3d72697827658c1ecf804ea9 | seanxwh/github | /Python/miscellaneous/Nerual_Network.py | 5,830 | 4.09375 | 4 | #A neural network implementation for data/labels classification using Python. User can train the network
#by provide data that has labels in it. User can also fine tune the network by modifying it parameters (e.ghidden layers, learning rate, etc)
# Package imports
import matplotlib.pyplot as plt
import math
import numpy as np
import time
# a test case that using data that generated by numpy, one can also use other dataset with its own
#labels (e.g MNIST http://yann.lecun.com/exdb/mnist/)
#data generation, and plot the data
N = 300 # number of points per class
D = 2 # dimensionality
K = 2 # number of classes
X = np.zeros((N*K,D)) # data matrix (each row = single example)
y = np.zeros(N*K, dtype='uint8') # class labels
for j in xrange(K):
ix = range(N*j,N*(j+1))
r = np.linspace(0.0,1,N) # radius
t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
y[ix] = j
plt.scatter(X[:,0], X[:,1], s=40, c=y, cmap=plt.cm.Spectral)
# a function that plot the decision boundary (i.e which label/class a data belong to),
def plot_decision_boundary(pred_func):
# Set min and max values and give it some padding
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
h = 0.01
# Generate a grid of points with distance h between them
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
print np.c_[xx.ravel(), yy.ravel()][0]
# Predict the function value for the whole gid
Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
print Z
Z = Z.reshape(xx.shape)
# Plot the contour and training examples
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)
# the neural net implementation
def forwardPropagation(reg,numLyr,X,y,w,b):
a=[]
a.append(X)
numEmp = X.shape[0]
totalRegLoss=0
for i in range(numLyr):
a.append(np.maximum(0,(np.dot(a[i],w[i])+b[i])))#ReLu activation
totalRegLoss += 0.5*reg*np.sum(w[i]*w[i])
fnOutput = np.exp(a[numLyr])
fnOutputProb = fnOutput/np.sum(fnOutput,axis=1, keepdims=True)
crtOutputProb = -np.log(fnOutputProb[range(numEmp),y])
dataLoss = np.sum(crtOutputProb)/numEmp
costFunc = dataLoss+totalRegLoss
return a,fnOutput,fnOutputProb,crtOutputProb,costFunc
def predict(reg,numLyr,X,w,b):
a=[]
a.append(X)
numEmp = X.shape[0]
totalRegLoss=0
for i in range(numLyr):
a.append(np.maximum(0,(np.dot(a[i],w[i])+b[i])))#ReLu activation, also the a[numlyer] is the final activation layer(AL) for each class, the
# AL of a class over the sum of all the classes is the softmax repesentation
totalRegLoss += 0.5*reg*np.sum(w[i]*w[i])
fnOutput = np.exp(a[numLyr])
fnOutputProb = fnOutput/np.sum(fnOutput,axis=1, keepdims=True)
predicted_class = np.argmax(a[numLyr], axis=1)
return predicted_class
def add(x,y):
return x+y
def backPropagation(lrnRate,reg,numLyr,probs,a,X,y,w,b):
numEmp = X.shape[0]
dltPrd = probs
dltPrd[range(numEmp),y]-=1 # result of the softmax derivertive
dltPrd /= numEmp
da=[]
dw=[]
db=[]
for i in reversed(range(numLyr)):
if(i == numLyr-1):
da.insert(0,np.dot(dltPrd,w[i].T))
da[0][a[i] <= 0]=0
dw.insert(0,np.dot(a[i].T, dltPrd))
db.insert(0,np.sum(dltPrd,axis=0,keepdims=True))
elif(i == 0):
dw.insert(0,np.dot(X.T, da[i])) #the da[i] has the value of 'da[i+1] (e.g: the da from prev layer toward ouput)' if we have the whole complete list,
#in this case, we current don't have value for da[i+1] of the
#complete list, because the first element of the list is d[i]. same idea apply to
#the index cal of da, db & dw
db.insert(0,np.sum(da[i],axis=0,keepdims=True))
else:
da.insert(0,np.dot(da[0],w[i].T))
da[0][a[i]<=0]=0
dw.insert(0,np.dot(a[i].T, da[0]))
db.insert(0,np.sum(da[0],axis=0,keepdims=True))
regDW = [(reg)*i for i in w]
dw = map(add,dw,regDW)
lrnDW = [-lrnRate*i for i in dw]
w = map(add,w,lrnDW)
lrnDB=[-(lrnRate)*i for i in db]
b= map(add,b,lrnDB)
return w,b
def model(X,y,hdim=200,numLyr=3,iterations=2500,step_size=3e-2,reg=7e-5):
# start = time.clock()
K = np.unique(y).size#number of classes from the output labels
xEmp = X.shape[0]
n=xEmp
xDim = X.shape[1]
w=[]
b=[]
for i in xrange(numLyr):
if(i==numLyr-1):
w.append(0.01 * np.random.randn(hdim,K))
b.append(np.zeros((1,K)))
elif(i==0):
w.append(0.01 * np.random.randn(xDim,hdim))
b.append(np.zeros((1,hdim)))
else:
w.append(0.01 * np.random.randn(hdim,hdim))
b.append(np.zeros((1,hdim)))
for t in range(iterations):
a,fnOutput,fnOutputProb,crtOutputProb,costFunc = forwardPropagation(reg, numLyr, X, y, w, b)
w, b = backPropagation(step_size, reg, numLyr, fnOutputProb, a, X, y, w, b)
if (t % 100 == 0):
print "iteration %d: loss %f" % (t, costFunc)
if (t==iterations-1):
predicted_class = np.argmax(a[numLyr], axis=1)
print 'training accuracy: %.2f' % (np.mean(predicted_class == y))
print 'end\n'
# end=time.clock()
# time=end-start
# print "time spend:", time
return reg,numLyr,w,b
#testing and plot the decision boundary
reg,numLyr,w,b=model(X,y,200,3,2500,.3,7e-5)
plot_decision_boundary(lambda k: predict(reg,numLyr,k,w,b))
|
8c551099820670650129116ba923151ccffcc6dc | Agugu95/AlgoPy | /algo_py/BridgeOnTrucks.py | 652 | 3.78125 | 4 | from collections import deque
def solution(bridge_length, weight, truck_weights):
answer = 0
waited_truck = deque(truck_weights)
cur_bridge = [0] * bridge_length
cur_weight = 0
while cur_bridge:
cur_weight -= cur_bridge.pop(0)
if waited_truck:
if(cur_weight + waited_truck[0]) <= weight:
cur_weight += waited_truck[0]
cur_bridge.append(waited_truck.popleft())
else:
cur_bridge.append(0)
answer += 1
return answer
if __name__ == '__main__':
print(solution(2, 10, [7, 4, 5, 6]))
print(solution(9, 99, [2, 4, 12, 52, 4]))
|
ab46a3b79cb7eeeba170fd2db174876fca14b900 | ritik1234/calculator | /calculatorgui.py | 5,091 | 3.71875 | 4 | from tkinter import *
import math
root = Tk()
def click(event):
global value
text = event.widget.cget("text")
if text == "sin":
value.set(math.sin(float(exp.get())))
exp.update()
elif text == "cos":
value.set(math.cos(float(exp.get())))
exp.update()
elif text == "tan":
value.set(math.tan(float(exp.get())))
exp.update()
elif text == "√":
value.set(math.sqrt(float(exp.get())))
exp.update()
elif text == "ln":
value.set(math.log(float(exp.get())))
exp.update()
elif text == "=":
if value.get().isdigit():
v = int(value.get())
else:
try:
v = eval(exp.get())
value.set(v)
exp.update()
except:
value.set("Wrong expression")
exp.update()
elif text == "C":
value.set("")
exp.update()
else:
value.set(value.get() + text)
exp.update()
if text == "X":
root.destroy()
root.title("Calculator")
root.geometry("325x392")
root.wm_iconbitmap("calculator.ico")
root.configure(bg = "skyblue")
value = StringVar()
value.set("")
exp = Entry(root, textvariable = value, bg = "grey24", font = "lucida 25 bold", fg = "white", relief = SUNKEN)
exp.pack(padx = 12, pady = 12, fill = X)
f = Frame(root, bg = "grey")
b = Button(f, text = "sin", font = "comicsansms 19 bold", padx = 18, bg = "grey", fg = "white")
b.pack()
b.bind('<Button-1>', click)
b = Button(f, text = "cos", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack()
b.bind('<Button-1>', click)
b = Button(f, text = "tan", font = "comicsansms 19 bold", padx = 17, bg = "grey", fg = "white")
b.pack()
b.bind('<Button-1>', click)
b = Button(f, text = "√", font = "comicsansms 19 bold", padx = 28, bg = "grey", fg = "white")
b.pack()
b.bind('<Button-1>', click)
b = Button(f, text = "ln", font = "comicsansms 19 bold", padx = 24, bg = "grey", fg = "white")
b.pack()
b.bind('<Button-1>', click)
b = Button(f, text = ".", font = "comicsansms 19 bold", padx = 32, bg = "grey", fg = "white")
b.pack()
b.bind('<Button-1>', click)
f.pack(side = LEFT, padx = 12)
f = Frame(root, bg = "grey")
b = Button(f, text = "9", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "8", font = "comicsansms 19 bold", padx = 14, bg ="grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "7", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
f.pack()
f = Frame(root, bg = "grey")
b = Button(f, text = "6", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "5", font = "comicsansms 19 bold", padx = 14, bg ="grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "4", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
f.pack()
f = Frame(root, bg = "grey")
b = Button(f, text = "3", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "2", font = "comicsansms 19 bold", padx = 14, bg ="grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "1", font = "comicsansms 19 bold", padx = 14, bg = "grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
f.pack()
f = Frame(root, bg = "grey")
b = Button(f, text = "+", font = "comicsansms 19 bold", padx = 13.5, bg = "orange")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "0", font = "comicsansms 19 bold", padx = 14, bg ="grey", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "-", font = "comicsansms 19 bold", padx = 16.5, bg = "orange")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
f.pack()
f = Frame(root, bg = "grey")
b = Button(f, text = "*", font = "comicsansms 19 bold", padx = 16.5, bg = "orange")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "%", font = "comicsansms 19 bold", padx = 13, bg ="orange")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "/", font = "comicsansms 19 bold", padx = 16.5, bg = "orange")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
f.pack()
f = Frame(root, bg = "grey")
b = Button(f, text = "C", font = "comicsansms 19 bold", padx = 8, bg = "brown", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "=", font = "comicsansms 19 bold", padx = 24, bg ="blue", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
b = Button(f, text = "X", font = "comicsansms 19 bold", padx = 8, bg = "red", fg = "white")
b.pack(side = LEFT)
b.bind('<Button-1>', click)
f.pack()
root.mainloop()
|
855fab989e0c28a10cfd7459bfcf6cd03091a061 | AlibekAbd/- | /Gauss.py | 826 | 3.71875 | 4 | import numpy as np
import random
import scipy.linalg as sla
n = int(input())
A = np.random.rand(n,n)
f = np.random.rand(n)
#diagonal dimension
for i in range(0,n):
summa = 0
for j in range(0,n):
summa += abs(A[i][j])
c = random.uniform(1,2)
A[i][i] = summa + c
def forward_elimination(A, f, n):
for k in range(0, n-1):
for i in range(k+1, n):
t = A[i][k] / A[k][k]
for j in range(k, n):
A[i][j] -= t * A[k][j]
f[i] -= t * f[k]
return A, f
def backward_substitution(a, b, n):
x = [0] * n
x[n-1] = f[n-1] / a[n-1][n-1]
for k in range(n-2, -1, -1):
summa = f[k]
for j in range(k+1, n):
summa -= a[k][j] * x[j]
x[k] = summa / a[k][k]
return np.array(x)
A, f = forward_elimination(A, f, n)
x = backward_substitution(A, f, n)
#y = np.linalg.solve(A,f)
#print("y = ",y)
print("x = ",x)
|
932dffef241b7aadab1551b63db501e7146457c0 | Ankirama/Epitech | /B5---Java-I-Programming/JWeb/data/initDB.py | 5,787 | 4.09375 | 4 | import sqlite3
import sys
class Database:
'''
Helper to use sqlite3 and init our database
'''
def __init__(self, dbname):
'''
It will connect to the database name (or create it) and create (if not exists) our tables
@param: dbname: database name
'''
try:
self.conn = sqlite3.connect(dbname)
self.cursor = self.conn.cursor()
except sqlite3.OperationalError as e:
print('error in db: ', e)
else:
print('connected to %s' % dbname)
def __del__(self):
self.cursor.close()
print('db closed')
def createTables(self, tablesQueries):
print('db: create tables ..')
try:
for name, query in tablesQueries.iteritems():
self.cursor.execute(query)
self.conn.commit()
print('db: [%s] table created' % name)
except sqlite3.OperationalError as e:
print('error during creation table: [%s]' % name, e)
except BaseException as e:
print(name)
def flushTables(self, tables):
print('db: flush tables...')
try:
for name in tables.keys():
self.cursor.execute("DROP TABLE IF EXISTS %s;" % name)
self.conn.commit()
print('db: [%s] table deleted' % name)
except sqlite3.OperationalError as e:
print('error during removing table: ', e)
def main():
'''
This scrip will allow us to create our database and tables
'''
tablesQueries = {}
tablesQueries['user'] = 'CREATE TABLE IF NOT EXISTS user (' \
'id INTEGER PRIMARY KEY AUTOINCREMENT,' \
'username TEXT UNIQUE NOT NULL,' \
'password TEXT NOT NULL,' \
'email TEXT UNIQUE NOT NULL,' \
'first_name TEXT DEFAULT "",' \
'last_name TEXT DEFAULT "",' \
'admin INTEGER NOT NULL DEFAULT 0,' \
'active INTEGER DEFAULT 1'\
');'
tablesQueries['address'] = 'CREATE TABLE IF NOT EXISTS address (' \
'id INTEGER PRIMARY KEY AUTOINCREMENT,' \
'name TEXT UNIQUE NOT NULL,' \
'first_name TEXT NOT NULL,'\
'last_name TEXT NOT NULL,'\
'address1 TEXT NOT NULL,' \
'address2 TEXT,' \
'city TEXT NOT NULL,' \
'country TEXT NOT NULL,' \
'userid INTEGER,' \
'FOREIGN KEY(userid) REFERENCES user(id)' \
');'
tablesQueries['payment'] = 'CREATE TABLE IF NOT EXISTS payment('\
'id INTEGER PRIMARY KEY AUTOINCREMENT,'\
'name TEXT UNIQUE NOT NULL,'\
'card_numbers TEXT UNIQUE NOT NULL,'\
'first_name TEXT NOT NULL,'\
'last_name TEXT NOT NULL,'\
'userid INTEGER,'\
'FOREIGN KEY(userid) REFERENCES user(id)'\
');'
tablesQueries['category'] = 'CREATE TABLE IF NOT EXISTS category('\
'id INTEGER PRIMARY KEY AUTOINCREMENT,'\
'name TEXT NOT NULL UNIQUE,'\
'slug TEXT NOT NULL UNIQUE'\
')'
tablesQueries['product'] = 'CREATE TABLE IF NOT EXISTS product(' \
'id INTEGER PRIMARY KEY AUTOINCREMENT,' \
'name TEXT NOT NULL,' \
'price REAL NOT NULL,' \
'illustration TEXT NOT NULL, '\
'description TEXT NOT NULL,' \
'active INTEGER NOT NULL DEFAULT 1,'\
'categoryid INTEGER,'\
'FOREIGN KEY(categoryid) REFERENCES category(id)'\
');'
tablesQueries['opinion'] = 'CREATE TABLE IF NOT EXISTS opinion (' \
'id INTEGER PRIMARY KEY AUTOINCREMENT,' \
'note INTEGER NOT NULL DEFAULT 0,' \
'comment TEXT NOT NULL,' \
'author TEXT NOT NULL,' \
'productid INTEGER,'\
'FOREIGN KEY(productid) REFERENCES product(id)'\
');'
tablesQueries['newsletter'] = 'CREATE TABLE IF NOT EXISTS newsletter ('\
'id INTEGER PRIMARY KEY AUTOINCREMENT, '\
'email TEXT UNIQUE NOT NULL'\
');'
tablesQueries['news'] = 'CREATE TABLE IF NOT EXISTS news ('\
'id INTEGER PRIMARY KEY AUTOINCREMENT,'\
'illustration TEXT NOT NULL, '\
'date_created DATETIME DEFAULT CURRENT_TIMESTAMP,'\
'title TEXT NOT NULL,'\
'content TEXT NOT NULL,'\
'author TEXT NOT NULL'\
');'
db = Database('jweb.db')
db.createTables(tablesQueries)
print('___')
#db.cursor.execute('SELECT * FROM user;')
#print(db.cursor.fetchall())
if __name__ == '__main__':
main()
|
0a0e107f75b9549da0db80273d81ff7b4e84e88a | alanmanderson/advent_of_code_2020 | /2/validate_passwords.py | 1,435 | 3.515625 | 4 | INPUT_FILE = 'my_input.txt'
def read_file(filename):
with open(filename, 'r') as fp:
data = []
for line in fp:
data.append(line.strip().split(': '))
return data
def old_valid_passwords(data):
valid_passwords = []
for str_policy, password in data:
policy = parse_policy(str_policy)
letter_count = 0
for i in password:
if i == policy.letter:
letter_count+=1
if letter_count >= policy.min_letter and letter_count <= policy.max_letter:
valid_passwords.append(password)
return valid_passwords
def new_valid_passwords(data):
valid_passwords = []
for str_policy, password in data:
policy = parse_policy(str_policy)
if xor(password, policy.min_letter - 1, policy.max_letter - 1, policy.letter):
valid_passwords.append(password)
return valid_passwords
def xor(password, idx1, idx2, letter):
return (password[idx1] == letter) != (password[idx2] == letter)
class Policy:
def __init__(self, min_letter, max_letter, letter):
self.min_letter = min_letter
self.max_letter = max_letter
self.letter = letter
def parse_policy(str_policy):
parts = str_policy.split(' ')
counts = parts[0].split('-')
return Policy(int(counts[0]), int(counts[1]), parts[1])
data = read_file(INPUT_FILE)
pws = new_valid_passwords(data)
print(pws)
print(len(pws))
|
eaeed21766f75657270303ddac34c8dcae8f4f01 | Scientific-Computing-at-Temple-Physics/prime-number-finder-gt8mar | /Forst_prime.py | 605 | 4.375 | 4 | # Marcus Forst
# Scientific Computing I
# Prime Number Selector
# This function prints all of the prime numbers between two entered values.
import math as ma
# These functions ask for the number range, and assign them to 'x1' and 'x2'
x1 = int(input('smallest number to check: '))
x2 = int(input('largest number to check: '))
print ('The Prime numbers between', x1, 'and', x2, 'are:')
for i in range(x1, x2+1):
if i<=0:
continue
if i==1:
continue
for j in range (2, int(ma.sqrt(i))+1):
if i%j == 0:
break
else:
print (i)
#print ('There are no Prime numbers between', x1, 'and', x2, '.') |
d40172caa6c5f944dd0db4a8a2b7af65ec861c63 | piotrbla/pyExamples | /format_poem.py | 580 | 3.78125 | 4 | from unittest.test.test_case import Test
def format_poem(poem):
if poem[-1:] == ".":
return ".\n".join(x.strip() for x in str.split(poem, '.'))
else:
return ".\n".join(x.strip() for x in str.split(poem, '.'))[:-1] + poem[-1:]
x=[1, 2, 3]
a = sum(x)/len(x)
print(format_poem('Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated?'))
# 'Beautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.') |
c38197e38f25c0a4897daf349529adb8371fd860 | piotrbla/pyExamples | /chess.py | 578 | 3.609375 | 4 | class Field:
def __init__(self, r, c):
self.r = r
self.c = chr(c + ord('A') - 1)
class Board:
def __init__(self):
self.fields = []
for row in range(1, 9):
row_fields = []
for column in range(1, 9):
row_fields.append(Field(row, column))
self.fields.append(row_fields)
def print(self):
for rf in reversed(self.fields):
for cf in rf:
print(cf.c, end='')
print(cf.r, end=' ')
print()
b = Board()
b.print()
b.print()
|
eb2dcb63ce695d4787b4269754005b9ff9074834 | piotrbla/pyExamples | /random_stack.py | 4,073 | 3.515625 | 4 | from random import randint
from random import seed
class element:
def __init__(self, data, prev=None):
self.data = data
self.prev = prev
class stos:
def __init__(self, first):
self.length = 1
self.porownania = 0
self.przypisania = 4
self.last = element(first)
def add(self, data):
new = element(data)
self.przypisania += 2
new.prev = self.last
self.przypisania += 1
self.prev = new
self.przypisania += 1
self.length += 1
self.przypisania += 1
def erase(self):
self.last = self.last.prev
self.przypisania += 1
self.length -= 1
self.przypisania += 1
self.porownania += 1
def check(self):
return self.last
def display(self):
elems = []
cur = self.last
for i in range(self.length):
elems.append(cur.data)
cur = cur.prev
elems.reverse()
print(elems)
def operations(self):
print("Przypisania:", self.przypisania)
print("Porownania:", self.porownania, "\n")
def clear(self):
self.przypisania = 0
self.porownania = 0
def append_in(self, index, data):
new = stos(None)
length = self.length
self.przypisania += 1
for i in range(length - index):
new.add(self.check().data)
self.erase()
self.add(data)
for i in range(length - index):
self.add(new.check().data)
new.erase()
def check_in(self, index):
new = stos(None)
length = self.length
for i in range(length - 1 - index):
new.add(self.check().data)
self.erase()
cur = self.check()
for i in range(length - 1 - index):
self.add(new.check().data)
new.erase()
return cur
def erase_in(self, index, data):
new = stos(None)
length = self.length
self.przypisania += 1
for i in range(length - 1 - index):
new.add(self.check().data)
self.erase()
self.add(data)
for i in range(length - 1 - index):
self.add(new.check().data)
new.erase()
def append_in_row(self):
for i in range(1, 25):
self.add(randint(0, 100))
print("Po kolei ")
self.display()
self.operations()
def append_start_end(self):
ktora_strona = 1
self.przypisania += 1
for i in range(25 - 1):
self.porownania += 1
if ktora_strona == 1:
self.add(randint(0, 100))
ktora_strona = 0
self.przypisania += 1
elif ktora_strona == 0:
self.append_in(0, randint(0, 100))
ktora_strona = 1
self.przypisania += 1
print("Poczatek/Koniec ")
self.display()
self.operations()
def append_randomly(self):
for i in range(24):
where = randint(0, self.length)
if where == self.length:
self.add(randint(0, 100))
else:
self.erase_in(where, randint(0, 100))
print("Losowo ")
self.display()
self.operations()
def wyszukaj():
struktura = stos(randint(0, 100))
struktura.append_in_row()
struktura.display()
struktura.clear()
for i in range(25):
print(i + 1, "element: ", struktura.check_in(i).data)
stos.display()
def usuwanie():
print("USUWANIE!")
for i in range(25):
seed(99)
struktura = stos(randint(0, 100))
struktura.append_in_row()
struktura.display()
struktura.clear()
struktura.erase_in(i)
print("Usuwanie ", i + 1, " elementu")
stos.display()
print("")
struktura = stos(randint(0, 100))
struktura.append_in_row()
# struktura.append_randomly()
# struktura.append_start_end()
# wyszukaj()
# usuwanie()
|
7a04c5413d26c1daf88792f0353f5a5ed0872a98 | piotrbla/pyExamples | /resistor.py | 3,887 | 3.734375 | 4 | import unittest
def encode_resistor_colors(ohms_string):
result = ""
codes = {0: "black", 1: "brown", 2: "red", 3: "orange", 4: "yellow", 5: "green", 6: "blue", 7: "violet", 8: "gray",
9: "white"}
without_ohms = ohms_string.replace(" ohms", "")
x = 0
if without_ohms.endswith('k'):
x = without_ohms.replace('k', '')
if len(x) == 1:
result += codes[int(x[0])] + " black" " red"
elif len(x) == 2:
result += codes[int(x[0])] + " " + codes[int(x[1])] + " orange"
else:
if x[1] == '.':
result += codes[int(x[0])] + " " + codes[int(x[2])] + " red"
else:
result += codes[int(x[0])] + " " + codes[int(x[1])] + " yellow"
elif without_ohms.endswith('M'):
x = without_ohms.replace('M', '')
if len(x) == 1:
result += codes[int(x[0])] + " black" " green"
elif len(x) == 2:
result += codes[int(x[0])] + " " + codes[int(x[1])] + " blue"
else:
if x[1] == '.':
result += codes[int(x[0])] + " " + codes[int(x[2])] + " green"
else:
result += codes[int(x[0])] + " " + codes[int(x[1])] + " violet"
else:
x = without_ohms
result += codes[int(x[0])] + " " + codes[int(x[1])]
if len(x) == 3:
result += " brown"
else:
result += " black"
result += " gold"
return result
# 0: black, 1: brown, 2: red, 3: orange, 4: yellow, 5: green, 6: blue, 7: violet, 8: gray, 9: white
class Tests(unittest.TestCase):
def test_resistors_test(self):
self.assertEqual(encode_resistor_colors("10 ohms"), "brown black black gold")
def test_resistors_test1(self):
self.assertEqual(encode_resistor_colors("47 ohms"), "yellow violet black gold")
def test_resistors_test2(self):
self.assertEqual(encode_resistor_colors("100 ohms"), "brown black brown gold")
def test_resistors_test3(self):
self.assertEqual(encode_resistor_colors("220 ohms"), "red red brown gold")
def test_resistors_test4(self):
self.assertEqual(encode_resistor_colors("330 ohms"), "orange orange brown gold")
def test_resistors_test5(self):
self.assertEqual(encode_resistor_colors("470 ohms"), "yellow violet brown gold")
def test_resistors_test6(self):
self.assertEqual(encode_resistor_colors("680 ohms"), "blue gray brown gold")
def test_resistors_test7(self):
self.assertEqual(encode_resistor_colors("1k ohms"), "brown black red gold")
def test_resistors_test8(self):
self.assertEqual(encode_resistor_colors("4.7k ohms"), "yellow violet red gold")
def test_resistors_test9(self):
self.assertEqual(encode_resistor_colors("10k ohms"), "brown black orange gold")
def test_resistors_test10(self):
self.assertEqual(encode_resistor_colors("22k ohms"), "red red orange gold")
def test_resistors_test11(self):
self.assertEqual(encode_resistor_colors("47k ohms"), "yellow violet orange gold")
def test_resistors_test12(self):
self.assertEqual(encode_resistor_colors("100k ohms"), "brown black yellow gold")
def test_resistors_test13(self):
self.assertEqual(encode_resistor_colors("330k ohms"), "orange orange yellow gold")
def test_resistors_test14(self):
self.assertEqual(encode_resistor_colors("1M ohms"), "brown black green gold")
def test_resistors_test15(self):
self.assertEqual(encode_resistor_colors("2M ohms"), "red black green gold")
def test_resistors_test16(self):
self.assertEqual(encode_resistor_colors("470M ohms"), "yellow violet violet gold")
if __name__ == '__main__':
unittest.assertEqual(encode_resistor_colors("10 ohms"), "brown black black gold")
# encode_resistor_colors("10 ohms")
|
83b7c6b2d13a748299802172b49f6cd0f51e1e25 | Charnub/python-code | /Python Programming Sheets/Q22.py | 284 | 3.984375 | 4 | myMessage = (input("Enter Message: "))
upperLower = (input("Shout or Whisper?: "))
upperLower = upperLower.lower()
if upperLower == "shout":
myShout = myMessage.upper()
print(myShout)
elif upperLower == "whisper":
myShout2 = myMessage.lower()
print(myShout2)
|
fe3c86ed4282507f3f96c7f070bc1ac0036db547 | Charnub/python-code | /Python Programming Sheets/Q13.py | 301 | 3.796875 | 4 | import random
character = (input("Do you want to create a Character?"))
character = character.lower()
dice1 = random.randint(1,6)
dice2 = random.randint(1,12)
if character == "yes":
calculate = dice2/dice1+10
print("Hit Points: "+(str(calculate)))
elif character == "no":
exit()
|
97ec90e598582256b2ba729af7cde46277481412 | Charnub/python-code | /Test Files/y10help.py | 242 | 3.96875 | 4 | print("Welcome to The Quiz!")
print("Please create a username and password:")
name = (str(input("What is your name?")))
age = (str(input("What is your age?")))
name2 = name[:3]
username = name2+age
print("Your username is: "+username)
|
7134c88c5828fd1675705ccecc1d9d6ad12f446e | Charnub/python-code | /Python Programming Sheets/Q27.py | 145 | 3.609375 | 4 | def coinToss():
import random
if(random.randint(0,1)==0):
return "Heads"
else:
return "Tails"
print(coinToss()) |
90ab247a769e653a54ddc3165106f74e85d83543 | kimstone/itp_week_3 | /day_3/exercise-daniel.py | 597 | 3.828125 | 4 | import requests
import json
# using the requests package, we can make API calls to retrieve JSON
# and storing it into a variable here called "response"
response = requests.get("https://rickandmortyapi.com/api/character")
# verify the response status as 200
# print(response)
# verify the raw string data of the response
# print(response.text)
# load as a python json object and store into a variable called "clean_data"
clean_data = json.loads(response.text)
print(clean_data)
# go through the results,
# for each row in an excel spreadsheet
# grab the name, species, gender, location name |
1e9988d1becd1cf946dd8d26f614cc0d142edd52 | annilq/python | /chapter-9/admin.py | 482 | 3.625 | 4 | from user import User
class Privileges():
"""docstring for Privileges"""
def __init__(self):
super().__init__()
self.privileges = ["can add post","can delete post","can ban user"]
def show_privileges(self):
print("the admin ",self.privileges)
class Admin(User):
"""docstring for Admin"""
def __init__(self, first_name,last_name):
super().__init__(first_name,last_name)
self.privileges = Privileges()
admin=Admin("liu","qiang")
admin.privileges.show_privileges()
|
f72db317acd78d63bae31468bcece656e696a540 | Nrams1/CSC1015F_Assignment-2 | /pi.py | 332 | 3.984375 | 4 | # calculate pi
# neo ramotlou
# 15 march 2018
x = 0
fraction = 2
import math
p = 2
while x !=2:
x = math.sqrt(x+2)
fraction = (2/x)
p = p*fraction
print('Approximation of pi:', round(p, 3))
radius = eval(input('Enter the radius: \n'))
print('Area:', round((p*(radius**2)), 3))
|
35cd940e9184686fb80f549dad3555404537714a | daniel321c/coding_quiz | /leafSum.py | 665 | 3.515625 | 4 | # class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sumNumbers(self, root: TreeNode) -> int:
self.total = 0
self.getNumber(root, 0)
return self.total
def getNumber(self, node, carry):
if(node is None):
return
if(node.left is None and node.right is None):
self.total += carry*10 + node.val
return
if(node.left is not None):
self.getNumber(node.left, carry*10 + node.val)
if(node.right is not None):
self.getNumber(node.right, carry*10+node.val)
|
1ee05d52209e23c2cacd5b512cb3963b26af6b30 | daniel321c/coding_quiz | /filter.py | 710 | 3.625 | 4 | from abc import ABC, abstractmethod
class BaseFilter(ABC):
def __init__(self, field, constraint):
self.field = field
self.constraint = constraint
@abstractmethod
def apply(self, object):
print("i am abstract")
pass
class EquationFilter(BaseFilter):
def __init__(self, field, constraint):
super().__init__(field, constraint)
def apply(self, object):
super().apply(self)
if(getattr(object, self.field) == self.constraint):
return True
return False
class Node:
def __init__(self, type):
self.type = type
node = Node('file')
filter = EquationFilter('type', 'folder')
print(filter.apply(node))
|
076fbda9c9524d527abe372d12f5ab69659bb100 | chz224/Apply-Security-HW1 | /HW_1.py | 760 | 3.90625 | 4 | #Cheng Hao Zheng
#HW 1 Spell Checker
#Github user name: chz224
#import spellchecker library
from spellchecker import SpellChecker
def main():
spell = SpellChecker()
#change the file to the text file you want to spell check
#currently spell checking file MisspelledText.txt
misspelledFile = open('MisspelledText.txt', 'r')
#output file that contains the correction for the file spell checked
#currently output to file CorrectedText.txt
correctedFile = open('CorrectedText.txt', 'w')
for line in misspelledFile:
for word in line.split():
correctedFile.write(spell.correction(word))
correctedFile.write(' ')
correctedFile.write('\n')
if __name__=="__main__":
main()
|
f6d7f32228e90e46336cab48bafca14da5be421a | jarbus/epsilon-machine-python | /em/parse_tree_node.py | 4,436 | 3.59375 | 4 | from collections import defaultdict, Counter
from typing import Dict, Sequence, List
from functools import partial
import plantuml
import sys
class ParseTreeNode:
"""Node of a parse tree.
Arguments:
depth: Level of depth in a tree. For roots, depth=0.
target_depth: Denoted as D in Crutchfield's lectures.
The maximum depth of the parse tree.
Example usage:
>>> root = ParseTreeNode(target_depth=3)
>>> root[1][2][3].value += 1
>>> root[1][2][3].value
1
>>> root[1][2][2].value += 1
>>> root.update_probabilities()
>>> root[1][2].prob
1.0
>>> root[1][2][3].prob
0.5
"""
def __init__(self, target_depth: int, depth: int = 0):
self.prob = None
self.leaf_count = None
self.depth = depth
self.target_depth = target_depth
self.is_leaf = depth == target_depth
self.state = None
self.value = 0
self.id = "[*]"
self.state = None
self.morph = "unassigned"
if self.is_leaf:
self.branches = None
else:
self.branches = defaultdict(
partial(ParseTreeNode, depth=depth + 1, target_depth=target_depth)
)
def count(self) -> int:
if self.is_leaf:
self.leaf_count = self.value
else:
for branch in self.branches:
self.leaf_count = sum((l.count() for l in self.branches.values()))
return self.leaf_count
def update_probabilities(self, count=True) -> None:
"""Updates ParseTreeNode.prob with the local probability of transitioning to it from a parent.
Args:
count: Calls ParseTreeNode.count() to update the count ofleaf nodes accessible from each node.
"""
# leaves get updated from parents
if self.is_leaf:
return
# update counts for all child nodes
if count:
self.count()
for key, branch in self.branches.items():
# No need to call count for child nodes, as they are already updated with calling
# node's count() call
branch.update_probabilities(count=False)
branch.prob = round(branch.leaf_count / self.leaf_count, 2)
def generate_state_diagram(self, file="default-state-diagram.txt"):
"""Outputs a png file relaying the state diagram, starting from
the node the function was called from"""
self.update_probabilities()
with open(file, "w") as f:
f.write("@startuml\n")
f.write("hide empty description\n")
print(self, file=f)
f.write("@enduml")
puml = plantuml.PlantUML("http://www.plantuml.com/plantuml/img/")
puml.processes_file(file)
def __str__(self):
if self.is_leaf:
return (
f"{self.id} : State {self.state}\n{self.id} : Count {self.leaf_count}\n"
)
branch_strings = []
child_strings = []
for key, branch in self.branches.items():
branch_strings.append(f"{self.id} --> {branch.id} : {branch.prob}")
child_strings.append(str(branch))
if self.id != "[*]":
branch_strings.append(
f"{self.id} : State {self.state}\n{self.id} : Count {self.leaf_count}\n{self.id} : Morph {self.morph}\n"
)
return "" + "\n".join(branch_strings) + "\n" + "".join(child_strings) + "\n"
def __setitem__(self, key, item):
if self.is_leaf:
self.value = item
else:
self.branches[key].id = (
self.id + "_" + str(key) if self.id != "[*]" else str(key)
)
self.branches[key].state = key
self.branches[key] = item
def __getitem__(self, key):
if self.is_leaf:
return self
else:
self.branches[key].id = (
self.id + "_" + str(key) if self.id != "[*]" else str(key)
)
self.branches[key].state = key
return self.branches[key]
def __eq__(self, other):
if other.state != self.state or other.prob != self.prob:
return false
for key, item in self.branches.items():
if key not in other.branches or other.branches[key] != self.branches[key]:
return false
return True
|
4845e44fa0afcea9f4293f45778f6b4ea0da52b0 | jamiegowing/jamiesprojects | /character.py | 402 | 4.28125 | 4 | print("Create your character")
name = input("what is your character's name")
age = int(input("how old is your character"))
strengths = input("what are your character's strengths")
weaknesses = input("what are your character's weaknesses")
print(f"""You'r charicters name is {name}
Your charicter is {age} years old
strengths:{strengths}
weaknesses:{weaknesses}
{name}says,'thanks for creating me.'
""") |
18c4527e5b18282b5d023fe97dbd880bc0f91796 | UPML/python2017 | /62.py | 1,097 | 3.6875 | 4 | import random
def british_word(word, param):
if len(word) >= param + 2:
last_to_change = min(param, len(word) - 2)
positions = random.sample(range(1, len(word) - 1), last_to_change)
characters = []
for j in positions:
characters.append(word[j])
random.shuffle(characters)
new_shuffle = list(word)
for i, j in enumerate(positions):
new_shuffle[j] = characters[i]
shuffled_string = ''
for s in new_shuffle:
shuffled_string += s
return shuffled_string
else:
return word
def prepare_to_british_scientists(text, param):
shuffled_text = ''
word = ''
for c in text:
if ord('a') <= ord(c) <= ord('z') or \
ord('A') <= ord(c) <= ord('Z'):
word += c
else:
shuffled_text += british_word(word, param)
shuffled_text += c
word = ''
shuffled_text += british_word(word, param)
return shuffled_text
# print(prepare_to_british_scientists("Namespaces are one honking great ", 2)) |
45822bdb6dc53702eff7f2a899117558bb05e4f0 | UPML/python2017 | /4.py | 812 | 3.75 | 4 | def memoize(function):
memo = {}
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
# не сложилось=(
@memoize
def fib(n):
if (n == 0):
return 0
if (n == 1):
return 1
if (n == 2):
return 2
if (n == 100):
return 573147844013817084101
if (n == 300):
return 359579325206583560961765665172189099052367214309267232255589801
if (n == 301):
return 581811569836004006491505558634099066259034153405766997246569401
return fib(n - 1) + fib(n - 2)
nFib = [0] * 1001
nFib[0] = 0
nFib[1] = 1
for i in range(2, 1001):
nFib[i] = nFib[i - 1] + nFib[i - 2]
print(nFib[int(input())])
|
142ecec208f83818157ce4c8dff7495892e5d5d2 | yagizhan/project-euler | /python/problem_9.py | 450 | 4.15625 | 4 | # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
# For example, 32 + 42 = 9 + 16 = 25 = 52.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def abc():
for c in range(1, 1000):
for b in range(1, c):
for a in range(1, b):
if(a*a + b*b == c*c and a + b + c == 1000):
return(a*b*c)
print(abc())
|
004571b005999b28b9913db8d646c82f1e562b1b | peterlew/euler-python | /p14.py | 379 | 3.5 | 4 |
results = {1 : 1}
def chainLen(n):
if n in results:
return(results[n])
if n % 2 == 0:
result = 1 + chainLen(n // 2)
else:
result = 1 + chainLen(n * 3 + 1)
results[n] = result
return result
longestChain = 0
longestChainStart = 0
for i in range(1, 1000000):
c = chainLen(i)
if c > longestChain:
longestChain = c
longestChainStart = i
print(longestChainStart)
|
1258ef4008a50145318fbd3e8bd13fabc8989cbb | peterlew/euler-python | /p31.py | 457 | 3.625 | 4 |
coins = [200, 100, 50, 20, 10, 5, 2, 1]
# results dic: (target, max coin index) -> ways to make target
# using coins at max index or greater
results = {}
for i in range(8):
results[(0, i)] = 1
def waysToMake(n, ind):
if (n, ind) in results:
return results[(n, ind)]
total = 0
for i in range(ind, 8):
coin = coins[i]
if coin <= n:
total += waysToMake(n - coin, i)
results[(n, ind)] = total
return total
print(waysToMake(200, 0))
|
e7db4be32011e9c773b088453853c24d0c98f4a7 | SoyeonHH/Algorithm_Python | /LeetCode/819.py | 562 | 3.5 | 4 | import collections
import re
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
# Solution
# --------------------------------------------------------------
# 입력값 전처리
words = [word for word in re.sub(r'[^\w]',' ', paragraph)
.lower().split()
if word not in banned]
# 빈도수가 가장 높은 요소 반환
counts = collections.Counter(words) # return [('word',count), ...]
print(counts.most_common(1)[0][0]) # most_common(1) : 가장 빈번한 counter collection 1개 반환 |
850cb22e85b943a16b872d0d826b498ab118b90b | SoyeonHH/Algorithm_Python | /LeetCode/206.py | 745 | 3.90625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# 재귀 구조로 뒤집기
def reverseList_1(self, head: ListNode) -> ListNode:
def reverse(node: ListNode, prev: ListNode):
if not node:
return prev
next, node.next = node.next, prev
return reverse(next, node)
return reverse(head, None)
# 반복문으로 뒤집기
def reverseList_2(self, head: ListNode) -> ListNode:
node, prev = head, None
while node:
next, node.next = node.next, prev
prev, node = node, next
return prev |
77b2c0824d422ba288765da390bd2b7c068bdb62 | Alston-Tang/Spam-Filter | /proc_mail.py | 1,858 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
This file contains functions of processing emails
"""
import re
from html2text import html2text
def get_mail_body(_mail_file):
"""
Extract the mail body from the mail file.
:param mail_file: file contains the raw content of email
:type mail_file: str
:return: string that contains the body of an email
:rtype: str
:param _mail_file:
:type _mail_file:
:return:
:rtype:
"""
with open(_mail_file, 'r', encoding='utf-8', errors='ignore') as f:
msg = f.read()
body_start = msg.find('\n\n') + len('\n\n')
return msg[body_start:]
def get_mail_text(_msg_body):
"""
Get plain text and remove html tags in the messge body.
:param _msg_body:
:type _msg_body:
:return: the string that does not contain html tags.
:rtype: str
"""
if '<html' in _msg_body:
return html2text(_msg_body)
else:
return _msg_body
def sub_entities(_plain_msg):
"""
sub-stitute the entities: url, email address, number, dollar.
:param _plain_msg: plain text message
:type _plain_msg: str
:return: plain text without unwanted entities
:rtype: str
"""
_sub_url = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', ' urladdr ',
_plain_msg, flags=re.MULTILINE)
_sub_eml = re.sub(r'[\w\.-]+@[\w\.-]+', ' mailaddr ', _sub_url, flags=re.MULTILINE)
_sub_num = re.sub(r'\b\d+\b', ' number ', _sub_eml, flags=re.MULTILINE)
_sub_dol = _sub_num.replace('$', ' dollar ')
_sub_usc = _sub_dol.replace('_', ' ')
return _sub_usc
def process_mail(_mail_file):
"""
wrap the processing functions.
:param _mail_file:
:type _mail_file:
:return:
:rtype:
"""
return sub_entities(get_mail_text(get_mail_body(_mail_file)))
|
aa8d3118caa910d1b2198cc6882b755d5dcb68c8 | shivg7706/CodeJam | /gcj1.py | 923 | 3.53125 | 4 | def curdam(s):
charge = 1
damage = 0
for i in s:
if i == 'C':
charge *= 2
else:
damage += charge
return damage
def swap_required(s, d):
swap_c = 0
while True:
current_damage = curdam(s)
if current_damage <= d:
return swap_c
else:
pos = -1
for i in range(len(s)-1):
if s[i] == 'C' and s[i+1] == 'S':
pos = i
if pos == -1:
return pos
s[pos], s[pos+1] = s[pos+1], s[pos]
swap_c += 1
def main():
for i in range(int(input())):
x = input().split()
d = int(x[0])
s = x[1]
s = list(s)
minimum_damage = s.count('S')
currunt_damage = curdam(s)
if currunt_damage <= d:
print("Case #"+str(i+1)+": 0")
elif minimum_damage > d:
print("Case #"+str(i+1)+": IMPOSSIBLE")
else:
swap_c = swap_required(s,d)
if swap_c == -1:
print("Case #"+str(i+1)+": IMPOSSIBLE")
else:
print("Case #"+str(i+1)+": "+str(swap_c))
if __name__ == '__main__':
main() |
42c2467e03efa96cb2e2c7a250ce9e741e0f383b | GitOsku/Olio-ohjelmointi | /Exercise 1 p4.py | 196 | 4.0625 | 4 | counter = 0
while True:
number = int(input("Enter a number "))
if number > 0 :
continue
if number < 0 :
counter += 1
else:
break
print (counter) |
d6f65d9feaf588632bda256f7ddf3d41ca2c9208 | GitOsku/Olio-ohjelmointi | /Harjoitus5/Actual/PlayerClass.py | 1,466 | 3.875 | 4 | from Dicefilu import Dice
class Player(Dice):
def __init__(self, id):
self.firstname = "Oskari"
self.lastname = "Helenius"
self.ID = id
self.roll = 0
#setters
def setFirstname(self):
set_firstname = input("Gimme your firstname: ")
self.firstname = set_firstname
def setlastname(self):
set_lastname = input("Gimme your lastname: ")
self.lastname = set_lastname
def setIdenticator(self, ID):
self.ID = ID
#getters
def getFirstname(self):
return self.firstname
def getLastname(self):
return self.lastname
def getIdenticator(self):
return self.ID
def __str__(self):
return "\nFirsname: " + format(self.firstname)\
+ "\nLastname: " + format(self.lastname)\
+ "\nID: " + format(self.ID)
def main():
Player1 = Player(1)
Player1.set_toss() #rolling dice
Player2 = Player(2)
Player2.set_toss() #rolling dice
Player3 = Player(3)
Player3.set_toss() #rolling dice
dicti = {
Player1.getIdenticator(): Player1.get_toss(),
Player2.getIdenticator(): Player2.get_toss(),
Player3.getIdenticator(): Player3.get_toss()
}
for key, value in dicti.items():
print("Player", key, ' rolled: ', value)
main() |
504ef80a8922a640784e7cb0d63fb3e20324a41e | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /spam_catcher.py | 806 | 4.09375 | 4 | # let us create a list containing a set of phrases that could be considered as spam.
# Made with ❤️ in Python 3 by Alvison Hunter - January 28th, 2021
spams_lst = ["make","money","buy","subscribe","click","claim","prize","win","lottery"]
def spam_catcher():
# Bool variable to determine if the phrase is an spam or not
is_spam = False
try:
# let us ask for the phrase y convert it to lowercase
phrase = input("Enter some phrase: \n").lower()
for el in spams_lst:
if el in phrase:
is_spam = True
break
else:
continue
except:
print("Uh oh, an error has occurred. Program terminated")
quit()
else:
print("This is Spam") if is_spam else print("This is not Spam")
print("Thank you for using the Spam Catcher - January 2021")
spam_catcher()
|
ffbaeccca8238647d0d8b397684fad814b47e7e7 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /sales_commission_calculation.py | 1,177 | 3.6875 | 4 | # --------------------------------------------------------------------------------
# Calculate Sales commision for sales received by a salesperson
# Made with ❤️ in Python 3 by Alvison Hunter - October 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
class CalculateCommission:
def __init__(self, name, amount_sales, class_type):
self.name = name
self.amount_sales = amount_sales
self.class_type = class_type
self.commision_received = 0
def displayCalculations(self):
print(f"Name: {self.name}")
print(f"Amount Of Sales: {self.amount_sales}")
print(f"Class Type: {self.class_type}")
print(f"Commission Received: {self.commision_received}")
def calculateCommission(self):
if(self.class_type==1):
print("Class 1")
elif():
print("Class 2")
elif():
print("Class 3")
else:
print("No Class")
print(f"\nGood bye for now, {self.name}.")
Employee_01 = CalculateCommission("Declan Hunter",4, 2)
|
2e0daa14381cb9216d32d9b564747b51fc381487 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /MACHINE LEARNING/ai_basic_decision_tree.py | 361 | 3.734375 | 4 | # -------------------------------------------------------------------------
# Basic operations with colletion types | Python exercises | Beginner level
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - April 7th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
|
7d45513f6cb612b73473be6dcefaf0d2646bc629 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /decorators.py | 1,146 | 4.96875 | 5 | # INTRODUCTION TO BASIC DECORATORS USING PYTHON 3
# Decorators provide a way to modify functions using other functions.
# This is ideal when you need to extend the functionality of functions
# that you don't want to modify. Let's take a look at this example:
# Made with ❤️ in Python 3 by Alvison Hunter - June 15th, 2021
# Website: https://alvisonhunter.com/
def my_decorator(func, caption):
LINE = "━"
TOP_LEFT = "┏"
TOP_RIGHT = "┓"
BOTTOM_LEFT = "┗"
BOTTOM_RIGHT = "┛"
# This will be the wrapper for the function passed as params [func]
# Additionally, We will use the caption param to feed the text on the box
def box():
print(f"{TOP_LEFT}{LINE*(len(caption)+2)}{TOP_RIGHT}")
func(caption)
print(f"{BOTTOM_LEFT}{LINE*(len(caption)+2)}{BOTTOM_RIGHT}")
return box
# This is the function that we will pass to the decorator
# This will receive a param msg containing the text for the box
def boxed_header(msg):
vline = "┃"
title = msg.center(len(msg)+2, ' ')
print(f"{vline}{title}{vline}")
decorated = my_decorator(boxed_header, "I bloody love Python")
decorated()
|
27c3847708abed4649efa487ed02fbe4d89904e5 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /randomPwdGenerator.py | 1,828 | 4.0625 | 4 | # This function will generate a random string with a lenght based
# on user input number. This can be useful for temporary passwords
# or even for some temporary login tokens.
# Made with ❤️ in Python 3 by Alvison Hunter - December 28th, 2020
from random import sample
import time
from datetime import datetime
# We will incorporate some colors to the terminal
class bcolors:
PRIMARY ='\033[34m'
SECONDARY = '\033[95m'
FOOTER = '\033[37m'
INFO = '\033[36m'
SUCCESS = '\033[32m'
WARNING = '\033[93m'
DANGER = '\033[31m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# Main function is defined here
def generate_rand_pwd():
try:
print("░░░░░░░░░░░░░ Hunter Password Generator Tool ░░░░░░░")
print("============= We do not store any passwords. =======")
pwd_len = int(input("Please Enter Password Length: \n"))
if pwd_len < 70:
base_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*+&^%$#!"
str_results = ''.join(sample(base_str, pwd_len))
print(f"{bcolors.WARNING}Generating new password, please hold...{bcolors.ENDC}")
time.sleep(1)
print(f"{bcolors.INFO}The new password is:{bcolors.ENDC}\n {bcolors.SUCCESS}{str_results}{bcolors.ENDC}")
else:
print (f"{bcolors.FAIL}The password length is too big, number has to be less than 70.{bcolors.ENDC}")
return
except:
print(f"{bcolors.FAIL}Uh Oh, something went wrong!{bcolors.ENDC}")
return
finally:
print(f"{bcolors.FOOTER}© {datetime.today().strftime('%Y')} Hunter Password Generator Tool. All rights reserved.{bcolors.ENDC}")
# Time to call the function now, fellows
generate_rand_pwd()
|
ef45a2be2134cdf0754d5f41a9245f4a242fdb0e | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /updating_dicts_lst.py | 1,327 | 4.40625 | 4 | # -------------------------------------------------------------------------
# Basic operations with colletion types | Python exercises | Beginner level
# Generate list with random elements, find the first odd number and its index
# Create empty dict, fill up an empty list with user input & update dictionary
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - May 30th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
import random
# lista aleatoria
lst = []
name_lst = []
empty_dict = {}
# llenar lista aleatoria
for el in range(10):
lst.append(random.randrange(10))
# mostrar la lista genarada
print(lst)
# encontrar el primer numero impar
for ind, num in enumerate(lst):
if num % 2 == 0:
pass
else:
print(f"El número {num} es impar y esta en la posicion {ind}.")
break
# llenar lista vacia de nombres con user input
amnt = int(input("Escriba Cuantos nombres ingresaras? \n"))
[name_lst.append(
input(f"Escriba Nombre #{elem+1}: ").title()) for elem in range(amnt)]
# llenar diccionario vacio con datos de la lista llenada
for indx, name in enumerate(name_lst):
empty_dict[str(indx+1)] = name_lst[indx]
# Imprimimos dictionary ya con los datos listos
print(f"{empty_dict}")
|
9d079ba2115bf5b9fc4a88255b33959813c6ce1c | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /reverse_words_order_and_swap_cases.py | 604 | 3.890625 | 4 | # Esta es una antigua Forma de comunicacion inventada por un famoso general salvadoreño
# llamado Francisco Malespin en 1845 a las tropas en el salvador, honduras y nicaragua.
# Made with ❤️ in Python 3 by Alvison Hunter - November 27th, 2020
IN = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
OUT = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def reverse_words_order_and_swap_cases(sentence):
str_res = sentence.translate(sentence.maketrans(IN, OUT))
lst = str_res.split()
reversed_lst = lst[::-1]
return (" ".join(reversed_lst))
reverse_words_order_and_swap_cases("rUns dOg")
|
f5469143697a9cdcbdf8bd41c326bafa3416137d | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /euclidian_algorithm.py | 843 | 3.796875 | 4 | # Made with ❤️ in Python 3 by Alvison Hunter - November 3rd, 2020
# primero importaremos este modulo para usar su metodo reduce
import functools as ft
# procedamos ahora a declarar la lista con los numeros que usaremos
numblst = [2, 6, 8, 4, 10, 24, 9, 96]
# Vamos a usar una funcion lambda para hacer nuestro calculo
# aplicandolo a dos de los elementos de la lista numblist
def mcd(a, b): return a if b == 0 else mcd(b, a % b)
# una vez hecho esto, usemos el reduce para iterar en la lista
# aplicando la misma funcion declarada arriba con los valores
# de cada elemento restante de la lista e imprimimos el final
print(ft.reduce(lambda x, y: mcd(x, y), numblst))
# Espero que te sirva, saludos desde Nicaragua. Subire pronto un video
# sobre este algoritmo explicando mas o menos como lo hice en mi canal
# YouTube: https://bit.ly/3mFFgwK
|
a6be5496ab9c0802d4142373f2dc4724faf74429 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /units_inducement_calculations.py | 944 | 4.0625 | 4 | # -------------------------------------------------------------------------
# Basic operations with colletion types | Python exercises | Beginner level
# Get weekly production units per day & calculate if employee gets bonus
# Made with ❤️ in Python 3 by Alvison Hunter Arnuero - April 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
units_lst = []
week_days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
while True:
try:
[units_lst.append(
int(input(f"Enter Employee Units for {d}: "))) for i, d in enumerate(week_days)]
total = sum(units_lst)
got_bonus = "YES" if total > 99 else "NO"
print(f"Weekly Units: {total} | Inducement: {got_bonus}")
break
except ValueError:
print("Units should be numbers! Please try again.")
pass
|
01a58f453134cfd65c7a80a32c61b00cae4bb91f | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /PYTHON NOTEBOOKS/9.0.6_file_function_questions_&_solutions.py | 2,277 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 26 15:15:24 2019
@author: giles
"""
# Exercises
'''
#Question 1
#Create a function that will calculate the sum of two numbers. Call it sum_two.
#'''
#
#def sum_two(a,b):
# ''' This function returns the sum of two numbers. '''
#
# return a + b
##
#print(f'The sum of 3 and 4 is {sum_two(3,4)}' )
#
'''
Question 2
Write a function that performs multiplication of two arguments. By default the
function should multiply the first argument by 2. Call it multiply.
'''
#def multiply(a,b=2):
#
# '''
# Returns the product of a and b; if b not given
# returns 2 * a.
# '''
#
# return a * b
##
#print(f'Inputting 3 gives {multiply(3)}')
#print(f'Inputting 3 and 5 gives {multiply(3,5)}')
#
#
#
'''
#Question 3
#Write a function to calculate a to the power of b. If b is not given
#its default value should be 2. Call it power.
#'''
#
#def power(a,b=2):
# '''
# Returns a**b; if b not given,
# it will return a**2
# '''
# return a ** b
#
#print(f'Inputting 8 gives {power(8)}')
#print(f'Inputting 2 and 8 gives {power(2,8)}')
'''
##Question 4
##Create a new file called capitals.txt , store the names of five capital cities
##in the file on the same line.
##'''
#file = open('capitals.txt','w')
#file.write('London, ')
#file.write('Paris, ')
#file.write('Madrid, ')
#file.write('Lisbon, ')
#file.write('Rome,')
#file.close()
'''
#Question 5
#Write some code that requests the user to input another capital city.
#Add that city to the list of cities in capitals. Then print the file to
#the screen.
#'''
#user_input = input('Plese enter a capital city:> ')
#
#file = open('capitals.txt','a')
#file.write('\n' + user_input)
#file.close
#
#file = open('capitals.txt','r')
#print(file.read())
#file.close
'''
Question 6
Write a function that will copy the contents of one file to a new file.
'''
def copy_file(infile,outfile):
''' Copies the contents of infile to a new file, outfile.'''
with open(infile) as file_1:
with open(outfile, "w") as file_2:
file_2.write(file_1.read())
copy_file('capitals.txt','new_capitals.txt')
|
ef10b945cf9569f72e199b22b35f839eae98c7ce | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /PYTHON NOTEBOOKS/9.0.1_Files_&_Functions.py | 2,846 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 24 10:19:52 2019
@author: giles
"""
# File handling in Python
# Python can open, close, read to and write to files
#f = open('kipling.txt','w')
#
#print(type(f))
#
#f.write('If you can keep your head while all about you \nare losing theirs\
#and blaming it on you,\n')
#
#f.write('If you can trust yourself when all men doubt you,\n\
#But make allowance for their doubting too;\n')
#
#f.write('If you can wait and not be tired by waiting,\n\
#Or being lied about, don\'t deal in lies,\n')
#
#f.write('Or being hated, don\'t give way to hating,\n\
#And yet don\'t look too good, nor talk too wise:\n')
#
#f.close()
#
#f = open('kipling.txt','r')
#
#print(type(f))
#
#print(f.read())
#f.close()
#
#f = open('kipling.txt','r')
#
#print(f.readline())
#f.close()
#print()
#
#f = open('kipling.txt','r')
#
#print(type(f))
#
#print(f.readlines())
#f.close()
#f = open('kipling.txt','r')
#
#print(type(f))
#
#content = f.readlines()
#f.close()
#
#f = open('kipling.txt','a')
#f.write('If you can dream - and not make dreams your master;\n\
#If you can think - and not make thoughts your aim;\n')
#f.close()
#print()
#f = open('kipling.txt','r')
#print(f.read())
#f.close()
#print()
#with open('kipling.txt','r') as f:
# for line in f.readlines():
# print(line,end='')
# Functions
#print('Hello, world!')
#def hello():
# print('Hello, world!')
#
#hello()
##
#for i in range(5):
# hello()
#def hi(name):
# print(f'Hello, {name}!')
##
#hi('Giles')
#hi('Anthony')
#hi()
#def hi_2(name='Giles'):
# print(f'Hello, {name}!')
##
#hi_2()
#n=20
#a = 0
#b = 1
#for i in range(n):
# a,b = b,a+b
#print(a)
#
#
#
def fib(n):
''' Calculates and returns the nth fibonacci number'''
a = 0
b = 1
for i in range(n):
a,b = b,a+b
return a
#
##
#fib_num = fib(20)
#print(fib_num)
##
#for i in range(20):
# print(fib(i))
# Docstring
#def calc_mean(first,*remainder):
# '''
# This calculates the mean of numbers.
# '''
# mean = (first + sum(remainder))/ (1 + len(remainder))
# print(type(remainder))
# return mean
#
#print(calc_mean(23,43,56,76,45,34,65,78,975,3456,54))
#
#
#
# Recursion
def fib_2(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib_2(n-1) + fib_2(n-2)
#
#x = fib_2(20)
#print(x)
#y = fib(1000)
#print(y)
##
#x = fib_2(37)
#print(x)
import timeit
t1 = timeit.Timer("fib(36)","from greetings import fib")
print(t1.timeit(5))
t2 = timeit.Timer("fib_2(36)","from greetings import fib_2")
print(t2.timeit(5))
|
a2a6348689cab9d87349099ae927cecad07ade1a | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /intro_to_classes_employee.py | 1,839 | 4.65625 | 5 | # --------------------------------------------------------------------------------
# Introduction to classes using getters & setters with an employee details example.
# Made with ❤️ in Python 3 by Alvison Hunter - March 16th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
class Employee:
# Constructor and Class Attributes
def __init__(self, first, last, title, department):
self.first = first
self.last = last
self.title = title
self.department = department
self.email = first.lower()+"."+last.lower()+"@email.com"
# REGULAR METHODS
def display_divider(self, arg_char = "-", line_length=100):
print(arg_char*line_length)
def display_information(self):
self.display_divider("-",45)
print(f"Employee Information | {self.first} {self.last}".center(45, ' '))
self.display_divider("-",45)
print(f"Title: {self.title} | Department: {self.department}")
print(f"Email Address: {self.email}")
print("\n")
# GETTERS
@property
def fullname(self):
print(f"{self.first} {self.last}")
# SETTERS
@fullname.setter
def fullname(self,name):
first, last = name.split(" ")
self.first = first
self.last = last
self.email = first.lower()+"."+last.lower()+"@email.com"
# DELETERS
@fullname.deleter
def fullname(self):
print("Name & Last name has been successfully deleted.")
self.first = None
self.last = None
# CREATE INSTANCES NOW
employee_01 = Employee("Alvison","Hunter","Web Developer","Tiger Team")
employee_01.display_information()
employee_01.fullname = "Lucas Arnuero"
employee_01.display_information()
del employee_01.fullname
|
a1f5c161202227c1c43886a0efac0c18be4b2894 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /population_growth.py | 1,199 | 4.375 | 4 | # In a small town the population is p0 = 1000 at the beginning of a year.
# The population regularly increases by 2 percent per year and moreover
# 50 new inhabitants per year come to live in the town. How many years
# does the town need to see its population greater or equal to p = 1200 inhabitants?
# -------------------------------------------------------
# At the end of the first year there will be:
# 1000 + 1000 * 0.02 + 50 => 1070 inhabitants
# At the end of the 2nd year there will be:
# 1070 + 1070 * 0.02 + 50 => 1141 inhabitants (number of inhabitants is an integer)
# At the end of the 3rd year there will be:
# 1141 + 1141 * 0.02 + 50 => 1213
# It will need 3 entire years.
# Note:
# Don't forget to convert the percent parameter as a percentage in the body
# of your function: if the parameter percent is 2 you have to convert it to 0.02.
# Made with ❤️ in Python 3 by Alvison Hunter - January 27th, 2021
# Website: https://alvisonhunter.com/
def nb_year(p0, percent, aug, p):
growth = (p0 + 1000) * percent
return(growth)
# Examples:
print(nb_year(1000, 5, 100, 5000)) # -> 15
print(nb_year(1500, 5, 100, 5000))# -> 15
print(nb_year(1500000, 2.5, 10000, 2000000)) # -> 10
|
fd287a7a3dad56ef140e053eba439de50cdfd9b6 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /dice.py | 983 | 4.40625 | 4 | #First, you only need the random function to get the results you need :)
import random
#Let us start by getting the response from the user to begin
repeat = input('Would you like to roll the dice [y/n]?\n')
#As long as the user keeps saying yes, we will keep the loop
while repeat != 'n':
# How many dices does the user wants to roll, 2 ,3 ,4 ,5 who knows. let's ask!
amount = int(input('How many dices would you like to roll? \n'))
# Now let's roll each of those dices and get their results printed on the screen
for i in range(0, amount):
diceValue = random.randint(1, 6)
print(f"Dice {i+1} got a [{diceValue}] on this turn.")
#Now, let's confirm if the user still wants to continue playing.
repeat = input('\nWould you like to roll the dice [y/n]?\n')
# Now that the user quit the game, let' say thank you for playing
print('Thank you for playing this game, come back soon!')
# Happy Python Coding, buddy! I hope this answers your question.
|
d94493c20365c14ac8393ed9384ec6013cf553d4 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /interest_calc.py | 2,781 | 4.1875 | 4 | # Ok, Let's Suppose you have $100, which you can invest with a 10% return each year.
#After one year, it's 100×1.1=110 dollars, and after two years it's 100×1.1×1.1=121.
#Add code to calculate how much money you end up with after 7 years, and print the result.
# Made with ❤️ in Python 3 by Alvison Hunter - September 4th, 2020
# note: this can also be simply done by doing the following: print(100 * 1.1 ** 7)
import sys
def user_input(args_lbl_caption, args_input_caption):
"""This function sets a Label above an input and returns the captured value."""
try:
print(args_lbl_caption.upper())
res = int(input(args_input_caption+": \n"))
return res
except ValueError:
sys.exit("Oops! That was no valid number. Try again...")
exit
def calculate_investment():
"""This function calculates the yearly earnings based on user input from cust_input function."""
#this tuple will contain all of my captions for the user input function that I am using on this routine
input_captions_tuple = (
"Initial Investment:",
"Amount of money that you have available to invest initially",
"Estimated Interest Rate:",
"Your estimated annual interest rate[10,15,20 etc]",
"Length of Time in Years:",
"Length of time, in years that you are planning to invest"
)
#This will serve as an accumulator to store the interest per year
acc_interest = 0
#let's get the information using a called function to get and validate this data
initial_investment=user_input(input_captions_tuple[0],input_captions_tuple[1])
interest_rate_per_year=user_input(input_captions_tuple[2],input_captions_tuple[3])
length_of_time_in_years=user_input(input_captions_tuple[4],input_captions_tuple[5])
# if the called function returns an empty object or value, we will inform about this error & exit this out
if initial_investment == None or interest_rate_per_year == None or length_of_time_in_years == None:
sys.exit("These values should be numbers: You entered invalid characters!")
#If everything goes well with the user input, let us proceed to make this calculation
for year in range(length_of_time_in_years):
acc_interest = initial_investment *(interest_rate_per_year/100)
initial_investment = initial_investment + acc_interest
# print the results on the screen to let the user know the results
print("The invested amount plus the yearly interest for {} years will be $ {:.2f} dollars.".format(year+1, initial_investment))
#let's call the function to put it into action now, cheers, folks!
calculate_investment()
#This could also be done by using python simplicity by doing the following:
print(f'a simpler version: {100 * 1.1 ** 7}')
|
00575e9b32db9476ffc7078e85c58b06d4ed98f2 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /format_phone_number.py | 1,248 | 4.1875 | 4 | # --------------------------------------------------------------------------------
# A simple Phone Number formatter routine for nicaraguan area codes
# Made with ❤️ in Python 3 by Alvison Hunter - April 4th, 2021
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# --------------------------------------------------------------------------------
def format_phone_number(ind, lst_numb):
# Create a whole string with the elements of the given list
lst_to_str_num = ''.join(str(el) for el in lst_numb)
# Format the string we just built with the appropiate characters
fmt_numb = f"{ind+1} - ({''.join(lst_to_str_num[:3])}) {''.join(lst_to_str_num[3:7])}-{''.join(lst_to_str_num[7:11])}"
# print a line as a divider
print("-"*20)
# print the formatted string
print(fmt_numb)
# list of lists to make these formatting as our driver's code
phone_lst = [
[5, 0, 5, 8, 8, 6, 3, 8, 7, 5, 1],
[5, 0, 5, 8, 1, 0, 1, 3, 2, 3, 4],
[5, 0, 5, 8, 3, 7, 6, 1, 7, 2, 9],
[5, 0, 5, 8, 5, 4, 7, 2, 7, 1, 6]
]
# List comprehension now to iterate the list of lists
# and to apply the function to each of the list elements
[format_phone_number(i, el) for i, el in enumerate(phone_lst)]
print("-"*20)
|
1c03ec92c1c0b26a9549bf8fd609a8637c1e0918 | AlvisonHunterArnuero/EinstiegPythonProgrammierung- | /weird_not_weird_variation.py | 960 | 4.34375 | 4 | # -------------------------------------------------------------------------
# Given an integer,n, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
# Input Format: A single line containing a positive integer, n.
# -------------------------------------------------------------------------
# Made with ❤️ in Python 3 by Alvison Hunter - August 12th, 2022
# JavaScript, Python and Web Development tips at: https://bit.ly/3p9hpqj
# -------------------------------------------------------------------------
n = 24
is_even = n % 2 == 0
is_weird = False if n > 20 else True
if not is_even: is_weird = True
elif is_even and (2 <= n <= 5) or (n >20): is_weird = False
elif is_even and (6 <= n <= 20): is_weird = True
print("Weird" if is_weird else "Not Weird") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.