blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
57d4e31c32391b66289da0fe14c29017a35a1973
wulinlw/leetcode_cn
/初级算法/array_8.py
1,668
3.8125
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/28/ # 移动零 # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 # 示例: # 输入: [0,1,0,3,12] # 输出: [1,3,12,0,0] # 说明: # 必须在原数组上操作,不能拷贝额外的数组。 # 尽量减少操作次数。 class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ l = len(nums) zeroIndex = False moveIndex = [] f = False for i in range(l): if nums[i] == 0: f = True if type(zeroIndex) == bool: zeroIndex = i elif f == True: moveIndex.append(i) # print(zeroIndex) # print(moveIndex) # sys.exit() if type(zeroIndex) == bool: return zl = len(moveIndex) p = 0 while(p < zl): nums[zeroIndex+p] = nums[moveIndex[p]] p +=1 start = zeroIndex+zl while(start<l): nums[start] = 0 start+=1 def moveZeroes2(self, nums): # 变量j用来保存已遍历过部位0的值。 j = 0 for i in range(len(nums)): if nums[i] != 0: nums[j], nums[i] = nums[i], nums[j] j += 1 # print(nums) return nums nums = [0,1,0,3,12] s = Solution() n = s.moveZeroes2(nums) print('return', n)
cc15abee5c3b984f0655422e058e242d235553c3
wulinlw/leetcode_cn
/leetcode-vscode/817.链表组件.py
2,469
3.671875
4
# # @lc app=leetcode.cn id=817 lang=python3 # # [817] 链表组件 # # https://leetcode-cn.com/problems/linked-list-components/description/ # # algorithms # Medium (55.78%) # Likes: 31 # Dislikes: 0 # Total Accepted: 5.1K # Total Submissions: 9K # Testcase Example: '[0,1,2,3]\n[0,1,3]' # # 给定一个链表(链表结点包含一个整型值)的头结点 head。 # # 同时给定列表 G,该列表是上述链表中整型值的一个子集。 # # 返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。 # # 示例 1: # # # 输入: # head: 0->1->2->3 # G = [0, 1, 3] # 输出: 2 # 解释: # 链表中,0 和 1 是相连接的,且 G 中不包含 2,所以 [0, 1] 是 G 的一个组件,同理 [3] 也是一个组件,故返回 2。 # # 示例 2: # # # 输入: # head: 0->1->2->3->4 # G = [0, 3, 1, 4] # 输出: 2 # 解释: # 链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1] 和 [3, 4] 是两个组件,故返回 2。 # # 注意: # # # 如果 N 是给定链表 head 的长度,1 <= N <= 10000。 # 链表中每个结点的值所在范围为 [0, N - 1]。 # 1 <= G.length <= 10000 # G 是链表中所有结点的值的一个子集. # # # from typing import List # @lc code=start # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def initlinklist(self, nums): head = ListNode(nums[0]) re = head for i in nums[1:]: re.next = ListNode(i) re = re.next return head def printlinklist(self, head): re = [] while head: re.append(head.val) head = head.next print(re) def numComponents(self, head: ListNode, G: List[int]) -> int: # 当前节点在G中,下一个节点不在,组件+1 gset = set(G) re = 0 cur = head while cur: nxtval = cur.next.val if cur.next else None #可能没有下一个节点,需要判断 if cur.val in gset and nxtval not in gset: re += 1 cur = cur.next return re # @lc code=end nums = [0,1,2,3,4] g = [0,3,1,4] o = Solution() head = o.initlinklist(nums) # o.printlinklist(head1) h = o.numComponents(head, g) print(h) # o.printlinklist(h)
20cff1c9700d9009a225c7413e248a2ee1c48322
wulinlw/leetcode_cn
/leetcode-vscode/912.排序数组.py
5,906
3.84375
4
# # @lc app=leetcode.cn id=912 lang=python3 # # [912] 排序数组 # # https://leetcode-cn.com/problems/sort-an-array/description/ # # algorithms # Medium (53.09%) # Likes: 68 # Dislikes: 0 # Total Accepted: 29.9K # Total Submissions: 52.7K # Testcase Example: '[5,2,3,1]' # # 给你一个整数数组 nums,将该数组升序排列。 # # # # # # # 示例 1: # # 输入:nums = [5,2,3,1] # 输出:[1,2,3,5] # # # 示例 2: # # 输入:nums = [5,1,1,2,0,0] # 输出:[0,0,1,1,2,5] # # # # # 提示: # # # 1 <= nums.length <= 50000 # -50000 <= nums[i] <= 50000 # # # from typing import List # @lc code=start class Solution: def sortArray(self, nums: List[int]) -> List[int]: #冒泡排序 def bubble(nums): for i in range(len(nums)): for j in range(len(nums)): if nums[i]<nums[j]: nums[i],nums[j] = nums[j],nums[i] return nums #选择排序 def select(nums): for i in range(len(nums)): idx = i for j in range(i, len(nums)): if nums[i]>nums[j]: idx = j nums[i],nums[idx] = nums[idx],nums[i] return nums #插入排序 def insert(nums): for i in range(len(nums)): pre = i-1 cur = nums[i] while pre>=0 and nums[pre]>cur: nums[pre+1] = nums[pre] pre -= 1 nums[pre+1] = cur return nums #快速排序 def quick(nums, l, r): if l<r: pivot = postition(nums, l, r) quick(nums, l, pivot-1) #不包含pivot quick(nums, pivot+1, r) return nums def postition(nums, l, r): i = l-1 pivot = nums[r] for j in range(l, r): if nums[j] < pivot: i += 1 nums[i],nums[j] = nums[j],nums[i] nums[i+1],nums[r] = nums[r],nums[i+1] return i+1 #归并排序 def merge(nums): if len(nums)==1:return nums mid = len(nums)//2 return _merge(merge(nums[:mid]), merge(nums[mid:])) def _merge(n1, n2): re = [] while n1 and n2: if n1[0]<n2[0]: re.append(n1.pop(0)) else: re.append(n2.pop(0)) while n1: re.append(n1.pop(0)) while n2: re.append(n2.pop(0)) return re #桶排序 def bucket(nums): maxval = max(nums) bucket = [0] * (maxval+1) for i in nums: bucket[i] += 1 re = [] for i in range(len(bucket)): while bucket[i]>0: re.append(i) bucket[i] -= 1 return re #奇数排序 def count(nums): re = [0] * len(nums) for i in range(len(nums)): cnt = 0 dup = 0 for j in range(len(nums)): if nums[i] > nums[j]: cnt += 1 elif nums[i] == nums[j]: dup += 1 for k in range(cnt, cnt+dup): re[k] = nums[i] return re #希尔排序 def shell(nums): gap = len(nums)//2 while gap>0: for i in range(len(nums)): j = i cur = nums[i] while j-gap>=0 and nums[j-gap]>cur: nums[j] = nums[j-gap] j -= gap nums[j] = cur gap //=2 return nums def heapify(nums, n, i): largest = i l = 2*i + 1 r = 2*i + 2 if l<n and nums[i] < nums[l]: largest = l if r<n and nums[largest] < nums[r]: largest = r if largest != i: nums[i],nums[largest] = nums[largest],nums[i] heapify(nums, n, largest) #堆排序 def heap(nums): n = len(nums) for i in range(n, -1, -1): heapify(nums, n, i) for i in range(n-1, 0, -1): nums[i],nums[0] = nums[0],nums[i] heapify(nums, i, 0) return nums #基数排序 def radix_sort(s): i = 0 # 记录当前正在排拿一位,最低位为1 max_num = max(s) # 最大值 j = len(str(max_num)) # 记录最大值的位数 while i < j: bucket_list =[[] for _ in range(10)] # 初始化桶数组 for x in s: bucket_list[int(x / (10**i)) % 10].append(x)# 找到位置放入桶数组 s.clear() # print(bucket_list) for x in bucket_list: # 放回原序列 for y in x: s.append(y) # print(s) i += 1 return s # return bubble(nums) # return select(nums) # return insert(nums) # return quick(nums, 0, len(nums)-1) # return merge(nums) # return bucket(nums) # return count(nums) # return shell(nums) return heap(nums) # return radix(nums) # @lc code=end nums = [5,1,1,2,0,0] o = Solution() print(o.sortArray(nums))
3e400e6a75eb427dc43cce66ff23c5e6bf40a9a2
wulinlw/leetcode_cn
/初级算法/mathematics_1.py
1,133
3.875
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/25/math/60/ # Fizz Buzz # 写一个程序,输出从 1 到 n 数字的字符串表示。 # 1. 如果 n 是3的倍数,输出“Fizz”; # 2. 如果 n 是5的倍数,输出“Buzz”; # 3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。 # 示例: # n = 15, # 返回: # [ # "1", # "2", # "Fizz", # "4", # "Buzz", # "Fizz", # "7", # "8", # "Fizz", # "Buzz", # "11", # "Fizz", # "13", # "14", # "FizzBuzz" # ] class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ re = [] for i in range(1,n+1): # print(i) if (i%3 + i%5) ==0: re.append("FizzBuzz") elif i%3==0 and i%5!=0: re.append("Fizz") elif i%3!=0 and i%5==0: re.append("Buzz") else: re.append(str(i)) return re n=12 s = Solution() re = s.fizzBuzz(n) print("deep:",re)
6719f2cc32c1a8cd9f06575e3c730105c15b3fc5
wulinlw/leetcode_cn
/字节跳动/array-and-sorting_8.py
2,455
3.890625
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/bytedance/243/array-and-sorting/1036/ # 朋友圈 # 班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。所谓的朋友圈,是指所有朋友的集合。 # 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。你必须输出所有学生中的已知的朋友圈总数。 # 示例 1: # 输入: # [[1,1,0], # [1,1,0], # [0,0,1]] # 输出: 2 # 说明:已知学生0和学生1互为朋友,他们在一个朋友圈。 # 第2个学生自己在一个朋友圈。所以返回2。 # 示例 2: # 输入: # [[1,1,0], # [1,1,1], # [0,1,1]] # 输出: 1 # 说明:已知学生0和学生1互为朋友,学生1和学生2互为朋友,所以学生0和学生2也是朋友,所以他们三个在一个朋友圈,返回1。 # 注意: # N 在[1,200]的范围内。 # 对于所有学生,有M[i][i] = 1。 # 如果有M[i][j] = 1,则有M[j][i] = 1。 class Solution(object): def findCircleNum(self, M): """ :type M: List[List[int]] :rtype: int """ """ 算法:DFS 思路: 可以将题目转换为是在一个图中求连通子图的问题,给出的N*N的矩阵就是邻接矩阵,建立N个节点的visited数组, 从not visited的节点开始深度优先遍历,遍历就是在邻接矩阵中去遍历,如果在第i个节点的邻接矩阵那一行中的第j 个位置处M[i][j]==1 and not visited[j],就应该dfs到这个第j个节点的位置, 复杂度分析: 时间:ON2?遍历所有节点 空间:ON,visited数组 """ if M == [] or M[0] == []: return 0 n = len(M) visited = [False] * n def dfs(i): visited[i] = True for j in range(n): if M[i][j] == 1 and not visited[j]: dfs(j) counter = 0 for i in range(n): if not visited[i]: dfs(i) counter += 1 return counter M = [[1,1,0], [1,1,0], [0,0,1]] s = Solution() n = s.findCircleNum(M) print(n)
177cb9cffdfe5c9fe8035ec10664006982f49606
wulinlw/leetcode_cn
/初级算法/other_2.py
1,212
4.0625
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/65/ # 汉明距离 # 两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 # 给出两个整数 x 和 y,计算它们之间的汉明距离。 # 注意: # 0 ≤ x, y < 231. # 示例: # 输入: x = 1, y = 4 # 输出: 2 # 解释: # 1 (0 0 0 1) # 4 (0 1 0 0) # ↑ ↑ # 上面的箭头指出了对应二进制位不同的位置。 class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ # x^y是异或运算,不同为1,相同为0,bin()的结果是01字符串,求结果01字符串中的'1'字符的个数,就是hamming distance。 return bin(x^y).count("1") def hammingDistance2(self, x, y): print("{:0>32b}".format(x)) print("{:0>32b}".format(y)) print("{:0>32b}".format(x^y)) v = x^y c=0 while v!=0 : if v&1 ==1: c+=1 v=v>>1 return c x=11 y=2 s = Solution() re = s.hammingDistance2(x,y) print("deep:",re)
c842b9d5b5342e91b9e84dbeecf698e1a8ce8570
wulinlw/leetcode_cn
/初级算法/mathematics_2.py
1,763
3.984375
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/25/math/61/ # 计数质数 # 统计所有小于非负整数 n 的质数的数量。 # 示例: # 输入: 10 # 输出: 4 # 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 # 厄拉多塞筛法 # 西元前250年,希腊数学家厄拉多塞(Eeatosthese)想到了一个非常美妙的质数筛法, # 减少了逐一检查每个数的的步骤,可以比较简单的从一大堆数字之中,筛选出质数来,这方法被称作厄拉多塞筛法(Sieve of Eeatosthese)。 # 具体操作: # 先将 2~n 的各个数放入表中,然后在2的上面画一个圆圈,然后划去2的其他倍数; # 第一个既未画圈又没有被划去的数是3,将它画圈,再划去3的其他倍数; # 现在既未画圈又没有被划去的第一个数 是5,将它画圈,并划去5的其他倍数…… # 依次类推,一直到所有小于或等于 n 的各数都画了圈或划去为止。 # 这时,表中画了圈的以及未划去的那些数正好就是小于 n 的素数。 class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n < 3: return 0 prime = [1] * n prime[0] = prime[1] = 0 for i in range(2, int(n**0.5) +1):#根号N后面的都会被划掉 if prime[i] == 1:#没有划去的值为1 # print(i,prime[i*i:n:i]) prime[i*i:n:i] = [0]*len(prime[i*i:n:i])#划去I的倍数,值设为0 # print(i,prime[i*i:n:i]) return sum(prime)#最后留下的都是质数,值为1 n=12 s = Solution() re = s.countPrimes(n) print("deep:",re)
8930fdd2af4503f19f5eea56e0e004319275a342
wulinlw/leetcode_cn
/程序员面试金典/面试题16.16.部分排序.py
2,042
4.03125
4
# #!/usr/bin/python # #coding:utf-8 # # 面试题16.16.部分排序 # # https://leetcode-cn.com/problems/sub-sort-lcci/ # # 给定一个整数数组,编写一个函数,找出索引m和n,只要将索引区间[m,n]的元素排好序,整个数组就是有序的。注意:n-m尽量最小,也就是说,找出符合条件的最短序列。函数返回值为[m,n],若不存在这样的m和n(例如整个数组是有序的),请返回[-1,-1]。 # 示例: # 输入: [1,2,4,7,10,11,7,12,6,7,16,18,19] # 输出: [3,9] # # 提示: # # 0 # # # # Medium 44.1% # Testcase Example: [] # # 提示: # 在开始和结束时知道最长的排序序列会有帮助吗? # 我们可以把这个数组分成3个子数组:LEFT、MIDDLE和RIGHT。LEFT和RIGHT都是有序的。MIDDLE的元素顺序是任意的。我们需要展开MIDDLE,直到可以对这些元素排序并使整个数组有序。 # 考虑3个子数组:LEFT、MIDDLE和RIGHT。只关注这个问题:是否可以排序MIDDLE以使整个数组有序?如何进行验证? # 为了能够对MIDDLE进行排序并对整个数组进行排序,需要MAX(LEFT) <= MIN(MIDDLE, RIGHT)和MAX(LEFT, MIDDLE) <= MIN(RIGHT)。 # 你能把中间部分展开直到满足前面的条件吗? # 你应该能在O(N)时间内解出来。 # # from typing import List class Solution: def subSort(self, array: List[int]) -> List[int]: n = len(array) maxval, minval = -10000000, 10000000 l, r = -1, -1 for i in range(n): #从左往右找最大值,出现小的,那这里就需要排序 if array[i] < maxval: r = i else: maxval = array[i] for i in range(n-1, -1, -1): #从右往左找最小值,出现大的,就要排序 if array[i] > minval: l = i else: minval = array[i] return [l, r] array = [1,2,4,7,10,11,7,12,6,7,16,18,19] o = Solution() print(o.subSort(array))
a7a068cb60a7c34934ca3980b45ab240ac077b7e
wulinlw/leetcode_cn
/leetcode-vscode/892.三维形体的表面积.py
1,718
3.671875
4
# # @lc app=leetcode.cn id=892 lang=python3 # # [892] 三维形体的表面积 # # https://leetcode-cn.com/problems/surface-area-of-3d-shapes/description/ # # algorithms # Easy (55.73%) # Likes: 68 # Dislikes: 0 # Total Accepted: 8.6K # Total Submissions: 14.3K # Testcase Example: '[[2]]' # # 在 N * N 的网格上,我们放置一些 1 * 1 * 1  的立方体。 # # 每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。 # # 请你返回最终形体的表面积。 # # # # # # # 示例 1: # # 输入:[[2]] # 输出:10 # # # 示例 2: # # 输入:[[1,2],[3,4]] # 输出:34 # # # 示例 3: # # 输入:[[1,0],[0,2]] # 输出:16 # # # 示例 4: # # 输入:[[1,1,1],[1,0,1],[1,1,1]] # 输出:32 # # # 示例 5: # # 输入:[[2,2,2],[2,1,2],[2,2,2]] # 输出:46 # # # # # 提示: # # # 1 <= N <= 50 # 0 <= grid[i][j] <= 50 # # # from typing import List # @lc code=start class Solution: def surfaceArea(self, grid: List[List[int]]) -> int: re = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]>0: re += grid[i][j] * 4 + 2 #上和下,4个面*个数 re -= min(grid[i-1][j], grid[i][j]) * 2 if i>0 else 0 #减去与上面相邻的面积,较少的*2 re -= min(grid[i][j-1], grid[i][j]) * 2 if j>0 else 0 #减去与左边相邻的面积,较少的*2 return re # @lc code=end grid = [[2]] grid = [[1,2],[3,4]] grid = [[1,0],[0,2]] grid = [[1,1,1],[1,0,1],[1,1,1]] grid = [[2,2,2],[2,1,2],[2,2,2]] o = Solution() print(o.surfaceArea(grid))
2a7878e20f2170d581b6defd02672e1d886cf7e6
wulinlw/leetcode_cn
/程序员面试金典/面试题02.04.分割链表.py
1,492
3.921875
4
#!/usr/bin/python #coding:utf-8 # 面试题 02.04. 分割链表 # 编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之后(如下所示)。 # 分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。 # 示例: # 输入: head = 3->5->8->5->10->2->1, x = 5 # 输出: 3->1->2->10->5->5->8 # https://leetcode-cn.com/problems/partition-list-lcci/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def initlinklist(self, nums): head = ListNode(nums[0]) re = head for i in nums[1:]: re.next = ListNode(i) re = re.next return head def printlinklist(self, head): re = [] while head: re.append(head.val) head = head.next print(re) def partition(self, head: ListNode, x: int) -> ListNode: i, j = head, head while j: if j.val < x: # 如果等于 x 不做处理 i.val, j.val = j.val, i.val #链表中的替换,原位置的next不变 i = i.next j = j.next return head nums = [3,5,8,5,10,2,1] x = 5 o = Solution() head = o.initlinklist(nums) o.printlinklist(head) h = o.partition(head, x) # print(h) o.printlinklist(h)
ecfa4146a927249cf7cb510dbf14432cd2bb84a7
wulinlw/leetcode_cn
/剑指offer/30_包含min函数的栈.py
1,296
4.125
4
#!/usr/bin/python #coding:utf-8 # // 面试题30:包含min函数的栈 # // 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min # // 函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。 class StackWithMin: def __init__(self): self.stack = [] self.min_stack = [] def push(self, node): # write code here self.stack.append(node) if not self.min_stack: self.min_stack.append(node) else: if self.min_stack[-1] < node: self.min_stack.append(self.min_stack[-1]) else: self.min_stack.append(node) def pop(self): # write code here self.stack.pop(-1) self.min_stack.pop(-1) def top(self): # write code here if self.stack: return self.stack[-1] else: return [] def min(self): # write code here return self.min_stack[-1] def debug(self): print(self.stack) print(self.stack_min) print("\n") s = StackWithMin() s.push(2.98) s.push(3) s.debug() s.pop() s.debug() s.push(1) s.debug() s.pop() s.debug() s.push(1) s.push(2) s.push(3) s.debug() s.push(0) s.debug()
9e2c9cc88b442a408d79363289c2cfc3905d13c4
wulinlw/leetcode_cn
/剑指offer/17_打印1到最大的n位数.py
1,245
3.6875
4
#!/usr/bin/python #coding:utf-8 # 打印1到最大的n位数 # 输入数字n, 按顺序打印从1最大的n位十进制数 # 比如输入3, 则打印出1、2、3、到最大的3位数即999 class Solution: def Print1ToMaxOfNDigits(self, n): for i in range(10): #套路写法,生产每一位的0-9,从最左边开始生成 self.recursion(str(i), n, 0) #每个数字的开头 # s 数字开头 # n 几位数 # index 当前第几位 def recursion(self, s, n, index): if index==n-1: #达到位数,开始输出 # print(s) self.printNum(s) return for i in range(10): #和上面一样套路,生成下一位的数0-9 self.recursion(s+str(i), n, index+1) def printNum(self, num): isBeginning0 = True nLength = len(num) for i in range(nLength): if isBeginning0 and num[i] != '0': isBeginning0 = False if not isBeginning0: print('%s' % num[i], end='') #格式化字符及其ASCII码 print('') obj = Solution() obj.Print1ToMaxOfNDigits(2)
1292292f8f86615a11e933a7234211ad43a71da8
wulinlw/leetcode_cn
/top-interview-quesitons-in-2018/dynamic-programming_1.py
1,113
3.953125
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/featured/card/top-interview-quesitons-in-2018/272/dynamic-programming/1174/ # 至少有K个重复字符的最长子串 # 找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。 # 示例 1: # 输入: # s = "aaabb", k = 3 # 输出: # 3 # 最长子串为 "aaa" ,其中 'a' 重复了 3 次。 # 示例 2: # 输入: # s = "ababbc", k = 2 # 输出: # 5 # 最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。 # https://blog.csdn.net/weixin_41303016/article/details/88686110 class Solution(object): def longestSubstring(self, s, k): """ :type s: str :type k: int :rtype: int """ for i in set(s):#去重 if s.count(i) < k: # 找出不满足k次的字母,将其作为分割点进行分治 return max(self.longestSubstring(m, k) for m in s.split(i)) return len(s) ss = "aaabbc" k = 3 s = Solution() res = s.longestSubstring(ss, k) print(res)
fcc7f51524ae8699c60101b37ff9bbcffdfa1263
wulinlw/leetcode_cn
/剑指offer/44_数字序列中某一位的数字.py
2,798
3.75
4
#!/usr/bin/python #coding:utf-8 # // 面试题44:数字序列中某一位的数字 # // 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这 # // 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一 # // 个函数求任意位对应的数字。 class Solution: def digitAtIndex(self, index): if index < 0: return -1 digits = 1 while True: length = self.digitsLength(digits) #n位数的长度 if index < length*digits: #长度在n位数的范围内 return self.findIndex(index, digits) index -= length*digits #超过了这个长度,减去已知的长度 digits += 1 # 计算n位数有多少个 ,1-10 2-90 3-900 4-9000 def digitsLength(self, digits): if digits==1: return 10 c = pow(10, digits-1) return 9 * c # 从第n位中找出index的位数 def findIndex(self, index, digits):#索引 位数 first = 0 if index==1: first = 0 else: first = pow(10, digits-1) #n位数的第一个数 num = first + index//digits #位数除以长度=第xx位数 indexFromRight = digits - index % digits#位数-第几位== 从右边要找的那个位 for _ in range(1,indexFromRight): num = num//10 return num % 10 #取一位 def findNthDigit(self, n: int) -> int: # 首先判断target是几位数,用digits表示 base = 9 digits = 1 while n - base * digits > 0: n -= base * digits base *= 10 digits += 1 # 计算target的值 idx = n % digits # 注意由于上面的计算,n现在表示digits位数的第n个数字 if idx == 0: idx = digits number = 1 for i in range(1,digits): number *= 10 if idx == digits: number += n // digits - 1 else: number += n // digits # 找到target中对应的数字 for i in range(idx,digits): number //= 10 return number % 10 # 作者:z1m # 链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/zhe-shi-yi-dao-shu-xue-ti-ge-zhao-gui-lu-by-z1m/ # 来源:力扣(LeetCode) # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 obj = Solution() print(obj.digitAtIndex(13)) print(obj.digitAtIndex(1001)) print(obj.digitAtIndex(1002)) print(obj.digitAtIndex(1003)) print(obj.digitAtIndex(1004)) print(obj.digitAtIndex(1005))
93980a2f1b9d778ff907998b6fb722722ec28d73
wulinlw/leetcode_cn
/递归/recursion_1_1.py
1,304
4.15625
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/orignial/card/recursion-i/256/principle-of-recursion/1198/ # 反转字符串 # 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 # 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 # 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 # 示例 1: # 输入:["h","e","l","l","o"] # 输出:["o","l","l","e","h"] # 示例 2: # 输入:["H","a","n","n","a","h"] # 输出:["h","a","n","n","a","H"] class Solution(object): # 递归 def reverseString(self, s): def recur(tmp): if len(tmp)<=1: return tmp else: return recur(tmp[1:])+[tmp[0]] s[:] = recur(s) # 递归+双指针 def reverseString2(self, s): """ :type s: str :rtype: str """ def recur_(s, i,j): if i>=j: return else: s[i],s[j] = s[j],s[i] recur_(s,i+1,j-1) recur_(s,0,len(s)-1) s = ["h","e","l","l","o"] S = Solution() deep = S.reverseString2(s) print("deep:",deep)
b3328bb716cac18bf8e375f48de6ae5d67faa44b
wulinlw/leetcode_cn
/中级算法/tree_6.py
2,059
3.796875
4
#!/usr/bin/python #coding:utf-8 # https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/32/trees-and-graphs/90/ # 岛屿的个数 # 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量。一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。 # 示例 1: # 输入: # 11110 # 11010 # 11000 # 00000 # 输出: 1 # 示例 2: # 输入: # 11000 # 11000 # 00100 # 00011 # 输出: 3 class Solution(object): # 遍历二维数组每一个元素,找到一块陆地后遍历寻找与这块陆地相连的所有陆地并将找到的陆地全部改为"0", # 每一个1,岛屿数量加一 def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ n = len(grid)#列数 if n == 0: return 0 m = len(grid[0])#行数 if m == 0: return 0 res = 0 # 遍历每一个字符 for i in range(n): for j in range(m): # 如果遍历字符是陆地"1" if grid[i][j] == "1": res += 1 # 递归查找与这块陆地相连的所有陆地 并将他们改为零 self.change(grid, i, j) return res def change(self, grid, i, j): grid[i][j] = "0" # 判断上方字符 if i > 0 and grid[i - 1][j] == "1": self.change(grid, i - 1, j) # 判断左方字符 if j > 0 and grid[i][j - 1] == "1": self.change(grid, i, j - 1) # 判断下方字符 if i < len(grid) - 1 and grid[i + 1][j] == "1": self.change(grid, i + 1, j) # 判断右方字符 if j < len(grid[0]) - 1 and grid[i][j + 1] == "1": self.change(grid, i, j + 1) grid = [ [1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1] ] s = Solution() r = s.numIslands(grid) print(r)
bacfbc3a4a068cf87954be2a53e0a6ab44ba41bc
wulinlw/leetcode_cn
/链表/linked-list_5_3.py
2,469
4.125
4
#!/usr/bin/python # coding:utf-8 # https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/764/ # 扁平化多级双向链表 # 您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。 # 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。 # 示例: # 输入: # 1---2---3---4---5---6--NULL # | # 7---8---9---10--NULL # | # 11--12--NULL # 输出: # 1-2-3-7-8-11-12-9-10-4-5-6-NULL # 以上示例的说明: # 给出以下多级双向链表: # 我们应该返回如下所示的扁平双向链表: # Definition for a Node. class Node(object): def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child class Solution(object): def list_generate(self, lst): """ 生成链表 """ if not lst: return None list_node = Node(lst[0]) if len(lst) == 1: list_node.next = None else: list_node.next = self.list_generate(lst[1:]) return list_node # 测试打印 def printList(self, list_node): re = [] while list_node: re.append(list_node.val) list_node = list_node.next print(re) def flatten(self, head): """ :type head: Node :rtype: Node """ p = rst = Node(None, None, None, None) # 初始化结果链表及其指针 visited = head and [head] # 初始化栈 while visited: vertex = visited.pop() if vertex.next: visited.append(vertex.next) if vertex.child: visited.append(vertex.child) p.next = vertex # pop出来的节点就是所需节点 p, p.prev, p.child = p.next, p, None # 设定节点属性 # p = p.next后相当于右移一位后,p.prev就是p了 if rst.next: rst.next.prev = None # rst是要返回的头,rst.next的prev属性要设为None return rst.next l = [1, 2, 6, 3, 4, 5, 6] node = 6 obj = Solution() head = obj.list_generate(l) obj.printList(head) r = obj.flatten(head) obj.printList(r)
43d875814e422cab3a1d28b38b8862ef137e70ae
wulinlw/leetcode_cn
/剑指offer/28_对称的二叉树.py
2,014
3.671875
4
#!/usr/bin/python #coding:utf-8 # // 面试题28:对称的二叉树 # // 题目:请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和 # // 它的镜像一样,那么它是对称的。 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetrical(self, root): if not root:return True def core(L, R): if not L and not R:return True if not L or not R:return False if L.val != R.val:return False return core(L.left, R.right) and core(L.right, R.left) return core(root.left, root.right) # 层次遍历 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 # 测试树 # 6 # 8 8 # 1 4 4 1 # 按层定义 t1 = TreeNode(6) t2 = TreeNode(8) t3 = TreeNode(8) t4 = TreeNode(1) t5 = TreeNode(4) t6 = TreeNode(4) t7 = TreeNode(1) root = t1 root.left = t2 root.right = t3 t2.left = t4 t2.right = t5 t3.left = t6 t3.right = t7 # t3.right = None #False obj = Solution() re = obj.levelOrder(root) for i in range(len(re)): print(re[i]) print("\n") print(obj.isSymmetrical(root))
b7fce39adf1ba1fa6029dda276e2fde9eb8277ec
wulinlw/leetcode_cn
/剑指offer/23_链表中环的入口结点.py
1,404
3.796875
4
#!/usr/bin/python #coding:utf-8 # // 面试题23:链表中环的入口结点 # // 题目:一个链表中包含环,如何找出环的入口结点?例如,在图3.8的链表中, # // 环的入口结点是结点3。 class ListNode: def __init__(self, x=None): self.val = x self.next = None class Solution: def initlinklist(self, nums): head = ListNode(nums[0]) re = head for i in nums[1:]: re.next = ListNode(i) re = re.next return head def printlinklist(self, head): re = [] while head: re.append(head.val) head = head.next print(re) def MeetingNode(self, head): if not head:return False p1 = slow = fast = head while 1: slow = slow.next if not fast.next.next: return False fast = fast.next.next if slow == fast: break while p1 != slow: p1 = p1.next slow = slow.next return slow n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n2#环在这里 # print(n5.val,n5.next.val) nums = [1,2,3,4,5] obj = Solution() # head = obj.initlinklist(nums) # obj.printlinklist(n1) print(obj.MeetingNode(n1).val)
4154a18778d1e344a20d388bb08ce7d33022adce
wulinlw/leetcode_cn
/leetcode-vscode/78.子集.py
1,086
3.578125
4
# # @lc app=leetcode.cn id=78 lang=python3 # # [78] 子集 # # https://leetcode-cn.com/problems/subsets/description/ # # algorithms # Medium (76.55%) # Likes: 493 # Dislikes: 0 # Total Accepted: 69.2K # Total Submissions: 90.1K # Testcase Example: '[1,2,3]' # # 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 # # 说明:解集不能包含重复的子集。 # # 示例: # # 输入: nums = [1,2,3] # 输出: # [ # ⁠ [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # # from typing import List # @lc code=start class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: re = [] def backtrack(nums, idx, tmp): if idx >len(nums):return re.append(tmp[:]) for i in range(idx, len(nums)): tmp.append(nums[i]) backtrack(nums, i+1, tmp) tmp.pop() nums.sort() backtrack(nums, 0, []) return re # @lc code=end nums = [1,2,3] o = Solution() print(o.subsets(nums))
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)))