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
d05beffef5f7bfc91922e44ce4091c080d7ed63e
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/python-nosetest-class-master/words.py
1,705
3.5625
4
from collections import defaultdict _punct = '.,;?:' def _normalize(fragment): fragment = fragment.lower() while len(fragment) > 0 and fragment[-1] in _punct: fragment = fragment[:-1] while len(fragment) > 0 and fragment[0] in _punct: fragment = fragment[1:] return fragment def numwords(text): ''' Return the number of unique words in a body of text. Punctuation and word casing are ignored. ''' words = set(_normalize(fragment) for fragment in text.split()) words.discard("") return len(words) def wordcounts(text): ''' Return dictionary mapping words to the number of occurences. Case is ignored, so each key is the lowercase version of the word. ''' counts = defaultdict(int) for fragment in text.split(): word = _normalize(fragment) if word == '': continue counts[word] += 1 return dict(counts) def addcounts(existing, new): ''' Updates an existing word count dictionary, adding in new values. Both existing and new are dicts that map words to counts (ints) - as might be returned by wordcounts(). existing is modified. For each key in new, if that key is in existing, add the value in existing. Else set the value (i.e. treat the count in existing as if 0). If either existing or new are not dictionaries, raise ValueError ''' if not type(existing) is dict: raise ValueError('existing must be a dictionary') if not type(new) is dict: raise ValueError('new must be a dictionary') for word, count in new.viewitems(): newcount = count + existing.get(word, 0) existing[word] = newcount
87034a3b828c0767c200a6f834524a6c9eeb6eb3
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Same_Patch.py
2,922
3.765625
4
# Python Test Mock # unittest.mock mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the action -> assertion pattern instead of record -> replay used by # many mocking frameworks. # # # Applying the same patch to every test method: # # If you want several patches in place for multiple test methods the obvious way is to apply the patch decorators to every method. # This can feel like unnecessary repetition. For Python 2.6 or more recent you can use patch() (in all its various forms) as a class decorator. # This applies the patches to all test methods on the class. # A test method is identified by methods whose names start with test: # @patch('mymodule.SomeClass') class MyTest(TestCase): def test_one(self, MockSomeClass): self.assertIs(mymodule.SomeClass, MockSomeClass) def test_two(self, MockSomeClass): self.assertIs(mymodule.SomeClass, MockSomeClass) def not_a_test(self): return 'something' MyTest('test_one').test_one() MyTest('test_two').test_two() MyTest('test_two').not_a_test() # OUTPUT: 'something' # # An alternative way of managing patches is to use the patch methods: start and stop. # These allow you to move the patching into your setUp and tearDown methods. # class MyTest(TestCase): def setUp(self): self.patcher = patch('mymodule.foo') self.mock_foo = self.patcher.start() def test_foo(self): self.assertIs(mymodule.foo, self.mock_foo) def tearDown(self): self.patcher.stop() MyTest('test_foo').run() # # If you use this technique you must ensure that the patching is undone by calling stop. # This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest.TestCase.addCleanup() # makes this easier: # class MyTest(TestCase): def setUp(self): patcher = patch('mymodule.foo') self.addCleanup(patcher.stop) self.mock_foo = patcher.start() def test_foo(self): self.assertIs(mymodule.foo, self.mock_foo) MyTest('test_foo').run()
98b04c908b9ee96b5460f6265780590ac4a969e8
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/algorithm-master/lintcode/156_merge_intervals.py
595
3.71875
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ c_ Solution: ___ merge intvs """ :type intvs: List[Interval] :rtype: List[Interval] """ ans # list __ n.. intvs: r.. ans intvs.s..(k.._l.... intv: (intv.start, intv.end ___ intv __ intvs: __ n.. ans o. intv.start > ans[-1].end: ans.a..(intv) ____ intv.end > ans[-1].end: ans[-1].end intv.end r.. ans
86070cd7fe5080766149afef78c3059e13c1d18a
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.6.Listing 8.6. An example of using the filter () function.py
409
3.921875
4
# -*- coding: utf-8 -*- def func(elem): return elem >= 0 arr = [-1, 2, -3, 4, 0, -20, 10] arr = list(filter(func, arr)) print(arr) # Результат: [2, 4, 0, 10] # Использование генераторов списков arr = [-1, 2, -3, 4, 0, -20, 10] arr = [ i for i in arr if func(i) ] print(arr) # Результат: [2, 4, 0, 10]
9668ed9b59dffd211b71d671e99bff049ca83215
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/232 Implement Queue using Stacks.py
1,349
4.28125
4
""" Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. Notes: You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). """ __author__ 'Daniel' c_ Queue: ___ - in_stk # list out_stk # list ___ push x """ :type x: int :rtype: None """ in_stk.a..(x) ___ pop """ :rtype: None """ __ n.. out_stk: w.... in_stk: out_stk.a..(in_stk.pop out_stk.p.. ) ___ peek """ :rtype: int """ __ n.. out_stk: w.... in_stk: out_stk.a..(in_stk.pop r.. out_stk[-1] ___ empty """ :rtype: bool """ r.. n.. out_stk a.. n.. in_stk
99e0d1b96397498ae343b4eae4e4b23307e59dbe
syurskyi/Python_Topics
/020_sequences/examples/ITVDN Python Essential 2016/12-mutable_sequences_methods.py
365
4.25
4
""" Примеры других общих для изменяемых последовательностей методов. """ sequence = list(range(10)) print(sequence) # Неполное копирование copy = sequence.copy() # copy = sequence[:] print(copy) # Разворот в обратном порядке sequence.reverse() print(sequence)
46b95cecb37be01d2c4ced998e143f9f08a7b9b2
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-13-convert-dict-to-namedtuple-json.py
2,029
4.1875
4
""" TASK DESCRIPTION: Write a function to convert the given blog dict to a namedtuple. Write a second function to convert the resulting namedtuple to json. Here you probably need to use 2 of the _ methods of namedtuple :) """ ____ c.. _______ n.. ____ c.. _______ O.. ____ d__ _______ d__ _______ j__ # Q: What is the difference between tuple and list? blog d.. name='PyBites', founders=('Julian', 'Bob'), started=d__ y.._2016, m.._12, d.._19), tags= 'Python', 'Code Challenges', 'Learn by Doing' , location='Spain/Australia', site='https://pybit.es') """ INITIAL CONSIDERATIONS: How could resulting JSON look like? Question is how to serialize datetime? j = { "name": "PyBites", "founders": ["Julian", "Bob"], "started": { "year": "2016", "month": "12", "day": "19" }, "tags": ["Python", "Code Challenges", "Learn by Doing"], "location": "Spain/Australia", "site": "https://pybit.es" } """ ### --------- My solution ------------- # define namedtuple here Blog n..('Blog', 'name founders started tags location site') ___ dict2nt(dict_ b Blog(dict_.g.. 'name'), dict_.g.. 'founders'), dict_.g.. 'started'), dict_.g.. 'tags'), dict_.g.. 'location'), dict_.g.. 'site' r.. b ___ nt2json(nt j__.d.. ) b ? ? # Q: How to serialize datetime object? # https://code-maven.com/serialize-datetime-object-as-json-in-python # https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable/36142844#36142844 print(j__.d..O..(b._asdict, default=s.., indent=4 ### ---------- PyBites original solution --------------- # define namedtuple here pybBlog n..('pybBlog', blog.keys # https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters ___ pyb_dict2nt(dict_ r.. pybBlog($$? ___ pyb_nt2json(nt nt ?._replace(started=s..(?.started r.. j__.d..?._asdict
35fdbbaaeae2b4f71a1e2b719034235c6918b130
syurskyi/Python_Topics
/100_databases/003_mongodb/_exercises/exercises/w3schools_Python MongoDB/002_Creating a Collection.py
954
4.0625
4
# # Creating a Collection # # To create a collection in MongoDB, use database object and specify the name of the collection you want to create. # # MongoDB will create the collection if it does not exist. # # _____ ? # # myclient _ ?.M.. "mongodb://localhost:27017/") # mydb _ ? "mydatabase" # # mycol _ ? "customers" # # # # Important: In MongoDB, a collection is not created until it gets content! # # # # MongoDB waits until you have inserted a document before it actually creates the collection. # # Check if Collection Exists # # # # Remember: In MongoDB, a collection is not created until it gets content, so if this is your first time creating # # a collection, you should complete the next chapter (create document) before you check if the collection exists! # # # # You can check if a collection exist in a database by listing all collections: # # print ?.l_c_n.. # # collist _ ?.l_c_n.. # __ "customers" __ ? # print("The collection exists.")
3fe411003aa7831e2d946ab7e657c9297d6c352d
syurskyi/Python_Topics
/120_design_patterns/001_SOLID_design_principles/examples/Isp/i.py
1,127
3.78125
4
""" Interface Segregation Principle bad - Circle class does not need draw_rectangle and draw_square. if we want to add new shapes, we have to change all classes. """ class IShape: def draw_square(self): raise NotImplementedError def draw_rectangle(self): raise NotImplementedError def draw_circle(self): raise NotImplementedError class Circle(IShape): def draw_square(self): pass def draw_rectangle(self): pass def draw_circle(self): pass class Square(IShape): def draw_square(self): pass def draw_rectangle(self): pass def draw_circle(self): pass class Rectangle(IShape): def draw_square(self): pass def draw_rectangle(self): pass def draw_circle(self): pass """ better draw segregate to different interfaces. """ class IShape: def draw(self): raise NotImplementedError class Circle(IShape): def draw(self): pass class Square(IShape): def draw(self): pass class Rectangle(IShape): def draw(self): pass
93ab25cc25e52713114cf3182a7b9b6cf3ab10d0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Heap/KthSmallestElementInASortedMatrix.py
7,123
4.0625
4
""" Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order, not the kth distinct element. Example: matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. Note: You may assume k is always valid, 1 ≤ k ≤ n2. 找到第k小个数。 测试用例: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/ 思路是用了堆: Python 有内置的堆模块,需要进行研究自写。 2018/08/02待跟进。 堆: 堆是一个完全二叉树,完全二叉树是除了最底层,其他层都是铺满的。 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 堆又分为最大堆与最小堆,最小堆是根节点是整个堆中最小的,最大堆则是最大的。 堆的操作分为:插入,取顶。 大部分情况下插入时的数据都是无序的,所以要保证最大堆与最小堆需要的操作肯定要有上浮与下沉。 上浮: 最小堆中: 如果父节点比自己大则自己上浮。 如果子节点比自己小则自己下沉。 也就是做数据交换,一直上浮或下沉到符合条件为止。 代码待添加... """ ''' 内置heapq的第一个版本: 运行时间长,但并未TLE.passed... import heapq class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ heap = [] for i in matrix: for j in i: heapq.heappush(heap, j) for i in range(k-1): heapq.heappop(heap) return heap[0] ''' ''' 第二个版本: 使用sorted. 每次都根据每个列表的0进行排序,然后取出。直到k=0. 排序时间复杂度为平均为 O(log len(n))。需要进行k次,所以是 O(klog len(n))。 理想情况下应该是最快的,但在书写时sorted在数据量过大时都会重新生成数组,所以导致很慢。 改进版本是直接打散列表,然后一次性sorted,这样的时间复杂度为 O(nlogn),也很容易写,但不想这样。 # 1 原以为会TTL,居然没有,跑了1778ms,也是最慢的。 class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ while k: # matrix = sorted(matrix, key=lambda x: x[0]) matrix.sort(key=lambda x: x[0]) pop = matrix[0][0] matrix[0] = matrix[0][1:] if not matrix[0]: matrix = matrix[1:] k -= 1 return pop ''' ''' 基于第二版的改进: 第二版的性能瓶颈应该是在排序时会重新移动大量的元素,如果每次仅对len(n)个元素排序呢? 每次都会for 一遍 len(n),生成一个新的 列表,列表中的元素是 ([0], index),然后排序这个列表。 也就是说不在排序原列表,而是排序一个新的列表。 根据index去修正原列表。 这版本TTl.这样排序会导致时间复杂度为(k*len(n)*log len(n)) ''' ''' class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ length = len(matrix) while k: # matrix = sorted(matrix, key=lambda x: x[0]) # matrix.sort(key=lambda x: x[0]) # 测试用例是Python 2. newMatrix = sorted([(matrix[i][0], i)for i in xrange(length)], key=lambda x: x[0]) pop = matrix[newMatrix[0][1]][0] matrix[0] = matrix[newMatrix[0][1]][1:] if not matrix[0]: matrix = matrix[1:] k -= 1 return pop ''' ''' 第四版思路: 基于第二版改进: 第二版每次都只取一个,如果取多个呢? 比如第一次做归并排序时, 我是 [[1]+[2]]+[3]]+[4]]+[5]]+[6]] 而实际上应该是 [[1]+[2]] + [[3]+[4]] + [[5]+[6]] [[1, 2, 3, 4]] + [[5, 6]]。 如果每次排序后去除t个,需要保证 n[0][-1] < n[1][-1]。 比如 matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8。 第二版中每次排序会去除一个最小的。 matrix = [ [5, 9], [10, 11, 13], [12, 13, 15] ], k = 7 matrix = [ [9], [10, 11, 13], [12, 13, 15] ], k = 6 matrix = [ [10, 11, 13], [12, 13, 15] ], k = 5 --- 如果加入一条 matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8 # 进入此条的条件是 k > len(matrix[0]) if matrix[0][-1] < matrix[1][0]: index1 = len(matrix[0]) # index2 = 0 # for t in xrange(matrix[1]): # if matrix[1][t] > matrix[0][-1]: # index2 = t # break 那么此时matrix[0] 将全部去除。k也相应的减去。 还有一种情况是 0[-1] 并不小于 1[0] 此时需要寻找 0 中小于 1[0]的数。 for t in xrange(len(matrix[0])-1, -1, -1): if matrix[0][t] < matrix[1][0]: index1 = t 那么此时将去除maxtrix[0][:t+1], k也减去相应的len. < len 则退化为第二版。 仍然TLE.... ''' ''' class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ while k: matrix.sort(key=lambda x: x[0]) if k >= len(matrix[0]): if len(matrix) >= 2: if matrix[0][-1] <= matrix[1][0]: index1 = len(matrix[0]) else: for t in range(len(matrix[0])-1, -1, -1): if matrix[0][t] <= matrix[1][0]: index1 = t+1 break popedMatrix = matrix[0][:index1] matrix[0] = matrix[0][index1:] if not matrix[0]: matrix = matrix[1:] pop = popedMatrix[-1] k -= len(popedMatrix) # print(matrix, index1) else: return matrix[0][-1] else: pop = matrix[0][0] matrix[0] = matrix[0][1:] if not matrix[0]: matrix = matrix[1:] k -= 1 return pop ''' ''' 目前为止,通过的是第一版和第二版,第三和第四基于2的改进都以失败告终。 第四版的性能瓶颈在于,如果1[0]一直小于0[-1] 那么就需要一直迭代,如果恰好每次0中只有[0]比1[0]小,那么就会迭代过多的次数。 从而导致 TLE. '''
6331a1ab8839a37e0f4e26c238395af367e109b1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/230 Kth Smallest Element in a BST.py
916
3.5625
4
# -*- coding: utf-8 -*- """ Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? Hint: """ __author__ 'Daniel' c_ TreeNode: ___ - , x val x left N.. right N.. c_ Solution: ___ kthSmallest root, k """ :type root: TreeNode :type k: int :rtype: int """ l cnt(root.left) __ l+1 __ k: r.. root.val ____ l+1 < k: r.. kthSmallest(root.right, k-(l+1 ____ r.. kthSmallest(root.left, k) ___ cnt root __ n.. root: r.. 0 r.. 1+cnt(root.left)+cnt(root.right)
c44c2a5714d92fc881306db6cdde4e3ef4c06dd3
syurskyi/Python_Topics
/045_functions/008_built_in_functions/enumerate/_exercises/templates/004.py
1,981
3.953125
4
# # Enumerate a List # # L = ['apples', 'bananas', 'oranges'] # ___ idx val __ ? ? # print("index is $ and value is $" ? ? # # # # index is 0 and value is apples # # index is 1 and value is bananas # # index is 2 and value is oranges # # # # Enumerate a Tuple # # t = ('apples', 'bananas', 'oranges') # ___ idx val __ ? ? # print("index is $ and value is $" ? ? # # # index is 0 and value is apples # # index is 1 and value is bananas # # index is 2 and value is oranges # # # Enumerate a List of Tuples (The Neat Way) # # L = [('Matt', 20), ('Karim', 30), ('Maya', 40)] # # ___ idx val __ ? ? # name = ? 0 # age = ? 1 # print("index is $, name is $, and age is $" \ # ? ? ? # # # index is 0, name is Matt, and age is 20 # # index is 1, name is Karim, and age is 30 # # index is 2, name is Maya, and age is 40 # # ___ idx |name age __ ? ? # print("index is $, name is $, and age is $" \ # ? ? ? # # # Enumerate a String # # str = "Python" # ___ idx, ch __ ? ? # print("index is $ and character is $" \ # ? ? # # # # index is 0 and character is P # # index is 1 and character is y # # index is 2 and character is t # # index is 3 and character is h # # index is 4 and character is o # # index is 5 and character is n # # # Enumerate with a Different Starting Index # # L = ['apples', 'bananas', 'oranges'] # ___ idx s __ ? ? s.._1 # print("index is $ and value is $" \ # ? ? # # # index is 1 and value is apples # # index is 2 and value is bananas # # index is 3 and value is oranges # # # Why It doesn’t Make Sense to Enumerate Dictionaries and Sets # # d = {'a': 1, 'b': 2, 'c': 3} # ___ k v __ ?.i.. # # k is now the key # # v is the value # print ? ? # # s = {'a', 'b', 'c'} # ___ v __ ? # print ? # # # Advanced: Enumerate Deep Dive # # l__ ? 'a', 'b', 'c' # # [(0, 'a'), (1, 'b'), (2, 'c')] # # ___ idx val __ ? 'a' 'b' # print ? ? # # # 0 a # # 1 b # # ___ i __ ? 'a' 'b' # print ? 0 ? 1 # # # 0 a # # 1 b
e21e74189a2b880b6c0a2c8fdeb7ef3663708645
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Magic_Mock.py
1,858
3.796875
4
# Python Unittest # unittest.mock mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the action -> assertion pattern instead of record -> replay used by # many mocking frameworks. # # # Mock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used. # You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used: # from unittest.mock import MagicMock thing = ProductionClass() thing.method = MagicMock(return_value=3) thing.method(3, 4, 5, key='value') # OUTPUT: '3' thing.method.assert_called_with(3, 4, 5, key='value') # # side_effect allows you to perform side effects, including raising an exception when a mock is called: # mock = Mock(side_effect=KeyError('foo')) mock() values = {'a': 1, 'b': 2, 'c': 3} def side_effect(arg): return values[arg] mock.side_effect = side_effect mock('a'), mock('b'), mock('c') # OUTPUT: '(1, 2, 3)' mock.side_effect = [5, 4, 3, 2, 1] mock(), mock(), mock() # OUTPUT: '(5, 4, 3)'
1af8cd8a831f0b63b8c77d2ff35f4ec3e6a1b3f8
syurskyi/Python_Topics
/125_algorithms/_examples/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 60 - MergeSortLists.py
1,158
4.15625
4
# Merge Sorted Lists # Question: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. # Solutions: class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @param two ListNodes # @return a ListNode def mergeTwoLists(self, l1, l2): dummy = ListNode(0) pointer = dummy while l1 !=None and l2 !=None: if l1.val<l2.val: pointer.next = l1 l1 = l1.next else: pointer.next = l2 l2 = l2.next pointer = pointer.next if l1 == None: pointer.next = l2 else: pointer.next = l1 return dummy.next def printll(self, node): while node: print ( node.val ) node = node.next if __name__ == '__main__': ll1, ll1.next, ll1.next.next = ListNode(2), ListNode(3), ListNode(5) ll2, ll2.next, ll2.next.next = ListNode(4), ListNode(7), ListNode(15) Solution().printll( Solution().mergeTwoLists(ll1,ll2) )
373b2e600995ec2dc414eee59493a2cbe93a118c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/113_v3/non_ascii.py
313
4
4
def extract_non_ascii_words(text): """Filter a text returning a list of non-ascii words""" words = text.split() result = [] for word in words: try: word.encode('ascii') except Exception as e: print(e) result.append(word) return result
56ff56c9d7977a59184e97c87a15187edbd1a63f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/520 Detect Capital.py
1,228
4.375
4
#!/usr/bin/python3 """ Given a word, you need to judge whether the usage of capitals in it is right or not. We define the usage of capitals in a word to be right when one of the following cases holds: All letters in this word are capitals, like "USA". All letters in this word are not capitals, like "leetcode". Only the first letter in this word is capital if it has more than one letter, like "Google". Otherwise, we define that this word doesn't use capitals in a right way. Example 1: Input: "USA" Output: True Example 2: Input: "FlaG" Output: False Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters. """ c_ Solution: ___ detectCapitalUse word: s..) __ b.. """ Two passes is easy How to do it in one pass """ __ n.. word: r.. T.. head_upper word[0].isupper() # except for the head has_lower F.. has_upper F.. ___ w __ word 1| __ w.isupper has_upper T.. __ has_lower o. n.. head_upper: r.. F.. ____ has_lower T.. __ has_upper: r.. F.. r.. T..
392e525fb8bacb0f76c87b70bf0782b3fd60f4fe
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/029_martins_iq_test/save1_nopass.py
504
3.828125
4
def get_index_different_char(chars): correct = [correct for correct in str(chars) if correct.isalnum()] not_correct = [not_correct for not_correct in chars if not str(not_correct).isalnum()] if len(correct) > len(not_correct): not_correct = ",".join(not_correct) return chars.index(not_correct) elif len(correct) < len(not_correct): correct = ",".join(correct) return chars.index(correct)
b7cd9d35064542f85f302b3c2ab375a447497601
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/Python_Unittest_Suite-master/Python_Test_Mock_Partial_Mocking.py
1,883
3.6875
4
# Python Test Mock # unittest.mock � mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. # After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. # You can also specify return values and set needed attributes in the normal way. # # Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel # for creating unique objects. # # Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by # many mocking frameworks. # # # Partial mocking: # In some tests I wanted to mock out a call to datetime.date.today() to return a known date, but I didn�t want to prevent the code under test from creating # new date objects. # Unfortunately datetime.date is written in C, and so I couldn�t just monkey-patch out the static date.today() method. # The patch decorator is used here to mock out the date class in the module under test. # The side_effect attribute on the mock date class is then set to a lambda function that returns a real date. # When the mock date class is called a real date will be constructed and returned by side_effect. # ____ d_t_ ______ date w__ patch('mymodule.date') __ mock_date: mock_date.today.return_value _ date(2010, 10, 8) mock_date.side_effect _ l___ *args, **kw: date(*args, **kw) a.. mymodule.date.today() __ date(2010, 10, 8) a.. mymodule.date(2009, 6, 8) __ date(2009, 6, 8)
2a2dd9b0637c9f1d82e18a5e55dc77f662dc1a3a
syurskyi/Python_Topics
/125_algorithms/001_arrays/_exercises/_templates/Array Sequences/Array Sequences Interview Questions/PRACTICE/Anagram Check .py
1,906
4.09375
4
# # %% # ''' # # Anagram Check # ## Problem # Given two strings, check to see i_ they are anagrams. An anagram is when the two strings can be written using # the exact same letters (so you can just rearrange the letters to get a different phrase or word). # For example: # "public relations" is an anagram of "crap built on lies." # "clint eastwood" is an anagram of "old west action" # **Note: Ignore spaces and capitalization. So "d go" is an anagram of "God" and "dog" and "o d g".** # ## Solution # # Fill out your solution below: # ''' # # # # %% # # 242. Valid Anagram(https://leetcode.com/problems/valid-anagram/description/) # ___ anagram s t # """ # :type s: str # :type t: str # :rtype: bool # """ # s _ ?.re.. ' ', '' .lo__ # t _ ?.re.. ' ', '' .lo__ # # i_ le.? !_ le.? # r_ F... # counter _ # dict # ___ letter __ s # __ ? __ c.. # c.. ? +_ 1 # ____ # c... ? _ 1 # # ___ letter __ t # __ ? __ c... # c... ? -_ 1 # ____ # r_ F... # # ___ k __ c... # __ ? k !_ 0 # r_ F... # # r_ T... # p.. # # # # %% # anagram 'dog', 'god' # # # %% # anagram 'clint eastwood', 'old west action' # # # %% # anagram 'aa', 'bb' # # # %% # ''' # # Test Your Solution # Run the cell below to test your solution # ''' # # # %% # """ # RUN THIS CELL TO TEST YOUR SOLUTION # """ # f___ n___.t... _______ a_e # # # c_ AnagramTest o.. # # ___ test sol # a._e. ? 'go go go', 'gggooo' , T... # a._e. ? 'abc', 'cba' , T... # a._e. ? 'hi man', 'hi man' , T.. # a._e. ? 'aabbcc', 'aabbc' , F... # a._e. ? '123', '1 2' , F... # print('ALL TEST CASES PASSED') # # # # Run Tests # t _ ? # ?.t.. a.. # # # %% # # t.test(anagram2) # # # %% # ''' # # Good Job! # '''
254755cc6671c42fd959d4425deadbf69fce1780
syurskyi/Python_Topics
/085_regular_expressions/_exercises/templates/Python 3 Most Nessesary/7.4. Lack of binding to the beginning or end of the line.py
595
3.59375
4
# # -*- coding: utf-8 -*- # # Если убрать привязку к началу и концу строки, то любая строка, содержащая хотя бы одну # цифру, будет распознана как число # # _______ __ # Подключаем модуль # p = __.c.. _ 0-9 1? .2? # 1.One or more occurrences | 2.Makes a period (dot) match any character, including a newline. # __ __.s..("Строка245") # print("Число") # Выведет: Число # ____ # print("Не число") # input()
ccfc3515015748270dd73cedbff571fd2750ca6b
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/exercises/Python_3_Deep_Dive_Part_4/Section 02 - Classes/03-Callable_Class_Attributes.py
771
3.71875
4
# # %% # ''' # ### Callable Class Attributes # ''' # # # %% # ''' # Class attributes can be any object type, including callables such as functions: # ''' # # # %% # c_ Program # language _ 'Python' # # ___ say_hello # print(_*Hello from ?.l.. !* # # # %% # print ?.-d # # # # # %% # # ''' # # As we can see, the `say_hello` symbol is in the class dictionary. # # We can also retrieve it using either `getattr` or dotted notation: # # ''' # # # # # %% # print ?.s._h. g.. ? 's.... # # # # # %% # # ''' # # And of course we can call it, since it is a callable: # # ''' # # # # # %% # ?.s._h. # # # # # %% # g.. ? s.. # # # # # %% # # ''' # # We can even access it via the namespace dictionary as well: # # ''' # # # # # %% # print ?.-d 's.... # # # # # %%
042c2a04af69bfaab7f5fbe77793c41d4e89d9f1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_Python_Exercises_Evaluate_and_Improve_Your_Skills/Exercise 89 - Database Filter NUKE.py
458
3.984375
4
#Please download the database file database.db. The file contains a table with 50 country names along with their area in square km and population. #Please use Python to print out those countries that have an area of greater than 2,000,000. _______ sqlite3 conn sqlite3.connect("database.db") cur conn.cursor() cur.execute("SELECT country FROM countries WHERE area >= 2000000") rows cur.fetchall() conn.close() print(rows) ___ i __ rows: print(i[0])
b8657fd9854b6e406dec4ae63bf4ce1336df307d
syurskyi/Python_Topics
/121_refactoring/Code_Smells/Bloaters/Long_Method/Replace_Temp_with_Query/005.py
1,080
3.9375
4
# Problem def calculateGrade(): totalScore = midtermScore + finalScore + assignmentScore averageScore = totalScore / 3 if averageScore >= 90: grade = "A" elif averageScore >= 80: grade = "B" elif averageScore >= 70: grade = "C" elif averageScore >= 60: grade = "D" else: grade = "F" return grade # Solution def calculateGrade(): averageScore = calculateAverageScore() if averageScore >= 90: grade = "A" elif averageScore >= 80: grade = "B" elif averageScore >= 70: grade = "C" elif averageScore >= 60: grade = "D" else: grade = "F" return grade def calculateAverageScore(): totalScore = midtermScore + finalScore + assignmentScore averageScore = totalScore / 3 return averageScore # In this example, we extract the calculation of the average score into a separate function calculateAverageScore(). # This eliminates the need for the temporary variable averageScore in the main function, making the code more readable.
2590ab4756df40525216d2a169c509dacac2ba36
syurskyi/Python_Topics
/070_oop/004_inheritance/examples/super/Understanding Python super()/004.py
807
3.59375
4
class A(object): def __init__(self, i, **kwargs): super(A, self).__init__(**kwargs) self.i = i def run(self, value): return self.i * value class B(A): def __init__(self, j, **kwargs): super(B, self).__init__(**kwargs) self.j = j def run(self, value): return super(B, self).run(value) + self.j class Logger(object): def __init__(self, name, **kwargs): super(Logger,self).__init__(**kwargs) self.name = name def run_logged(self, value): print("Running", self.name, "with info", self.info()) return self.run(value) class BLogged(B, Logger): def __init__(self, **kwargs): super(BLogged, self).__init__(name="B", **kwargs) def info(self): return 42 b = BLogged(i=3, j=4) print(b)
d1cca3de84367b208ee27acfe410ffec6a4f69f5
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/100_SameTree.py
725
3.671875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None c.. Solution o.. ___ isSameTree p, q """ :type p: TreeNode :type q: TreeNode :rtype: bool """ __ n.. p a.. n.. q: r_ True __ (n.. p a.. q) or (p a.. n.. q r_ F.. __ p.val != q.val: r_ F.. __ n.. self.isSameTree(p.left, q.left r_ F.. __ n.. self.isSameTree(p.right, q.right r_ F.. r_ True """ [] [1] [1,2,3] [1,2,3] [2,null,3,4,5] [2,null,3,5,4] """
0e260d563115adc1074d6e6135c4d62085b1f48f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/100_python_Best_practices_for_absolute_beginers/Project+13 How to create quadratic Equation.py
331
4.34375
4
____ math _______ sqrt x float(input("Insert x = ")) y float(input("Insert y = ")) z float(input("Insert z = ")) a y*y-4*x*z __ a>0: x1 (-y + sqrt(a))/(2*x) x2 (-y - sqrt(a))/(2*x) print("x1 = %.2f; x2 = %.2f" % (x1,x2)) ____ a__0: x1 -y/(2*x) print("x1 = %.2f" % x1) ____: print("No roots exist")
d30652b267569247f9d3c6a1f20ad03f3f902250
syurskyi/Python_Topics
/115_testing/_exercises/_templates/temp/Github/_Level_1/UnitTesting-master/Proj4/ListsAndTuples/listAndTuples.py
2,218
4.375
4
______ ___ ______ timeit # https://www.youtube.com/watch?v=NI26dqhs2Rk # Tuple is a smaller faster alternative to a list # List contains a sequence of data surrounded by brackets # Tuple contains a squence of data surrounded by parenthesis """ Lists can have data added, removed, or changed Tuples cannot change. Tuples can be made quickly. """ # List example prime_numbers _ [2, 3, 5, 7, 11, 13, 17] # Tuple example perfect_squares _ (1, 4, 9, 16, 25, 36) # Display lengths print("# Primes = ", le.(prime_numbers)) print("# Squares = ", le.(perfect_squares)) # Iterate over both sequences ___ p __ prime_numbers: print("Prime: ", p) ___ n __ perfect_squares: print("Square: ", n) print("") print("List Methods") print(dir(prime_numbers)) print(80*"-") print("Tuple methods") print(dir(perfect_squares)) print() print(dir(___)) print(help(___.getsizeof)) print() list_eg _ [1, 2, 3, "a", "b", "c", T.., 3.14159] tuple_eg _ (1, 2, 3, "a", "b", "c", T.., 3.14159) print("List size = ", ___.getsizeof(list_eg)) print("Tuple size = ", ___.getsizeof(tuple_eg)) print() list_test _ timeit.timeit(stmt_"[1, 2, 3, 4, 5]", number_1000000) tuple_test _ timeit.timeit(stmt_"(1, 2, 3, 4, 5)", number_1000000) print("List time: ", list_test) print("Tuple time: ", tuple_test) print() ## How to make tuples empty_tuple _ () test0 _ ("a") test1 _ ("a",) # To make a tuple with just one element you need to have a comma at the end test2 _ ("a", "b") test3 _ ("a", "b", "c") print(empty_tuple) print(test0) print(test1) print(test2) print(test3) print() # How to make tuples part 2 test1 _ 1, test2 _ 1, 2 test3 _ 1, 2, 3 print(test1) print(test2) print(test3) print() # (age, country, knows_python) survey _ (27, "Vietnam", T..) age _ survey[0] country _ survey[1] knows_python _ survey[2] print("Age =", age) print("Country =", country) print("Knows Python?", knows_python) print() survey2 _ (21, "Switzerland", F..) age, country, knows_python _ survey2 print("Age =", age) print("Country =", country) print("Knows Python?", knows_python) print() # Assigns string to variable country country _ ("Australia") # Here country is a tuple, and it doesnt unpack contents into variable country _ ("Australia",)
fcac989dc3c9d7454b7f7cf9d4caf0d977144993
syurskyi/Python_Topics
/110_concurrency_parallelism/_examples/Learn Parallel Computing in Python/005_barriers/matrix_multiply_single.py
1,099
3.609375
4
import time from random import Random matrix_size = 200 # matrix_a = [[3, 1, -4], # [2, -3, 1], # [5, -2, 0]] # matrix_b = [[1, -2, -1], # [0, 5, 4], # [-1, -2, 3]] matrix_a = [[0] * matrix_size for a in range(matrix_size)] matrix_b = [[0] * matrix_size for b in range(matrix_size)] result = [[0] * matrix_size for r in range(matrix_size)] random = Random() def generate_random_matrix(matrix): for row in range(matrix_size): for col in range(matrix_size): matrix[row][col] = random.randint(-5, 5) start = time.time() for t in range(10): generate_random_matrix(matrix_a) generate_random_matrix(matrix_b) result = [[0] * matrix_size for r in range(matrix_size)] for row in range(matrix_size): for col in range(matrix_size): for i in range(matrix_size): result[row][col] += matrix_a[row][i] * matrix_b[i][col] # for row in range(matrix_size): # print(matrix_a[row], matrix_b[row], result[row]) # print() end = time.time() print("Done, time taken", end - start)
a51e653d17ccdefa013f6915d43344c176e57fb1
syurskyi/Python_Topics
/012_lists/_exercises/_templates/ITVDN Python Starter 2016/15-list-traversal.py
213
3.578125
4
# -*- coding: utf-8 -*- # # Создание списка чисел # my_list = 5, 1, 5, 7, 8, 1, 0, -23 # # # Вывод квадратов этих чисел # ___ x __ ? # print '@ ^ 2 = @'.f.. x, x ** 2
4a920bacfcb09c3f17ccc27d7e49ed3415f7240d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/BreadthFirstSearch/199_BinaryTreeRightSideView.py
793
3.84375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None c.. Solution o.. # Breadth First Search ___ rightSideView root __ n.. root: r_ [] cur_level = [root] next_level # list result # list _____ cur_level: ___ node __ cur_level: __ node.left: next_level.a.. node.left) __ node.right: next_level.a.. node.right) result.a.. cur_level[-1].val) cur_level = next_level next_level # list r_ result """ [] [1,2,3] [1,2,3,null,4,null,5] """
ff55229df681d9bb62d831cec5b66fe7ec203c1c
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 12 Regex/remove_parenthesis_solution.py
772
3.6875
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # Write a Python program to remove the parenthesis area in a string. # # Input # ["example (.com)", "w3resource", "github (.com)", "stackoverflow (.com)"] # # Output # example # w3resource # github # stackoverflow import re items = ["example (.com)", "w3resource", "github (.com)", "stackoverflow (.com)"] for item in items: print(re.sub(r" ?\([^)]+\)", "", item))
98d01ea24418a470927f2b7cfda199f8c7a15a83
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/TwoPointers/75_SortColors.py
734
3.640625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def sortColors(self, nums): len_n = len(nums) # pos_put_0: next position to put 0 # pos_put_2: next position to put 2 pos_put_0 = 0 pos_put_2 = len_n - 1 index = 0 while index <= pos_put_2: if nums[index] == 0: nums[index], nums[pos_put_0] = nums[pos_put_0], nums[index] pos_put_0 += 1 index += 1 elif nums[index] == 2: nums[index], nums[pos_put_2] = nums[pos_put_2], nums[index] pos_put_2 -= 1 else: index += 1 """ [0] [1,0] [0,1,2] [1,1,1,2,0,0,0,0,2,2,1,1,2] """
ed2c72f3d8b7d3da15b93c53f0f8a83d5607d12f
syurskyi/Python_Topics
/014_tuples/examples/Learning Python/009_001_Tuples in Action.py
187
4
4
print((1, 2) + (3, 4)) # Concatenation # (1, 2, 3, 4) print((1, 2)) * 4 # Repetition # (1, 2, 1, 2, 1, 2, 1, 2) T = (1, 2, 3, 4) # Indexing, slicing print(T[0], T[1:3]) # (1, (2, 3))
c035fcefec027a5b8e1c619b49d09c7c96cbc330
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-169-simple-length-converter.py
1,245
4.34375
4
''' Your task is to complete the convert() function. It's purpose is to convert centimeters to inches and vice versa. As simple as that sounds, there are some caveats: convert(): The function will take value and fmt parameters: value: must be an int or a float otherwise raise a TypeError fmt: string containing either "cm" or "in" anything else raises a ValueError. returns a float rounded to 4 decimal places. Assume that if the value is being converted into centimeters that the value is in inches and centimeters if it's being converted to inches. That's it! ''' ___ convert(value: f__, fmt: s..) __ f__: """Converts the value to the designated format. :param value: The value to be converted must be numeric or raise a TypeError :param fmt: String indicating format to convert to :return: Float rounded to 4 decimal places after conversion """ __ t..(value) __ i.. o. t..(value) __ f__: __ fmt.l.. __ "cm" o. fmt.l.. __ "in": __ fmt.l.. __ "cm": result value*2.54 r.. r..(result,4) ____ result value*0.393700787 r.. r..(result, 4) ____ r.. V... ____ r.. T.. print(convert(60.5, "CM"
6875e7dcbedb3d6dff5c4554e0659921519f0224
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/111_MinimumDepthofBinaryTree.py
745
3.859375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None c.. Solution o.. ___ minDepth root """ :type root: TreeNode :rtype: int """ __ n.. root: r_ 0 __ root.left a.. root.right: r_ 1 + m.. self.minDepth(root.left), self.minDepth(root.right)) __ n.. root.left: r_ 1 + self.minDepth(root.right) __ n.. root.right: r_ 1 + self.minDepth(root.left) ____ r_ 1 """ [] [1] [1,2,null,3] [1,2,3,4,null,6,7,5,8] [1,2,2,3,null,null,3,4,null,null,4] """
4e4ffc46df598ca4b6990664d765f2ee36ca9c63
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.1. Listing 8.1. Create a shallow copy of the list.py
1,169
4.375
4
# -*- coding: utf-8 -*- x = [1, 2, 3, 4, 5] # Создали список # Создаем копию списка y = list(x) # или с помощью среза: y = x[:] # или вызовом метода copy(): y = x.copy() print(y) # [1, 2, 3, 4, 5] print(x is y) # Оператор показывает, что это разные объекты # False y[1] = 100 # Изменяем второй элемент print(x, y) # Изменился только список в перемеой y # ([1, 2, 3, 4, 5], [1, 100, 3, 4, 5]) x = [1, [2, 3, 4, 5]] # Создали вложенный список y = list(x) # Якобы сделали копию списка print(x is y) # Разные объекты # False y[1][1] = 100 # Изменяем элемент print(x, y) # Изменение затронуло переменную x!!! # ([1, [2, 100, 4, 5]], [1, [2, 100, 4, 5]])
0e1f60a4dd71d99753e8a19d3f767d8d2815615d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/768 Max Chunks To Make Sorted II.py
1,673
4.40625
4
#!/usr/bin/python3 """ This question is the same as "Max Chunks to Make Sorted" except the integers of the given array are not necessarily distinct, the input array could be up to length 2000, and the elements could be up to 10**8. Given an array arr of integers (not necessarily distinct), we split the array into some number of "chunks" (partitions), and individually sort each chunk. After concatenating them, the result equals the sorted array. What is the most number of chunks we could have made? Example 1: Input: arr = [5,4,3,2,1] Output: 1 Explanation: Splitting into two or more chunks will not return the required result. For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted. Example 2: Input: arr = [2,1,3,4,4] Output: 4 Explanation: We can split into two chunks, such as [2, 1], [3, 4, 4]. However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible. Note: arr will have length in range [1, 2000]. arr[i] will be an integer in range [0, 10**8]. """ ____ t___ _______ L.. ____ c.. _______ d.., d.. c_ Solution: ___ maxChunksToSorted arr: L.. i.. __ i.. """ not necessarily distinct sort and assign index For the smae element, the right ones should get larget assigned index """ A s..(arr) hm d..(d..) ___ i, e __ e..(A hm[e].a..(i) proxy # list ___ e __ arr: proxy.a..(hm[e].popleft ret 0 cur_max_idx 0 ___ i, e __ e..(proxy cur_max_idx m..(cur_max_idx, e) __ cur_max_idx __ i: ret += 1 r.. ret
8199e90857ce7ac268a79d59098e31bfebc1b0d0
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/LinkedList/02.AddTwoNumbers.py
1,184
3.703125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry_in = 0 head = ListNode(0) l_sum = head while l1 and l2: l_sum.next = ListNode((l1.val + l2.val + carry_in) % 10) carry_in = (l1.val + l2.val + carry_in) / 10 l1 = l1.next l2 = l2.next l_sum = l_sum.next if l1: while l1: l_sum.next = ListNode((l1.val + carry_in) % 10) carry_in = (l1.val + carry_in) / 10 l1 = l1.next l_sum = l_sum.next if l2: while l2: l_sum.next = ListNode((l2.val + carry_in) % 10) carry_in = (l2.val + carry_in) / 10 l2 = l2.next l_sum = l_sum.next if carry_in != 0: l_sum.next = ListNode(carry_in) return head.next
4212e36d8f58c6daa1eca4f90874a489d4a8f3b0
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/fibonacci sequence index.py
381
4.0625
4
fib_store [0,1] #generating the fibonacci Sequence ___ i __ r..(2,1000 fib_store.a..(fib_store[-2] + fib_store[-1]) #searching for the index of the given element from Fibonacci Sequence ___ i __ r..(i..(i.. ))): fib_num i..(input #using index to find the index of the element from fibonacci sequence fib_index fib_store.i.. fib_num) print(fib_index,end' ')
add65a1168b59f9cfa32fdce22b0caa4321fd5f7
syurskyi/Python_Topics
/050_iterations_comprehension_generations/004_coroutines/examples/004_coroutines.py
4,071
4.125
4
# -*- coding: utf-8 -*- # producer-consumer-coroutines # """ # Сопрограмма (англ. coroutine) — компонент программы, обобщающий понятие # подпрограммы, который дополнительно поддерживает множество входных точек # (а не одну, как подпрограмма) и остановку и продолжение выполнения с # сохранением определённого положения. # Rolling our own Next method class Squares: def __init__(self): self.i = 0 def next_(self): result = self.i ** 2 self.i += 1 return result sq = Squares() sq.next_() sq.next_() for i in range(10): print(sq.next_()) # Coroutines # The word co actually comes from cooperative. # A coroutine is a generalization of subroutines (think functions), focused on cooperation between routines. # If you have some concepts of multi-threading, this is similar in some ways. # But whereas in multi-threaded applications the operating system usually decides when to suspend one thread and # resume another, without asking permission, so-called preemptive multitasking, # here we have routines that voluntarily yield control to something else - hence the term cooperative. # Coroutines # # We can specify a maximum size for the queue when create it - this allows us to limit the number of items in the queue. # # (Note that I'm avoiding calling it the start and end of the queue, # because what you consider the start/end of the queue might depend on how you are using it) from collections import deque dq = deque([1, 2, 3, 4, 5]) dq dq.append(100) dq dq.appendleft(-10) dq dq.pop() dq dq.popleft() # Coroutines # # We can create a capped queue: # # As you can see the first item (2) was automatically discarded from the left of the queue when we added 300 to the right. # # We can also find the number of elements in the queue by using the len() function: # as well as query the maxlen: from collections import deque dq = deque([1, 2, 3, 4], maxlen=5) dq.append(100) dq dq.append(200) dq dq.append(300) dq len(dq) dq.maxlen # Coroutines # Now let's create an empty queue, and write two functions - one that will add elements to the queue, and one that will consume elements from the queue: def produce_elements(dq): for i in range(1, 36): dq.appendleft(i) def consume_elements(dq): while len(dq) > 0: item = dq.pop() print('processing item', item) def coordinator(): dq = deque() producer = produce_elements(dq) consume_elements(dq) coordinator() # Coroutines # The goal is to process these after some time, and not wait until all the items have been added to the queue - # maybe the incoming stream is infinite even. # In that case, we want to "pause" adding elements to the queue, process (consume) those items, # then once they've all been processed we want to resume adding elements, and rinse and repeat. # We'll use a capped deque, and change our producer and consumers slightly, so that each one does it's work, # the yields control back to the caller once it's done with its work - the producer adding elements to the queue, # and the consumer removing and processing elements from the queue: def produce_elements(dq, n): for i in range(1, n): dq.appendleft(i) if len(dq) == dq.maxlen: print('queue full - yielding control') yield def consume_elements(dq): while True: while len(dq) > 0: print('processing ', dq.pop()) print('queue empty - yielding control') yield def coordinator(): dq = deque(maxlen=10) producer = produce_elements(dq, 36) consumer = consume_elements(dq) while True: try: print('producing...') next(producer) except StopIteration: # producer finished break finally: print('consuming...') next(consumer) coordinator()
32756e47a525d9265a1658da0e13ff9cbcdee87f
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/120_v2/validate.py
430
3.78125
4
from functools import wraps def int_args(func): @wraps(func) # complete this decorator def wrapper(*args): for arg in args: if type(arg) != int: raise TypeError("All arguments passed in must be integers") if arg <0: raise ValueError("All arguments must be non-negative integers") return func(*args) return wrapper
9680a5cff98db7015326444222cba49bc3c99421
syurskyi/Python_Topics
/100_databases/001_sqlite/examples/PYnative/005_Insert multiple rows.py
1,253
3.625
4
import sqlite3 def insertMultipleRecords(recordList): try: sqliteConnection = sqlite3.connect('SQLite_Python.db') cursor = sqliteConnection.cursor() print("Connected to SQLite") sqlite_insert_query = """INSERT INTO SqliteDb_developers (id, name, email, joining_date, salary) VALUES (?, ?, ?, ?, ?);""" cursor.executemany(sqlite_insert_query, recordList) sqliteConnection.commit() print("Total", cursor.rowcount, "Records inserted successfully into SqliteDb_developers table") sqliteConnection.commit() cursor.close() except sqlite3.Error as error: print("Failed to insert multiple records into sqlite table", error) finally: if (sqliteConnection): sqliteConnection.close() print("The SQLite connection is closed") recordsToInsert = [(4, 'Jos', 'jos@gmail.com', '2019-01-14', 9500), (5, 'Chris', 'chris@gmail.com', '2019-05-15',7600), (6, 'Jonny', 'jonny@gmail.com', '2019-03-27', 8400)] insertMultipleRecords(recordsToInsert) # Connected to SQLite # Total 3 Records inserted successfully into SqliteDb_developers table # The SQLite connection is closed
0b1fd052ca6b3b22072b44bbdd1212e15f6bcddd
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/exercises/Python_3_Deep_Dive_Part_4/Section 14 Metaprogramming/157. Metaprogramming Application 3.py
8,307
3.65625
4
# %% ''' ### Metaprogramming - Application 3 ''' # %% ''' Let's say we have some `.ini` files that hold various application configurations. We want to read those `.ini` files into an object structure so that we can access the data in our config files using dot notation. ''' # %% ''' Let's start by creating some `.ini` files: ''' # %% with open('prod.ini', 'w') as prod, open('dev.ini', 'w') as dev: prod.write('[Database]\n') prod.write('db_host=prod.mynetwork.com\n') prod.write('db_name=my_database\n') prod.write('\n[Server]\n') prod.write('port=8080\n') dev.write('[Database]\n') dev.write('db_host=dev.mynetwork.com\n') dev.write('db_name=my_database\n') dev.write('\n[Server]\n') dev.write('port=3000\n') # %% ''' Note: I could have used the `configparser` module to write out these ini files, but we don't have to - generally these config files are created and edited manually. We will use `configparser` to load up the config files though. ''' # %% ''' When we start our program, we want to load up one of these files into a config object of some sort. We could certainly do it this way: ''' # %% import configparser class Config: def __init__(self, env='dev'): print(f'Loading config from {env} file...') config = configparser.ConfigParser() file_name = f'{env}.ini' config.read(file_name) self.db_host = config['Database']['db_host'] self.db_name = config['Database']['db_name'] self.port = config['Server']['port'] # %% config = Config('dev') # %% print(config.__dict__) # %% ''' but whenever we need access to this config object again, we either have to store the object somewhere in a global variable (common, and extremely simple!), or we need to re-create it: ''' # %% config = Config('dev') # %% ''' Which means we end up parsing the `ini` file over and over again. ''' # %% print(config.db_name) # %% help(config) # %% ''' Furthermore, `help` is not very useful to us here. ''' # %% ''' The other thing is that we had to "hardcode" each config value in our `Config` class. That's a bit of a pain. Could we maybe create instance attributes from inspecting what's inside the `ini` files instead? ''' # %% class Config: def __init__(self, env='dev'): print(f'Loading config from {env} file...') config = configparser.ConfigParser() file_name = f'{env}.ini' config.read(file_name) for section_name in config.sections(): for key, value in config[section_name].items(): setattr(self, key, value) # %% config = Config('prod') # %% print(config.__dict__) # %% ''' So this is good, we can access our config values using dot notation: ''' # %% print(config.port) # %% ''' The next issue we need to deal with is that our config files are organized into sections, and here we've essentially ignored this and create just a "flat" data structure. ''' # %% ''' So let's deal with that next. ''' # %% ''' Let's write a custom class for representing sections: ''' # %% class Section: def __init__(self, name, item_dict): """ name: str name of section item_dict : dictionary dictionary of named (key) config values (value) """ self.name = name for key, value in item_dict.items(): setattr(self, key, value) # %% ''' And now we can rewrite our `Config` class this way: ''' # %% class Config: def __init__(self, env='dev'): print(f'Loading config from {env} file...') config = configparser.ConfigParser() file_name = f'{env}.ini' config.read(file_name) for section_name in config.sections(): section = Section(section_name, config[section_name]) setattr(self, section_name.lower(), section) # %% config = Config() # %% ''' Now we have sections: ''' # %% vars(config) # %% ''' And each section has its config values: ''' # %% vars(config.database) # %% ''' But that still does not solve our documentation issue: ''' # %% help(Config) # %% ''' Most modern IDE's will still be able to provide us some auto-completion on the attributes though, using some form of introspection. ''' # %% ''' But let's assume we really want `help` to give us some useful information, or we're working with an IDE that isn't sophisticated enough. ''' # %% ''' To do that, we are going to switch to metaclasses. ''' # %% ''' Our custom metaclass will load up the `ini` file and use it to create class attributes instead: ''' # %% ''' And we'll need to do this for both the sections and the overall config. ''' # %% ''' To keep things a little simpler, we're going to create two distinct metaclasses. One for the sections in the config file, and one that combines the sections together - very similar to what we did with our original `Config` class. ''' # %% ''' One key difference, is that each `Section` class instance, will be a brand new class, created via its metaclass. ''' # %% ''' Let's write the `Section` metaclass first. ''' # %% class SectionType(type): def __new__(cls, name, bases, cls_dict, section_name, items_dict): cls_dict['__doc__'] = f'Configs for {section_name} section' cls_dict['section_name'] = section_name for key, value in items_dict.items(): cls_dict[key] = value return super().__new__(cls, name, bases, cls_dict) # %% ''' We can now create `Section` classes for different sections in our configs, passing the metaclass the section name, and a dictionary of the values it should create as class attributes. ''' # %% class DatabaseSection(metaclass=SectionType, section_name='database', items_dict={'db_name': 'my_database', 'host': 'myhost.com'}): pass # %% vars(DatabaseSection) # %% ''' As you can see, our items `db_name` and `host` are in the class. ''' # %% print(DatabaseSection.db_name) # %% ''' And the `help` function introspection will work too: ''' # %% help(DatabaseSection) # %% ''' And we can now create any section we want using this metaclass, for example: ''' # %% class PasswordsSection(metaclass=SectionType, section_name='passwords', items_dict={'db': 'secret', 'site': 'super secret'}): pass # %% vars(PasswordsSection) # %% ''' Just like we can create classes programmatically by calling the `type` metaclass: ''' # %% MyClass = type('MyClass', (object,), {}) # %% print(MyClass) # %% ''' We can also create `Section` **classes** by calling the `SectionType` metaclass: ''' # %% MySection = SectionType('DBSection', (object,), {}, section_name='databases', items_dict={'db_name': 'my_db', 'port': 8000}) # %% print(MySection) # %% vars(MySection) # %% ''' Now that we have a metaclass to create section classes, we can build our main config metaclass to build the `Config` class. ''' # %% class ConfigType(type): def __new__(cls, name, bases, cls_dict, env): """ env : str The environment we are loading the config for (e.g. dev, prod) """ cls_dict['__doc__'] = f'Configurations for {env}.' cls_dict['env'] = env config = configparser.ConfigParser() file_name = f'{env}.ini' config.read(file_name) for section_name in config.sections(): class_name = section_name.capitalize() class_attribute_name = section_name.casefold() section_items = config[section_name] bases = (object, ) section_cls_dict = {} # create a new Section class for this section Section = SectionType( class_name, bases, section_cls_dict, section_name=section_name, items_dict=section_items ) # And assign it to an attribute in the main config class cls_dict[class_attribute_name] = Section return super().__new__(cls, name, bases, cls_dict) # %% ''' Now we can create config classes for each of our environments: ''' # %% class DevConfig(metaclass=ConfigType, env='dev'): pass class ProdConfig(metaclass=ConfigType, env='prod'): pass # %% vars(DevConfig) # %% help(DevConfig) # %% vars(DevConfig.database) # %% help(DevConfig.database) # %% print(DevConfig.database.db_host, ProdConfig.database.db_host)
e2eeb69f75ae0eae849eb1708cf0b81d90eb5583
syurskyi/Python_Topics
/121_refactoring/Code_Smells/Bloaters/Long_Method/Replace_Temp_with_Query/007.py
1,106
3.734375
4
# Problem def calculateTotalAmount(): subtotal = calculateSubtotal() taxRate = getTaxRate() taxAmount = subtotal * taxRate totalAmount = subtotal + taxAmount return totalAmount def calculateSubtotal(): pass # calculation logic for subtotal def getTaxRate(): pass # logic to fetch tax rate from database or configuration # Solution def calculateTotalAmount(): subtotal = calculateSubtotal() taxAmount = calculateTaxAmount(subtotal) totalAmount = subtotal + taxAmount return totalAmount def calculateSubtotal(): pass # calculation logic for subtotal def calculateTaxAmount(subtotal): taxRate = getTaxRate() return subtotal * taxRate def getTaxRate(): pass # logic to fetch tax rate from database or configuration # In this example, we extract the calculation of the tax amount into a separate function calculateTaxAmount(). # This function takes the subtotal as a parameter and calculates the tax amount based on the tax rate fetched # from the getTaxRate() function. This improves code modularity and readability.
902ad12fab4277f162fb97899caedb82e403a078
syurskyi/Python_Topics
/012_lists/examples/Python 3 Most Nessesary/8.12. Filling the list with numbers.py
387
3.59375
4
print(list(range(11))) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(range(1, 16))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print(list(range(15, 0, -1))) # [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] import random arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(random.sample(arr, 3)) # [1, 9, 5] print(random.sample(range(300), 5)) # [259, 294, 142, 292, 245]
e5309aa50d37717ff0f75cd5c12bb3422a00ad35
syurskyi/Python_Topics
/095_os_and_sys/_exercises/templates/Python pathlib tutorial/011_parts.py
658
3.5625
4
# Path consists of subelements, such as drive or root. # parts.py # #!/usr/bin/env python ____ p.. ______ P__ path = P__('C:/Users/Jano/Documents') print(path.parts) print(path.drive) print(path.root) # The program prints some parts of a path. print(path.parts) # The parts gives access to the path’s various components. print(path.drive) # The drive gives a string representing the drive letter or name, if any. print(path.root) # The root gives a string representing the (local or global) root, if any. # $ parts.py # ('C:\\', 'Users', 'Jano', 'Documents') # C: # \ # # This is the output. # The following program gives other parts of a path.
17c9922315777a98beb9a4799bad497699ecd265
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/299/base_converter.py
859
4.5
4
# ___ convert number i.. base i.. 2 __ s.. # """Converts an integer into any base between 2 and 36 inclusive # # Args: # number (int): Integer to convert # base (int, optional): The base to convert the integer to. Defaults to 2. # # Raises: # Exception (ValueError): If base is less than 2 or greater than 36 # # Returns: # str: The returned value as a string # """ # __ (1 < ? < 37) a.. isi.. ? i.. # base_num "" # w.... ?>0 # dig i.. ?%? # __ ?<10 # b.. +_ s.. ? # ____ # b.. +_ c.. o.. 'A' +d.. - 10 #Using uppercase letters # ? //= ? # # b.. b.. ||-1 #To reverse the string # r.. ? # ____ n.. isi.. ? i.. # r.. T.. # ____ # r.. V... # # #print(convert(128, 5))
c38dd68bbeecd9d6126d1c37d9900b615c3e1e88
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Tree/PathSumII.py
1,632
3.953125
4
""" Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. Note: A leaf is a node with no children. Example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Return: [ [5,4,11,2], [5,8,4,5] ] PathSum 的进阶版,输出所有符合条件的路径。所以这里直接用遍历,有负数加上不是二叉搜索树应该没太多需要优化的地方。 测试用例: https://leetcode.com/problems/path-sum-ii/description/ """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if not root: return [] result = [] def helper(prev, root, sum, path): if prev + root.val == sum: if not root.left and not root.right: result.append(list(map(int, path.split(' ')[1:]))+[root.val]) return True if root.left: helper(prev + root.val, root.left, sum, path=path+" "+str(root.val)) # return True if root.right: helper(prev + root.val, root.right, sum, path=path+" "+str(root.val)) return False helper(0, root, sum, "") return result
1cb2e490da0eb7d7dcf491ade9fbfb576807c9ce
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BitManipulation/78_Subsets.py
808
3.65625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ subsets = [] n = len(nums) nums.sort() # We know there are totally 2^n subsets, # becase every num may in or not in one subsets. # So we check the jth(0<=j<n) bit for every ith(0=<i<2^n) subset. # If jth bit is 1, then nums[j] in the subset. sum_sets = 2 ** n for i in range(sum_sets): cur_set = [] for j in range(n): power = 2 ** j if i & power == power: cur_set.append(nums[j]) subsets.append(cur_set) return subsets """ [0] [] [1,2,3,4,7,8] """
22f8974676203d4efb0a4e4280a30a93413e3d6e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/intermediate-bite-78-find-programmers-with-common-languages.py
1,319
3.96875
4
""" Similar as last Bite we do another comparison of sequences exercise. Here is the deal: you are in charge of huge org of many software devs. You need as many devs for a new app you want to build so let's do an inventory of the most common languages across the board. Your input data is a dict of this format: {'bob': ['JS', 'PHP', 'Python', 'Perl', 'Java'], 'paul': ['C++', 'JS', 'Python'], 'sara': ['Perl', 'C', 'Java', 'Python', 'JS'], 'tim': ['Python', 'Haskell', 'C++', 'JS']} Complete the common_languages function that receives a dict of this format and returns the languages that ALL devs have in common, so in this case it would return Python and JS. Under TESTS we test your code against a few more scenarios. Have fun! """ programmers {'bob': 'JS', 'PHP', 'Python', 'Perl', 'Java' , 'paul': 'C++', 'JS', 'Python' , 'sara': 'Perl', 'C', 'Java', 'Python', 'JS' , 'tim': 'Python', 'Haskell', 'C++', 'JS' } ___ common_languages programmers """Receive a dict of keys -> names and values -> a sequence of of programming languages, return the common languages""" sets # list ___ key, value __ programmers.i.. sets.a..(s..(value first_set sets[0] remaining_sets sets[1:] print(remaining_sets) result first_set.i.. *remaining_sets) print(result) ? ?
0087f05b3409c4d03e75075c0e2d0ac68fb14a9e
syurskyi/Python_Topics
/115_testing/examples/Test-Driven Python Development/Chapter 8/test_driven_python-chapter-8/test_driven_python-chapter-8/stock_alerter/tests/test_timeseries.py
763
3.5
4
import unittest from datetime import datetime from ..timeseries import TimeSeries class TimeSeriesTestCase(unittest.TestCase): def assert_has_price_history(self, price_list, series): for index, expected_price in enumerate(price_list): actual_price = series[index].value if actual_price != expected_price: raise self.failureException("Price index {0}: {1} != {2}".format( index, expected_price, actual_price)) class TimeSeriesEqualityTest(TimeSeriesTestCase): def test_timeseries_price_history(self): series = TimeSeries() series.update(datetime(2014, 3, 10), 5) series.update(datetime(2014, 3, 11), 15) self.assert_has_price_history([5, 15], series)
38231747e6d91a361d2015bbb2816d4e3383ae94
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_2/unittest-master/python/basics.py
1,386
3.765625
4
# assignment03.py # @author: Shubham Sachdeva # @email: # @date: 18-10-09 import csv CONST_AUTHOR = "Shubham Sachdeva" # REF_DATE GEO DGUID Food categories Commodity class Product: # initialisation def __init__(self, year, geo, guid, category, commodity): self.id = 0 self.year = int(year) self.geo = geo self.guid = guid self.category = category self.commodity = commodity # for print def __str__(self): return ("%d\t%d\t%s\t%s\t%s\t%s" % (self.id, self.year, self.geo, self.guid, self.category, self.commodity)) def read_csv(file_name): lst = [] try: with open(file_name, newline='', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile) for row in reader: product = Product(1960, row['GEO'], row['DGUID'], row['Food categories'], row['Commodity']) print (product) lst.append(product) except: print ('read_csv failed') return lst def main(): lst = read_csv('input.csv') n = len(lst) print ('Number of records: ', n) if n < 10000: print ('There are less than 10000 records') elif n > 10000: print ('There are more than 10000 records') else: print ('There are exactly 10000 records') if __name__ == '__main__': print (CONST_AUTHOR) main()
2a941e251d78633d70caf05e60efa864cc49aba9
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/701 Insert into a Binary Search Tree.py
1,190
4.375
4
#!/usr/bin/python3 """ Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them. For example, Given the tree: 4 / \ 2 7 / \ 1 3 And the value to insert: 5 You can return this binary search tree: 4 / \ 2 7 / \ / 1 3 5 This tree is also valid: 5 / \ 2 7 / \ 1 3 \ 4 """ # Definition for a binary tree node. c_ TreeNode: ___ - , x val x left N.. right N.. c_ Solution: ___ insertIntoBST root: TreeNode, val: i.. __ TreeNode: __ n.. root: r.. TreeNode(val) __ root.val < val: root.right insertIntoBST(root.right, val) ____ root.val > val: root.left insertIntoBST(root.left, val) ____ r.. r.. root
e153092a6a9d922dcaa9be6eebae3e003802110f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/079 Combinations.py
1,138
3.78125
4
""" Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] """ __author__ 'Danyang' c_ Solution: ___ combine n, k """ Similar to 045 Permutation :param n: int :param k: int :return: a list of lists of integers """ result # list nums [i+1 ___ i __ x..(n)] # sorted, avoid duplicate get_combination(k, nums, # list, result) r.. ? ___ get_combination k, nums, current, result __ l..(current)__k: result.a..(current) r.. # prune ____ l..(current)+l..(nums)<k: r.. # prune ___ ind, val __ e..(nums # try: get_combination(k, nums[ind+1:], current+[val], result) # list(current).append(val) is side-effect # except IndexError: # self.get_combination(k, [], current+[val], result) # array slice out of index will return [] __ _____ __ ____ print Solution().combine(4, 2)
4424a0e72f4df9b61cb9b4d66b3e78ab0964ee61
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/025_Reverse_Nodes_i_ k-Group.py
1,099
3.765625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # class Solution(object): # def reverseKGroup(self, head, k): # """ # :type head: ListNode # :type k: int # :rtype: ListNode # """ c_ Solution o.. ___ reverseKGroup head, k __ head is N..: r_ N.. index = 0 lead, last = 0, 0 pos = head temp = ListNode(-1) temp.next = head head = temp start = head w.. pos is n.. N..: __ index % k __ k - 1: last = pos.next start = reverseList(start, last) pos = start pos = pos.next index += 1 r_ head.next ___ reverseList head, end pos = head.next last = end next_start = pos w.. pos != end: head.next = pos last_pos = pos pos = pos.next last_pos.next = last last = last_pos r_ next_start
f50b7d8beae1763ff2665416301bec37eff8fc53
syurskyi/Python_Topics
/050_iterations_comprehension_generations/009_permutations/examples/009_permutations.py
1,745
4.46875
4
# Permutations # In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence # or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. # These differ from combinations, which are selections of some members of a set where order is disregarded. # We can create permutations of length n from an iterable of length m (n <= m) using the permutation function: # As you can see all the permutations are, by default, the same length as the original iterable. # We can create permutations of smaller length by specifying the r value: # The important thing to note is that elements are not 'repeated' in the permutation. # But the uniqueness of an element is not based on its value, but rather on its position in the original iterable. # This means that the following will yield what looks like the same permutations when considering the values of # the iterable: l1 = 'abc' list(itertools.permutations(l1)) list(itertools.permutations(l1, 2)) list(itertools.permutations('aaa')) list(itertools.permutations('aba', 2)) # Combinations # Combinations refer to the combination of n things taken k at a time without repetition. To refer to combinations in # which repetition is allowed, the terms k-selection,[1] k-multiset,[2] or k-combination with repetition are often used. # itertools offers both flavors - with and without replacement. # Let's look at a simple example with replacement first: # As you can see (4, 3) is not included in the result since, as a combination, it is the same as (3, 4) - # order is not important. list(itertools.combinations([1, 2, 3, 4], 2)) list(itertools.combinations_with_replacement([1, 2, 3, 4], 2))
ea94e97ae81c46d16d5b7fb99e9776dca336fe57
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/121 Best Time to Buy and Sell Stock II.py
1,065
3.765625
4
""" Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). """ __author__ 'Danyang' c_ Solution: ___ maxProfit prices """ multiple transactions you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Algorithm: transformed array :param prices: list of integers :return: integer """ __ l..(prices) <_ 1: r.. 0 delta_prices # list # \delta ___ i __ x..(1, l..(prices: delta_prices.a..(prices[i]-prices[i-1]) # O(n) profit 0 ___ i __ x..(l..(delta_prices: __ delta_prices[i] > 0 profit += delta_prices[i] r.. profit
c3cac517a34075d13cc9839c5aafffab20eefd1d
syurskyi/Python_Topics
/045_functions/007_lambda/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 67 sum_even_values.py
566
4.21875
4
# Sum Even Values Solution # # I define a function called sum_even_values which accepts any number of arguments, thanks to *args # I grab the even numbers using the generator expression (arg for arg in args if arg % 2 == 0) # (could also use a list comp) # I pass the even numbers I extracted into sum() and return the value # The default start value of sum() # is 0, so I don't have to do anything special to get it to return 0 if there are no even numbers! def sum_even_values(*args): return sum(arg for arg in args if arg % 2 == 0)
e68fa28abb8eb130145171dbbaadced13f473c6d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/953 Verifying an Alien Dictionary.py
1,996
4.21875
4
#!/usr/bin/python3 """ In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language. Example 1: Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" Output: true Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted. Example 2: Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" Output: false Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted. Example 3: Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" Output: false Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info). Note: 1 <= words.length <= 100 1 <= words[i].length <= 20 order.length == 26 All characters in words[i] and order are english lowercase letters. """ ____ t___ _______ L.. c_ Solution: ___ isAlienSorted words: L..[s..], order: s..) __ b.. h # dict ___ i, c __ e..(order h[c] i ___ i __ r..(1, l.. ? __ cmp(words[i], words[i-1], h) __ -1: r.. F.. r.. T.. ___ cmp w1, w2, h ___ c1, c2 __ z..(w1, w2 __ h[c1] < h[c2]: r.. -1 ____ h[c1] > h[c2]: r.. 1 __ l..(w1) __ l..(w2 r.. 0 ____ l..(w1) > l..(w2 r.. 1 ____ r.. -1 __ _______ __ _______ ... Solution().isAlienSorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz") __ T..
f0e8cad843cb9ecf98ad007c178056965a0ad12b
amuralitharan/ML-Algorithms
/linear_regression.py
511
3.765625
4
import os import numpy as np from matplotlib import pyplot def cost(theta, y, X): n = y.size prediction = np.sum(np.square(y - np.transpose(theta[1:])*X + theta[0]))/n print(prediction.shape) def gradient_descent(): return 1 def predict(): return 1 def main(): #load data data = np.genfromtxt(os.path.join('Data', 'winequality-white.csv'), delimiter=';') X, y = data[:, :11], data[:, 11:] #generate sample theta theta = np.random.rand(12) cost(theta, y, X) if __name__ == "__main__": main()
5fda98f6aefa499a9f3c89c28db5d61304241337
lggurgel/python
/prime_v2.py
245
3.890625
4
def fib(n): """Returns a list containing the Fibonacci series up to n.""" result = [] a, b = 0, 1 while a < n: result.append(a) a, b = b, a+b return result def func(a, L=[]): L.append(a) return L
2c191b2346b933eb372c0d2a6001cc40b50ef013
AhmedOAshour/File-Allocation-Simulator
/file_allocation.py
9,844
3.9375
4
import random class File: def __init__(self, size, name): # Constructor self.size = size self.name = name self.start = None self.end = None def display(self): # How the console will display the allocated Files if self.start is None: print("Name: ", self.name, " Size: ", self.size, "Start: Unallocated") else: print("Name: ", self.name, " Size: ", self.size, "Start:", self.start, "End: ", self.end) class Memory: def __init__(self, size): # Constructor self.size = size self.allocated = 0 self.block = [] for i in range(size): # Initializing every memory block with NULL value (empty) self.block.append(None) def change_size(self, size): if size == 0: self.block = [] elif self.size < size: # If new size > old size, system will append new empty blocks for i in range(self.size, size): self.block.append(None) elif self.size > size: # If new size < old size, system will delete difference difference = self.size - size # in memory size and delete any Files that were allocated in the recently for i in range(self.size - 1, self.size - difference, -1): # deleted memory blocks del self.block[i] last = self.block[-1] if last is not None and last.start + last.size > size: for i in range(size, last.start - 1, -1): self.block[i] = None else: print("Same size entered, no changes made") return self.size = size def unallocated(self): return self.size - self.allocated def display(self): # How the console will display the allocated memory blocks for i in range(self.size): if self.block[i] is None: print("Block: ", i, " File: ", self.block[i]) elif isinstance(self.block[i], list): print("Block: ", i, " Index Table: ", self.block[i]) else: print("Block: ", i, " File: ", self.block[i].name) def display_linked(self): for i in range(self.size): if self.block[i] is None: print("Block: ", i, " File: ", self.block[i]) else: print("Block: ", i, " File: ", self.block[i].data.name) def display_indexed(self): for i in range(self.size): if self.block[i] is None: print("Block: ", i, " File: ", self.block[i]) else: print("Block: ", i, " File: ", self.block[i].name) class Node: def __init__(self, data, nextval): self.data = data self.nextval = nextval class Simulator: def __init__(self, files, memory): # Constructor self.files = files self.memory = memory self.flag = None def contiguous(self): self.flag = 1 for file in self.files: error_count = 0 if file.start is None and self.memory.unallocated() >= file.size: start = rng(0, self.memory.size - 1) rngval = start loop_flag = True while loop_flag: count = 0 error_count += 1 flag = False for i in range(start, start + file.size): if flag and i >= rngval: loop_flag = False if i >= self.memory.size and not flag: flag = True break if self.memory.block[i] is None: count += 1 else: start += self.memory.block[i].size + count break if error_count > 200: break if flag: start = 0 # due to random start if end is reached loop back to memory block 0 if count == file.size: for i in range(start, start + file.size): # allocate self.memory.block[i] = file self.memory.allocated += 1 file.start = start file.end = file.size + file.start - 1 break def linked(self): self.flag = 2 for file in self.files: if file.start is None and self.memory.unallocated() >= file.size: current = None for i in range(0, file.size): index = rng(0, self.memory.size - 1) while self.memory.block[index] is not None: index += 1 if index >= self.memory.size: index = 0 self.memory.block[index] = Node(file, None) self.memory.allocated += 1 if current is not None: current.nextval = self.memory.block[index] current = current.nextval if i == 0: file.start = index current = self.memory.block[index] if i == file.size - 1: file.end = index def indexed(self): self.flag = 3 for file in self.files: if file.start is None and self.memory.unallocated() >= file.size + 1: # Check condition for i in range(0, file.size + 1): index = rng(0, self.memory.size - 1) while self.memory.block[index] is not None: index += 1 if index >= self.memory.size: index = 0 if i == 0: file.start = index self.memory.block[index] = [] self.memory.allocated += 1 continue self.memory.block[index] = file self.memory.block[file.start].append(index) self.memory.allocated += 1 def reset(self): for i in range(0, self.memory.size): self.memory.block[i] = None self.memory.allocated = 0 for file in self.files: file.start = None file.end = None def delete(self, filename): if self.flag is None or self.flag == 1: return self.delete_contiguous(filename) elif self.flag == 2: return self.delete_linked(filename) elif self.flag == 3: return self.delete_indexed(filename) def delete_contiguous(self, filename): # Function that deletes File given the File's name from the user for file in self.files: if file.name == filename: if file.start is not None: # Remove file from every memory block it is allocated to for i in range(file.start, file.size + file.start): self.memory.block[i] = None self.memory.allocated -= 1 self.files.remove(file) # Removing the File from the file list return True return False def delete_indexed(self, filename): for file in self.files: if file.name == filename: if file.start is not None: table = self.memory.block[file.start] self.memory.block[file.start] = None self.memory.allocated -= 1 for i in table: self.memory.block[i] = None self.memory.allocated -= 1 self.files.remove(file) return True return False def delete_linked(self, filename): for file in self.files: if file.name == filename: if file.start is not None: current = self.memory.block[file.start] while current.nextval is not None: next = current.nextval del current current = next self.files.remove(file) return True return False def display(self): # Function to display the Files alongside the memory blocks print("Available space: ", self.memory.unallocated()) print("Files:") for file in self.files: file.display() print("Blocks: ") self.memory.display() def display_linked(self): print("Available space: ", self.memory.unallocated()) print("Files:") for file in self.files: file.display() print("Blocks: ") self.memory.display_linked() def display_indexed(self): print("Available space: ", self.memory.unallocated()) print("Files:") for file in self.files: for i in range(0, file.size): if file.start is None: print("File Block: ", file.name, i, " Not Allocated") continue if i == (file.size - 1): print("File Block: ", file.name, i, ", Memory Block: ", self.memory.block[file.start][i], ", Next Block: NONE") continue print("File Block: ", file.name, i, ", Memory Block: ", self.memory.block[file.start][i], ", Next Block: ", self.memory.block[file.start][i+1]) print("Blocks: ") self.memory.display() def rng(start, end): # random number generator, default seed is system time return random.randint(start, end)
c7fde44dbdbdd8fbf0a8f75bc98819f46a6d2dd2
Nunziatellanicolepalarymzai/Python-104
/mean.py
883
4.375
4
# Python program to print # mean of elements # list of elements to calculate mean import csv with open('./height-weight.csv', newline='') as f: reader = csv.reader(f) #csv.reader method,reads and returns the current row and then moves to the next file_data = list(reader) #list(reader) adds the data to the list file_data.pop(0) #to remove the title from the data print(file_data) # sorting data to get the height of people. new_data=[] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(float(n_num)) #Then create a empty list named new_data . #Then use a for loop on file_data to get the elements inside the nested lists #and append them to the new_data list. # #getting the mean n = len(new_data) total =0 for x in new_data: total += x mean = total / n # print("Mean / Average is: " + str(mean))
f2b95c8cfb31b7bda19f595933464f7c00b8484d
kremenovic96/mitxpy
/textbook/sqr.py
406
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 6 09:54:49 2016 @author: ranko """ x = 25 epsilon = 0.01 step = epsilon ** 2 numGuesses = 0 ans = 0.0 while abs(ans ** 2-x) >= epsilon and ans <= x: ans += step numGuesses += 1 print("Numguesses: "+ str(numGuesses)) if abs(ans ** 2 -x) >= epsilon: print("failed to finds squuare root ") else: print(str(ans) + " is close to: " + str(x))
581eb4f8342ca1603abb22b42b2b710f4ff33951
aleshkoa/python_exercise
/question2.py
156
3.734375
4
celsius = float(raw_input('Enter Temperature in Celsius ')) fahrenheit = 9.0/5.0 * celsius + 32 print 'Temperature in Fahrehnheit is: ' + str(fahrenheit)
4027c95a7a449d9c46b21c2b08ca93ca51f37b8b
AngelTNP/Entrenamiento
/ProjectEuler/7.py
300
3.703125
4
import math def primo(x): if(x%2==0): return False for i in range(3,math.floor(math.sqrt(x))+1,2): if(x%i==0): return False return True def __main__(): x = 1 #uno por el dos prim = 1 while(x!=10001): prim+=2 if(primo(prim)): x+=1 print(prim) __main__()
4018f88f3fe2adff2ffd46ea33fa91976ee6e837
AngelTNP/Entrenamiento
/ProjectEuler/15.py
184
3.6875
4
def factorial(x): if(x<=1): return 1 else: return x*factorial(x-1) def __main__(): tam = 20 routes = factorial(2*tam)/(factorial(tam)**2) print(routes) __main__()
34b74af222fda40f35d744e2909cde08df0f3092
ravis3517/i-neuron-assigment-and-project-
/i neuron_python_prog_ Assignment_3.py
1,845
4.34375
4
#!/usr/bin/env python # coding: utf-8 # 1. Write a Python Program to Check if a Number is Positive, Negative or Zero # In[25]: num = float(input("Enter a number: ")) if num >0: print("positive") elif num <0 : print("negative") else: print(" number is zero") # 2. Write a Python Program to Check if a Number is Odd or Even? # In[26]: num=int(input("enter the number:\n")) if (num %2==0): print("The number is even") else: print("the number is odd") # 3.Write a Python Program to Check Leap Year? # A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400 # In[27]: # To enter year by user year=int(input("Enter the year:\n")) # Leap Year Check if year % 4 == 0 and year % 100 != 0: print(year, "is a Leap Year") elif year % 100 == 0: print(year, "is not a Leap Year") elif year % 400 ==0: print(year, "is a Leap Year") else: print(year, "is not a Leap Year") # Write a Python Program to Check Prime Number? # In[28]: #test all divisors from 2 through n-1 (Skip 1 and n since prime number is divided by 1 and n ) num=10 for i in range(2,num): ## it will test till n-1 i.e till 9 if num % i == 0: print( num , " is Not prime") break else : print( num ," is a prime") # Write a Python Program to Print all Prime Numbers in an Interval of 1-10000? # In[29]: # Python program to print all # prime number in an interval # number should be greater than 1 first_number = 1 last_number = 10000 for i in range(first_number ,last_number +1): if i>1: for j in range(2,i): if i%j==0: break else: print(i)
ec03cd41e2133e9853dd508b691bc926da35dfb2
naveenailawadi/old
/roku/json_parser.py
3,481
3.5625
4
''' This script is designed to pull many objects in JSON from an api. It then formats it into a csv file. This was done to research the every screensaver that roku had to offer. ''' import requests from bs4 import BeautifulSoup as bs import json import pandas as pd import csv # obtain the channel and key --> input to csv (see key_finder.py) # then read the keys and iterate for each one # name csv that will be written new_file = 'roku_extracted_data.csv' # api main URL main_site = 'https://channelstore.roku.com/api/v6/channels/detailsunion/' # find necessary csv name = 'name_and_key.csv' # read csv data and create a list of it data = pd.read_csv(name, header=0) # read csv and find keys keys = data.key def json_parser(key): # create alterated webkey website_alt = str(main_site + str(key)) # create soup print('creating soup for ' + website_alt + '...') print('Do not touch anything.') site_raw = requests.get(website_alt) site_soup = bs(site_raw.text, "html.parser") # convert website string to json json_final = json.loads(site_soup.text) # parse json for pertinent data # create variables for pertinent data name = json_final['feedChannel']['name'] starRating = json_final['feedChannel']['starRating'] starRatingCount = json_final['feedChannel']['starRatingCount'] description = json_final['feedChannel']['description'] screenshotUrls = json_final['feedChannel']['screenshotUrls'] screenshotUrls_length = len(screenshotUrls) paymentSchedule = json_final['feedChannel']['paymentSchedule'] priceAsNumber = json_final['details']['priceAsNumber'] developerUserId = json_final['details']['developerUserId'] developerId = json_final['details']['developerId'] isPublic = json_final['details']['isPublic'] channelState = json_final['details']['channelState'] name_detail = json_final['details']['name'] fixedName = json_final['details']['fixedName'] createdDate = json_final['details']['createdDate'] modifiedDate = json_final['details']['modifiedDate'] publishedDate = json_final['details']['publishedDate'] effectiveAdditionalRequirements = json_final['details']['effectiveAdditionalRequirements'] literalRevenueSources = json_final['details']['currentDetail']['literalRevenueSources'] # create list for all of the data (will be loaded into pandas dataframe and master csv) data_list = [ name, starRating, starRatingCount, description, screenshotUrls, screenshotUrls_length, paymentSchedule, priceAsNumber, developerUserId, developerId, isPublic, channelState, name_detail, fixedName, createdDate, modifiedDate, publishedDate, effectiveAdditionalRequirements, literalRevenueSources ] return data_list # count potential errors in parsing JSON data error_count = 0 # create a csv file with open(str(new_file), mode='w') as csv_file: # set up master csv writer writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # iterate over all of the keys for key in keys: try: new_row = json_parser(key) writer.writerow(new_row) except UnicodeEncodeError: error_count += 1 continue print('Could not find data for ' + str(error_count) + ' screensavers.') print('Done!')
a028274caf752af14baee2af8545bc6cda42735b
naveenailawadi/old
/reddit scraper/initializer.py
937
3.671875
4
''' In order to run any reddit scraper using the PRAW API, you have to register yourself with reddit. To avoid reeditting each script with the user's API keys, this script inputs them all into a central CSV which will later be referred to in each script. ''' import csv print('Follow the instructions below to input the necessary information into a csv for future reference.') with open('reddit_login_info.csv', 'w') as file: # let w represent our file w = csv.writer(file) # write the header row w.writerow(['clientid', 'secret', 'password', 'user_agent', 'username']) clientid = input('What is your clientid? \n') secret = input('What is your secret key? \n') user_agent = 'useragentex' username = input('What is your username? \n') password = input('What is your password? \n') w.writerow([clientid, secret, password, user_agent, username]) print('Done. your data file has been created.')
f00a9c43628e75670b8dbea28eda0b0b5e792c25
naveenailawadi/old
/reddit scraper/all_searcher.py
4,835
3.5
4
''' In addition to the reguilar reddit scraper, the same client wanted to scrape all of reddit for specific search terms. This was not difficult to implement as the subreddit for all of reddit is simply "all". ''' import praw import pandas as pd import datetime # read login information name = 'reddit_login_info.csv' info_csv = pd.read_csv(name, header=0) # log in to reddit reddit = praw.Reddit(client_id=info_csv.clientid[0], client_secret=info_csv.secret[0], password=info_csv.password[0], user_agent=info_csv.user_agent[0], username=info_csv.username[0]) # enter and acces decided subreddit entry = input('Enter reddit search term: \n') # set an api postcall limit post_call_limit = input('What is the maximum number of posts that you would like to return? \n') # set start date date_start = input("What is the earliest date that you would like to start scraping at (e.g. 2000-12-25)? \n") def subreddit_post_scraper(entry, post_call_limit, date_start): # dissect start date date_start_year = int(date_start[:4]) date_start_month = int(date_start[5:7]) date_start_day = int(date_start[8:]) - 1 subreddit = reddit.subreddit('all').search(entry, limit=int(post_call_limit)) # create a list of lists for each post and its information mega_list = [] # find all of the posts in the subreddit post_list = [] for submission in subreddit: # filter out all submissions before the desired date publish_date = str(datetime.datetime.utcfromtimestamp(submission.created_utc)) if int(publish_date[:4]) < date_start_year: break if (int(publish_date[:4]) == date_start_year) and (int(publish_date[5:7]) < date_start_month): break if (int(publish_date[:4]) == date_start_year) and (int(publish_date[5:7]) == date_start_month) and (int(publish_date[8:10]) < date_start_day): break post_list.append(submission) # find all the comments in the post for post in post_list: individual_cell = [post.title, post.id, post.author, int(post.ups - post.downs), datetime.datetime.utcfromtimestamp(post.created_utc), post.selftext] comment_list = [] for comment in post.comments: try: comment_list.append(str(comment.body + ' (replies: ' + str(len(comment.replies))) + ')') except AttributeError: continue individual_cell.append(comment_list) mega_list.append(individual_cell) return mega_list def subreddit_comment_scraper(entry, post_call_limit, date_start): # dissect start date date_start_year = int(date_start[:4]) date_start_month = int(date_start[5:7]) date_start_day = int(date_start[8:]) - 1 subreddit = reddit.subreddit('all').search(entry, limit=int(post_call_limit)) # create a list of lists for each post and its information mega_list = [] # find all of the posts in the subreddit post_list = [] for submission in subreddit: # filter out all submissions before the desired date publish_date = str(datetime.datetime.utcfromtimestamp(submission.created_utc)) if int(publish_date[:4]) < date_start_year: break if (int(publish_date[:4]) == date_start_year) and (int(publish_date[5:7]) < date_start_month): break if (int(publish_date[:4]) == date_start_year) and (int(publish_date[5:7]) == date_start_month) and (int(publish_date[8:10]) < date_start_day): break post_list.append(submission) # find all the comments in the post for post in post_list: for comment in post.comments: individual_cell = [post.title, post.id, post.author, int(post.ups - post.downs), datetime.datetime.utcfromtimestamp(post.created_utc), post.selftext] try: new_addition = [comment.body, comment.id, comment.author, comment.ups, len(comment.replies)] for addition in new_addition: individual_cell.append(addition) mega_list.append(individual_cell[:11]) except AttributeError: continue return mega_list # post dataframe subreddit_posts_scraped = subreddit_post_scraper(entry, post_call_limit, date_start) df_posts = pd.DataFrame(subreddit_posts_scraped, columns=['Title', 'post_id', 'Author', 'Vote_Score', 'Date', 'Body', 'Comments']) print('Post Dataframe:') print(df_posts) # comment dataframe subreddit_comments_scraped = subreddit_comment_scraper(entry, post_call_limit, date_start) df_comments = pd.DataFrame(subreddit_comments_scraped, columns=['Title', 'post_id', 'Author', 'Vote_Score', 'Date', 'Body', 'Comment', 'comment_id', 'comment_author', 'ups', 'replies']) print('Comment Dataframe:') print(df_comments)
f6e90f66de85f270c174bf3d5d0b0aa40a5135ce
bowie2k3/cos205
/COS-205_assignment4a_AJ.py
526
4.0625
4
# COS-205_assignment4a_AJ.py # Write a program that calculates and prints out the numeric value # of a single name provided as input by the user. # The value of a name is determined by summing up the values of the letters # of the name where “a” or “A” is 1, “b” or “B” is 2, and so on, up to “z” or “Z” being 26 name = input("Please enter a name: ") name = name.lower() total = 0 for each in name: val = ord(each)-96 total = total + val print("The numeric value of the name is:", total)
07540d509c99f96db7fcc7f7362a36f5dc52d36d
bowie2k3/cos205
/COS-205_assignment4b_AJ.py
683
4.5
4
# Write a program that counts the number of words in a text file. # the program should print out [...] the number of words in the file. # Your program should prompt the user for the file name, which # should be stored at the same location as the program. # It should consider anything that is separated by white space or # new line on either side of a contiguous group of characters or # character as a word. def main(): fname = input("Please enter the filename: ") infile = open(fname, "r") data = infile.read() stripnl = data.replace("\n", " ") words = stripnl.split(" ") count = len(words) print("The number of words in the file is: ", count) main()
492e5b9f3c3a540ede56386dd10e8fb0961ee7cd
iaen7/leetcode
/leetcode12.py
1,247
3.671875
4
def intToRoman(num): One = num % 10 num = num/10 Ten = num % 10 num = num/10 Hundred = num % 10 num = num/10 Thousand = num % 10 num = num/10 Roman = '' if Thousand > 0: for i in range(0,Thousand): Roman += 'M' if Hundred == 9: Roman += 'CM' elif Hundred <=8 and Hundred >=5: Roman += 'D' for i in range(0,Hundred-5): Roman += 'C' elif Hundred == 4: Roman += 'CD' elif Hundred >= 0 and Hundred <= 3: for i in range(0,Hundred): Roman += 'C' if Ten == 9: Roman += 'XC' elif Ten <=8 and Ten >=5: Roman += 'L' for i in range(0,Ten-5): Roman += 'X' elif Ten == 4: Roman += 'XL' elif Ten >= 0 and Ten <= 3: for i in range(0,Ten): Roman += 'X' if One == 9: Roman += 'IX' elif One <=8 and One >=5: Roman += 'V' for i in range(0,One-5): Roman += 'I' elif One == 4: Roman += 'IV' elif One >= 0 and One <= 3: for i in range(0,One): Roman += 'I' return Roman num = 3888 print intToRoman(num)
cf72a8464f464469a57fb5703814c2916673ba3b
iaen7/leetcode
/leetcode13.py
870
3.6875
4
def romanToInt(s): Length = len(s) Number = 0 for i in range(0,Length): if s[i] == 'M': Number += 1000 elif s[i] == 'C': if i<Length-1 and (s[i+1] == 'M' or s[i+1] == 'D'): Number -= 100 else: Number += 100 elif s[i] == 'D': Number += 500 elif s[i] == 'X': if i<Length-1 and (s[i+1] == 'C' or s[i+1] == 'L'): Number -= 10 else: Number += 10 elif s[i] == 'L': Number += 50 elif s[i] == 'I': if i<Length-1 and (s[i+1]=='X' or s[i+1] == 'V'): Number -= 1 else: Number += 1 elif s[i] == 'V': Number += 5 return Number s = 'MMMCMXCIX' print romanToInt(s)
b6d35f31562d97ec2fe4c6d9a1d349d23a45e7ea
jmmalnar/python_projects
/primes.py
1,896
4.40625
4
import unittest # Find all the prime numbers less than a given integer def is_prime(num): """ Iterate from 2 up to the (number-1). Assume the number is prime, and work through all lower numbers. If the number is divisible by ANY of the lower numbers, then it's not prime """ prime_status = True # 1, by definition, is not a prime number, so lets account for that directly if num == 1: prime_status = False return prime_status for i in range(2, num): mod = num % i if mod == 0: prime_status = False break return prime_status def find_primes(num): primes = [] for n in range(1, num): prime_status = is_prime(n) if prime_status: primes.append(n) return primes ######## # TEST # ######## class IsPrimesTests(unittest.TestCase): def test_19_should_be_prime(self): """Verify that inputting a prime number into the is_prime method returns true""" self.assertEqual(is_prime(19), True) def test_20_should_not_be_primer(self): """Verify that inputting a non-prime number into the is_prime method returns false""" self.assertEqual(is_prime(20), False) def test_1_should_not_be_prime(self): """Verify that inputting 1 into the is_prime method returns false""" self.assertEqual(is_prime(1), False) class FindPrimesTests(unittest.TestCase): def test_primes_to_20(self): """Verify that all of the correct primes less than 20 are returned""" primes = find_primes(20) self.assertEqual(primes, [2, 3, 5, 7, 11, 13, 17, 19]) def test_1_should_not_be_prime(self): """Verify that nothing is returned when you try and find all primes under 1""" primes = find_primes(1) self.assertEqual(primes, []) if __name__ == '__main__': unittest.main()
d938f0710f5c181262274d7214da083cc6407b26
lfcten/DataStructure
/search/sequential_search.py
659
3.71875
4
import time import datetime def sequential_search(a_list,item): pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos + 1 return found def sequential_search1(a_list,item): for num in a_list: if num == item: return True return False if __name__ == "__main__": test_list = range(1500000000000000) print(datetime.datetime.now(), sequential_search(test_list, 1500000), datetime.datetime.now()) time.sleep(3) print(datetime.datetime.now(), sequential_search1(test_list, 150000), datetime.datetime.now())
f46a8f7543a65eee3bb63829d3cf1f31de951fd3
nnegri/hackbright-dicts-word-count
/wordcount.py
1,404
4
4
import string, sys from collections import Counter def word_count(file_name): """ Create function to count occurances of each words in file_name""" #Created a function called word_tally pointing to file_name that is undefined atm text = open(file_name) #word_tally = {} # Empty dictionary word_tally = Counter() # Empty Counter for line in text: words = line.rstrip().split(' ') # Split each line into separate words for word in words: # Make word all lowercase, and remove punctuation word = word.lower().rstrip(string.punctuation) # Store word in dictionary, along with corresponding count #word_tally[word] = word_tally.get(word, 0) + 1 # Store word with in Counter, increase count by 1 word_tally.update({word:+1}) # for entry in word_tally.iteritems(): # Each 'entry' is a tuple in a new list # print '%s %d' % (entry[0], entry[1]) # Print information in each tuple for entry in word_tally: print '%s %d' % (entry, word_tally[entry]) # Print word and corresponding tally in Counter return word_tally # Return dictionary so you can use it in other functions # Use sys.argv, so in the Python shell you can call whichever textfile you want # For example, in terminal call: python wordcount.py test.txt file_name = sys.argv[1] word_count(file_name)
f0df69ad43bba6758269865bf50cb68ac9ea5ade
DenisZun/data_sturcture
/double_list.py
3,863
4
4
# python双向链表 class Node(object): """双向链表的节点""" def __init__(self, data): # data为节点的元素域 # pre为节点的头链接部 # next为节点的尾链接部 self.data = data self.pre = None self.next = None class DoubleLinkedList(object): """双向链表""" def __init__(self, node=None): """双向链表的头指针""" self.__head = node def is_empty(self): """链表是否为空""" return self.__head == None def length(self): """链表长度""" # 定义计数 # 定义游标 count = 0 cur = self.__head while cur != None: cur = cur.next count += 1 return count def travel(self): """遍历链表""" cur = self.__head while cur != None: print("链表内元素:{}".format(cur.data)) cur = cur.next def add(self, data): """头插法""" # 在头部创建一个新节点 # 1.创建一个新节点 # 2.将新节点的next指向旧头节点的pre # 3.将旧头节点的pre指向新节点的next # 4.头指针指向新节点 node = Node(data) if self.is_empty(): self.__head = node else: node.next = self.__head self.__head.pre = node self.__head = node def append(self, data): """尾插法""" # 1.创建一个新节点 # 2.将旧尾节点next指向新节点pre # 3.将新尾节点pre指向旧节点next # 4.新节点的链接部指向空节点None node = Node(data) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node cur.pre = cur node.next = None def insert(self, pos, data): """在指定位置插入元素""" if pos <= 0: # 头部插入 self.add(data) elif pos > self.length()-1: # 尾部插入 self.append(data) else: node = Node(data) # 计数 count = 0 # 游标 cur = self.__head while count < (pos - 1): cur = cur.next count += 1 node.pre = cur node.next = cur.next cur.next.pre = node cur.next = node def remove(self, data): """删除节点""" cur = self.__head while cur != None: # 查询待删除的节点 if cur.data == data: # 1.待删除的节点就是头节点 if cur == self.__head: self.__head = cur.next if cur.next: cur.next.pre = None # 2.待删除的节点是普通节点 else: cur.pre.next = cur.next if cur.next: cur.next.pre = cur.pre return else: cur = cur.next def search(self, data): """查找节点是否存在""" cur = self.__head while cur != None: if cur.data == data: print("查询{}成功".format(data)) return "查询结果为:{}".format(True) cur = cur.next return "查询结果为:{}".format(False) if __name__ == '__main__': li = DoubleLinkedList() li.add("a") li.add(2) li.append(3) li.insert(2, 4) print("链表长度为:{}".format(li.length())) li.travel() li.remove(2) print("链表长度为:{}".format(li.length())) li.travel() print(li.search(3))
14095826ac80567341236e436622a8fea5ad1840
kapil-varshney/byte_ds
/Week4/terminal_trader/controller.py
7,661
3.53125
4
#!/usr/bin/env python3 import model class Controller: username = '' @classmethod def navigate(cls): print("Welcome to the Terminal Trading Platform") cls.new_or_returning_user() cls.tasks() @classmethod def new_or_returning_user(cls): print("Are you a returning user or a new user?") choice = input("1. Returning user\n2. New user\n") if choice == '1': cls.returning_user() elif choice == '2': cls.new_user() else: print("\nPlease enter a valid selection.") cls.invalid_selection(cls.new_or_returning_user) @classmethod def returning_user(cls): username = input("\nPlease enter your username: ") password = input("Please enter your password: ") if model.identity_verified(username, password): print("Username and Password verified") cls.username = username return True else: print("\nIncorrect username and/or password.") cls.invalid_selection(cls.returning_user) @classmethod def new_user(cls): username = input("\nPlease create a username.\n") if model.username_available(username): print("\nUsername is available. Please continue...") password = input("Please create a password.\n") name = input("Please enter your name\n") model.create_user(username, password, name) print("Congratulation, you are now a part of Terminal Trader family.") print("\nRedirecting you to the login page...") cls.returning_user() else: print("\nUsername not available.") cls.invalid_selection(cls.new_user) @classmethod def tasks(cls): print("\nWhat do you want to do today?") print("1. Search companies") print("2. Retrieve market data for a stock") print("3. Buy stocks") print("4. Sell stocks") print("5. View your portfolio") print("0. Exit") user_input = input() if user_input == '1': df = cls.search_companies() if df.empty: print("Invalid company or data not available") else: print(df) cls.tasks() elif user_input == '2': print(cls.retrieve_market_data()) cls.tasks() elif user_input == '3': cls.buy() elif user_input == '4': cls.sell() elif user_input == '5': df = cls.view_portfolio() if df.empty: print("You don't hold any stocks\n") else: print(df) cls.tasks() elif user_input == '0': cls.user_exit() else: print("Please enter a valid selection") cls.tasks() @classmethod def search_companies(cls): user_input = input("Which company are you trying to lookup?\n") print("\nRetrieving company information...\n") return model.retrieve_company_data(user_input) @classmethod def retrieve_market_data(cls): user_input = input("Enter the ticker symbol (all caps) for the stock you are looking at.\n") print("\nRetrieving market data...\n") return model.retrieve_market_data(user_input) @classmethod def buy(cls): df = cls.search_companies() if df.empty: print("Invalid company or data not available") cls.tasks() else: print(df) ticker_symbol = input("\nPlease enter the ticker of the stock you are interested in.\n") if ticker_symbol not in list(df['Symbol']): print("Enter a valid ticker") cls.invalid_selection(cls.buy) market_data = model.retrieve_market_data(ticker_symbol) print("The last price of", market_data['Symbol'], "is:", market_data['LastPrice'], "as of", market_data['Timestamp']) if market_data['LastPrice'] == 0: print("\nThis stock is worth nothing. Please select another stock.\n") cls.buy() user_input = input("\nDo you want to proceed?\n1. Yes\n2. No (Go to the previous options)\n") if user_input == '1': cls.buy_stock(market_data['Symbol']) elif user_input == '2': cls.tasks() else: print("Please enter a valid selection") cls.invalid_selection(cls.buy) @classmethod def buy_stock(cls, ticker_symbol): balance = model.retrieve_balance(cls.username) print("\nYou have $", balance) num_of_stocks = int(input("How many stocks do you wanna buy?\n")) if model.enough_balance(cls.username, ticker_symbol, num_of_stocks): model.make_purchase(cls.username, ticker_symbol, num_of_stocks) else: user_input = input("\nYou don't have sufficient balance.\n1. Try different volume.\n2. Pick some other stock.\n0. Exit.") if user_input == '1': cls.buy_stock(ticker_symbol) elif user_input == '2': cls.buy() elif user_input == '0': cls.user_exit() else: print("Please enter a valid selection.") cls.invalid_selection(cls.buy) print("\nUpdated") print(cls.view_portfolio()) cls.tasks() @classmethod def sell(cls): df = model.get_portfolio(cls.username) print(df) ticker_symbol = input("Enter the ticker for the stock you want to sell: ") if ticker_symbol not in list(df['symbol']): print("You don't own that stock.") cls.invalid_selection(cls.sell) market_data = model.retrieve_market_data(ticker_symbol) print("The last price of", market_data['Symbol'], "is:", market_data['LastPrice'], "as of", market_data['Timestamp']) volume = int(input("How many stock do you want to sell? ")) if volume < int(df[df['symbol'] == ticker_symbol]['quantity']): model.sell_stocks(cls.username, ticker_symbol, volume) else: user_input = input("\nYou don't have sufficient volume.\n1. Try different volume.\n2. Pick some other stock.\n0. Exit.") if user_input == '1': cls.sell() elif user_input == '2': cls.sell() elif user_input == '0': cls.user_exit() else: print("Please enter a valid selection.") cls.invalid_selection(cls.buy) print("\nUpdated") print(cls.view_portfolio()) cls.tasks() @classmethod def view_portfolio(cls): print("\nBalance: ", model.retrieve_balance(cls.username)) print("\n*****Portfolio*****\n") return model.get_portfolio(cls.username) @classmethod def invalid_selection(cls, funct): user_input = input("Enter 0 to exit. Press any other key to try again.\n") if user_input == '0': cls.user_exit() else: funct() @classmethod def user_exit(cls): print("\nThank you for visiting. Have a good day.") exit(-1) @classmethod def test(cls): df = cls.view_portfolio() print(df[df['symbol'] == 'GOOG']['quantity']) if __name__ == '__main__': Controller.navigate() # Controller.buy() # Controller.tasks() # Controller.buy_stock('AAPL') # print(Controller.view_portfolio()) # Controller.sell() # Controller.test()
7f073591b7025d0e1d72e4c619d071f93be9779a
lmhavrin/python-crash-course
/chapter-seven/movie_tickets.py
491
4.09375
4
# Exercise 7-5: Movie Tickets prompt = "\nWelcome to the movies; What is your age?" prompt += "\nEnter quit when finished." while True: age = input(prompt) if age == "quit": break # break # if statment true loop will stop #if statement false loop will run rest of code age = int(age) if age < 3: print("You're ticket is free.") elif age >= 3 and age <= 12: print("The ticket is $10.") else: print("Your ticket is $15.")
7565f46abf62cc1f1e217d137bc6371c19bcf480
lmhavrin/python-crash-course
/chapter-ten/read_number.py
347
3.59375
4
# Exercise 10-11 Favorite Number CTD import json def read_number(): """Get stored number if available""" try: filename = "favorite_num.json" with open(filename) as f_obj: number = json.load(f_obj) print(number) except FileNotFoundError: print("This file was not found..") read_number()
ec0e546c9a0937008130754b59a79f0d7e58e405
lmhavrin/python-crash-course
/chapter-three/intentional_error.py
130
3.734375
4
# Exercise 3-11: Intentional Error my_list = ["Lauren", "David", "David"] print(my_list[3]) # there is no index 3 in this list
adf06b4c6190e34261f401f24721faff2ecb22e8
lmhavrin/python-crash-course
/chapter-nine/login_attempts.py
1,437
4.03125
4
# Exercise 9-5: Login Attempts class User(): """Making a brief user profile""" def __init__(self, first_name, last_name, gender, age, hometown): self.first_name = first_name self.last_name = last_name self.gender = gender self.age = age self.hometown = hometown self.login_attempts = 0 def describe_user(self): """Summarizes user information""" print("\nUser information for " + self.first_name.title() + " " + self.last_name.title() + " is as follows:") print("\n-" + self.gender.title() + "\n-" + str(self.age) + "\n-" + self.hometown.title()) def greet_user(self): """Prints a personalized greeting to the user""" print("Welcome, " + self.first_name.title() + " " + self.last_name.title() + "!") def increment_login_attempts(self): """Increments login attempts by 1""" self.login_attempts += 1 print("User attempted to login " + str(self.login_attempts) + " time[s].") def reset_login_attempts(self): """Resets login attempts to zero.""" self.login_attempts = 0 print("Login attempt reset to: " + str(self.login_attempts)) user_one = User("lauren", "havrin", "female", 27, "murrysville") user_one.increment_login_attempts() user_one.increment_login_attempts() user_one.increment_login_attempts() user_one.reset_login_attempts() user_one.increment_login_attempts()
5dc67e88fd9e6aff3a243bf3f52bc0390952be18
lmhavrin/python-crash-course
/chapter-seven/rental_car.py
136
3.796875
4
# Exercise 7-1 Rental Car car = input("What type of car would you like?") print("Let me see if I can find you a " + car.title() + ".")
6e684cde8f5f356821dbe73f929b05632e8bc61b
lmhavrin/python-crash-course
/chapter-ten/verify_user.py
1,466
4.09375
4
# Exercise 10-13: Verfiy User import json #Load the username, if it has been stored previously. # Otherwise, prompt for the username and store it. # Refactoring- Breaking up code into a series of functions that have specific jobs def get_stored_username(): """Get stored username if available.""" filename = "username.json" try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): """Prompt for a new username.""" username = input("What is your name?") filename = "username.json" with open(filename, "w") as f_obj: json.dump(username, f_obj) return username def greet_user(): """Greet the user by name.""" username = get_stored_username() if username: question = input("Is " + username + " the correct username? Print yes or no.") if question == "yes": print("Welcome back, " + username + "!") elif question == "no": username = get_new_username() print("We'll rememver you when you come back, " + str(username) + "!") else: print("Please enter yes or no") else: username = get_new_username() print("We'll remember you when you come back, " + str(username) + "!") # I missed this else statement; Was trying to do a loop for user input get_new_username() greet_user()
7cbacc84c82a73b1510646bdcb58bbd37992724c
lmhavrin/python-crash-course
/chapter-eight/user_albums.py
569
4.0625
4
# Exercise 8-8: Albums def make_album(artist, title, tracks=0): album = { "artist": artist.title(), "title": title.title() } if tracks: album["tracks"] = tracks return album while True: artist = input("Enter artists name; Press 'q' to quit ") if artist == "q": break title = input("Enter album title; Press 'q' to quit ") if title == "q": break tracks = input("Enter number of tracks; Press 'q' to quit ") if tracks == "q": break print(make_album(artist, title, tracks))
1ac43c7e43e37fd03241cd9b29d7d37738dd0817
lmhavrin/python-crash-course
/chapter-five/conditional_tests.py
903
3.875
4
# Exercise 5-1: Conditional Tests cat = "pregnant" print("Is cat == 'pregnant'? I predict true.") print(cat == "pregnant") print("\nIs cat == 'not pregnant'? I predict false.") print(cat == "not pregnant") color = "purple" print("\n Is color == 'purple', I predict true:") print(color == 'purple') print("\n Does color = 'blue', I predict false:") print(color == 'blue') print("\n Does color == 'brown', I predict false:") print(color == "brown") print("\n Does color == 'red', I predict false:") print(color == 'red' ) print("\n Does color == 'taupe', I predict false:") print(color == 'taupe') tv_show = "south park" print("\n Does tv show == 'south park'? I predict true:") print(tv_show == "south park") mood = "happy" print("\n Does mood == happy? I predict true:") print(mood == "happy") month = "january" print("\n Does month == january? I predict true:") print(month == "january")
f863b89f876e1848266043ec729b8e0de5008907
lmhavrin/python-crash-course
/chapter-six/favorite_places.py
452
4.09375
4
# Exercise 6-9: Favortie Places favorite_places = { "david": ["netherlands", "romania", "germany"], "lauren": ["bahamas", "chicago"], "bob": ["pennsylvania"] } # EVERYTHING MUST BE IN LIST FORMAT EVEN IF ONE ITEM #INSIDE DICTIONARY for person, places in favorite_places.items(): print(person.title() + " 's favorite places are: ") for place in places: print("\t-" + place.title()) # MUST LOOP in a loop to get values
69d63e236fd5585208ec5bebab45137c260c3562
lmhavrin/python-crash-course
/chapter-seven/deli.py
536
4.4375
4
# Exercise: 7-8 Deli # A for loop is useful for looping through a list # A while loop is useful for looping through a list AND MODIFYING IT sandwich_orders = ["turkey", "roast beef", "chicken", "BLT", "ham"] finished_sandwiches = [] while sandwich_orders: making_sandwich = sandwich_orders.pop() print("I made your " + making_sandwich + " sandwich.") finished_sandwiches.append(making_sandwich) print("\n Here are the list of sandwiches finished: ") for sandwich in finished_sandwiches: print("-" + sandwich.title())
928b6669af9290b2b79f38fd90800525698b44da
lmhavrin/python-crash-course
/chapter-nine/user.py
801
3.71875
4
# 9-12 Multiple Modules class User(): """Making a brief user profile""" def __init__(self, first_name, last_name, gender, age, hometown): self.first_name = first_name.title() self.last_name = last_name.title() self.gender = gender.title() self.age = age self.hometown = hometown.title() def describe_user(self): """Summarizes user information""" print("\nUser information for " + self.first_name.title() + " " + self.last_name.title() + " is as follows:") print("\n-" + self.gender.title() + "\n-" + str(self.age) + "\n-" + self.hometown.title()) def greet_user(self): """Prints a personalized greeting to the user""" print("Welcome, " + self.first_name.title() + " " + self.last_name.title() + "!")
729921c5bff22cfb4e82d496f4ae654b629f5071
lmhavrin/python-crash-course
/chapter-two/famous_quote_two.py
584
3.546875
4
# what should have been done in Exercise 2-5 Famous Quote #print(""" Vince, Lombardi once said, "The difference between a successful person and others #is not a lack of strength, not a lack of knowledge, but rather a lack of will." """) # Exercise 2-6: Famous Quote famous_person = "Vince Lombardi" message = """ "The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack of will." """ # should have put in message variable not quote according to exercise famous_quote = famous_person + " once said," + message print(famous_quote)
cb4880043372a403c524628588983e8a2027cbd7
Anjal17122/Python_Tkinter_Library
/database.py
2,318
3.75
4
import sqlite3 username = 'admin' password = 'admin' PATH = r'C:\Users\User\Desktop\AnjalSaps\projects\pythondjangoprojects\pythontkinterfinalproject\tkinterr\lib_mngmt' def connect(): conn = sqlite3.connect(PATH) return conn def create_table_book(): conn=connect() c=conn.cursor() c.execute('''create table book( ID INTEGER PRIMARY KEY AUTOINCREMENT, BookName TEXT not null unique, Author TEXT, Type TEXT, Quantity INTEGER )''') conn.commit() conn.close() def create_table_student(): conn=connect() c=conn.cursor() c.execute('''create table student( ID integer primary key AUTOINCREMENT, StudentName TEXT, Phoneno TEXT, Class TEXT, Gender TEXT )''') conn.commit() conn.close() def create_table_login(): conn=connect() c=conn.cursor() c.execute('''create table Login( ID integer primary key AUTOINCREMENT, username TEXT, password TEXT )''') conn.commit() conn.close() def create_table_borrow(): conn=connect() c=conn.cursor() c.execute('''create table borrow( ID integer primary key AUTOINCREMENT, bookid INTEGER, studentid INTEGER, takendate TEXT, deadline TEXT, returndate TEXT )''') conn.commit() conn.close() def insert_table_login(): conn = connect() c=conn.cursor() c.execute(f"insert into LOGIN(USERNAME,PASSWORD) values('{username}', '{password}')") conn.commit() conn.close() print(f"Your username is {username} and password is {password}") def getdata(): conn = connect() c = conn.cursor() c.execute(''' select bo.id,b.bookname,b.type,s.studentname, s.class,bo.takendate,bo.deadline from borrow bo inner join book b on bo.bookid = b.id inner join student s on bo.studentid = s.ID where bo.returndate is Null ''') rows = c.fetchall() print(rows) conn.commit() conn.close() create_table_student() create_table_book() create_table_borrow() create_table_login() insert_table_login()
864c84af3931c74fa40eb0d5f3175450abc2dda0
athawley/learnictnow.com
/programming/python/turtle_multiple.py
662
3.828125
4
# Set up the window and its attributes import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") # create tess and set some attributes tess = turtle.Turtle() tess.color("hotpink") tess.pensize(5) # create alex, who is a second turtle object alex = turtle.Turtle() # Let tess draw an equilateral triangle tess.forward(80) tess.left(120) tess.forward(80) tess.left(120) tess.forward(80) tess.left(120) # turn tess around, and move her away from the origin tess.right(180) tess.forward(80) # make alex draw a square alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) alex.forward(50) alex.left(90) wn.exitonclick()
637260eab712b7cca3c5f0f9e058fcd3639ffa96
bqr407/PyIQ
/bubble.py
1,671
4.15625
4
class Bubble(): """Class for bubble objects""" def __init__(self, id, x, y, x2, y2, value): """each bubble object has these values associated with it""" self.x = x self.y = y self.x2 = x2 self.y2 = y2 self.id = id self.value = value def getX(self): """returns x1 of tkinter shape""" return self.x def getY(self): """returns y1 of tkinter shape""" return self.y def getX2(self): """returns x2 pos of tkinter shape""" return self.x2 def getY2(self): """returns y2 of tkinter shape""" return self.y2 def getID(self): """returns unique object identifier""" return self.id def getValue(self): """returns value of the bubble""" return self.value class Choice(): """Class for choice objects""" def __init__(self, id, x, y, x2, y2, value): """each choice object has these values associated with it""" self.x = x self.y = y self.x2 = x2 self.y2 = y2 self.id = id self.value = value def getX(self): """returns x1 of tkinter shape""" return self.x def getY(self): """returns y1 of tkinter shape""" return self.y def getX2(self): """returns x2 pos of tkinter shape""" return self.x2 def getY2(self): """returns y2 of tkinter shape""" return self.y2 def getID(self): """returns unique object identifier""" return self.id def getValue(self): """returns answer the object represents""" return self.value
833bfb2748edd83bf2848768c2fd7f5f75175731
hhxxss0722/double
/PyQt5-Chinese-tutoral-master/test/threadEvent_test.py
980
3.671875
4
# coding:utf-8 import threading import time event = threading.Event() def chihuoguo(name): # 等待事件,进入等待阻塞状态 print('%s 已经启动' % threading.currentThread().getName()) print('小伙伴 %s 已经进入就餐状态!'%name) time.sleep(1) event.wait() # 收到事件后进入运行状态 print('%s 收到通知了.' % threading.currentThread().getName()) print('小伙伴 %s 开始吃咯!'%name) # 设置线程组 threads = [] # 创建新线程 thread1 = threading.Thread(target=chihuoguo, args=("a", )) thread2 = threading.Thread(target=chihuoguo, args=("b", )) print("添加线程") # 添加到线程组 threads.append(thread1) threads.append(thread2) print('添加线程完毕') print(threading.currentThread().getName()) # 开启线程 for thread in threads: thread.start() time.sleep(0.1) # 发送事件通知 print('主线程通知小伙伴开吃咯!') event.set()
66a7ca9ef390456166a01c10d56b3e168e4cc015
rishipandey125/Machine-Learning-Classification
/random_forest.py
4,641
3.65625
4
import decision_tree import random """ Random forest Machine Learning Model by Rishi Pandey. Generates a Random forest Machine Learning Model. Model is trained based off of data loaded as CSV. """ """ Object for a Random Forest ML Model. Contains a forest of decision trees, accuracy of model, and differences between actual and predicted. """ class RFModel: def __init__(self, forest, accuracy, differences): self.forest = forest self.accuracy = accuracy self.differences = differences """ Returns a bagged dataset to generate new decision tree. Bagged dataset must have the same length as the original, but number of features will be randomized. Bagged dataset has the same header as the rest of the data. """ def bagged(data): rand_num_features = random.randint(1,len(data[0])-1) feature_indices = [] while rand_num_features != 0: random_feature_index = random.randint(0,len(data[0])-2) if random_feature_index not in feature_indices: feature_indices.append(random_feature_index) else: continue rand_num_features -= 1 feature_indices.append(len(data[0])-1) bagged_data = [[data[0][i] for i in feature_indices]] #Starting at y = 1 as first entry is the header. for y in range(1,len(data)): index = random.randint(1,len(data)-1) bagged_data.append([data[index][i] for i in feature_indices]) return bagged_data """ Build Random Forest Machine Learning Model based on data passed. Model is created on 60% of the data passed and tested using the other 40% of data it has never seen. acceptedAccuracy parameter specifies the accuracy the model should support. numTrees paramter specifies the depth of the forest. If the model is created with less accuracy than the specificed ammount, it will be scrapped and recreated. """ def buildForest(original_data,acceptedAccuracy,numTrees): differences = [['Actual','Predicted']] data = sorted(original_data[1:], key = lambda x: random.random()) data.insert(0,original_data[0]) training_data = data[:int(.6*len(data))] testing_data = data[int(.6*len(data)):] testing_data.insert(0,data[0]) forest = [decision_tree.buildTree(training_data)] for x in range(numTrees-2): forest.append(decision_tree.buildTree(bagged(training_data))) """ Tests a Random forest Machine Learning Model for Accuracy. Model and Testing Data are passed as parameters. Model is created on 60% of the data passed and tested using the other 40% of data it has never seen. Returns a float of the accuracy (ie: 0.91). """ def model_accuracy(forest,testing_data): count = 0 #loop through testing_data for y in range(1,len(testing_data)): input = {} #loop through features for x in range(len(testing_data[0])-1): input.update({testing_data[0][x]:testing_data[y][x]}) #expected label actual = testing_data[y][len(testing_data[y])-1] predictions = [] # loop through trees in forest for tree in forest: predictions.append(decision_tree.traverseTree(input,tree.node)) distinct_prediction = {} # loop through and aggregate predictions for x in predictions: if not (isinstance(x,dict)): if x not in distinct_prediction: distinct_prediction.update({x:predictions.count(x)}) else: continue else: for i in x: try: val = distinct_prediction[i] + x[i] distinct_prediction.pop(i,None) distinct_prediction.update({i:val}) except KeyError: continue predicted = max(distinct_prediction, key=distinct_prediction.get) differences.append([actual,predicted]) #count accurate prediction if actual == predicted: count += 1 return float(count)/float((len(testing_data)-1)) accuracy = model_accuracy(forest,testing_data) if accuracy < acceptedAccuracy: print("Accuracy Test Failed "+ str(round(accuracy*100,2))+"%" + " Rebuilding...") return buildForest(data,acceptedAccuracy,numTrees) else: print("Passed! Model Built w/ " + str(round(accuracy*100,2)) + "%") forest.append(decision_tree.buildTree(data)) return RFModel(forest,accuracy,differences)
f32de78f226af34b14d0bf5ca4c2356c19da1107
Saf1n/python_algorythm
/HomeWork3/test3_9.py
548
3.78125
4
__author__ = 'Сафин Ильшат' # 9. Найти максимальный элемент среди минимальных элементов столбцов матрицы. print('Введите 12 цифр:') matrix = [[int(input()) for _ in range(4)] for _ in range(3)] for i in range(3): print(matrix[i]) mx = -1 for i in range(3): mn = 10 for j in range(4): if matrix[i][j] < mn: mn = matrix[i][j] if mn > mx: mx = mn print('Максимальный элемент среди минимальных:', mx)
195ee70ab12758814791e0b9d1a3c1e318420d7d
Saf1n/python_algorythm
/HomeWork2/test2_7.py
767
4.0625
4
__author__ = 'Сафин Ильшат' # coding: utf-8 # 7. Написать программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется равенство: # 1+2+...+n = n(n+1)/2, где n – любое натуральное число. # Докажем равенство через отдельное вычисление левой и правой сторон n = int(input('Введите предел вычисления: ')) s = 0 for i in range(1, n+1): s += i m = n * (n + 1) // 2 print('Сумма, вычисленная последовательно:', s) print('Сумма, вычисленная по формуле:', m) print('Равенство!')
6d666cef9d012833d19e3038bf923158aabc9da4
manuelcabral524/Agent0_Grupo5
/Grupo 5 Agent0 A Star Base/Agent0_minotauro/client/example_agent_search_profundidade.py
12,539
3.640625
4
import client import ast import random VISITED_COLOR = "#400000" # Vermelho escuro. FRONTIER_COLOR = "red3" # Vermelho claro. # AUXILIAR class Stack: def __init__(self): self.stack_data = [] def isEmpty(self): if len(self.stack_data) == 0: return True else: return False def pop(self): return self.stack_data.pop(len(self.stack_data) - 1) def insert(self, element): return self.stack_data.append(element) def getStack(self): return self.stack_data def getLength(self): return len(self.stack_data) def __iter__(self): ''' Returns the Iterator object ''' return StackIterator(self) def getValueAtIndex(self, i): return self.stack_data[i] class StackIterator: ''' Iterator class ''' def __init__(self, stack): # Stack object reference self._stack = stack # member variable to keep track of current index self._index = self._stack.getLength() - 1 def __next__(self): ''''Returns the next value from stack object's lists ''' if self._index >= 0: result = (self._stack.getStack()[self._index]) self._index -= 1 return result # End of Iteration raise StopIteration class Queue: def __init__(self): self.queue_data = [] def isEmpty(self): if len(self.queue_data) == 0: return True else: return False def pop(self): return self.queue_data.pop(0) def insert(self,element): return self.queue_data.append(element) def getQueue(self): return self.queue_data def __iter__(self): ''' Returns the Iterator object ''' return QueueIterator(self) class QueueIterator: ''' Iterator class ''' def __init__(self, queue): # Queue object reference self._queue = queue # member variable to keep track of current index self._index = 0 def __next__(self): ''''Returns the next value from queue object's lists ''' if self._index < len(self._queue.getQueue()): result = (self._queue.getQueue()[self._index]) self._index +=1 return result # End of Iteration raise StopIteration # SEARCH AGENT class Node: def __init__(self,state,parent,action,path_cost,level): self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.level = level def getState(self): return self.state def getParent(self): return self.parent def getAction(self): return self.action def getPathCost(self): return self.path_cost def getLevel(self): return self.level class Agent: def __init__(self): self.c = client.Client('127.0.0.1', 50001) self.res = self.c.connect() random.seed() # To become true random, a different seed is used! (clock time) self.visited_nodes = Stack() self.frontier_nodes = Stack() self.weightMap =[] self.goalNodePos =(0,0) self.state = (0,0) self.maxCoord = (0,0) def getConnection(self): return self.res def getGoalPosition(self): msg = self.c.execute("info", "goal") goal = ast.literal_eval(msg) # test print('Goal is located at:', goal) return goal def getSelfPosition(self): msg = self.c.execute("info", "position") pos = ast.literal_eval(msg) # test print('Received agent\'s position:', pos) return pos def getWeightMap(self): msg = self.c.execute("info", "map") w_map = ast.literal_eval(msg) # test print('Received map of weights:', w_map) return w_map def getPatchCost(self,pos): return self.weightMap[pos[0]][pos[1]] def getMaxCoord(self): msg = self.c.execute("info","maxcoord") max_coord =ast.literal_eval(msg) # test print('Received maxcoord', max_coord) return max_coord def getObstacles(self): msg = self.c.execute("info","obstacles") obst =ast.literal_eval(msg) # test print('Received map of obstacles:', obst) return obst # COM MODIFICAÇÕES NO SERVIDOR def getObjectsAt(self, x, y): msg = self.c.execute("info", str(x)+","+str(y)) return ast.literal_eval(msg) # COM MODIFICAÇÕES NO SERVIDOR def isVisitable(self, x, y): return all(obj != "obstacle" and obj != "bomb" for obj in self.getObjectsAt(x,y)) def step(self,pos,action): if action == "east": if pos[0] + 1 < self.maxCoord[0]: new_pos = (pos[0] + 1, pos[1]) else: new_pos =(0,pos[1]) if action == "west": if pos[0] - 1 >= 0: new_pos = (pos[0] - 1, pos[1]) else: new_pos = (self.maxCoord[0] - 1, pos[1]) if action == "south": if pos[1] + 1 < self.maxCoord[1]: new_pos = (pos[0], pos[1] + 1 ) else: new_pos = (pos[0], 0) if action == "north": if pos[1] - 1 >= 0: new_pos = (pos[0], pos[1] - 1) else: new_pos = (pos[0], self.maxCoord[1] - 1 ) return new_pos def getNode(self,parent_node,action,level): state = self.step(parent_node.getState(),action) pathCost = parent_node.getPathCost() + self.getPatchCost(state) return Node(state, parent_node, action, pathCost,level) def printNodes(self,type,nodes,i): print(type," (round ",i," )") print("state | path cost") for node in nodes: print(node.getState(),"|", node.getPathCost()) def printPath(self, node): n = node n_list = [] while n.getPathCost() != 0: n_list.insert(0,[n.getState(), n.getPathCost()]) n = n.getParent() print("Final Path", n_list) def mark_visited(self, node): # self.c.execute("mark_visited", str(node.getState())[1:-1].replace(" ", "")) self.c.execute("mark", str(node.getState())[1:-1].replace(" ", "") + "_" + VISITED_COLOR) def mark_frontier(self, node): # self.c.execute("mark_frontier", str(node.getState())[1:-1].replace(" ", "")) self.c.execute("mark", str(node.getState())[1:-1].replace(" ", "") + "_" + FRONTIER_COLOR) def think(self): # Get the position of the Goal self.goalNodePos = self.getGoalPosition() # Get information of the weights for each step in the world ... self.weightMap = self.getWeightMap() # Get max coordinates self.maxCoord = self.getMaxCoord() # Get the initial position of the agent self.state = self.getSelfPosition() root = Node(self.state, None, "", 0, 0) end = False i = 0 # lista_visitados=[] # nos_fronteira_atual = [] # Lista de obstáculos. obstaculos = [] # Adicionar obstáculos à lista. for column in range(len(self.getObstacles())): for row in range(len(self.getObstacles()[column])): if (self.getObstacles()[column][row] == 1): obstaculos.append((column, row)) # O ciclo while começa com o nó inicial, root. v = root # nivel: profundidade atual. nivel = 0 # limite: profundidade limite. limite = 2000 # Pesquisa em Profundidade. while (end == False): # Incremento da profundidade atual. nivel = nivel + 1 if (nivel > limite): input("Não foi possível atingir o objetivo com esse limite de profundidade.") end = True else: if (self.state == self.goalNodePos): # Visitar o nó. self.visited_nodes.insert(v) # Marcar a vermelho escuro o nó visitado. self.mark_visited(v) end = True else: # Visitar o nó. self.visited_nodes.insert(v) # Marcar a vermelho escuro o nó visitado. self.mark_visited(v) for d in ["north", "east", "south", "west"]: no_fronteira = self.getNode(v, d, nivel) # Regista os nós fronteira se não forem obstáculos, se não foram visitados # e se não estão no Stack dos nós fronteira. if no_fronteira.getState() not in obstaculos: if no_fronteira.getState() not in [n.getState() for n in self.visited_nodes.getStack()]: if no_fronteira.getState() not in [f.getState() for f in self.frontier_nodes.getStack()]: self.frontier_nodes.insert(no_fronteira) # Marca a vermelho claro os nós fronteira. self.mark_frontier(no_fronteira) self.printNodes("Frontier", self.frontier_nodes, i) print("-------------------------------------------") self.printNodes("Visited", self.visited_nodes, i) print("-------------------------------------------") # Lista para guardar valores que são retirados do Stack (self.frontier.nodes) # para depois serem inseridos de volta. stack_values = [] # Percorrer nós fronteira. for w in range(3): w = self.frontier_nodes.pop() # Se a profundidade atual for menor que a profundidade limite # e se o nó ainda não foi visitado, visita-se o nó e retira-se do stack # dos nós fronteira. if w.level <= limite: v = w self.state = v.getState() i += 1 for index in range(len(stack_values)-1, -1, -1): self.frontier_nodes.insert(stack_values[index]) break else: stack_values += w continue self.do(v) input("GOAL FOUND! CONGRATULATIONS") def turn_and_go(self, direction): if direction == "south": left, right, back = "east", "west", "north" elif direction == "north": left, right, back = "west", "east", "south" elif direction == "east": left, right, back = "north", "south", "west" elif direction == "west": left, right, back = "south", "north", "east" if self.getSelfDirection() == back: self.c.execute("command", "right") self.c.execute("command", "right") elif self.getSelfDirection() == right: self.c.execute("command", "left") elif self.getSelfDirection() == left: self.c.execute("command", "right") self.c.execute("command", "forward") def do(self, path): self.c.execute("command", "set_steps") for node in path: coords = node[0] position = self.getSelfPosition() dx, dy = coords[0]-position[0], coords[1]-position[1] if abs(dx) != 1: dx = -dx if abs(dy) != 1: dy = -dy if dy > 0: self.turn_and_go("south") # , "east", "west", "north") elif dy < 0: self.turn_and_go("north") # , "west", "east", "south") elif dx > 0: self.turn_and_go("east") # , "north", "south", "west") else: self.turn_and_go("west") # , "south", "north", "east") input("Waiting for return") def getSelfDirection(self): return self.c.execute("info", "direction") #STARTING THE PROGRAM: def main(): print("Starting client!") ag = Agent() if ag.getConnection() != -1: path = ag.think() if path is not None: ag.do(path) else: print("Goal not found!") main()