blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
2688f66ba9e38b00dac4c25532e6cca5af931c0b | gsy/leetcode | /level_order_traversal_reverse.py | 1,119 | 3.515625 | 4 | __author__ = 'guang'
__author__ = 'guang'
from bst import TreeNode
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
>>> s = Solution()
>>> three, nine, twenty, fifty, seven = TreeNode(3), TreeNode(9), TreeNode(20), TreeNode(15), TreeNode(7)
>>> three.left, three.right, twenty.left, twenty.right = nine, twenty, fifty, seven
>>> result = s.levelOrderBottom(three)
>>> result
[[15, 7], [9, 20], [3]]
>>> one = TreeNode(1)
>>> s.levelOrderBottom(one)
[[1]]
"""
if root is None:
return []
result = []
parents = [root]
while parents:
nodes = []
values = []
for parent in parents:
values.append(parent.val)
if parent.left:
nodes.append(parent.left)
if parent.right:
nodes.append(parent.right)
parents = nodes
result.append(values)
return result[::-1]
|
e94c8523946233ee9c2fc222a6ddbdad9be24f07 | gsy/leetcode | /third_maximum.py | 1,187 | 3.875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def thirdMax(self, nums):
stack = []
remain = []
for num in nums:
if len(stack) == 0:
stack.append(num)
else:
while len(stack) > 0:
top = stack[-1]
if top < num:
remain.append(stack.pop(-1))
elif top == num:
stack.pop(-1)
else:
break
if len(stack) < 3:
stack.append(num)
while len(stack) < 3 and len(remain) > 0:
stack.append(remain.pop(-1))
return stack[-1] if len(stack) == 3 else stack[0]
if __name__ == '__main__':
s = Solution()
r = s.thirdMax([1, 2])
print(r)
assert r == 2
r = s.thirdMax([3, 1, 2])
print(r)
assert r == 1
r = s.thirdMax([3, 1, 2, 2])
print(r)
assert r == 1
r = s.thirdMax([1, 2, 2, 3])
print(r)
assert r == 1
r = s.thirdMax([1, 2, 2, 2, 3])
print(r)
assert r == 1
r = s.thirdMax([2, 2, 2, 2, 3])
print(r)
assert r == 3
|
7b56902235095a797f4c8296a6e239eda45285cb | gsy/leetcode | /partition_list.py | 2,472 | 3.734375 | 4 | __author__ = 'guang'
from linklist import LinkedList, ListNode
class Solution(object):
def empty(self, ls):
head, tail = ls
return head is None and tail is None
def append(self, node, ls):
"""
>>> s = Solution()
>>> node = ListNode(3)
>>> head = LinkedList.fromList([1, 2, 4])
>>> tail = head.next.next
>>> result = s.append(node, (head, tail))
>>> LinkedList.toList(result[0])
[1, 2, 4, 3]
>>> head = LinkedList.fromList([1, 2, 4])
>>> result = s.append(None, (head, tail))
>>> LinkedList.toList(result[0])
[1, 2, 4]
"""
if node is None:
return ls
head, tail = ls
if self.empty(ls):
head = node
tail = node
tail.next = None
else:
tail.next = node
tail = node
tail.next = None
return head, tail
def concat(self, ls1, ls2):
if self.empty(ls1):
return ls2
elif self.empty(ls2):
return ls1
else:
head1, tail1 = ls1
head2, tail2 = ls2
tail1.next = head2
return head1, tail2
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
>>> s = Solution()
>>> head = LinkedList.fromList([1,4,3,2,5,2])
>>> result = s.partition(head, 3)
>>> LinkedList.toList(result)
[1, 2, 2, 4, 3, 5]
>>> head = LinkedList.fromList([1,4,3,2,5,2])
>>> result = s.partition(head, 10)
>>> LinkedList.toList(result)
[1, 4, 3, 2, 5, 2]
>>> head = LinkedList.fromList([1,4,3,2,5,2])
>>> result = s.partition(head, 0)
>>> LinkedList.toList(result)
[1, 4, 3, 2, 5, 2]
>>> head = LinkedList.fromList([1, 1, 1, 1, 1])
>>> result = s.partition(head, 1)
>>> LinkedList.toList(result)
[1, 1, 1, 1, 1]
"""
if head is None:
return None
smaller, greater = (None, None), (None, None)
node = head
while node:
succeeding = node.next
if node.val < x:
smaller = self.append(node, smaller)
else:
greater = self.append(node, greater)
node = succeeding
result = self.concat(smaller, greater)
return result[0]
|
e4911f942dec9139ff2e5604c35420fb74b40ac5 | gsy/leetcode | /expressive_words.py | 1,715 | 3.71875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def stretchy(self, word, string):
# word -> string
index, prev, count, stretch, length = 0, None, 0, False, len(word)
for char in string:
if index < length and char == word[index]:
if stretch and count < 3:
return False
stretch = False
index = index + 1
if char == prev:
count = count + 1
else:
count = 1
prev = char
else:
if prev and char == prev:
stretch = True
count = count + 1
else:
return False
if stretch:
return count >= 3 and index == length
else:
return index == length
def expressiveWords(self, string, words):
result = 0
for word in words:
if self.stretchy(word, string):
# print(word, string)
result = result + 1
return result
if __name__ == '__main__':
s = Solution()
r = s.expressiveWords("heeellooo", words=["hello", "hi", "helo"])
assert r == 1
r = s.expressiveWords("heellooo", words=["hello"])
assert r == 0
r = s.expressiveWords("heeelloo", words=["hello"])
assert r == 0
r = s.expressiveWords("dddiiiinnssssssoooo", ["dinnssoo"])
assert r == 1
r = s.expressiveWords("dddiiiinnssssssoooo", ["ddiinnso"])
assert r == 1
r = s.expressiveWords("dddiiiinnssssssoooo", ["dinnssoo", "ddinso", "ddiinnso", "ddiinnssoo", "ddiinso", "dinsoo", "ddiinsso", "dinssoo", "dinso"])
assert r == 3
|
0173011b8fe6d564cf6cb99f5bce029910c40e8d | gsy/leetcode | /merge_sorted_arrays.py | 924 | 3.78125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def merge(self, nums1, m, nums2, n):
"""
Do not return anything, modify nums1 in-place instead.
"""
last, i, j = m + n - 1, m - 1, n - 1
while last >= 0:
if i >= 0 and j >= 0:
if nums1[i] >= nums2[j]:
nums1[last] = nums1[i]
i, last = i - 1, last - 1
else:
nums1[last] = nums2[j]
j, last = j - 1, last - 1
elif i >= 0:
nums1[last] = nums1[i]
i, last = i - 1, last - 1
elif j >= 0:
nums1[last] = nums2[j]
j, last = j - 1, last - 1
if __name__ == '__main__':
s = Solution()
r = s.merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)
r = s.merge([1, 2, 3, 0, 0, 0], 1, [2, 5, 6], 3)
r = s.merge([0, 0, 0, 0], 0, [1], 1)
|
a771c81613d8a54089018954a7c83496ece404e0 | gsy/leetcode | /shortest_completing_word.py | 1,086 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import string
class Solution:
def word_count(self, word):
result = {}
for char in word:
char = char.lower()
if char in string.ascii_lowercase:
result[char] = result.get(char, 0) + 1
return result
def contains(self, current, words):
for key, value in words.items():
if key not in current or current[key] < value:
return False
return True
def shortestCompletingWord(self, licensePlate, words):
words = sorted(words, key=len)
license_wordcount = self.word_count(licensePlate)
for word in words:
current = self.word_count(word)
if self.contains(current, license_wordcount):
return word
return None
if __name__ == "__main__":
s = Solution()
r = s.shortestCompletingWord("1s3 PSt", ["step", "steps", "stripe", "stepple"])
assert r == "steps"
r = s.shortestCompletingWord("1s3 456", ["looks", "pest", "stew", "show"])
print(r)
assert r == "pest"
|
d1cb3c5f571f7cddd6683d95a90ae39febe5befe | gsy/leetcode | /word_subsets.py | 1,459 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def word_count(self, word):
count = {}
for char in word:
count[char] = count.get(char, 0) + 1
return count
def all_is_subset(self, sets, word):
target = self.word_count(word)
sources = [self.word_count(item) for item in sets]
# print(target, sources)
for source in sources:
for key, value in source.items():
if target.get(key, 0) < value:
return False
return True
def wordSubsets(self, words, sets):
result = []
for word in words:
if self.all_is_subset(sets, word):
result.append(word)
return result
if __name__ == '__main__':
s = Solution()
r = s.wordSubsets(["amazon", "apple", "facebook", "google", "leetcode"], ["e", "o"])
assert r == ["facebook", "google", "leetcode"]
r = s.wordSubsets(["amazon", "apple", "facebook", "google", "leetcode"], ["l", "e"])
assert r == ["apple", "google", "leetcode"]
r = s.wordSubsets(["amazon", "apple", "facebook", "google", "leetcode"], ["e", "oo"])
assert r == ["facebook", "google"]
r = s.wordSubsets(["amazon", "apple", "facebook", "google", "leetcode"], ["lo", "eo"])
assert r == ["google", "leetcode"]
r = s.wordSubsets(["amazon", "apple", "facebook", "google", "leetcode"], ["ec", "oc", "ceo"])
assert r == ["facebook", "leetcode"]
|
734a867d6107a4687e080b736b74b68211808e5d | gsy/leetcode | /binarytree/bstToGst.py | 1,043 | 3.859375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
acc = 0
class Solution:
def dfs(self, root):
global acc
if root is None:
return
if root.right:
self.dfs(root.right)
print(f"{root.val}->{root.val+acc, {acc}}")
root.val = root.val + acc
acc = root.val
if root.left:
self.dfs(root.left)
return
def bstToGst(self, root: TreeNode) -> TreeNode:
# 后序遍历:右 -> 中 -> 左
global acc
acc = 0
self.dfs(root)
return root
if __name__ == '__main__':
node = TreeNode(4)
node.left = TreeNode(1)
node.right = TreeNode(6)
node.left.left = TreeNode(0)
node.left.right = TreeNode(2)
node.left.right.right = TreeNode(3)
node.right.left = TreeNode(5)
node.right.right = TreeNode(7)
node.right.right.right = TreeNode(8)
s = Solution()
s.bstToGst(node)
|
c24cec409a45b42544a6baf747d0d67353468248 | gsy/leetcode | /most_common_word.py | 959 | 3.6875 | 4 | # -*- coding: utf-8 -*-
class Solution:
def mostCommonWord(self, paragraph, banned):
count = {}
result, maximum = "", 0
p = ""
for char in paragraph:
if char in (["!", "?", "'", ",", ";", "."]):
p = p + " "
else:
p = p + char.lower()
p = p.strip()
for word in p.split(" "):
if word == "":
continue
count[word] = count.get(word, 0) + 1
if count[word] > maximum and word not in banned:
maximum = count[word]
result = word
return result
if __name__ == '__main__':
s = Solution()
r = s.mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"])
print(r)
assert r == "ball"
r = s.mostCommonWord(" Bob hit a ball, the hit BALL flew far!after,it was, ,,, ! hit...", ["hit"])
print(r)
assert r == "ball"
|
15e93f299e567cc4f433fe691660ede5e0e05556 | gsy/leetcode | /rotate_array.py | 399 | 3.578125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def rotate(self, nums, k):
length = len(nums)
tmp = nums[:]
for index, num in enumerate(nums):
new_index = (index + k) % length
nums[new_index] = tmp[index]
print(nums)
if __name__ == '__main__':
s = Solution()
s.rotate([1, 2, 3, 4, 5, 6, 7], k=3)
s.rotate([-1, -100, 3, 99], k=2)
|
759b84866a1bdeb16c8d43607a696cf9f54bb03a | gsy/leetcode | /binarysearch/search.py | 1,511 | 3.953125 | 4 | # 段落内有序,所以在一个段落内是可以使用二分搜索的
# 怎样确定一个段落?从 left 往后找,知道第一个比 left 小的 item 为止,都是一个段落
# 一个段落一个段落搜索
class Solution:
def calculateRight(self, arr, length, left):
# 递增的尽头,需要的包含的关系
j = left + 1
if j >= length:
return length - 1
if arr[j] > arr[left]:
while j < length and arr[j] > arr[j-1]:
j = j + 1
return j - 1
else:
return left
def search(self, arr, target):
length = len(arr)
left = 0
while left < length:
right = self.calculateRight(arr, length, left)
# binary search
current_left, current_right = left, right
found = False
# print("left:", current_left, "right:", current_right)
while current_left <= current_right:
mid = (current_left + current_right) // 2
if arr[mid] == target:
found = True
current_right = mid
if current_left == current_right:
break
elif arr[mid] > target:
current_right = mid - 1
else:
current_left = mid + 1
if found:
return True
else:
left = right + 1
return False
|
705c58a95afe2e0cca93ee1835e36762fcb10cb1 | gsy/leetcode | /divide_two_integers.py | 1,785 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
def to_result(self, sign, result):
if (sign == '+' and result > 2147483647) or (sign == '-' and result >= 2147483647):
return 2147483647
if sign == '+':
return result
else:
return -result
def divide(self, dividend, divisor):
if divisor == 0:
return None
elif dividend == 0:
return 0
elif divisor == 1:
return dividend
sign = '+'
if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
sign = '-'
dividend = abs(dividend)
divisor = abs(divisor)
if divisor == 1:
return self.to_result(sign, dividend)
count = 1
a = divisor
while a <= dividend:
a = a + a
count = count + count
# a > dividend
if a == dividend:
return self.to_result(sign, count)
else:
print(a, dividend)
while a > dividend:
a = a - divisor
count = count - 1
return self.to_result(sign, count)
if __name__ == '__main__':
s = Solution()
r = s.divide(7, 3)
print(r)
assert r == 2
r = s.divide(7, -3)
assert r == -2
r = s.divide(7, 0)
assert r is None
r = s.divide(0, 7)
assert r == 0
r = s.divide(0, 999999)
assert r == 0
r = s.divide(999999, 0)
assert r is None
r = s.divide(999999999, 1)
assert r == 999999999
r = s.divide(10, 3)
assert r == 3
r = s.divide(-2147483648, -1)
assert r == 2147483647
r = s.divide(2147483647, 2)
assert r == 1073741823
r = s.divide(-2147483648, 2)
assert r == 1073741824
|
61a95ba036525853d05519c90d4f4611661258ba | gsy/leetcode | /symmetric_tree.py | 1,400 | 3.625 | 4 | __author__ = 'guang'
from bst import TreeNode
class Solution(object):
def is_mirror(self, tree_a, tree_b):
"""
>>> s = Solution()
>>> two, three, four = TreeNode(2), TreeNode(3), TreeNode(4)
>>> two.left, two.right = three, four
>>> another_two, another_three, another_four = TreeNode(2), TreeNode(3), TreeNode(4)
>>> another_two.left, another_two.right = another_four, another_three
>>> s.is_mirror(three, another_three)
True
>>> s.is_mirror(two, another_two)
True
"""
if tree_a is None and tree_b is None:
return True
elif tree_a is None:
return False
elif tree_b is None:
return False
else:
if tree_a.val != tree_b.val:
return False
else:
return self.is_mirror(tree_a.left, tree_b.right) and self.is_mirror(tree_a.right, tree_b.left)
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
>>> s = Solution()
>>> root, one = TreeNode(2), TreeNode(1)
>>> root.left = one
>>> s.isSymmetric(root)
False
>>> root.right = TreeNode(1)
>>> s.isSymmetric(root)
True
"""
if root is None:
return True
return self.is_mirror(root.left, root.right)
|
429b4db73aceb10f9e60088d84184c08b93d0709 | gsy/leetcode | /to_lowercase.py | 237 | 3.75 | 4 | # -*- coding: utf-8 -*-
class Solution:
def toLowerCase(self, text):
if len(text) == 0:
return ""
result = ""
for char in text:
result = result + char.lower()
return result
|
16813951845c110fc7016b6ffcbb4bf36e3bbd5e | gsy/leetcode | /character_bits.py | 395 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def isOneBitCharacter(self, bits):
if len(bits) == 0:
return False
start, end = 0, len(bits)
while start < end:
if bits[start] == 1:
step = 2
start = start + step
else:
step = 1
start = start + step
return step == 1
|
8eba3c4f9088044d2b3dc3dc575ed7624d2fc474 | gsy/leetcode | /longest_word.py | 1,204 | 3.65625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def longestWord(self, words):
words = sorted(words, key=len)
# print(words)
prefix = set()
result, maxlen = "", 0
for word in words:
length, flag = len(word), False
if length == 1:
prefix.add(word)
flag = True
else:
substring = word[:-1]
if substring in prefix:
flag = True
prefix.add(word)
if flag:
if length > maxlen:
result = word
maxlen = length
elif length == len(result) and word < result:
result = word
return result
if __name__ == "__main__":
s = Solution()
r = s.longestWord(["w", "wo", "wor", "worl", "world"])
print(r)
assert r == "world"
r = s.longestWord( ["a", "banana", "app", "appl", "ap", "apply", "apple"])
print(r)
assert r == "apple"
r = s.longestWord(["ts","e","x","pbhj","opto","xhigy","erikz","pbh","opt","erikzb","eri","erik","xlye","xhig","optoj","optoje","xly","pb","xhi","x","o"])
assert r == "e"
|
a07ac46de56d67febbb9de4fc3f4d94fcbdfef16 | gsy/leetcode | /complex_number_multiply.py | 1,666 | 4 | 4 | # -*- coding: utf-8 -*-
class Complex(object):
def to_int(self, number):
if len(number) == 0:
return 0
else:
return int(number)
def virtual_to_int(self, virtual):
if len(virtual) == 0:
return 0
assert 'i' in virtual
virtual = virtual.strip('i')
if len(virtual) == 0:
return 1
return int(virtual)
def __init__(self, string):
real, virtual, state = '', '', "real"
for char in string:
if char == '+':
state = "virtual"
continue
else:
if state == "real":
real = real + char
else:
virtual = virtual + char
self.real = self.to_int(real)
self.virtual = self.virtual_to_int(virtual)
class Solution:
def multiply(self, a, b):
real = (a.real * b.real) - (a.virtual * b.virtual)
virtual = (a.real * b.virtual + a.virtual * b.real)
return "{}+{}i".format(real, virtual)
def complexNumberMultiply(self, a, b):
return self.multiply(Complex(a), Complex(b))
if __name__ == '__main__':
s = Solution()
r = s.complexNumberMultiply("1+1i", "1+1i")
assert r == "0+2i"
r = s.complexNumberMultiply("1+-1i", "1+-1i")
assert r == "0+-2i"
r = s.complexNumberMultiply("1", "1")
assert r == "1+0i"
r = s.complexNumberMultiply("1+0i", "1")
assert r == "1+0i"
r = s.complexNumberMultiply("0+1i", "0+1i")
print(r)
assert r == "-1+0i"
r = s.complexNumberMultiply("0+i", "0+i")
print(r)
assert r == "-1+0i"
|
b5c90ec12d927261e8646f2f012a5fa085a2e34e | gsy/leetcode | /h_index.py | 923 | 3.53125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def hIndex(self, citations):
if len(citations) == 0:
return 0
citations = sorted(citations, reverse=True)
count, seen = {}, set()
acc = 0
for citation in citations:
if citation not in seen:
seen.add(citation)
count[citation] = acc + count.get(citation, 0) + 1
acc = acc + 1
keys = sorted(count.keys(), reverse=True)
for citation in keys:
# count[key]: docs
if citation <= count[citation]:
return citation
return len(citations)
if __name__ == '__main__':
s = Solution()
r = s.hIndex([3, 0, 6, 1, 5])
print(r)
assert r == 3
r = s.hIndex([100])
print(r)
assert r == 1
r = s.hIndex([11, 15])
print(r)
assert r == 2
r = s.hIndex([4, 4, 0, 0])
assert r == 2
|
87ceba67fa4c7df94bd8b068917124ed2b9e0764 | gsy/leetcode | /magic_dictionary.py | 2,072 | 3.859375 | 4 | # -*- coding: utf-8 -*-
import string
class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.origin = {}
def buildDict(self, words):
"""
Build a dictionary through a list of words
"""
for word in words:
length = len(word)
key = "{}/{}".format(length, word[0])
ls = self.origin.get(key, [])
ls.append(word)
self.origin[key] = ls
def only_modify_one_char(self, word, origin):
count = 0
for i, char in enumerate(word):
if char != origin[i]:
count = count + 1
if count >= 2:
return False
return count == 1
def search(self, word):
"""
Returns if there is any word in the trie that equals to the given word after modifying exactly one character
"""
length = len(word)
if length == 1:
for letter in string.ascii_lowercase:
key = "{}/{}".format(1, letter)
if key in self.origin and letter != word:
return True
return False
key = "{}/{}".format(len(word), word[0])
ls = self.origin.get(key, [])
if len(ls) == 0:
return False
for origin in ls:
if self.only_modify_one_char(word, origin):
return True
return False
if __name__ == "__main__":
obj = MagicDictionary()
obj.buildDict(["hello", "leetcode"])
r = obj.search("hello")
assert r is False
r = obj.search("hhllo")
assert r is True
r = obj.search("hell")
assert r is False
r = obj.search("leetcoded")
assert r is False
obj.buildDict(["a"])
r = obj.search("a")
assert r is False
obj.buildDict(["a"])
r = obj.search("b")
assert r is True
# ["MagicDictionary", "buildDict", "search", "search", "search", "search", "search", "search"]
# [[], [["a"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"]]
|
c5d7c2e7628f882388b6f4824e5585a4ad5031dd | gsy/leetcode | /greatest_common_divisor_of_strings.py | 1,410 | 3.625 | 4 | # -*- coding: utf-8 -*-
class Solution:
def can_divide(self, string, pattern):
len_string = len(string)
len_pattern = len(pattern)
if len_string < len_pattern:
return False
elif len_string == len_pattern:
return string == pattern
elif len_string % len_pattern != 0:
return False
else:
for i in range(0, len_string - len_pattern, len_pattern):
substring = string[i: i + len_pattern]
if substring != pattern:
return False
return True
def gcd_of_string(self, str2, length):
if length == 0:
return ""
if length % 2 == 1:
return [str2]
else:
left = str2[0:length/2]
right = str2[length/2:]
if left == right:
return [str2, left] + self.gcd_of_string(left, length/2)
else:
return [str2]
def gcdOfStrings(self, str1, str2):
len_str2 = len(str2)
if len_str2 == 0:
return ""
gcds = self.gcd_of_string(str2, len_str2)
gcds = set(gcds)
# print("gcds", gcds)
for gcd in gcds:
# can_divide = self.can_divide(str1, gcd)
# print(str1, gcd, can_divide)
if self.can_divide(str1, gcd):
return gcd
return ""
|
7628da6b3b35602907c016486af3671a1c956b6e | gsy/leetcode | /binarysearch/minArray.py | 504 | 3.828125 | 4 | class Solution:
def minArray(self, numbers):
length = len(numbers)
left, right = 0, length - 1
while left < right:
mid = (left + right) // 2
if (mid-1 >= 0 and numbers[mid-1] > numbers[mid]) and\
(mid+1 < length and numbers[mid+1] > numbers[mid]):
return numbers[mid]
elif numbers[mid] < numbers[left]:
right = mid
else:
left = mid + 1
return numbers[0]
|
6723a4891900dea8926f5a5afec4b65af35b8209 | gsy/leetcode | /balanced_binary_tree2.py | 1,058 | 3.765625 | 4 | # -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 深度优先搜索,找到左右子树的深度
def bfs(self, node):
if node is None:
return 0
height = 0
level = [None, node]
while len(level) > 0:
node = level.pop()
if node is None:
height = height + 1
if len(level) == 0:
break
else:
level.insert(0, None)
else:
if node.left:
level.insert(0, node.left)
if node.right:
level.insert(0, node.right)
return height
def isBalanced(self, root):
if root is None:
return True
left_depth = self.bfs(root.left)
right_depth = self.bfs(root.right)
# print(f"left {left_depth}, right {right_depth}")
return abs(left_depth - right_depth) <= 1
|
1596f34fe89c8b494c33d86b9dfb4d3ed5218b7d | gsy/leetcode | /sum_of_two_integers.py | 752 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def bit_plus(self, a, b, carry):
return (a ^ b) ^ carry, (a & b) | (a ^ b) & carry
def getSum(self, a, b):
digit, carry, result = 1, 0, 0
while True:
a_bit = a & digit
b_bit = b & digit
if a_bit == 0 and b_bit == 0:
break
tmp, carry = self.bit_plus(a_bit, b_bit, carry)
result = result | tmp
digit = digit << 1
print(result, carry)
if carry:
return digit ^ result
else:
return result
if __name__ == "__main__":
s = Solution()
r = s.getSum(1, 1)
print(r)
r = s.getSum(1, 2)
print(r)
r = s.getSum(1, 3)
print(r)
|
aff108b752d4c24402b491d8c16adebdf8e83c32 | gsy/leetcode | /remove_elements.py | 1,420 | 3.640625 | 4 | __author__ = 'guang'
from linklist import LinkedList
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
>>> s = Solution()
>>> head = LinkedList.fromList([1, 2, 6, 3, 4, 5, 6])
>>> result = s.removeElements(head, 6)
>>> LinkedList.toList(result)
[1, 2, 3, 4, 5]
>>> s.removeElements(None, 3)
>>> head = LinkedList.fromList([1, 1, 1, 1, 1])
>>> result = s.removeElements(head, 1)
>>> result
>>> head = LinkedList.fromList([6, 1, 2, 6, 3, 4, 5, 6])
>>> result = s.removeElements(head, 6)
>>> LinkedList.toList(result)
[1, 2, 3, 4, 5]
>>> head = LinkedList.fromList([1, 2, 2, 1])
>>> result = s.removeElements(head, 2)
>>> LinkedList.toList(result)
[1, 1]
"""
if head is None:
return None
while head:
if head.val == val:
head = head.next
else:
break
node = head
while node:
next_node = node.next
while next_node:
if next_node.val == val:
node.next = next_node.next
next_node = next_node.next
else:
break
node = next_node
return head
|
3589234dc4866f58175ac0997900612b26810e0c | gsy/leetcode | /greedy/splitIntoFibonacci.py | 1,131 | 3.75 | 4 | class Solution:
def isValid(self, sub, result):
if sub[0] == '0':
if sub != '0':
return False
number = int(sub)
if number < 0 or number > 2**31 - 1:
return False
length = len(result)
if length >= 2:
if int(result[-2]) + int(result[-1]) == number:
return True
else:
return False
return True
def backtrack(self, text, path, result):
# 只要找到1个就可以返回了
length = len(text)
if length == 0 and len(path) >= 3:
result.append(path)
return True
# candidates
for i in range(1, length+1):
sub = text[:i]
if self.isValid(sub, path):
done = self.backtrack(text[i:], path + [sub], result)
if done:
return True
return False
def splitIntoFibonacci(self, S):
path, result = [], []
self.backtrack(S, path, result)
if result:
return [int(item) for item in result[0]]
return []
|
3d6b32068849d5a9ba3710624939f2c005d248c5 | gsy/leetcode | /jewels_and_stones.py | 280 | 3.734375 | 4 | # -*- coding: utf-8 -*-
class Solution:
def numJewelsInStones(self, jewels, stones):
return len([stone for stone in stones if stone in jewels])
if __name__ == "__main__":
s = Solution()
r = s.numJewelsInStones("aA", "aAAbbbb")
print(r)
assert r == 3
|
0226034d87c72f4ae335dc4caec32a79ec3d81ef | gsy/leetcode | /number_of_segments_in_a_string.py | 439 | 3.8125 | 4 | # -*- coding: utf-8 -*-
class Solution:
def countSegments(self, s):
if s == '':
return 0
s = s.strip()
return len([word for word in s.strip().split(' ') if len(word) > 0])
if __name__ == '__main__':
s = Solution()
r = s.countSegments(", , , , a, eaefa")
assert r == 6
r = s.countSegments(" ")
assert r == 0
r = s.countSegments("apple pie")
assert r == 2
|
9053cb3f263ebbd5abb09c8f2e3bb25f6dabc10f | miklo88/Python-Traversy | /functions.py | 787 | 3.890625 | 4 | # A function is a block of code which only runs when it is called. In python, we do not use curly brackets, we use indentation with tabs or spaces
# Create function
def sayHello(name):
print(f'Hola {name}')
sayHello('Carlitos')
# can also invoke function with no argument
def sayHello(name='Muchachicho'):
print(f'Hola {name}')
sayHello()
# Return values
def getSum(num1, num2):
total = num1 + num2
return total
# most of the time you'll be assigning it to a variable
num = getSum(3, 14)
print(num)
# A lambda function is a small anonymous function.
# A lambda function can take any number of arguments, but can only have one expression. Very similar to JS arrow functions
# implicitly returns
getSum = lambda num1, num2 : num1 + num2
print(getSum(10, 17)) |
48554d61a2c6fb9ea934594ead8d9f9f3878e0af | prasadbhatane/Nesting_Software_and_Automated_Marker | /Nesting software/nesting.py | 624 | 3.6875 | 4 | from sheet import Sheet
from utils import insertRectangles, showNestedDiagram
n = int(input("Enter the number of rectangles : "))
input_rect = []
sheetLength, sheetBreadth = 0, 0
print('Enter length and breadth of each rectangle separated by space eg, : 100 20')
for i in range(n):
s = input("rect {} length breadth : ".format(i + 1)).split()
sheetLength += max((int(s[0]), int(s[1])))
sheetBreadth = sheetLength
input_rect.append((int(s[0]), int(s[1])))
sh = Sheet(sheetLength, sheetBreadth)
insertRectangles(input_rect, sh)
showNestedDiagram(sh.rectangleSet, sh.length, sh.breadth)
|
1933c18b415d81163a1062c572945fdbe68ef776 | Dmitrii-Geek/Homework | /lesson4.7.py | 256 | 3.65625 | 4 | from math import factorial
from itertools import count
def fibo_gen():
for el in count(1):
yield factorial(el)
x = 0
for i in fibo_gen():
print('Factorial {} - {}'.format(x + 1, i))
if x == 14:
break
x += 1 |
dddaff54b7253daf23b8affde8ecb78738525ea0 | binary-hideout/sistemas-adaptativos | /practica3/constantes.py | 699 | 3.625 | 4 | from numpy import ones, fill_diagonal
# crear matriz de numpy rellena con unos, de 6 x 6
feromonas = ones((6, 6), int)
# poner la diagonal principal en ceros
fill_diagonal(feromonas, 0)
# cambiar el tipo de la matriz a listas nativas de Python
feromonas = list([list(_) for _ in feromonas])
distancias = list()
# 0. Valle Rocco
distancias.append([0, 20, 10, 33, 8, 2])
# 1. Isla Banshee
distancias.append([20, 0, 6, 15, 5, 3])
# 2. Hongolandia
distancias.append([10, 6, 0, 24, 23, 13])
# 3. Fontana
distancias.append([33, 15, 24, 0, 17, 7])
# 4. Koopalandia
distancias.append([8, 5, 23, 17, 0, 22])
# 5. Springfield
distancias.append([2, 3, 13, 7, 22, 0])
# 6. matriz de pesos
pesos = [d for d in distancias] |
b86abe1335cb3bccf6ab9d37a61f2360d53db4f3 | canbula/wait_and_signal | /main.py | 1,535 | 3.734375 | 4 | import random
import time
from threading import Thread, Condition
class JobsAndUsers:
def __init__(self, number_of_users, number_of_resources, job_size):
self.n = number_of_users
self.r = number_of_resources
self.m = job_size
self.resources = [Condition() for _ in range(number_of_resources)]
self.jobs = [job_size for _ in range(number_of_users)]
def user(self, i):
print("Hi, I am user #%d" % i)
while self.jobs[i] > 0:
time.sleep(3 + random.random())
print("User #%d wants to start now" % i)
r = random.randint(0, self.r - 1)
print("User #%d is trying to get the resource #%d" % (i, r))
if self.resources[r].acquire():
print("User #%d has the resource #%d" % (i, r))
time.sleep(5 + random.random())
self.jobs[i] -= 1
self.resources[r].notify()
self.resources[r].release()
print("User #%d has completed the job" % i)
else:
print("User #%d could not get the resource #%d" % (i, r))
def main():
n = 10
r = 3
m = 100
jobs_and_users = JobsAndUsers(n, r, m)
users = [Thread(target=jobs_and_users.user, args=(i,)) for i in range(n)]
for user in users:
user.start()
'''
while sum(jobs_and_users.jobs):
print(jobs_and_users.jobs)
time.sleep(0.1)'''
for user in users:
user.join()
if __name__ == "__main__":
main()
|
50ab8a86aebc87a51c24521aa58ded5812a7bb1c | kostadinov92/Python-Demo | /dicts.py | 1,190 | 4.0625 | 4 | temperatures = {
'София': -14,
'Новосибирск': -31,
'Таити': 30,
'Таити1': [30, 2],
'Варна': {22, 3},
'Русе': {
"temperature": -23,
"humidity": 90,
},
'ловдив': None,
'Пазарджик': None
}
print("-" * 20)
print(temperatures)
print(temperatures['София'])
print(temperatures.get('Бургас'))
print(temperatures.get('Бургас', 'No data'))
print(temperatures.get('София', 'No data'))
# temp_burgas = temperatures.setdefault('Бургас', -2)
print("-" * 20)
key = 'Бургас'
if key in temperatures:
print(temperatures[key])
else:
print("No data for {}".format(key))
temperatures['Пловдив'] = 31
print(temperatures)
print("-" * 20)
for city_name in temperatures:
temperature_data = temperatures[city_name]
print(city_name, ' -> ', temperature_data)
for neshto in temperatures.items():
key, value = neshto
print(neshto)
print(key)
print(value)
for city_name, temperature_data in temperatures.items():
print(city_name, ' -> ', temperature_data)
for temperature_data in temperatures.values():
print(temperature_data)
|
fc5cfcfae2c7e0a44cc29705b057c357bb8d143e | kostadinov92/Python-Demo | /mostCommonLetters.py | 1,325 | 3.75 | 4 | import math
MAX_LETTERS = 20
def collect_data(text: str) -> dict:
if not text:
raise ValueError('The text is empty.')
letters = {}
for ch in text.upper():
if ch.isalpha():
if ch not in letters:
letters[ch] = 0
letters[ch] += 1
return letters
def compute_data(data: dict) -> list:
if not data:
raise ValueError('There is no letters.')
pairs = sorted(data.items(), key=lambda i: (-i[1], i[0]))
return pairs[:MAX_LETTERS]
def get_graphic_data(tuples: list) -> str:
graphic = ['Most common letters:', '']
max_value = tuples[0][1]
factor = MAX_LETTERS / max_value
padding = 0
while max_value > 0:
padding += 1
max_value //= 10
for key, value in tuples:
graphic.append('{}: {} {}'.format(key,
str(value).rjust(padding),
'#' * (math.ceil(factor * value) or 1)))
return str.join('\n', graphic)
def solve(text: str):
print(get_graphic_data(compute_data(collect_data(text))))
if __name__ == '__main__':
while True:
try:
text = input('Please enter some text: ')
solve(text)
break
except ValueError as e:
print(e)
|
28b37589581db73560df3b438c7101b7c08379c6 | BitScriptor/MetodosNumericos | /regresionLineal.py | 1,055 | 3.546875 | 4 | #!/usr/bin/python
from sympy import *
x = Symbol('x')
ejex=[]
ejey=[]
xmedia = 0.0
ymedia = 0.0
b1num = 0.0
b1den = 0.0
datosx = input("Cuantos datos insertaras?: ")
for i in range (0,datosx):
columna1 = input("Introduce el dato %d de la primer columna: " %i)
columna2 = input("Introduce el valor del dato anterior: ")
print "\n"
ejex.append(columna1)
ejey.append(columna2)
print "\n\t\tEJE X EJE Y \n\n"
for i in range (len(ejex)):
print "\t\t", ejex[i],"\t\t\t", ejey[i],"\n\n"
for i in range(len(ejex)):
xmedia = (xmedia + ejex[i])
ymedia = (ymedia + ejey[i])
xmediat = xmedia / len(ejex)
ymediat = ymedia / len(ejex)
print "\nLa media de x es: ", xmediat, "\n\n"
print "La media de y es: ", ymediat, "\n\n"
for i in range(len(ejex)):
b1num = b1num + (ejex[i] - xmediat) * (ejey[i] - ymediat)
b1den = b1den + (ejex[i] - xmediat)**2
b1 = (b1num) / (b1den)
b0 = (ymediat -(b1*xmediat))
y = b0 + (b1*x)
print "El valor de b1 es: ", b1, "\n\n"
print "El valor de b0 es: ", b0, "\n\n"
print "La formula es: \t\t y = ", y, "\n\n\n"
|
e7b4fe817ae3bde42f8fa61638a4e1a8251c1086 | dongwookang95/PythonAndRubyPrac | /Practice14/practice14.py | 163 | 3.859375 | 4 | input = 33
real_andy = 11
real_abc = "ab"
if real == input:
print("hoe")
elif real_andy == input:
print("hey andy")
else:
print("you are not a hoe")
|
cdd2515c906f5e2d6baf680b81e63cbe8930d015 | ChrisChrisRivera/CS1-Lab | /main.py | 273 | 3.8125 | 4 | xValue= 20
while xValue>=10:
print(xValue)
xValue= xValue - .5
for i in range(25):
import math
print(math.sqrt(i))
vaild= False
while not vaild:
value= int(input("number please"))
if value > 0 and value < 100:
valid= True
else:
print("CORRECT!") |
15774b26dae087e6ec683e676046c29d2009b904 | devimonica/Python-exercises---Mosh-Hamedani-YT- | /4.py | 490 | 4.5 | 4 | # Write a function called showNumbers that takes a parameter called limit. It should
# print all the numbers between 0 and limit with a label to identify the even and odd numbers. For example,
# if the limit is 3, it should print:
# 0 EVEN
# 1 ODD
# 2 EVEN
# 3 ODD
# Solution:
def showNumbers(limit):
for number in range(0, limit+1):
if number % 2 == 0:
print(f'{number} EVEN')
else:
print(f'{number} ODD')
showNumbers(5)
|
adbdfb2b999bdc80235f70a51e552491b4b96456 | Saurav-bit/Hacktober | /sum.py | 120 | 3.90625 | 4 | a=0
b=1
print(a,b)
n=int(input("enter a number"))
for i in range (n-2):
c=a+b
a=b
b=c
print(c)
|
30ac424917d40846e2e494400a194358a06578ef | StephanOn/Project1 | /Ausgabe.py | 272 | 3.65625 | 4 | # Datumsabfrage
print("Geben Sie ein Datum ein (TT.MM.JJJJ):")
x = input()
z = x[6] + x[7] + x[8] + x[9] + x[3] + x[4] + x[0] + x[1]
# Definition des Dateinamens
filename = z+".txt"
f = open(filename, "r")
# Ausgabe des Dateiinhalts
print(f.read())
|
77891051a793383d0ec33c5570cb1a0674dcd938 | jgeilers/nyt_spelling_bee_word_finder | /word_finder.py | 680 | 3.59375 | 4 | import sys
import json
## READS JSON FILE
with open(sys.argv[1], "r") as JSON:
json_dict = json.load(JSON)
letters, alph = sys.argv[2], "qwertyuiopasdfghjklzxcvbnm"
required, additional = letters[0], letters[1:]
## FOR JSON FILE WITH ALPHABET LETTERS AS KEYS AND
## WORDS CONTAINING THAT LETTER AS VALUES
common = set(json_dict[required])
for letter in additional:
letter_set = set(json_dict[letter])
intersection = common.intersection(letter_set)
only_A = common - letter_set
common = only_A.union(intersection)
final = set()
not_included = set(alph) - set(letters)
for word in common:
if len(set(word).intersection(not_included)) == 0:
final.add(word)
print(final) |
ef5ff75446d45350e4c3399889891eab99db4b28 | marekbrzo/CodingPractice | /rotateArray.py | 428 | 3.703125 | 4 | def rotateArray(A,k):
if k == 0 or k == len(A):
return print(A)
elif k > len(A):
return print(A)
else:
output = []
output = A[-k:]
output.extend(A[0:-k])
return print(output)
rotateArray([1,2,3,4,5,6,7,8,9,10],2)
rotateArray([1,2,3,4,5,6,7,8,9,10],0)
rotateArray([1,2,3,4,5,6,7,8,9,10],10)
rotateArray([1,2,3,4,5,6,7,8,9,10],11)
rotateArray([1,2,3,4,5,6,7,8,9,10],9)
|
d5d3b540482b581ad95e5a4d4ab4e8dbcc1280fd | gninoshev/SQLite_Databases_With_Python | /delete_records.py | 411 | 4.1875 | 4 | import sqlite3
# Connect to database
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Order By Database - Order BY
c.execute("SELECT rowid,* FROM customers ORDER BY rowid ")
# Order Descending
c.execute("SELECT rowid,* FROM customers ORDER BY rowid DESC")
items = c.fetchall()
for item in items:
print(item)
# Close out connection
conn.close()
|
3122c8fdebd7f0643e99d8132225f97aed98fe0f | sanjay19/gopal | /amstrongint.py | 205 | 3.546875 | 4 | y=int(input())
z=int(input())
for num in range(y,z):
order = len(str(num))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
|
6ce623ff50e0e6c030bf8f53f2f2c43e2bafdfe2 | WerterHong/Machine-Learning-Algorithm-NLP | /code/binary_search.py | 521 | 3.5 | 4 | import sys
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
if __name__ == '__main__':
list_num = int(sys.stdin.readline().strip())
list_1 = []
for _ in range(list_num):
list_1.append(list(map(int, sys.stdin.readline().strip().split()))
print(binary_search(list_1[_], 4))
|
fc4353c5386b5d2497e0f1cfa7bd2d0503c7f1c1 | kaloyansabchev/Programming-Basics-with-Python | /05 While Loop Lab/02. Password.py | 151 | 3.53125 | 4 | username = input()
password = input()
new_password = input()
while new_password != password:
new_password = input()
print(f"Welcome {username}!") |
5a0637856f9dddcb3d6667340def81e831361c7d | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 20 and 21 February 2021/03. Computer Room.py | 755 | 4.25 | 4 | month = input()
hours = int(input())
people_in_group = int(input())
time_of_the_day = input()
per_hour = 0
if month == "march" or month == "april" or month == "may":
if time_of_the_day == "day":
per_hour = 10.50
elif time_of_the_day == "night":
per_hour = 8.40
elif month == "june" or month == 'july' or month == "august":
if time_of_the_day == "day":
per_hour = 12.60
elif time_of_the_day == "night":
per_hour = 10.20
if people_in_group >= 4:
per_hour *= 0.9
if hours >= 5:
per_hour *= 0.5
price_per_person = per_hour
total_price = (price_per_person * people_in_group) * hours
print(f"Price per person for one hour: {price_per_person:.2f}")
print(f"Total cost of the visit: {total_price:.2f}") |
9c9e6b4602f9b5df1273b9d42b2972276a32b104 | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 20 and 21 February 2021/02. Spaceship.py | 445 | 3.90625 | 4 | import math
width = float(input())
lenght = float(input())
high = float(input())
astronaught_h = float(input())
rocket_s = width * lenght * high
room_s = (astronaught_h + 0.4) * 2 * 2
persons = rocket_s / room_s
persons = math.floor(persons)
if persons <= 2:
print(f"The spacecraft is too small.")
elif 3 <= persons <= 10:
print(f"The spacecraft holds {persons} astronauts.")
elif persons > 10:
print(f"The spacecraft is too big.") |
a818501d5eccec65ef65fe2d1cf461258ade1e99 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Lab/11. Fruit Shop.py | 1,773 | 4.125 | 4 | product = input()
day = input()
quantity = float(input())
if day == "Saturday" or day == "Sunday":
if product == 'banana':
banana_cost = 2.70 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.25 * quantity
print(f'{apple_cost:.2f}')
elif product == 'orange':
orange_cost = 0.90 * quantity
print(f'{orange_cost:.2f}')
elif product == 'grapefruit':
grapefruit_cost = 1.60 * quantity
print(f'{grapefruit_cost:.2f}')
elif product == 'kiwi':
kiwi_cost = 3.00 * quantity
print(f'{kiwi_cost:.2f}')
elif product == 'pineapple':
pineapple_cost = 5.60 * quantity
print(f'{pineapple_cost:.2f}')
elif product == 'grapes':
grapes_cost = 4.20 * quantity
print(f'{grapes_cost:.2f}')
else:
print('error')
elif day == "Monday" or day == "Tuesday" or day == "Wednesday" or day == "Thruesday" or day == "Friday":
if product == 'banana':
banana_cost = 2.50 * quantity
print(f'{banana_cost:.2f}')
elif product == 'apple':
apple_cost = 1.20 * quantity
print(f'{apple_cost:.2f}')
elif product == 'orange':
orange_cost = 0.85 * quantity
print(f'{orange_cost:.2f}')
elif product == 'grapefruit':
grapefruit_cost = 1.45 * quantity
print(f'{grapefruit_cost:.2f}')
elif product == 'kiwi':
kiwi_cost = 2.70 * quantity
print(f'{kiwi_cost:.2f}')
elif product == 'pineapple':
pineapple_cost = 5.50 * quantity
print(f'{pineapple_cost:.2f}')
elif product == 'grapes':
grapes_cost = 3.85 * quantity
print(f'{grapes_cost:.2f}')
else:
print('error')
else:
print("error") |
422e3e5875226f17df321bfa3b7b568a57ac361b | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 6 and 7 July 2019/04. Renovation.py | 703 | 3.71875 | 4 | import math
wall_h = int(input())
wall_w = int(input())
percentage_wp = int(input()) # част която няма да се боядисва
total_area = wall_h * wall_w * 4
area_for_painting = total_area - (total_area * percentage_wp / 100)
while True:
painted = input()
if painted == "Tired!":
print(f"{math.ceil(area_for_painting)} quadratic m left.")
break
painted = int(painted)
area_for_painting -= painted
if area_for_painting < 0:
print(f"All walls are painted and you have {math.ceil(abs(area_for_painting))} l paint left!")
break
elif area_for_painting == 0:
print(f"All walls are painted! Great job, Pesho!")
break
|
a743f255baf631681fd5c9b3d2c95d8d7ba07d34 | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 28 and 29 March 2020/03. Energy Booster.py | 3,582 | 3.84375 | 4 | fruit = input()
size = input()
quantity = int(input())
if fruit == "Watermelon":
if size == "small":
small_W_price = quantity * 2 * 56
if small_W_price < 400:
print(f'{small_W_price:.2f} lv.')
elif 400 <= small_W_price <= 1000:
final_price = small_W_price - small_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif small_W_price > 1000:
final_price = small_W_price - small_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif size == "big":
big_W_price = quantity * 5 * 28.7
if big_W_price < 400:
print(f'{big_W_price:.2f} lv.')
elif 400 <= big_W_price <= 1000:
final_price = big_W_price - big_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif big_W_price > 1000:
final_price = big_W_price - big_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif fruit == "Mango":
if size == "small":
small_W_price = quantity * 2 * 36.66
if small_W_price < 400:
print(f'{small_W_price:.2f} lv.')
elif 400 <= small_W_price <= 1000:
final_price = small_W_price - small_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif small_W_price > 1000:
final_price = small_W_price - small_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif size == "big":
big_W_price = quantity * 5 * 19.6
if big_W_price < 400:
print(f'{big_W_price:.2f} lv.')
elif 400 <= big_W_price <= 1000:
final_price = big_W_price - big_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif big_W_price > 1000:
final_price = big_W_price - big_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif fruit == "Pineapple":
if size == "small":
small_W_price = quantity * 2 * 42.10
if small_W_price < 400:
print(f'{small_W_price:.2f} lv.')
elif 400 <= small_W_price <= 1000:
final_price = small_W_price - small_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif small_W_price > 1000:
final_price = small_W_price - small_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif size == "big":
big_W_price = quantity * 5 * 24.80
if big_W_price < 400:
print(f'{big_W_price:.2f} lv.')
elif 400 <= big_W_price <= 1000:
final_price = big_W_price - big_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif big_W_price > 1000:
final_price = big_W_price - big_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif fruit == "Raspberry":
if size == "small":
small_W_price = quantity * 2 * 20
if small_W_price < 400:
print(f'{small_W_price:.2f} lv.')
elif 400 <= small_W_price <= 1000:
final_price = small_W_price - small_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif small_W_price > 1000:
final_price = small_W_price - small_W_price * 0.5
print(f'{final_price:.2f} lv.')
elif size == "big":
big_W_price = quantity * 5 * 15.2
if big_W_price < 400:
print(f'{big_W_price:.2f} lv.')
elif 400 <= big_W_price <= 1000:
final_price = big_W_price - big_W_price * 0.15
print(f'{final_price:.2f} lv.')
elif big_W_price > 1000:
final_price = big_W_price - big_W_price * 0.5
print(f'{final_price:.2f} lv.')
|
b4ef7e9dc074915ea667f55af0b95f81618b93ae | kaloyansabchev/Programming-Basics-with-Python | /PB - More Exercises/Simple Operations and Calculations/05. Training Lab.py | 208 | 3.640625 | 4 | import math
w = float(input())
h = float(input())
height = h * 100 - 100
h_desk = math.floor(height / 70)
wide = w * 100
w_desk = math.floor(wide / 120)
total_desks = h_desk * w_desk - 3
print(total_desks) |
1fac4c4ecff8b35c4290f3080edd14464cf6140a | kaloyansabchev/Programming-Basics-with-Python | /05 While Loop Lab/09. Moving.py | 381 | 3.8125 | 4 | width = int(input())
lenght = int(input())
hight = int(input())
volume = width * lenght * hight
command = input()
while command != 'Done':
boxes = int(command)
volume -= boxes
if volume <= 0:
print(f'No more free space! You need {abs(volume)} Cubic meters more.')
break
command = input()
if volume > 0:
print(f"{volume} Cubic meters left.") |
3af6201978625babdf6f693331cc09b65b8054bc | kaloyansabchev/Programming-Basics-with-Python | /04 For Loop Lab/08. Number sequence.py | 313 | 3.84375 | 4 | import sys
numbers = int(input())
bigger_n = -sys.maxsize
smaller_n = sys.maxsize
for n in range(1, numbers+1):
number = int(input())
if number < smaller_n:
smaller_n = number
if number > bigger_n:
bigger_n = number
print(f'Max number: {bigger_n}')
print(f'Min number: {smaller_n}') |
d21876b84f4f1b0c5548e785e8c9ce1cafa55615 | kaloyansabchev/Programming-Basics-with-Python | /PB - More Exercises/Simple Operations and Calculations/06. Fishland.py | 433 | 3.515625 | 4 | mackerel_price = float(input())
caca_price = float(input())
bonito_kg = float(input())
horse_mackerel_kg = float(input())
mussels_kg = float(input())
bonito_price = mackerel_price * 1.6
horse_mackerel_price = caca_price * 1.8
sum_bonito = bonito_price * bonito_kg
sum_horse_mackerel = horse_mackerel_price * horse_mackerel_kg
sum_mussels = mussels_kg * 7.5
total = sum_mussels + sum_bonito + sum_horse_mackerel
print(f'{total:.2f}') |
9a6a0e05d1e457673a032e4806b051a67e68c612 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Lab/04. Personal Titles.py | 869 | 3.953125 | 4 | # 4. Обръщение според възраст и пол
# Да се напише конзолна програма, която прочита възраст (реално число) и пол ('m' или 'f'), въведени от
# потребителя, и отпечатва обръщение измежду следните:
# • "Mr." – мъж (пол 'm') на 16 или повече години
# • "Master" – момче (пол 'm') под 16 години
# • "Ms." – жена (пол 'f') на 16 или повече години
# • "Miss" – момиче (пол 'f') под 16 години
age = float(input())
gender = input()
if gender == 'm':
if age >= 16:
print('Mr.')
else:
print('Master')
elif gender == 'f':
if age >= 16:
print('Ms.')
else:
print('Miss') |
e48d2ef1b48c79abd6ce8e422e29e70da3db6d0b | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 28 and 29 March 2020/06. Tournament of Christmas.py | 780 | 3.765625 | 4 | days = int(input())
money_won = 0
total_wins = 0
total_loses = 0
for day in range(1, days+1):
result = input()
money_won_per_day = 0
wins = 0
loses = 0
while result != "Finish":
result = input()
if result == "win":
wins += 1
money_won_per_day += 20
elif result == "lose":
loses += 1
if wins > loses:
money_won_per_day *= 1.1
total_wins += 1
else:
total_loses += 1
money_won += money_won_per_day
total_money = 0
if total_wins > total_loses:
total_money = money_won * 1.2
print(f"You won the tournament! Total raised money: {total_money:.2f}")
else:
total_money = money_won
print(f"You lost the tournament! Total raised money: {total_money:.2f}")
|
a5d9d23300010113265e515b094ea70e482283f3 | kaloyansabchev/Programming-Basics-with-Python | /PB Exam - 18 and 19 July 2020/01. Agency Profit.py | 435 | 3.8125 | 4 | company = input()
tickets_adult = int(input())
tickets_kids = int(input())
ticket_price = float(input())
fee = float(input())
kid_t_price = ticket_price * 0.3
tickets_adult_total = ticket_price + fee
tickets_kids_total = kid_t_price + fee
total_t_price = tickets_adult_total * tickets_adult + tickets_kids_total * tickets_kids
profit = total_t_price * 0.2
print(f"The profit of your agency from {company} tickets is {profit:.2f} lv.") |
3d5213bbc4c322cf07f2bd4c2814d5fcd772f6d2 | kaloyansabchev/Programming-Basics-with-Python | /03 Conditional Statements Advanced Exercise/06. Operations Between Numbers.py | 746 | 4.0625 | 4 | n1 = int(input())
n2 = int(input())
operatora = input()
result = 0
result_type = ''
if n2 == 0 and operatora == '/' or n2 == 0 and operatora == '%':
print(f"Cannot divide {n1} by zero")
quit()
if operatora == '+':
result = n1 + n2
elif operatora == '-':
result = n1 - n2
elif operatora == '*':
result = n1 * n2
elif operatora == '/':
result = n1 / n2
elif operatora == '%':
result = n1 % n2
if result % 2 == 0:
result_type = 'even'
else:
result_type = 'odd'
if operatora == '+' or operatora == '-' or operatora == '*':
print(f'{n1} {operatora} {n2} = {result} - {result_type}')
elif operatora == '/':
print(f'{n1} / {n2} = {result:.2f}')
elif operatora == '%':
print(f'{n1} % {n2} = {result}') |
10ab4f1dcd7a222356255a18de53c248e15445c9 | moreirab/nfml-quizzes | /estatistica-descritiva-2/investimentos.py | 611 | 3.6875 | 4 | import math
def calc_variance(dataset):
mean = sum(dataset)/len(dataset)
variances = []
for value in dataset:
variances.append((value - mean)**2)
variance = sum(variances)/len(dataset)
return variance
def calc_std(variance):
return math.sqrt(variance)
def print_spread(dataset):
variance = calc_variance(dataset)
std = calc_std(variance)
print('Variance: {}; Standard Deviation: {}'.format(variance, std))
return
i1 = [5, 5, 5, 5, 5, 5]
i2 = [12, -2, 10, 0, 7, 3]
print('Investimentos 1')
print_spread(i1)
print('')
print('Investimentos 2')
print_spread(i2) |
49db4a8b1194738347865c019d9b4964b91d5dd8 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-2]120210198_윤동성_2.py | 520 | 3.875 | 4 | import math
bottle = []
def vol():
pi = math.pi
bottle.append(bottle[1]*pi*(bottle[0]**2))
bottle.append((bottle[2]/bottle[3])*100)
bottle[3] = round(bottle[3], 2)
bottle[4] = round(bottle[4], 2)
if bottle[4] > 100:
bottle.append("overflow")
else:
bottle.append("")
return bottle
bottle = list(map(float, input("Enter height & radius: ").split()))
vol()
print("volume of bucket :%.2f" %bottle[3])
print("percentage of water : %.2f%% %s" %(bottle[4], bottle[5]))
|
3635376bd58b8f471349f69ff5f6c630c03b3d71 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[4장-1]120210198_윤동성_2.py | 275 | 3.71875 | 4 | s1 = "2021"
s2 = "03"
s3 = "21"
n1 = 12345.12345
n2 = 54321.54321
print("(1) Today is {}/{}/{}" .format(s1, s2, s3))
print("(2) n1={}, n2={}" .format(n1, n2))
print("(3) n1={:!^40.3f}" .format(n1))
print("(4) n2={:15.3e}" .format(n2))
print("(5) n1={:%<10.2f}" .format(n1))
|
a464fedd911ba308f7fab2b30b2e02a1ecd4abf6 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/9장 실습_3-1.py | 404 | 3.875 | 4 | N = int(input("Enter N (0 < N < 10) : "))
#error 출력
if N >= 10 or N <= 0 :
print("ERROR: N must be 0 < N < 10.")
else :
for i in range(1, N+1) :
for j in range(1, i+1) :
print(j, end="")
print()
Lines = N
if N % 2 == 1 :
Lines = N - 1
for i in range(Lines, 0, -1) :
for j in range(1, i + 1) :
print(j, end="")
print()
|
cb257b3f1ee94fcd8e8ab82e07b2114695d6aba4 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습7-2]120210198_윤동성_1.py | 301 | 4.0625 | 4 | st1 = input("Enter the first string:")
st2 = input("Enter the second string:")
st1 = list(st1)
st2 = list(st2)
if sorted(st1) == sorted(st2):
print("%s, %s is anagram." %(str(''.join(st1)),str(''.join(st2))))
else :
print("%s, %s is not anagram." %(str(''.join(st1)),str(''.join(st2))))
|
9d1b60ecdd080b18c5fda1c16624595d257834bd | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/7장 실습_2-1.py | 330 | 3.953125 | 4 | input1_ = input('Enter the first string:')
input2_ = input('Enter the second string:')
input_1 = list(input1_)
input_2 = list(input2_)
if (sorted(input_1) == sorted(input_2)) and (len(input_1) == len(input_2)):
print(input1_, ',', input2_, 'is anagram.')
else:
print(input1_, ',', input2_, 'is not anagram.')
|
acb1feb9d8441bbb0b69f7cf508bb1db2b724e50 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습9-2]120210198_윤동성_2.py | 243 | 3.875 | 4 | n1, n2 = map(int, input("Enter N1, N2(0 < N1 <= N2) : ").split())
n3 = 0
for i in range(n1, n2+1):
if (i % 2) == 0 :
n3 = n3 + i
else :
continue
print("Sum of even numbers between %d and %d is %d." %(n1, n2, n3))
|
5c23970b9349d03185d474b8e99fb917e2de5904 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-1]120210198_윤동성_3.py | 692 | 4.03125 | 4 | def operation(in1):
ft1, ft2, ft3 = in1.split()
ft1 = float(ft1)
ft3 = float(ft3)
result = 0
flag = 0
if ft2 == "+":
result = ft1 + ft3
elif ft2 == "-":
result = ft1 - ft3
elif ft2 == "*":
result = ft1 * ft3
elif ft2 == "/":
if ft3 == 0:
flag = 1
result = str(ft3) + " cannot divide"
else:
result = ft1 / ft3
else:
flag = 1
result = ft2 + " is not supported."
return flag, ft1, ft2, ft3, result
flag, ft1, ft2, ft3, result = operation(input("Enter the operation (Ex 20 * 40) : "))
if flag == 0:
print(ft1,ft2,ft3,"=",result)
else:
print(result)
|
98b2c8fc5aede334d9e12ed1ba0ae7147036b3e2 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습9-1]120210198_윤동성_3.py | 115 | 3.734375 | 4 | s = "Sogang University"
print("original_s:", s)
for i in range(len(s)-1, -1, -1):
print(s[i], end="")
print()
|
d736d5e63095c4835179669dc6c32309190faf29 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[추가3]120210198_윤동성_3.py | 484 | 3.609375 | 4 | flag = True
def strfind(strs):
if len(strs) == 0:
global flag
flag = False
big = 0
small = 0
for i in strs:
if i.islower() == True:
small = small + 1
if i.isupper() == True:
big = big + 1
return big, small
n1, n2 = strfind(input("문자열 입력 : "))
if flag == True:
print("소문자 개수 : %d, 대문자 개수 : %d" %(n2, n1))
else: print("입력 데이터가 없습니다")
|
9fce05d95b44709ad7cdd9ec998969cf622786e0 | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/제출/[실습12-3]120210198_윤동성_3.py | 2,632 | 3.90625 | 4 | student = [["name", "mid", "final", "grade"]]
def menu1():
info = list(input("이름 중간 기말 성적 입력:").split())
if len(info) == 3:
names = set()
if len(student) > 1:
for i in range(1, len(student)):
names.add(student[i][0])
if info[0] in names:
print("이미 존재하는 학생 정보입니다.")
else:
info[1] = int(info[1])
info[2] = int(info[2])
grade = (info[1]*0.4) + (info[2]*0.6)
if grade > 89 :
grade = "A"
elif grade > 79 :
grade = "B"
elif grade > 69 :
grade = "C"
else:
grade = "D"
info.append(grade)
student.append(info)
else:
print("입력 데이터 갯수 오류입니다.")
def menu2():
if len(student) <= 1:
print("입력된 학생 정보가 없습니다")
else:
print("%s\t%s\t%s\t%s\t" %(student[0][0],student[0][1],student[0][2],student[0][3]))
print("----------------------------------------------")
for i in range(1, len(student)):
print("%s\t%d\t%d\t%s" %(student[i][0],student[i][1],student[i][2],student[i][3]))
pass
def menu3():
if len(student) > 1:
name1 = input("삭제할 학생의 이름을 입력 :")
temp = False
idx = 0
for i in student:
if name1 in i:
temp = True
break
else:
pass
idx = idx + 1
if temp == True:
del student[idx]
print("%s 학생의 정보를 삭제했습니다." %name1)
else:
print("정보가 업는 학생입니다.")
else:
print("입력된 학생 정보가 없습니다.")
print("*Menu***********************************")
print("1. 성적 관리 (입력 형태는 name score1 score2)")
print("2. 학생 정보 출력")
print("3. 학생 정보 삭제")
print("4. 프로그램 종료")
print("****************************************")
while True:
menu = input("메뉴 1,2,3,4번 중 하나 선택 :")
if menu.isdigit() == False:
print("숫자를 입력해 주세요")
else:
menu = int(menu)
if menu == 1:
menu1()
elif menu == 2:
menu2()
elif menu == 3:
menu3()
elif menu == 4:
print("프로그램을 종료합니다.")
break;
else :
print("없는 번호의 명령어입니다. 다시 선택하세요.")
|
7e51aaadada9158e4049e1d7b3f9f060b51db255 | i-fernandez/Project-Euler | /Problem_047/problem_47.py | 1,354 | 3.546875 | 4 | """
Find the first four consecutive integers to have four distinct prime
factors each. What is the first of these numbers?
"""
from math import sqrt
def is_prime_from_list(n):
global prime_list
if len(prime_list) == 0:
return True
for p in prime_list:
if n%p == 0:
return False
return True
def next_prime(index):
while True:
index += 1
if is_prime_from_list(index):
prime_list.append(index)
return index
def factorize_number(number):
factors = []
objective = number
while not is_prime_from_list(objective):
for i in prime_list:
if objective%i == 0:
# Elimina factores duplicados
if i not in factors:
factors.append(i)
objective = objective / i
break
return factors
# Genera los primos
index = 1
prime_list = []
for i in range(0,20000):
index = next_prime(index)
print(f'Ultimo primo: {prime_list[len(prime_list)-1]}')
start = 100000
n_factores = 4
count = 0
while count < n_factores:
if len(factorize_number(start)) == n_factores:
count += 1
#print(f'{start} -- {count}')
if count > 1:
print(f'{start} -- {count}')
else:
count = 0
start += 1
print(f'{start - n_factores}')
|
00748cd7fff30c9aa50b89a0e72f454fd510dd33 | i-fernandez/Project-Euler | /Problem_014/problem_14.py | 742 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 30 13:18:25 2020
@author: israel
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Which starting number, under one million, produces the longest chain?
"""
def get_sequence(number):
count = 0
n = number
#print(n)
while n > 1:
count += 1
if n%2 == 0:
n = int(n / 2)
else:
n = int(3*n + 1)
#print(n)
return count
maximum = 0
number = 0
for i in range(1000000,1,-1):
items = get_sequence(i)
if items > maximum:
maximum = items
number = i
print(f'Number: {number} Items: {maximum}') |
3c13523aef62492df2bb4ed85a28d6b4924f93b5 | i-fernandez/Project-Euler | /Problem_035/problem_35.py | 991 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 6 18:24:43 2020
@author: israel
The number, 197, is called a circular prime because all rotations
of the digits: 197, 971, and 719, are themselves prime.
How many circular primes are there below one million?
"""
def is_prime_number(n):
if n < 0:
return False
start = int(n**0.5)
for i in range(start, 1, -1):
if n%i == 0:
return False
return True
def get_rotations(num):
str_num = str(num)
rotations = []
for i in range(0,len(str_num)):
n = int(str_num[i:len(str_num)] + str_num[0:i])
rotations.append(n)
return rotations
def is_rotation_prime(numbers):
for n in numbers:
if not is_prime_number(n):
return False
return True
result = []
for i in range(2,1000000):
if is_rotation_prime(get_rotations(i)):
result.append(i)
print(result)
print(f'Number of items: {len(result)}')
|
44b081ed32f22ae2fc0f5cebfaeab6fd1bf85390 | i-fernandez/Project-Euler | /Problem_005/problem_5.py | 1,392 | 3.90625 | 4 | """
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
# Primeros 4 numeros primos
primes = [2,3,5,7]
# Obtiene una lista con los factores de un numero
def get_factors(n):
if n in primes:
return [int(n)]
else:
#print(f'Calling with n={n}')
for i in range (2,int(n)):
if int(n)%i == 0:
#print(f'Factor found: {i}')
resto = get_factors(int(n)/i)
return [*resto, *[int(i)]]
return[int(n)]
# Devuelve un diccionario con el numer de ocurrencias de cada factor
def dict_factor(factores):
dic = {}
for i in factores:
if i in dic.keys():
dic[i] += 1
else:
dic[i] = 1
return dic
# A partir de un diccionario factor/ocurrencias, saca en mcm
def get_mcm(factores: dict):
resultado = 1
for i in factores.keys():
n = i**factores[i]
resultado = resultado * n
return resultado
all_divisors = {}
for n in range(2,21):
factores = dict_factor(get_factors(n))
for f in factores.keys():
if f in all_divisors:
if all_divisors[f] < factores[f]:
all_divisors[f] = factores[f]
else:
all_divisors[f] = factores[f]
print(f'All divisors: {all_divisors}')
mcm = get_mcm(all_divisors)
print(f'The mcm is: {mcm}')
|
cd4df12309cf4c0b7b4aa9dfa093404c356084f6 | i-fernandez/Project-Euler | /auxiliary.py | 1,932 | 3.5 | 4 |
# Devuelve true si n es primo (sin conocimiento previo)
def is_prime_number(n):
if n < 2:
return False
end = int(n**0.5)
for i in range(2, end+1):
if n%i == 0:
return False
return True
# Devuelve true si n es primo
# Se apoya en prime_list, que contiene los primos descubiertos
# hasta el momento
def is_prime_from_list(n, prime_list):
if len(prime_list) == 0:
return True
for p in prime_list:
if n%p == 0:
return False
return True
prime_list = []
# Genera todas las permutaciones posibles entre los digitos de r
def get_permutations(r):
if len(r) == 1:
return [r]
output = []
for i in range(0,len(r)):
resto = r[0:i] + r[i+1:len(r)]
comb = get_permutations(resto)
for p in comb:
l = [r[i]] + p
# No añade duplicados
if l not in output:
output.append(l)
return output
# Convierte las permutaciones a enteros
def array_to_str(array: list) -> int:
array_n = [str(n) for n in array]
return int(''.join(array_n))
# Devuelve true si el elemento x está en arr
# busqueda binaria
def is_present(arr, x):
low = 0
high = len(arr) - 1
mid = 0
if x < arr[0] or x > arr[len(arr)-1]:
return False
while low <= high:
mid = (high + low) // 2
if x == arr[mid]:
return True
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
return False
# Devuelve una lista de factores unicos de number
def get_factores(number):
factores = []
resto = number
for i in range(2,int(sqrt(number)+1)):
if resto % i == 0:
factores.append(i)
while resto % i == 0:
resto = resto / i
if resto == 1:
return factores
factores.append(int(resto))
return factores |
86fc473e69d613957f64071f74deccb56705e5e0 | i-fernandez/Project-Euler | /Problem_037/problem_37.py | 986 | 3.984375 | 4 | """
Find the sum of the only eleven primes that are both truncatable
from left to right and right to left.
"""
def is_prime_number(n):
if n < 2:
return False
start = int(n**0.5)
for i in range(start, 1, -1):
if n%i == 0:
return False
return True
def all_primes(numbers):
for i in numbers:
if not is_prime_number(i):
return False
return True
def is_truncatable(number):
if not is_prime_number(number):
return False
t = set()
st_num = str(number)
for i in range(1,len(st_num)):
t.add(int(st_num[0:i]))
t.add(int(st_num[i:]))
#print(t)
return all_primes(t)
trunc_count = 0
trunc_list = []
total = 0
index = 10
while trunc_count < 11:
if is_truncatable(index):
trunc_count += 1
trunc_list.append(index)
total += index
print(f'Suma: {total}')
print(trunc_list)
index += 1
print(f'Suma: {total}')
print(trunc_list)
|
3b46d280e7581cb9cf36098bf3375b126a9305b7 | i-fernandez/Project-Euler | /Problem_004/problem_4.py | 862 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 19:32:24 2020
@author: israel
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(number):
st = str(number)
size = len(st)
for i in range(0,int(size/2)):
if (st[i] != st[size-i-1]):
return False
return True
# Comprueba si es divisible por dos numeros de tres digitos
def is_divisible(n):
for i in range(999,100,-1):
if n%i == 0:
r = int(n/i)
st = str(r)
if len(st) == 3:
print(f'Eureka: {n} = {i} * {r}')
return True
return False
max_val = 999*999
cont = True
while cont:
for i in range(max_val,100,-1):
if is_palindrome(i) and is_divisible(i):
cont = False
break
|
8d8679553a6740ffd22e782108d22493ee3c652b | i-fernandez/Project-Euler | /Problem_055/problem_55.py | 849 | 3.953125 | 4 | """
A number that never forms a palindrome through the reverse and add process is called a Lychrel number.
How many Lychrel numbers are there below ten-thousand?
"""
def is_palindrome(number):
st_n = str(number)
st_r = ''
for i in range(len(st_n)-1,-1,-1):
st_r += st_n[i]
return st_n == st_r
def get_reverse(number):
st_n = str(number)
st_r = ''
for i in range(len(st_n)-1,-1,-1):
st_r += st_n[i]
return int(st_r)
def is_Lychrel(number):
suma = number
for i in range(1,51):
r = get_reverse(number)
suma += r
if is_palindrome(suma):
return False
number = suma
return True
non_lychrel = []
for i in range(2,10001):
if is_Lychrel(i):
non_lychrel.append(i)
print(non_lychrel)
print(f'Non Lychrel nunmbers: {len(non_lychrel)}')
|
bb2ff59d2062a5b6ab007782f05653c2fd7fb1c1 | Ramya74/ERP-projects | /Employee.py | 1,296 | 4.25 | 4 | employees = [] #empty List
while True:
print("1. Add employee")
print("2. Delete employee")
print("3. Search employee")
print("4. Display all employee")
print("5. Change a employee name in the list")
print("6. exit")
ch = int(input("Enter your choice: "))
if ch is None:
print("no data present in Employees")
elif ch == 1:
#Add employee
name = input("Enter name: ")
employees.append(name)
#in one line
#employees.append(input("Enter name: "))
elif ch == 2:
#Delete employee
print(employees)
print("Choose name from this: ")
name = input("Enter name to delete: ")
employees.remove(name)
elif ch == 3:
#Search employee
name = input("Enter name you want to search: ")
if name in employees:
print(name + " is in the list")
else:
print(name + " not in the list")
elif ch == 4:
#Display employee
#print("---['r','t']---like output")
#print(employees)
for i in range(0,len(employees)):
print(i+1,".",employees[i])
i+=1
elif ch== 5:
#Change a employee name in the list
name = input("Enter the name: ")
index = employees.index(name)
new_name = input("Enter new name: ")
employees[index] = new_name
#employees[employees.index(name)] = input("Enter new name: ")
elif ch == 6:
#Exit
break;
else:
print("Invalid Choice")
|
8bac12f24d04003cb824c7242c9f77102ac8118b | notveryfamous/python-project1 | /number 布尔类型.py | 538 | 4.09375 | 4 | # 布尔类型是数字分类下的一种
print (int (True));
print (isinstance (True,int));
print (isinstance (False,int));
print (bool(1));
print (bool(0));
print (bool(-1));# 在数字类型下,布尔类型为0时,返回False
#布尔值总结
#当布尔值为0、None、空值时,布尔返回类型为False
print (bool(0));
print (bool(None));
print (bool());
print (bool(''));
print (bool(' '));#字符串中间不能有空格
print (bool([]));#空列表
print (bool({}));#空字典
print (bool(()));#空元组 |
d7ec0d578c12d6fa8fca8924d7b4565bc5ebc2de | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex69.py | 735 | 3.5625 | 4 | cont = maior = homem = novinha = 0
while True:
cont+=1
print('-'*40)
idade = int(input(f'Digite a idade da {cont}ª pessoa: '))
sexo = ' '
while sexo not in 'fFmM':
sexo = str(input('Digite o sexo desta pessoa[F/M]: ')).strip().upper()
if idade > 18:
maior +=1
if sexo == 'M':
homem+=1
elif idade < 20:
novinha+=1
parada =' '
while parada not in 'sSNn':
parada = str(input('Deseja continuar? [S/N]')).strip().upper()
print('-'*40)
if parada == 'N':
break
print(f'Foram cadastradas {cont} pessoas')
print(f'A) Tem {maior} pessoas com mais de 18 anos')
print(f'B) Tem {homem} homens')
print(f'C) Tem {novinha} mulheres com menos de 20 anos') |
2fcb3f5d3ade699a7aac7c8eeb93acd714f3d0f8 | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex95.py | 1,226 | 3.75 | 4 | lista_jogadores = list()
while True:
nome = str(input('Nome do jogador: '))
partidas = int(input('Quantas partidas ele jogou? '))
aproveitamento = list()
for i in range(1, partidas+1):
gols = int(input(f'Quantos gols na partida {i}? '))
aproveitamento.append(gols)
totalgols = sum(aproveitamento)
fichajog = {'nome':nome,'gols':aproveitamento,'total':totalgols}
lista_jogadores.append(fichajog)
cont = str(input('Deseja continuar? [S/N] ')).upper()
if cont == 'N':
print('-='*30)
break
print('--'*30)
print('cod ',end='')
for i in fichajog.keys():
print(f'{i:<15} ', end='')
print()
for k,v in enumerate(lista_jogadores):
print(f'{k:>3} ', end='')
for d in v.values():
print(f'{str(d):<15}', end='')
print()
while True:
jog = int(input('Mostrar dados de qual jogador? (999 para terminar) ' ))
if jog == 999:
break
if jog >= len(lista_jogadores):
print(f'ERRO não existe jogador com o código {jog}')
else:
print(f'LEVANTAMENTO DO JOGADOR {lista_jogadores[jog]["nome"]}')
for k,v in enumerate(lista_jogadores[jog]['gols']):
print(f' No jogo {k+1} ele fez {v} gols')
|
da4ad75ecdf8263e72c7c1159cea4a22e84c353f | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex41.py | 309 | 3.90625 | 4 | from datetime import date
ano = int(input('Digite seu ano de nascimento: '))
idade = date.today().year - ano
print('Sua categoria é: ')
if idade > 20:
print('Master')
elif idade > 19:
print('Senior')
elif idade > 14:
print('Junior')
elif idade > 9 :
print('Infantil')
else:
print('Mirim') |
902cb1c5600f00391d9967678cec9721119666ca | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex100.py | 450 | 3.625 | 4 | from random import randint
def sorteio(lista):
print(f'Sorteando 5 valores da lista: ',end='')
for i in range(0,5):
x= randint(1,10)
lista.append(x)
print(f'{x} ', end='', flush=True)
print('PRONTO!')
def somaPar(lista):
soma=0
for i in lista:
if i % 2 == 0:
soma+=i
print(f'Somando os valores pares de {lista}, temos {soma}')
numeros = list()
sorteio(numeros)
somaPar(numeros) |
08ec291cd7b1d00b008385ba689d4840667736ba | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex78.py | 656 | 3.5625 | 4 | lista =[]
maior = 0
menor = 999999
for i in range(0,5):
lista.append(int(input(f'Digite um numero para a posição {i}: ')))
if i ==0:
maior=menor=lista[i]
else:
if lista[i] > maior:
maior = lista[i]
if lista[i] < menor:
menor = lista[i]
print('=-'*20)
print(f'Você digitou os valores {lista}')
print(f'O maior valor digitado foi {maior} nas posições ',end='')
for c,i in enumerate(lista):
if i == maior:
print(f'{c}... ',end='')
print(f'\nO menor valor digitado foi {menor} nas posições ',end='')
for c,i in enumerate(lista):
if i == menor:
print(f'{c}... ',end='') |
29bf78bab98dc250f497fc8b1f72adbdaa36b9dc | Ruymelo10/CursoemvideoPy | /exercicios/mundo3/ex104.py | 392 | 3.796875 | 4 | def leiaint(msg):
bol = False
value = 0
while True:
x = str(input(msg))
if x.isnumeric():
value = int(x)
bol = True
else:
print('\033[0;31mErro! Digite um número inteiro válido\033[m')
if bol:
break
return value
n = leiaint('Digite um numero: ')
print(f'Você acabou de digitar o numero {n}') |
772271882a27bb4d660e2af47ab455b585e846a3 | Ruymelo10/CursoemvideoPy | /exercicios/mundo2/ex52.py | 266 | 4.03125 | 4 | num = int(input('Digite um numero: '))
bool = True
for i in range(num,0,-1):
if i!=num and i!=1:
if num%i==0:
bool=False
if bool == False:
print('O numero {} não é primo'.format(num))
else:
print('O numero {} é primo'.format(num)) |
4cbe2b7aefea9a5e38e2d69f55a1507ec14c9a65 | Aishwaryasri15/Python | /Hangman.py | 3,398 | 3.859375 | 4 | import random
import string
def hangman():
word =random.choice(["pugger","littlepugger","monkey","lemon","tamarind"
,"apple","mango","fruits","ginger","tiger","thor",
"avengers","ironman"])
validletters=string.ascii_lowercase
turns=10
guessmade=''
while len(word)>0:
main=""
missed= 0
for letter in word:
if letter in guessmade:
main=main+letter
else:
main=main+"_"+""
if main == word:
print(main)
print("You win!")
break
print("Guess the word:",main)
guess=input()
if guess.isalpha():
if guess in validletters:
if guess in word:
guessmade=guessmade+guess
validletters=validletters.replace(guess,"")
else:
print("Dont enter repeated letters")
turns=turns-1
else:
print("Enter a valid character")
if guess not in word:
turns = turns - 1
if turns == 9:
print("9 turns left")
print(" -------- ")
if turns == 8:
print("8 turns left")
print(" -------- ")
print(" O ")
if turns == 7:
print("7 turns left")
print(" -------- ")
print(" O ")
print(" | ")
if turns == 6:
print("6 turns left")
print(" -------- ")
print(" O ")
print(" | ")
print(" / ")
if turns == 5:
print("5 turns left")
print(" -------- ")
print(" O ")
print(" | ")
print(" / \ ")
if turns == 4:
print("4 turns left")
print(" -------- ")
print(" \ O ")
print(" | ")
print(" / \ ")
if turns == 3:
print("3 turns left")
print(" -------- ")
print(" \ O / ")
print(" | ")
print(" / \ ")
if turns == 2:
print("2 turns left")
print(" -------- ")
print(" \ O /| ")
print(" | ")
print(" / \ ")
if turns == 1:
print("1 turns left")
print("Last breaths counting, Take care!")
print(" -------- ")
print(" \ O_|/ ")
print(" | ")
print(" / \ ")
if turns == 0:
print("You loose")
print("You let a kind man die")
print(" -------- ")
print(" O_| ")
print(" /|\ ")
print(" / \ ")
break
name=input("Enter your name ")
print("Welcome to Hangman Game",name)
print("----------------")
print("try to guess the word in less than 10 attempts ")
print(hangman())
|
6e6a6cb235727ad6ea5a10bc0a44043d3260f444 | jonsongoffwhite/AlgorithmsCoursework | /Coursework_2/CW2-1 Sampling.py | 10,630 | 4 | 4 |
# coding: utf-8
# # Algorithms 202: Coursework 2 Task 1: Random Sampling
# Group-ID: 32
# Group members: Jonathan Muller, Louis de Beaumont, Jonny Goff-White
# ## Objectives
# The aim of this coursework is to enhance your algorithmic skills by developing algorithms from textual, non-formal descriptions. You are asked to show that you can:
#
# - implement three different random sampling algorithms
# - compare those algorithms using visual representations based on image sampling
#
# This notebook *is* the coursework. It contains cells with function definitions that you will need to complete. You will submit this notebook as your coursework.
# ## Preliminaries: helper functions
# Here we define a collection of functions that will be useful for the rest of the coursework. You'll need to run this cell to get started.
# In[3]:
get_ipython().magic('matplotlib inline')
import numpy as np
from scipy.ndimage import map_coordinates
from scipy.spatial import cKDTree as KDTree
from matplotlib import pyplot as plt
from PIL import Image
def load_image(path):
return np.array(Image.open(str(path)))
def sample_colors(image, sample_points):
r"""
Sample RGB colour values from an image of shape (w, h, 3)
at floating point (x, y) sample points.
"""
r = map_coordinates(image[..., 0], sample_points.T)
g = map_coordinates(image[..., 1], sample_points.T)
b = map_coordinates(image[..., 2], sample_points.T)
return np.vstack((r, g, b)).T
def indices_of_pixels(image):
r"""(x, y) index values for each pixel in an image.
"""
return np.indices(image.shape[:2]).reshape([2, -1]).T
def closest_index(sample_points, indices):
r"""
Find the nearest sample_point at a given index
(along with the distance to the point). Input is
an array of sample_points and an array of indicies to
test at. Output is array of indices and distances.
"""
kdtree = KDTree(sample_points)
distance, index = kdtree.query(indices)
return index, distance
def resample_image(image, sample_points):
# for each (floating point) sample_point extract the
# RGB colour value of the image at that location
colors = sample_colors(image, sample_points)
# get all (x, y) index values for each pixel in
# the image
indices = indices_of_pixels(image)
# for every pixel (each index) find the nearest sample
# point (and the distance, but we don't need it here)
c_index,_ = closest_index(sample_points, indices)
# map the closest indexes to colour values - reshape
# the resulting RGB array back into the original image
# shape.
return colors[c_index].reshape(image.shape)
# ## Task 1: Random Sampling
# In this task you are asked to implement `uniform_sampling`, `best_candidate_sampling` and `poison_disc_sampling`. Additionally, you will need to implement visualising techniques that can be used to compare the output of the three different random sampling algorithms.
#
# Complete the below function definitions in the provided skeleton code. Do not change the names of the functions or their arguments.
# ### 1a. Implement `uniform_sampling`
# The `uniform_sampling` function should produce `n_samples` sample points randomly distributed over the sample domain. See lecture slides for details and pseudo-code. Hint: The sample domain defined by the width and the height of the image can be obtained by `image.shape[:2]`.
# In[7]:
import random
def uniform_sampling(image, n_samples):
samples = []
width = image.shape[0]
height = image.shape[1]
for i in range(n_samples):
samples.append(uniform_sample(width, height))
return np.array(samples)
def uniform_sample(width, height):
x = random.random() * width
y = random.random() * height
return (x, y)
# ### 1b. Implement `best_candidate_sampling`
# The `best_candidate_sampling` function should produce `n_samples` sample points randomly distributed over the sample domain. See lecture slides for details and pseudo-code. Hint: The `best_candidate` function here corresponds to the BEST-CANDIDATE-SAMPLE function in the slides, which generates a single new sample.
# In[8]:
import math
def best_candidate_sampling(image, n_samples, n_candidates):
samples = []
for i in range(n_samples):
samples.append(best_candidate(image, samples, n_candidates))
return np.array(samples)
def distance(point1, point2):
x1 = point1[0]
y1 = point1[1]
x2 = point2[0]
y2 = point2[1]
xsqrd = math.pow(x2-x1, 2)
ysqrd = math.pow(y2-y1, 2)
return math.sqrt(xsqrd+ysqrd)
def find_closest(samples, point):
x = point[0]
y = point[1]
if not samples:
return point
closest = samples[0][0], samples[0][1]
for sample in samples:
if (distance(sample, (x,y)) < distance(closest, (x,y))):
closest = sample
return closest
def best_candidate(image, samples, n_candidates):
width = image.shape[0]
height = image.shape[1]
best_candidate = (0,0)
best_distance = 0
for i in range(n_candidates):
c = uniform_sample(width, height)
d = distance(find_closest(samples, c), c)
if (d > best_distance):
best_distance = d
best_candidate = c
return best_candidate
# ### 1c. Implement `poison_disc_sampling`
# The `poison_disc_sampling` function should produce sample points randomly distributed over the sample domain with a minimum distance of `radius`. See lecture slides and [Bridson's original paper](https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf) for details.
# In[53]:
import math
# Find point is spherical annulus.
def point_in_annulus(point, radius):
a = random.uniform(radius, 2*radius)
b = random.uniform(0, 2*math.pi)
return (point[0] + a*math.cos(b), point[1] + a*math.sin(b))
# Returns true iff the point is within the image.
def in_image(point, image):
width = image.shape[0]
height = image.shape[1]
return (0 <= point[0] < width) and (0 <= point[1] < height)
# Returns true iff point is near existing samples.
def not_near(background_grid, point, radius):
for p in background_grid:
for i in p:
if (i != -1 and distance(i, point) < radius):
return False
return True
def poison_disc_sampling(image, radius, n_candidates):
samples = []
active_list = []
width = image.shape[0]
height = image.shape[1]
cell_size = radius / math.sqrt(2)
grid_width = math.ceil(width / cell_size)
grid_height = math.ceil(height / cell_size)
background_grid = []
for i in range(grid_height):
background_grid.append([-1] * grid_width)
initial_sample = uniform_sample(width, height)
initial_index1 = int(initial_sample[0] / cell_size)
initial_index2 = int(initial_sample[1] / cell_size)
background_grid[initial_index1][initial_index2] = initial_sample
samples.append(initial_sample)
active_list.append(initial_sample)
while active_list: # while active_list not empty
random_index = random.randint(0, len(active_list) - 1)
random_point = active_list[random_index]
for i in range(n_candidates):
point = point_in_annulus(random_point, radius)
if in_image(point, image) and not_near(background_grid, point, radius):
grid_index1 = int(point[0] / cell_size)
grid_index2 = int(point[1] / cell_size)
background_grid[grid_index1][grid_index2] = point
samples.append(point)
active_list.append(point)
active_list.remove(random_point)
return np.array(samples)
# ### Image sampling
# The following cells are for testing and visualisation of your sampling methods.
# #### Load test image
# In[5]:
# image= load_image('./brain.png')
# image = load_image('./face.png')
# image = load_image('./lighthouse.png')
image = load_image('./mandrill.png')
# image = load_image('./parrots.png')
# image = load_image('./starry-night.png')
# image = load_image('./synth.png')
plt.imshow(image)
# #### Generate random samples
# In[63]:
#less samples - good for debugging
# samples_uni = uniform_sampling(image, 685)
# samples_bc = best_candidate_sampling(image, 685, 10)
# samples_pd = poison_disc_sampling(image, 15, 30)
#more samples - looks better
samples_uni = uniform_sampling(image, 2000)
samples_bc = best_candidate_sampling(image, 2000, 10)
samples_pd = poison_disc_sampling(image, 10, 30)
# #### Plot samples
# In[64]:
fig, axs = plt.subplots(1, 3, figsize=(18,5))
axs[0].scatter(samples_uni[:,0], samples_uni[:,1], marker='x')
axs[0].set_title('Uniform Sampling')
axs[1].scatter(samples_bc[:,0], samples_bc[:,1], marker='x')
axs[1].set_title('Best-Candidate Sampling')
axs[2].scatter(samples_pd[:,0], samples_pd[:,1], marker='x')
axs[2].set_title('Poison-Disc Sampling')
plt.show()
# #### Resample images using random samples
# In[65]:
image_uni = resample_image(image, samples_uni)
image_bc = resample_image(image, samples_bc)
image_pd = resample_image(image, samples_pd)
# #### Plot images
# In[66]:
fig, axs = plt.subplots(1, 4, figsize=(15,3))
axs[0].imshow(image)
axs[0].set_title('Original')
axs[1].imshow(image_uni)
axs[1].set_title('Uniform Sampling')
axs[2].imshow(image_bc)
axs[2].set_title('Best-Candidate Sampling')
axs[3].imshow(image_pd)
axs[3].set_title('Poison-Disc Sampling')
plt.show()
# ### 1d. Implement `distance_map` for colouring image points according to their distance to sample points
# The `distance_map` function should generate an image where each pixel intensity is set to the distance to the closest sample point. Hint: You might want to check out the `resample_image` function provided above for guidance.
# In[70]:
def distance_map(image, sample_points):
indices = indices_of_pixels(image)
_, distance = closest_index(sample_points, indices)
return distance.reshape(image.shape[:2])
# #### Generate distance maps using random samples
# In[71]:
distmap_uni = distance_map(image, samples_uni)
distmap_bc = distance_map(image, samples_bc)
distmap_pd = distance_map(image, samples_pd)
# #### Plot distance maps
# In[72]:
fig, axs = plt.subplots(1, 3, figsize=(18,5))
axs[0].imshow(distmap_uni)
axs[0].set_title('Uniform Sampling')
axs[1].imshow(distmap_bc)
axs[1].set_title('Best-Candidate Sampling')
axs[2].imshow(distmap_pd)
axs[2].set_title('Poison-Disc Sampling')
plt.show()
# In[ ]:
|
2552aff90c999eaa5435e856ee47700c32fc2161 | Vicky-hyq/pratice | /pratice/one test one day/文件相关操作/文字竖排/test.py | 1,261 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# coding:utf-8
import sys
stops = '!,。'
stops = stops.decode('utf-8')
print stops
def getLength(poe):
situation = [i for i in range(len(poe)) if poe[i] in stops]
situation.insert(0,-1)
print situation
gaps = [situation[i]-situation[i-1] for i in range(1,len(situation))]
print gaps
if gaps:
return max(gaps)
else:
return None
def transferPoetry(poe,sentLength):
NewPoe = []
tempSent = []
for i in poe:
if i not in stops:
tempSent.append(i)
#print tempSent
elif len(tempSent) < sentLength:
tempSent.append(i)
tempSent +=stops[0]*(sentLength-len(tempSent))
#print tempSent
NewPoe.append(tempSent)
#print NewPoe
tempSent = []
RealPoe = []
for i in xrange(sentLength):
RealPoe.append([NewPoe[x][i] for x in xrange(len(NewPoe))])
for i in xrange(len(RealPoe)):
RealPoe[i].reverse()
RealPoe[i] = '|'.join(RealPoe[i])
return RealPoe
if __name__ == '__main__':
poe = raw_input('Please input your poetry:')
#print type(poe)
poe = poe.decode('utf-8')
#poe = poe.decode(sys.stdin.encoding)
print len((poe))
#print type (poe)
sentLength = getLength(poe)
if sentLength:
for i in transferPoetry(poe,sentLength):
print i
else:
print 'no poetry!!!' |
53708d31b2a96e02795a299fed1c1a017c13fe8b | Vicky-hyq/pratice | /pratice/one test one day/输出乘法表/test.py | 264 | 3.578125 | 4 | #!/usr/bin/python
# -*-coding:utf-8 -*-
'''
i = 1
for m in range(1,10):
while (i <= m):
s = i*m
print ("%d * %d = %d"%(i,m,s))
i = i+1
i = 1
'''
#参考答案更加简洁
for i in range(1,10):
for j in range(1,i+1):
print ("%d * %d = %d"%(j,i,j*i))
|
65bcba9f6366ad8091cfbb4dd2f53dc4af0fd85c | DaeseungLee/devops-eng-training | /unittest/test_functions.py | 682 | 3.53125 | 4 | # TODO(everyone): 더하기, 빼기, 곱하기, 나누기 함수 테스트 케이스 작성
import sys, os
from functions import plus, sub, multiplication, divide, square, sqrt
import pytest
def test_plus():
assert plus(3,4) == 7
assert plus(132,145) == 277
def test_sub():
assert sub(3,4) == -1
assert sub(120, 120) == 0
def test_multiplication():
assert multiplication(3,4) == 12
assert multiplication(-4, -5) == 20
def test_divide():
assert divide(3, 4) == 0.75
assert divide(1, 3) == 0.33
assert divide(4, 0) == None
def test_square():
assert square(2,1) == 2
assert square(3,5) == 243
def test_sqrt():
assert sqrt(4) == 2
|
6a40a28665f8194dc44ebb1fe4b43e80c59614a3 | elgrian/Tweet-Generator | /HistogramLists.py | 825 | 3.5625 | 4 | import re
frequency = {}
first_list = []
second_list = []
document_text = open('frankenstein.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{1,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word, 0)
frequency[word] = count + 1
first_list.append(word)
# first_list.append(int(frequency[word]))
for word in match_pattern:
first_list.append(int(frequency[word]))
second_list.append(first_list)
# second_list.append(int(frequency[word]))
# zipped = zip(first_list, second_list)
# dictionary = (list(set(zipped)))
#
print(str(second_list))
#
# def unique_words():
# print('The amount of unique words in this text file is: ' + str(len(dictionary)))
#
#
#
#
#
# if __name__ == '__main__':
#
# unique_words()
|
79342a6f9022af2503d7f0396a7226ff1a9dbaa5 | jke-zq/my_lintcode | /Intersection of Two Linked Lists.py | 778 | 3.71875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param headA: the first list
# @param headB: the second list
# @return: a ListNode
def getIntersectionNode(self, headA, headB):
# Write your code here
pA, pB = headA, headB
tailA, tailB = False, False
while pA and pB:
if pA == pB:
return pA
pA = pA.next
if not pA and not tailA:
pA = headB
tailA = True
pB = pB.next
if not pB and not tailB:
pB = headA
tailB = True
return None |
a5969e2abbe3bdb906c39937617558dab5b6dff3 | jke-zq/my_lintcode | /Largest Rectangle in Histogram.py | 874 | 3.640625 | 4 | class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
# write your code here
if not height:
return 0
length = len(height)
stack = []
ans = float('-inf')
for i in range(length + 1):
if i == length:
val = -1
else:
val = height[i]
if not stack or height[stack[-1]] <= val:
stack.append(i)
else:
while stack and height[stack[-1]] > val:
cur = stack.pop()
last = -1 if not stack else stack[-1]
ans = max(ans, height[cur] * (i - last - 1))
stack.append(i)
return ans
|
a4234de4dcd883365be5796b61b3086e138acbfe | jke-zq/my_lintcode | /Interleaving String.py | 1,203 | 3.875 | 4 | class Solution:
"""
@params s1, s2, s3: Three strings as description.
@return: return True if s3 is formed by the interleaving of
s1 and s2 or False if not.
@hint: you can use [[True] * m for i in range (n)] to allocate a n*m matrix.
"""
def isInterleave(self, s1, s2, s3):
# write your code here
m, n = len(s1), len(s2)
if m + n != len(s3):
return False
dp = [[0] * (n + 1) for __ in range(m + 1)]
dp[0][0] = 1
for i in range(1, n + 1):
if dp[0][i - 1] and s2[i - 1] == s3[i - 1]:
dp[0][i] = dp[0][i - 1]
# print dp[0]
for i in range(1, m + 1):
if dp[i - 1][0] and s1[i - 1] == s3[i - 1]:
dp[i][0] = dp[i - 1][0]
for j in range(1, n + 1):
if dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]:
dp[i][j] = dp[i - 1][j]
## why break? Dont break!
# break
if dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]:
dp[i][j] = dp[i][j - 1]
# break
# print dp[i]
return bool(dp[m][n]) |
b7f6423314f8b6b884b6da63344c1491c503eda4 | jke-zq/my_lintcode | /Merge k Sorted Arrays.py | 3,015 | 3.75 | 4 | ## list optimization
class Solution:
# @param {int[][]} arrays k sorted integer arrays
# @return {int[]} a sorted array
def mergekSortedArrays(self, arrays):
# Write your code here
## 3 solution
def merge(list1, list2):
if not list1:
return list2
if not list2:
return list1
len1, len2 = len(list1), len(list2)
start1, start2 = 0, 0
ans = []
while start1 < len1 and start2 < len2:
if list1[start1] > list2[start2]:
ans.append(list2[start2])
start2 += 1
else:
ans.append(list1[start1])
start1 += 1
if start1 < len1:
ans.extend(list1[start1:])
if start2 < len2:
ans.extend(list2[start2:])
return ans
if not arrays:
return []
length = len(arrays)
while length > 1:
left, right = 0, length - 1
nextArray = []
while left < right:
nextArray.append(merge(arrays[left], arrays[right]))
left, right = left + 1, right - 1
if left == right:
nextArray.append(arrays[left])
length = len(nextArray)
arrays = nextArray
return arrays[0]
class Solution:
# @param {int[][]} arrays k sorted integer arrays
# @return {int[]} a sorted array
def mergekSortedArrays(self, arrays):
# Write your code here
## 3 solution
def merge(list1, list2):
if not list1:
return list2
if not list2:
return list1
len1, len2 = len(list1), len(list2)
start, start1, start2 = 0, 0, 0
ans = [None] * (len1 + len2)
while start1 < len1 and start2 < len2:
if list1[start1] > list2[start2]:
ans[start] = list2[start2]
start2 += 1
start += 1
else:
ans[start] = list1[start1]
start1 += 1
start += 1
if start1 < len1:
ans[start:] = list1[start1:]
if start2 < len2:
ans[start:] = list2[start2:]
return ans
if not arrays:
return []
length = len(arrays)
while length > 1:
left, right = 0, length - 1
nextArray = []
while left < right:
nextArray.append(merge(arrays[left], arrays[right]))
left, right = left + 1, right - 1
if left == right:
nextArray.append(arrays[left])
length = len(nextArray)
arrays = nextArray
return arrays[0] |
8481e78392bdfdd7d9cbc52831c10946d68fe2c8 | jke-zq/my_lintcode | /Palindrome Linked List.py | 1,186 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def isPalindrome(self, head):
# Write your code here
def reverse(root):
cur = None
while root:
tmp = root.next
root.next = cur
cur = root
root = tmp
return cur
if not head:
return True
dummy = ListNode(-1)
dummy.next = head
fast, slow = dummy, dummy
while fast and fast.next:
fast, slow = fast.next.next, slow.next
nextHead = slow.next
nextHead = reverse(nextHead)
cur = nextHead
ans = True
while cur:
if head.val == cur.val:
head = head.next
cur = cur.next
else:
ans = False
break
## recover the data
nextHead = reverse(nextHead)
head = dummy.next
slow.next = nextHead
return ans |
2018146ed44187d36ed69a9b84395af772e413a8 | jke-zq/my_lintcode | /Data Stream Median.py | 1,112 | 3.671875 | 4 | import heapq
class Solution:
"""
@param nums: A list of integers.
@return: The median of numbers
"""
def medianII(self, nums):
# write your code here
if not nums:
return []
maxlen, minlen = 0, 0
maxheap, minheap = [], []
ans = []
for n in nums:
if not minheap or n >= minheap[0]:
heapq.heappush(minheap, n)
minlen += 1
else:
heapq.heappush(maxheap, -1 * n)
maxlen += 1
if minlen - maxlen > 1:
val = heapq.heappop(minheap)
minlen -= 1
heapq.heappush(maxheap, -1 * val)
maxlen += 1
if minlen < maxlen:
val = -1 * heapq.heappop(maxheap)
maxlen -= 1
heapq.heappush(minheap, val)
minlen += 1
if minlen == maxlen:
ans.append(-1 * maxheap[0])
else:
ans.append(minheap[0])
return ans |
8aba59376aac59f1f9e0b6bc6083239d816c3f3b | jke-zq/my_lintcode | /Search in a Big Sorted Array.py | 1,025 | 3.84375 | 4 | """
Definition of ArrayReader:
class ArrayReader:
def get(self, index):
# this would return the number on the given index
# if there is no number on that index, return -1
"""
class Solution:
# @param {ArrayReader} reader: An instance of ArrayReader
# @param {int} target an integer
# @return {int} an integer
def searchBigSortedArray(self, reader, target):
# write your code here
if not reader:
return -1
k = 1
while reader.get(k) != -1 and reader.get(k) < target:
k *= 2
left, right = 0, k
while left + 1 < right:
mid = left + (right - left) / 2
if reader.get(mid) == -1 or reader.get(mid) >= target:
right = mid
elif reader.get(mid) < target:
left = mid
if reader.get(left) == target:
return left
if reader.get(right) != -1 and reader.get(right) == target:
return right
return -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.