blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
3168a8a5b039ff768f950aad457259beb531296d
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Topological_sorting/2_topological_sort_to_find_all_sorts.py
2,942
3.8125
4
''' All topological sorts of a directed acyclic graph ''' ''' In a Directed acyclic graph many a times we can have vertices which are unrelated to each other because of which we can order them in many ways. These various topological sorting is important in many cases, for example if some relative weight is...
4ae850854c829d0b900b3c5633977c0337153ef5
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Construction_and_Conversion/1_construct_tree_from_inorder_and_preorder.py
913
3.90625
4
''' Construct a tree from given inorder and preorder traversals ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None pre_index = 0 def construct_tree(inorder, preorder): global pre_index if pre_index >= len(preorder) or not inorder: ...
a4f0590b8cd3f608b41b68aa5e5711600572507b
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Searching/20_find_fixed_point_in_an_array.py
799
3.890625
4
''' Find a Fixed Point (Value equal to index) in a given array Input: arr[] = {-10, -5, 0, 3, 7} Output: 3 // arr[3] == 3 Input: arr[] = {0, 2, 5, 8, 17} Output: 0 // arr[0] == 0 ''' # Method 1: Linear search def findFixedPt(arr): n = len(arr) for i in range(n): if arr[i] == i: ...
f099962e6c0c11d5ca238e02e758a331e23eb61b
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Linked_Lists/Singly_linked_lists/24_segregate_even_and_odd_node.py
920
3.703125
4
''' Segregate even and odd nodes Input: 17->15->8->12->10->5->4->1->7->6->NULL Output: 8->12->10->4->6->17->15->5->1->7->NULL ''' class Node(object): def __init__(self, val): self.val = val self.next = None class LinkedList(object): def __init__(self): self.head = None...
022a3b00181987d805c246bfbe3427e295b11e3d
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Introductions_and_traversals/10_iterative_depth_first_traversal.py
1,859
3.671875
4
''' Iterative Depth First Traversal ''' from collections import defaultdict class Graph(object): def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def add_edge(self, src, dest): self.graph[src].append(dest) def dfs(self, s): visited = [False] ...
ebcb06ecbda30910c6a7b447c6931d22f6191db1
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Introductions_and_traversals/adjacency_list_representation_of_a_graph.py
1,080
3.953125
4
''' Adjacency list representation of a graph ''' class AdjNode(object): def __init__(self, vertex): self.vertex = vertex self.next = None class Graph(object): def __init__(self, vertices): self.vertices = vertices self.graph = [None] * vertices def add_edge(self, src, de...
2345c415a562c67c231656575b32b2bcfae805d1
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/IMP_10_find_kth_largest_element_with_constant_space.py
1,558
3.640625
4
''' Find kth largest element in BST using constant extra space ''' # Idea is to do reverse Morris Traversal class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def kth_largest_element(root, k): curr = root kLargest = None # Keep cou...
4e612bc6b0425b59d37e9341cd4bc8783a2f2bad
sauravgsh16/DataStructures_Algorithms
/g4g/ALGO/Searching/Coding_Problems/12_max_element_in_array_which_is_increasing_and_then_decreasing.py
1,725
4.15625
4
''' Find the maximum element in an array which is first increasing and then decreasing ''' ''' Eg: arr = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1] Output: 500 Linear Search: We can search for the maximum element and once we come across an element less than max, we break and return max ''' ''' Bi...
2e5160df99e62cbf1ff974a42eaf6b7de3fd42d4
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/10_prac_kth_largest.py
953
3.53125
4
''' Find kth largest element in BST using constant extra space ''' # Idea is to do reverse Morris Traversal class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def kth_largest(root, k): curr = root kth_largest = None count = 0 ...
536926dbe1374a5bfac6d3fd62074cde4a1cab12
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Sorting/14_union_and_intersection.py
1,174
4.125
4
''' Union and Intersection of two sorted arrays Input : arr1[] = {1, 3, 4, 5, 7} arr2[] = {2, 5, 6} Output : Union : {1, 2, 3, 4, 5, 6, 7} Intersection : {3, 5} ''' def union(arr1, arr2): m = len(arr1) n = len(arr2) i = k = 0 result = [] while i < m and k < n: ...
316ce359249231c99fbe511ce0518e2cc4374815
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Summation/20_difference_of_sum_between_even_and_odd_levels.py
1,039
3.984375
4
''' Difference between sums of odd level and even level nodes of a Binary Tree ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # Idea is to do level order traversal def diff_odd_even_levels(root): if not root: return 0 ...
246a9c2ada4bd8ba76fe414801b95d5ce806db03
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Traversals/25_postorder_traversal_without_recursion_or_stacks.py
1,153
4
4
''' Postorder traversal without recusion or stack ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # Idea is keep track of all visited node in a hashmap def postorder_traversal(root): visited = set() current = root # We traves...
7c2a7e429e3582c9faab3b914c166bb88d771d22
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Arrangement_Rearrangement/arrange_double_move_zero.py
922
3.671875
4
# -*- coding: utf-8 -*- ''' Double the first element and move zero to end Given an array of integers of size n. Assume ‘0’ as invalid number and all other as valid number. Convert the array in such a way that if next valid number is same as current number, double its value and replace the next number wit...
f46225921fa8c8c8e6dd90e3f8bd6de69e13d94b
sauravgsh16/DataStructures_Algorithms
/g4g/ALGO/Searching/Coding_Problems/26_find_pair_closest_to_a_number_in_sorted_array.py
523
3.8125
4
''' Given a sorted array and a number x, find pair whose sum is closest to x ''' def find_pair(arr, x): diff = 2**32 i = 0 j = len(arr) - 1 l_idx = r_idx = 0 while i < j: if abs(arr[i] + arr[j] - x) < diff: l_idx = i r_idx = j diff = abs(arr[i] + arr[j]...
a979f3adfaa35373818c61c824a097d82f12093d
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Optimization_Problems/3_subarray_with_least_average.py
842
3.921875
4
''' Find the subarray with least average Given an array arr[] of size n and integer k such that k <= n. Input: arr[] = {3, 7, 90, 20, 10, 50, 40}, k = 3 Output: Subarray between indexes 3 and 5 The subarray {20, 10, 50} has the least average among all subarrays of size 3. Input: arr[] = {3...
4385d59caaa80cc3cba5d0c4250a6496fbed5ab8
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Introductions_and_traversals/12_count_all_possible_paths_between_2_vertices.py
1,289
3.984375
4
''' Count all possible nodes between 2 vertices ''' ''' The problem can be solved using backtracking. i.e. We take a path and start walking it, if it leads to the destination then we count that path and backtrack to take another one. If the path does not lead us to the destination vertex, we discard the...
66113f4bd4eb111fa728de0dd14346105e776256
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/14_check_bst_contains_dead_ends.py
769
3.921875
4
''' Check if BST contains dead ends ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def check_dead_ends(root, minm, maxm): if not root: return False if minm == maxm: return True return check_dead_ends(roo...
7f34ced061a32bc761b4ac18b9119b7167293744
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Queues/Standard_problems/9_zig_zag_tree_traversal.py
1,245
3.984375
4
''' ZigZag Tree Traversal ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def zig_zag_traversal(root): if root is None: return # 2 stacks to traverse, current and next level currentLevel = [] nextLevel = [] ...
b820d08879eecae30d95bcaa221be073f71a22ad
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/RN_7_check_each_internal_node_has_exactly_1_child.py
1,372
4.15625
4
''' Check if each internal node has only one child ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # In Preorder traversal, descendants (or Preorder successors) of every node # appear after the node. In the above example, 20 is the first n...
d1ddfcc6b0ab8165519cafc721950ed20b38e44a
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Introductions_and_traversals/14_shortest_path_from_one_prime_number.py
2,319
3.90625
4
''' Shortest path from one prime number to other by changing 1 digit ''' ''' We generate an adjacency matrix of all prime number to 9999. Then we use BFS to find shortest path ** We use "Sieve of Eratosthenes" to generate the prime numbers ''' from Queue import Queue from collections import defaultdict clas...
8ce6a0a66a022ce44df73660eb4272c450cfce54
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Searching/8_element_that_appears_only_once.py
498
4.09375
4
''' Find the element that appears once in an array where every other element appears twice Input: ar[] = {7, 3, 5, 4, 5, 3, 4} Output: 7 ''' # METHOD 1- nested loops O(n**2) # METHOD 2 - Hashing - Time - O(n), space - O(n) # METHOD 3 - XOR # x ^ x = 0, x ^ 0 = x def find_element(arr): n = len(arr) ...
d082617ceff635f548261ef56e9850746a2131d4
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Summation/23_sum_of_nodes_in_kth_level.py
542
3.65625
4
''' Sum of nodes at k-th level in a tree represented as string ''' # Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" # k = 2 # Output : 14 def get_kth_sum(tree, k): level = -1 kth_sum = 0 for i in range(len(tree)): if tree[i] == '(': level += 1 elif tree[i] ...
6ff26422169c9da2686dd801893e6817e7c3a0b7
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Stacks/Standard_problems_based_on_Stacks/3_prefix_to_postfix.py
1,111
3.75
4
''' Convert prefix to postfix ''' ''' Same as prefix to infix, only difference is as below: # EXPRESSION = OP1 + OP2 + OPERATION ''' class Conversion(object): def __init__(self, exp): self.exp = exp self.stack = [] def push(self, val): self.stack.append(val) def pop(self): ...
c75fd1d87da9c8f51a1277a729919a7e4cfdd1e1
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Traversals/3_inorder_travesal_Morris_traversal.py
1,349
4.03125
4
''' Morris Inorder traversal ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def morris_inorder_traversal(root): current = root while current is not None: if current.left is None: print current.val, ...
9b02dba3732a0bfc1953ff7e8f90254fc4668c68
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/5_are_all_leaf_nodes_in_the_same_level.py
1,286
4.0625
4
''' Check if all leaf nodes are at the same level ''' import sys class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None # ITERATIVE def check_leaf_level(root): if not root: return max_level = sys.maxsize level = 0 q = [] ...
79d8cdc0b6a487daff286ea34fd6cf7ff1fc5dcd
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Construction_and_conversion/6_transform_bst_to_greater_sum_tree.py
1,359
3.9375
4
''' BST to Greater sum Tree ''' ''' Method 2 By leveraging the fact that the tree is a BST, we can find an O(n) solution. The idea is to traverse BST in reverse inorder. Reverse inorder traversal of a BST gives us keys in decreasing order. Before visiting a node, we visit all greater nodes of that node....
41e4afb7333e4659c68eb36b7a3e7a24a85d12e9
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Introductions_and_traversals/RN_28_print_all_paths_from_src_to_dest.py
1,363
3.984375
4
''' Print all paths from src to destination using BFS in a directed graph ''' class Graph(object): def __init__(self, vertices): self.V = vertices self.graph = [[] for _ in range(self.V)] def add_edge(self, src, dest): self.graph[src].append(dest) def find_paths(self, src, dest): ...
4558bfe174752429eea45d6c169ff039b111db73
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Graphs/Graph_Cycles/2_detect_cycle_in_an_undirected_graph.py
1,403
3.890625
4
''' Detect an cycle in an undirected graph ''' ''' We use DFS to detect presense of any cycles. For every vertex 'v', if there is an adjacent vertex 'u' such that, u is already visited, and the parent of 'u' is not 'v', then a cycle exists. ''' from collections import defaultdict class Graph(object): def...
1507e2ab37a5f36e5ba8a20fd41acff2815e9fa8
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/24_symmetric_tree_iterative.py
1,250
4.28125
4
''' Check if the tree is a symmetric tree - Iterative ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def check_symmetric(root): if not root: return True if not root.left and not root.right: return True ...
b5de74c62b53b6a7218dcab4df2eb987745de21a
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Linked_Lists/Circular_Linked_List/3_split_CLL_into_2_halves.py
1,792
3.71875
4
''' Split a circular LL into 2 halves If there are odd number of nodes, then first list should contain one extra ''' class Node(object): def __init__(self, val): self.val = val self.next = None class CircularLL(object): def __init__(self): self.head = None self.size = ...
3c9862d5415ad03833cb22fd14230a5657399434
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Summation/6_diagonal_sum_of_binary_tree.py
1,075
3.984375
4
''' Diagonal sum of binary tree ''' # We use a map. # We use the slope as the key. This mean, every time we travel to left of a # node, a the slope will be incremented. class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def diagonal_sum_util(ro...
85717b8bce1c480cb7527a427aabdb13bf57154f
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/32_inorder_predecessor_and_successor.py
1,258
3.875
4
''' Inorder successor and predecessor ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def find_pre_suc(root, node): if not root: return if root.val == node.val: if root.left is not None: temp = root.l...
06354d4f46de16ca4d0162548992da2fe6061973
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/26_find_middle_of_perfect_binary_tree.py
900
4.15625
4
''' Find middle of a perfect binary tree without finding height ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None ''' Use two pointer slow and fast, like linked list Move fast by 2 leaf nodes, and slow by one. Once fast reaches leaf...
582d1a47e8f7dc69b2eabcb005a9c5d7aed8862d
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Checking_and_Printing/20_check_in_two_trees_are_mirrors.py
804
3.828125
4
''' Check if two trees are mirror ''' ''' two trees 'a' and 'b' are mirrors 1) Their root's key are the same 2) a's left subtree is b's right subtree 3) a's right subtree is b's left subtree ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.r...
8a4e3014c2d00c65b26e88364e7d4eb883b8b2cc
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Linked_Lists/Circular_Linked_List/7_8_CLL_insertion_deletion.py
2,729
3.828125
4
''' Insertion and deletion in a Circular Linked List ''' class Node(object): def __init__(self, val): self.val = val self.next = None class CircularLinkedList(object): def __init__(self): self.last = None def insert_empty(self, val): newNode = Node(val) if not se...
b9b8a14fe496cdd6f06731e3efdbea8dbbe36776
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/23_largest_BST_in_a_binary_tree.py
1,679
3.921875
4
''' Largest BST in a binary tree ''' # We use to property of a binary tree to solve this problem # We traverse the tree in post order fashion and return the following # a. If the tree subtree is true # b. min value of subtree # c. max value of subtree # d. size of the tree class Node(object): def __init_...
70cd26f2c923aafdf17beb56dd31b750e5e43484
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Arrays/Searching/3_pairs_equalling_a_sum.py
387
3.796875
4
''' Given an array A[] and a number x, check for pair in A[] with sum as x ''' def checkPairs(arr, s): n = len(arr) arr.sort() f = 0 l = n - 1 while f < l: curr_sum = arr[f] + arr[l] if curr_sum < s: f += 1 elif curr_sum > s: l -= 1 else: ...
389c20e15726073fa146ac1d1ae391120f1580ec
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Traversals/RN_9_find_inorder_successor.py
1,565
3.921875
4
''' Inorder Successor of a node in Binary Tree ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def leftMostNode(node): while node != None and node.left != None: node = node.left return node def rightMostNode(node): wh...
e980a2f8f33c1d925d49704b4fc12e985436d9fb
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Traversals/RN_4_postorder_from_pre_and_inorder.py
764
3.71875
4
''' Postorder from Preorder and inorder ''' class Node(object): def __init__(self, val): self.val = val self.left = None self.right = None def post_order_traversal(inorder, preorder, n): if preorder[0] in inorder: root = inorder.index(preorder[0]) if root != 0: # Left...
744edcc7660ee7981ef7a28a7b5fdb9a3b3ed361
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Linked_Lists/Singly_linked_lists/singly_linked_list_implementation.py
1,227
3.890625
4
''' Singly Linked List ''' class Node(object): def __init__(self, val): self.val = val self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None self.tail = None self.size = 0 def push(self, val): newNode = Node(val) ...
ba2a36a09d3e8a8e1312743d868ea1e50c157890
sauravgsh16/DataStructures_Algorithms
/g4g/DS/Trees/Binary_Trees/Construction_and_Conversion/INC_4_construct_full_binary_tree_from_preorder_and_postorder.py
1,233
4.03125
4
''' Construct a Full Binary Tree from Preorder and Postorder traversal ''' ''' It is not possible to construct a general Binary Tree from preorder and postorder traversals. But if we know that the binary tree is 'FULL', we can construct the tree with ambiguity. Explanation: preorder = [1, 2, 4, 8, 9...
6929c02961148bf1df559634c102f0fdd55b8413
RabbitRPA/Alex-Husband
/czwicenia.py
975
3.671875
4
""" x = 42 y = 5.2 z = "siema" p = True print(type(x)) print(type(y)) print(type(z)) print(type(p)) """ """ x = int(input("Wprowadż liczbę: ")) if x % 2 == 0: print("Liczba parzysta") else: print("Liczba jest parzyst") """ """ key = 6999 x = int(input()) if key == x: print("Brawo") else: print("b...
0b6ccb7e6755c2e416d5a6efdbe45a4cc00cbf73
HarperHao/python
/mypython/数据库/005.py
362
3.71875
4
"""数据的删除""" import sqlite3 # 创建连接 con = sqlite3.connect(r'K:\SQLite3\first_DB.db') # 创建游标对象 cur = con.cursor() sql = 'delete from t_person where pno=?' try: cur.execute(sql, (2,)) con.commit() print("删除成功") except Exception as e: print(e) print('删除失败') finally: cur.close() con.close()
748bccf48ef30c79bb9312e2d3be2c37c66cf459
HarperHao/python
/mypython/第七章文件实验报告/001.py
1,235
4.28125
4
"""统计指定文件夹大小以及文件和子文件夹数量""" import os.path totalSize = 0 fileNum = 0 dirNum = 0 def visitDir(path): global totalSize global fileNum global dirNum for lists in os.listdir(path): sub_path = os.path.join(path, lists) if os.path.isfile(sub_path): fileNum = fileNum + 1 ...
fad7431c112807657ced8c3775822f454cca6583
HarperHao/python
/exercise/022.py
718
4
4
""" 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13... 求出这个数列的前20项之和。 用三种方法实现 """ def fun1(): mu = 1 zi = 2 sum = zi / mu a = mu b = zi for i in range(19): mu = b zi = a + b a = mu b = zi sum = sum + zi / mu print(sum) def fun2(): fenzi = 2 fenmu = 1 ...
0490c817903bd232fd91fcc0b2b1ed67f4c7e467
HarperHao/python
/mypython/习题/084.py
154
3.71875
4
#84 a=input('输入的字符串是:') if len(a) == len(set(a)): print('输出的结果是: True') else: print('输出的结果是: False')
5cc02d81a0e8a0b7ec41999720f6ccca922ac6dc
HarperHao/python
/exercise/002.py
442
3.796875
4
""" 请编写一个函数fun(),它的功能是:求解一个数各个数据位的平方和, 一个数各数字的平方求和最终得到1或145,返这个数。主函数已经实现结果的输出 """ def fun(number): sum = 0 for i in number: sum = sum + int(i) ** 2 if sum == 1 and sum == 145: return number else: return sum number = input("请输入一个数:") x = fun(number) print(x)
e1975b26d139cb40ed36a5cfaf70d25aca9cf0d2
HarperHao/python
/lesson/lesson001.py
1,879
3.5625
4
""" a/b得到的数是float 而range()中必须为int a={2,2,3} b={2,2} a&b={2} 这是因为集合是无序不重复的 """ # 求两个数的最大公约数(正整数) def commonFactor(num1, num2): result = 1 m = num1 n = num2 if (num1 == 1): print("{}与{}的最大公约数是{}".format(num1, num2, num1)) elif (num2 == 1): print("{}与{}的最大公约数是{}".format(num1, num2, nu...
1bba3dfb0dc0c823c60b32f9dfcd26b3501297cc
HarperHao/python
/exercise/020.py
947
3.90625
4
""" 题目:要求输出国际象棋棋盘。 """ import turtle def fun(): length = 50 switch = 1 turtle.screensize(720, 720) turtle.speed(10) turtle.penup() for i in range(8): for j in range(8): if switch == 1: if j % 2 == 0: color = "black" else:...
45d111d8ca0aa5f608e15378b696fd855a0b31dd
LeRoiFou/codemy_excel
/008_addingDataList.py
1,130
3.640625
4
""" Excel et python Dans ce programme on charge un classeur Excel, on apprend à ajouter une liste de données dans le fichier concerné Éditeur : Laurent REYNAUD Date : 28-01-2021 """ from openpyxl.workbook import workbook # création d'une classeur Excel from openpyxl import load_workbook # chargement d'un...
99df1d6edfab380e18328704f3b5c56938b16a1d
josecoelho96/psd-proj2
/bilinear-interpolation.py
2,423
3.546875
4
#!/usr/bin/env python3 import math def get_number(min, max, name): n = int(input("{} [{}, {}]: ".format(name, min, max))) if n > max or n < min: print("Error! '{}' must be within the given interval.".format(name)) quit() return n def main(): print("Starting bilinear interpolation test...
685f96a9eca4157127ce689a80f1efce577309e8
horken7/movie-credits
/moviecredits/old_main.py
1,059
3.90625
4
import pickle from collections import namedtuple import pprint Actor = namedtuple('Actor', ['name', 'extra']) filename = "movie_dict_lite.pkl" filename2 = "actor_dict_lite.pkl" with open(filename, "rb") as file, open(filename2, "rb") as file2: data = pickle.load(file) data2 = pickle.load(file2) #print(data, ...
6fecf6d2c96d29409c240b76a7a0844668b17594
kalyanitech2021/codingpractice
/string/easy/prgm4.py
701
4.25
4
# Given a String S, reverse the string without reversing its individual words. Words are separated by dots. # Example: # Input: # S = i.like.this.program.very.much # Output: much.very.program.this.like.i # Explanation: After reversing the whole # string(not individual words), the input # string becomes # much...
83b5224314c1eba5d985c0413b69960dc9c26c3a
pavel-malin/new_practices
/new_practice/decorators_practice/abc_decorators_meta.py
654
4.1875
4
''' Using a subclass to extend the signature of its parent's abstract method import abc class BasePizza(object, metaclass=abc.ABCMeta): @abc.abstractmethod def get_ingredients(self): """Returns the ingredient list.""" class Calzone(BasePizza): def get_ingredients(self, with_egg=False): e...
df142d23614bcbf8dd1b16e3f446e681391d4833
riaz/Python_Dumps
/PythonCV/pilBasics/imageRoll.py
453
3.59375
4
#Roling an Image from PIL import Image #Module is to roll an image sideways def roll(image,delta): xsize,ysize = image.size delta = delta * xsize if delta == 0: return image part1 = image.crop((0,0,delta,ysize)) part2 = image.crop((delta,0,xsize,ysize)) image.paste(part2,(0,0,xsize-delta, ys...
e7eaa843f625fe4d5e3e8bff095ff627ee80b114
riaz/Python_Dumps
/Text/string_textwrap.py
381
3.6875
4
#textwrap - fill function import textwrap from textwrap_example import sample_text print 'Raw Text:\n' print sample_text print 'No dedent"\n' #i.e not removing existing indentations in the raw text print textwrap.fill(sample_text,width=8) #preparing dedented text using the textwrap module dedent_text = textwrap.ded...
9216d686ad0deb206998db55005c4e4889c6332f
courtneyng/Intro-To-Python
/If-exercises/If-exercises.py
681
4.125
4
# Program ID: If-exercises # Author: Courtney Ng, Jasmine Li # Period 7 # Program Description: Using if statements months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November'] # months.append('December') ans = input("Enter the name of a month: ") i...
2d1e08e74910d00f238f27b705b7196a35dacdf9
courtneyng/Intro-To-Python
/Tuples_and_Lists/A_List_Of_Numbers.py
1,727
4.28125
4
# Program ID: A_List_Of_Numbers # Author: Courtney Ng # Period: 7 # Program Description: List extensions in Python # numList = [1, 1, 2, 3, 5, 8, 11, 19, 30, 49] # product = 30*8*11*19*30*49 num1 = int(input("Enter the first number.")) numList = [100, 101, 102] numList.append(num1) numList.remove(100) numLi...
b4a981c76af3be316f3b22b2c0d979bd7386e73c
courtneyng/Intro-To-Python
/Tuples_and_Lists/list_extensions.py
797
4.34375
4
# Program ID: lists_extensions # Author: Courtney Ng # Period: 7 # Program Description: List extensions in Python # Given list fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] # The new list extensions test fruits.count('apple') print(fruits.count('apple')) # Added a print stateme...
0a8f90c1a1b12127c00e9add744a145e7d211b9d
mengyujackson121/python_practice
/URLify.py
263
3.515625
4
def main(): a, length= "Mr John Smith ", int(13) new_a = [] for each in a[:length]: if each == ' ': new_a.append('%20') else: new_a.append(each) print (''.join(new_a)) if __name__ == '__main__': main()
523a71bbd11956dd901b920c104a7955368473e0
mathewsjose90/Python-Learnings
/Examples/Practice/first_dupplicate.py
1,388
4
4
''' Arr elements will be between 1 and length of the array. Print the first duplicate character . If no duplicates return -1 ''' import sys arr = [2, 1, 3, 5, 3, 2] def find_first_duplicate(arr): ''' Order of n2 it may take :param arr: :return: ''' start = 0 min_pos_for_duplicate = sys.ma...
e8fd8f9985ee60697c1957364376e32e2a620ef2
mathewsjose90/Python-Learnings
/Examples/Python Learnings/Advanced/Exercise Files/04 Collections/namedtup_start.py
369
3.734375
4
# Demonstrate the usage of namdtuple objects import collections def main(): # TODO: create a Point namedtuple Point=collections.namedtuple("Point",['x','y']) p1=Point(12,33) p2=Point(10,20) print(p1,p2) p1=p1._replace(x=150) print(p1,p2) # TODO: use _replace to create a new instance ...
c0ea704b44a781f0356c14330d25108818fa7a5c
mathewsjose90/Python-Learnings
/Examples/Practice/rev_stack_using_another_stack.py
720
3.703125
4
class Stack: def __init__(self): self.stack = [] def push(self, n): self.stack.append(n) def pop(self): return self.stack.pop() def isEmpty(self): return len(self.stack) == 0 def display(self): return " ".join(map(str, self.stack)) def size(self): ...
3c5edf2088281f13e1e47208835f7f865a0c0fcf
mathewsjose90/Python-Learnings
/Examples/Practice/prime_check_in_squareroot_of_n_time.py
333
3.71875
4
import math def check_prime(n): check_untill = math.sqrt(n) factors = 2 start = 2 while start <= check_untill: if n % start == 0: factors += 1 break start += 1 return True if factors == 2 else False print(check_prime(100)) print(check_prime(99)) print(chec...
84bb1d843031144d73262e48a1b4b8f3b310af7b
mathewsjose90/Python-Learnings
/Examples/Practice/reverse_character_array.py
1,019
3.984375
4
''' Given a array of characters reverse it such that each word remains same .Words are separated by space. Try to do it without any extra space. Ex: ['H','i' ,' ','M','a','t','h','e','w','s',' ','H','e','l','l','o'] ==>['H','e','l','l','o',' ','M','a','t','h','e','w','s',' ','H','i'] ''' arr = ['H', 'i', ' ', 'M', 'a...
c284cc3eadebf95f0ef6c7268f9459e6700e13b5
mathewsjose90/Python-Learnings
/Examples/Practice/min_platform_for_trains.py
640
3.890625
4
''' Min platforms needed for the trains ''' def min_platforms_needed(arrival_times, departure_times): min_platforms = 1 arrival_times.sort() departure_times.sort() i = j = 0 train_count = len(arrival_times) while i < train_count and j < train_count: if arrival_times[i] < departure_time...
cbe042579b3d657114e9df7a96784b04cd8a3a37
mathewsjose90/Python-Learnings
/Examples/Practice/longest_common_subsequence.py
1,673
3.6875
4
def lcs(arr1, arr2, i, j): if i >= len(arr1) or j >= len(arr2): return 0 if arr1[i] == arr2[j]: return 1 + lcs(arr1, arr2, i + 1, j + 1) return max(lcs(arr1, arr2, i + 1, j), lcs(arr1, arr2, i, j + 1)) string1 = "abcdefzbr" string2 = "acdhfxgbn" print(lcs(string1, string2, 0, 0)) # Solut...
7384a57f881283780eafdec9eec221bcd5ee1177
mathewsjose90/Python-Learnings
/Examples/Python Learnings/Advanced/Exercise Files/05 Classes/enums_start.py
817
4
4
# define enumerations using the Enum base class from enum import Enum,unique,auto @unique class Fruit(Enum): Apple=1 Banana=2 Orange=3 SOMETHING=10 SOMETHING_ELSE=auto() def main(): pass # TODO: enums have human-readable values and types print(Fruit.Apple.name,Fruit.Apple.value) p...
74cb62310d19e4c1e3c2b791659680f66e662986
allenai/amti
/amti/utils/validation.py
1,590
3.578125
4
"""Utilities for validating data""" def validate_dict(dict_like, schema): """Return a list of validation error strings. Compare ``dict_like`` to ``schema``, returning a list of strings describing all the validation errors. In particular, validate that ``dict_like`` contains every key specified in ``s...
abe33df45ffb2a997f5bf9f688f1111adebb921b
Reechabhatt/REIT-STOCK-ANALYSIS
/real_estate_investment_trust_analysis_solution.py
7,734
3.765625
4
#!/usr/bin/env python # coding: utf-8 # ## REIT STOCK ANALYSIS # In this project, you will analyze Real Estate Investment Trusts, commonly known as REITs. REITs are companies that own or operate real estate that produces income. REITs, like the stocks of regular public companies, are traded on different stock exchang...
2c78718b09b8ca14261b08d7a1ab966052f87d54
Lukaid/Python_BackEnd
/Python_Advanced/myvenv/class_method_2.py
267
3.859375
4
class math: # 정적 메서드 (static method) # 인스턴스를 만들 필요가 없는 메서드 @staticmethod def add(x, y): return x+y @staticmethod def sub(x, y): return x-y print(math.add(3, 2)) print(math.sub(3, 2))
84312d4139b66751fe9f5ae0f35f5db4390dc6b4
Koppulaamrutha/python-basics-perfectplanb
/list of tuples.py
152
3.9375
4
#sum of list of tuple list = [(1,2), (3,4), (5,6)] res = [sum(x) for x in list] print("the sum are:",res) #output the sum are: [3, 7, 11]
2252906eed1741fb41a4dda12241aa3ef99a93fa
Koppulaamrutha/python-basics-perfectplanb
/sort.py
134
3.515625
4
list1=[0,1,2,10,4,1,0,56,2,0,1,3,0,56,0,4] list1.sort() print(list1) x=list1[0:4] print(x) z=list1+x print(z) y=z[5:] print(y)
bcef00fbacb443c75b8a69a97c56d78924ce4d7d
pouya-mhb/University-Excersises-and-Projects
/Compiler Class/prefix suffix substring proper prefix subsequence/substring of a string.py
454
4.53125
5
#substring of a string stringValue = input("Enter string : ") def substring(stringValue): print("The original string is : " + str(stringValue)) # Get all substrings of string # Using list comprehension + string slicing res = [stringValue[i: j] for i in range(len(stringValue)) for j in range(...
d6cf7a9f246b4e57cc1f748eccfd1d24dc64575a
shiblon/pytour
/3/tutorials/recursion.py
1,988
4.78125
5
# vim:tw=50 """Recursion With an understanding of how to write and call functions, we can now combine the two concepts in a really nifty way called **recursion**. For seasoned programmers, this concept will not be at all new - please feel free to move on. Everyone else: strap in. Python functions, like those in many...
02bb74dc9715d2efa10c4648caa441e5d0fa4fe3
shiblon/pytour
/3/tutorials/what_next.py
14,150
4.5625
5
# vim:tw=50 """What Next? You have covered all of the really necessary basic parts of Python, and that is a lot. Well done! So, what do you do next? Depending on how comforable you are with this material, you may want to go back through the slides one more time, just to cement things in your mind. Of course, another...
97d15e657335a99ebef4173a74934017006a7f2e
shiblon/pytour
/3/tutorials/tracker_histogram.py
1,819
4.0625
4
# vim:tw=50 """Histograms and Dictionaries Suppose we want to know how often the measurement changed in one direction or another. Let's use a dictionary. Dictionaries are good for this because you don't have to know what keys they'll have before you start. With a list, you do (unless you're just appending). We'll ta...
d7771130f1ee54dc2d3924e8266c91c559bf4063
shiblon/pytour
/3/tutorials/hello.py
1,596
4.71875
5
# vim:tw=50 """Hello, Python 3! Welcome to Python version 3, a very fun language to use and learn! Here we have a simple "Hello World!" program. All you have to do is print, and you have output. Try running it now, either by clicking *Run*, or pressing *Shift-Enter*. What happened? This tutorial contains a *Python ...
175cb46d21caa053e7ab4e96702c0547eb68a696
shiblon/pytour
/tutorials/comments.py
826
3.8125
4
# vim:tw=50 """Comments Python ignores **comments**: bits of text that start with |#| and extend to the end of the line. They are strictly for humans to read, and do not affect how your program runs. # This is a comment. Comments are useful for making notes to yourself or others about how the program's code works...
60b0ff336ec48cb60786c47528fa31777ffc8693
shiblon/pytour
/tutorials/urls.py
1,583
4.125
4
# vim:tw=50 """Opening URLs The web is like a huge collection of files, all jamming up the pipes as they fall off the truck. Let's quickly turn our attention there, and learn a little more about file objects while we're at it. Let's use |urllib| (http://docs.python.org/2/library/urllib.html) to open the Google Priva...
6da41cd6a18a01a19ba2c507bbfd015bc91b53a2
piplani/Linked-list-Applications
/rotate.py
1,242
3.984375
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printlist(self): count = 0 temp = self.head while temp: count += 1 print str(temp.data) + '->', ...
c195101159af895a160edbd59174a9e606c22928
amanojeremie/bioinformatics-hw1
/main.py
756
3.9375
4
import sys from translate import translate def main(argv): """ Given a FASTA file, translate from RNA to amino acids Usage: python main.py fasta.txt """ if(len(argv) < 2): print("Translates RNA sequences in a FASTA file into an amino acid sequence") print("Usage: python", argv[0], "fasta.txt") return...
503f1aa74c5d3c2dbd5f5b4e6f97cdbc67aeaa23
abhisek08/Basic-Python-Programs
/problem22.py
1,247
4.4375
4
''' You, the user, will have in your head a number between 0 and 100. The program will guess a number, and you, the user, will say whether it is too high, too low, or your number. At the end of this exchange, your program should print out how many guesses it took to get your number. As the writer of this program, y...
6affb302816e8fcf5015596806c5082fa2d3d30d
abhisek08/Basic-Python-Programs
/problem5.py
1,248
4.25
4
''' Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of diff...
107a32642f0def5ce58017a4d6156bebf1287a1c
abhisek08/Basic-Python-Programs
/problem16.py
1,008
4.34375
4
''' Create a program that will play the “cows and bulls” game with the user. The game works like this: Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wr...
ba3da019b3eeab53a6a9d26ec806f4fd74dc68a7
Cristofer6010/simplest_search_eingen.py
/search_eingen.py
699
3.78125
4
lines = (''' python is very good programing language . it is very popular in all over the world . it is very easy to learn . it is one of the best programing language . more programing languages c , c++ , java , ruby etc .''') beforeLines = lines.split(".") nowLines = lines.split(" ") word = input("Enter what you wa...
c3ce1b3af28b50b9789330c246f2ca92afbf10fd
jpcano1/IBIO2240-tareas
/Tarea 1/functions.py
13,115
4.4375
4
from datetime import datetime as dt ############## import math def circle_radius(radius) -> float: """ 1. Calculates the circle area :param radius: the radius of a circle :return: the circle's area """ return math.pi * (radius**2) ############ def inverted_name(name) -> str: "...
cc0fe65d97a1914cc986b3dd480ff97bd8a53320
wilsouza/RbGomoku
/src/core/utils.py
1,504
4.28125
4
import numpy as np def get_diagonal(table, offset): """ Get diagonal from table Get a list elements referencing the diagonal by offset from main diagonal :param table: matrix to get diagonal :param offset: Offset of the diagonal from the main diagonal. Can ...
7fcce9e91afe5f9ef97a7c5c5338833a0c5954f6
kimte2/PythonTraning
/debugger.py
116
3.5625
4
a = 7 b = 3 def func1(ex1,ex2): e = ex1 + ex2 e += ex1 e *= ex2 return e f = func1(a,b) print f
71a6aac4ab164194fe7f650aacdffaf7630f8c12
Nalipp/cs_concepts
/leet_code/python/linked_lists/easy/merge_linked_lists.py
901
3.96875
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def print_list(self, l): while l: print(l.val) l = l.next def mergeTwoLists(self, l1, l2): l3 = ListNode('x') result = l3 while l1 a...
d4f39fa604a2f320064f1d9823699ee3b319dc8d
Nalipp/cs_concepts
/udemy/python_for_data_structures_algorithms/arrays/is_anagram.py
2,714
3.953125
4
def is_anagram1(str1, str2): str1 = str1.replace(' ', '').lower() str2 = str2.replace(' ', '').lower() return sorted(str1) == sorted(str2) def is_anagram2(str1, str2): str1 = str1.replace(' ', '').lower() str2 = str2.replace(' ', '').lower() if len(str1) != len(str2): return False for i...
cfde47e5bd757b4341503066e5c91e7a8b75c3ca
Nalipp/cs_concepts
/meetups/noisebridge/trees/print_iteration.py
464
3.921875
4
class Node: def __init__(self, v): self.val = v self.c = [] n1 = Node(10) n1.c.append(Node(5)) n1.c.append(Node(7)) n1.c.append(Node(2)) n1.c[0].c.append(Node(12)) n1.c[0].c.append(Node(4)) n1.c[0].c[1].c.append(Node(3)) n1.c[1].c.append(Node(8)) def print_all(node): queue = [node] wh...
346fb50223c7ce09c6e7d01cc115934205edafd4
Nalipp/cs_concepts
/udemy/python_for_data_structures_algorithms/recursion/reverse_convert_str_arr.py
361
3.6875
4
def to_arr(str): if not str: return [] result = [] result = [str[-1]] + to_arr(str[0:-1]) return result print(to_arr('happy')) # def permute(str): # if not str: # return [] # print(permute('abc')) # => ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] # print(permute('dog')) # => ['...
949346b15ef12a9d3d5bc7e7ed4f42b3bc279cca
Nalipp/cs_concepts
/udemy/python_for_data_structures_algorithms/recursion/fibonacci.py
189
4
4
def fibonacci(n): if n == 1: return [1] if n == 2: return [1, 1] results = [n] return results + fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(5))
03de84a1dd9926648e38582a86ad2f4969770c6f
Nalipp/cs_concepts
/leet_code/python/linked_lists/medium/82_remove_duplicates_from_sorted_list.py
1,337
3.953125
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def deleteDuplicates(self, head): if not head: return head cur = ListNode('x') cur.next = head head = cur while cur: cur.next = ...
c9840ed87995991ebbc10efd1577de7575d141ba
joshmarte/GH_Projects
/automate py/Ch 5 Dictionary/Inv.py
779
3.59375
4
#Fantasy Game Inventory stuff = {'rope' : 1, 'torch' : 6, 'gold chain' : 42, 'dagger' : 1, 'arrow' : 12 } def displayInv(inventory): print('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total = item_total + v...
50b483093994fc0586be5452006aee6ccd49e218
joshmarte/GH_Projects
/lpthw/ex19.py
773
3.625
4
# the variables in your function are not are not connected #to the variables in your script def chesse_and_crackers(chesse_count, boxes_of_crackers): print(f"You have {chesse_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man that's enough for a party!") print("Get a...
dbe4baa0d52db437baaa14552c236a22d9c6269e
MLoopz/CodeWars
/fib.py
538
3.640625
4
def solution(string,markers): print(string) print(markers) resp="".join(string) for m in markers: while True: ini=resp.find(m) fin=resp.find("\n",ini) if(ini<0): break if(fin<0): fin=len(resp) resp=resp[:...
68fda720c6474484978b31ff2e1b2d1767cebc01
MLoopz/CodeWars
/validation.py
741
3.96875
4
def valid_parentheses(string): countx=0 county=0 flag=False countres=0 for i in string: if i =="(": countx+=1 if i==")": county+=1 if i==")" and countx>=county: countres+=1 if (countres>=0 and countx == countres and county=...
a67d079d0855521a4e22d1a8d1301c162adb5599
Nithin-Peter-Jesuraj-12/Python
/Matrix Index Finder.py
381
3.90625
4
def find_index(array,element): for line in array: if element in line: i=array.index(line) j=line.index(element) pass indexes=[i,j] return indexes myArray = [ ['banana','jam'], ['mango','apple'] ] index_a = find_index(myArray,'banana') index_b ...