blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4d42e180640b99d5da994d6020a52d8f54a85866 | Asunqingwen/LeetCode | /hard/Wildcard Matching.py | 1,821 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/16 0016 16:17
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Wildcard Matching.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input:
s = "acdcb"
p = "a*c?b"
Output: false
"""
def isMatch(s: str, p: str) -> bool:
if len(s) != len(p) and '?' not in p and '*' not in p:
return False
dp = [[0] * (len(p) + 1) for _ in range(len(s) + 1)]
dp[0][0] = 1
for i in range(len(p)):
if p[i] == '*':
dp[0][i + 1] = dp[0][i]
for i in range(len(s)):
for j in range(len(p)):
if p[j] == s[i] or p[j] == '?':
dp[i + 1][j + 1] = dp[i][j]
if p[j] == '*':
dp[i + 1][j + 1] = dp[i + 1][j] or dp[i][j + 1]
return dp[len(s)][len(p)] == 1
if __name__ == '__main__':
s = "adceb"
p = "*a*b"
result = isMatch(s, p)
print(result)
| true |
279f14a391ecdf9ef7de06885c350a60c6a07ce6 | Asunqingwen/LeetCode | /easy/Quad Tree Intersection.py | 2,798 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/9/3 0003 14:36
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Quad Tree Intersection.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
A quadtree is a tree data in which each internal node has exactly four children: topLeft, topRight, bottomLeft and bottomRight. Quad trees are often used to partition a two-dimensional space by recursively subdividing it into four quadrants or regions.
We want to store True/False information in our quad tree. The quad tree is used to represent a N * N boolean grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same. Each node has another two boolean attributes : isLeaf and val. isLeaf is true if and only if the node is a leaf node. The val attribute for a leaf node contains the value of the region it represents.
For example, below are two quad trees A and B:
A:
+-------+-------+ T: true
| | | F: false
| T | T |
| | |
+-------+-------+
| | |
| F | F |
| | |
+-------+-------+
topLeft: T
topRight: T
bottomLeft: F
bottomRight: F
Your task is to implement a function that will take two quadtrees and return a quadtree that represents the logical OR (or union) of the two trees.
Note:
Both A and B represent grids of size N * N.
N is guaranteed to be a power of 2.
If you want to know more about the quad tree, you can refer to its wiki.
The logic OR operation is defined as this: "A or B" is true if A is true, or if B is true, or if both A and B are true.
"""
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
def intersect(quadTree1: 'Node', quadTree2: 'Node') -> 'Node':
if quadTree1.isLeaf:
if quadTree1.val:
return quadTree1
else:
return quadTree2
if quadTree2.isLeaf:
if quadTree2.val:
return quadTree2
else:
return quadTree1
topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft)
topRight = intersect(quadTree1.topRight, quadTree2.topRight)
bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)
bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight)
if topLeft.isLeaf and topRight.isLeaf and bottomLeft.isLeaf and bottomRight and topLeft.val and topRight.val and bottomLeft.val and bottomRight.val:
return Node(True, True, None, None, None, None)
return Node(False, False, topLeft, topRight, bottomLeft, bottomRight)
if __name__ == '__main__':
input = 0
intersect()
| true |
d766d7a9b5aa0930ac7a76a6839b801830679829 | Asunqingwen/LeetCode | /easy/Maximum Depth of N-ary Tree.py | 1,161 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/23 0023 15:41
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Maximum Depth of N-ary Tree.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
We should return its max depth, which is 3.
Note:
The depth of the tree is at most 1000.
The total number of nodes is at most 5000.
"""
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
def maxDepth(root: 'Node') -> int:
if not root:
return 0
node_depth_dict = [[root, 1]]
depth = 0
while node_depth_dict:
node_depth = node_depth_dict.pop(0)
root = node_depth[0]
curr_depth = node_depth[1]
depth = max(depth, curr_depth)
if root.children:
for child in root.children:
node_depth_dict.append([child, curr_depth + 1])
return depth
if __name__ == '__main__':
input = Node(1, 1)
output = maxDepth(input)
print(output)
| true |
d6927193176ccedc82875fa6614e44be20495d03 | Asunqingwen/LeetCode | /medium/Minimum Moves to Equal Array Elements II.py | 960 | 4.25 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/10 0010 16:41
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Minimum Moves to Equal Array Elements II.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
Example:
Input:
[1,2,3]
Output:
2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]
"""
from typing import List
def minMoves2(nums: List[int]) -> int:
nums.sort()
mid = nums[len(nums) // 2]
return sum([abs(k - mid) for k in nums])
if __name__ == '__main__':
input = [1, 2, 3]
result = minMoves2(input)
print(result)
| true |
9cb10e26933e62e0571fbca7ab77c40dbd2f941c | Asunqingwen/LeetCode | /每日一题/等式方程的可满足性.py | 2,135 | 4.21875 | 4 | """
给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
示例 1:
输入:["a==b","b!=a"]
输出:false
解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
示例 2:
输出:["b==a","a==b"]
输入:true
解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
示例 3:
输入:["a==b","b==c","a==c"]
输出:true
示例 4:
输入:["a==b","b!=c","c==a"]
输出:false
示例 5:
输入:["c==c","b==d","x!=z"]
输出:true
提示:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] 和 equations[i][3] 是小写字母
equations[i][1] 要么是 '=',要么是 '!'
equations[i][2] 是 '='
"""
from typing import List
class Solution:
class UnionFind:
def __init__(self):
self.parent = list(range(26))
def find(self, index):
if index == self.parent[index]:
return index
self.parent[index] = self.find(self.parent[index])
return self.parent[index]
def union(self, index1, index2):
self.parent[self.find(index1)] = self.find(index2)
def equationsPossible(self, equations: List[str]) -> bool:
uf = Solution.UnionFind()
for st in equations:
if st[1] == "=":
index1 = ord(st[0]) - ord("a")
index2 = ord(st[3]) - ord("a")
uf.union(index1, index2)
for st in equations:
if st[1] == "!":
index1 = ord(st[0]) - ord("a")
index2 = ord(st[3]) - ord("a")
if uf.find(index1) == uf.find(index2):
return False
return True | false |
2a451848c07eab332b0e52c676f7dc9c45a9e181 | Asunqingwen/LeetCode | /easy/Flood Fill.py | 2,511 | 4.375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/9/2 0002 13:44
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Flood Fill.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:
The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
"""
from typing import List
def floodFill(image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
if newColor == image[sr][sc]:
return image
row, col = len(image), len(image[0])
queue_list = [[sr, sc]]
init_color = image[sr][sc]
image[sr][sc] = newColor
while queue_list:
x, y = queue_list.pop(0)
l, r, u, d = y - 1, y + 1, x - 1, x + 1
if l >= 0 and image[x][l] == init_color:
image[x][l] = newColor
queue_list.append([x, l])
if r < col and image[x][r] == init_color:
image[x][r] = newColor
queue_list.append([x, r])
if u >= 0 and image[u][y] == init_color:
image[u][y] = newColor
queue_list.append([u, y])
if d < row and image[d][y] == init_color:
image[d][y] = newColor
queue_list.append([d, y])
return image
if __name__ == '__main__':
image = [[0, 0, 0], [0, 1, 1]]
sr = 1
sc = 1
newColor = 1
result = floodFill(image, sr, sc, newColor)
print(result)
| true |
e14a216338c74133aced7258e4e170db5c6f3856 | Asunqingwen/LeetCode | /easy/Number of Equivalent Domino Pairs.py | 1,222 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/9/24 0024 15:48
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Number of Equivalent Domino Pairs.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Constraints:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
"""
from typing import List
def numEquivDominoPairs(dominoes: List[List[int]]) -> int:
if len(dominoes) < 2:
return 0
count = {}
res = 0
for dominoe in dominoes:
dominoe.sort()
key = ''.join([str(i) for i in dominoe])
count[key] = count.get(key, 0) + 1
for v in count.values():
res += v * (v - 1) // 2
return res
if __name__ == '__main__':
dominoes = [[1, 2], [2, 1], [3, 4], [5, 6]]
result = numEquivDominoPairs(dominoes)
print(result)
| true |
4fbaab2328fd0e2fb0c439c4d83a41f9d86bb18c | Asunqingwen/LeetCode | /medium/Convert to Base -2.py | 786 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/26 0026 15:49
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Convert to Base -2.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given a number N, return a string consisting of "0"s and "1"s that represents its value in base -2 (negative two).
The returned string must have no leading zeroes, unless the string is "0".
Example 1:
Input: 2
Output: "110"
Explantion: (-2) ^ 2 + (-2) ^ 1 = 2
Note:
0 <= N <= 10^9
"""
def baseNeg2(N: int) -> str:
result = ''
while N:
N, k = -(N // 2), N % 2
result = str(k) + result
return result if result else '0'
if __name__ == '__main__':
input = 2
result = baseNeg2(input)
print(result)
| true |
5fd091722fb919ac160ee0f6d443dbaf0f296654 | Asunqingwen/LeetCode | /medium/Path With Maximum Minimum Value.py | 1,931 | 4.4375 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/11 0011 15:36
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Path With Maximum Minimum Value.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given a matrix of integers A with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1].
The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4.
A path moves some number of times from one visited cell to any neighbouring unvisited cell in one of the 4 cardinal directions (north, east, west, south).
Example 1:
Input: [[5,4,5],[1,2,6],[7,4,6]]
Output: 4
Explanation:
The path with the maximum score is highlighted in yellow.
Example 2:
Input: [[2,2,1,2,2,2],[1,2,2,2,1,2]]
Output: 2
Example 3:
Input: [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]
Output: 3
Note:
1 <= R, C <= 100
0 <= A[i][j] <= 10^9
"""
import heapq as hq
from typing import List
def maximumMinimumPath(A: List[List[int]]) -> int:
row, col = len(A), len(A[0])
# 坐标值必须放在最前面,因为heapq排序默认是以存储对象的第一个值进行排序的,然后再对第二个值排序,以此类推
ans = [(-A[0][0], 0, 0)]
A[0][0] = -1
hq.heapify(ans)
while ans:
score, i, j = hq.heappop(ans)
if (i, j) == (row - 1, col - 1):
return -score
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
new_i = i + di
new_j = j + dj
if 0 <= new_i < row and 0 <= new_j < col:
if A[new_i][new_j] != -1:
hq.heappush(ans, (max(score, -A[new_i][new_j]), new_i, new_j))
A[new_i][new_j] = -1
if __name__ == '__main__':
A = [[3, 4, 6, 3, 4], [0, 2, 1, 1, 7], [8, 8, 3, 2, 7], [3, 2, 4, 9, 8], [4, 1, 2, 0, 0], [4, 6, 5, 4, 3]]
result = maximumMinimumPath(A)
print(result)
| true |
319ad5c92b3df72a4a45c43ce5355e5cf022f77c | Asunqingwen/LeetCode | /easy/Fibonacci Number.py | 921 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/9 0009 10:09
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Fibonacci Number.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
"""
def fib(N: int) -> int:
if N < 2:
return N
nums = [0, 1]
temp = 0
for i in range(2, N + 1):
temp = nums[0] + nums[1]
nums[0] = nums[1]
nums[1] = temp
return temp
def fib1(N: int) -> int:
if N < 2:
return N
f0, f1 = 0, 1
for i in range(N - 1):
f0, f1 = f1, f0 + f1
return f1
if __name__ == '__main__':
nums = 3
result = fib1(nums)
print(result)
| false |
4aaef49551a246c67ce7de4f0e01bd9f6e0c0748 | Asunqingwen/LeetCode | /medium/Number of Dice Rolls With Target Sum.py | 1,997 | 4.25 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/16 0016 9:36
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Number of Dice Rolls With Target Sum.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
Example 1:
Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces. There is only one way to get a sum of 3.
Example 2:
Input: d = 2, f = 6, target = 7
Output: 6
Explanation:
You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
Example 3:
Input: d = 2, f = 5, target = 10
Output: 1
Explanation:
You throw two dice, each with 5 faces. There is only one way to get a sum of 10: 5+5.
Example 4:
Input: d = 1, f = 2, target = 3
Output: 0
Explanation:
You throw one die with 2 faces. There is no way to get a sum of 3.
Example 5:
Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation:
The answer must be returned modulo 10^9 + 7.
Constraints:
1 <= d, f <= 30
1 <= target <= 1000
"""
def numRollsToTarget(d: int, f: int, target: int) -> int:
dp = [[0] * 1001 for _ in range(31)]
min_v = min(f, target)
# 丢一个骰子,单个骰子字面上的数字产生的次数都为1
for i in range(1, min_v + 1):
dp[1][i] = 1
# 从两个骰子开始
for i in range(2, d + 1):
# 投出的数字最大不能超过目标值
for j in range(i, target + 1):
# 前一个骰子投出的数字,小于目标值,且在一个骰子能投出的数字内
k = 1
while j - k >= 0 and k <= f:
dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % 1000000007
k += 1
return dp[d][target]
if __name__ == '__main__':
d = 1
f = 6
target = 3
result = numRollsToTarget(d, f, target)
print(result)
| true |
32ade4dd6de91b9e2fe826fd0337de839d1f6ce3 | Asunqingwen/LeetCode | /medium/Rectangle Area.py | 1,036 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/26 0026 15:16
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Rectangle Area.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
"""
def computeArea(A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
total_area = (C - A) * (D - B) + (G - E) * (H - F)
if C < E or D < F or G < A or H < B:
return total_area
cov_area = (min(C, G) - max(A, E)) * (min(D, H) - max(B, F))
return total_area - cov_area
if __name__ == '__main__':
A, B, C, D, E, F, G, H = -2,-2,2,2,3,3,4,4
result = computeArea(A, B, C, D, E, F, G, H)
print(result)
| true |
47bc6fe67589143a869b308917095179d2c9f265 | Asunqingwen/LeetCode | /medium/Number of Longest Increasing Subsequence.py | 1,421 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/25 0025 13:59
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Number of Longest Increasing Subsequence.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
"""
from typing import List
def findNumberOfLIS(nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)
# 当前长度,当前个数
lengths = [0] * len(nums)
counts = [1] * len(nums)
for i, num in enumerate(nums):
for j in range(i):
if nums[j] < num:
if lengths[j] >= lengths[i]:
lengths[i] = lengths[j] + 1
counts[i] = counts[j]
elif lengths[j] + 1 == lengths[i]:
counts[i] += counts[j]
max_len = max(lengths)
return sum(c for i, c in enumerate(counts) if lengths[i] == max_len)
if __name__ == '__main__':
nums = [5, 4, 3, 1, 3]
result = findNumberOfLIS(nums)
print(result)
| true |
faeb5730387565077af9e946d84d0411bb78bd53 | Asunqingwen/LeetCode | /easy/Check If a Number Is Majority Element in a Sorted Array.py | 1,392 | 4.46875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/11/15 0015 10:35
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Check If a Number Is Majority Element in a Sorted Array.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given an array nums sorted in non-decreasing order, and a number target, return True if and only if target is a majority element.
A majority element is an element that appears more than N/2 times in an array of length N.
Example 1:
Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
Output: true
Explanation:
The value 5 appears 5 times and the length of the array is 9.
Thus, 5 is a majority element because 5 > 9/2 is true.
Example 2:
Input: nums = [10,100,101,101], target = 101
Output: false
Explanation:
The value 101 appears 2 times and the length of the array is 4.
Thus, 101 is not a majority element because 2 > 4/2 is false.
"""
from typing import List
def isMajorityElement(nums: List[int], target: int) -> bool:
count, ans = 0, target
for num in nums:
if count == 0 or ans == num:
count += 1
ans = num
else:
count -= 1
count = 0
for num in nums:
if num == ans:
count += 1
return ans == target and count > len(nums) / 2
if __name__ == '__main__':
nums = [10, 100, 101, 101]
target = 101
result = isMajorityElement(nums, target)
print(result)
| true |
0ac5276c169b1fd18144ab00311031a571e61f3b | Asunqingwen/LeetCode | /easy/Degree of an Array.py | 1,564 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/10/18 0018 9:20
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Degree of an Array.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6
Note:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
"""
from typing import List
def findShortestSubArray(nums: List[int]) -> int:
count = {}
for i in range(len(nums)):
if nums[i] in count:
count[nums[i]][1] = i
count[nums[i]][2] += 1
else:
count[nums[i]] = [i, i, 1]
count = sorted(count.items(), key=lambda x: x[1][2])
min_len = count[-1][1][1] - count[-1][1][0]
for c in count[-2::-1]:
if c[1][2] == count[-1][1][2]:
min_len = min(c[1][1] - c[1][0], min_len)
else:
break
return min_len + 1
if __name__ == '__main__':
nums = [1, 2, 2, 1, 2, 1, 1, 1, 1, 2, 2, 2]
result = findShortestSubArray(nums)
print(result)
| true |
08bf03355f9364d3e9a05cb8640a53b8ddc78fed | Asunqingwen/LeetCode | /medium/Kth Largest Element in an Array.py | 888 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/9/4 0004 10:21
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Kth Largest Element in an Array.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
"""
import heapq
from typing import List
def findKthLargest(nums: List[int], k: int) -> int:
heapq.heapify(nums)
while len(nums) > k:
heapq.heappop(nums)
return nums[0]
if __name__ == '__main__':
input = [3,2,1,5,6,4]
k = 2
result = findKthLargest(input, k)
print(result)
| true |
94c0dc5786a935ab7522209dc18cb434dfed64f2 | Asunqingwen/LeetCode | /easy/Climbing Stairs.py | 990 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/19 0019 15:43
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Climbing Stairs.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
"""
def climbStairs(n: int) -> int:
if n <= 1:
return 1
ways = 0
n0 = 1
n1 = 1
for i in range(2, n+1):
ways = n1 + n0
n0, n1 = n1, ways
return ways
if __name__ == '__main__':
input = 3
result = climbStairs(input)
print(result)
| true |
a57ab3452a03a7dd136103ce3de19f64c9ff6acb | turpure/py_algo | /algorithms/arrays/limit.py | 862 | 4.5 | 4 | """
Sometimes you need to limit array result to use. Such as you only need the value over
10 or, you need value under than 100. By use this algorithms, you can limit your array
to specific value
If array, Min, Max value was given, it returns array that contains values of given array
which was larger than Min, and lower than Max. You need to give 'unlimit' to use only Min
or Max.
ex) limit([1,2,3,4,5], None, 3) = [1,2,3]
Complexity = O(n)
"""
def limit(arr, min_lim = None, max_lim = None):
result = []
if min_lim == None:
for i in arr:
if i<= max_lim:
result.append(i)
elif max_lim == None:
for i in arr:
if i >= min_lim:
result.append(i)
else:
for i in arr:
if i >= min_lim and i <= max_lim:
result.append(i)
return result
| true |
59e2103fc82191a152545d39adb046e58f3ea347 | Burner999/Python | /car_class_electric.py | 2,151 | 4.3125 | 4 | class Car():
"""A simple attempt to model a car"""
def __init__ (self, make, model, year, colour, odometer_reading):
"""initialize name and age"""
self.make = make
self.model = model
self.year = year
self.colour = colour
self.odometer_reading = odometer_reading
self.category = 'combustion'
def description(self):
print("This car is a " + self.year + " " + self.make.title() + " " + self.model)
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " KMs on it")
def update_odometer(self, newmileage):
if self.odometer_reading < int(newmileage):
self.odometer_reading = int(newmileage)
self.description()
self.read_odometer()
elif mycar.odometer_reading == newmileage:
print("No change to mileage")
else:
print("You can't rollback the mileage !")
class ElectricCar(Car):
"""Represents aspects of an electric car"""
def __init__(self, make, model, year, colour, odometer_reading, charge_level):
super().__init__(make, model, year, colour, odometer_reading)
self.charge_level = charge_level
self.category = 'electric'
def charging(self):
if (int(self.charge_level) < 100) and (int(self.charge_level) > 50):
print("You're car has enough charge")
elif (int(self.charge_level) <= 50) and (int(self.charge_level) > 20):
print("You should consider charging your car soon")
else:
print("You need to charge your car soon")
def update_charge_level(self, new_charge_level):
self.charge_level = new_charge_level
mycar = ElectricCar('Porsche' ,'Taycan' , '2021' , 'Chalk' , 0 , 80 )
mycar.description()
mycar.read_odometer()
mycar.charging()
if mycar.category == 'electric':
msg=("Your charge level is " + str(mycar.charge_level) + "%." + " Is this correct ? (y/n)" )
conf=input(msg)
if conf == 'n':
newmsg=("Enter charge_level:")
new_charge_level=input(newmsg)
mycar.update_charge_level(new_charge_level)
mycar.charging()
msg=("Is the above mileage correct ? (y/n)")
conf=input(msg)
if conf == 'n':
newmsg=("Enter mileage:")
newmileage=input(newmsg)
mycar.update_odometer(newmileage)
else:
print("Enjoy your new car !")
| true |
9d6a56a31533bf402ec3486ccc7a746c50c20efc | meganskrobacz/CCIS | /Othello_Project_Dec_2019/main.py | 1,573 | 4.1875 | 4 |
from board import Board
# PURPOSE
# Sorts the items in a list
# SIGNATURE
# bubble_sort :: List[[Str, Int]] => List[[String, Int]]
def bubble_sort(lst):
length = len(lst)
for i in range(length):
for j in range(length - i - 1):
if lst[j][1] < lst[(j + 1)][1]:
temp = lst[j]
lst[j] = lst[(j + 1)]
lst[(j + 1)] = temp
return lst
def main():
b = Board(8)
b.draw_board()
scores_unsorted = []
if b.winner_declared is True:
name = input(str("Enter your name for the scoreboard: "))
indiv_score = b.black_score
new_entry = [name, indiv_score]
try:
file = open("scores.txt", "r")
for line in file:
line.strip()
lst = line.split(" ")
name = lst[0]
score = int(lst[1])
to_add = [name, score]
scores_unsorted.append(to_add)
file.close()
except FileNotFoundError:
pass
scores_unsorted.append(new_entry)
sorted_list = bubble_sort(scores_unsorted)
file = open("scores.txt", "w")
for entry in sorted_list:
file.writelines("{} {}\n".format(entry[0], entry[1]))
file.close()
print("Here is the leaderboard:")
for entry in sorted_list:
name = entry[0]
score = entry[1]
not_a_list = "{} {}".format(name, score)
print(not_a_list)
main()
| true |
aada4d834a321b2cfb1d73b35d6ccfa6de213fb3 | nik24g/Python | /No. camparison and BMI calculator.py | 1,266 | 4.21875 | 4 | a = 1
b = 2
if a < b:
print("A is less than B")
print("Not sured if A is less than B")
print("_______________________________________________________")
c = 6
d = 4
if c < d:
print("C is less than d")
else:
print("C is not less than D")
print("I don't think C is less than D")
print("out side the if block")
print("________________________________________________________")
e = 8
f = 7
if e < f:
print("E is less than F")
else:
if e == f:
print("E is equal to F")
else:
print("E is greater than F")
print("________________________________________________________")
g = 19
h = 9
if g < h:
print("G is less than H")
elif g == h:
print("G is equal to H")
elif g > h + 9:
print("G is greater than H by more than 9")
else:
print("G is greater than H")
print("________________________________________________________")
print(" B.M.I. CALCULATOR")
print(" -----------------")
name = "Sahil"
weight_kg = 50
height_m = 1.2
bmi = weight_kg / (height_m ** 2)
print("bmi: ")
print(bmi)
if bmi < 25:
print(name)
print("is not overweigth")
else:
print(name)
print("is overweight")
print("________________________________________________________")
power = 3**3
print(power)
| true |
52652edd95e7fbd2578c4bbde05d5547b86e45b4 | nik24g/Python | /write a file.py | 772 | 4.40625 | 4 | file = open("info.txt", "wt") # when we open a file in write mode it will overwrite the content
print(file.write("Hello ")) # write method is used to write a content in a file
file.close()
# note-- write mode and write method both are different
file = open("info.txt", "a") # if file open in a append mode it add content to the end of the file
print(file.tell())
a = file.write("Shayna") # write method returns no. of total characters that we have written
# print(file.read())
print(a)
file.close()
file = open("info.txt", "r+") # + mode is used to read and write
file.write("is anyone there?")
print(file.tell())
# file.seek(1)
# print(file.read())
print(file.readline())
print(file.tell())
print(file.readline())
file.seek(0)
print(file.readline())
file.close()
| true |
7876978a70dda449462d2af838a77e26f631cabd | David92p/Python-workbook | /function/Exercise89.py | 795 | 4.53125 | 5 | #Convert an Integer to Its Ordinal Number
number = int(input('Enter the number between 1 to 12 '))
def ordinal_number(int):
if int == 1:
print('1 ---> Firts')
elif int == 2:
print('2 ---> Second')
elif int == 3:
print('3 ---> Third')
elif int == 4:
print('4 ---> Fourth')
elif int == 5:
print('5 ---> Fourth')
elif int == 6:
print('6 ---> Sixth')
elif int == 7:
print('7 ---> Seventh')
elif int == 8:
print('8 ---> Eigth')
elif int == 9:
print('9 ---> Nineth')
elif int == 10:
print('10 ---> Tenth')
elif int == 11:
print('11 ---> Eleventh')
elif int == 12:
print('12 ---> Twelfth')
else:
print('Wrong number')
ordinal_number(number)
| false |
a5eba3faa434bda523cccc6bfe7b54493323b67a | David92p/Python-workbook | /repetition/Exercise67.py | 743 | 4.21875 | 4 | #Compute the Perimeter of a Polygon
from math import sqrt
p = 0
while True:
x1 = input('Enter the first point X (blank to quit) ')
if x1 != " ":
y1 = input('Enter the first point Y ')
x2 = input('Enter the second point X ')
y2 = input('Enter the second point Y ')
x1 = int(x1)
y1 = int(y1)
x2 = int(x2)
y2 = int(y2)
distance = sqrt((x2-x1 )**2+(y2-y1)**2)
distance = round(distance, 3)
p += round(distance,3)
print('Distance for these points are',distance)
print('*'*50)
print('total perimeter of the polygon is', p)
continue
else:
print('********************ByBy******************************')
break
| true |
7a8bba9915a602d9ef0b264ff271a022152af943 | David92p/Python-workbook | /lists/Exercise111.py | 201 | 4.125 | 4 | #Reverse Order
n = int(input("Enter an integer, 0 to exit "))
list = []
while n != 0:
list.append(n)
n = int(input("Enter an integer, 0 to exit "))
list.reverse()
for i in list:
print(i) | true |
22f585ad90401187a828c463f22d6596213be5b3 | David92p/Python-workbook | /function/Exercise87.py | 339 | 4.125 | 4 | #Shipping Calculator
def express_shipping(item):
shipping = 10.95
if item >1:
plus = 2.95*(item-1)
return shipping + plus
else:
return shipping
quantity = int(input('How many items did you buy? '))
total_price = round(express_shipping(quantity),2)
print('The total shipping price is $', total_price) | true |
748855c73991e8374c8a9d7466550aa7cf623d3b | Huijuan2015/leetcode_Python_2019 | /143. Reorder List.py | 2,488 | 4.1875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head:
return
# 取后半段,reverse,然后与前半段插入
slow , fast = head, head.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
middle = slow.next
slow.next = None
head1 = head
head2 = self.reverse(middle)
while head1 and head2:
tmp1, tmp2 = head1.next, head2.next
head1.next = head2
head2.next = tmp1
head1 = tmp1
head2 = tmp2
def reverse(self, head):
dummy = ListNode(0)
curr = head
while curr:
tmp = curr.next
curr.next = dummy.next
dummy.next = curr
curr = tmp
return dummy.next
///second time
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
# half the list
# reverse right half
# insert node2 in node 1
if not head or not head.next:
return head
slow = fast = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
rightHead = slow.next #右边多一个或者相等
slow.next = None
newHead = self.reverse(rightHead)
dummy = ListNode(0)
dummy.next = head
while head and newHead:
tmp1 = head.next
tmp2 = newHead.next
head.next = newHead
newHead.next = tmp1
head = tmp1
newHead = tmp2
return dummy.next
def reverse(self, head):
dummy = ListNode(0)
tail = dummy.next
while head:
tmp = head.next
dummy.next = head
head.next = tail
tail = head
head = tmp
return dummy.next
| true |
7c28963464fb4fef7e86ce476abee533311c7298 | ruslancybertek/group_z | /fibonacci.py | 393 | 4.21875 | 4 | target = int(input("Enter a number: "))
n1, n2 = 1, 1
count = 0
num_list = []
if target <= 0:
print("Please enter a positive integer")
elif target == 1:
print("Fibonacci sequence upto",target,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < target:
num_list.append(n1)
summ = n1 + n2
n1 = n2
n2 = summ
count += 1
print(num_list) | false |
919535fb51afd455532001e63c855ebbc9c7abac | ndpage/py4e-course2-python-data-structures | /Week6/graded_10-2.py | 1,229 | 4.25 | 4 | # 10.2 Write a program to read through the mbox-short.txt
# and figure out the distribution by hour of the day for each of the messages.
# You can pull the hour out from the 'From ' line by finding the time
# and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
hrlist = list()
for line in handle: # read each line
if not line.startswith('From '): # extract lines that start with From
continue
wlist = line.split() # split string into a list of strings
time = wlist[5] # store time string in variable 'time'
time = time.split(':') # split time into a list of strings
hrlist.append(time[0])
# determine occurance of each hour
count = dict() # create count dictionary
for hr in hrlist:
count[hr] = count.get(hr,0) + 1 # increment count for each hour in the dictionary
count = sorted(count.items()) # sort the items in the dictionary
[print(item[0],item[1]) for item in count] # print each hour and count in the sorted count dictionary | true |
54c975a8e622134b5ce0819ea6ef3a5ec1ee6b4e | karta059488/project01 | /day04/ftp_file_server_test/ftp-test/07_object_relative.py | 1,440 | 4.125 | 4 | # 面向对象的综合示例
# 有两个人:
# 1.
# 姓名: 张三
# 年龄: 35
# 2.
# 姓名: 李四
# 年龄: 8
# 行为:
# 1. 教别人学东西 teach
# 2. 赚钱
# 3. 借钱
# 事情:
# 张三 教 李四 学 python
# 李四 教 张三 学 跳皮筋
# 张三 上班赚了 1000元钱
# 李四向张三借了 200元
class Human:
'''人類'''
def __init__(self,n,a):
self.name =n
self.age = a
self.money = 0
def teach(self,other,skill):
print(self.name,'教',other.name,'學',skill)
def works(self,money):
self.money += money
print(self.name,'工作賺了',money,'元')
def borrow(self,other,money):
if other.money > money : #判對他有這多錢
print(other.name,'借給',self.name,money,'元錢')
other.money -= money
self.money += money
else:
print(other.name,'不借給',self.name) #它沒遮多錢可借
def show_info(self):
print(self.age,'歲的',self.name,'存有',self.money,'元')
zhang3 =Human('張三',35)
li4 = Human('李四',8)
zhang3.teach(li4,'python')
li4.teach(zhang3,'跳皮筋')
zhang3.works(1000)
li4.borrow(zhang3,200)
zhang3.show_info()
li4.show_info()
# 張三 教 李四 學 python
# 李四 教 張三 學 跳皮筋
# 張三 工作賺了 1000 元
# 張三 借給 李四 200 元錢
# 35 歲的 張三 存有 800 元
# 8 歲的 李四 存有 200 元
| false |
baa5f87ee2bff2992499b4c7667bdac26e7e8a0c | karta059488/project01 | /day04/ftp_file_server_test/ftp-test/class_student_count.py | 1,872 | 4.25 | 4 | # 練習
# 1. 用類來描述一個學生的資訊(可以修改之前的寫的Student類)
# class Student:
# # 此處自己實現
# 要求該類的物件用於存儲學生資訊:
# 姓名,年齡,成績
# 將這些物件存於清單中.可以任意添加和刪除學生資訊
# 1. 列印出學生的個數
# 2. 列印出所有學生的平均成績
# (建議用類變數存儲學生的個數,也可以把清單當作類變數)
class Student:
count = 0 # 此类变量用来记录学生的个数
def __init__(self, n, a, s=0):
self.name = n
self.age = a
self.score = s
Student.count += 1 # 让对象个数加1
def __del__(self):
Student.count -= 1 # 对象销毁时count减1
def get_score(self):
return self.score
@classmethod
def getTotalCount(cls):
'''此方法用来得到学生对象的个数'''
return cls.count
def test():
L = [] # 1班的学生
L.append(Student('小张', 20, 100))
L.append(Student('小王', 18, 97))
L.append(Student('小李', 19, 98))
print('此时学生对象的个数是:',Student.getTotalCount())
L2 = [] # 2班学生
L2.append(Student('小赵', 18, 55))
print(Student.getTotalCount()) # 4
# 删除L中的一个学生
L.pop(1) #刪掉小王
print("此时学生个数为:", Student.getTotalCount())
all_student = L + L2
scores = 0 # 用此变量来记录所有学生的成绩总和
for s in all_student:
# scores += s.score # 累加所有学生的成绩
scores += s.get_score() #用方法操作實力變量
print("平均成绩是:", scores/len(all_student))
if __name__ == '__main__':
test()
# 此时学生对象的个数是: 3
# 4
# 此时学生个数为: 3
# 平均成绩是: 84.33333333333333
| false |
111380ba18fb06d7ea17e6672023249be83e9ae9 | dlehdgus99/CS-30 | /P1/rps.py | 1,916 | 4.21875 | 4 | '''
Written By: Dong Hyun Lee
Description: This is a version of rock-paper-scissors where the computer cheats and always wins.
pChoice is the person's choice of a move: either 'rock', 'paper', or 'scissors'.
This will always return 'computer wins'.
Date : 10/10/2018
'''
def rpsCheat(pChoice):
return (print('computer wins'))
'''
Description: This is a version of rock-paper-scissors where the computer always chooses rock.
pChoice is the person's choice of a move: either 'rock', 'paper', or 'scissors'.
This will returns either 'person wins', 'computer wins', or 'tie game'.
'''
def rpsRock(pChoice):
if (pChoice == 'paper'):
return (print('person wins'))
elif (pChoice == 'scissors'):
return (print('computer wins'))
else:
return (print('tie game'))
'''
Description: This is an implementation of rock-paper-scissors for two players.
pChoice is the person's choice of a move: either 'rock', 'paper', or 'scissors'.
cChoice is the computer's choice of a move, with the same three possible values.
This will return either 'person wins', 'computer wins', or 'tie game'.
'''
def rps2(pChoice, cChoice):
if (pChoice == 'paper' and cChoice == 'rock'):
return (print('person wins'))
elif (pChoice =='rock' and cChoice == 'scissors' ):
return (print('person wins'))
elif (pChoice =='scissors' and cChoice == 'paper' ):
return (print('person wins'))
elif (pChoice == cChoice):
return (print('tie game'))
else:
return (print('computer wins'))
'''
Description: This is an implementation of rock-paper-scissors where the computer chooses its move randomly.
pChoice is the person's choice of a move: either 'rock', 'paper', or 'scissors'.
This will return either 'person wins', 'computer wins', or 'tie game'.
'''
from random import choice
def rpsRandom(pChoice):
return(rps2(pChoice, choice(['rock', 'paper', 'scissors'])))
| true |
ebf475d27ffcdc884b662dc2c536abe6011c1a38 | raserhin/project-euler | /Problem001.py | 634 | 4.34375 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000
"""
import time
pair_of_numbers = [3, 5]
N = 1000 # This is the number that we have to find its divisibles
def sum_of_numbers(i):
"""
Sum of all integers from 1 to N:
Equivalent to ``sum(num for num in range(i+1))``
"""
return i*(i+1)//2
start_time = time.time()
result = sum_of_numbers((N-1) // 3) * 3 + 5 * \
sum_of_numbers((N-1) // 5) - 15 * sum_of_numbers((N-1)//15)
final_time = time.time()
print(result)
| true |
5e9d015793b50a730e387b1b09bc9598bf79fbe5 | yanhualei/about_python | /python_learning/python_base/装饰器的学习与理解/006带有参数的装饰器.py | 1,092 | 4.28125 | 4 | """"""
"""带有参数的装饰器:
为什么要创建带参数的装饰器?
===>因为装饰器添加的功能需要接收外部传参数
怎么创建带参数的装饰器?
===>在普通的装饰器外部再添加一层函数,用于传递参数
带参数的装饰器有什么用处?
===>为添加的功能传递参数
"""
def num_func(num):
def set_func(func):
def call_func(*args,**kwargs):
if num ==1:
print("这是权限验证1")
if num == 2:
print("这是权限验证2")
return func(*args,**kwargs)
return call_func
return set_func
@num_func(2) # test = set_func(test)
def test1():
print("这是原函数...")
@num_func(1) # test = set_func(test)
def test2():
print("这是原函数...")
test1()
test2()
"""这段带参数的装饰器在没有改变原函数的情况下,
把权限验证加载到了原函数上,也就是说,如果装饰器
添加的功能需要参数,那么就在普通装饰器上再加一层函数,
用来传递参数就行了"""
| false |
64d5fc382927f3c400f230451b3ba37b37811865 | szazyczny/MIS3640 | /Session08/quiz1.py | 2,356 | 4.15625 | 4 | #Sarah Zazyczny Quiz 1 9/15/18
"""
Question 1:
If the number, n, is divisible by 4, return True;
return False otherwise. Return False if n is divisible by 100
(for example, 1900); the only exception is when n is divisible
by 400(for example, 2000), return True.
"""
def is_special(n):
"""
If the number, n, is divisible by 4
(for example, 2020), return True.
Return False if n is divisible by 100 (for example, 300);
the only exception is when n is divisible by
400(for example, 2400), return True.
"""
n = n/4
if n == 0:
return True
else:
n = n / 100
if n == 0:
return False
n = n / 4
elif n == 0:
return True
else:
return False
# When you've completed your function, uncomment the
# following lines and run this file to test!
# print(is_special(2020))
# print(is_special(300))
# print(is_special(2018))
# print(is_special(2000))
"""
-----------------------------------------------------------------------
Question 2:
"""
# def detect(a, b, n):
# """
# Returns True if either a or b is n,
# or if the sum or difference or product of a and b is n.
# """
# if a == n or b == n:
# return True
# else:
# if a + b == n:
# return True
# elif abs(a - b) == n:
# return True
# elif a * b == n:
# return True
# else:
# return False
# When you've completed your function, uncomment the
# following lines and run this file to test!
# print(detect(2018, 9, 2018))
# print(detect(2017, 1, 2018))
# print(detect(1009, 2, 2018))
# print(detect(2020, 2, 2018))
# print(detect(2017, 3, 2018))
"""
-----------------------------------------------------------------------
Question 3:
Write a function with loops that computes the sum of all cubes
of all the odd numbers between 1(inclusive) and
n (inclusive if n is not even).
"""
def sum_cubes_of_odd_numbers(n):
result = 0
for n in range(1, n, 2):
if n % 2 == 1:
result = result + n**3
print('the sum of all cubes of odd numbers is:', result)
# When you've completed your function, uncomment the
# following lines and run this file to test!
# print(sum_cubes_of_odd_numbers(1))
# print(sum_cubes_of_odd_numbers(10)) | true |
48013e20619c10fbc1dc2005e9db1cdcf83ebb6d | szazyczny/MIS3640 | /Session15OOP/OOP/OOP3/Exercise5.py | 1,205 | 4.4375 | 4 | # Exercise 5 (group work)
# Write a definition for a class of anything you want. You have to use the following methods:
# __init__ method that initializes some attributes. One of the attributes has to be an empty list.
# __str__ method that returns a string that reasonably represent the thing.
# A special method that overloads the one type of operators.
# Some other methods that reasonably represent the thing's actions, inclduing one method that takes an object of any type and adds it to the attribute of type list.
# Test your code by creating two objects and using all the methods.
# https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables
class Exercise:
"""
Represents the list of exercises.
attributes: muscle, exercise
"""
def __init__(self, muscle):
self.muscle = muscle
self.exercises = [] # creates a new empty list for each dog
def add_exercise(self, exercise):
self.exercises.append(exercise)
core = Exercise('Core')
upper = Exercise('Upper')
lower = Exercise('Lower')
core.add_exercise('Crunch')
upper.add_exercise('Push Up')
lower.add_exercise('Squat')
# core.exercise
# upper.exercise
# lower.exercise | true |
3cfdf85b46495b32d671b8443a9c3f3e56c69f78 | archerImagine/myNewJunk | /HeadFirstPython/Chapter_01/src/Page19.py | 1,039 | 4.28125 | 4 | movies = [
"The Holy Grail", 1975, "Terry Jones & Terry Gillman", 91,
[
"Graham Chapman",
[
"Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"
]
]
]
print(movies)
print(len(movies))
print("===============================================================================================")
for each_item in movies:
print(each_item)
print("===============================================================================================")
for each_item in movies:
if isinstance(each_item,list):
for item in each_item:
print(item)
else:
print(each_item)
print("===============================================================================================")
for each_item in movies:
if isinstance(each_item,list):
for nested_item in each_item:
if isinstance(nested_item,list):
for deeper_item in nested_item:
print(deeper_item)
else:
print(nested_item)
else:
print(each_item)
| false |
9cf62006554b0ec5ea34a7773ed659973ceb0b9e | archerImagine/myNewJunk | /my2015Code/myGithubCode/6.00SC/Misc/src/montyHall.py | 1,091 | 4.1875 | 4 | """ This program provides a simulation for a monty hall
problem of n doors, showing the expected value as well as
the experimental. This program assumes always switching. """
import random
won = 0
lost = 0
num = int(input("Number of Doors? "))
n = int(input("How many iterations? \n"))
def setup(): #creates random set of num doors
car = random.randint(0, num - 1)
doors = ["goat"] * num
doors[car] = "car"
return doors
for n in range(n):
doors = setup()
chosen = random.randint(0, num - 1) #chooses random door
if doors[chosen] == "car": #if chosen is car then always lose (since always switching)
lost += 1
else:
switch = random.randint(0, num - 3) #else there is 1/n-2 chance of selecting car (winning)
if switch == 0:
won += 1
else:
lost += 1
print("Switch \n")
print("Trials: " + str(won + lost))
print("Percentage Won: " + str(won/(won + lost) * 100))
print("Expected Win Percentage: " + str((num - 1)/(num * (num - 2)) * 100))
print("Percentage Lost: " + str(lost/(won + lost) * 100))
| true |
9b9c7418eec5c8875b671f8c7af71847b79ee1ba | archerImagine/myNewJunk | /my2015Code/myGithubCode/PythonLearning/AByteOfPython/Chapter_12/src/example04.py | 1,140 | 4.125 | 4 | class Robot(object):
"""Represent a Robot with a string"""
# A class variable, counting the number of robots.
population = 0
def __init__(self, name):
"""Initalize the data"""
self.name = name
print "(Initalizing {})".format(self.name)
# When this person is created, the robot
# adds to the population
Robot.population += 1
def die(self):
"""I am dying"""
print "{} is being destroyed ".format(self.name)
Robot.population -= 1
if Robot.population == 0:
print "{} was the last one ".format(self.name)
else:
print "There are still {:d} robots working".format(Robot.population)
def say_hi(self):
"""Greetings by the robot
Yeah, they can do that
"""
print "Greetings, my master call me {}".format(self.name)
@classmethod
def how_many(cls):
"""prints the current population"""
print "We have {:d} robots".format(cls.population)
droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()
droid2 = Robot("C-3P0")
droid2.say_hi()
Robot.how_many()
print "\nRobots can do come work here.\n"
print "\nRobots have done their work, so let's destroy them"
droid1.die()
droid2.die()
Robot.how_many() | true |
29d7635ec3bdaffb7897ee402fd9b2a2f75e8b7e | archerImagine/myNewJunk | /my2015Code/myGithubCode/PythonLearning/AByteOfPython/Chapter_13/src/example01.py | 239 | 4.40625 | 4 | def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = raw_input("Enter a Text: ")
if is_palindrome(something):
print "Yes, its is a palindrome"
else:
print "No, It is not a palindrome" | true |
e37991880160d0543d2b43b84706239e64cf1cbc | Fr4nc3/code-hints | /leetcode/mergeLexicography.py | 2,711 | 4.5 | 4 | # You are implementing your own programming language and you've decided to add support for merging strings. A typical merge function would take two strings s1 and s2, and return the lexicographically smallest result that can be obtained by placing the symbols of s2 between the symbols of s1 in such a way that maintains the relative order of the characters in each string.
# For example, if s1 = "super" and s2 = "tower", the result should be merge(s1, s2) = "stouperwer".
# You'd like to make your language more unique, so for your merge function, instead of comparing the characters in the usual lexicographical order, you'll compare them based on how many times they occur in their respective initial strings (fewer occurrences means the character is considered smaller). If the number of occurrences are equal, then the characters should be compared in the usual lexicographical way. If both number of occurences and characters are equal, you should take the characters from the first string to the result. Note that occurrences in the initial strings are compared - they do not change over the merge process.
# Given two strings s1 and s2, return the result of the special merge function you are implementing.
# Example
# For s1 = "dce" and s2 = "cccbd", the output should be
# solution(s1, s2) = "dcecccbd".
# All symbols from s1 goes first, because all of them have only 1 occurrence in s1 and c has 3 occurrences in s2.
# For s1 = "super" and s2 = "tower", the output should be
# solution(s1, s2) = "stouperwer".
# Because in both strings all symbols occur only 1 time, strings are merged as usual. You can find explanation for this example on the image in the description.
def solution(s1, s2):
# record appear times
record1 = {}
record2 = {}
for ch in s1:
record1[ch] = record1.get(ch,0)+1
for ch in s2:
record2[ch] = record2.get(ch,0)+1
# merge with two pointers
pt1 = 0
pt2 = 0
len1 = len(s1)
len2 = len(s2)
res = []
while pt1 < len1 and pt2 < len2:
if record1[s1[pt1]] < record2[s2[pt2]]:
res.append(s1[pt1])
pt1 += 1
elif record1[s1[pt1]] > record2[s2[pt2]]:
res.append(s2[pt2])
pt2 += 1
else:
# if equal times
if s1[pt1] <= s2[pt2]:
res.append(s1[pt1])
pt1 += 1
elif s1[pt1] > s2[pt2]:
res.append(s2[pt2])
pt2 += 1
# continue with the remaining characters
while pt1 < len1:
res.append(s1[pt1])
pt1 += 1
while pt2 < len2:
res.append(s2[pt2])
pt2 += 1
return "".join(res) | true |
aa2baff7bc5b202e93430b7ea531cdd6080c39f1 | Fr4nc3/code-hints | /leetcode/stringNumberConv.py | 1,357 | 4.125 | 4 | # You are given a string s. Your task is to count the number of ways of splitting s into three non-empty
# parts a, b and c (s = a + b + c) in such a way that a + b, b + c and c + a are all different strings.
# NOTE: + refers to string concatenation.
# For s = "xzxzx", the output should be solution(s) = 5.
# Consider all the ways to split s into three non-empty parts:
# If a = "x", b = "z" and c = "xzx", then all a + b = "xz", b + c = "zxzx" and c + a = xzxx are different.
# If a = "x", b = "zx" and c = "zx", then all a + b = "xzx", b + c = "zxzx" and c + a = zxx are different.
# If a = "x", b = "zxz" and c = "x", then all a + b = "xzxz", b + c = "zxzx" and c + a = xx are different.
# If a = "xz", b = "x" and c = "zx", then a + b = b + c = "xzx". Hence, this split is not counted.
# If a = "xz", b = "xz" and c = "x", then all a + b = "xzxz", b + c = "xzx" and c + a = xxz are different.
# If a = "xzx", b = "z" and c = "x", then all a + b = "xzxz", b + c = "zx" and c + a = xxzx are different.
# Since there are five valid ways to split s, the answer is 5.
def solution(s):
n = len(s)
asw = 0
for i in range(n-1):
for j in range(i+1, n-1):
ab = s[0:j]
bc = s[i:]
ca = s[j:] + s[0:i]
if not (ab == bc or bc == ca or ca == ab):
asw +=1
return asw
| true |
2c9accae7df94f192c10ee7cd68d0a3d231f6ccc | franciscoG98/ws-python | /condicionales.py | 1,095 | 4.15625 | 4 | # OPERADORES ARITMETICOS
# +, -, *, /
# ** POTENCIA
# // raiz
# Operador incemento
edad = 22
edad = edad + 1
# es lo mismo que decir
edad += 1
# OPERADORES CONDICIONALES
# print('10 es MAYOR que 4')
# print( 10 > 4 )
# print('10 es MENOR que 3')
# print( 10 < 3 )
# print('2 es MENOR O IGUAL que 6')
# print( 2 <= 6 )
# print('20 es MAYOR O IGUAL que 6')
# print( 20 >= 6 )
# print('5 es IGUAL que 5')
# print( 5 == 5 )
# print('25 es DISTINTO que 5')
# print( 25 != 5 )
# OPERADORES LOGICOS (and - or - not)
# print(True and True) # True
# print(True and False) # False
# print(True or True) #True
# print(True or False) #True
# print(False or True) #True
# print(False or False) #False
# print(not True) # False
# print(not False) # True
# CONDICIONALES ESTRUCTURA IF/ELSE
print('Iniciando el sistema para que ingreses...')
passwd = 'python'
passwdEntered = input('Ingresa tu contraseña:\n')
if passwdEntered == passwd:
print('La contraseña es correcta, podes entrar capo')
else:
print('Quien te conoce papa, tomatela que sos poio')
| false |
b56cdc80cba76eb9ae47589464ade47a6de469f8 | KR1410/Pyhton-Projects | /guess_game.py | 387 | 4.15625 | 4 | import random
random_num = random.randint(1,100)
#print(random_num)
chances = 0
while(True):
guess = int(input("Enter your number: "))
chances += 1
if(guess == random_num):
print(f"you guessed the correct number in {chances} chances")
break
elif(guess < random_num):
print("your guess is smaller")
else:
print("your guess is greater")
| true |
0ab0673b2c67f6263abf2773b63dd890a1f1fcb2 | silkaitis/project_euler | /Problem01.py | 541 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 29 09:11:13 2016
@author: Danius.silkaitis
"""
#Problem 1
#If we list all the natural numbers below 10 that are multiples of 3 or 5,
#we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
#Find the sum of all the multiples of 3 or 5 below 1000.
def multiples(m1,m2,ub):
sum = 0
for x in range(0,ub):
if x % m1 == 0:
sum = sum + x
elif x % m2 == 0:
sum = sum + x
return(sum)
m1 = 3
m2 = 5
ub = 1000
sum = multiples(m1,m2,ub)
print sum | true |
3e0ef1485ffad7b68cc733f64f90f37f05cbb948 | btatkerson/CIS110 | /Excercises/Ch2/ch2ex10.py | 266 | 4.125 | 4 | def main():
print("This Program converts kilometers to miles.")
print()
kilo=eval(input("Enter the distance in kilometers: "))
miles = kilo *0.62
print("This distance in miles is: ",miles)
input("Press the <Enter> key to quit.")
main()
| true |
4595ab0f1b07e7cb244b8651c436b9195a590495 | DrSJBauman/SEMO-Python-Coursework | /futval.py | 432 | 4.125 | 4 | #futval.py
# A program to compute the value of an investment
# carried 10 years into the future
def futval():
print("This program calculates the future value")
print("of a 10-year investment")
principal= input("Enter the initial principal: ")
apr= input("Enter the annual interest rate: ")
for i in range(10):
principal=principal*(1+apr)
print("The value in 10 years is:",principal)
| true |
18f1dd2697b2941fc253d7b92fc854e8d344a4d2 | Soumodip13/TCS-NQT-2020-Practice-Problems | /LeapYear.py | 359 | 4.21875 | 4 | year = int(input())
# Displays a year is Leap year or not
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print "{0} is a leap year".format(year)
else:
print "{0} is not a leap year".format(year)
else:
print "{0} is a leap year".format(year)
else:
print "{0} is not a leap year".format(year) | false |
63bc81a34ba481cc09a56e190a7ef935a22d1707 | takumiw/AtCoder | /ABC149/C.py | 567 | 4.125 | 4 | import math
def is_prime(x):
if x < 2: return False # 2未満に素数はない
if x == 2 or x == 3 or x == 5: return True # 2,3,5は素数
if x % 2 == 0 or x % 3 == 0 or x % 5 == 0: return False # 2,3,5の倍数は合成数
prime = 7
step = 4
while prime <= math.sqrt(x):
if x % prime == 0: return False
prime += step
step = 6 - step
return True
def main():
X = int(input())
while 1:
if is_prime(X):
print(X)
break
X += 1
if __name__ == '__main__':
main() | false |
8f3017f8acf08452e016860866e589225e807c2a | TayeeChang/algorithm | /前缀树/trie.py | 1,319 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2021/4/29 14:38
# @Author : haojie zhang
import collections
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
node = self.root
for char in word:
node = node.setdefault(char,{})
node["end"] = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return "end" in node
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for char in prefix:
if char not in node:
return False
node = node[char]
return True
word1 = 'apple'
word2 = 'google'
prefix = 'app'
obj = Trie()
obj.insert(word1)
obj.insert(word2)
param_2 = obj.search(word1)
param_3 = obj.startsWith(prefix)
| true |
b5c833193fb30c837e594431dc4e91da6dde8bfd | Harshit-Raj-2000/Algorithms-and-Data-Structures | /coding interview practice/arrays/wave array.py | 628 | 4.1875 | 4 | #User function Template for python3
class Solution:
#Complete this function
#Function to sort the array into a wave-like array.
def convertToWave(self,arr,N):
for i in range(0,N-1,2):
arr[i],arr[i+1] = arr[i+1],arr[i]
return
#{
# Driver Code Starts
#Initial Template for Python 3
import math
def main():
T=int(input())
while(T>0):
N=int(input())
A=[int(x) for x in input().split()]
ob=Solution()
ob.convertToWave(A,N)
for i in A:
print(i,end=" ")
print()
T-=1
if __name__=="__main__":
main()
| true |
eec85d5b1926292953bee25e008d5cf2d14361fa | andyleva/kurs-python | /lesson05-hw02.py | 509 | 4.125 | 4 | """2. Создать текстовый файл (не программно), сохранить в нём несколько строк, выполнить
подсчёт строк и слов в каждой строке."""
my_file = open("lesson05-hw02.txt", "r", encoding='utf-8')
i = 1
for line in my_file:
my_list = [line.split()]
print(f"Строка {i} состоит из {len(my_list)} слов")
i += 1
print(f"Всего в файле {i} строк.")
my_file.close()
| false |
40d0b0700cbbf542125e385c5497316a2b3a4b88 | andyleva/kurs-python | /lesson03-hw06.py | 1,207 | 4.15625 | 4 | """Реализовать функцию int_func() , принимающую слова из маленьких латинских букв и
возвращающую их же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
"""
# уставовка прописной первой буквы
def int_func(text_input):
str_text_input = str(text_input)
txt_title = str_text_input.title()
return txt_title
# проверка на маленькие латинские буквы
def ascii_test(txt_test):
flag_ascii = True
for item in txt_test:
if ord(item) > 122 or ord(item) < 97 or item.isupper():
flag_ascii = False
break
return flag_ascii
txt = input("Введите маленькие латынские буквы в виде одного слова:")
"""проверка на маленькие латинские буквы"""
result_ascii_test = ascii_test(txt)
if result_ascii_test != False:
print(int_func(txt))
else:
print("Вы не выполнили условие ввода слова! Программа завершена.")
| false |
029be1bbecef7f244c59a595f044d088f266d348 | andyleva/kurs-python | /lesson06-wh05.py | 1,651 | 4.125 | 4 | """Реализовать класс Stationery (канцелярская принадлежность).
определить в нём атрибут title (название) и метод draw (отрисовка). Метод выводит сообщение «Запуск отрисовки»;
создать три дочерних класса Pen (ручка), Pencil (карандаш), Handle (маркер);
в каждом классе реализовать переопределение метода draw. Для каждого класса метод должен выводить
уникальное сообщение;
создать экземпляры классов и проверить, что выведет описанный метод для каждого экземпляра.
"""
"""на переопределение"""
class Stationery:
def __init__(self, title):
self.title = title
def draw(self):
print(f"Запуск отрисовки: {self.title}")
class Pen(Stationery):
def draw(self):
print(f"Запуск отрисовки: {self.title}")
class Pencil(Stationery):
def draw(self):
print(f"Запуск отрисовки: {self.title}")
class Handle(Stationery):
def draw(self):
print(f"Запуск отрисовки: {self.title}")
my_stationery=Stationery("канцелярская принадлежность")
my_stationery.draw()
my_pen=Pen("ручка")
my_pen.draw()
my_pencil=Pencil("карандаш")
my_pencil.draw()
my_handle=Handle("маркер")
my_handle.draw() | false |
a8bf9f9cd7321a0b319efdd6830941287888fc8c | mangalagb/Leetcode | /Medium/BuildingsWithAnOceanView.py | 1,532 | 4.34375 | 4 | #There are n buildings in a line. You are given an integer array heights of size n that represents the
# heights of the buildings in the line.
# The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean
# without obstructions. Formally, a building has an ocean view if all the buildings to its right have a smaller height.
#
# Return a list of indices (0-indexed) of buildings that have an ocean view, sorted in increasing order.
class Solution(object):
def findBuildings(self, heights):
"""
:type heights: List[int]
:rtype: List[int]
"""
number_of_buildings = len(heights)
if number_of_buildings == 0:
return []
elif number_of_buildings == 1:
return [0]
max_seen_so_far = None
result = []
for i in range(number_of_buildings-1, -1, -1):
current_building = heights[i]
if max_seen_so_far is None:
result.insert(0, i)
max_seen_so_far = current_building
else:
if current_building > max_seen_so_far:
result.insert(0, i)
max_seen_so_far = current_building
return result
my_sol = Solution()
heights = [4, 2, 3, 1]
print(my_sol.findBuildings(heights)) #[0,2,3]
heights = [4,3,2,1]
print(my_sol.findBuildings(heights)) #[0,1,2,3]
heights = [1,3,2,4]
print(my_sol.findBuildings(heights)) #[3]
| true |
c2b83ee100b31f77d52a8986aad0c809b00c854f | mangalagb/Leetcode | /Medium/GraphValidTree.py | 2,502 | 4.15625 | 4 | # Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes),
# write a function to check whether these edges make up a valid tree.
#According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices
# are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
#https://leetcode.com/problems/graph-valid-tree/discuss/69046/Python-solution-with-detailed-explanation
#SOLUTION
# When we iterate through the neighbours of a node, we ignore
# the "parent" node as otherwise it'll be detected as a trivial cycle
# A -> B -> A(ignore B's parent A in B's neighbours)
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
graph = self.build_adjacency_list(n, edges)
root = 0
parent_dict = {0: -1}
adj_list = self.build_adjacency_list(n, edges)
visited = [False] * n
#Check cycle
has_cycle = self.has_cycle(0, -1, adj_list, visited)
if has_cycle:
return False
#Check if all nodes were visited
all_nodes_visited = True
for value in visited:
if not value:
all_nodes_visited = False
break
return all_nodes_visited
def has_cycle(self, current, parent, adj_list, visited):
visited[current] = True
neighbours = adj_list[current]
for neighbour in neighbours:
if not visited[neighbour]:
result = self.has_cycle(neighbour, current, adj_list, visited)
if result:
return True
else:
if visited[neighbour] and parent != current:
return True
return False
def build_adjacency_list(self, n, edges):
adj = {}
for i in range(0, n):
adj[i] = []
for edge in edges:
i = edge[0]
j = edge[1]
adj[i].append(j)
adj[j].append(i)
return adj
my_sol = Solution()
n = 5
edges = [[0,1], [0,2], [0,3], [1,4]]
print(my_sol.validTree(n, edges)) #True
#
# n = 5
# edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
# print(my_sol.validTree(n, edges)) #False
#
# n = 2
# edges = [[1,0]]
# print(my_sol.validTree(n, edges)) #True
#
# n = 3
# edges = [[1,0],[2,0]]
# print(my_sol.validTree(n, edges)) #True
| true |
6d4d678865a0e1c7862a33bd9698deaa08f7e4f0 | mangalagb/Leetcode | /Medium/ValidateBinarySearchTree.py | 1,520 | 4.3125 | 4 | # Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type numbers: node values
:rtype: bool
"""
stack = []
current = root
prev = None
while True:
if current is not None:
stack.append(current)
current = current.left
elif stack:
current = stack.pop()
# print(current.val, end=" ")
# check valid BST
if prev and prev.val >= current.val:
return False
else:
prev = current
current = current.right
else:
break
return True
def make_tree(self):
root = TreeNode(2)
node1 = TreeNode(1)
node2 = TreeNode(3)
root.left = node1
root.right = node2
return root
my_sol = Solution()
root = my_sol.make_tree()
print(my_sol.isValidBST(root))
| true |
4eeaa6cb753a1ffc1374f29d8b21bea9cdd111c7 | mangalagb/Leetcode | /Easy/Merge2SortedLists.py | 1,183 | 4.25 | 4 | # Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = current = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 or l2
return head.next
def print_result(self, result: ListNode):
while result is not None:
print(result.val, end=" ")
result = result.next
print("\n_____________________________________________\n")
my_sol = Solution()
list_node1 = ListNode(1)
list_node2 = ListNode(2)
list_node3 = ListNode(4)
list_node1.next = list_node2
list_node2.next = list_node3
l1 = ListNode(1)
l2 = ListNode(3)
l3 = ListNode(4)
l1.next = l2
l2.next = l3
my_sol.mergeTwoLists(list_node1, l1)
| true |
777fe0bf787608dc89a7da7000eec2ada7f3411f | jelena-vk-itt/jvk-tudt-notes | /swd1-pt/res/files/python/lab_solutions/a3e2.py | 226 | 4.125 | 4 | i = int(input("Please enter a whole number: "))
j = int(input("Please enter another whole number: "))
if i % j:
print("{0} is not a factor of {1}".format(j, i))
else:
print("{0} is a factor of {1}".format(j, i))
| true |
c5807c7fa56a6b953c643f8c93a83165b0721587 | jelena-vk-itt/jvk-tudt-notes | /swd1-pt/res/files/python/conditionals/cond_elif.py | 211 | 4.3125 | 4 | x = 2
if x > 10:
print("x is greater than 10")
elif x > 3:
print("x is greater than 3 but not greater than 10")
elif x > 0:
print("x is 1, 2 or 3")
else:
print("x is not a positive number") | true |
7882e7fbf318717913509cc5664db2880a67e9c6 | Ajiteshrock/OOps_with_Python | /Python Oops/Inner_c;lass.py | 591 | 4.21875 | 4 | class outer:
def __init__(self):
self.name = "Ajites Mishra"
self.ine = self.inner()
def Aj(self):
print("This is outer class and your name is ",self.name)
class inner:
def __init__(self):
self.car="Mercedes Benz"
def Mish(self):
print("This is inner class and your car is", self.car)
o = outer()
o.Aj()
a=outer.inner() ##creating object of inner class
b = o.ine #sencond method to create object of inner class
print("calling inner class' method")
print(b.car,b.Mish())
| false |
f2fe054fe0c999b0dd0fea65361e2e5e5c98262d | Tanner-Mindrum/some-school-python-projects | /Discrete Structures with Computing Applications II (CECS 229)/Number Theory & Cryptography/Programming Assignment 2.py | 1,490 | 4.1875 | 4 | import math
# Question 1
# Write afunction that will take in three inputs: base, exponent, and divisor. The output would be the values of the
# modulus operations such that when multiplied and then taken the modulus of the divisor, you will get the problem’s
# remainder. The output should bea list data type.
def modulus(base, exponent, divisor):
binary_nums = []
exponentiation_nums = []
result_nums = []
while exponent > 0:
binary_nums.append(exponent % 2)
exponent = exponent // 2
for i in range(len(binary_nums)):
exponentiation_nums.append(base ** (2**i) % divisor)
for i in range(len(binary_nums)):
if binary_nums[i] == 1:
result_nums.append(exponentiation_nums[i])
print(result_nums)
# Question 2
# Write a function that will take in a list of integers and then output whether the list is pairwise relatively prime.
# If the list is pairwise relatively prime, then the function will output “Pairwise Relatively Prime”.
# Otherwise, it will output “Not Pairwise Relatively Prime”.
def relativelyPrime(aList):
ifPrime = []
result = "Pairwise Relatively Prime"
for i in range(len(aList) - 1):
for j in range(i + 1, len(aList)):
ifPrime.append(math.gcd(aList[i], aList[j]))
for i in range(len(ifPrime)):
if ifPrime[i] != 1:
result = "Not Pairwise Relatively Prime"
print(result)
| true |
cd8dae450096b80db240869500b50f87ab51133e | CharlesQQ/Python_Data_Analyse | /方法和装饰器/方法的运行机制.py | 1,249 | 4.15625 | 4 | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
__author__ = 'Charles Chang'
"""
class Pizza(object):
def __init__(self,size):
self.size = size
def get_size(self):
return self.size
#print (Pizza.get_size)
print (Pizza.get_size.__self__)
"""
class Pizza(object):
def __init__(self,cheese,vegetables):
self.cheese = cheese
self.vegetables= vegetables
@staticmethod
def min_ingredient(x,y):
return x+y
def cook(self):
return self.min_ingredient(self.cheese,self.vegetables)
# print Pizza('t1','t2').cook() is Pizza('t1','t2').cook()
# print Pizza('t1','t2').min_ingredient is Pizza.min_ingredient
# print Pizza('t1','t2').min_ingredient is Pizza('t1','t2').min_ingredient
class Sub_Pizza(Pizza):
pass
class Pizza_1(object):
radius = 12
@classmethod
def get_radius(cls):
print cls
return cls.radius
# print Pizza_1.get_radius
# print Pizza_1().get_radius
print (Pizza_1.get_radius is Pizza_1().get_radius)
print Pizza_1.get_radius()
class MyPizza(object):
def __init__(self,ingredients):
self.ingredients = ingredients
@classmethod
def from_fridge(cls,fridge):
return cls(fridge.get_cheese()+fridge.get_vegetables())
| false |
8be16767e05a1beade190790ae2581f6d2a7279b | m-ali-ubit/PythonProgramming | /zip.py | 612 | 4.59375 | 5 |
# According to Python documentation:
# zip(*iterables) returns an iterator of tuples, where the i-th tuple contains the i-th element
# from each of the argument sequences or iterables.
obtainedMarks = [22, 26, 21, 15, 19]
maxMarks = [25, 30, 25, 20, 25]
print(list(zip(obtainedMarks, maxMarks))) # like map, zip also return iterator and need to cast in list
# example from book 'Learning Python'
a = [5, 9, 2, 4, 7]
b = [3, 7, 1, 9, 2]
c = [6, 8, 0, 5, 3]
maxs = map(lambda n: max(*n), zip(a, b, c)) # list the max values of three sequences
print(list(maxs)) # [6, 9, 2, 9, 7]
| true |
1d1ea098b8d0c4f30e46f288a14d8566b238d081 | m-ali-ubit/PythonProgramming | /DataStructures/SortingAlgorithms/shellSort.py | 844 | 4.125 | 4 |
# shell sort starts by sorting pairs of elements far apart from each other
# then progressively reducing the gap between elements to be compared
# time complexity ; worst case O(size^2), best case O(nLogn)
def shell_sort(lst): # start with a big gap then reduce the gap
size = len(lst)
gap = int(size/2)
while gap > 0: # keep adding elements until whole list is gap sorted
for i in range(gap, size): # iterate b/w gaps
temp = lst[i]
j = i
while j >= gap and lst[j - gap] > temp:
lst[j] = lst[j - gap]
j -= gap
lst[j] = temp
gap = int(gap/2)
lst = [11, 77, 44, 3, 21, 99, 1, 38]
shell_sort(lst)
print('sorted list')
for i in lst:
print(i, end=' ')
| true |
b6bf3475f64b476892066461d7a600ec632a4db7 | m-ali-ubit/PythonProgramming | /identityOperator.py | 627 | 4.1875 | 4 |
# identity operators compare the memory locations of two objects and returns TRUE or False
x = 10
y = 10
z = 20
print(id(x)) # print the memory location of x
print(id(y)) # print the memory location of y
print(id(z)) # print the memory location of z
print(x is y) # true because x and y have same memory location as both are 10
print(x is not y) # false
print(x is z) # false because x and z have different memory location as x is 10 and z is 20
print(x is not z) # true
print(y is z) # false because y and z have different memory location as y is 10 and z is 20
print(y is not z) # true
| true |
ba51c71673a2cfe3ac27ae35370b3b5dd873e3fb | shermanash/dsp | /python/q8_parsing.py | 1,209 | 4.34375 | 4 | # -*- coding: utf-8 -*-
#The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# The below skeleton is optional. You can use it or you can write the script with an approach of your choice.
import csv
import pandas as pd
import numpy as np
def worst_goal_diff(csvpath):
# read csv to pandas dataframe
df = pd.read_csv(csvpath)
# add column to frame "goal differential"
df['goal_diff'] = df['Goals'] - df['Goals Allowed']
# sort by goal diff (doesnt return both teams in event of tie yet**)
df.sort_values(by = ['goal_diff'], ascending=True)
# get last row in the sorted frame (maybe not the best way)
worst_team_differential = df.tail(1)
return(worst_team_differential['Team'])
# csvpath = '~/ds/metis/prework/dsp/python/football.csv'
# print worst_goal_diff(csvpath)
| true |
33098574cb11ed8198389a18f6bd1cc211013fda | zulsb/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 254 | 4.15625 | 4 | #!/usr/bin/python3
def uppercase(str):
for count in str:
character = ord(count)
if (character >= ord("a") and character <= ord("z")):
character = character - 32
print("{:c}".format(character), end="")
print()
| true |
d67627dd68e45c4c5a0c66e2736ad359d9274cdd | Duenwege2312/CTI110 | /P3T1_AreasOfRectangles_EthanDuenweg.py | 922 | 4.53125 | 5 | # Rectangle Area Calculator
# 2/25/20
# CTI-110 P3T1- Areas of Rectangles
# Ethan Duenweg
# First we need to get the rectangle dimensions from the user
print("Rectangle Area Calculator")
h1 = int(input("What's the height of the rectangle 1?"))
w1 = int(input("Whats the width of rectangle 1?"))
h2 = int(input("What's the height of rectangle 2?"))
w2 = int(input("Whats the width of rectangle 2?"))
# We then need to calculate which of these rectangles would have the largest area using multiplication
area1 = (h1 * w1)
area2 = (h2 * w2)
# Now we can use 'if' functions to determine the greater number, which will be the largest area.
# We will also display the outcome to the user
if area1 > area2:
print('Rectangle 1 has the greatest area')
else:
if area2 > area1:
print('Rectangle 2 has the greatest area')
else:
print('Both rectangles have the same area')
| true |
92a287b864f9a0f21c0ca718a55b1d7f7432416e | neem693/My_Study_Inc | /deep_learning/python_syntax/02_if.py | 633 | 4.1875 | 4 |
# if : 두 가지 중에서 한 가지 코드만 선택하는 문법
a = 110
if a%2 == 1:
print('odd')
else:
print('even')
if a%2:
print('odd')
else:
print('even')
if a:
print('odd')
else:
print('even')
print('-'*30)
# 문제
# 정수 a가 음수인지 양수인지 0인지 출력하는 코드를 만들어 보세요.
if a > 0:
print('양수')
else:
# print('음수, 제로')
if a < 0:
print('음수')
else:
print('제로')
if a > 0:
print('양수')
elif a < 0:
print('음수')
else:
print('제로')
print('finished.')
print('\n\n\n\n\n\n\n\n\n\n\n\n')
| false |
3d6da0c7838ae7e14ae0b41370deaf324cf4c7a4 | sarahdomanti/CP1404_Pracs | /Prac2/asciiTable.py | 288 | 4.21875 | 4 | lower = 10
upper = 100
print("Enter a number between {} and {} : ".format(str(lower), str(upper)))
for i in range(1, 10):
ASCII = int(input("> "))
if ASCII < lower or ASCII > upper:
print("Invalid number.")
else:
print("{:<5} {:>5}".format(ASCII, chr(ASCII)))
| true |
74a7346aadeb1dcc3ea320dff132e4241828d6a7 | arnnav/rts-labs | /q1.py | 1,218 | 4.25 | 4 | '''
Print the number of integers in an array that are above the given input and the number that are below.
default inpArr = [1,5,2,1,10], k = 6
RUNNING INSTRUCTIONS:
- python q1.py [--inpArr InputArray ] [--k valueOfGivenNumber]
EXAMPLE:
- python q1.py
- python q1.py --inpArr 1,5,2,1,10 --k 6
OUTPUT:
- Number of integers in an array that are above or below the given number.
'''
import argparse
def aboveBelow(inpArr,k):
# Assumption: ignore if equal.
above,below = 0,0
for i in inpArr:
if i>k:
above += 1
elif i<k:
below += 1
return "above: "+str(above)+", below: "+str(below)
if __name__ == "__main__":
py_parser = argparse.ArgumentParser(description='Above or Below a number', allow_abbrev=False)
py_parser.add_argument('--inpArr', action='store', type=str, help='Input Array')
py_parser.add_argument('--k', action='store', type=int, help='the value of given Number')
args = py_parser.parse_args()
inpArr = [1,5,2,1,10]
k = 6
if args.inpArr:
inpArr = [int(i) for i in args.inpArr.split(',')]
if args.k:
k = args.k
print(aboveBelow(inpArr,k))
| true |
3babe6335bcb4033e5a37e32fad3e552456ca09d | airosent/Rock-Paper-Scissor-Game | /rockpaperscissors.py | 1,019 | 4.15625 | 4 | #Ariel Rosenthal
# Rock, Paper, Scissor game in Python
import random
while True:
user_choice= input("Enter a choice (rock, paper, scissors): ")
possible_choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(possible_choices)
if user_choice == computer_choice:
print(f"Both players selected {user_choice}. It's a tie!")
elif user_choice == "rock":
if computer_choice == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif user_choice == "paper":
if computer_choice == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")
elif user_choice == "scissors":
if computer_choice == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")
play_again = input("Play again? (y/n): ")
if play_again.lower() != "y":
break
| true |
13bf71a52e5664e164ac4e0576cbadff4aacc9d8 | MahmoudFierro98/Embedded_Linux | /Algorithm_Python/Selection_Sort.py | 766 | 4.1875 | 4 | #################################
# Selection Sort #
# Author: Mahmoud Mohamed Kamal #
# Date : 26 NOV 2020 #
#################################
# Enter N Numbers
List_Length = int(input("Enter the Length of list: "))
Input_List = []
print("\n")
# Scan the Values
for i in range(List_Length):
print("Enter #",i,": ",end="")
New_Number = float(input())
Input_List.append(New_Number)
# Display List
print("\nYour List:",Input_List)
# Selection Sorting
for i in range(List_Length-1):
for j in range(i+1,List_Length):
if (Input_List[i] > Input_List[j]):
# Swap
Input_List[i],Input_List[j] = Input_List[j],Input_List[i]
# Display List after Sorting
print("\nYour List after \"Selection Sorting\":",Input_List) | false |
fefac0ef8c8ab61a4bfc12efd8869db121ab1ade | Krisfer1988/Curso-Python | /Comenzando/EstructurasControlFLujoIF.py | 1,833 | 4.25 | 4 | #Estructuras de control de flujo, if, else if, else.
#Ejemplo-1
""""Crear un programa que recoja dos numeros A y B, y nos saque por pantalla los siguientes casos:
si A>B debe imprimir A
si B>A debe de imprimir B
y si son iguales, debe imprimir 'son iguales' """
A = 10
B = 27
if( A > B):
print (A)
elif (A==B):
print("Son iguales")
else:
print(B)
#Ejemplo-2
#Crear un programa que nos muestre por pantalla:
#si el color del semaforo esta en verde, se pueda cruzar y si es otro color nos diga que esperemos.
semaforo = "verde"
if (semaforo == "verde") :
print ("Cruzar la calle")
else:
print ("Esperar")
#Ejemplo-3
"""Queremos hacer el mismo programa que el ejercicio 1 pero implementandolo con una funcion. Para ello debemos de definirlo con:
**************Estructura basica*****************
def NOMBRE_MI_FUNCION(variables/parametros de entrada si los hay) :
#Cuerpo de mi funcion
NOMBRE_MI_FUNCION(valores de inicio para que se ejecute)"""
#En base a esta estructura basica, resuelve el mismo ejercicio: decir de dos nuemeros A y B si uno es mayor que el otro o si son iguales.
#Implementar al final de codigo, una modificacion de la misma funcion para que te resuelva el mayor de 3 numeros.
def maximo(a,b):
if (a > b):
return a
else:
return b
def maximoDe3(a,b,c):
return maximo(a,maximo(b,c))
print(maximo(10,11))
print(maximo(20,30))
print(maximoDe3(1,2,3))
#Implementar al final de codigo, una modificacion de la misma funcion para que te resuelva el mayor de 3 numeros, y el resultado lo x3.
mimaximo = maximoDe3(1,2,3)
print(mimaximo*3)
#Ejemplo-4
#Escribir un programa sencillo con if else que nos diga si un numero es par o impar.
numero = int(input("Escriba un número: "))
if (numero % 2):
print("es impar")
else:
print("es par")
| false |
c6b8a6a464f1dddaf3cefe9988d47f42c2704e7b | Krisfer1988/Curso-Python | /Comenzando/EstructurasControlFlujo2.py | 2,522 | 4.21875 | 4 | """Programar una funcion que nos indique si es vocal o no una cierta cadena de texto, pasandole como parametros principales un texto y una
posicion de caracter"""
#debe devolver un valor booleano, y debe de distinguir entre vocales Mayusculas o Minusculas. Hacer uso de if, elif o else.
def esVocal(texto,posicionCaracter):
caracter = texto[posicionCaracter]
if(caracter == "A" or caracter == "E" or caracter == "I" or caracter == "O" or caracter == "U"):
return True
elif(caracter == "a" or caracter == "e" or caracter == "i" or caracter == "o" or caracter == "u"):
return True
else:
return False
#Inicializar 3 textos; indicar para cada uno de ellos si es vocal o no las siguientes posiciones de caracteres
#texto1 = aevde ; posicion 1 ¿es vocal?
#texto2 = AEIOU ; posicion 3 ¿es vocal?
#texto3 = ABCDE ; posicion 4 ¿es vocal? ; imprimir tambien la letra B pasandole una posicion.
#texto 1
texto1 = "aevde"
print(esVocal(texto1,1))
#texto 2
texto2 = "AEIOU"
print(esVocal(texto2,3))
#texto 3
texto3 = "ABCDE"
print(esVocal(texto3,4))
#imprimir letra B pasandole una posicion al texto
posicion = 1
print(texto3[1])
"""Programar una funcion que cuente el numero de vocales desde una posicion dada por parametro, en un texto"""
#Esta funcion debe hacer uso de la funcion esVocal.
def contarVocalesDesdePosicion(texto, posicion):
# Mirar si en la posicion actual hay una vocal o no
esteEsVocal = esVocal(texto, posicion)
if( esteEsVocal == True ) :
aSumar = 1
else:
aSumar = 0;
# Si no soy el ultimo caracter, continuo
longitudDelTexto = len (texto) -1
if ( posicion == longitudDelTexto):
return aSumar
else:
return aSumar + contarVocalesDesdePosicion(texto, posicion+1)
print(contarVocalesDesdePosicion("ABCDE",0))
"""Crear una funcion que nos cuente las vocales que hay en un texto, para ello debemos de recorrer el texto haciendo uso de un while/bucle
hasta la longitud de texto"""
def contarVocales(texto):
posicion=0
numeroDeVocalesQueLlevo=0
#Contar las vocales
while posicion<len(texto):
#Mirar si en esta posicion es vocal o no y totalizarlo
estaEsVocal = esVocal(texto,posicion)
if(estaEsVocal == True):
numeroDeVocalesQueLlevo = numeroDeVocalesQueLlevo + 1
#Pasar a la siguiente posicion
posicion = posicion+1 #posicion+=1
return numeroDeVocalesQueLlevo
print(contarVocales("AEIOU"))
print(contarVocalesDesdePosicion("AEIOU",0)) | false |
e84c0d6cb432bc6ca4e51d92f2251e4f58184a03 | Andrew-Ng-s-number-one-fan/Python-for-Everybody-Specialization | /01 - Programming for Everybody (Getting Started with Python)/Assignment3-1.py | 830 | 4.25 | 4 | # Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours.
# Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking the user input - assume the user types numbers properly.
#---------DesiredOutput---------
#498.75
#-----------SourceCode----------
#hrs = input("Enter Hours:")
#h = float(hrs)
#-------------Answer------------
hrs = input("Enter Hours:")
h = float(hrs)
rate = input("Enter Rate:")
rate = float(rate)
if h<=40 :
pay=h*rate
else :
pay=40*rate+(h-40)*rate*1.5
print(pay) | true |
f29f53060a00f3b36fde993d185b137e5bc587d0 | Volgushka/the_best_bank | /ooo.py | 1,341 | 4.15625 | 4 | class Human:
default_name = "Oleg"
default_age = 35
def __init__(self, name=default_name, age=default_age):
self.name = name
self.age = age
self.__money = 1000
self.__house = None
def info(self):
print(f"Имя: {self.name}\nВозраст: {self.age}\nДеньги: {self.__money}\nДом: {self.__house}")
@staticmethod
def default_info():
print(f"Дефолтное имя: {Human.default_name}\nДефолтный возраст: {Human.default_age}")
def __make_deal(self, house, money):
self.__house = house
self.__money -= money
def earn_money(self, money):
self.__money += money
def buy_house(self, house, sale):
if self.__money < house.final_price(sale):
print("У объекта недостаточно средств")
else:
self.__make_deal(house, house.final_price(sale))
class House:
default_cost = 3000
def __init__(self, area, cost=default_cost):
self._price = cost
def final_price(self, sale):
return self._price*(1-sale/100)
def __str__(self):
return "Дом"
class SmallHouse(House):
def __init__(self):
super().__init__(40)
s_house = SmallHouse()
human = Human()
human.buy_house(s_house, 20)
human.earn_money(10000)
human.buy_house(s_house, 20)
human.info() | false |
fb5923bc37e890d05963cbd07204fce1a2d6db6a | rslindee/daily-coding-problem | /004_missing_int.py | 1,228 | 4.15625 | 4 | """ Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
"""
def find_missing(nums):
# Check every potential value up to the length
for i in range(len(nums)):
found = False
# Check to see if the number already exists in our list
for x in nums:
if ((x > 0) and (x == (i+1))):
found = True
break
# The value was not found and thus is our lowest
if (found == False):
return (i+1)
# We never found a missing value, so it must be the next highest
return len(nums)+1
def find_missing_fast(nums):
# reduce to set
nums = set(nums)
length = range(len(nums))
# check if it exists in set
for i in range(len(nums)):
if (i+1) not in nums:
return (i+1)
return length+1
assert find_missing_fast([3, 4, -1, 1]) == 2
assert find_missing_fast([1, 2, 0]) == 3
| true |
d3be87316e59014c72b096cd5002331f56eddbee | maneeshd/Hacktoberfest-2020 | /Python/bmi calculator.py | 448 | 4.25 | 4 | weight = float(input('Put your weight? (Kg) '))
height = float(input('Put your height? (Mtr) '))
bmi = weight/(height*height)
if bmi <= 18.5:
print('Your BMI is', bmi, 'which means you are underweight')
elif 18.5 < bmi < 25:
print('Your BMI is', bmi,'which means you are normal')
elif 25 < bmi < 30:
print('your BMI is', bmi,' which means you are overweight')
elif bmi > 30:
print('Your BMI is', bmi,'which means you are obese') | false |
506d350ebb8ad4bdc2fbb9028e019f9862f6457a | FelypeNasc/PythonCursoEmVideo | /Exercicios/061-080/desafio073.py | 790 | 4.125 | 4 | tabela = ('Fortaleza', 'Athletico-PR', 'Atlético-MG', 'Flamengo', 'Atlético-GO', 'Bragantino', 'Fluminense', 'Bahia', 'Palmeiras',
'Corinthians', 'Ceará SC', 'Santos', 'São Paulo', 'Internacional', 'Juventude', 'Cuiabá', 'Sport Recife', 'Chapecoense', 'Grêmio', 'América-MG')
print ('''-------- BRASILEIRÃO 2021 -------
Os 5 primeiros colocados do campeonato: ''')
for time in range (0, 4):
print (f'• {time+1} - {tabela[time]}')
input ()
print ('Os 5 últimos colocados do campeonato: ')
for time in range (15, 20):
print(f'• {time+1} - {tabela[time]}')
input ()
print ('Times em ordem alfabética: ')
tabelaOrd = sorted(tabela)
for time in tabelaOrd:
print (f'• {time}')
input ()
print (f'O Chapecoense está em {tabela.index("Chapecoense")}º lugar')
| false |
6f6e674f97d04d33c583a91807f25bdb167ac7ee | FelypeNasc/PythonCursoEmVideo | /Aulas/Aula17/Aula17a.py | 704 | 4.15625 | 4 | # Listas Tuplas () Listas []
lista = ['cookie', 'pizza', 'suco', 'hamburguer']
lista.append('refri')
# Adiciona no final da lista o valor referido
lista[1] = 'pizza de queijo'
lista.insert(3, 'iced tea')
# Adiciona na posição referida o valor referido e o restante é colocado pra frente
del lista[0]
# Comando para deletar uma posição da lista
lista.pop()
# Deleta a última posição da lista ou a posição referida
if 'suco' in lista:
lista.remove('suco')
# Deleta o valor referido independemente da posição
print(lista)
valores = list(range(0, 11))
valores.sort(reverse=True)
# Ordena do maior pro menor
print(valores)
valoresB = [2, 4, 6, 9, 0, 2]
valoresB.sort()
print(valoresB)
| false |
902f43dc2dc894eb2e4431082e985f95f176a9b2 | ttreit-scrapyard/MyCode | /fib.py | 586 | 4.15625 | 4 | ## Print i number of Fibonacci numbers
## variables for Fibonacci calculations are x, y, and z
## i = number of Fibonacci numbers to print
def fibonacci(i):
x = 1
print(x)
y = 1
print(y)
i = i-2 # to account for x and y starting values
while i > 0:
z = x + y
print(z)
i = i - 1
if i > 0:
x = y + z
print(x)
i = i - 1
else:
return
if i > 0:
y = z + x
print(y)
i = i - 1
else:
return
fibonacci(10)
| false |
6ae6152d97f0bc3482abad0c26898747c0e9bf0a | moraesmm/learn_python | /cursoEmVideo/pythonExercise/Mundo 01/5 - Condicoes em Python/ex028_adivinhar_v1.py | 825 | 4.1875 | 4 | # crie um programa que sorteie um numero e receba um valor do usuario como tentativa de acerto
"""
# minha criaçao
import random as r
t = int(input('Digite um numero de 1 a 5: '))
l = [0,1,2,3,4,5]
if t == int(r.choice(l)):
print(f'Voce acertou no sorteio numero digitado: {t} numero sorteado: {r.choice(l)}')
else:
print(f'Voce errou, o numero sorteado era: {r.choice(l)}')
"""
from random import randint
from time import sleep
c = randint(0, 5) # faz o computador "PENSAR"
print('-=-' * 20)
print('Vou pensar em um número entre 0 e 5. Tente adivinhar...')
print('-=-' * 20 + '\n')
p = int(input('Em que numero eu pensei? ')) # jogador tenta adivinhar
print('Processando...')
sleep(1)
if p == c:
print('PARABENS! Voce conseguiu adivinhar!')
else:
print(f'GANHEI! Eu pensei no numero {c} e nao no {p}!') | false |
8832e6b16e6244f1f9e39e8c595882ba6b2ed298 | Myles-Trump/ICS3U-Unit3-03 | /random_guessing_game.py | 742 | 4.40625 | 4 | #!/usr/bin/env python3
# Created by: Myles Trump
# Created on: May 2021
# This program lets the user guess a number between 1-10
# with a randomized integer and tells them if they are correct or not
import random
def main():
# this function lets the user pick a number between 1-10
# and randomizes said number
# input
guess = int(input("Guess an integer between 1-10: "))
print("")
randomized_number = random.randint(1, 10) # a number between 1-10
# process & output
if guess == randomized_number:
print("You are correct")
else:
print("You are not correct, the answer was {0}"
.format(randomized_number))
print("\nDone")
if __name__ == "__main__":
main()
| true |
458a6e8a12487e367f89543533015b8bbf466ea0 | rabranto/python-kurs | /Pierwsze kroki/Trening_Stringow.py | 2,848 | 4.21875 | 4 | """
Zadanie 1 – rozgrzewka
Podpunktów nie trzeba wykonywać pokolei, jeśli czegoś nie pamietasz – idź dalej. Możesz przeczytać wpis ponownie i wrócić do pozostawionego zadania
Do zmiennej sentence przypisz zdanie: „Kurs Pythona jest prosty i przyjemny.”,
a następnie:
Policz wszystkie znaki w napisie
Nie modyfikując zmiennej sentence wyświetl słowo „prosty”
Wyświetl znak o indeksie (czy za każdym razem rozumiesz co się dzieje?):
a)7
b)12
c)-4
d)37
Wprowadź do zdania 2 błędy ortograficzne 😉
"""
print("*" * 20)
print("Zadanie 1 - rozgrzewka")
print("*" * 20)
sentence = "Kurs Pythona jest prosty i przyjemny."
print(sentence)
print("Przypisano wartość do zmiennej \'sentence\'")
print('Ilość wszystkich znaków w napisie to: ',len(sentence))
print("Wyświetlono słowo \'prosty\' nie modyfikując zmiennej:",sentence[18:24])
print("Znak o indeksie a)7: ", sentence[7])
print("Znak o indeksie b)12: ", sentence[12])
print("Znak o indeksie c)-4: ", sentence[-4])
print("Znak o indeksie d)37: \"Brak możliwości wyświetlenia znaku o indeksie 37 - nie istnieje\"")
print("Dodano 2 błędy ortograficzne w zmiennej \'sentence\'")
sentence = sentence.replace("jest", "jezd")
sentence = sentence.replace("rz", "sz")
print(sentence)
"""
Zadanie 2
Utwórz skrypt, który zapyta użytkownika o imię, nazwisko i numer telefonu, a następnie:
Sprawdź czy imię i nazwisko składają się tylko z liter, a nr tel składa się wyłącznie z cyfr (wyświetl tę informację jako true/false)
Użytkownicy bywają leniwi. Nie zawsze zapisują imię czy nazwisko z dużej litery – popraw ich
Niektórzy podają numer telefonu z myślnikami lub z spacjami, usuń zbędne znaki z numeru
Zakładając, że twoi użytkownicy noszą polskie imiona, sprawdź czy użytkownik jest kobietą
Połącz dane w jeden ciąg personal za pomocą spacji
Policz liczbę wszystkich znaków w napisie personal
Podaj liczbę tylko liter w napisie personal[hint]
[hint]Podpowiedź – weź pod uwagę, że numery telefonów w Polsce są 9-cyfrowe
"""
print("*" * 20)
print("Zadanie 2 - utwórz skrypt")
print("*" * 20)
name = input("Jak masz na imię?: ")
surname = input("Jak masz na nazwisko?: ")
tel = input("Podaj numer telefonu: ")
print("Wszystkie znaki w Twoim imieniu są literami?:", name.isalpha())
print("Wszystkie znaki w Twoim nazwisku są literami?:",surname.isalpha())
print("Wszystkie znaki w Twoim numerze telefonu są cyframi?:",tel.isdigit())
name = name.title()
surname = surname.title()
tel = tel.replace("+","")
tel = tel.replace("-","")
tel = tel.replace(" ","")
personal = name + " " + surname +" "+ tel
length = len(personal)
print("Stworzono zmienną personal, która zawiera wszystkie wprowadzone informacje:", personal)
print("Liczba znaków w personal: ", length)
print("Liczba liter w personal: ",length-11)
| false |
0641899e253f1da658099bf086df14e46d744e6d | peterhsprenger/VuRProjects | /TrainingResources/03workingsnippets/Assignment33.py | 781 | 4.5625 | 5 | # 3.3 Write a program to prompt for a score between 0.0 and 1.0.
# If the score is out of range, print an error. If the score is between 0.0 and 1.0, print a grade using the following table:
# Score Grade
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# If the user enters a value out of range, print a suitable error message and exit. For the test, enter a score of 0.85
score = raw_input("type your score:")
try:
scorefloat = float(score)
if scorefloat >= 0.9:
print "A"
elif scorefloat >=0.8:
print scorefloat, "B"
elif scorefloat >= 0.7:
print 'Hello, your ' + score + ' grades to C'
elif scorefloat >= 0.6:
print "D"
else :
print "F"
except:
print "Your input was not a number" | true |
9d65c9e1e04307b286c22fce473b3a7172e45c08 | emmanuelepp/design-patterns-examples | /Creational-Patterns/factory.py | 602 | 4.21875 | 4 | # Factory:
# Provides an interface for creating objects in a superclass,
# but allows subclasses to alter the type of objects that will be created.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return "Woof"
class Cat:
def __init__(self, name):
self.name = name
def speak(self):
return "Meow"
#### Factory method ####
def get_animal(animal="dog"):
animals = dict(dog=Dog("Poki"), cat=Cat("Rudy"))
return animals[animal]
dog = get_animal("dog")
print(dog.speak())
cat = get_animal("cat")
print(cat.speak())
| true |
69c097d36db51056d942e09c0c388912bd5d056c | DrChrisLevy/python_intro_udemy | /book/_build/jupyter_execute/content/chapter2/more_basic_operators.py | 2,349 | 4.78125 | 5 | #!/usr/bin/env python
# coding: utf-8
# # More Basic Python Operators
# We have already learned multiple Python operators such as
# `+,=,-,*,/,>,<,>=,<=,and,or,not,in,not in` and so on.
# In this section we will learn some more. Create a new Jupyter Notebook
# and name it **more_basic_operators** to follow along.
#
# (mod-operator)=
# ## Modulus Operator `%`
# The operator `%` is called the modulo operator.
# It gives the remainder when performing division between two
# numbers. For example, if you divide 4 by 2 the remainder is 0.
# Therefore, `4 % 2` would return `0`. Another example is when
# you do 9 divided by 4. The remainder is 1 so `9 % 4` would
# return `1`.
# In[1]:
4 % 2
# In[2]:
print(9 % 4)
# We can use the `%` operator to check if a number is even.
# For example, the number `n` is even if `n % 2` returns `0`
# because the number 2 would divide evenly into `n`.
# In[3]:
6 % 2 # 6 is even because remainder is 0
# In[4]:
10 % 2 # 10 is even because remainder is 0
# In[5]:
13 % 2 # 13 is odd because remainder is not 0.
# You can also use `%` to check if a number is a multiple of any given number. If you do `a % b` and get a remainder of 0, then it means that `a` is a multiple of `b`. This just means that `b` divides into `a` evenly with a remainder of 0.
# In[6]:
123 % 3 # returns 0 so 123 is a multiple of 3
# In[7]:
256 % 32 # returns 0 so 256 is multiple of 32
# In[8]:
99 % 45 # does not return 0 so 99 is not a multiple of 45
# ## Assignment Operators
# We have already learned about the `=` operator.
# In[9]:
a = 1
# In[10]:
print(a)
# But there are some other operators which you will
# often see coders use. For example, you will often see the pattern:
# In[11]:
i = 0
for x in range(4):
print(i)
i = i + 1
# Another way of writing `i = i + 1` is `i += 1`
# In[12]:
i = 0
for x in range(4):
print(i)
i += 1 # is the same as i = i + 1
# In general, `a += b` is the same as `a = a + b`. It is good to know about
# this because many Python coders will use these little shortcuts operators.
# Here are some others ones:
#
# - `a += b` is the same as `a = a + b`
# - `a -= b` is the same as `a = a - b`
# - `a *= b` is the same as `a = a * b`
# - `a /= b` is the same as `a = a / b`
#
# Feel free to use these when you want.
# In[ ]:
| true |
e9bd7479e8a0a141c6e9a609465dbe7700bda901 | DrChrisLevy/python_intro_udemy | /book/_build/jupyter_execute/content/chapter6/truthy_falsy_values.py | 2,942 | 4.75 | 5 | #!/usr/bin/env python
# coding: utf-8
# # Truthy and Falsy Values
#
# In previous chapters we have used the boolean values `True` and `False`.
# We already know that expressions with operators can evaluate to True or False.
# In[1]:
10 > 2
# In[2]:
if 10 > 2:
print('Hello World!')
# We use these expressions a lot in `if` statements, `while` loops and so on. Now consider the following `if` statements where there is no use of an operator such as `>`, `<`, `==` etc.
# In[3]:
x = 10
if x:
print('Hello World')
else:
print('Good Bye')
# In[4]:
x = 0
if x:
print('Hello World')
else:
print('Good Bye')
# In[5]:
x = [1, 2, 3 ]
if x:
print('Hello World')
else:
print('Good Bye')
# In[6]:
x = []
if x:
print('Hello World')
else:
print('Good Bye')
# You may be wondering how the above `if` statements are even evaluating to `True` or `False`. There is not a typical expression next to the `if`. Instead, only a variable is next to the `if`. In Python, specific values can evaluate to either `True` or `False` even if they are not part of a larger expression. The basic idea is that values that evaluate to `False` are considered **Falsy** whereas values that evaluate to `True` are considered **Truthy**. There are several rules we need to know to figure out what these values will evaluate to. You can checkout out the official [Python documentation](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) for these rules. We will cover them here mostly.
#
# By default, the majority of values in Python will be **truthy**. That is they will evaluate to `True`. So you just need to remember what type of values evaluate to `False`. They are:
#
# - constants defined to be false: `None` and `False`.
# - zero of any numeric type: `0` and `0.0` for example.
# - empty sequences and collections: `''`, `()`, `[]`, `{}`, `set()`, `range(0)`
#
# So think of 0 and anything "empty" (having a length of 0) as evaluating to `False`.
# In[7]:
if 0:
print('I will not print')
elif []:
print('I will not print')
elif {}:
print('I will not print')
elif set():
print('I will not print')
elif ():
print('I will not print')
elif None:
print('I will not print')
else:
print('I will print because every value above evaluates to False.')
# Here are some more examples.
# In[8]:
# once i gets to 0 it will evaluate to False and the loop will break/stop
i = 3
while i:
print(i)
i = i - 1
# In[9]:
if 5 and 0:
print('HEY')
# In[10]:
if 3 and -10:
print('HEY')
# In[11]:
if 0 or [] or {}:
print('HEY')
# In[12]:
if 0 or [] or {} or 0.5:
print('HEY')
# In[13]:
if None:
print('HEY')
# In[14]:
if not None:
print('Hey')
# That is it for truthy and falsy values. It's very important to remember these when using control flow. In the next section we will learn more about the `None` value type.
| true |
05aed4378406c27b69c290b4ac93aa48489c1f03 | eshita18/python | /fabonacci series.py | 370 | 4.15625 | 4 | nterms = int(“How many terms are”)
n1 , n2 = 0,1
count = 0
#check if the number of terms is valid
If terms <= 0:
print(“Please enter a positive integer”)
elif n terms ==1:
print(“Fibnoacci sequence upto”, n terms”:”)
print(n1)
else:
print(“Fibonacci sequence:”)
while count < nterms:
pint(n1)
nth = n1+n2
#update vales
n1 = n2
n2 = nth
count += 1
| false |
c906aed12ea6cd0b6d7d230576485b4eabe1783f | Christochi/Udemy-Python-Course | /Ex_08_loops.py | 1,136 | 4.15625 | 4 | import random
print( "Program asks the user 8 names of people and stores them in a list.",
"Picks a random name and prints it." )
#count = 1 # loop counter
nameList = [] # list of names
#while count <= 8: (alternative with while loop )
for count in range( 0, 8 ):
names = input( "Please enter 8 names: " )
nameList.append( names )
#count += 1
people = random.randint( 0, 7 )
print( "Random person:", nameList[people] )
print( "--------------------" )
print ( "Program creates a guess game with the names of the colors." )
# list of colours
colours = [ "red", "blue", "green", "yellow", "white" ]
guess = "yes"
num = random.randint( 0, len( colours) - 1 )
while guess == 'yes':
guess = input( "Please guess a colour from this list [ red, blue, green, yellow, white ]: " )
if ( guess.lower() == colours[ num ] ):
guess = input( "correct guess. Would you like to play again (yes/no): " )
if (guess.lower() == 'no'):
break
else:
guess = input( "wrong guess. Would you like to play again (yes/no): " )
if (guess.lower() == 'no'):
break
| true |
8d63eb0ff55726a16433d50decd5ced5043240ad | ivaturi/pythonthehardway | /ex38.py | 1,267 | 4.34375 | 4 | #! /usr/bin/env python
# create a list of things
ten_things = "car bus rocket phone chair stool pen"
print ten_things
# are these really ten things?
print "Hm. There are supposed to be ten things in that list..."
# let's keep a bunch of things on hand, to add to our list
more_things = ["bowl", "box", "zebra", "hyena", "bread", "dumpster"]
# make a real list out of the ten_things string
my_stuff = ten_things.split(" ")
# how many things are supposed to be on this list?
required_number_of_things = 10
# add things to my_stuff until we have the requisite amount
while len(my_stuff) < required_number_of_things:
latest = more_things.pop()
print "Adding ", latest
my_stuff.append(latest)
print "There are %d things now" % len(my_stuff)
print "my_stuff : ", my_stuff
print "\n-----"
print "Accessing things..."
print "-----"
# zero-based index, second element
print " [1] : ", my_stuff[1]
# last element
print " [-1] : ", my_stuff[-1]
# last in, first out (also modifies the list)
print " .pop() : ", my_stuff.pop()
# concatenate into a string, using a specified separator
print " .join() : ", ' '.join(my_stuff)
# concatenate a subset of the list, using a specified operator
print " .join(:) : ", ' # '.join(my_stuff[3:5])
| true |
88699b417bed774791fe5399cf7150ba7497b9d4 | ivaturi/pythonthehardway | /ex37/lambda.py | 1,221 | 4.21875 | 4 | #! /usr/bin/python
# Lambdas
# ------
# A lambda (or an anonymous function) is a function that is not bound to any identifier
# Lambdas are often used when we want to return a function as an argument
#
# Unlike in other functional programming languages, python does not let us define
# normal functions anonymously; a lambda can only contain an <expression> that is returned
#
# A lambda function can be used anywhere a function is expected.
#
#
print "\n"
print "-- lambda --"
def multiplier(x):
return lambda n: n * x
times3 = multiplier(3)
times20 = multiplier(20)
print "4 times 3 is %d" % times3(4)
print "4 times 20 is %d" % times20(4)
# Slightly advanced use-cases:
#
# Lamda functions are useful in list operations...
my_array = [10,15,20,23, 26, 27, 13, 29, 43, 56, 108]
print my_array
# retrieve only the elements that are divisible by 5:
print "Divisible by 5:"
print filter(lambda x:x%5==0, my_array)
# square each element of the array
print "Squared:"
print map(lambda x: x**2, my_array)
# compute the sum of the elements of the array
print "Sum"
print reduce(lambda x,y: x+y, my_array)
# (more on map and reduce later)
#
# Links:
# http://www.secnetix.de/olli/Python/lambda_functions.hawk
| true |
199344d0412d63f84bc9d7eae6f148822bfafcd1 | ivaturi/pythonthehardway | /ex42/study_drill.py | 1,596 | 4.25 | 4 | # Study drills
# Why does Python include 'object' in class definitions?
"""
This is the 'new-style' definition of a class in Python.
This was introduced in PEP 252 and PEP 253, see [1], [2], and [3].
Basically, this model is intended to unify the 'class' and 'type' concepts.
In the old-style (classic) classes, instances of classes had a different class
and type.
(the type was 'instance',and the class was whatever they were instances of)
In the new-style classes, a new-style class is basically a user-defined type.
This allows us to extend built-in types by simply specifying them as the parent
class. (or simply 'object', if no other parent class is required)
[1] https://www.python.org/dev/peps/pep-0252/
[2] https://www.python.org/dev/peps/pep-0253/
[3] https://docs.python.org/release/2.2.3/whatsnew/sect-rellinks.html
[4] https://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes
"""
# ------------------------------------------------------------------------------
# Can I use a class as I can an object?
"""
Yes. Everything in Python is an object [1].
Basically, a class is an instance of a metaclass. Because the class itself can be
used to derive instances, it is a 'class' and not an 'object'.
Object <<< (instance of) <<< Class <<< (instance of) <<< Metaclass
Because a class is an object, we can:
- assign it to a variable
- copy it
- create it dynamically
- add attributes to it
More on SO: [2]
[1] https://docs.python.org/2/reference/datamodel.html
[2] https://stackoverflow.com/a/100146
[3] https://stackoverflow.com/a/100037
""""
| true |
62f17f576c26c85d4ca97782d05fe451a69982b9 | Rushi03/robot_motion_planning | /robot.py | 2,726 | 4.28125 | 4 | import numpy as np
import random
from q_learning import QLearning
from maze import Maze
import sys
class Robot(object):
def __init__(self, maze_dim):
'''
Use the initialization function to set up attributes that your robot
will use to learn and navigate the maze. Some initial attributes are
provided based on common information, including the size of the maze
the robot is placed in.
'''
# Starting location; bottom right corner
self.location = [0, maze_dim - 1]
# Starts heading up
self.heading = 'up'
# Dimensions of the maze
self.maze_dim = maze_dim
# Goal(square) for robot
self.goal = [self.maze_dim / 2 - 1, self.maze_dim / 2]
# Import maze environment for rewards
self.maze = Maze(str(sys.argv[1]))
def next_move(self, sensors):
'''
This function is to determine the next move the robot should make,
based on the input from the sensors after its previous move. Sensor
inputs are a list of three distances from the robot's left, front, and
right-facing sensors, in that order.
'''
position = tuple(self.location)
sensor = tuple(sensors)
# Implement Q-Learning
q_learn = QLearning()
# Build state through sesnsor information
state = q_learn.build_state(position, sensor)
# Create state in Q-table if is not already there
q_learn.create_Q(state)
# Take action according to state
action = q_learn.choose_action(state)
if self.location[0] in self.goal and self.location[1] in self.goal:
rotation = 'Reset'
movement = 'Reset'
if (rotation, movement) == ('Reset', 'Reset'):
self.location = [0, self.maze_dim - 1]
self.heading = 'up'
else:
# Up
if action == 'up':
rotation = 0
movement = 1
# Right
elif action == 'right':
rotation = 90
movement = 1
# Down
elif action == 'down':
rotation = 0
movement = -1
# Left
elif action == 'left':
rotation = -90
movement = 1
else:
rotation = 'Reset'
movement = 'Reset'
# Gather reward per action taken by the robot
reward = self.maze.move(self.goal, self.location, action)
# Learn from the state, action, and reward
q_learn.learn(state, action, reward)
# Returns tuple (rotation, movement)
return rotation, movement
| true |
f092ac1d9e561590587b555e44f21271cccd9119 | Vinnu1/python3-crashcourse | /python.py | 1,647 | 4.3125 | 4 | # Welcome to Python 3 crash course
#Contents
#variables - declaration,user input
num = 5;
country = "India";
user_input = input("Enter a number:")
print("The num you've entered is:",user_input)
#operators - arithmetic, comparison, relational, logical
# +, - , /, *, **
# ==
# <, >, <=, >=
# and, or, not
print(5+6,5*6,5-6,5/6,2**3);
#data types - number, string, list, tuple, dictionary
#number
#int
int_num = 5
#float
float_num = 5.66
print("Integer Number:",int_num," Float Number:",float_num);
#complex - a+bi
#string
string = "I am Vinayak"
print(string[0])
#list
list1 = [1,2,"Hi",4]
print(list1)
print(list1[1])
list1[2] = 3
print(list1[0:3])
#tuple
tuple1 = (1,3,5,7,"Str")
tuple1[4] = 9 #immutable, will give error
print(tuple1)
#dictionary
diction1 = {"name":"Vinayak","age":21} ; print(diction1)
print(diction1.keys())
print(diction1.values())
#decision statements - if,elif,else
if(1 == 1):
print("true")
if(1 == 1 and 2 == 2):
print("Both are true")
num = 10
if(num > 20):
print("More than 20")
elif(num < 10):
print("Less than 10")
else:
print("We don't know if the num is >20 or <10")
#loops - for, while
for x in range(0,10):
print(x)
num = 40
while(num < 45):
num = num + 1
print("Less than 45:",num)
#functions - definition, calling
def printName(name):
print("Your name is:",name)
printName("Vinayak")
#file handling - open(r, w, a), read(), write()
#write
file = open("textfile.txt","w")
file.write("This is a textfile")
#read
file = open("textfile.txt","r")
print(file.read(20))
#append
file = open("textfile.txt","a")
file.write(". Python is awesome!")
| true |
28bdd05182c11e1c1612a40169ee581d6859b1d5 | KristenLinkLogan/PythonClass | /playtime4_csvtodict.py | 2,803 | 4.5 | 4 | # Challenge Level: Advanced
# Group exercise!
# Scenario: Your organization has put on three events and you have a CSV with details about those events
# You have the event's date, a brief description, its location, how many attended, how much it cost, and some brief notes
# File: https://github.com/shannonturner/python-lessons/blob/master/section_09_(functions)/events.csv
# Goal: Read this CSV into a dictionary.
# Your function should return a dictionary that looks something like this.
# Bear in mind dictionaries have no order, so yours might look a little different!
# Note that I 'faked' the order of my dictionary by using the row numbers as my keys.
# {0:
# {'attendees': '12',
# 'description': 'Film Screening',
# 'notes': 'Panel afterwards',
# 'cost': '$10 suggested',
# 'location': 'In-office',
# 'date': '1/11/2014'},
# 1:
# {'attendees': '12',
# 'description': 'Happy Hour',
# 'notes': 'Too loud',
# 'cost': '0',
# 'location': 'That bar with the drinks',
# 'date': '2/22/2014'},
# 2:
# {'attendees': '200',
# 'description': 'Panel Discussion',
# 'notes': 'Full capacity and 30 on waitlist',
# 'cost': '0',
# 'location': 'Partner Organization',
# 'date': '3/31/2014'}
# }
from playtime4_csvtolist import csv_to_list
def csv_to_dict(filename,delimiter=","):
"""
reads in the data from a csv file and outputs the data in an embedded dictionary
top level keys are row numbers (e.g., "row 1")
lower level keys are the names of the headers from the csv file
"""
# call csv_to_list function to create a list of lists (called 'list_of_lists' from the csv file
# the list of lists will contain a list with the headers and a list for each row of data
list_of_lists = csv_to_list(filename)
# pop off the list of headers
headers_list = list_of_lists.pop(0)
#rename the original list just to indicate that it's just got the data in it now.
data_lists = list_of_lists
# count how many columns of data there are
record_count = len(headers_list)
#initialize dict and a counter
the_dictionary = {}
count = 0
# put the data into an embedded dictionary
# the first level keys will be the row numbers (1 for each row of data in the csv)
# the column headers will be the 2nd level keys to access each data point
for data_row_index,data_row in enumerate(data_lists):
record_key = "row {0}".format(data_row_index + 1)
the_dictionary[record_key] = {}
while count < record_count:
for header_index,header in enumerate(headers_list):
header_key = header
the_dictionary[record_key][header_key] = data_row[count]
count = count + 1
count = 0
return the_dictionary
#test the function
print csv_to_dict('../resources/events.csv')
| true |
922abafb7564bd1057ad1af8682e2d18fdab81d7 | KristenLinkLogan/PythonClass | /playtime4_csvtolist.py | 877 | 4.6875 | 5 | # Goal: Using the code from Lesson 3: File handling and dictionaries, create a function that will open a CSV file and return the result as a nested list.
def csv_to_list(filename,delimiter=","):
"""
Returns a nested list of records from a delimited file
"""
with open(filename,'r') as csv_file:
records = csv_file.read().split("\n")
# now we're splitting each element of the list into an embedded list containing data elements in each row
for index, record in enumerate(records): #enumerate loops through the list and gives you an index and the value for each element
records[index] = record.split(delimiter)
return records
#testing the function...
print csv_to_list('../resources/survey.csv'),'\n'
print csv_to_list('../resources/states.csv'),'\n'
print csv_to_list('../resources/state_info.csv'),'\n'
print csv_to_list('../resources/contacts.csv'),'\n'
| true |
30ea17dc959102908da13adb272a0eb1c37b5352 | aucan/LeetCode-problems | /461.HammingDistance.py | 824 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 21:59:05 2020
@author: nenad
"""
"""
Problem URL: https://leetcode.com/problems/hamming-distance/
Problem description:
Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
"""
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
hammingDiff = x ^ y
return bin(hammingDiff)[2:].count('1')
sol = Solution()
# Test 1
x = 1; y = 4
print(sol.hammingDistance(x, y)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.