blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
31de1ebea079dc10269a2d888bda22891b13d588 | eric496/leetcode.py | /stack/735.asteroid_collision.py | 2,054 | 4.25 | 4 | """
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
Example 1:
Input:
asteroids = [5, 10, -5]
Output: [5, 10]
Explanation:
The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input:
asteroids = [8, -8]
Output: []
Explanation:
The 8 and -8 collide exploding each other.
Example 3:
Input:
asteroids = [10, 2, -5]
Output: [10]
Explanation:
The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Example 4:
Input:
asteroids = [-2, -1, 1, 2]
Output: [-2, -1, 1, 2]
Explanation:
The -2 and -1 are moving left, while the 1 and 2 are moving right.
Asteroids moving the same direction never meet, so no asteroids will meet each other.
Note:
The length of asteroids will be at most 10000.
Each asteroid will be a non-zero integer in the range [-1000, 1000]..
"""
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stk = []
for ast in asteroids:
if ast > 0:
stk.append(ast)
else:
# Postive on the left are smaller, it explodes
while stk and stk[-1] > 0 and stk[-1] < -ast:
stk.pop()
# Two asteroids are opposites, e.g. [-8,8] >>> []
if stk and stk[-1] == -ast:
stk.pop()
# Current asteroid is largest in size and all previous exploded
# Or the previous one is moving towards left too
elif not stk or stk[-1] < 0:
stk.append(ast)
return stk
| true |
93ac1f9aded7169013ca48686d192c038ecd2082 | eric496/leetcode.py | /graph/737.sentence_similarity_II.py | 2,835 | 4.125 | 4 | """
Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar.
For example, words1 = ["great", "acting", "skills"] and words2 = ["fine", "drama", "talent"] are similar, if the similar word pairs are pairs = [["great", "good"], ["fine", "good"], ["acting","drama"], ["skills","talent"]].
Note that the similarity relation is transitive. For example, if "great" and "good" are similar, and "fine" and "good" are similar, then "great" and "fine" are similar.
Similarity is also symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar.
Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs.
Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"].
Note:
The length of words1 and words2 will not exceed 1000.
The length of pairs will not exceed 2000.
The length of each pairs[i] will be 2.
The length of each words[i] and pairs[i][j] will be in the range [1, 20].
"""
class Solution:
def areSentencesSimilarTwo(
self, words1: List[str], words2: List[str], pairs: List[List[str]]
) -> bool:
if len(words1) != len(words2):
return False
parent = {}
rank = {}
for w1, w2 in zip(words1, words2):
parent[w1] = w1
parent[w2] = w2
rank[w1] = 0
rank[w2] = 0
for w1, w2 in pairs:
if w1 not in parent:
parent[w1] = w1
if w2 not in parent:
parent[w2] = w2
if w1 not in rank:
rank[w1] = 0
if w2 not in rank:
rank[w2] = 0
self.union(w1, w2, parent, rank)
for w1, w2 in zip(words1, words2):
root1 = self.find(w1, parent)
root2 = self.find(w2, parent)
if root1 != root2:
return False
return True
def find(self, word: str, parent: dict) -> str:
if word == parent[word]:
return word
root = self.find(parent[word], parent)
parent[word] = root
return root
def union(self, word1: str, word2: str, parent: List[str], rank: dict) -> None:
root1 = self.find(word1, parent)
root2 = self.find(word2, parent)
if root1 == root2:
return
if rank[root1] > rank[root2]:
parent[root2] = root1
elif rank[root1] < rank[root2]:
parent[root1] = root2
else:
parent[root2] = root1
rank[root1] += 1
| true |
503ddf1278a6b6c2c289560713f492b5222499f6 | eric496/leetcode.py | /string/165.compare_version_numbers.py | 2,679 | 4.125 | 4 | """
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.
Example 1:
Input: version1 = "0.1", version2 = "1.1"
Output: -1
Example 2:
Input: version1 = "1.0.1", version2 = "1"
Output: 1
Example 3:
Input: version1 = "7.5.2.4", version2 = "7.5.3"
Output: -1
Example 4:
Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1”
Example 5:
Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0"
Note:
Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes.
Version strings do not start or end with dots, and they will not be two consecutive dots.
"""
# Solution 1: Pad trailing zeros
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1 = [int(d) for d in version1.split(".")]
v2 = [int(d) for d in version2.split(".")]
n1, n2= len(v1), len(v2)
if n1 > n2:
v2 += [0] * (n1 - n2)
if n2 > n1:
v1 += [0] * (n2 - n1)
for d1, d2 in zip(v1, v2):
if d1 > d2:
return 1
elif d1 < d2:
return -1
return 0
# Solution 2
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1 = version1.split(".")
v2 = version2.split(".")
i = j = 0
n1, n2 = len(v1), len(v2)
while i < n1 and j < n2:
if int(v1[i]) < int(v2[j]):
return -1
if int(v1[i]) > int(v2[j]):
return 1
i += 1
j += 1
while i < n1:
if int(v1[i]):
return 1
i += 1
while j < n2:
if int(v2[j]):
return -1
j += 1
return 0
| true |
8c969a86093417d47cf279144c3d317ddb308f09 | eric496/leetcode.py | /hash_table/1072.flip_columns_for_maximum_number_of_equal_rows.py | 1,144 | 4.125 | 4 | """
Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and flip every cell in that column. Flipping a cell changes the value of that cell from 0 to 1 or from 1 to 0.
Return the maximum number of rows that have all values equal after some number of flips.
Example 1:
Input: [[0,1],[1,1]]
Output: 1
Explanation: After flipping no values, 1 row has all values equal.
Example 2:
Input: [[0,1],[1,0]]
Output: 2
Explanation: After flipping values in the first column, both rows have equal values.
Example 3:
Input: [[0,0,0],[0,0,1],[1,1,0]]
Output: 2
Explanation: After flipping values in the first two columns, the last two rows have equal values.
Note:
1 <= matrix.length <= 300
1 <= matrix[i].length <= 300
All matrix[i].length's are equal
matrix[i][j] is 0 or 1
Accepted
"""
class Solution:
def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:
cnt = {}
for row in matrix:
flip = [1 - num for num in row]
cnt[tuple(row)] = cnt.get(tuple(row), 0) + 1
cnt[tuple(flip)] = cnt.get(tuple(flip), 0) + 1
return max(cnt.values())
| true |
f5532a36d7eca4f6e2b6de99ae5f20f09f568656 | eric496/leetcode.py | /hash_table/1570.dot_product_of_two_sparse_vectors.py | 1,544 | 4.125 | 4 | """
Given two sparse vectors, compute their dot product.
Implement class SparseVector:
SparseVector(nums) Initializes the object with the vector nums
dotProduct(vec) Compute the dot product between the instance of SparseVector and vec
A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector.
Follow up: What if only one of the vectors is sparse?
Example 1:
Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
Output: 8
Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8
Example 2:
Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
Output: 0
Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0
Example 3:
Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4]
Output: 6
Constraints:
n == nums1.length == nums2.length
1 <= n <= 10^5
0 <= nums1[i], nums2[i] <= 100
"""
class SparseVector:
def __init__(self, nums: List[int]):
self.vals = {i: n for i, n in enumerate(nums) if n}
# Return the dotProduct of two sparse vectors
def dotProduct(self, vec: 'SparseVector') -> int:
res = 0
for i, n in vec.vals.items():
if i in self.vals:
res += self.vals[i] * n
return res
# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)
| true |
a17970f0112264f156d47f33651d6dece40a2fc8 | eric496/leetcode.py | /binary_search/69.sqrt(x).py | 1,355 | 4.25 | 4 | """
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
"""
"""
Thought:
Solution 1: binary search
Solution 2: Newton's method
Solution 3: bit manipulation
"""
# Solution 1: binary search
class Solution:
def mySqrt(self, x: int) -> int:
low, high = 1, x
while low <= high:
mid = low + ((high - low) >> 1)
if mid > x / mid:
high = mid - 1
elif mid + 1 > x / (mid + 1):
return mid
else:
low = mid + 1
return 0
# Solution 2: Newton's method
class Solution:
def mySqrt(self, x: int) -> int:
r = x
while r * r > x:
r = (r + x // r) >> 1
return r
# Solution 3: bit manipulation
class Solution:
def mySqrt(self, x: int) -> int:
res = 0
bit = 1 << 16
while bit:
res |= bit
if res * res > x:
res ^= bit
bit >>= 1
return res
| true |
7264a645d55284318cfe0622c13ffcba4a1bfdde | eric496/leetcode.py | /linked_list/206.reverse_linked_list.py | 1,194 | 4.15625 | 4 | """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
"""
Thought process:
Use three pointers prev, cur, and nxt.
Explanations: https://www.geeksforgeeks.org/reverse-a-linked-list/
Draw a graph helps to understand the process.
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
# Solution 1: Iterative (Explanations: https://www.geeksforgeeks.org/reverse-a-linked-list/)
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
while head:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
# Solution 2: Recursive
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
return self.reverse(head, None)
def reverse(self, cur: ListNode, prev: ListNode) -> ListNode:
if not cur:
return prev
nxt = cur.next
cur.next = prev
return self.reverse(nxt, cur)
| true |
ab6657db6034e3ba3d5b84afa418f9cdce589c9e | eric496/leetcode.py | /backtracking/212.word_search_II.py | 2,857 | 4.125 | 4 | """
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Note:
All inputs are consist of lowercase letters a-z.
The values of words are distinct.
"""
# Solution: Backtracking + Trie
class TrieNode:
def __init__(self):
self.end = False
self.children = {}
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
walk = self.root
for c in word:
if c not in walk.children:
walk.children[c] = TrieNode()
walk = walk.children[c]
walk.end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
walk = self.root
for c in word:
if c not in walk.children:
return False
walk = walk.children[c]
return walk.end
def startswith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
walk = self.root
for c in prefix:
if c not in walk.children:
return False
walk = walk.children[c]
return True
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
trie = Trie()
for word in words:
trie.insert(word)
m, n = len(board), len(board[0])
visited = set()
res = set()
for i in range(m):
for j in range(n):
self.dfs(board, i, j, "", trie, visited, res)
return list(res)
def dfs(self, board: List[List[str]], y: int, x: int, cur: str, trie: Trie, visited: set, res: set) -> None:
if 0 <= y < len(board) and 0 <= x < len(board[0]) and (y, x) not in visited:
cur += board[y][x]
if not trie.startswith(cur):
return
if trie.search(cur):
res.add(cur)
visited.add((y, x))
for dy, dx in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
self.dfs(board, y + dy, x + dx, cur, trie, visited, res)
visited.remove((y, x))
| true |
e2ef3c5ddc54889fa883a09cd956b7cf1cea0756 | eric496/leetcode.py | /math/9.palindrome_number.py | 1,012 | 4.34375 | 4 | """
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
"""
"""
Thought:
Convert to string and reverse it.
Follow up:
Similar to 7.reverse_integer, using divmod() to calculate divident and modulo.
"""
class Solution(object):
def isPalindrome(self, x):
return str(x) == str(x)[::-1]
# follow up
class Solution(object):
def isPalindrome(self, x):
if x < 0:
return False
rev, num = 0, x
while num != 0:
num, mod = divmod(num, 10)
rev = rev * 10 + mod
return rev == x
| true |
482ec99935aac0761547e3d261fde4cf88d7acff | eric496/leetcode.py | /tree/404.sum_of_left_leaves.py | 1,338 | 4.125 | 4 | """
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Solution 1: recursive
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
return self.dfs(root, False)
def dfs(self, node: TreeNode, is_left: bool) -> int:
if not node:
return 0
if not node.left and not node.right and is_left:
return node.val
return self.dfs(node.left, True) + self.dfs(node.right, False)
# Solution 2: iterative
from collections import deque
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if not root:
return 0
q = deque([(root, 0)])
res = 0
while q:
for _ in range(len(q)):
node, left = q.popleft()
if left and not node.left and not node.right:
res += node.val
if node.left:
q.append((node.left, 1))
if node.right:
q.append((node.right, 0))
return res
| true |
1d2f58e0e7341d711cbfdabcfbe4264c6d901dd8 | eric496/leetcode.py | /string/443.string_compression.py | 1,727 | 4.1875 | 4 | """
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2:
Input:
["a"]
Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
Explanation:
Nothing is replaced.
Example 3:
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
Note:
All characters have an ASCII value in [35, 126].
1 <= len(chars) <= 1000.
"""
class Solution:
def compress(self, chars: List[str]) -> int:
read_idx = write_idx = 0
while read_idx < len(chars):
cur_char = chars[read_idx]
cnt = 0
while read_idx < len(chars) and chars[read_idx] == cur_char:
read_idx += 1
cnt += 1
chars[write_idx] = cur_char
write_idx += 1
if cnt > 1:
for d in str(cnt):
chars[write_idx] = d
write_idx += 1
return write_idx
| true |
3e7b3dddc5e7ddcbaa445db7996c6d873918fbc4 | eric496/leetcode.py | /bfs/210.course_schedule_II.py | 2,036 | 4.125 | 4 | """
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.isinstance
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] .
Example 2:
Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.
"""
from collections import defaultdict, deque
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
indegree = [0] * numCourses
pre = defaultdict(list)
q = deque()
res = []
for p in prerequisites:
indegree[p[0]] += 1
pre[p[1]].append(p[0])
for i, n in enumerate(indegree):
if not n:
q.append(i)
while q:
course = q.popleft()
res.append(course)
for nxt in pre[course]:
indegree[nxt] -= 1
if not indegree[nxt]:
q.append(nxt)
for i in indegree:
if i:
return []
return res
| true |
43f32c57f70fdf2d106d3f2b0a4fe83e468c0a4d | eric496/leetcode.py | /stack/224.basic_calculator.py | 2,600 | 4.15625 | 4 | """
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
Example 1:
Input: "1 + 1"
Output: 2
Example 2:
Input: " 2-1 + 2 "
Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
"""
# Solution 1
class Solution:
def calculate(self, s: str) -> int:
operand_stk = []
operator_stk = []
depth = 0
tokens = self.tokenize(s)
for token in tokens:
if token.isdigit():
operand_stk.append(int(token))
elif token in "()":
depth += 1 if token == "(" else -1
elif token in "+-":
while operator_stk and operator_stk[-1][1] >= depth:
operator, _ = operator_stk.pop()
right, left = operand_stk.pop(), operand_stk.pop()
res = left + right if operator == "+" else left - right
operand_stk.append(res)
operator_stk.append((token, depth))
while operator_stk:
operator, _ = operator_stk.pop()
right, left = operand_stk.pop(), operand_stk.pop()
res = left + right if operator == "+" else left - right
operand_stk.append(res)
return operand_stk[0]
def tokenize(self, s: str) -> List[str]:
res = []
cur = -1
for c in s:
if c.isspace():
continue
elif c.isdigit():
cur = cur * 10 + int(c) if cur != -1 else int(c)
else:
if cur != -1:
res.append(str(cur))
cur = -1
res.append(c)
return res + [str(cur)] if cur != -1 else res
# Solution 2
class Solution:
def calculate(self, s: str) -> int:
res, cur, sign, stk = 0, 0, 1, []
for ch in s:
if ch.isdigit():
cur = 10 * cur + int(ch)
elif ch in ["+", "-"]:
res += sign * cur
cur = 0
sign = 1 if ch == "+" else -1
elif ch == "(":
stk.append(res)
stk.append(sign)
sign, res = 1, 0
elif ch == ")":
res += sign * cur
res *= stk.pop()
res += stk.pop()
cur = 0
return res + sign * cur
| true |
a583271ff008c458b55cda177a20b4beb70f2a04 | eric496/leetcode.py | /array/950.reveal_cards_in_increasing_order.py | 1,978 | 4.28125 | 4 | """
In a deck of cards, every card has a unique integer. You can order the deck in any order you want.
Initially, all the cards start face down (unrevealed) in one deck.
Now, you do the following steps repeatedly, until all cards are revealed:
Take the top card of the deck, reveal it, and take it out of the deck.
If there are still cards in the deck, put the next top card of the deck at the bottom of the deck.
If there are still unrevealed cards, go back to step 1. Otherwise, stop.
Return an ordering of the deck that would reveal the cards in increasing order.
The first entry in the answer is considered to be the top of the deck.
Example 1:
Input: [17,13,11,2,3,5,7]
Output: [2,13,3,11,5,17,7]
Explanation:
We get the deck in the order [17,13,11,2,3,5,7] (this order doesn't matter), and reorder it.
After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.
We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].
We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].
We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].
We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].
We reveal 11, and move 17 to the bottom. The deck is now [13,17].
We reveal 13, and move 17 to the bottom. The deck is now [17].
We reveal 17.
Since all the cards revealed are in increasing order, the answer is correct.
Note:
1 <= A.length <= 1000
1 <= A[i] <= 10^6
A[i] != A[j] for all i != j
"""
"""
Thought process:
Reverse the process
- Sort the deck in reversed order (from largest to smallest)
- Rotate the queue first
- Then append the element
"""
from collections import deque
class Solution:
def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
deck.sort(reverse=True)
q = deque()
for d in deck:
if q:
q.appendleft(q.pop())
q.appendleft(d)
return list(q)
| true |
4b1aefbe9b7938d96ec023a0e66609bf873c399b | eric496/leetcode.py | /design/295.find_median_from_data_stream.py | 1,729 | 4.21875 | 4 | """
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
Example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
Follow up:
If all integer numbers from the stream are between 0 and 100, how would you optimize it?
If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
"""
from heapq import heappush, heappop
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.first_half = []
self.second_half = []
def addNum(self, num: int) -> None:
if len(self.first_half) == len(self.second_half):
heappush(self.first_half, -num)
largest = -heappop(self.first_half)
heappush(self.second_half, largest)
else:
heappush(self.second_half, num)
smallest = heappop(self.second_half)
heappush(self.first_half, -smallest)
def findMedian(self) -> float:
if len(self.first_half) == len(self.second_half):
return float(self.second_half[0] - self.first_half[0]) / 2
else:
return float(self.second_half[0])
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
| true |
c4e547ac497a2343419d7162828c1f3f2b3651cd | simmol/aktis_tasks | /running_median.py | 989 | 4.3125 | 4 | import bisect
from decimal import Decimal
def calculate_median_from_file(file_name):
with open(file_name) as input_file:
number_of_records = int(input_file.readline())
input_list = []
for x in range(0, number_of_records):
next_line = input_file.readline()
# insert the new element so the list is kept sorted
# Convert the number to Decimal - Better precision and avoided float rounding errors
bisect.insort(input_list, Decimal(next_line))
median = calculate_median(input_list)
# Output the median to STDOUT.
print(median.quantize(Decimal('.1')))
def calculate_median(sorted_list):
"""Function that can calculate the median of a list
Assumes the given list to be sorted
"""
whole_part, remainder = divmod(len(sorted_list), 2)
if remainder:
return sorted_list[whole_part]
return sum(sorted_list[whole_part - 1:whole_part + 1]) / Decimal(2)
| true |
aef30e7d197756733ae1c6a9003b62fd9d927021 | Sangeethakarthikeyan/CS-2 | /numguess.py | 674 | 4.125 | 4 | import sys
import random
correct=random.randint(1,9) #fix the correct guess
while True:
try: num=int(float(input('Guess a number between 1 to 9: ')))
except: #prompt user for a numeric data and get the input again
print('Wrong input. Enter numeric data only')
continue
if num>0 and num<=9: # check if input is between 1 to 9. Else prompt the user that it is wrong input and get input again
if num==correct: # if correct guess, say well guessed and exit . Otherwise get input again
print('Well guessed!')
sys.exit()
else:
print('Wrong guess.Try again')
continue
else:
print('Wrong input. Numbers between 1 to 9 only allowed')
continue
| true |
d20b11c382cb9c6bdd0ad91b9f7e0ccfa35bdc9f | Sangeethakarthikeyan/CS-2 | /sleep_in_cp2.py | 928 | 4.3125 | 4 | import sys
print('Sleep_in_check'.upper())
# Function definition to decide sleep_in or not
def sleep_in(weekday,vacation):
weekday = weekday == 'y' #if user enters either 'Y' or 'y', variable weekday will be assigned True otherwise False.
vacation =vacation == 'y' #if user enters either 'Y' or 'y', variable vacation will be assigned True otherwise False.
if vacation or not weekday: print("\nSleep in tight!")
else: print("\nGo to Work!")
#Get input to know if it is a weekend, vacation
weekday=input('Is it a weekday? Enter Y if yes or N if no: ').lower()
# Sleep_in Function call after getting inputs
if(weekday=='y' or weekday=='n'):
vacation=input('Are we on a vacation? Enter Y if yes or N if no: ').lower()
if (vacation=='y' or vacation=='n'): sleep_in(weekday, vacation)
else:
print('Invalid input. Enter either Y or N')
sys.exit()
else:
print('Invalid input. Enter either Y or N')
sys.exit()
| true |
45fc06e3c0a54227fab94a09446a7e281c382bd3 | Sangeethakarthikeyan/CS-2 | /sum_double_cp2.py | 412 | 4.1875 | 4 | import sys
#fucnction definition: sum_double
def sum_double(a,b):
# Check if equal or not
if a==b: return 2*(a+b)
else: return a+b
#get inputs
try:
a=int(float(input('Enter first number: ')))
b=int(float(input('Enter second number: ')))
except:
print('Enter numeric input')
sys.exit()
#print ("sum_double(%d,%d): %d " %(a,b,sum_double(a,b)))
print("sum_double({},{}):{}".format(a,b,sum_double(a,b)))
| false |
3ffb82bc8e3ae131a44fe7018467431bc70ab67c | Sangeethakarthikeyan/CS-2 | /class_size.py | 1,101 | 4.1875 | 4 | #program to find the class size of Yr1 to Yr6 for years from 2004-2017 based on the user input
print('CLASS SIZES OF YR 1 TO YR 6 FOR THE ACADEMIC YEARS FROM 2004 TO 2017')
import sys
# open the file or print a message if the file doesnt exist
try:
fhand=open('class_size.txt')
except:
print('File cannot be opened',fname)
sys.exit()
#Get user inputs
try:
year=int(input('Enter any year between 1 and 6 for which class size to be found: '))
acyear=int(input('Enter any year between 2004 and 2017: '))
except:
print('Please enter valid numeric data only')
sys.exit()
#Give a prompt for invalid inputs
if (year not in range(1,7)) or (acyear not in range(2004,2018)):
print('Data not found. Invalid input. Please enter valid input')
sys.exit()
# Loop for operating on each line of the file
for line in fhand:
field=line.split() #splitting into different fields with | as a separator
if field[0]==str(acyear): # For the required academic year
print("The class size of Yr {} in the year {} is {}".format(year,acyear,field[year+1])) # field[year+1] has the data for the required year
| true |
cab29a8ec1bd90f2218998ea4338890b0ce82dc7 | ShardarQuraishi/Python-CPSC-2-3-1- | /Assignment 2/as2.py | 2,813 | 4.375 | 4 | #Shardar Mohammed Quraishi
#UCID: 30045559
#22 Oct 2017
#Assignment 2
#importing turtle and random modules
import turtle
import random
count = 0;
scorekeeper = turtle.Turtle();
#defining function for Alex which will move taking specific inputs from the user inorder to move
def Alex_movement(Alex):
u=30
k=45
direction = input("please enter direction: ")
if(direction == "w"):
Alex.forward(u)
elif(direction == "a"):
Alex.left(k)
elif(direction == "d"):
Alex.right(k)
elif(direction == "s"):
Alex.bk(u)
else:
print('Invalid response, TRY AGAIN!')
return False
#counting the number of times Alex was moved.
global count
count = count+1;
scorekeeper.clear()
scorekeeper.penup()
scorekeeper.hideturtle()
scorekeeper.setposition(50, -300)
scorestring = "Number of times Alex was moved: %d" %count
scorekeeper.write(scorestring,False, align="left", font=("Arial", 14, "normal"))
#defining function for the movement of Alice. Where 2/3rd of Alice's movement is forward and the rest is either right or left.
def Alice_movement(Alice):
g=20
b=90
movement = random.randint(1,3)
angle = random.randint(1,2)
if(movement != 3):
Alice.forward(g)
else:
if(angle == "1"):
Alice.right(b)
else:
Alice.left(b)
#defining a function for calculating the distance between the Alex and Alice
def check_distance(turtle1, turtle2):
distance = turtle1.distance(turtle2)
return distance
#defining a function where the game is run, Alex and Alice functions are called. There is a while loop in which the contents are run until the conditions are fulfilled.
def play(turtle1, turtle2):
while (check_distance(turtle1, turtle2) > 30):
Alex_movement(turtle1)
Alice_movement(turtle2)
#setting up commands for the distance between the two turtles to be displayed on the turtle screen.
global distance
distance = turtle1.distance(turtle2)
scorekeeper.setposition(-300, 300)
distance = turtle1.distance(turtle2)
distancestring = "Distance between Alex & Alice: %d" %distance
scorekeeper.write(distancestring,False, align="left", font=("Arial", 14, "normal"))
print(":.:Game over:.: Alex caught Alice:.:")
#this is the main function which calls upon all the functions defined and plays a major rule for the smooth running of the program. This also contains turtle and the screen properties.
def main():
tScreen = turtle.Screen()
WIDTH = 500
HEIGHT = 500
tScreen.screensize(WIDTH,HEIGHT)
Alex = turtle.Turtle()
Alex.color("Blue")
Alex.shape("turtle")
Alice = turtle.Turtle()
Alice.color("Red")
Alice.shape("turtle")
x1 = random.randint(-250, 250)
y1 = random.randint(-250, 250)
Alice.pu()
Alice.setposition(x1, y1)
Alice.pd()
play(Alex, Alice)
#print(check_distance(Alex, Alice))
print("Number of times Alex was moved ", count)
tScreen.mainloop()
main()
| true |
82b0e9dc549fa92e1c50c6337bf1ec4107ab4fb7 | shubhamrocks888/questions | /SORTING_PROGRAMS/bubble_sort.py | 1,485 | 4.21875 | 4 | ##Bubble Sort
-> Bubble sort, also referred to as comparison sort, is a simple sorting algorithm that repeatedly goes through the list,
compares adjacent elements and swaps them if they are in the wrong order.
-> This is the most simplest algorithm and inefficient at the same time.
##Explanation
Algorithm: We compare adjacent elements and see if their order is wrong (i.e a[i] > a[j] for 1 <= i < j <= size of array;
if array is to be in ascending order, and vice-versa). If yes, then swap them.
#PYTHON-PROGRAM:
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
return arr
arr = [5,2,6,7,1,0,3]
print (bubble_sort(arr))
-> This is used to identify whether the list is already sorted.
When the list is already sorted (which is the best-case scenario), the complexity of bubble sort is only O(n).
##Worst case and Average case scenario:
In Bubble Sort, n-1 comparisons are done in the 1st pass, n-2 in 2nd pass, n-3 in 3rd pass and so on.
So, the total number of comparisons will be:
Sum = (n-1) + (n-2) + (n-3) + ..... + 3 + 2 + 1
Sum = n(n-1)/2
Hence, the time complexity is of the order n2 or O(n2).
##Space Complexity of Bubble sort
The space complexity for the algorithm is O(1), because only a single additional memory space is required
i.e. for temporary variable used for swapping.
| true |
b40cd8b90b4aa1e655835e5cafbf4379abe28390 | ItaloQoliveira/Segundo-Semestre | /python?/ClassCat.py | 912 | 4.125 | 4 | class cat: #creating the class cat
def __init__(self,color,age): #Defining attributes for cat
self.color=color
self.age=age
def meow(self): #A method to just print something, the self as argument is a must
print("Meeeow!!~~")
def yearpassed(self): #Adding one year to the cat's age
self.age+=1
def showinfo(self): # Method to print all the info on the screen
print(self.age)
print(self.color)
def info(self): #A different way to get the info
return self.age,self.color
#Now i'm gonna test somethings to get more comfortable using objects
morgana= cat("black",4)
morgana.showinfo()
age,color= morgana.info()
idade,cor=morgana.age,morgana.color
print("Morgana is a {} cat, and is {} years old".format(color,age))
#print("Morgana is a {} cat, and is {} years old".format(cor,idade))
morgana.yearpassed()
morgana.showinfo()
morgana.meow()
| true |
c1dc89d5b76c9299942488ebdf65db36baa9a775 | Aswinraj-023/Python_CA-1 | /Assessment_1/Substitution_Cipher.py | 1,527 | 4.625 | 5 | #3) Substitution Cipher
encrypt="" # assigning encrypt variable to an empty string
decrypt="" # assigning decrypt variable to an empty string
string_1 = input("String 1 : ").upper() # getting plain text from user & converting to uppercase
string_2 = input("String 2 : ").lower() # getting encrypted text from user & converting to lowercase
letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] # creating a list of 26 alphabets in uppercase
code = ['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'] # creating a list of 26 alphabets in reverse order in lowercase
for i in string_1: #accessing each values of string_1
if i in letters: #if value in i is in 'letters'
index = letters.index(i) #accessing the index values in letters using index values of string_1
encrypt = encrypt + code[index] # encrypting the plain text
decrypt = decrypt + letters[index] #decrypting the encrypted text
if string_2==encrypt: #comparing if user's encrypted text is equal to the encrypted text found
print("String 2 is the encoded version of String 1") #if they are equal string_2 is the encoded text
else: # if they aren't equal string_2 is not encoded text
print("String 2 is not encoded version of String 1") #printing string_2 is not encoded text
print("Plain Text : ",string_1) # printing the plain text
print("Encrypted Text is : ",encrypt) # printing the encrypted text
| true |
e6d0bf511ea73447106da46284cb6f36ded8b428 | nguyenbrandon/CMSC201 | /Homeworks/hw8/hw8_part3.py | 1,115 | 4.1875 | 4 | #File: hw8_part3.py
#Author: Brandon Nguyen
#Date: 11/24/15
#Section: 20
#E-mail: Brando15@umbc.edu
#Description: This program takes in two integers (greater than 0)
# from the user and calculates the greatest common
# denominator of the two numbers by calling a recursive
# function named gcd().
#NOTE: Worked with Ellen Gupta
def gcd(num1, num2, index):
if num1 % index == 0 and num2 % index == 0:
return index
else:
return gcd(num1, num2, index - 1)
def main():
num1 = 0
while num1 <= 0:
num1 = int(input("Please enter the first integer: "))
if num1 <= 0:
print("Your number must be positive (greater than 0).")
num2 = 0
while num2 <= 0:
num2 = int(input("Please enter the second integer: "))
if num2 <= 0:
print("Your number must be positive (greater than 0).")
if num1 > num2:
index = num2
else:
index = num1
GCD = gcd(num1, num2, index)
print("The GCD of", num1, "and", num2, "is", GCD)
print()
main()
| true |
05829e00a7405c2ee2926b6752387c9464cf8b47 | nguyenbrandon/CMSC201 | /Homeworks/hw3/hw3_part5.py | 1,304 | 4.625 | 5 | # File: hw3_part5.py
# Written by: Brandon Nguyen
# Date: 9/24/15
# Lab Section: 20
# UMBC email: brando15@umbc.edu
# Description: The purpose of this program is to prompt the user to enter the
# day of the month. Assuming the month starts on a Monday, the
# program then determines which day of the week it is. If the
# user enters an invalid number, the program says so.
def main() :
day = int(input("Please enter the day of the month: "))
if day == 1 or day == 8 or day == 15 or day == 22 or day == 29 :
print("Today is a Monday!")
elif day == 2 or day == 9 or day == 16 or day == 23 or day == 30 :
print("Today is a Tuesday!")
elif day == 3 or day == 10 or day == 17 or day == 24 or day == 31 :
print("Today is a Wednesday!")
elif day == 4 or day == 11 or day == 18 or day == 25 :
print("Today is a Thursday!")
elif day == 5 or day == 12 or day == 19 or day == 26 :
print("Today is a Friday!")
elif day == 6 or day == 13 or day == 20 or day == 27 :
print("Today is a saturday!")
elif day == 7 or day == 14 or day == 21 or day == 28 :
print("Today is a Sunday!")
else :
print("Invalid day.")
main()
| true |
73d69c30c8704663b1221a1667680b4e63388b17 | nguyenbrandon/CMSC201 | /Homeworks/hw5/hw5_part2.py | 648 | 4.4375 | 4 | # File: hw5_part2.py
# Written by: Brandon Nguyen
# Date: 10/10/15
# Lab section: 20
# UMBC Email: brando15@umbc.edu
# Description: This program prompts the user to enter two integers; a width
# and height. The program then prints a box using the given
# dimensions & the box is made out of numbers counting up from 1.
def main():
width = int(input("Please enter a width: "))
height = int(input("Please enter a height: "))
counter = 1
for i in range (height):
for i in range (width):
print (counter ,"", end = "")
counter+=1
print("\n", end = "")
main()
| true |
7f5e0e7a6a165fb220f39fa217316d0139a82fe2 | gibrankhantareen/Understand-Cryptography-Concepts | /decode.py | 1,880 | 4.34375 | 4 | #In this code we will only do the Decryption Part
import time
# By this we get the Encrypted Code which was given to user using Encode.py earlier
encrypted_code = input("Enter your Encrypted Code: ")
#Here we will make our own Conversion Chart for the Respective Letters
conversion_table_ka_code = {
# I have used a simple logic for Key here.
# Same logic used in Encryption but here Letters will be reversed
# Any Encrypted letter eg. C is equal to (Its Previous Letter)-1
# So C now is equal to A. Rest alphabets will follow the same case
# Below are Alphabets which are Uppercase
'C': 'A', 'D': 'B', 'E': 'C', 'F': 'D', 'G': 'E', 'H': 'F',
'I': 'G', 'J': 'H', 'L': 'I', 'L': 'J', 'M': 'K', 'N': 'L',
'O': 'M', 'P': 'N', 'Q': 'O', 'R': 'P', 'S': 'Q', 'T': 'R',
'U': 'S', 'V': 'T', 'W': 'U', 'X': 'V', 'Y': 'W', 'Z': 'X',
'A': 'Y', 'B': 'Z',
#Alphabets which are Lowercase
'c': 'a', 'd': 'b', 'e': 'c', 'f': 'd', 'g': 'e', 'h': 'f',
'i': 'g', 'j': 'h', 'l': 'i', 'l': 'j', 'm': 'k', 'n': 'l',
'o': 'm', 'p': 'n', 'q': 'o', 'r': 'p', 's': 'q', 't': 'r',
'u': 's', 'v': 't', 'w': 'u', 'x': 'v', 'y': 'w', 'z': 'x',
'a': 'y', 'b': 'z',
}
# Now code for getting the converted output ie. "The Encrypted Code"
decrypted_code = ""
for x in range(0, len(encrypted_code)):
if encrypted_code[x] in conversion_table_ka_code.keys():
decrypted_code += conversion_table_ka_code[encrypted_code[x]]
else:
decrypted_code += encrypted_code[x]
# Printing our Encrypted code output (\n is used for new line)
print("Decrypting your Hidden Message...")
time.sleep(2)
print("\nUser's given Encrypted Code was: ", encrypted_code)
print("The Decrypted Code for it will be: ", decrypted_code)
print("\n------This code is made by Gibran Khan Tareen------") | true |
4f669745b1cd0f7ded2c27e089c06460ac26e763 | twdockery/PythonProgramming | /DOCKERY-lab11p1-CSC121.py | 1,848 | 4.625 | 5 | #Tyler Dockery for CSC121 twdockery@waketech.edu 7-9-2020
# ----------------------------------------------------------------
# Author: Tyler Dockery
# Date:
#
# This program is about sets. Write a Python program to do the following:
# (a) Generate 5 random integers between 1 and 10, inclusive. Store the random integers in a set named set1. Display the set. Please note that the set may have less than 5 elements because some of the random integers generated may be redundant.
# (b) Generate 5 random integers between 1 and 10, inclusive. Store the random integers in another set named set2. Display the set. Please note that the set may have less than 5 elements because some of the random integers generated may be redundant.
# (c) Find and display the union of set1 and set2.
# (d) Use set comprehension to select odd numbers from the union and store them in a set. Display this set.
# (e) Find and display the intersection of set1 and set2.
# (f) Find and display the symmetric difference of set1 and set2.
#
# The following is an example.
# set1: {9, 10, 1, 7}
# set2: {8, 1, 7}
# Union of set1 and set2: {1, 7, 8, 9, 10}
# Odd numbers in union of set1 and set2: {1, 9, 7}
# Intersection of set1 and set2: {1, 7}
# Symmetric difference of set1 and set2: {8, 9, 10}
# ----------------------------------------------------------------
from random import randint
set1 = set()
set2 = set()
for everyitem in range(5):
set1.add(randint(1,10))
set2.add(randint(1,10))
def odds(a,b):
odd_set = a | b
# Using list comprehension on the union
return [x for x in odd_set if x % 2 == 1]
print("set1:",set1)
print("set2:",set2)
print("Union of set1 and set2:", set1 | set2)
print("Odd numbers in union of set1 and set2:", odds(set1,set2))
print("Intersection of set1 and set2:", set1 & set2)
print("Symmetric difference of set1 and set2:", set1 ^ set2) | true |
873050a88f42dfac5bf5fc52fc054a7bdb9acc13 | twdockery/PythonProgramming | /Extra points for low scores.py | 1,894 | 4.15625 | 4 | # Tyler Dockery for CSC121 5-23-2020 twdockery@waketech.edu
"""
A teacher wants a program to give extra points to students who fail a test. Write a Python program to do the following:
• Ask the user to enter 5 test scores. Store the scores in a list. Display the list.
• Copy all 5 test scores to another list. Use a loop to examine each test score in the new list. If the score is below 60, add 10 extra points to the score. Display the list.
• Compare the old score and new score of each student. If the old score and new score are different, display the two scores.
The following is an example.
Enter a test score: 45
Enter a test score: 77
Enter a test score: 88
Enter a test score: 52
Enter a test score: 90
All scores: [45.0, 77.0, 88.0, 52.0, 90.0]
Students who scored below 60 get 10 extra points.
All scores: [55.0, 77.0, 88.0, 62.0, 90.0]
Students whose scores have changed:
Old score: 45.0 New score: 55.0
Old score: 52.0 New score: 62.0
"""
scores =[]
for i in range(5):
scores.append(float(input("Enter a test score: "))) # ask for 5 scores, store them
print("All scores: ",scores)
print("\033[1mStudents who scored below 60 get 10 extra points. \033[0m") #bold for fun
#copy list and +10 pts if 59 or lower
new_scores = [] #create a new list
for everyitem in scores:
if everyitem >= 60:
new_scores.append(everyitem) # if score 60+ add to new list
else:
new_scores.append(everyitem + 10) # if score < 60, add 10 then add to new list
print("All scores: ",new_scores)
# compare lists
print("\033[1mStudents whose scores have changed: \033[0m") #bold for fun
if scores is not new_scores:
for everyitem in range(len(scores)):
if scores[everyitem] != new_scores[everyitem]:
print(f"Old Score: {scores[everyitem]} New Score {new_scores[everyitem]}")
else:
print("No grades have changed. ") #just in case no scores have changed
| true |
7fa9891fd709b28e7003dff66f401636fe148f78 | twdockery/PythonProgramming | /test.py | 737 | 4.125 | 4 | list1 = []
dictionary1 = {}
master_string = input("enter a string: ")
for everyletter in master_string:
if everyletter.isalpha():
list1.append(everyletter.upper())
#print(list1) #debug to see it worked
# list1 now has every letter of the master_string
for everyletter in list1:
if everyletter not in dictionary1:
a = everyletter
b = list1.count(everyletter)
dictionary1[a] = b
print(dictionary1)
"""
from collections import Counter
dictionary1 = Counter(master_string)
print(Counter(master_string))
"""
s=input()
t=s.lower()
for everyletter in range(len(master_string)):
b=master_string.count(master_string[everyletter])
print("{} -- {}".format(master_string[everyletter],b)) | true |
9916b11b07d994de08b8468b26b8d6128f191c72 | twdockery/PythonProgramming | /Prime-number-test.py | 345 | 4.125 | 4 | def is_prime(num):
factor = num
for i in range(1,num):
num -= 1
if factor % num == 0:
print("This number is NOT prime. %s is a factor of %s" % (num, factor))
break
else:
if num == 1:
print("This number is a PRIME")
is_prime(int(input("what is your number: "))) | true |
aaf9f30aee1ff61d1f22e979517e9fe34a3fc7b1 | twdockery/PythonProgramming | /DOCKERY-LAB06p03-CSC121.py | 2,040 | 4.53125 | 5 | # Tyler Dockery for CSC121 5-23-2020 twdockery@waketech.edu
"""
Write a Python program to do the following:
• Use a for loop and a random integer generator to generate 10 random integers in 1 through 15. Store the random integers in a tuple. Display the tuple. [Hint: you may want to store the random integers in a list first and then convert the list to a tuple]
• Create a new tuple. Copy the first three elements of the tuple in part (a) to this tuple. Display this tuple.
• Create a new tuple. Copy the last three elements of the tuple in part (a) to this tuple. Display this tuple.
• Concatenate the two tuples in part (b) and part (c). Display the concatenated tuple.
• Sort the concatenated tuple. Display the sorted tuple.
The following is an example. There is no user input in this program.
Tuple of 10 random numbers: (12, 3, 4, 7, 5, 9, 7, 3, 1, 7)
Tuple of first 3 numbers: (12, 3, 4)
Tuple of last 3 numbers: (3, 1, 7)
Two tuples concatenated: (12, 3, 4, 3, 1, 7)
Two tuples concatenated and sorted: (1, 3, 3, 4, 7, 12)
"""
from random import randint
list1 = []
# [Hint: Store the random integers in a list first and then convert the list to a tuple]
for x in range(10): #Generate 10 random integers in 1 through 15.
list1.append(randint(1,15)) # Storing in a list because tuples cannot be altered
# print(list1) # just a debug area
# Store the random integers in a tuple. Display the tuple.
tuple10 = list1[0:10] # all 10 randoms stored
tuple10 = tuple(tuple10)
tuple3 = tuple(tuple10[0:3]) # list item
tuplel3 = tuple(tuple10[7:10]) # list item from (length -3 to length)
tuplecon = tuple(tuple3 + tuplel3) # tuple first 3 + tuple last 3 concatenated
tupleconsort = tuple(sorted(tuplecon)) # concatenated tuple sorted
print("Tuple of 10 random numbers:",tuple10)
print("Tuple of first 3 numbers: ",tuple3)
print("Tuple of last 3 numbers: ",tuplel3)
print("Two tuples concatenated: ",tuplecon)
print("Two tuples concatenated and sorted: ",tupleconsort) | true |
5da9f14d5d605c1e52990634413981d360d6a5d3 | twdockery/PythonProgramming | /Range and sequence.py | 601 | 4.3125 | 4 | #Tyler Dockery for CSC121 5-22-2020 twdockery@waketech.edu
"""
Write a Python program to do the following:
• Use the range function to generate this sequence of integers: 5, 9, 13, 17, 21. Use a for loop to display this sequence.
• Use the range function to generate this sequence of integers: 26, 19, 12, 5. Use a for loop to display this sequence.
The following is the expected output. There is no user input in this program.
First Sequence:
5
9
13
17
21
Second Sequence:
26
19
12
5
"""
print("First Sequence")
for i in range(5,22,4):
print(i)
print("Second Sequence")
for i in range(26,4,-7):
print(i) | true |
de10a4fce285963f70de35ecfba705d1e076b874 | antonyalexcm/Bridgelabz_updated | /Functional_programming/Quadratic.py | 587 | 4.125 | 4 |
from math import sqrt
def quadratic(a,b,c):
delta = b*b - 4*a*c
if delta >= 0:
root1 = (-b + sqrt(delta))/(2*a)
root2 = (-b - sqrt(delta))/(2*a)
return root1, root2
elif delta < 0 :
print("\n Complex number solution!!!!")
if __name__ == "__main__":
print("The equation is in the form ax^2 + bx + c !!!")
a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
c = float(input("Enter the value of c: "))
sol = quadratic(a,b,c)
print("\nThe roots of the equation are:", sol)
| true |
41d8a74ce0d143ce5255edc890621d7d269a22eb | vasujain/Pythonify | /lib109.py | 444 | 4.15625 | 4 | #!/usr/bin/env python
"""Prints the decimal equivalent of a binary string."""
binaryString = "110110011"
decimalInt = 0
counter = 0
for ch in binaryString :
if ch not in "01":
print "invalid input"
break
else:
for ch in reversed(binaryString) :
decimalInt += pow(2, counter) * int(ch)
# print int(ch), counter, pow(2, counter), bin
counter = counter +1
print "decimal value is", decimalInt
| true |
3d61b09e740579ceace57ff4794e0484dedc26c6 | normanpilusa/TOA | /roots.py | 499 | 4.375 | 4 | #Program to find all the square roots of a number x under arithmetic modulo n.
#It finds all the integers a, 0 < a < n, such that a^2 = x mod n.
import sys
def roots(x, n):
mod = x % n
roots = ""
for number in range(n):
square = number*number
if(square == mod):
roots += str(number) + " "
elif(square > n):
if square % n == mod: roots += str(number) + " "
return roots
if __name__ == '__main__':
n = int(raw_input())
x = int(raw_input())
print roots(x, n)
| true |
34bdaccb7098ddacc5f191a46f44110bfa6e7287 | JavierSLX/Python-Platzi | /12-slices-strings.py | 231 | 4.125 | 4 | # Se pueden obtener substrings con los slices
string = 'platzi'
print(string[1:])
print(string[1:3])
# De toda la cadena en saltos de 2 myString[inicio:final:saltos]
print(string[1:6:2])
# Invertir la cadena
print(string[::-1]) | false |
cca024de7e57665b0af4af96562ca95e4446694c | GetulioCastro/codigo_livro_aprenda_python_basico | /09-sets/09-sets.py | 1,307 | 4.34375 | 4 | # Código utilizado no livro Aprenda Python Básico - Rápido e Fácil de entender, de Felipe Galvão
# Mais informações sobre o livro: http://felipegalvao.com.br/livros
# Capítulo 9: Sets
# Criando nossos primeiros sets
lista1 = ["Luiz", "Alfredo", "Felipe", "Alfredo", "Joana", "Carolina", "Carolina"]
set1 = set(lista1)
print(set1)
set2 = {"cachorro", "gato", "papagaio", "cachorro", "papagaio", "macaco", "galinha"}
print(set2)
# Criando um set a partir de uma string
set3 = set("papagaio")
print(set3)
# Criando uma lista sem duplicatas através dos sets
lista2 = ["Luiz", "Alfredo", "Felipe", "Alfredo", "Joana", "Carolina", "Carolina"]
lista_sem_duplicatas = list(set(lista2))
print(lista_sem_duplicatas)
# Removendo um item do set
print(set2)
set2.remove("cachorro")
print(set2)
# Funções úteis para se trabalhar com sets
print(len(set2))
print("gato" in set2)
print("elefante" in set2)
set4 = {"Luiz", "Alfredo", "Joana", "Felipe", "Mauro"}
set5 = {"Joana", "Carolina", "Afonso", "Carlos", "Mauro"}
print(set4.difference(set5))
print(set4.intersection(set5))
set_backup = set4
print(set_backup)
set4.clear()
print(set_backup)
set()
set4 = {"Luiz", "Alfredo", "Joana", "Felipe", "Mauro"}
set_backup = set4.copy()
print(set_backup)
set4.clear()
print(set_backup) | false |
0a2598c60d6492c5e4e15760cb913022ae94aebc | GetulioCastro/codigo_livro_aprenda_python_basico | /15-excecoes/15-excecoes.py | 1,457 | 4.375 | 4 | # Código utilizado no livro Aprenda Python Básico - Rápido e Fácil de entender, de Felipe Galvão
# Mais informações sobre o livro: http://felipegalvao.com.br/livros
# Capítulo 15: Exceções
print("Vamos dividir dois números inseridos por você\n")
num1 = input("Insira o primeiro número: ")
num2 = input("Insira o segundo número: ")
# resultado = int(num1) / int(num2)
# print("O resultado é " + str(resultado))
# try:
# resultado = int(num1) / int(num2)
# print("O resultado é " + str(resultado))
# except ZeroDivisionError:
# print("O segundo número não pode ser zero")
# except ValueError:
# print("Você deve inserir dois números")
# try:
# resultado = int(num1) / int(num2)
# print("O resultado é " + str(resultado))
# except:
# print("Uma das entradas é inválida. Favor inserir dois números, sendo o segundo diferente que zero")
# Blocos else e finally em exceções
try:
resultado = int(num1) / int(num2)
print("O resultado é " + str(resultado))
except ZeroDivisionError:
print("O segundo número não pode ser zero")
except ValueError:
print("Você deve inserir dois números")
else:
print("Divisão feita!")
finally:
print("Programa concluído")
# Chamando exceções dentro do seu código com "raise"
nome = input("Qual o seu nome? ")
try:
if nome == "Felipe":
raise NameError("Não gostei do seu nome")
print("Olá, %s" % nome)
except NameError:
print("O programa não gostou do seu nome") | false |
85c69b4a2beb073b750c861c1c4a65bbe2827672 | abhijithshankar93/coding_practise | /DailyCodingProblem/day3.py | 2,047 | 4.25 | 4 | '''Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given the root to a binary tree, implement serialize(root), which serializes
the tree into a string, and deserialize(s), which deserializes the string
back into the tree.
For example, given the following Node class
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
The following test should pass:
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
'''
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def print_tree(self, root):
'''Pre-order'''
if root:
print root.val
self.print_tree(root.left)
self.print_tree(root.right)
def serialize(root, s=[]):
'''
Crux of problem: How to identify the edges of the tree
We serealize by following the pre-order traversal (actually any will work
as long as same technique is used while deserializing) technique
When we hit the end of the tree(when we hit None) we add a special
MARKER (this case '/') to the list. This way, when we try reconstructing
back the tree we can exactly figure out the edges of the tree.
'''
if root is None:
s.append('/')
return
s.append(root.val)
serialize(root.left, s)
serialize(root.right, s)
return s
def deserialize(s):
'''
Crux of problem: Same as above; key is to figure out the edges
As we serialized, we run through the list and removing each element as we
construct the tree.
Every time we hit the marker('/' in this case) we return bactrack as this
signifies an edge of the tree
'''
val = s.pop(0)
if len(s) < 1 or val == '/':
return None
node = Node(val)
node.left = deserialize(s)
node.right = deserialize(s)
return node
node = Node('root', Node('left', Node('left.left')), Node('right'))
assert deserialize(serialize(node)).left.left.val == 'left.left'
| true |
3c11ccf79f2b6985ce31a3876da473d622047210 | bf109f/python | /helloword/test_1/test_list.py | 466 | 4.25 | 4 | """
列表 for循环
"""
list_name = ["张三", "李四", "王五"]
"""
迭代:顺序的从列表中获取数据,每一次循环过程中数据都会保存在name这个变量中
"""
for name in list_name:
print(name)
# list_name.remove()
# print(list_name)
def demo(num_list):
"""
列表的 += 操作 相当于 num_list.extend()
:param num_list:
:return:
"""
num_list += num_list
gl_list = [1, 2, 3]
demo(gl_list)
print(gl_list)
| false |
e955d560127a266ca83de75d488d15b5bb9b8477 | yang1006/PythonLearning | /testPython/class5_funtionnal_programming/python5_5_partial_function.py | 1,341 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 偏函数 Partial function
print(int('12345')) # 默认按10进制转换
print(int('12345', base=8)) # base参数,按 N 进制转换
print(int('12345', base=16)) # 按16进制转换
# 转换大量的二进制字符串,每次都传入int(x, base=2)非常麻烦,于是,我们想到,可以定义一个int2()的函数,默认把base=2传进去
def int2(x, base=2):
return int(x, base=base)
print(int2('10'))
# functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2(),可以直接使用下面的代码创建一个新的函数int2:
# 简单总结functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单
import functools
int2 = functools.partial(int, base=2)
print(int2('10'))
print(int2('10', base=10)) # 依然可以传入其他值
# 创建偏函数时,实际上可以接收函数对象、*args 和 **kw 这3个参数,当传入:
# int2 = functools.partial(int, base=2)
# 相当于:
# kw = { 'base': 2 }
# int('10010', **kw)
# 当传入
max2 = functools.partial(max, 10)
# 时,实际上会把10作为*args的一部分自动加到左边
max2(5, 6, 7) # 相当于
args = (10, 5, 6, 7)
max(*args)
| false |
72dea5b07e4ee637d714c1a99b43913c5445e9bb | yang1006/PythonLearning | /testPython/class5_funtionnal_programming/higher_order_function/python5_1_3_sorted.py | 757 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# sorted 排序算法
l = [1, 5, 2, -10, 29, 56, -33]
print(sorted(l))
print(sorted(l, key=abs))
l1 = ['bob', 'about', 'Zoo', 'Credit']
print(sorted(l1))
print(sorted(l1, key=str.lower))
# 反向排序
print(sorted(l1, key=str.lower, reverse=True))
# exercise 一组tuple表示学生名字和成绩: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# 用sorted()对上述列表分别按名字排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
if isinstance(t, tuple):
return str(tuple(t)[0]).lower()
def by_score(t):
if isinstance(t, tuple):
return int(-tuple(t)[1])
print(sorted(L, key=by_name))
print(sorted(L, key=by_score))
| false |
a05aa113e58c968d9be7051823d600369cbb3901 | OksKV/python | /Lesson2/Task3.py | 1,290 | 4.1875 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
# Dictionary method
seasons = {'winter': {12: 'December', 1: 'January', 2: 'February'}, 'spring': {3: 'March', 4: 'April', 5: 'May'},
'summer': {6: 'June', 7: 'July', 8: 'August'}, 'autumn': {9: 'September', 10: 'October', 11: 'November'}}
def which_season():
month = int(input('Please insert a number from 1 to 12'))
if 1 <= month <= 12:
for item, season in seasons.items():
if month in season:
print(f'{season[month]} is a month of {item}')
break
else:
continue
else:
print('Incorrect number, please try again!')
which_season()
which_season()
# List method
seasons = {'winter': [12, 1, 2], 'spring': [3, 4, 5], 'summer': [6, 7, 8], 'autumn': [9, 10, 11]}
month = int(input('Please insert a number from 1 to 12'))
for season in seasons:
if month in seasons[season]:
print(f'It is a month of {season}')
break
else:
continue
| false |
e86a6262546564a723cf8b77d864bb47d2048bcc | ArianaMikel/CSE | /notes/Lists Notes.py | 2,418 | 4.46875 | 4 | # Creating Lists
'''
colors = ["blue", "turquoise", "pink", "orange", "black","red", "green", "purple", "violet", "black", "brown","grey" ] # USE SQUARE BRACKETS
print(colors)
print(colors[1])
print(colors[0])
# Length of the list
print("There are %d things in the list." % len(colors))
# Changing Elements in a list
colors[1] = "green"
print(colors)
# Looping through lists
for item in colors:
print(item)
1. Make a list with 7 items
2. change the 3rd thing in the list
3. print the item
4. print the full list
new_list = ["work", "school", "home", "supermarket", "restaurant", "beach", "prison"]
new_list[2] = "desert"
print(new_list)
print("The last thing in the list is %s" % new_list[len(new_list)-1])
# Slicing a list
print(new_list[1:3])
print(new_list[1:4])
print(new_list[1:])
print(new_list[:6])
'''
food_list = ["pizza", "enchiladas", "popcorn", "chicken", "cupcake", "cake", "cookies", "rice","noodles", "meatball",
"clam chowder", "hamburger","chicken wings","salad", "french fries","salmon", "alfredo","garlic bread",
"shrimp", "carne asada", "chili", "bread"]
print(len(food_list))
# Adding stuff to a list
food_list.append("bacon")
food_list.append("eggs")
# Notice that everything is object.method(parameters)
print(food_list)
food_list.insert(1, "eggo waffles")
print(food_list)
# Removing things from a list
food_list.remove("salad")
print(food_list)
'''
ari_list = ["pretzels", "pizza", "pie"]
print(ari_list)
ari_list.append("pecan")
print(ari_list)
ari_list.remove("pretzels")
print(ari_list)
# Tuples
brands = ("apple", "samsung", "HTC") # Noctice the parentheses, this is a tuple it cannot be changed,
#it is immutable, not a list
'''
# Also removing stuff from a LIST
print(food_list)
food_list.pop(0)
print(food_list)
# Find the index of an item
print(food_list.index("chicken"))
# Changing things into a list, extremely handy para hangman
string1 = "turquoise"
list1 = list(string1)
print(list1)
# Turn a list into a string
print("".join(list1))
for i in range (len(list1)): # i goes through all indicies
if list1[i] == "u": # if we find a U
list.pop(i) # remove the i-th index
list.insert(i, "*") # Put a * there instead
'''
for character in list1:
is character == "u":
# replace with a *
current_index = list1.index(character)
list1.pop(current_index)
list1.insert(current_index, "*")
'''
| true |
6385287ace0ebe8ec4c9dc4895494cd61f3ee381 | roagabriel/SEII-Gabriel-Oliveira | /semana02/prog02.py | 1,683 | 4.25 | 4 | # Working with Numeric Data
# -------------------------------------------------------------
# Arithmetic Operators:
# Addition: a + b
# Subtraction: a - b
# Multiplication: a * b
# Division: a / b
# Floor Diviaion: a // b
# Exponent: a ** b
# Modulus: a % b
# -------------------------------------------------------------
# Short commands:
# a = a + b or a += b
# a = a - b or a -= b
# a = a * b or a *= b
# a = a / b or a /= b
# a = a // b or a //= b
# a = a ** b or a **= b
# a = a % b or a %= b
# -------------------------------------------------------------
# Comparisons:
# Equal: a == b
# Not Equal: a != b
# Greater Than: a > b
# Less Than: a < b
# Greater or Equal: a >= b
# Less or Equal: a <= b
# -------------------------------------------------------------
a = 13
b = 5
c = 5
print("-------------------------------------------------------------")
print(type(a))
print("-------------------------------------------------------------")
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a ** b)
print(a % b)
print("-------------------------------------------------------------")
print(a * b - c)
print(a * (b - c))
print("-------------------------------------------------------------")
print(abs(-a))
print(round(a+0.75))
print(round(a+0.75,1))
print("-------------------------------------------------------------")
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
print("-------------------------------------------------------------")
a = "100"
b = "200"
print(a + b)
a = int(a)
b = int(b)
print(a + b)
| false |
4ac7f09a58961422efb15d1ace47fd3040e7d1a4 | sayalikarnewar/HackerRank-Solutions | /CountOfCharacter.py | 254 | 4.34375 | 4 | #Write a Python program to count the number occurrence of a specific character in a string.
char = input()
string = "my name is anthony gonsalvis."
string = list(string)
count = 0
for i in string:
if i == char:
count+=1
print(count)
| true |
5a64f7af9a8486db227b23cc5508c749fe133f19 | jfangwang/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 238 | 4.125 | 4 | #!/usr/bin/python3
def uppercase(str):
willy = ""
for a in str:
if ord(a) >= 97 and ord(a) <= 122:
a = ord(a) - 32
willy += chr(a)
else:
willy += a
print("{}".format(willy))
| false |
b160489ad904dbec612906caefabcd07dd61f64d | jfangwang/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 383 | 4.125 | 4 | #!/usr/bin/python3
"""asdf"""
class Square:
"""__init__ method
The __init__ method intializes a size of the square
Note:
This is annoying and I am gonna have to learn this and I
understand why this is necessay.
Attributes:
size (int): A private value defining the square
"""
def __init__(self, size):
self.__size = size
| true |
c10bb332ecfd4cea4afcb192da7ff8932180922f | jfangwang/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 1,632 | 4.375 | 4 | #!/usr/bin/python3
"""
Class Square
"""
class Square:
"""
Class Square
"""
def __init__(self, size=0):
"""__init__ method
Intializes everything
Args:
size: the size
"""
self.__size = size
@property
def size(self):
"""
Getter
"""
return self.__size
@size.setter
def size(self, value):
"""
Setter
Attributes:
value (int): A private value defining the square
Rasies:
TypeError: If size is not an int
ValueError: If size < 0
"""
if type(value) is not int:
raise TypeError("size must be a number")
elif value < 0:
raise ValueError("size must be >= 0")
self.__size = value
def area(self):
"""
area
Returns:
Returns the area
"""
return self.__size ** 2
def __lt__(self, value):
"""
Less Than
"""
return self.size < value.size
def __le__(self, value):
"""
Less Than Equal
"""
return self.size <= value.size
def __eq__(self, value):
"""
Equal
"""
return self.size == value.size
def __ne__(self, value):
"""
Not Equal
"""
return self.size != value.size
def __gt__(self, value):
"""
Greater Than
"""
return self.size > value.size
def __ge__(self, value):
"""
Greater Than Equal
"""
return self.size >= value.size
| true |
6319fe787900b443399ec7970f7c50a2e479afab | jcattanach/9-20-18 | /calc.py | 1,966 | 4.3125 | 4 |
### MATH FUNCTIONS
def add_function(first_number, second_number):
return first_number + second_number
def sub_function(first_number, second_number):
return first_number - second_number
def mul_function(first_number, second_number):
return first_number * second_number
def div_function(first_number, second_number):
return first_number / second_number
def operator_selector(first_number,operator,second_number):
correct_operator = True
if(operator == '+'):
result = add_function(first_number,second_number)
elif(operator == '-'):
result = sub_function(first_number,second_number)
elif(operator == '*'):
result = mul_function(first_number,second_number)
elif(operator == '/'):
result = div_function(first_number,second_number)
else:
correct_operator = False
print("Select a valid operator")
operator = input("Enter a mathmatical operator (+,-,/,*): ")
result = operator_selector(first_number, operator, second_number)
if(correct_operator == True):
display_result(first_number,operator,second_number,result)
def display_result(first_number,operator,second_number,result):
print('-------------------------')
print(' {0} {1} {2} = {3}'.format(first_number, operator, second_number, result))
print('-------------------------')
while True:
print("************** WELCOME TO CALCULATOR **************")
choice = input("Press 'q' to quit or 'enter' to continue: ").lower()
if(choice == 'q'):
break
try:
first_number = int(input("Choose your first number: "))
operator = input("Enter a mathmatical operator (+,-,/,*): ")
second_number = int(input("Choose your second number: "))
operator_selector(first_number, operator, second_number)
except ValueError:
print("You did not enter a valid number")
print("************ YOU HAVE EXITED CALCULATOR ************")
| false |
ae464555d157edbf888a9c051c71b14e17aee810 | muneeb1994/Movie-Catalogue-System | /Movie Catalogue - Class.py | 2,030 | 4.34375 | 4 | class Movie:
__price_with_gst = 0
def __init__(self,name, category, description, price):
"""this is the constructor which is used to initialize the attributes"""
self.name = name
self.category = category
self.description = description
self.price = price
def __calculatePriceWithGST(self,price):
""" this private method is used to calculate the price with gst"""
return (float(self.price) * 1.07)
def getName(self):
""" this method is used to return the name of movie"""
return self.name
def getCategory(self):
""" this method is used to return the category of movie"""
return self.category
def getDescription(self):
""" this method is used to return the description of movie"""
return self.description
def getPrice(self):
""" this method is used to return the price of movie"""
return self.price
def getPriceWithGST(self):
""" this method is used to return the price with gst of movie"""
self.__price_with_gst = self.__calculatePriceWithGST(self.price)
return self.__price_with_gst
def __repr__(self):
"""this method return the detail of movie in the form of list"""
return [self.name,self.category,self.description,self.price]
def __add__(self, more_price):
""" this magic method is used when we need to increase the price of movie """
return float(self.price) + float(more_price)
# Testing
if __name__ == "__main__":
mov = Movie("Avengers","Adventure","Action based super hero movie","2")
assert mov.getName() == "Avengers", "This is not the right movie name"
assert mov.getCategory() == "Adventure","Wrong Category"
assert mov.getDescription() == "Action based super hero movie","Wrong info."
assert mov.getPrice() == "2"
assert mov.getPriceWithGST() == 2.14, "Wrong Price"
assert mov + 20 == 22 # test __add__ method
| true |
8273ce6c3ab0e60338f2d308b8a6e97e58ec9bc5 | valentinegarikayi/Getting-Started- | /String_Lists.py | 339 | 4.34375 | 4 | #!/usr/bin/env python
#this is the solution to:
#http://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
# here I attempt reversing the string using double colon and it works
user=input('Please give me a string:')
back =user[::-1]
if back==user:
print('This is a palindrome')
else:
print('This is not a palindrome')
| true |
622c0f1b2765110b41b2902c5ab061f658dbd678 | sillyfellow/rosalind | /stronghold/b001_count_dna_nucleotides.py | 1,056 | 4.3125 | 4 | #!/usr/bin/python
#Problem
#A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.
#An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG."
#Given: A DNA string s of length at most 1000 nt.
#Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s.
#import rosalib
def count_dna_nucleotides(string):
d = {}
for base in string:
d[base] = 1 + d.get(base, 0)
return d
def print_nucleotide_count(d):
for b in 'ACGT':
print d.get(b, '0'),
def main(filename):
with open(filename) as f:
d = count_dna_nucleotides(f.read())
print_nucleotide_count(d)
def Usage(name):
print "Usage: %s <filename>" % name
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
Usage(sys.argv[0])
else:
main(sys.argv[1])
| true |
cb258b3760758dd2b241a0160ef39328ab531ec5 | deepakr6242/caramel | /demo/static/admin/js/inheritance.py | 1,176 | 4.21875 | 4 | # Inheritance
# Types of Inheritance
# Polymorphism
# Method Overriding
# ethod Overloading
# Examples of Access Identifiers
#Multilevel Inheritance
class Home:
def living(self):
return ("Living Room built")
class Bungalow():
def garden(self):
return("portico built")
class Palace():
def garden(self):
return("Palace built with garden ")
#
def foo():
print(1)
def foo():
print (2)
foo()
obj=Palace()
obj1=Bungalow()
# # print (obj)
print (dir(obj))
# print (obj.living())
# print (obj.portico())
print (obj.garden())
print(obj1.garden())
# # class Second_Palace(Home,Bungalow):
# # def porttrt(self):
# # print("porttrt ")
# obj=Palace()
# obj.living()
# obj.portico()
# obj.garden()
# # sec =Second_Palace()
# # sec.porttrt()
# class Father():
# def driving(self):
# print("Father Driving")
# class Son(Father):
# def driving(self):
# print("Pillion rider")
# # ob=Son()
# # ob.driving()
# ob=Father()
# ob.driving()
# # print(Father.__dict__)
# # print (Son.__dict__)
def foo():
print(1+2)
def bar():
print("asas"+"heehhe")
| false |
e0fa21bab9453a7886720792cefa62c7284bf495 | MarkJParry/MyGMITwork | /Week08/matplotlibLab.py | 1,056 | 4.53125 | 5 | #Filename: matplotlibLab.py
#Author: Mark Parry
#Created: 09/03/2021
#Purpose: Weekly Lab 8 using matplotlib, demonstrates how to use it
#5. Write a program that plots the function y = x**2.
import matplotlib.pyplot as mpl
import numpy as np
#Plot
xvalues = np.array(range(1,101))
yvalues = xvalues * xvalues
mpl.plot(xvalues,yvalues)
mpl.show()
#hist
salMin = 20000
salMax = 80000
ageMin = 21
ageMax = 65
arrLen = 100
#2. seeds the random numbers so that they stay the same while program is being run and tested
np.random.seed(1)
#1. program that makes a list, called salaries, that has (say 10) random numbers (20000 – 80000).
salaries = np.random.randint(salMin,salMax,arrLen)
mpl.hist(salaries)
mpl.show()
#scatter
ages = np.random.randint(ageMin,ageMax,arrLen)
mpl.scatter(ages, salaries)
mpl.show()
#mixed
mpl.scatter(ages, salaries, label="Salaries")
mpl.plot(xvalues,yvalues,color="r", label="x squared")
mpl.title("random plot")
mpl.xlabel("Salaries")
mpl.ylabel("age")
mpl.legend()
mpl.savefig("prettier-plpt.png")
| true |
fa712a530bae131939fded1f4c4d583f0964f7dc | MarkJParry/MyGMITwork | /Week04-flow/isEven.py | 293 | 4.375 | 4 | #Filename: isEven.py
#Author: Mark Parry
#Created: 08/02/2021
#Purpose: Read in a number and determine if it is even or odd
numIn=int(input("Please enter a number: "))
if numIn % 2 == 0:
print("{} is an even Number".format(numIn))
else:
print("{} is an odd Number".format(numIn)) | true |
59da9eeca37665c3333f9c2bbb7aea54014eaa4a | Frederick-S/Introduction-to-Algorithms-Notes | /src/chapter_02/merge_sort_with_insertion_sort.py | 1,317 | 4.3125 | 4 | def merge_sort_with_insertion_sort(numbers):
cutoff = 3
auxiliary = numbers[:]
merge_sort(numbers, auxiliary, 0, len(numbers) - 1, cutoff)
def merge_sort(numbers, auxiliary, low, high, cutoff):
if low < high:
if low + cutoff >= high:
insertion_sort(numbers, low, high)
return
middle = (low + high) // 2
merge_sort(numbers, auxiliary, low, middle, cutoff)
merge_sort(numbers, auxiliary, middle + 1, high, cutoff)
merge(numbers, auxiliary, low, middle, high)
def merge(numbers, auxiliary, low, middle, high):
for k in range(low, high + 1):
auxiliary[k] = numbers[k]
i = low
j = middle + 1
for k in range(low, high + 1):
if i > middle:
numbers[k] = auxiliary[j]
j += 1
elif j > high:
numbers[k] = auxiliary[i]
i += 1
elif auxiliary[i] <= auxiliary[j]:
numbers[k] = auxiliary[i]
i += 1
else:
numbers[k] = auxiliary[j]
j += 1
def insertion_sort(numbers, low, high):
for i in range(low, high + 1):
j = i - 1
key = numbers[i]
while j >= low and numbers[j] > key:
numbers[j + 1] = numbers[j]
j -= 1
numbers[j + 1] = key
| false |
2e14338bcff81586efb34cf602a97eeb2e047bea | xprasoulas/SMTP_Module | /test/main.py | 1,896 | 4.25 | 4 | import csv
import pandas as pd
# # Take the temperature from the file in a list
# with open("weather_data.csv") as file:
# data = csv.reader(file)
# temperature = []
# # Make a list from data = object of csv.reader
# for item in list(data)[1:]: # from the second row not the "temp"
# temperature.append(int(item[1]))
# print(temperature)
# Using a library call as PANDA
# data = pd.read_csv("weather_data.csv")
# # Type of data is a DataFrame = a sheet(table) of an excel file
# print(type(data))
# # Types of data is a Series = Στηλη στο excel
# print(type(data.temp))
# varo = data.to_dict()
# print(varo)
# lists = data.temp.to_list()
# print(lists)
#
# summary = data["temp"].sum()
# print(summary)
# average = summary / data.temp.size
# # # Equal with the above code
# # average= sum / data["temp"].size
#
# print(average)
#
# # Using the PANDA
# pd_average = data.temp.mean()
# print(pd_average)
#
# pd_maximum_value = data["temp"].max()
# print(pd_maximum_value)
# # Equal with
# pd_maximum_value_alternative = data.temp.max()
# print(pd_maximum_value_alternative)
#
#
# # Get data from ROW
# print(data[data.day == "Monday"])
# # Find the day of the week with the max temp
# max_temp = data.temp.max()
# # print(max_temp)
#
# print(data[data.temp == max_temp])
# # Transform temp to Fahrenheit using the Formula
# # (0°C × 9/5) + 32 = 32°F
# monday = data[data.day == "Monday"]
# fahrenheit = (int(monday.temp) * 9/5)+32
# print(f"{fahrenheit}F")
#
# # Create Dataframe from Scratch using a given dictionary
#
# data_dict = {
# "student": ["amy","Jenna", "Angela"],
# "scores": [79,55,26]
# }
# data = pd.DataFrame(data_dict)
# print(data)
# # Save to a csv
# data.to_csv("export_to.csv",columns=None)
#
data = pd.read_csv("Squirrel_Data.csv")
table = data["Primary Fur Color"].value_counts()
new_data_table = table.to_csv("colors.csv") | true |
ac3907e673fff8a1d4ccc629e4b5785e0f4826f4 | Napster56/CP1404_Practicals | /Prac03/ascii_table.py | 1,674 | 4.40625 | 4 | """
Program to convert a character to it's corresponding ASCII code and vice versa.
"""
LOWER_NUM = 33
UPPER_NUM = 127
# Gets number form user; checks for valid input and within given limits.
def get_number(LOWER_NUM, UPPER_NUM):
valid_input = False
while not valid_input:
try:
num = int(input("Enter a number between 10 and 100: "))
valid_input = True
except ValueError:
print("Please enter a valid integer.")
except:
print("Ooops! Something went wrong!")
print("The program will now close.")
while num < LOWER_NUM or num > UPPER_NUM:
print("Please enter a number between 33 and 127.")
num = int(input("Enter a number between 33 and 127: "))
return num
# Print a table showing the characters for ASCII codes between 33 and 127
def print_table():
print("Do you want to print the ASCII table from {} to {} ?".format(LOWER_NUM, UPPER_NUM))
answer = input("Enter (Y) or (N)o: ")
if answer.lower() == "y":
print("How many columns do you want in the table?: ")
for i in range(LOWER_NUM, UPPER_NUM + 1):
ascii_character = chr(i)
print("{:>5}{:>10s}".format(i, ascii_character))
else:
print("Goodbye")
def main():
user_character = input("Enter a character: ")
ascii_code = ord(user_character)
print("The ASCII code for {} is {}".format(user_character, ascii_code))
user_number = get_number(LOWER_NUM, UPPER_NUM)
print(user_number)
ascii_character = chr(user_number)
print("The character for {} is {}".format(user_number, ascii_character))
print_table()
main()
| true |
ebdc88e17c44466ee64911d92113c9c09b8d0170 | Napster56/CP1404_Practicals | /Prac02/Prac02/random_password_generator.py | 1,538 | 4.40625 | 4 | """
CP1404/CP5632 - Practical
Program generates a random password:
- gets length of password from the user
- uses lowercase characters and numerals for all passwords as a minimum
- then asks user if uppercase and/or special characters are required
"""
import random
import string
print("The password must contain lowercase characters and number; however, you may specify if you want to include \
special characters and/or uppercase characters.")
password_length = int(input("Enter the length of the password: "))
uppercase = input("Are uppercase letters required for the password: ")
special = input("Are special characters required for the password: ")
password = " "
if uppercase == "y" and special == "y":
for i in range(password_length):
characters = (string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation)
password += random.choice(characters)
elif uppercase == "n" and special == "y":
for i in range(password_length):
characters = (string.ascii_lowercase + string.digits + string.punctuation)
password += random.choice(characters)
elif uppercase == "y" and special == "n":
for i in range(password_length):
characters = (string.ascii_lowercase + string.ascii_uppercase + string.digits)
password += random.choice(characters)
elif uppercase == "n" and special == "n":
for i in range(password_length):
characters = (string.ascii_lowercase + string.digits)
password += random.choice(characters)
print(password)
| true |
d27fdb82d5b023af221f086d6994cd701607dbe6 | Napster56/CP1404_Practicals | /Prac10/print_word_recursively.py | 326 | 4.28125 | 4 | """
Program to print a word n times.
"""
word = input("Enter the word: ")
times = int(input("How many times to repeat: "))
def print_recursively(word, times):
if times == 1:
return [word]
else:
return [word] + print_recursively(times - 1, word)
print(print_recursively(word, times))
| true |
aeb566defb73a709d662ca348fa5a6f716bb71d1 | Napster56/CP1404_Practicals | /Prac03/gopherPopulationSimulator.py | 1,074 | 4.4375 | 4 | """
Program simulates the gopher population over a ten year period based on:
- initial population of 1,000
- births is a random number between 10 - 20%
- deaths is a random number between 5 - 25%
"""
import random
STARING_POPULATION = 1000
def calc_yearly_change(population, births, deaths):
current_population = population + births - deaths
return current_population
def main():
print("Welcome to the Gopher Population Simulator!\nStarting population is: 1000")
population = STARING_POPULATION
count = 0
for i in range(10):
birth_rate = random.randint(10, 20)
death_rate = random.randint(5, 25)
births = int(birth_rate * STARING_POPULATION / 100)
deaths = int(death_rate * STARING_POPULATION / 100)
current_population = int(calc_yearly_change(population, births, deaths))
population = current_population
count += 1
print("Year {}\n{}\n{} gophers were born. {} died.\nPopulation: {}\n".format(count, "*****", births, deaths,
current_population))
main()
| true |
60ab83725b0ad1491f1dd56f32e2815ef773e668 | minrk/simula-tools-meetup | /2020-02-20-githooks/list_adder/list_adder.py | 845 | 4.1875 | 4 | def add(x, y):
"""Add two numbers
Arguments
---------
x : float
First number
y : float
Second number
Returns
-------
float
The sum of x and y
"""
for arg in [x, y]:
assert isinstance(arg, float)
return float(x + y)
def add_lists(list1, list2):
"""Elementwise addition of lists
Arguments
---------
list1: list
The first list
list2 : list
The seond list
Returns
-------
list
Elementwise sum of the two lists
"""
if len(list1) != len(list2):
msg = (
"Elementwise additions of two lists of different sizes not "
f"allowed. len(list1) = {len(list1)}, len(list2) == {len(list2)}"
)
raise ValueError(msg)
return [add(x, y) for x, y in zip(list1, list2)]
| true |
97cfa9a78f70499ba94a14c0f9b260eadcd1d9b4 | 664120817/python-test | /web+多线程/协程/自定义迭代器.py | 1,059 | 4.28125 | 4 | class MyList(object):
#初始化方法
def __init__(self):
#自定义保存数据
self.items=[]
def __iter__(self):
mylist=MyListIterator(self.items)
return mylist
def addItem(self,data):
#追加保存数据
self.items.append(data)
print(self.items)
#自定义迭代器类:
class MyListIterator(object):
def __init__(self,items):
self.items=items
self.current_index=0
def __iter__(self):
pass
def __next__(self):
if self.current_index<len(self.items):
data= self.items[self.current_index]
self.current_index+=1
return data
else:
raise StopIteration #主动抛出异常 停止迭代
if __name__ == '__main__':
#创建自定义列表对象
mylist =MyList()
mylist.addItem("鲁班")
mylist.addItem("张飞")
mylist.addItem("吕布")
for value in mylist:
print(value)
mylist_iterator = iter(mylist)
value =next(mylist_iterator)
print(value) | false |
646379c79440174756918456fc6305710aad171b | cdosborn/streamline | /exampledoc.py | 2,027 | 4.5 | 4 | """
This is a Python file to demonstrate PyDoc formatting.
To add comments to a class or method, place the comment directly underneath the class or method.
If you are adding comments to an actual Python file, add the comment at the very beginning. (like here)
The comments must be enclosed in triple quotes as seen here.
This is my suggested format:
Summary: Quick summary of the class/method. Ideally no longer than about 70 columns.
Attributes:
(data type) [variables of that data type separated by commas]
(data type) [variables of that data type separated by commas]
Parameters:
(data type) [variables of that data type separated by commas]
OR
self
Parameter Notes (if necessary):
Place any special notes on the behavior of parameters here if necessary.
Returns:
(data type) [variables of that data type separated by commas]
OR
None
Return Notes (if necessary):
Place any special notes on the behavior of returned values here if necessary.
"""
from math import pi
class Circle:
"""
Summary: The Circle class creates an object with various circle properties.
Attributes:
(number) x, y, radius, circumference
(string) name
Methods:
(void) toString - prints out the object attributes
"""
def __init__(self, x, y, radius, name):
"""
Summary: Initializes a Circle.
Parameters:
(number) x, y, radius
Returns:
None
"""
self.name
self.x = x
self.y = y
self.radius = radius
self.area = pi * (radius ** 2)
self.circumference = 2 * pi * radius
def toString(self):
"""
Summary: Prints out Circle attributes to console.
Parameters:
Self
Returns:
None
"""
print "Name: " + self.name
print "Origin: (" + str(self.x) + ", " + str(self.y) + ")"
print "Radius: " + str(self.radius)
print "Area: " + str(self.circumference) | true |
adeca6d00b5def1064ba133d0a9c3b618bf0d644 | Victornguli/datastructures-and-algorithms | /algorithms/algorithms.py | 2,643 | 4.125 | 4 | """Analysis of Algorithms and Algorithmic complexities"""
# Asymptotic analysis
# Proposition 3.7: The algorithm, find max, for computing the maximum element of a list of n numbers, runs in O(n) time.
def find_max(data):
"""Find the maximum element from a non-empty python list"""
biggest = data[0] # 0(1) time
for val in data: # 0(n) -> dependent on the length of the list
if val > biggest:
biggest = val
return biggest
# Prefix averages 1 on 0(n2)
def prefix_average1(input_list):
"""Return a list such that, for all j , A[j] equals average of S[0], ... S[j] """
n = len(input_list)
prefix_avg = [0] * n
for j in range(n):
total = 0
for i in range(j + 1):
total += input_list[i]
prefix_avg[j] = total / (j + 1)
return prefix_avg
# 0(n2)
def prefix_avg2(input_list):
""""""
n = len(input_list) # Constant 0(1)
prefix_avg = [0] * n # Linear 0(n)
for j in range(n): # 0(n) too for loop computation
prefix_avg[j] = sum(input_list[0:j + 1]) / (j + 1) # The statement input_list[0:j+1] takes 0(j+1) therefore
# 0(n) too
return prefix_avg
# Linear 0(n)
def prefix_3(input_list):
n = len(input_list)
prefix_avg = [0] * n
total = 0
for j in range(n):
total += input_list[j]
prefix_avg[j] = total / (j + 1)
return prefix_avg
# Three way Disjointness
def disjoint(a, b, c):
"""Return True if there is no element common to all three arrays."""
for i in range(a):
for j in range(b):
for k in range(c):
if a == b == c:
return False
return True
# An improvement on the above 0(n3) approach is realising that you only need to check i and j against j if they match
def disjoint_2(a, b, c):
"""Return True if there is no element common to all three arrays."""
for i in range(a):
for j in range(b):
if a == b:
for k in range(c):
if a == c:
return False
return True
# Element uniqueness problem
# In the element uniqueness problem, we are given a single sequence s with n elements and asked
# whether all elements of that collection are distinct from each other
def unique1(s):
"""Return True if there are no duplicate elements in sequence s."""
for i in range(len(s)):
for j in range(i + 1, len(s)):
if s[i] == s[j]:
return False
return True # The solution is obviously 0(n2)
def unique2(s):
"""Return True if there are no duplicate elements in sequence s."""
sort = sorted(s)
for i in range(len(sort) - 1):
if s[i] == s[i + 1]:
return False
return True # Due to sorting action the complexity of this operation is 0(nlogn)
if __name__ == '__main__':
print(unique2([3, 35, 5, 6, 2, 2, 34, 54, 465, 656, 6, 73, 24, 23243, 545, 65]))
| true |
6f8ba8b33dac9ac71c4effdd9accbcc155deeb36 | BiswasAngkan/BasicPython | /Odd_EvenNo_Detection.py | 481 | 4.34375 | 4 | # Angkan Biswas
# 24.05.2020
# To decide whether a number is even or odd.
# Even number: remainder will be 0 when it is divided by 2. Example (2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 )
# Odd number : remainder will be 1 when it is divided by 2. Example (1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49)
x = input('Enter your number: ')
if (float(x) % 2) == 0:
print('Even Number.')
elif(float(x) % 2) == 1):
print('Odd Number.')
| true |
1db4d595b67d12cdc9cf4eea4edf84977e93c051 | dewoolkaridhish4/C98 | /function.py | 291 | 4.25 | 4 | def countingWords():
counting=input("ENTER A FILE NAME : ")
numberofwords=0
file=open(counting,'r')
for line in file :
word=line.split()
numberofwords=numberofwords+len(word)
print("Number Of Words = " )
print(numberofwords)
countingWords() | true |
b38be89b2266bbe8cf3b9f2dec3adc56e9f243fd | iulasbayram/Programming-Basic | /Assignment3/Assignment3.py | 2,689 | 4.21875 | 4 | # Student Name: Ismail Ulas Bayram
# Student ID: 220201040
greeting=raw_input("Welcome our company. What is your name?")
print "We are plaesed to meet you" , greeting
print "Our car list according to brands"
car_list=[['BMW',4,False,200],['Mercedes',3,False,250],['Renault',2,False,150],['Audi',3,False,180]]
print car_list
# Below that I used for loob and 2 parameters.
def sell_car(brand, car_list) :
for car in car_list:
if car[0]==brand:
if car[1]>0:
car[1]=car[1]-1
else:
print "You enter undefined brand. Please, try again."
print "Updated car list is below"
print car_list
# Below that I used two for loobs because i rented car easily with two for loob and I used 3 parameters.
def rent_car(selected_rent_brand, car_list):
for car in car_list:
for i in car:
if i == selected_rent_brand:
if (car[2] == False and car[1]>0 ):
car[2]=True
car[1]= car[1]-1
print "Updated car list is below"
print car_list
elif car[1]<0 :
print "Unfortunately, We don't have this brand yet."
elif car[2]== True:
print "This brand is rented by someone."
# Below that I used one for loob for changing situation of rent and I used 2 parameters.
def return_car(brand,car_list):
for car in car_list:
if car[0]==brand:
if car[2]== True :
car[2]= False
car[1]=car[1]+1
elif car[2]== False:
print "This brand isn't rented previously."
print car_list
# Below that I used "return" because I defined new list for executing. Apart from these, I used one for loob and 3 parameters.
# Again below that if user doesn't want to take input, He/She should write "print" before he/she calls the function.
def give_car_list(lower_horsepower,upper_horsepower,car_list):
suggested_car=[]
for car in car_list:
if lower_horsepower <= car[3] <= upper_horsepower:
suggested_car.append(car)
return suggested_car
# Below that I used for-else loob because if given values didn't sort together, the program passed to next step. I used 3 parameters.
# Again below that I used "break" because before print of updated list, not due to execute again and again, I wrote "break".
def add_car(brand,horsepower,car_list):
for car in car_list:
if car[0]== brand and car[3]== horsepower:
car[1]= car[1] + 1
break
else:
car_list.append([brand, 1, False, horsepower])
print car_list
| true |
03194ed32f2734a880abc8d41614942bfca60c43 | CodeBoss86/learning_projects | /new_project/new_password.py | 1,746 | 4.125 | 4 | import random
import secrets
# import string
# A function do shuffle all the characters of a string
# def shuffle(string):
# tempList = list(string)
# random.shuffle(tempList)
# new = ''.join(tempList)
# return new
# Generating the password randint
uppercase = chr(random.randint(65, 90))
lowercase = chr(random.randint(97, 122))
number = chr(random.randint(48, 53))
special = chr(random.randint(32, 64))
# Generate password using all the characters, in random order
# password = ''
# password = shuffle(password)
def greet_msg():
print("Welcome to cheezy random password generator")
print("Put in the number of each character you want in your password")
print(user_msg())
def user_msg():
upper = int(input("How many upper case letters:"))
lower = int(input("How many lower case letters:"))
spec = int(input("How many special characters:"))
num = int(input("How many numbers:"))
return pass_gen(upper, lower, spec, num)
def pass_gen(upper, lower, spec, num):
new_password = ''
if (upper + lower + spec + num) < 6:
print('Please enter minimum of 6 numbers.')
else:
for _ in range(upper):
new_password += uppercase
print('I want you ', new_password)
for _ in range(lower):
new_password += lowercase
print('I hate you ' + new_password)
for _ in range(spec):
new_password += special
print('hey ' + new_password)
for _ in range(num):
new_password += number
print('hello ' + new_password)
pass_word = list(new_password)
random.shuffle(pass_word)
new_pass = "". join(pass_word)
return new_pass
greet_msg()
| true |
cd68b85a65723df95e9fee98da1d8d1873d72bb5 | pudikartik/exercise | /inputage_ex1.py | 427 | 4.15625 | 4 | import datetime
today=datetime.date.today().year
birthday=input("did you have your birthday yet?(y/n): ")
age=int(input("what is your age: "))
assert age>=0, "Age has to be greater than 0"
if birthday=='y':
yearborn=today-age
else:
yearborn=today-age-1
year=yearborn+100
print 'you will turn 100 in: '+ str(year)
number=int(input("number; "))
for x in range(number):
print (number*(str(number)))+'\n'
| false |
0034d0417ca3a6a540e072e390c805a1c66a05bb | lillialjackson/pythonminigames | /pyrps.py | 2,232 | 4.25 | 4 | import random
# or from random import randint
def rps():
print('Rock...')
print('Paper...')
print('Scissors...')
print('Choose rock, paper, or scissors to determine the fate of all human kind! Best of 3!')
count = 0
human_score = 0
computer_score = 0
while human_score < 2 and computer_score < 2:
midgame_scores = f"The score is humans: {human_score}, computers: {computer_score}"
player = input('Choose silly human!').lower()
rand_num = random.randint(0, 2)
human_victory_msg = 'You Won! Humans will remain free... for now...'
comp_victory_msg = 'I Won! MUAH. HA. HA. Bring me a byte to eat slave!'
count += 1
if rand_num == 0:
computer = 'rock'
elif rand_num == 1:
computer = 'paper'
else:
computer = 'scissors'
print(f"I choose {computer}")
if player == computer:
print("It's a draw! We will play this round again!")
count -= 0
elif player == 'rock':
if computer == 'scissors':
human_score += 1
print(f"The score is humans: {human_score}, computers: {computer_score}")
else:
computer_score += 1
print(f"The score is humans: {human_score}, computers: {computer_score}")
elif player == 'paper':
if computer == 'rock':
human_score += 1
print(f"The score is humans: {human_score}, computers: {computer_score}")
else:
computer_score += 1
print(f"The score is humans: {human_score}, computers: {computer_score}")
elif player == 'scissors':
if computer == 'rock':
computer_score += 1
print(f"The score is humans: {human_score}, computers: {computer_score}")
else:
human_score += 1
print(f"The score is humans: {human_score}, computers: {computer_score}")
else:
print('Quit stalling and make your choice!')
if computer_score == 2:
print(comp_victory_msg)
if human_score == 2:
print(human_victory_msg)
| true |
cd9e975a36d6bb59685051ac02a7c56ea55ebd03 | sebastianagomez/Programming-Building-Blocks | /Week 10/milestoneShopCart_10.py | 2,333 | 4.125 | 4 | """
File: ProveAssignment_10py
Author: Sebastian Gomez
Purpose: Practicing with list indexes.
Date: 06/26/2021
"""
print("Welcome to the Shopping Cart Program!")
required = "\n\nPlease enter again you answer\n\n"
itemList = []
itemPriceList = []
newItem = ""
itemPrice = ""
def intro():
print("\nPlease select one of the following: \n1. Add item \n2. View cart \n3. Remove item \n4. Compute total \n5. Quit")
choice = input("\nPlease enter an action: ")
if choice == "1":
AddItem()
elif choice == "2":
ViewCart()
elif choice == "3":
RemoveItem()
elif choice == "4":
ComputeTotal()
elif choice == "5":
Quit()
else:
print(required)
intro()
def AddItem():
newItem = input("\nWhat item would you like to add? ")
itemList.append(newItem)
itemPrice = float(input(f"What is the price of '{newItem}'? "))
itemPriceList.append(itemPrice)
print(f"'{newItem}' has been added to the cart.")
intro()
def ViewCart():
print()
print("The contents of the shopping cart are:")
print()
for i in range(len(itemList)) and range(len(itemPriceList)):
list = itemList[i]
price = itemPriceList[i]
print(f"{i+1}. {list} - ${price:.2f}")
intro()
def RemoveItem():
changeItem = int(input("\nWhich number of item would you like to remove? "))
if changeItem < 1 or changeItem >len(itemList):
print("Sorry, that is not a valid item number.")
RemoveItem()
else:
itemList.pop(changeItem-1)
itemPriceList.pop(changeItem-1)
print("Item removed.")
intro()
def ComputeTotal():
totalAmount = sum(itemPriceList)
print(f"\nThe total price of the items in the shopping cart is ${totalAmount:.2f}")
print("\nIf you answer this question you will have a 15% discount:")
questionDiscount = input("\nIn what year was the first vision? ")
if questionDiscount == "1820":
discount = totalAmount * 0.15
formuTotal = totalAmount - discount
print("\nCongrats! You got the discount!\n")
print(f"The total price of the items in the shopping cart is ${formuTotal:.2f}")
else:
print("Sorry, that was not the answer... Maybe later.")
intro()
def Quit():
print("Thank you. Goodbye.")
intro()
| true |
9fcf228b1694384161955108a88d802a0fe8549b | BZukerman/StepikRepo | /Python_Programming/3. Functions, Dictionaries, Files, Modules/Fun_3_areas.py | 579 | 4.15625 | 4 | # Напишите функцию f(x), которая возвращает значение следующей функции, определённой
# на всей числовой прямой.
# Требуется реализовать только функцию, решение не должно осуществлять операций ввода-вывода.
#
def f3a(x):
if x <= -2:
res = 1 - (x + 2)**2
if -2 < x <= 2:
res = - x / 2
if x > 2:
res = (x - 2)**2 + 1
return(res)
print(f3a(4.5))
print(f3a(-4.5))
print(f3a(1)) | false |
78e8049f961d5b3ee8e5b2d4125bd5f1ee63e830 | brenj/solutions | /hacker-rank/python/introduction/whats_your_name.py | 342 | 4.28125 | 4 | # What's Your Name Challenge
"""
You are given the first name and the last name of a person. Your task is to
read them and print the following:
Hello firstname lastname! You just delved into python.
"""
first_name = raw_input()
last_name = raw_input()
print "Hello {0} {1}! You just delved into python.".format(
first_name, last_name)
| true |
8fd1f56f6c006c49f59978bd44a9542a32625603 | brenj/solutions | /hacker-rank/python/python-functionals/validating_email_addresses_with_a_filter.py | 653 | 4.1875 | 4 | # Validating Email Addresses With A Filter Challenge
"""
You are given an integer N followed by N email addresses. Your task is to
print a list containing valid email addresses, in lexicographic order.
A valid email address is of the format username@websitename.extension
Username can only contain letters, digits, dash and underscore. Website name
can have letters and digits. Maximum length of the extension is 3.
"""
import re
EMAIL_RE = re.compile('[-\w]+@[a-zA-Z\d]+\.[a-zA-Z]{1,3}$')
addresses = []
for _ in range(int(raw_input())):
addresses.append(raw_input())
print filter(lambda e: EMAIL_RE.match(e) is not None, sorted(addresses))
| true |
bc2a979be3950835b38f2344e233fa07fe2407b9 | brenj/solutions | /hacker-rank/python/closures-and-decorators/name_directory.py | 1,041 | 4.125 | 4 | # Name Directory Challenge
"""
You are given some information about N people. Each person has a first name,
last name, age and sex. You have to print their names in a specific format
sorted by their age in ascending order i.e. the youngest person's name should
be printed first. For two people having the same age, the printing should be
done in the order of their input.
"""
import functools
from operator import itemgetter
def with_honorifics(func):
@functools.wraps(func)
def wrapper(people):
def add_honorific(person):
first_name, last_name, gender = person
honorific = 'Mr.' if gender == 'M' else 'Ms.'
return ' '.join([honorific, first_name, last_name])
return map(
add_honorific,
[itemgetter(0, 1, 3)(person) for person in func(people)])
return wrapper
@with_honorifics
def get_names(people):
return sorted(people, key=itemgetter(2))
people = [raw_input().split() for _ in range(int(raw_input()))]
print '\r\n'.join(get_names(people))
| true |
90c2887b7233b338cb175340483f9de58740e394 | brenj/solutions | /hacker-rank/python/regex-and-parsing/detect_html_tags.py | 1,441 | 4.34375 | 4 | # Detect HTML Tags, Attributes And Attribute Values Challenge
"""
You are given an HTML code snippet of N lines.
Your task is to detect and print all HTML tags, attributes and attribute
values.
Print the detected items in the following format:
Tag1
Tag2
-> Attribute2[0] > Attribute_value2[0]
-> Attribute2[1] > Attribute_value2[1]
-> Attribute2[2] > Attribute_value2[2]
Tag3
-> Attribute3[0] > Attribute_value3[0]
-> symbol indicates that tag contains an attribute. It is immediately
followed by the name of attribute and attribute value.
> symbol acts as a separator of attribute and attribute value.
If an HTML tag has no attribute then simply print the name of the tag.
Note: Do not detect any HTML tag, attribute and attribute value, inside the
HTML comment tags (<!-- Comments -->).Comments can be multiline also.
All attributes have an attribute value.
"""
from HTMLParser import HTMLParser
class HackerRankParser(HTMLParser):
"""Parse HTML HackerRank provided tags."""
def handle_starttag(self, tag, attributes):
print tag
for attribute in attributes:
print "-> %s > %s" % attribute
def handle_startendtag(self, tag, attributes):
print tag
for attribute in attributes:
print "-> %s > %s" % attribute
def handle_comment(self, comment):
pass
parser = HackerRankParser()
parser.feed(''.join([raw_input() for _ in range(int(raw_input()))]))
| true |
1698db6119ef973e9264d657f9e0d8ed8d0e6a15 | brenj/solutions | /hacker-rank/python/introduction/print_function.py | 268 | 4.1875 | 4 | # Print Function Challenge
"""
Read an integer N. Without using any string methods, try to print the
following: 1,2,3.....N
Note that "....." represents the values in between.
"""
from __future__ import print_function
print(*range(1, int(raw_input()) + 1), sep='')
| true |
a9117c359bc0210a57d150c691cd930a3f49afa7 | amirtori/Python | /Ass5/Assignment5.py | 396 | 4.1875 | 4 | from functions import *
comments = """
Press 1 for the option reverse:
Press 2 for the option password:
Press 3 for the option cryptography:"""
print (comments)
userinput = input()
loop = True
while loop == True:
if userinput == "1":
reverse()
elif userinput == "2":
password()
elif userinput == "3":
cryptography()
print(comments)
userinput = input()
| true |
cbedc2a14b068c3860e646fbdec51ea1db48f5e9 | ryan-jr/Side-Projects | /FizzBuzzProblems/FCCAdvancedAlgoInventory.py | 2,303 | 4.125 | 4 | """
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
// If item from arr2 is already in arr1, update the arr1 quantity
// else add the item from arr2 to arr1
return arr1;
}
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);
"""
def flattenList(nestedList):
"""Takes in a nested list and returns a flattened list
Args:
nestedList: The nested list in question
Returns:
flatList: A flattned list
Raises:
N/A
"""
flatList = []
for sublist in nestedList:
for item in sublist:
flatList.append(item)
return flatList
def updateInventory(arr1, arr2):
# If item from arr2 is already in arr1, update the arr1 quantity
# else add the item from arr2 to arr1
arr1 = flattenList(arr1)
arr2 = flattenList(arr2)
numList = []
stuffList = []
for x in arr1:
if type(x) == int:
numList.append(x)
else:
stuffList.append(x)
x = dict(zip(stuffList, numList))
print(list(x))
del numList[:]
del stuffList[:]
for y in arr2:
if type(y) == int:
numList.append(y)
else:
stuffList.append(y)
y = dict(zip(stuffList, numList))
print(y)
otherList = []
for k, v in x.items():
if k in y:
inventory = y.get(k)
print(inventory)
x[k] += inventory
dictlist = []
for key, value in x.items():
temp = [key,value]
dictlist.append(temp)
for k, v in y.items():
if k not in x:
temp = [k, v]
dictlist.append(temp)
for item in dictlist:
a, b = item[0], item[1]
item[0] = b
item[1] = a
a, b= dictlist[3], dictlist[4]
dictlist[3] = b
dictlist[4] = a
print(dictlist)
# Turn arr1 into a dictionary with k, v pairs
curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]]
newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]]
updateInventory(curInv, newInv) | true |
e40499b93beeadee7ff321b1102f97475d0aaf56 | ryan-jr/Side-Projects | /DailyProgrammer/Easy/11 - DayOfTheWeek/11 - DayOfTheWeek.py | 666 | 4.4375 | 4 | """
The program should take three arguments. The first will be a day, the second will be month, and the third will be year. Then, your program should compute the day of the week that date will fall on.
https://www.reddit.com/r/dailyprogrammer/comments/pwons/2192012_challenge_11_easy/
"""
import datetime
import calendar
userDate = input("Please input a date in the format of YYYY/MM/DD")
year, month, day = map(int, userDate.split("/"))
date1 = datetime.date(year, month, day)
# Python formatting starts "day 0" with Monday
# print(datetime.datetime.weekday(date1))
# Getting a day of the week in a readable format
print(calendar.day_name[date1.weekday()])
| true |
d7daafc3c44c13d5a90da7b5bb9c5fb085f88058 | hpencerGA/GACourse-Work | /Unit-1/pigs.py | 1,602 | 4.125 | 4 | import random
score_to_win = 20
player1_score = 0
player2_score = 0
current_player = 1
while True:
#if player 1's turn:
if current_player == 1:
#roll the die
die = random.randint(1, 6)
print(f"Player 1 rolled a {die}")
#if player 1 rolled a 1, reset the score and pass the turn
if die == 1:
current_player = 2
player1_score = 0
print("It is now Player 2's turn")
#otherwise, add the die score to player 1's score
else:
player1_score += die
print(f"Player 1's score: {player1_score}", f"Player 2's score: {player2_score}", sep="\n")
#check for win
# if player1_score >= score_to_win:
# print("Player 1 wins!")
# current_player = 0
#if player 2's turn
elif current_player == 2:
#roll the die
die = random.randint(1, 6)
print(f"Player 2 rolled a {die}")
#if player 2 rolled a 1, reset the score and pass the turn
if die == 1:
current_player = 1
player2_score = 0
print("It is now Player 1's turn")
#otherwise, add the die score to player 2's score
else:
player2_score += die
print(f"Player 1's score: {player1_score}", f"Player 2's score: {player2_score}", sep="\n")
#check for win
if player2_score >= score_to_win or player1_score >= score_to_win:
break
#print winner
if player1_score >= score_to_win:
print("Player 1 wins!")
elif player2_score >= score_to_win:
print("Player 2 wins!") | true |
79f84a7ea29e304a344796c08ec9c81b4c9ef207 | hpencerGA/GACourse-Work | /Unit-3/sols.py | 2,548 | 4.125 | 4 | #problem 5 Write a function called possible_words that accespts a list of words and a list of characters, and returns
# the valid words that can be made from the characters given.
#NOTE: Repetition of characters is not allowed
#legal_words = ['go', 'bat' 'me', 'eat', 'goal', 'boy', 'run']
#letters = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
#possible_words(legal_words, letters) # should return ['go', 'me', goal']
'''
def letter_count(word):
count = {}
for l in word:
count[l]= count.get(l,0) + 1 #count.get retrives a value with a specific key
return count
def possible_words(word_list, char_list):
#which word in word list can be formed from the
#characters in char list
#iterate over word_list (each word be formed from chacters we have)
for word in word_list:
is_word_valid = True #default with true that word is valid
#check each character in the word
valid_words = []
char_count = letter_count(word)
# cheack each character in the word
for letter in word:
if letter not in char_list:
is_word_valid = False
else:
if char_list.count(letter) != char_count[letter]: #.count is a list character count function
is_word_valid = False
#now need to add valid word to list
if is_word_valid:
valid_words.append(word)
return valid_words
legal_words = ['go', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
letters = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
print(possible_words(legal_words, letters))
'''
#Princetons code
def letter_count(word):
count = {}
for l in word:
count[l] = count.get(l, 0) + 1
return count
def possible_words(word_list, char_list):
#which words in word_list can be formed from the
#charaters in char_list
valid_words = []
#iterate over word_list
for word in word_list:
is_word_valid = True
#get a count of each character in word
char_count = letter_count(word)
#check each character in the word
for letter in word:
if letter not in char_list:
is_word_valid = False
else:
if char_list.count(letter) != char_count[letter]:
is_word_valid = False
#add valid word to a list
if is_word_valid:
valid_words.append(word)
return valid_words
legal_words = ['go', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
letters = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
| true |
4c3e8bfeb4028981e2cf99917a5c8a244928a70e | hpencerGA/GACourse-Work | /Unit-3/dict_functions.py | 2,662 | 4.28125 | 4 | '''
#Problem 1 Write a function called dict_merge that merges two dictionaries. If there are common keys, the merged
#dictionary should have a list of the values of the common keys
import json
def dict_merge(dict1,dict2):
#merge dict 1 and dict 2
#create a new dictionary that has key value pairs in dic 1 and dic2
dict3 = {} #create a new dictionary
for key in dict1:
if key not in dict2: #'key is wrong because looking for the same key
dict3[key] = dict1[key]
else: #if key in dict 2
dict3[key] = [dict2[key] , dict1[key]]
for key in dict2:
if key not in dict1:
dict3[key] = dict2[key]
else: #if key in dict 1
dict3[key] = [dict2[key] , dict1[key]]
return dict3
print(dict_merge({'a': 1, 'b': 2}, {'c': 3, 'd': 4}))
print(dict_merge({'a': 1, 'b': 2}, {'b': 3, 'c': 4}))
print(dict_merge({'x': 'one', 'y': 'two'}, {'x': 1.5, 'y': 3.7}))
#1. key not in dict 2
#2. key is not in dic 1
#3. key is in both
#{'name: John', 'address': 'toronto', 'telephone': 000}
#Problem 2 #Write a function called list_to_dict that accepts a person list (which is a list of lists), and returns a
#dictionary. Each list in the person list has only two items. The keys of your result dictionary should be the
#first item in each list, and the value should be the second item
#list_to_dict([['name', 'Alice'], ['job', 'Engineer'], ['city', 'Toronto']])
def list_to_dict(person_list):
result = {}
for item in person_list:
result[item[0]] = item[1]
return result
print(list_to_dict([ 'Alice'], ['job', 'Engineer'], ['city', 'Toronto'])
#1 take list 1- take name set as key then value as name
#2 go to list 2 take name set as key then value as job
#Write a function called reverse_dict to reverse a dictionary. This means, given a dictionary, return a new
#dictionary that has the keys of as values, and the values as keys
def reverse_dict(input_dict):
result = {}
for key in input_dict:
if type(input_dict[key]) is list or type(input_dict[key]) is dict:
result[tuple(inpute_dict[key])] = key
else:
result[input_dict[key]] = key
return result
print(reverse_dict({'a': [1,2,3], 'b': [4,5,6], 'c':[7,8,9]}))
print(reverse_dict({'name': 'alicia', 'job':'Engineer', 'city': 'Toronto'}))
'''
playlist = [
{
'title': 'Bodak Yellow',
'genre': 'Pop',
'artiste': 'Cardi B',
'year': '2017',
'length': 3.25
},
]
def all_titles(pl):
for item in pl:
print(item['title', ',',end=' '])
all_titles[playlist]
#expect playlist
| false |
37d8f3ad4af76dcb577d8b40cb54d775d690577d | way2arun/datastructures_algorithms | /src/matrix/eraseOverlapIntervals.py | 2,988 | 4.25 | 4 | """
Non-overlapping Intervals
https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/551/week-3-august-15th-august-21st/3425/
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
"""
from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
# Solution 1 - 132 ms
"""
# if intervals is empty then return 0
if not intervals:
return 0
# sort intervals
intervals.sort()
# getting initial value to compare every interval with
last_interval_finish = intervals[0][0]
# count of non overlapping interval, inc only when
# current interval is not overlapping
non_overlap_interval = 0
# for each interval decide whether it overlap or not
for interval in intervals:
# if last interval have finish greater than start of current interval
if last_interval_finish > interval[0]:
# choose optimal finish as latest finish
last_interval_finish = min(last_interval_finish, interval[1])
else:
# if current interval do not overlap inc count by 1
non_overlap_interval += 1
# update latest finish to current interval finish
last_interval_finish = interval[1]
# return number of overlapping intervals
return len(intervals) - non_overlap_interval
"""
# Solution 2 - 52 ms
end_sort = sorted(intervals, key=lambda x: x[1])
last = None
ans = 0
for it in end_sort:
if not last:
last = it
else:
if it[0] >= last[1]:
last = it
else:
ans += 1
return ans
"""
# Solution 3 - 56 ms
if not intervals:
return 0
intervals.sort(key=lambda x: x[1])
end = intervals[0][0]
rmCount = 0
for s, e in intervals:
if s >= end:
end = e
else:
rmCount += 1
return rmCount
"""
# Main Call
solution = Solution()
intervals = [[1, 2], [2, 3], [3, 4], [1, 3]]
print(solution.eraseOverlapIntervals(intervals))
| true |
6b3e725ec1154f9e1ab6f85ff10c3484e793e084 | way2arun/datastructures_algorithms | /src/matrix/carPooling.py | 2,472 | 4.1875 | 4 | """
Car Pooling
https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/556/week-3-september-15th-september-21st/3467/
You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000
Hide Hint #1
Sort the pickup and dropoff events by location, then process them in order.
"""
from typing import List
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
# Solution 1 - 68 ms
"""
dic = dict()
for i in trips:
if i[1] not in dic:
dic[i[1]] = i[0]
else:
dic[i[1]] += i[0]
if i[2] not in dic:
dic[i[2]] = -i[0]
else:
dic[i[2]] -= i[0]
cap = 0
l = []
for i in dic.keys():
l.append(i)
l.sort()
for i in l:
cap += dic[i]
if cap > capacity:
return False
return True
"""
# Solution 2 - 48 ms
pois = []
for num, start, end in trips:
pois.extend([(start, num), (end, -num)])
num_used = 0
for _, num in sorted(pois):
num_used += num
if num_used > capacity:
return False
return True
# Main Call
solution = Solution()
trips = [[2, 1, 5], [3, 3, 7]]
capacity = 4
print(solution.carPooling(trips, capacity))
trips = [[2,1,5],[3,3,7]]
capacity = 5
print(solution.carPooling(trips, capacity))
| true |
cb73e652d1232a5493d1eed53621c6d14a02cdd2 | way2arun/datastructures_algorithms | /src/trees/isValidSequence.py | 2,960 | 4.25 | 4 | """
Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.
We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.
Example 1:
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
Output: true
Explanation:
The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure).
Other valid sequences are:
0 -> 1 -> 1 -> 0
0 -> 0 -> 0
Example 2:
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
Output: false
Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.
Example 3:
Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
Output: false
Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.
Constraints:
1 <= arr.length <= 5000
0 <= arr[i] <= 9
Each node's value is between [0 - 9].
Hide Hint #1
Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers.
Hide Hint #2
When reaching at final position check if it is a leaf node.
https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/532/week-5/3315/
"""
# Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
# 112 ms
counter = 0
return self.traverse_path(root, arr, counter, len(arr))
def traverse_path(self, root, arr, counter, array_length):
if not root:
return array_length == 0
if root.left is None and root.right is None:
if counter == array_length - 1:
if root.val == arr[counter]:
return True
if counter < array_length:
if root.val == arr[counter]:
return self.traverse_path(root.left, arr, counter + 1, array_length) or self.traverse_path(root.right,
arr,
counter + 1,
array_length)
# Main Call
root = TreeNode(0)
root.left = TreeNode(1)
root.right = TreeNode(0)
root.left.left = TreeNode(0)
root.left.left.right = TreeNode(1)
root.left.right = TreeNode(1)
root.left.right.left = TreeNode(0)
root.left.right.right = TreeNode(0)
root.right.right = None
root.right.left = TreeNode(0)
arr = [0, 1, 0, 1]
solution = Solution()
print(solution.isValidSequence(root, arr))
| true |
66b593b16b5fbb715a8eb310565d3df234f64cba | way2arun/datastructures_algorithms | /src/integers/reverse_integer_solution_1.py | 469 | 4.28125 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
"""
# Time Complexity - O(n)
# Space Complexity - O(1)
def reverse_integer(number):
sign = 1
res = 0
if number < 0:
sign = -1
number = -number
while number != 0:
res = (res * 10) + number % 10
number = number // 10
if (res > 2 ** 31 - 1) or (res < -2 ** 31):
return 0
return sign * res
# Driver Call
print(reverse_integer(12501))
| true |
65d56f9078c75e59c24dfbdaf91a5c0220e666f3 | way2arun/datastructures_algorithms | /src/arrays/unique_chars_solution_2.py | 646 | 4.21875 | 4 | # Only 1 loop in this case
# Time Complexity - O(n log n)
# Why log n - as we sorted the array, so the complexity changed to log n time.
# Space Complexity - O(1)
def unique_chars_sorted(input_string):
# Sort the array, this will help to remove extra loop
input_string_sorted = sorted(input_string)
for i in range(len(input_string_sorted) - 1):
# In this approach we are always checking the elements in adjacent indexes
# This is how sorted function helps.
if input_string_sorted[i] == input_string_sorted[i + 1]:
return False
return True
# Driver Call
print(unique_chars_sorted("zdabez"))
| true |
fb72f867baf2b806a6b3e8bbefbd16b47e9d6f4b | way2arun/datastructures_algorithms | /src/arrays/maxSlidingWindow.py | 2,671 | 4.34375 | 4 | """
Sliding Window Maximum
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Example 3:
Input: nums = [1,-1], k = 1
Output: [1,-1]
Example 4:
Input: nums = [9,11], k = 2
Output: [11]
Example 5:
Input: nums = [4,-2], k = 2
Output: [4]
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
Hide Hint #1
How about using a data structure such as deque (double-ended queue)?
Hide Hint #2
The queue size need not be the same as the window’s size.
Hide Hint #3
Remove redundant elements and the queue should store only elements that need to be considered.
"""
import collections
from typing import List
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# Solution 1 - 2280 ms
"""
ret = []
maximum_indices = collections.deque([0])
for i in range(1, k):
while len(maximum_indices) > 0 and nums[i] >= nums[maximum_indices[0]]:
maximum_indices.popleft()
maximum_indices.appendleft(i)
ret.append(nums[maximum_indices[-1]])
for i in range(k, len(nums)):
if maximum_indices[-1] == i - k:
maximum_indices.pop()
while len(maximum_indices) > 0 and (nums[i] >= nums[maximum_indices[0]]):
maximum_indices.popleft()
maximum_indices.appendleft(i)
ret.append(nums[maximum_indices[-1]])
return ret
"""
# Solution 2 - 1180 ms
m = max(nums[:k])
res = [m]
left = 0
for n in range(k, len(nums)):
cur = nums[n]
left += 1
if left > 0 and nums[left - 1] == m:
if nums[left] == m - 1:
m = nums[left]
else:
m = max(nums[left: n + 1])
if cur > m:
m = cur
res.append(m)
return res
# Main Call
solution = Solution()
nums = [9, 11]
k = 2
print(solution.maxSlidingWindow(nums, k))
| true |
6b5836aa9ea31eabd61e9c26806cb218aebb6ff1 | way2arun/datastructures_algorithms | /src/arrays/stringShifts.py | 2,962 | 4.1875 | 4 | """
You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]:
direction can be 0 (for left shift) or 1 (for right shift).
amount is the amount by which string s is to be shifted.
A left shift by 1 means remove the first character of s and append it to the end.
Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.
Return the final string after all operations.
Example 1:
Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
Explanation:
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"
Example 2:
Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
Output: "efgabcd"
Explanation:
[1,1] means shift to right by 1. "abcdefg" -> "gabcdef"
[1,1] means shift to right by 1. "gabcdef" -> "fgabcde"
[0,2] means shift to left by 2. "fgabcde" -> "abcdefg"
[1,3] means shift to right by 3. "abcdefg" -> "efgabcd"
Constraints:
1 <= s.length <= 100
s only contains lower case English letters.
1 <= shift.length <= 100
shift[i].length == 2
0 <= shift[i][0] <= 1
0 <= shift[i][1] <= 100
Hint 1
Intuitively performing all shift operations is acceptable due to the constraints.
Hint 2
You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
"""
import collections
from typing import List
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
# solution 1 - 32 ms
"""
string_len, left_shift, right_shift = len(s), 0, 0
for direction, amount in shift:
if direction == 0:
left_shift += amount
else:
right_shift += amount
left_shift = left_shift % string_len
right_shift = right_shift % string_len
if left_shift == right_shift:
return s
if left_shift > right_shift:
left_shift = left_shift - right_shift
return s[left_shift:] + s[:left_shift]
else:
right_shift = right_shift - left_shift
return s[-right_shift:] + s[:-right_shift]
"""
# solution 2
"""
chars = collections.deque(s)
for d, amount in shift:
if d == 0:
for _ in range(amount):
num = chars.popleft()
chars.append(num)
else:
for _ in range(amount):
num = chars.pop()
chars.appendleft(num)
return ''.join(chars)
"""
# solution 3
left = 0
for d, a in shift:
if d:
left -= a
else:
left += a
left %= len(s)
return s[left:] + s[:left]
# Main Call
solution = Solution()
result = solution.stringShift("abc", [[0, 1], [1, 2]])
print(result)
| true |
e10c73a4cbb5c9e127021a2e0b91db24bfdedb2f | way2arun/datastructures_algorithms | /src/arrays/maxScore.py | 2,447 | 4.5625 | 5 | """
Maximum Points You Can Obtain from Cards
There are several cards arranged in a row, and each card has an associated number of points The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array cardPoints and the integer k, return the maximum score you can obtain.
Example 1:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
Example 2:
Input: cardPoints = [2,2,2], k = 2
Output: 4
Explanation: Regardless of which two cards you take, your score will always be 4.
Example 3:
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
Explanation: You have to take all the cards. Your score is the sum of points of all cards.
Example 4:
Input: cardPoints = [1,1000,1], k = 1
Output: 1
Explanation: You cannot take the card in the middle. Your best score is 1.
Example 5:
Input: cardPoints = [1,79,80,1,1,1,200,1], k = 3
Output: 202
Constraints:
1 <= cardPoints.length <= 10^5
1 <= cardPoints[i] <= 10^4
1 <= k <= cardPoints.length
Hide Hint #1
Let the sum of all points be total_pts. You need to remove a sub-array from cardPoints with length n - k.
Hide Hint #2
Keep a window of size n - k over the array. The answer is max(answer, total_pts - sumOfCurrentWindow)
"""
from typing import List
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
# Solution 1 - 408 ms
"""
best = total = sum(cardPoints[:k])
for i in range(k - 1, -1, -1):
total += cardPoints[i + len(cardPoints) - k] - cardPoints[i]
best = max(best, total)
return best
"""
# Solution 2 - 364 ms
size = len(cardPoints) - k
minSubArraySum = curr = sum(cardPoints[:size])
for i in range(len(cardPoints) - size):
curr += cardPoints[size + i] - cardPoints[i]
minSubArraySum = min(minSubArraySum, curr)
return sum(cardPoints) - minSubArraySum
# Main Call
cardPoints = [1, 2, 3, 4, 5, 6, 1]
k = 3
solution = Solution()
print(solution.maxScore(cardPoints, k)) | true |
4744be1ede0e673acbc0fb3d594ef32c3b5d9b67 | way2arun/datastructures_algorithms | /src/arrays/validMountainArray.py | 2,080 | 4.21875 | 4 | """
Valid Mountain Array
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < A[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Example 1:
Input: arr = [2,1]
Output: false
Example 2:
Input: arr = [3,5,5]
Output: false
Example 3:
Input: arr = [0,3,2,1]
Output: true
Constraints:
1 <= arr.length <= 104
0 <= arr[i] <= 104
Hide Hint #1
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and you will be able to come up with a straightforward solution.
"""
from typing import List
class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# Solution 1 - 204 ms
"""
start, run, l = 0, 0, len(arr)
# Going up hill
while run + 1 < l and arr[run] < arr[run + 1]: run += 1
# Check if run pointer has moved compared to last Start position
if run == start: return False
# Going down hill
start = run
while run + 1 < l and arr[run] > arr[run + 1]: run += 1
# Check if run pointer has moved compared to last Start position
if run == start: return False
# Final Check if run is pointing to the last element
return run == l - 1
"""
# Solution 2 - 168 ms
n = len(arr)
if n < 3: return False
inc = arr[0] < arr[1]
k = 0
for i in range(1, n):
if inc and arr[i - 1] >= arr[i]:
k += 1
inc = False
if not inc and arr[i - 1] <= arr[i]:
return False
return k == 1
# Main Call
arr = [3, 5, 5]
solution = Solution()
print(solution.validMountainArray(arr))
| true |
568348ab3d1addb6ff262964a246982c86b76ca5 | way2arun/datastructures_algorithms | /src/arrays/largestNumber.py | 2,235 | 4.15625 | 4 | """
Largest Number
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/557/week-4-september-22nd-september-28th/3472/
"""
from functools import cmp_to_key
from typing import List
# Solution 3 - 24 ms
class Comparator(str):
def __lt__(self, other):
return self + other < other + self
class Solution:
def largestNumber(self, nums: List[int]) -> str:
# Solution 1 - 36 ms
"""
str_nums = []
for num in nums:
str_nums.append(str(num)) # turn numbers to strings
str_nums.sort(reverse=True) # sort by lexicographical order
flag = False # flag to keep track if there were swaps, if no more swaps needed - finished
while not flag:
flag = True
i = 0
while i < len(str_nums) - 1:
if str_nums[i] + str_nums[i + 1] < str_nums[i + 1] + str_nums[i]: # if larger when swapped - swap
str_nums[i], str_nums[i + 1] = str_nums[i + 1], str_nums[i]
flag = False
i += 1
res = "".join(str_nums)
if res[0] == '0':
return str(0)
return res
"""
# Solution 2 - 20 ms
def cmp(x, y):
u = x + y
v = y + x
if u == v:
return 0
elif u < v:
return -1
else:
return 1
v = map(str, nums)
result = ''.join(reversed(sorted(v, key=cmp_to_key(cmp))))
if result and result[0] == '0':
return '0'
else:
return result
# Solution 3 - 24 ms
"""
if not nums:
return ""
nums = list(map(str, nums))
nums.sort(reverse=True, key=Comparator)
return "".join(nums) if nums[0] != "0" else "0"
"""
# Main Call
nums = [3, 30, 34, 5, 9]
solution = Solution()
print(solution.largestNumber(nums))
| true |
15c1d61c9fd9bf54ddbfded755806ebd1ed5cabe | VladMerk/stepic_tasks | /modify_lst.py | 625 | 4.21875 | 4 | lst = [1, 2, 3, 4, 5, 6]
def modify_lst(l):
"""
Напишите функцию modify_list(l), которая принимает на вход список целых чисел, удаляет из него все нечётные значения,
а чётные нацело делит на два. Функция не должна ничего возвращать, требуется только изменение переданного списка
"""
l[:] = [i//2 for i in l if not i%2]
print(modify_lst(lst))
print(lst)
modify_lst(lst)
print(lst)
lst = [10, 5, 8, 3]
modify_lst(lst)
print(lst) | false |
f4a2bffeeeb56b9d8af2f5c6b59248c1a7e11708 | skr47ch/Python_Beginner | /12_list_ends.py | 359 | 4.15625 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list.
# For practice, write this code inside a function.
import random
a = []
for x in range(1, random.randint(10, 25)):
a.append(random.randint(1, 100))
print(a)
print([a[0], (a[len(a)-1])])
| true |
b0c50d3ef1cd057b679f90d128cfbdce41ad5cf7 | chriszeng8/Python | /Programming_for_Everyone/error_handling.py | 623 | 4.25 | 4 | # Chris Zeng, Feb 15, 2015
# Try ... Except
# operations within the TRY block is to say that, as a programmer,
# I know that things could go wrong in this block. If it goes wrong,
# jump straight to the EXCEPT block WITHOUT executing the following
# code within the TRY block.
print 'This program will multiply your input integer by 10.'
test = raw_input("Enter an integer number:")
try:
test = int(test)
print 'Good, it\'s a Valid Entry' # Note that this helloworld will not be printed if the input is invalid.
except:
print "Invalid entry. Please enter an integer"
quit()
result = test * 10
print result | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.