blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7add9be476feb7fef6afc412ac8cb578bd2ca7ff
ganesh-supriya/99-problems
/BinaryTree codes/bst.py
1,293
4.15625
4
class bst: def __init__(self,key): self.key=key self.lchild=None self.rchild=None def insert(self,data): if self.key is None: self.key=data return if self.key>data: #left child part if self.lchild: self.lchild.insert(data) else: self.lchild=bst(data) #creating new obj means creating new node else: if self.rchild: self.rchild.insert(data) else: self.rchild=bst(data) def search(self,data): if self.key==data: #check if node is present or not print("the node is found") return if data<self.key: #search in left sub tree if self.lchild: self.lchild.search(data) else: print("node is not found") else: #search in right sub tree if self.rchild: self.rchild.search(data) else: print("node is not present in tree") root = bst(10) list1=[20,4,2,6,1,8,4,40] for i in list1: root.insert(i) root.search(6) '''print(root.key) print(root.lchild) print(root.rchild)'''
true
caeaafa0a7f081472f6f2341334f1d1d7dcb782a
ganesh-supriya/99-problems
/linked_list code/LinkedList.py
2,962
4.1875
4
class node: def __init__(self,data): self.data=data self.ref=None class linkedlist: def __init__(self): #creating head self.head=None def print_LL(self): if self.head is None: #checking if LL is empty or not...if head is empty,LL is empty. print("linkedlist is empty") else: n=self.head while n is not None: print(n.data,"----->",end="") n=n.ref def node_begin(self,data): #adding node at begining new_node=node(data) new_node.ref=self.head self.head=new_node def node_end(self,data): #adding node at the end new_node=node(data) if self.head is None: self.head=new_node else: n=self.head while n.ref is not None: n = n.ref n.ref=new_node def node_after(self,data,x): n=self.head while n is not None: if x==n.data: break n=n.ref if n is None: print("the node is not present in linked list") else: new_node=node(data) new_node.ref=n.ref n.ref=new_node def node_before(self,data,x): if self.head is None: print("the linked list is empty") return if self.head.data==x: #adding node before 1st node new_node=node(data) new_node.ref=self.head self.head=new_node return n=self.head #adding node at rest position while n.ref is not None: if n.ref.data==x: #x for the data of next node...if value match then we're on previous node break n=n.ref if n.ref is None: print("node is not found") else: #adding node after previous node new_node=node(data) new_node.ref= n.ref n.ref=new_node def delete_by_value(self,x): #deleting node by value if self.head is None: print("we can't delete element because of empty linkedlist") return if x==self.head.data: self.head=self.head.ref return n=self.head while n.ref is not None: if x==n.ref.data: break n=n.ref if n.ref is None: print("node is not present") else: n.ref=n.ref.ref LL1 = linkedlist() LL1.node_begin(10) LL1.node_begin(20) LL1.node_end(100) LL1.node_begin(30) LL1.node_before(50,20) LL1.node_after(60,20) LL1.node_after(1,30) LL1.node_before(5,1) LL1.delete_by_value(1) LL1.print_LL()
true
b65979c60706edbe72b6ec3d097fa6e361cc19b1
anjujames33/projects
/Python/ProgrammingLanguage1/MatrixMultiplication/matrix_multiplication.py
1,680
4.125
4
# Author : Anju K. James # Date : 09-17-2019 # Purpose : Perform matrix multiplication on square matrices # Assumption : Nil # Description : This program multiplies two NxN floating point Matrices. # The memory is allocated dynamically based on the size of matrix. # A random number generator is used to populate the Matrices, import sys import random def main () : # Read the size of squre matrix size = input ( "Enter the size of matrix( 250, 500, 1000, 1500, 2000 ):" ) # Check for size. Exit if it doesnt match the requirement. if size == 250 or size == 500 or size == 1000 or size == 1500 or size == 2000 : # Declare 3 two dimensional matrices. matrix1 = [] matrix2 = [] result = [] # Assign random float values in matrix1 and matrix2 for i in range ( size ) : matrix1.append ( list () ) matrix2.append ( list () ) result.append ( list () ) for j in range ( size ) : matrix1[i].append ( random.random () ) matrix2[i].append ( random.random () ) result[i].append ( 0 ) #print matrix1 #print matrix2 # Matrix multiplication for i in range( size ): for j in range( size ): for k in range( size ): # resulted matrix result[i][j] += matrix1[i][k] * matrix2[k][j] #print result else : print ( "Incorrect size!!. Please enter a value from ( 250, 500, 1000, 1500, 2000 )" ) sys.exit () if __name__ == "__main__" : main ()
true
dcc92398f077251572214fd38f3c857c3b5bffef
jtw10/T2
/ACIT 2515/Lab1B/course.py
1,548
4.34375
4
class Course: """ Represents a course """ def __init__(self, course_id, crn, school, program): """ Constructor for the course object """ self._course_id = course_id self._crn = crn self._school = school self._program = program self._stud_list = [] def add_student(self, stud_id): """ Add student to the course """ if stud_id not in self._stud_list: self._stud_list.append(stud_id) def remove_student(self, stud_id): """ Remove student from the course """ if stud_id in self._stud_list: self._stud_list.remove(stud_id) def check_enrollment(self, stud_id): """ Check if student is enrolled in the course """ if stud_id in self._stud_list: return True else: return False def course_crn(self): """ Returns the course id and its corresponding CRN as a string """ return (self._course_id + ' - ' + str(self._crn)) def course_details(self): """ Returns course details in sentence form """ if self._stud_list == []: return (self._course_id + ' (CRN ' + str(self._crn) + ') ' + 'is a course in the ' + self._program + ' program in the ' + self._school + ' with the following students: None') else: return (self._course_id + ' (CRN ' + str(self._crn) + ') ' + 'is a course in the ' + self._program + ' program in the ' + self._school + ' with the following students: ' + ', '.join(self._stud_list))
true
c0a7098f9ec1390d9148baad7742ce3faabb1c30
kaphys/Variational-Quantum-Monte-Carlo
/Functions/errorcalc.py
2,063
4.21875
4
import numpy as np def data_blocking_error(data, block_size): """ Uses data blocking to compute the error in a given data set. The time series data set is replaced with a block averaged version. It first splits the time series into blocks with a certain blocksize. Then it computes the averages of each of these blocks. If the blocksize is chosen correctly the data will be statistically uncorrelated so the error can be computed in the usual fashion. Parameters ---------- data: Data set of N points block_size: Size of the blocks from the data set Returns: -------- error_data: error of the data variance: Variance of data """ N_blocks = int(len(data)/block_size) blocks = np.array( np.array_split(data, N_blocks)) block_av = np.zeros(N_blocks) for i in range(N_blocks): block_av[i] = np.mean( blocks[i]) error_data = np.sqrt(1/(N_blocks - 1)*(np.mean(block_av**2)- np.mean(block_av)**2 ) ) variance = np.var(data) return (error_data, variance) def bootstrapError(data, N_error): """ Calculates error of a data set with the bootstrap Method. It picks a random set from the data, with this subset the mean is calculated. This is done N_error times, then the standard deviation of this gives the error of the data. # NOTE: This can only be used for non correlated data Parameters ---------- data: Data set of N points N_error Number of times to calculate the mean data from the subset Returns: -------- error_data: error of the data variance: Variance of data """ N_subset = 10000 data_subset = np.random.choice(data, (N_subset, N_error)) average_data_subsets = np.mean(data_subset, axis = 0) var_rdnset = np.var(data_subset, axis = 0) variance = np.mean(var_rdnset) error_var = np.std(var_rdnset) error_data = np.std(average_data_subsets) return (error_data, variance)
true
b20550a59053df1db0863d014ea1d63e331f11a3
xiaohuanlin/Algorithms
/Leetcode/589. N-ary Tree Preorder Traversal.py
813
4.15625
4
''' Given an n-ary tree, return the preorder traversal of its nodes' values. For example, given a 3-ary tree: Return its preorder traversal as: [1,3,5,6,2,4]. Note: Recursive solution is trivial, could you do it iteratively? ''' import unittest # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def preorder(self, root): """ :type root: Node :rtype: List[int] """ if root is None: return [] stack = [root] result = [] while stack: node = stack.pop() for child in node.children[::-1]: stack.append(child) result.append(node.val) return result
true
bd19d9f28b56d6d4aa5618bee154416a081f004a
xiaohuanlin/Algorithms
/Leetcode/493. Reverse Pairs.py
1,418
4.15625
4
''' Given an integer array nums, return the number of reverse pairs in the array. A reverse pair is a pair (i, j) where: 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. Example 1: Input: nums = [1,3,2,3,1] Output: 2 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1 Example 2: Input: nums = [2,4,3,5,1] Output: 3 Explanation: The reverse pairs are: (1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1 (2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1 (3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1 Constraints: 1 <= nums.length <= 5 * 104 -231 <= nums[i] <= 231 - 1 ''' from typing import * import unittest from bisect import bisect_left, insort class Solution: def reversePairs(self, nums: List[int]) -> int: a = [] res = 0 for n in nums[::-1]: index = bisect_left(a, n) res += index insort(a, n * 2) return res class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([1,3,2,3,1],),2), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().reversePairs(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
d2fd765b69e22f8addc158c259af23bb86799f14
xiaohuanlin/Algorithms
/Leetcode/1792. Maximum Average Pass Ratio.py
2,650
4.21875
4
''' There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2 Output: 0.78333 Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. Example 2: Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4 Output: 0.53485 Constraints: 1 <= classes.length <= 105 classes[i].length == 2 1 <= passi <= totali <= 105 1 <= extraStudents <= 105 ''' from typing import * import unittest from heapq import heappush, heappop class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: def calcu(top, bottom): return top/bottom - (top+1)/(bottom+1) heap = [] for top, bottom in classes: heappush(heap, (calcu(top, bottom), top, bottom)) for _ in range(extraStudents): _, top, bottom = heappop(heap) top += 1 bottom += 1 heappush(heap, (calcu(top, bottom), top, bottom)) res = 0 for _, top, bottom in heap: res += top / bottom return res / len(heap) class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([[2,4],[3,9],[4,5],[2,10]],4),0.5348484848484848), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().maxAverageRatio(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
87b96e18dae1b48ffb7d4979121b34037e8c247e
xiaohuanlin/Algorithms
/Leetcode/2580. Count Ways to Group Overlapping Ranges.py
2,368
4.125
4
''' You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith range. You are to split ranges into two (possibly empty) groups such that: Each range belongs to exactly one group. Any two overlapping ranges must belong to the same group. Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges. For example, [1, 3] and [2, 5] are overlapping because 2 and 3 occur in both ranges. Return the total number of ways to split ranges into two groups. Since the answer may be very large, return it modulo 109 + 7. Example 1: Input: ranges = [[6,10],[5,15]] Output: 2 Explanation: The two ranges are overlapping, so they must be in the same group. Thus, there are two possible ways: - Put both the ranges together in group 1. - Put both the ranges together in group 2. Example 2: Input: ranges = [[1,3],[10,20],[2,5],[4,8]] Output: 4 Explanation: Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group. Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. Thus, there are four possible ways to group them: - All the ranges in group 1. - All the ranges in group 2. - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2. - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1. Constraints: 1 <= ranges.length <= 105 ranges[i].length == 2 0 <= starti <= endi <= 109 ''' import unittest from typing import * class Solution: def countWays(self, ranges: List[List[int]]) -> int: ranges.sort() count = 0 prev_end = -1 for start, end in ranges: if start <= prev_end: # overlapping prev_end = max(prev_end, end) else: count += 1 prev_end = end return 2 ** count class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([[1,3],[10,20],[2,5],[4,8]],),4), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().countWays(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
654ae1ae1dbad8b1d8d7a970afafa929dea39777
xiaohuanlin/Algorithms
/Leetcode/2186. Minimum Number of Steps to Make Two Strings Anagram II.py
1,689
4.3125
4
''' You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering. Example 1: Input: s = "leetcode", t = "coats" Output: 7 Explanation: - In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas". - In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede". "leetcodeas" and "coatsleede" are now anagrams of each other. We used a total of 2 + 5 = 7 steps. It can be shown that there is no way to make them anagrams of each other with less than 7 steps. Example 2: Input: s = "night", t = "thing" Output: 0 Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps. Constraints: 1 <= s.length, t.length <= 2 * 105 s and t consist of lowercase English letters. ''' import unittest from typing import * from math import sqrt from collections import Counter class Solution: def minSteps(self, s: str, t: str) -> int: s_c = Counter(s) t_c = Counter(t) return ((s_c | t_c) - (s_c & t_c)).total() class TestSolution(unittest.TestCase): def test_case(self): examples = ( (("night", "thing"), 0), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().minSteps(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
16690b91794daf91206112bca6a0bf2a9d7f76fe
xiaohuanlin/Algorithms
/Leetcode/101. Symmetric Tree.py
1,693
4.375
4
''' Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively. ''' import unittest # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ def pair_match(contray_x, contray_y): if contray_x is None and contray_y is None: # if the pair are both None, we think it is true return True elif contray_x is not None and contray_y is not None: if contray_x.val != contray_y.val: # we need check the value of both return False else: return pair_match(contray_x.left, contray_y.right) and pair_match(contray_x.right, contray_y.left) return False if root is None: return True return pair_match(root.left, root.right) class TestSolution(unittest.TestCase): def test_isSymmetric(self): examples = ( ) for first,second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().isSymmetric(*first), second) unittest.main()
true
111cd79032839a076f62636c7cd24f6f555ef8f7
xiaohuanlin/Algorithms
/Leetcode/344. Reverse String.py
1,024
4.125
4
''' Write a function that takes a string as input and returns the string reversed. Example 1: Input: "hello" Output: "olleh" Example 2: Input: "A man, a plan, a canal: Panama" Output: "amanaP :lanac a ,nalp a ,nam A" ''' import unittest class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ new_str = [] for i in range(len(s)): index = len(s) - 1 - i new_str.append(s[index]) return ''.join(new_str) class TestSolution(unittest.TestCase): def test_reverseString(self): examples = ( ("A man, a plan, a canal: Panama", "amanaP :lanac a ,nalp a ,nam A"), ("hello", "olleh"), ("", "") ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().reverseString(first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
cd6d8b39784e27f1b5501b308da096acc9d4fb4d
xiaohuanlin/Algorithms
/Leetcode/796. Rotate String.py
1,381
4.15625
4
''' We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A. Example 1: Input: A = 'abcde', B = 'cdeab' Output: true Example 2: Input: A = 'abcde', B = 'abced' Output: false Note: A and B will have length at most 100. ''' import unittest class Solution: def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ # if A == '' and B == '': # return True # D_A = A * 2 # for i in range(len(A)): # if D_A[i:i+len(A)] == B: # return True # return False return B in A * 2 if len(A) == len(B) else False class TestSolution(unittest.TestCase): def test_case(self): examples = ( (('abcde', 'cdeab'), True), (('abcde', 'abced'), False), (('', ''), True) ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().rotateString(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
3e89cb0fccd799f3c6260f676cbc441671da5fa4
xiaohuanlin/Algorithms
/Leetcode/110. Balanced Binary Tree.py
1,505
4.21875
4
''' Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of every node never differ by more than 1. Example 1: Given the following tree [3,9,20,null,null,15,7]: 3 / \ 9 20 / \ 15 7 Return true. Example 2: Given the following tree [1,2,2,3,3,null,null,4,4]: 1 / \ 2 2 / \ 3 3 / \ 4 4 Return false. ''' import unittest # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ def get_tree_hight(node): if node == None: return 0 return max(get_tree_hight(node.left), get_tree_hight(node.right)) + 1 if root == None: return True if self.isBalanced(root.left) and self.isBalanced(root.right): return abs(get_tree_hight(root.left)-get_tree_hight(root.right)) <= 1 return False class TestSolution(unittest.TestCase): def test_isBalanced(self): examples = ( ) for first,second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().isBalanced(*first), second) unittest.main()
true
4b30776a73e7a650f392e5bd298730b3e22ae25c
xiaohuanlin/Algorithms
/Leetcode/2008. Maximum Earnings From Taxi.py
2,494
4.28125
4
''' There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip. For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time. Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point. Example 1: Input: n = 5, rides = [[2,5,4],[1,5,1]] Output: 7 Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars. Example 2: Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]] Output: 20 Explanation: We will pick up the following passengers: - Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars. - Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars. - Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars. We earn 9 + 5 + 6 = 20 dollars in total. Constraints: 1 <= n <= 105 1 <= rides.length <= 3 * 104 rides[i].length == 3 1 <= starti < endi <= n 1 <= tipi <= 105 ''' import unittest from typing import * class Solution: def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: rides.sort() dp = [0 for _ in range(n+1)] for i in range(n)[::-1]: dp[i] = dp[i+1] while rides and rides[-1][0] == i: start, end, tip = rides.pop() dp[i] = max(dp[i], dp[end] + end - start + tip) return dp[0] class TestSolution(unittest.TestCase): def test_case(self): examples = ( ((5, [[2,5,4],[1,5,1]],), 7), ((20, [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]), 20), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().maxTaxiEarnings(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
38e81e843d82dfafef198a44d0c4bffd4e0dd470
xiaohuanlin/Algorithms
/Leetcode/2507. Smallest Value After Replacing With Sum of Prime Factors.py
1,506
4.125
4
''' You are given a positive integer n. Continuously replace n with the sum of its prime factors. Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n. Return the smallest value n will take on. Example 1: Input: n = 15 Output: 5 Explanation: Initially, n = 15. 15 = 3 * 5, so replace n with 3 + 5 = 8. 8 = 2 * 2 * 2, so replace n with 2 + 2 + 2 = 6. 6 = 2 * 3, so replace n with 2 + 3 = 5. 5 is the smallest value n will take on. Example 2: Input: n = 3 Output: 3 Explanation: Initially, n = 3. 3 is the smallest value n will take on. Constraints: 2 <= n <= 105 ''' import unittest from typing import * class Solution: def smallestValue(self, n: int) -> int: def factor(num): i = 2 while i * i <= num: if num % i == 0: return factor(num // i) + [i] i += 1 return [num] while True: factor_sum = sum(factor(n)) if factor_sum >= n: return n n = factor_sum class TestSolution(unittest.TestCase): def test_case(self): examples = ( ((15,),5), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().smallestValue(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
15e181d4164502205537db06ce81f81f070232b7
xiaohuanlin/Algorithms
/Leetcode/1419. Minimum Number of Frogs Croaking.py
2,130
4.15625
4
''' You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed. Return the minimum number of different frogs to finish all the croaks in the given string. A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1. Example 1: Input: croakOfFrogs = "croakcroak" Output: 1 Explanation: One frog yelling "croak" twice. Example 2: Input: croakOfFrogs = "crcoakroak" Output: 2 Explanation: The minimum number of frogs is two. The first frog could yell "crcoakroak". The second frog could yell later "crcoakroak". Example 3: Input: croakOfFrogs = "croakcrook" Output: -1 Explanation: The given string is an invalid combination of "croak" from different frogs. Constraints: 1 <= croakOfFrogs.length <= 105 croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'. ''' from typing import * import unittest class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -> int: s = "croak" counts = [0 for _ in range(len(s))] counts[0] = 1 res = 1 for c in croakOfFrogs: if c not in s: return -1 i = s.index(c) counts[i] -= 1 counts[(i+1) % len(s)] += 1 if counts[i] < 0: if i != 0: return -1 else: counts[i] = 0 return counts[0] if counts[0] == sum(counts) else -1 class TestSolution(unittest.TestCase): def test_case(self): examples = ( (("croakcroak",),1), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().minNumberOfFrogs(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
fdc3528846213cad3b77d49cead13fa0283b2353
xiaohuanlin/Algorithms
/Leetcode/1104. Path In Zigzag Labelled Binary Tree.py
1,794
4.15625
4
''' In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label. Example 1: Input: label = 14 Output: [1,3,4,14] Example 2: Input: label = 26 Output: [1,2,6,10,26] Constraints: 1 <= label <= 10^6 ''' from typing import * import unittest class Solution: def pathInZigZagTree(self, label: int) -> List[int]: res = [] # build list last_label_every_row = [] current = 1 while current < 2 * 1e6: last_label_every_row.append(current) current = current * 2 + 1 def find_op(num): if num == 1: return 1 for i in range(len(last_label_every_row)): if last_label_every_row[i] >= num: return last_label_every_row[i] + last_label_every_row[i - 1] + 1 - num return -1 while label != 1: res.append(label) label = find_op(label // 2) res.append(1) return res[::-1] class TestSolution(unittest.TestCase): def test_case(self): examples = ( ((14, ), [1,3,4,14]), ((26, ), [1,2,6,10,26]) ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().pathInZigZagTree(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
080f3559164d897a1dbdfede8b8a0ac9faf264af
xiaohuanlin/Algorithms
/Leetcode/1864. Minimum Number of Swaps to Make the Binary String Alternating.py
2,055
4.28125
4
''' Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Any two characters may be swapped, even if they are not adjacent. Example 1: Input: s = "111000" Output: 1 Explanation: Swap positions 1 and 4: "111000" -> "101010" The string is now alternating. Example 2: Input: s = "010" Output: 0 Explanation: The string is already alternating, no swaps are needed. Example 3: Input: s = "1110" Output: -1 Constraints: 1 <= s.length <= 1000 s[i] is either '0' or '1'. ''' from typing import * import unittest class Solution: def minSwaps(self, s: str) -> int: res_odd = -1 res_even = -1 total_one = 0 # odd count = 0 for i in range(len(s)): if i % 2 == 0: if s[i] != '1': count += 1 if s[i] == '1': total_one += 1 if total_one == (len(s) + 1) // 2: res_odd = count # even count = 0 for i in range(len(s)): if i % 2 == 1: if s[i] != '1': count += 1 if total_one == len(s) // 2: res_even = count if res_odd != -1 and res_even != -1: return min(res_odd, res_even) elif res_odd == -1 and res_even == -1: return -1 elif res_odd != -1: return res_odd return res_even class TestSolution(unittest.TestCase): def test_case(self): examples = ( (("111000",),1), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().minSwaps(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
0c400b7ad20dff9a1b719729e4c14ee283c68f88
xiaohuanlin/Algorithms
/Leetcode/719. Find K-th Smallest Pair Distance.py
1,874
4.125
4
''' The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length. Example 1: Input: nums = [1,3,1], k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0. Example 2: Input: nums = [1,1,1], k = 2 Output: 0 Example 3: Input: nums = [1,6,1], k = 3 Output: 5 Constraints: n == nums.length 2 <= n <= 104 0 <= nums[i] <= 106 1 <= k <= n * (n - 1) / 2 ''' from typing import * import unittest class Solution: def smallestDistancePair(self, nums: List[int], k: int) -> int: nums.sort() def count_dis(dis): left = 0 right = 0 res = 0 while left < len(nums): while right < len(nums) and nums[right] - nums[left] <= dis: right += 1 res += (right - left - 1) left += 1 return res start = 0 end = max(nums) - min(nums) while start < end: middle = start + (end - start) // 2 count = count_dis(middle) if count < k: start = middle + 1 else: end = middle return start class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([1,3,1],1),0), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().smallestDistancePair(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
2a15510470879e11bb4b035f72fd8409a6c018e0
xiaohuanlin/Algorithms
/Leetcode/189. Rotate Array.py
1,979
4.15625
4
''' Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4] Example 2: Input: [-1,-100,3,99] and k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? ''' import unittest class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ length = len(nums) k = k % length if k == 0: return None a, b = 0, k k_list = nums[a:b] max_time = length//k + 1 i = 0 while i <= max_time: if a >= b: # print((a,b), nums, k_list) nums[a:], k_list[:length-a] = k_list[:length-a], nums[a:] # print((a,b), nums, k_list) nums[:b], k_list[length-a:] = k_list[length-a:], nums[:b] # print((a,b), nums, k_list) else: nums[a:b], k_list= k_list, nums[a:b] a,b = (a+k)%length, (b+k)%length i += 1 # return nums class TestSolution(unittest.TestCase): def test_rotate(self): examples = ( (([1,2,3,4,5,6,7], 3), [5,6,7,1,2,3,4]), (([1], 1), [1]), (([1,2], 5), [2,1]), ) for first,second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().rotate(*first), second) unittest.main()
true
433770f40764b1831ee9c385a58fa8e93b338def
xiaohuanlin/Algorithms
/Leetcode/1375. Number of Times Binary String Is Prefix-Aligned.py
2,467
4.1875
4
''' You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step. A binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros. Return the number of times the binary string is prefix-aligned during the flipping process. Example 1: Input: flips = [3,2,4,1,5] Output: 2 Explanation: The binary string is initially "00000". After applying step 1: The string becomes "00100", which is not prefix-aligned. After applying step 2: The string becomes "01100", which is not prefix-aligned. After applying step 3: The string becomes "01110", which is not prefix-aligned. After applying step 4: The string becomes "11110", which is prefix-aligned. After applying step 5: The string becomes "11111", which is prefix-aligned. We can see that the string was prefix-aligned 2 times, so we return 2. Example 2: Input: flips = [4,1,2,3] Output: 1 Explanation: The binary string is initially "0000". After applying step 1: The string becomes "0001", which is not prefix-aligned. After applying step 2: The string becomes "1001", which is not prefix-aligned. After applying step 3: The string becomes "1101", which is not prefix-aligned. After applying step 4: The string becomes "1111", which is prefix-aligned. We can see that the string was prefix-aligned 1 time, so we return 1. Constraints: n == flips.length 1 <= n <= 5 * 104 flips is a permutation of the integers in the range [1, n]. ''' from typing import * import unittest class Solution: def numTimesAllBlue(self, flips: List[int]) -> int: count = 0 right = 0 res = 0 for i in range(len(flips)): right = max(right, flips[i]) count += 1 res += (right == count) return res class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([3,2,4,1,5],),2), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().numTimesAllBlue(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
a91cbb95f983ca0c3af951ca35aec3879fd6a2ed
xiaohuanlin/Algorithms
/Leetcode/554. Brick Wall.py
2,039
4.3125
4
''' There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line. Example 1: Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]] Output: 2 Example 2: Input: wall = [[1],[1],[1]] Output: 3 Constraints: n == wall.length 1 <= n <= 104 1 <= wall[i].length <= 104 1 <= sum(wall[i].length) <= 2 * 104 sum(wall[i]) is the same for each row i. 1 <= wall[i][j] <= 231 - 1 ''' from typing import * from collections import defaultdict import unittest class Solution: def leastBricks(self, wall: List[List[int]]) -> int: counts = defaultdict(int) max_fre = 0 total = sum(wall[0]) for row in wall: start = 0 for brick in row: start += brick if start == total: continue counts[start] += 1 max_fre = max(max_fre, counts[start]) return len(wall) - max_fre class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]],), 2), (([[1],[1],[1]],), 3), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().leastBricks(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
7c02b8df71e76a9528f3dce480d13f501936f66f
xiaohuanlin/Algorithms
/Leetcode/1609. Even Odd Tree.py
2,407
4.28125
4
''' A binary tree is named Even-Odd if it meets the following conditions: The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc. For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right). For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right). Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false. Example 1: Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2] Output: true Explanation: The node values on each level are: Level 0: [1] Level 1: [10,4] Level 2: [3,7,9] Level 3: [12,8,6,2] Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd. Example 2: Input: root = [5,4,2,3,3,7] Output: false Explanation: The node values on each level are: Level 0: [5] Level 1: [4,2] Level 2: [3,3,7] Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd. Example 3: Input: root = [5,9,1,3,5,7] Output: false Explanation: Node values in the level 1 should be even integers. Constraints: The number of nodes in the tree is in the range [1, 105]. 1 <= Node.val <= 106 ''' import unittest from typing import * from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isEvenOddTree(self, root: Optional[TreeNode]) -> bool: q = deque() q.append(root) count = 0 while q: size = len(q) if count % 2 == 0: prev = 0 else: prev = float('+inf') for _ in range(size): node = q.popleft() if node is None: continue if count % 2 == 0: if prev >= node.val or node.val % 2 == 0: return False else: if prev <= node.val or node.val % 2 == 1: return False prev = node.val q.append(node.left) q.append(node.right) count += 1 return True
true
b6133b7cffea04caf51d401b12f94eb6169e1348
xiaohuanlin/Algorithms
/Leetcode/1616. Split Two Strings to Make Palindrome.py
2,791
4.125
4
''' You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome. When you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = "abc", then "" + "abc", "a" + "bc", "ab" + "c" , and "abc" + "" are valid splits. Return true if it is possible to form a palindrome string, otherwise return false. Notice that x + y denotes the concatenation of strings x and y. Example 1: Input: a = "x", b = "y" Output: true Explaination: If either a or b are palindromes the answer is true since you can split in the following way: aprefix = "", asuffix = "x" bprefix = "", bsuffix = "y" Then, aprefix + bsuffix = "" + "y" = "y", which is a palindrome. Example 2: Input: a = "xbdef", b = "xecab" Output: false Example 3: Input: a = "ulacfd", b = "jizalu" Output: true Explaination: Split them at index 3: aprefix = "ula", asuffix = "cfd" bprefix = "jiz", bsuffix = "alu" Then, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome. Constraints: 1 <= a.length, b.length <= 105 a.length == b.length a and b consist of lowercase English letters ''' from typing import * import unittest class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: return self.check(a, b) or self.check(b, a) def check(self, a, b): left = 0 right = len(a) - 1 while left < right: if a[left] != b[right]: return self.checkPalindrome(a, left, right) or self.checkPalindrome(b, left, right) left += 1 right -= 1 return True def checkPalindrome(self, a, a_start, a_end): while a_start < a_end and a[a_start] == a[a_end]: a_start += 1 a_end -= 1 return a_start >= a_end class TestSolution(unittest.TestCase): def test_case(self): examples = ( (('x', 'y'), True), (('xbdef', 'xecab'), False), (('ulacfd', 'jizalu'), True), (('abdef', 'fecab'), True), (('abcdcbf', 'fecabaa'), True), (('pvhmupgqeltozftlmfjjde', 'yjgpzbezspnnpszebzmhvp'), True), (('abmsbz', 'wyzzka'), False), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().checkPalindromeFormation(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
0122f3da1ca59298ee0526420f5cb92f46a1f47a
xiaohuanlin/Algorithms
/Leetcode/809. Expressive Words.py
2,748
4.53125
5
''' Sometimes people repeat letters to represent extra feeling. For example: "hello" -> "heeellooo" "hi" -> "hiiii" In these strings like "heeellooo", we have groups of adjacent letters that are all the same: "h", "eee", "ll", "ooo". You are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more. For example, starting with "hello", we could do an extension on the group "o" to get "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If s = "helllllooo", then the query word "hello" would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s. Return the number of query strings that are stretchy. Example 1: Input: s = "heeellooo", words = ["hello", "hi", "helo"] Output: 1 Explanation: We can extend "e" and "o" in the word "hello" to get "heeellooo". We can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more. Example 2: Input: s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"] Output: 3 ''' from typing import * import unittest class Solution: def expressiveWords(self, s: str, words: List[str]) -> int: res = 0 for word in words: i = 0 j = 0 while i < len(s) or j < len(word): i_start = i while i + 1 < len(s) and s[i] == s[i+1]: i += 1 i_count = i - i_start + 1 j_start = j while j + 1 < len(word) and word[j] == word[j+1]: j += 1 j_count = j - j_start + 1 if (i >= len(s) and j < len(word)) or (i < len(s) and j >= len(word)): break if (s[i] != word[j]) or (i_count < 3 and i_count != j_count) or (i_count >= 3 and i_count < j_count): break i += 1 j += 1 else: res += 1 return res class TestSolution(unittest.TestCase): def test_case(self): examples = ( (("heeellooo", ["hello", "hi", "helo"]), 1), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().expressiveWords(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
b737e7878dc44e6b8821567610ffc2834c539c0f
xiaohuanlin/Algorithms
/Leetcode/2492. Minimum Score of a Path Between Two Cities.py
2,475
4.3125
4
''' You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected. The score of a path between two cities is defined as the minimum distance of a road in this path. Return the minimum possible score of a path between cities 1 and n. Note: A path is a sequence of roads between two cities. It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path. The test cases are generated such that there is at least one path between 1 and n. Example 1: Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]] Output: 5 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5. It can be shown that no other path has less score. Example 2: Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]] Output: 2 Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2. Constraints: 2 <= n <= 105 1 <= roads.length <= 105 roads[i].length == 3 1 <= ai, bi <= n ai != bi 1 <= distancei <= 104 There are no repeated edges. There is at least one path between 1 and n. ''' import unittest from typing import * from collections import deque, defaultdict class Solution: def minScore(self, n: int, roads: List[List[int]]) -> int: graph = defaultdict(list) for u, v, d in roads: graph[u].append((v, d)) graph[v].append((u, d)) visited = set() q = deque([1]) res = float('inf') while q: node = q.popleft() if node in visited: continue visited.add(node) for v, d in graph[node]: q.append(v) res = min(res, d) return res class TestSolution(unittest.TestCase): def test_case(self): examples = ( ((4, [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]), 5), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().minScore(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
c0345be48172a0e53eb4025a7d0415d2cccc0fb0
xiaohuanlin/Algorithms
/Leetcode/2275. Largest Combination With Bitwise AND Greater Than Zero.py
1,947
4.15625
4
''' The bitwise AND of an array nums is the bitwise AND of all integers in nums. For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1. Also, for nums = [7], the bitwise AND is 7. You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination. Return the size of the largest combination of candidates with a bitwise AND greater than 0. Example 1: Input: candidates = [16,17,71,62,12,24,14] Output: 4 Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0. The size of the combination is 4. It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0. Note that more than one combination may have the largest size. For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0. Example 2: Input: candidates = [8,8] Output: 2 Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0. The size of the combination is 2, so we return 2. Constraints: 1 <= candidates.length <= 105 1 <= candidates[i] <= 107 ''' import unittest from typing import * class Solution: def largestCombination(self, candidates: List[int]) -> int: res = 0 for i in range(32): total = 0 for c in candidates: total += ((c >> i) & 1 == 1) res = max(res, total) return res class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([16,17,71,62,12,24,14],),4), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().largestCombination(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
9d2938ef0db9bd2b96c5ab00bd40d8b4a937febe
xiaohuanlin/Algorithms
/Leetcode/1042. Flower Planting With No Adjacent.py
2,198
4.28125
4
''' You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers. All gardens have at most 3 paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. Example 1: Input: n = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Explanation: Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]. Example 2: Input: n = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2] Example 3: Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4] Constraints: 1 <= n <= 104 0 <= paths.length <= 2 * 104 paths[i].length == 2 1 <= xi, yi <= n xi != yi Every garden has at most 3 paths coming into or leaving it. ''' from typing import * import unittest class Solution: def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]: # it always has the result res = [0 for _ in range(n)] graph = [[] for _ in range(n)] for u, v in paths: graph[u-1].append(v-1) graph[v-1].append(u-1) allset = {1, 2, 3, 4} for i in range(n): res[i] = (allset - {res[u] for u in graph[i]}).pop() return res class TestSolution(unittest.TestCase): def test_case(self): examples = ( ((4, [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]), [1,2,3,4]), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().gardenNoAdj(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
8bc48c8ca3c8048b67815f61b4cd6e81d5176ab6
xiaohuanlin/Algorithms
/Leetcode/1550. Three Consecutive Odds.py
1,127
4.25
4
''' Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. Example 1: Input: arr = [2,6,4,1] Output: false Explanation: There are no three consecutive odds. Example 2: Input: arr = [1,2,34,3,4,5,7,23,12] Output: true Explanation: [5,7,23] are three consecutive odds. Constraints: 1 <= arr.length <= 1000 1 <= arr[i] <= 1000 ''' from typing import * import unittest class Solution: def threeConsecutiveOdds(self, arr: List[int]) -> bool: for i in range(len(arr)-2): if arr[i] % 2 == 1 and arr[i+1] % 2 == 1 and arr[i+2] % 2 == 1: return True return False class TestSolution(unittest.TestCase): def test_case(self): examples = ( (([1,2,34,3,4,5,7,23,12],), True), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().threeConsecutiveOdds(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
b8402ec24cc4cec63b446dc42d09a628eca95d79
xiaohuanlin/Algorithms
/Leetcode/2178. Maximum Split of Positive Even Integers.py
2,181
4.3125
4
''' You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order. Example 1: Input: finalSum = 12 Output: [2,4,6] Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8). (2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6]. Note that [2,6,4], [6,2,4], etc. are also accepted. Example 2: Input: finalSum = 7 Output: [] Explanation: There are no valid splits for the given finalSum. Thus, we return an empty array. Example 3: Input: finalSum = 28 Output: [6,8,2,12] Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). (6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12]. Note that [10,2,4,12], [6,2,4,16], etc. are also accepted. Constraints: 1 <= finalSum <= 1010 ''' from typing import * import unittest class Solution: def maximumEvenSplit(self, finalSum: int) -> List[int]: start = 2 res = [] while start <= finalSum: finalSum -= start res.append(start) start += 2 if res: res[-1] += finalSum return res if finalSum % 2 == 0 else [] class TestSolution(unittest.TestCase): def test_case(self): examples = ( ((12,),[2,4,6]), ) for first, second in examples: self.assert_function(first, second) def assert_function(self, first, second): self.assertEqual(Solution().maximumEvenSplit(*first), second, msg="first: {}; second: {}".format(first, second)) unittest.main()
true
972f80394b3677075805cdd01f099085a6c8d004
LucasHenrique-dev/Exercicios-Python
/Desafios/desafio033.py
353
4.15625
4
n1 = int(input('Digite um número: ')) maior = n1 menor = n1 n2 = int(input('Digite outro número: ')) if maior < n2: maior = n2 if menor > n2: menor = n2 n3 = int(input('Digite o outro número: ')) if maior < n3: maior = n3 if menor > n3: menor = n3 print(f'O maior número digitado foi {maior} e o menor número digitado foi {menor}')
false
44cc557975cf9a047927b3afbecd1fbe06932a31
samalpartha/Python_scripting_certification
/module1/Fact.py
521
4.28125
4
ele = int(input("Enter the Number: ")) factorial = 1; if ele < 0: print("Please enter the Number Above 1 and Factorial does not exist for number less than ZERO") elif ele == 0: print("The factorial of the Zero is 1") else: for i in range(ele,1,-1): print(i) factorial = factorial * i print("The factorial of the Element", ele ,"is", factorial) if (ele % 2) == 0: print("The Input Number is EVEN:", ele) else: print("The Input Number is ODD:", ele)
true
69d7195b6eae04d6fc89e6aefec9e74149e5016d
matheusglemos/Python_Udemy
/Métodos e Funções/Expressões Lambda/lambda.py
844
4.4375
4
# Projeto em python 3 referente a aula 36 do Curso python da plataforma Udemy. # Observar que a função 'square' pode ser escrita de 3 formas, uma mais simplificada que a outra. # forma 01 def square(num): result = num**2 return result # forma 02 def square(num): return num**2 # forma 03 def square(num): return num ** 2 # resulrado '4' print(square(2)) # Usando expressões lambda para a mesma função # resultado '9' square = lambda num: num**2 print(square(3)) # Expressão lambda que verifica se o número é par par = lambda x: x % 2 == 0 # resultado 'True' print(par(4)) # Expressão lambda que retorna o primeiro caractere de uma string first = lambda s: s[0] # resultado 'M' print(first('Matheus')) # Expressão lambda que inverte uma string rev = lambda s: s[::-1] # resultado 'suehtam' print(rev('Matheus'))
false
7430755c7b5876b8a6e3d4596c14e0851b86bd13
matheusglemos/Python_Udemy
/Conceitos básicos de estrutura de dados e objetos em Python/Tuplas/tupla.py
616
4.5
4
# Projeto em python 3 referente a aula 18 do Curso python da plataforma Udemy. # Criação de uma tupla se dá pelo uso de '()' e esta estrutura é imutável. # Criando tuplas tupla_01 = (1,2,3,4,5,1,1,1,8) tupla_02 = ('Matheus', 14,5,1997) # Métodos básicos das tuplas # Uso do método 'index' que serve para recuperar o índice do elemento passado como paramêtro # resultado '4' print(tupla_01.index(5)) # resultado '0' print(tupla_02.index('Matheus')) # Uso do método 'count' que serve para contar quantas vezes determinado elemento está se repetindo na tupla # resultado '4' print(tupla_01.count(1))
false
3a153352e09c6464e8e9ddad773ab954b99215e6
rohansamuel/Unix
/Unix/Assignment 6/Hw6.py
1,666
4.25
4
from random import randint def randGenerator(min,max): """Function returns a random number""" return randint(min,max) if __name__ == "__main__": user_name = input("Enter user name: ") #get user name guesses = 7 #initialize guesses to 7 print("You have",guesses,"Guesses only.") #Display total guesses rand = randGenerator(-100,100) #get random number flag = False #set flag false print("You need to guess a number between -100 and 100 inclusive.") #loop till guesses get completed while guesses>0: user_input = int(input("Guess a number: ")) #ask user to guess a number guesses = guesses - 1 #decrement guesses #if guess is correct set flag true and break loop if user_input==rand: flag = True break; #if guess is less than number then print low guess elif user_input<rand: print("low guess\n") #if guess is greater than number then print high guess else: print("high guess\n") #if flag is true congratulate user if flag: print("Congratulations! You have guessed number correctly in", 7 - guesses, "Guesses") else: # if flag is false print sorry print("Sorry:( you failed to guess number correctly in 7 Guesses") print("The Random number was ", rand) # open report.txt in appending mode and write user name and guesses taken with open("report.txt", "a") as myfile: myfile.write(user_name + "\t" + str(7 - guesses) + "\n")
true
2624940b68a79933b50bbde0972ecba4ea393837
Timgill987/cs-module-project-algorithms
/moving_zeroes/moving_zeroes.py
1,215
4.3125
4
''' Input: a List of integers Returns: a List of integers ''' def moving_zeroes(arr): # Your code here #need to be able to change the index of any existing zeros in a given array #need to use a method that can manipulate the index value for list items left = 0 right = len(arr) -1 # last in the array while left <= right: if arr[left] == 0 and arr[right] != 0: #swap if these conditions are met arr[left], arr[right] = arr[right], arr[left] left += 1 #move left marker to right right -= 1#move lright marker to left else: if arr[left] != 0: # Move on and don't swap left += 1#move left marker to right if arr[right] == 0:# Move on and don't swap right -= 1#move right marker to left return arr # if value is equal to 0 # any 0's index is +1 # for i in arr: # if i == 0: # arr.remove(0) # arr.append(0) # return arr if __name__ == '__main__': # Use the main function here to test out your implementation arr = [0, 3, 1, 0, -2] print(f"The resulting of moving_zeroes is: {moving_zeroes(arr)}")
true
efe56d8c7e672412500e59ca0519ec0b5edacdc9
G00376332/52445Python
/begins-with-t.py
318
4.4375
4
#Program 2 that checks if day begins with letter T #Use datetime module import datetime #Check if today's day is Tuesday or Thursday if (datetime.datetime.today().weekday() == 1 or datetime.datetime.today().weekday() == 3): print("Yes - today begins with a T") else: print("No - today does not begin with a T")
true
3eca8bd6e8162632770336ef28ef6fdcd0fede42
shreya28171/udacity_movie_trailer_website
/udacity_movie_trailer_website/media.py
829
4.15625
4
class Movie(): """ This class provides a way to store movie related information """ def __init__(self, title, storyline, time, stars, poster_url, trailer_url): """ This is documentation about the method: self- It is the object or instance being created title- The title of the movie storyline- A short description of what the movie is about time- Duration of a movie stars- Star cast of the movie poster_url- The URL address of a poster of the movie trailer_url- A link to show the trailer of the movie """ self.title = title self.storyline = storyline self.time = time self.stars = stars self.poster_url = poster_url self.trailer_url = trailer_url
true
3c18e95022f63ae06e284f449debdd4cd36ae702
selectxing/LearningNote
/Python/1_基础.py
2,821
4.15625
4
#---数据类型---# #字符串 print('HelloWold' + "Test" + "你好") print("1","2","3") #布尔值 a = True print(a) #空值 a = None print(a) #转义符 print("i'm \'ok\'") print('''1...2...3''') #换行? #浮点除/、整除(地板除)//、取余% print(9 / 3) #3.0 print(9 // 3) #3 print(10 / 3) #3.3333333333333335 print(10 // 3) #3 print(10 % 3) #1 #格式化字符串 print("hello %s, welcome to %s, today is %d" % ("zhang", "china", 20170625)) print("hello {0}, welcome to {1}, today is {2}" .format("zhang", "china", 20170625)) #字符串中的“.”写法? #列表list 关键字[] lista = ["test1","test2","test3"] listb = [] #空列表 print("第一个元素:" + lista[0] + " 最后一个元素:" + lista[len(lista) - 1] + " 最后一个元素的另外一种写法:" + lista[-1]) lista[0] = "test0" lista.append("testadd") #末尾追加元素 lista.insert(1, "test_insert") #某位置插入元素 lista.pop() #删除末尾元素 listb = [11, 22, lista, 33] #二元列表 print(listb) #元组tuple 关键字() #一旦初始化其元素就不能修改,代码安全 tuplea = ("test1","test2","test3") tupleb = () #空tuple tupleb = (11, 22, tuplea, 33) tuplec = (11, 22, lista, 33) lista[-1] = "tuple相对可变" print(tuplec) #---dict和set---# #字典dict 关键字{} 访问元素:字典名[]。判断键key是否存在in。可以修改值value但不可修改键key dictTest = {"tony":80, "jack":92, "lily":99} dictTest.pop("tony") dictTest["lily"] = 75 if "sss" in dictTest: print(dictTest["sss"]) elif "lily" in dictTest: print(dictTest["lily"]) #集合set 关键字set(),需要提供list作为输入集合。交集&,并集| setTestA = set([1,2,3,4]) setTestB = set([2,3,5,7,8]) print(setTestA & setTestB) listTestA = ["A", "B", "C"] tupleTestA = (1,2,3) setTestA = set([1,2,tupleTestA,4]) setTestA.add("TTT") #***重要概念*** #可变对象、不可变对象的概念 #list、dict属于可变对象;string、tuple、set属于不可变对象??? #对于不变对象来说,调用对象自身的任意方法,也不会改变该对象自身的内容。相反,这些方法会创建新的对象并返回 #---流程控制---# #ifelse判断 a = int(input("input first num:")) #input返回为string,所以需要转换为int b = int(input("input second num:")) if a > b: print("result:",a,">",b) elif a == b: print("result:",a,"=",b) else: print("result:",a,"<",b) #for循环 tuplefor = (11, 22, ["test1", "test2"], 44) for tuplei in tuplefor: print(tuplei) #range函数:生成整数序列 sum = 0 listsum = range(101) for listi in listsum: if listi % 2 == 0: continue sum = sum + listi print(sum) #while循环 sum = 100 n = 99 while n > 0: if sum > 1000: break sum = sum + n n = n - 2 print(sum)
false
7e4618e5285c05cd6910c28d0da83e0ceb2f3150
NituAgarwal/codebook
/Array/3.reorder-array/Solution.py
289
4.21875
4
#Reorder elements in arr based on index array def reorder_array(arr,index): for i in range(0,len(arr)): arr[index[i]],arr[i]=arr[i],arr[index[i]] index[index[i]],index[i]=index[i],index[index[i]] print arr print index arr = [10, 11, 12]; index= [1, 0, 2]; reorder_array(arr,index)
false
b564b9e7457b3c3ea4387db983e0ae29158f6312
Resethel/Kattis
/Problems/marswindow/Python3/marswindow.py
287
4.15625
4
# Using Python 3 # https://open.kattis.com/problems/marswindow from math import floor request = int(input()) month = 3 year = 2018 while(year < request): month += 26; year += floor(month / 12) month = month%12 if(year == request): print("yes") else: print("no")
true
c816faed8e94a73cd3e1cb64a47dcc9c52bb5461
KUMARA-733/kumar
/Untitled.py
1,226
4.28125
4
#!/usr/bin/env python # coding: utf-8 # In[39]: class Shape: def name(self, shape): print("Shape: %s" % shape) class Rectangle(Shape): def name(self, shape): print("Child class shape %s" % shape) self.draw() def draw(self): print("Printing rectangle,") self.print_sides() def print_sides(self): print("it has 4 sides") return self class Circle(Shape): def name(self, shape): print("Child class shape %s" % shape) self.draw() def draw(self): print("Printing circle ,") self.print_sides() def print_sides(self): print("it has 0 sides") return self class Square(Shape): def name(self, shape): print("Child class shape %s" % shape) self.draw() def draw(self): print("Printing square ,") self.print_sides() def print_sides(self): print("it has 4 sides") return self x = (int)(input("Enter 1:Rectangle 2:Square 3: Circle")) if x == 1: Shape = Rectangle() Shape.name("Rectangle") elif x == 2: Shape = Square() Shape.name("Square") elif x == 3: Shape = Circle() Shape.name("Circle") # In[ ]:
true
0cd4c1c5dcd30a65c27b2dc751c720930217dced
mtony75/isItEven
/main.py
2,095
4.125
4
#functions def isItEven(): usrNumber = input('Enter a number: ') if type(int(usrNumber)).__name__ == 'int': numberMod = int(usrNumber) % 2 if numberMod == 0: print('Your number is even') elif numberMod == 1: print('Your number is odd') else: print('Not a number') def areTheyDivisible(): print('I am going to ask you for two numbers.') print('Thin I will see if they are divisible') print('') firstNumber = input('Please enter a number: ') secondNumber = input('Please enter a second number: ') try: if type(int(firstNumber)).__name__ == 'int': print('First number is valid.') # else: # print('First number is invalid.') # print('Goodbye') # return except ValueError: print('Error: {} Is an invalid arguement.'.format(firstNumber)) print('Error: {} Is of type {}. '.format(firstNumber, type(firstNumber).__name__)) return try: if type(int(secondNumber)).__name__ =='int': print('Second number is valid.') except ValueError: print('Error: {} Is an invalid arguement.'.format(secondNumber)) print('Error: {} Is of type {}. '.format(secondNumber, type(secondNumber).__name__)) return # else: # print('Second number is invalid.') # print('Goodbye') # return if int(firstNumber) % int(secondNumber) == 0: print('{} is divisible by {}'.format(firstNumber, secondNumber)) return else: print('The numbers are not divisible.') return #main Section print('Welcome to is even.') print('Give me a number and I will tell') print('you if the number is even.') print('') print('Please make a selection') print('1. Is it even') print('2. Is it divisible') print('') usrInput = input('Enter Selection: ') if int(usrInput) == 1: isItEven() elif int(usrInput) == 2: areTheyDivisible() else: print('Not a vaild response. Goodbye!')
true
ce153af7aef5d33a47bd7558f02d14d31cb30eba
DammyDee/Algorithms
/insertionsort.py
256
4.1875
4
def insertion_sort(arr): for i in range(len(arr)): k = i while k > 0 and arr[k - 1] > arr[k]: arr[k - 1], arr[k] = arr[k], arr[k - 1] k = k - 1 array = [3, 2, 0, 9, 5, 3, 1] insertion_sort(array) print(array)
false
d954c638ef00a86fa1feea553c6ed28c6d4b3fe2
algo-1/ciphers
/permutation.py
2,463
4.28125
4
# permutation function def get_permutations(sequence): ''' Enumerate all permutations of a given string sequence (string): an arbitrary string to permute. Assume that it is a non-empty string. ''' # case for 1 letter if len(sequence) == 1: return list(sequence) else: first_letter = sequence[0] #recursive permutation of sequence list_of_permutations = [] #of sequence minus first letter word_without_first_letter = sequence.replace(first_letter, "") #if sequence is a 2 letter word (base case) #permutation list trivial if its just a letter if len(word_without_first_letter) == 1: list_of_permutations.append(word_without_first_letter) else: #permutation of word minus first letter (recursive step) #using its insertion list for the permutation list for i in get_permutations(word_without_first_letter): list_of_permutations.append(i) #list_of_permutations.append(i) #insertion of first letter list_of_insertions = [] for i in list_of_permutations: for j in range(len(sequence)): if j > 0: list_of_insertions.append(i[:j] + first_letter + i[j:]) else: list_of_insertions.append(first_letter + i[j:]) return list_of_insertions if __name__ == '__main__': # tests test1 = "abcd" print("Input:", test1) print("Expected Output:", ["too large"], "n = 24") print("Actual Output:", get_permutations(test1), "n =", len(get_permutations(test1))) test2 = "abcde" print("Input:", test2) print("Expected Output:", ["too large"], "n = 120") print("Actual Output:", get_permutations(test2), "n =", len(get_permutations(test2))) test3 = "b" print("Input:", test3) print("Expected Output:", ["b"], "n = 1") print("Actual Output:", get_permutations(test3), "n =", len(get_permutations(test3))) test4 = "bcd" print("Input:", test4) print("Expected Output:", ["bcd", "cbd", "cdb", "bdc", "dbc", "dcb"], "n = 6") print("Actual Output:", get_permutations(test4), "n =", len(get_permutations(test4))) test5 = "acd" print("Input:", test5) print("Expected Output:", ["acd", "cad", "cda", "adc", "dac", "dca"], "n = 6") print("Actual Output:", get_permutations(test5), "n =", len(get_permutations(test5)))
true
60bb641dfc5fa701368f07b11df62f411f76a191
saketrule/algorithms
/dp/knapsack.py
879
4.125
4
''' Given a list of tuples(w,v) lst, and maximum weight - bag, w - weight v - value of items, knapsack(lst) returns a solution to the Knapsack problem, i.e it returns a list of items which maximize the value within the maximum weight constraint. ''' def knapsack(lst,bag): def get_knapsack(lst,bag,table): if bag<=0: return 0 if str(bag) in table: v,itm = table[str(bag)] return int(v) max_v = 0 max_itm = (-1,-1) for itm in lst: if itm[0] <= bag: temp_v = get_knapsack(lst,bag-itm[0],table) if temp_v + itm[1] > max_v: max_v = temp_v + itm[1] max_itm = itm table[str(bag)] = (max_v,max_itm) return max_v table = {} val = get_knapsack(lst,bag,table) sol = [] while(str(bag) in table and table[str(bag)][0]>0): sol.append(table[str(bag)][1]) bag -= table[str(bag)][1][0] return (val,sol) print(knapsack([(3,5),(2,1)],8))
true
214ee17368cd2a0f02ed403078e6a971c5c759d9
Szubie/Misc
/Euler project/4 - Largest Palindrome.py
2,554
4.25
4
#Could find the max possible number made by two 3-digit numbers being multiplied together #And then count backwards to find the biggest palindrome. From there, is there a way to check whether this palindrome can be made by multiplying two 3-digit numbers together? def isPalindrome(x): """converts the number x into a string""" x=str(x) if len(x)<2: return True if x[0] == x[-1]: return isPalindrome(x[1:-1]) else: return False def two3digit(m): """attempts to divide m by all 3-digit numbers. Return "True" if a sucessful division results in a 3-digit number. False otherwise.""" #This does not work correctly currently. n=999 while n > 99: if m%n == 0: #The above AND BELOW symbols were the wrong way around!!! temp = m/n temp = str(temp) if len(temp) == 3: return True else: n -= 1 else: n-=1 return False def findPalindrome(m): #From max #m=998001 if m <=10000: return "None in range" if isPalindrome(m): #Then need to check to see if this number can be constructed by two 3-digit numbers being multiplied together. if two3digit(m): return m else: m -=1 return findPalindrome(m) else: m -= 1 return findPalindrome(m) #Need some way to stop this: it is recursive forever. def findPalindrome2(m): #iterative approach, to evade max recursion limit. while m >9999: if isPalindrome(m): #Then need to check to see if this number can be constructed by two 3-digit numbers being multiplied together. if two3digit(m): return m else: m = m-1 else: m = m-1 return "None in range" #Not sure why this doesn't work really... def findPalindrome3(): maxPalindrome = 1 for x in range(100, 1000): for y in range(100, 1000): temp = x*y if isPalindrome(temp): if temp>maxPalindrome: maxPalindrome = temp # if x*y<maxPalindrome: # break return maxPalindrome #Remember the concept of: "Nested Loops". This is how you can check every possible answer. #That other question you were stuck on may have been solvable through the use of triple nested loops. #This approach is expensive, but clear-cut and works: yours didn't (not entirely sure why...)
true
596bad3b788d62cff8abd7c491cb44c983e5fd91
Szubie/Misc
/Sudoku_solver/SolverClass.py
2,126
4.3125
4
import Sudoku_board import Sudoku_view import Sudoku_validCheck import Sudoku_main """ A Backtracking program in Python to solve Sudoku problem""" class Sudoku_solver(object): def __init__(self): self def findUnassignedLocation(self,tileList): """This function finds an entry in grid that is still unassigned. Returns Boolean false if it can't find an unassigned item. Otherwise, returns item.""" for item in Sudoku_board.board.tileList(): if item.value()==-1: return item else: return False def isValid(self,tile, num): """Checks whether it will be legal to assign num to the given tile. NOTE: this function doesn't check whether the item is unassigned. Don't call this on already assigned tiles, or it will overwrite them.""" col=Sudoku_board.board.columnList()[tile.col()-1] row=Sudoku_board.board.rowList()[tile.row()-1] square=Sudoku_board.board.squareList()[tile.square()-1] if not (col.valueExists(num) or row.valueExists(num) or square.valueExists(num)): return True else: return False def solveSudoku(self,tileList): """ Takes a partially filled-in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution (non-duplication across rows, columns, and boxes) """ Sudoku_validCheck.validChecker(Sudoku_board.board.tileList()) index=self.findUnassignedLocation(tileList) # If there is no unassigned location, we are done if (self.findUnassignedLocation(tileList)==False): Sudoku_view.view() return True # success! # consider valid digits for num in index.validValues(): if (self.isValid(index,num)): index.setValue(num) if self.solveSudoku(tileList): return True index.setValue(-1) return False # this triggers backtracking solveSudoku=Sudoku_solver()
true
ed2c50f9a30d9278407276a7529e4ff1b173ea19
bibekkakati/Python-Problems
/33-Reverse-Word-Order.py
348
4.21875
4
# Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to # the user the same string, except with the words in backwards order. userInput = input("Write something : ") def reverseSentence(): rev = userInput.split() rev.reverse() return " ".join(rev) print(reverseSentence())
true
21fcc517ea11d3a64808da451d2f2c606fa7ca16
bibekkakati/Python-Problems
/15-Fibonacci.py
664
4.53125
5
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. Take this # opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in # the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the # sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, # 13, …) numbersToGenerate = int(input('How many numbers to generate : ')) a = 0 b = 1 list = [a, b] for i in range(2, numbersToGenerate): c = a + b list.append(c) a = b b = c print(list)
true
85d5d34368cf67402ac72d35ad35194c5f5ac1d9
bibekkakati/Python-Problems
/38-sum-of-array.py
228
4.125
4
# Given an array of integers, find the sum of its elements. from numpy import * import random arr = array(random.sample(range(0,20),5)) total = 0 for num in arr: total += num print("total of array ", arr, " is", total)
true
0378e43415f82125f52f287de66374fedba09de0
EmmanuelArMe/CURSO-PYTHON-CODIGO-FACILITO
/formatos.py
1,200
4.5
4
# -*- coding: utf-8 -*- texto = " este es un curso de Python 3, Python bàsico " #new_string = texto.capitalize() # genera un nuevo string con la primera letra mayuscùla #new_string2 = texto.swapcase() # convierte las letras del string que esten en mayuscùlas a minuscùlas y viceversa new_string = texto.replace("Python", "Java", 1)# El primer parametro el es texto a reemplazar, el segundo es por el cual se va a reemplazar y el tercero es cuantas veces new_string = texto.strip() # quita los espacios que tenga el texto al inicio y al final print(new_string) #print(new_string.isupper()) #print(new_string.islower()) # Los metodos upper y lower son para convertir de mayuscùla a minuscùla #El metodo title genera un formato de titulo, es decir, Si el titulo es hola mundo lo genera como Hola Mundo Curso = "Python" version = 3 #resultado = "Este es el curso de %s %s" %(Curso, version) # lo que realiza es ingresar cada variable en su lugar resultado = "Este es el curso de {a} {b}".format(a = Curso, b = version)#la ventaja de cambiarte el nombre a las variables #es que no importa el orden en que las coloque en el format van a tomar el valor donde se desee colocar print(resultado)
false
54c40570052d29924ceea8d2754cd7a937d3602b
saenuruki/Codility
/Iterations/binaryGap.py
1,938
4.125
4
#A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. # #For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps. # #Write a function: # #def solution(N) # #that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. # #For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps. # #Write an efficient algorithm for the following assumptions: # #N is an integer within the range [1..2,147,483,647]. # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") import math def solution(N): # write your code in Python 3.6 # Nを2進数に変換する # 2進数の1と1の間の0の数をカウントする -> countに格納する # 最終的なcountをresultに格納する # return result binaryN = int(format(N, 'b')) result = 0 count = 0 flag = 0 while binaryN != 0: target = binaryN % 10 binaryN = math.floor(binaryN / 10) if target == 1: flag = 1 if count >= result: result = count count = 0 elif target == 0: if flag == 1: count = count + 1 return result
true
e6d1e01c0cdf2d20d8bfe6fbdf84c089eaa10dc2
qingyuanhz1/core-problem-set-recursion
/part-1.py
753
4.125
4
# There are comments with the names of # the required functions to build. # Please paste your solution underneath # the appropriate comment. # factorial def factorial(num): if num < 0: raise ValueError("Number must be greater than zero") elif num <= 1: return 1 return num * factorial(num -1) # reverse def reverse(text): if len(text) <= 1: return text return reverse(text[1:]) + text[0] # bunny def bunny(count): if count < 1: return 0 return 2 + bunny(count -1) # is_nested_parens def is_nested_parens(parens): if len(parens) == 0: return True elif parens[0] + parens[-1] == "()": return is_nested_parens(parens[1:-1]) else: return False
true
f1347dc560902f2eca023b9bf557cff8abb4d9dc
eneajorgji/Python_programmig_Book
/8.2_average_1.py
317
4.15625
4
def average_number(): n = int(input("How many numbers do you have? ")) total = 0.0 for i in range(n): x = float(input("Enter a number: ")) total += x average = round(total / n, 2) print("\nThe average of the number is", average) if __name__ == '__main__': average_number()
true
dc978c7279bbf1508014872f66a39e406401fd79
kevinlee075/MIT-Python-course-Midterm-Problem4
/MIT-Python-course-Midterm-problem4.py
823
4.46875
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 4 16:21:34 2021 @author: Lenovo """ #Implement a function that meets the specifications below. #For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]] def deep_reverse(L): """ assumes L is a list of lists whose elements are ints Mutates L such that it reverses its elements and also reverses the order of the int elements in every element of L. It does not return anything. """ L.reverse() #mutate L to the one whose all elements are in a reversed order for i in range(len(L)): #shift the order of sub-elements in every element of L using for loop L[i].reverse()
true
606d2a55a8375dbd78cba4bace63c3f4c6fb89b8
jesgogu27/holbertonschool-higher_level_programming
/0x06-python-classes/100-singly_linked_list.py
2,147
4.21875
4
#!/usr/bin/python3 """This module contains a class that defines a square. In the Square class we initialize each object by the __init__ method with a private instance variable called __size that takes the size variable's value passed as argument. Also checks if the size arg has a valid value. """ class Node(): """Node Class.""" def __init__(self, data, next_node=None): """Initialization of Node Class""" self.data = data self.next_node = next_node @property def data(self): """Data""" return self.__data @data.setter def data(self, DataValue): """Set data""" if type(DataValue) != int: raise TypeError("data must be an integer") self.__data = DataValue @property def next_node(self): """Node""" return self.__next_node @next_node.setter def next_node(self, NodeValue): """set Node""" if NodeValue is not None and not isinstance(NodeValue, Node): raise TypeError("next_node must be a Node object") self.__next_node = NodeValue class SinglyLinkedList(): """Class SinglyLinkedList""" def __init__(self): """Initialization of SinglyLinkedList""" self.__head = None def sorted_insert(self, DataValue): """Inserts a nodes""" NewNode = Node(DataValue) if self.__head is None: self.__head = NewNode return if DataValue < self.__head.data: NewNode.next_node = self.__head self.__head = NewNode return actual = self.__head while DataValue >= actual.data: prev = actual if actual.next_node: actual = actual.next_node else: actual.next_node = NewNode return prev.next_node = NewNode NewNode.next_node = actual def __str__(self): """Class As a String""" strg = "" actual = self.__head while actual: strg += str(actual.data) + "\n" actual = actual.next_node return strg[:-1]
true
a61f5c16022809504695072689df814d7b80a51c
bommulr/Python-Practice
/oddoreven.py
210
4.28125
4
## Function to find the given number is odd or even ## def oddoreven(num): if num%2 == 0: print(f'Given number {num} is even') else: print(f'Given number {num} is odd') oddoreven(9)
true
ba767f13e11d03975630d20d3ec9df5a3e5494fd
xiaominone/MachineAlgorithm
/language_basement/language_while_input.py
1,526
4.15625
4
#学习while 以及交互式操作 input() #while 用于列表的修改  列表之间的移动 #for 列表之间的遍历 #input()将内容打印到屏幕,作为提示内容 并且接受用户输入作为变量内容 message = input('hello, wellcome here , yes or no ?'); print('\t your answer is '+ message); #当输入提示内容较多时,使用 += 将提示内容定义一个变量 message_1 = 'if you want to be who ?, please you can' message_1 += '\nkeep to think ,and your answer is yes or no ? ' while True: answer = input(message_1); if answer == 'yes': print('\tyour answer is ' + answer); else: break; #while 用于修改列表 字典 for更多用于遍历,不用于修改 #列表之间移动元素 adress = []; stayed = ['bei jing','shang hai','xia men','xia men','xia men','xia men'] print(stayed) while stayed: stay = stayed.pop() adress.append(stay) print(adress) #删除列表元素 remove() 删除第一个指定元素 不能删除全部特定元素 也可以使用set转换 while 'xia men' in adress: adress.remove('xia men') print(adress); #用于用户不断添加元素到列表、字典 sense = {} flag = True while flag: #存储信息 name = input('your name: ') sense1 = input('love is what? ') #添加到字典 sense[name] = sense1 #判断是否结束 message_1 = 'do you wang to continue , ' message_1 += 'input your answer(yes/no) ? ' ans = input(message_1.title()); if ans == 'no': flag = False; else: continue; print(sense)
false
850a7be9fd0577c0c88131ce6fa79322347054f7
Ninamma/Project-Euler
/problem1.py
388
4.46875
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def sumMultiples(x): nums = range(3,x) sum = 0 for i in nums: if i%3 == 0 or i%5 ==0: sum+= i return sum print sumMultiples(10) print sumMultiples(1000)
true
4cb17d5719b8c6a1c0f26c76bbeb5d4e5431ee3e
ganesh1729ganesh/Algos_task1
/task1_1A.py
2,663
4.28125
4
lenBin= int(input("Enter the length of your binary string: "))#24 bytes #length of the input binary string binStr = input("Enter the binary string that you want to decompose: ") #The binary string the user wants to decompose """ The int() function converts the binary string into base 2 number that is a binary number , it takes two arguments first is the required argument and the second is to which base since we want a binary string base 2 is provided """ decVal = int(binStr,2) decVal = decVal * 2 #24 Bytes """ let S be the main string we want to decompose, so doubling the decimal value of the binary string and finding possible order pairs and finally converting them to binary strings is the core idea. S = (s1 + s2)/2 2S = S1 + S2 """ i = 0 #24 bytes j = 0 #24 bytes for i in range (0, decVal+1): #iterating over the range from 0 to decimal value of the binary string for j in range(0,decVal - i +1 ): #iterating over the complementary values in making sum equals to decimal value of the binary string if i+j == decVal : i = bin(i)[2: ] j= bin(j)[2: ] #print(i,j) len_i = len(str(i)) len_j = len(str(j)) if lenBin == len_i and lenBin == len_j :#comparing the lengths to make sure that all are of same lengths as of original string if i < j:#to make sure that in the order pairs first value is less than 2nd value print(i + " " + j) elif len_i <= lenBin or len_j <= lenBin : x = lenBin - len_i y = lenBin - len_j if len_i <=lenBin: if i < j: #print("0"+i) c = len(str(x*'0'+i)) d = len(str(j)) if c == d: print(x*'0'+i + " " + j) elif len_j <= lenBin: if i < j: #print("0"+j) a = len(str(y*'0' + j)) b = len(str(i)) if a == b: print(i + " " + y*'0'+ j) """ Time complexicity: let the complexity of all the statements is c1 since there are two for loops for each loop the statement is executed n times in inner loop and each inner loop is iterated another n times the total complexity is O(n^2) or BigO(n^2) Space complexicity: The space complexity is a no. of int variables * 24 bytes that is c* 24 = O(1) , constant"""
true
92bef3060cc1f5f314298e53354e4f3bcfdc023a
FarhatJ/python
/isIPv4Address.py
1,255
4.25
4
''' An IP address is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. There are two versions of the Internet protocol, and thus two versions of addresses. One of them is the IPv4 address. Given a string, find out if it satisfies the IPv4 address naming rules. Example • For inputString = "172.16.254.1", the output should be isIPv4Address(inputString) = true; • For inputString = "172.316.254.1", the output should be isIPv4Address(inputString) = false. 316 is not in range [0, 255]. • For inputString = ".254.255.0", the output should be isIPv4Address(inputString) = false. There is no first number. ''' def isIPv4Address(inputString): char_list= inputString.split('.') if(len(char_list) !=4): return False for i in char_list: if(len(i) > 1 and i[0] == '0'): return False elif i.isdigit() and 0 <= int(i) <= 255: continue else: return False return True if __name__ == "__main__": print(isIPv4Address("172.16.254.1")) print(isIPv4Address(".16.254.1")) print(isIPv4Address("00.16.254.1")) print(isIPv4Address("172.16.01.1"))
true
ecc62c4047a5aaaf808efbedc884fb7393a7fa0f
FarhatJ/python
/reverseInParanthesis.py
1,096
4.25
4
''' Write a function that reverses characters in (possibly nested) parentheses in the input string. Input strings will always be well-formed with matching ()s. • For inputString = "(bar)", the output should be reverseInParentheses(inputString) = "rab"; • For inputString = "foo(bar)baz", the output should be reverseInParentheses(inputString) = "foorabbaz"; • For inputString = "foo(bar)baz(blim)", the output should be reverseInParentheses(inputString) = "foorabbazmilb"; • For inputString = "foo(bar(baz))blim", the output should be reverseInParentheses(inputString) = "foobazrabblim". Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim". ''' def reverseInParentheses(inputString): char = list(inputString) open_branket = [] for i,c in enumerate(char): if c == '(': open_branket.append(i) elif c == ')': j = open_branket.pop() char[j:i] = char[i:j:-1] return ''.join(c for c in char if c not in'()') if __name__ == "__main__": print(reverseInParentheses("foo(bar)baz"))
true
652a1d288595e921b6b5eb7629a40fa4cd9527b0
jfbamorim/100dayspython
/daytwelve/daytwelve.py
1,413
4.1875
4
################################################################ # Day 12 - Beginner - Number Guessing Game ################################################################ from random import randint from daytwelve.number_guessing_art import logo EASY_LEVEL_TURNS = 10 HARD_LEVEL_TURNS = 5 def start_game(input_attempts, input_surprise_nr): """Starts the game with the number of attempts""" end_game = False while input_attempts > 0 and not end_game: print(f"You have {input_attempts} remaining to guess the number.") guessed_nr = int(input("Make a guess:")) if guessed_nr == input_surprise_nr: print(f"You got it! The answer was {input_surprise_nr}") end_game = True elif guessed_nr < input_surprise_nr: print(f"Too low.") else: print(f"Too high.") input_attempts -= 1 if input_attempts > 0: print("Guess again") else: print("You've run out of guesses, you lose.") # Main program attempts = 0 print(logo) print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100.") surprise_nr = randint(1, 100) difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ").lower() if difficulty == 'easy': attempts = EASY_LEVEL_TURNS elif difficulty == 'hard': attempts = HARD_LEVEL_TURNS start_game(attempts, surprise_nr)
true
7062e1cfd2212e5dbaec9ae2e2de60ddc071c611
jfbamorim/100dayspython
/dayfour/dayfour.py
2,537
4.15625
4
######################################################## # Day 4 - Beginner - Random & Python lists # Banker Roulette Exercise - Who will pay the bill? ######################################################## #import random # 🚨 Don't change the code below 👇 #test_seed = int(input("Create a seed number: ")) #random.seed(test_seed) # Split string method #namesAsCSV = input("Give me everybody's names, seperated by a comma. ") #names = namesAsCSV.split(", ") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #bill_taker = random.randint(0, len(names)-1) #name = names[bill_taker] #print(f"{name} is going to buy the meal today!") ######################################################## # Treasure Map ######################################################## # 🚨 Don't change the code below 👇 #row1 = ["⬜️","⬜️","⬜️"] #row2 = ["⬜️","⬜️","⬜️"] #row3 = ["⬜️","⬜️","⬜️"] #map = [row1, row2, row3] #print(f"{row1}\n{row2}\n{row3}") #position = input("Where do you want to put the treasure? ") # 🚨 Don't change the code above 👆 #Write your code below this row 👇 #first_position = round(int(position)/10) - 1 #second_position = round(int(position) % 10) - 1 #map[second_position][first_position] = 'x' #Write your code above this row 👆 # 🚨 Don't change the code below 👇 #print(f"{row1}\n{row2}\n{row3}") ######################################################## # Final day project ######################################################## import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' print("Lets play Rock, Paper, Scissors") shot = int(input("What do you choose? Type 0 for rock, 1 for paper and 2 for scissors:\n")) if shot == 0: print("Your choice:\n" + rock) elif shot == 1: print("Your choice:\n" + paper) else: print("Your choice:\n" + scissors) pc_shot = random.randint(0, 2) if pc_shot == 0: print("PC choice:\n" + rock) elif pc_shot == 1: print("PC choice:\n" + paper) else: print("PC choice:\n" + scissors) if pc_shot == shot: print("Tied game") else: if (pc_shot == 0 and shot == 1) or (pc_shot == 1 and shot == 2) or (pc_shot == 2 and shot == 0): print("You win") else: print("You lose")
true
23fb53ba4114bf6d8efba37efd86d9bb5f7a7831
jfbamorim/100dayspython
/daytwo/daytwo.py
1,280
4.21875
4
################################################################ # Day 2 - Beginner - Understanding data types ################################################################ #My solution print("Welcome to the tip calculator") bill = float(input("What was the total bill? $")) tip = int(input("How much tip would you like to give? 10, 12, or 15? ")) people = int(input("How many people to split the bill?")) bill = float(bill) * ((1/float(tip)) + 1) total_person = round(float(bill) / int(people), 2) print(f"Each person should pay: {total_person}") # Teacher solution #If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 #Round the result to 2 decimal places = 33.60 #print("Welcome to the tip calculator!") #bill = float(input("What was the total bill? $")) #tip = int(input("How much tip would you like to give? 10, 12, or 15? ")) #people = int(input("How many people to split the bill?")) #long form #tip_as_percent = tip / 100 #total_tip_amount = bill * tip_as_percent #total_bill = bill + total_tip_amount #bill_per_person = total_bill / people #final_amount = round(bill_per_person, 2) #short form #final_amount = round(bill * (1 + tip / 100) / people, 2) #print(f"Each person should pay: ${final_amount}")
true
2fa23b950c560669d993d6f4fa90dd555e8740f4
JeanExtreme002/CSES-Problem-Set-Solutions
/Introductory Problems/repetitions.py
541
4.125
4
string = input() max_length = 0 current_char, current_length = string[0], 0 for char in string: # Se o caractere for o mesmo do anterior, o comprimento # da substring atual é aumentado em 1. current_length += 1 if char == current_char else 0 if max_length < current_length: max_length = current_length # Se o caractere for diferente do anterior, o comprimento # da substring atual é resetado para 1. if char != current_char: current_char = char current_length = 1 print(max_length)
false
c6cc9372db88b20df7beea7bd601912c3d678164
meFargot/gu-algorithms-py
/lesson_2/task_2.py
1,390
4.1875
4
# 2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, то у него 3 # четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). def count_even(number): """ Рекурсивно считаем количество четных цифр в числе """ if number // 10 == 0: # базовый случай if number % 2 == 0: return 1 else: return 0 else: if (number % 10) % 2 == 0: count = 1 + count_even(number // 10) else: count = 0 + count_even(number // 10) return count def count_odd(number): """ Рекурсивно считаем количество нечетных цифр в числе """ if number // 10 == 0: # базовый случай if number % 2 == 1: return 1 else: return 0 else: if (number % 10) % 2 == 1: count = 1 + count_odd(number // 10) else: count = 0 + count_odd(number // 10) return count num = int(input('Введите натуральное число: ')) evens = count_even(num) odds = count_odd(num) print(f'Четных цифр: {evens}\nНЕчетных цифр: {odds}')
false
5bf01c06d9e8345ca6d14ec96e8fc90ccb370b7a
meFargot/gu-algorithms-py
/lesson_3/task_2.py
842
4.15625
4
# 2. Во втором массиве сохранить индексы четных элементов первого массива. # Например, если дан массив со значениями 8, 3, 15, 6, 4, 2, # то во второй массив надо заполнить значениями 1, 4, 5, 6 (или 0, 3, 4, 5 - если индексация начинается с нуля), # т.к. именно в этих позициях первого массива стоят четные числа. import random SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 100 first_array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] second_array = [] for index, element in enumerate(first_array): if element % 2 == 0: second_array.append(index) print(first_array) print(second_array)
false
9483a5a182f0b05afd7c839c01b19ddb85ac4a58
vdesire2641/python-for-programming
/pyc27.py
281
4.25
4
# write a function to complete the volume of sphere with a radius of r. # use r as the parameter to the function. use pi from the math module # PE 2.3 import math def vol(r): volumeOfsphere = 4/3 * math.pi * r * r * r print("volume of sphere is", volumeOfsphere) vol(6)
true
df02539d651a565072f01923edec75ad86a4c60e
JunZhang0629/interview_code
/link_list/reverse_link_node.py
1,382
4.15625
4
''' 实现链表的逆序,共有三种方法 1:就地逆序 初始化三个变量,记录 前驱结点、当前节点、后继节点 的位置,让当前节点的指针从原来指向后继节点改为指向前驱结点实现逆序。 2:递归逆序 先逆序除第一个结点以外的子链表,接着把节点添加到逆序的子链表的后面 3:插入法 ''' class link_node: def __init__(self): self.data = 0 self.next = None def RecursiveReverse(head): if head is None or head.next is None: return head else: newhead = RecursiveReverse(head.next) head.next.next = head head.next = None return newhead def reverse(head): if head is None: return first_node = head.next newnode = RecursiveReverse(first_node) head.next = newnode return newnode if __name__ == "__main__": i = 1 head = link_node() head.next = None tmp = None ptr = head while i<8: tmp = link_node() tmp.data = i tmp.next = None ptr.next = tmp ptr = tmp i += 1 print("逆序前:") ptr = head.next while ptr != None: print(ptr.data) ptr = ptr.next print("\n逆序后:") newnode=reverse(head) ptr = head.next while ptr != None: print(ptr.data) ptr = ptr.next
false
5ee5601ae391b7bc64818b263a9061a4e202d5c8
savourylie/projectEuler
/015_LatticePaths.py
1,050
4.21875
4
import random def countPaths(gridSize): """ (int) -> int Return the number of unique paths of a gridSize * gridSize lattice. >>> countPaths(2) 6 """ # 1. Create a array of paths paths = [] # 2. Randomly create paths with given restrictions i = 0 while ((i < len(paths) * len(paths)) | (len(paths) < 6)): # print [i, len(paths)] path = [] x = 0 y = 0 while (x + y <= 2 * gridSize): path.append((x, y)) if ((random.randint(0, 1) == 0) & (x < gridSize)): x = x + 1 elif (y < gridSize): y = y + 1 else: x = x + 1 # 3. Add path to the array if it's not already in it if (path not in paths): paths.append(path) i = i + 1 # 4. Terminate the path finding when tried iterations 10 times more than the length of the array. print "Awesome!" print len(paths) return len(paths)
true
860bf38a0f522d3331f1271096c83e5b0e750a35
beastieGer/Python
/Foxford 8-10 class/lesson5_task4.py
503
4.3125
4
"""Трехзначные числа Квадрат трехзначного числа оканчивается тремя цифрами, равными этому числу. Найдите и выведите все такие числа в порядке возрастания. В поле для записи ответа нужно ввести все эти числа через пробел. """ for i in range(100, 1000): number = (i ** 2) % 1000 if number == i: print(i)
false
7ef65dd003645638e160b65845f9cc87025b64cd
beastieGer/Python
/Foxford 8-10 class/lesson3_task5.py
711
4.15625
4
"""ФИО Напишите программу, которая преобразует строку, содержащую имя, отчество и фамилию человека, к форме <фамилия> <инициалы> Входные данные Входная строка содержит имя, отчество и фамилию, разделённые одиночными пробелами. Выходные данные Программа должна вывести в одной строке сначала фамилию, а потом (через пробел) – инициалы. """ name, middle_name, family = input().split() print(family, name[0]+'.', middle_name[0]+'.')
false
94b70eae7d0270b0796da7fa41efd33c82e81df9
djkool/OcempGUI3
/doc/examples/draw_triangle.py
900
4.3125
4
# Draw.draw_triangle () usage example. import pygame, pygame.locals from ocempgui.draw import Draw # Initialize the drawing window. pygame.init () screen = pygame.display.set_mode ((200, 200)) screen.fill ((250, 250, 250)) pygame.display.set_caption ('Draw.draw_triangle ()') # Draw three triangles. Draw.draw_triangle (screen, (255, 0, 0), (20, 5), (5, 30), (35, 30), 0) Draw.draw_triangle (screen, (0, 255, 0), (25, 5), (40, 30), (55, 5), 0) Draw.draw_triangle (screen, (0, 0, 255), (60, 5), (45, 30), (75, 30), 0) # Draw a 'tunnel effect' of triangles. for i in range (30): val = i + 3 color = (val * 4, val * 7, val * 5) Draw.draw_triangle (screen, color, (5 + 2 * val, 50 + val), (195 - 2 * val, 50 + val), (100, 195 - 2 * val), 1) # Show anything. pygame.display.flip () # Wait for input. while not pygame.event.get ([pygame.locals.QUIT]): pass
true
a212968085603aa8750ffaa10e682b5f537783cb
lf2a/Python_Exemplos
/zip.py
785
4.40625
4
'''Esta função retorna uma lista de tuplas, onde a i-ésima tupla contém o i-ésimo elemento de cada um dos argumentos. ex: input: zip([1, 2], [3, 4]) output: (1, 3) (2, 4) ''' import itertools print('# 0') for i in zip([1, 2, 3]): print(i) print('\n# 1') for i in zip([1, 2, 3], ['A', 'B', 'C']): print(i) print('\n# 2') for i in zip([1, 2, 3], ['A', 'B', 'C'], ['#', '$', '%']): print(i) print('\n# 3') for i in zip([1, 2, 3], ['A', 'B']): print(i) print('\n# 4') for i in itertools.zip_longest([1, 2, 3], ['A', 'B']): print(i) print('\n# 5') values = zip([1, 2, 3], ['A', 'B']) a, b = zip(*values) print(a, b) print('\n# 6') values_zl = itertools.zip_longest([1, 2, 3], ['A', 'B']) a, b = zip(*values_zl) print(a, b)
false
4ba2c5cb9b8e1dafc9aac135865f0c84375ef036
sdan/python-deanza
/unitE/test.py
498
4.125
4
import random secretNum = random.randint(1,100) print("Welcome to the guessing game.") print("You need to guess a number from 1 to 100.") guess=0 counter=0 while (guess != secretNum): guess = int(input("What is your guess: ")) counter+=1 if(guess < secretNum): print('Guess is too low.') elif(guess > secretNum): print('Guess is too high.') else: print("Congratulations!") print('You guessed the secret number in',counter,'guesses!')
true
e891ceee8f6de2a1bbc9642878f713a999a7e543
weydaej/GeneratePhonebook
/generate_phonebook.py
1,940
4.15625
4
import random def generate_phonebook(): # open three external files for reading # you can access each line of the file via its associated variable female_file = open('names.female', "r") male_file = open('names.male') family_file = open ('names.family') # create some empty lists of female, male & surnames female_list = [] male_list = [] family_list = [] # add the names from the files to each list for line in female_file: fname = line.rstrip() female_list = female_list + [fname] for line in male_file: mname = line.rstrip() male_list = male_list + [mname] for line in family_file: aname = line.rstrip() family_list = family_list + [aname] # files should be closed when you're finished with them female_file.close() male_file.close() family_file.close() # now open a file to write the results to # if the file doesn't already exist, it is created out = open("phonebook.txt", "w") # randomly choose a surname # once used, remove it from the surname list while len(family_list): surname = family_list[random.randrange(len(family_list))] family_list.remove(surname) # randomly 50% should be male, 50% female # once gender is decided, randomly pick a male or female name if random.randrange(1) == 1: index = random.randrange(len(male_list)) first_name = male_list[index] else: index = random.randrange(len(female_list)) first_name = female_list[index] print (first_name + " " + surname + " : ", end="", file=out) # randomly generate a phone number for n in range(1,10) : print (random.randrange(start=1, stop=10), end="", file=out) print ("\n", end='', file=out) out.close() if __name__ == "__main__": generate_phonebook()
true
de1d13de3b63f9dc0f846c31b82db62e2def6542
carola92/Python
/pythonProjects/section3/StringMethod.py
1,591
4.34375
4
""" len() and str() practice: 1.create a variable and assign it the string "Python" 2.create another variable and assign it the length of the string assigned to the variable in step 1 3.create a variable and use string slicing and len() to assign it the length of the slice "yth" from the string assigned to the variable from step 1 4.create a variable and assign it the float 1.32 5.create a variable and assign it the string "2" from the float assigned to the variable from the last problem (use the str() string method for this) """ # type your code for "len() and str() practice" below this single line comment and above the one below it -------------- # assigns pyLen the length of the string assigned to the variable py pyLen = ​len​(py) sliceLen = ​len​(py[​1​:​4​]) num = ​1.32 # uses str() to change 1.32 to "1.32" where index 3 of "1.32" is "2" stringed = ​str​(num)[​3​] # ---------------------------------------------------------------------------------------------------------------------- """ .upper() and .lower() practice: 1.create a variable and assign it the string "upper" changed to "UPPER" using .upper() 2.create a variable and assign it the string "owe" from "LOWER" using string slicing and .lower() """ # type your code for ".upper() and .lower() practice" below this single line comment and above the one below it -------- upCase = ​"upper"​.upper() loSlice = ​"LOWER"​[​1​:​4​].lower() # ----------------------------------------------------------------------------------------------------------------------
true
2d87910429e63aa4fe1a3de15c0c3a847f2f914c
carola92/Python
/pythonProjects/section8/WhileLoops.py
1,490
4.46875
4
""" 1.While Loop Basics a.create a while loop that prints out a string 5 times (should not use a break statement) b.create a while loop that appends 1, 2, and 3 to an empty string and prints that string c.print the list you created in step 1.b. 2.while/else and break statements a.create a while loop that does the same thing as the the while loop you created in step 1.a. but uses a break statement to end the loop instead of what was used in step 1.a. b.use the input function to make the user of the program guess your favorite fruit c.create a while/else loop that continues to prompt the user to guess what your favorite fruit is until they guess correctly (use the input function for this.) The else should be triggered when the user correctly guesses your favorite fruit. When the else is triggered, it should output a message saying that the user has correctly guessed your favorite fruit. """ counter = 10 while counter <15: print(+1) counter += 1 #______________________ append = 1 emp_list = [] while append < 4: emp_list.append(append) append += 1 print(emp_list) #______________________ counter = 20 while True: print("true") counter -= 2 if counter < 10: break #_________________________ fruit = input ("What is my favourite fruit?") while fruit != "Strawberry": print (fruit + " is not my favourite!") fruit = input ("What is my favourite fruit?") else: print("That is Correct, " + fruit + " is my favourite fruit!")
true
c92c69e6c9e10345b89f9f2104d755ea49118814
popescuaaa/Computer-Architecture
/labs/lab no #1 2017/skel/task2.py
1,387
4.375
4
""" Task 2 Read all the content of a text file into a string and show some info about it. Objectives: - use documentation!!! - basic work with files - variable declarations - string operations """ # Let's use the __main__ ! Put all your code inside it! # Open the file with the name 'fisier_input' # Read all the content in a single string # Let's play with that string! # - count the number of words # - make it uppercase # - count occurances of parantheses, other characters or the word 'Python' # - print the last 10 characters # - bonus - whatever you find interesting (e.g. use some regular expressions # to parse it) # Use methods, declare and assign variables # All changes should be made on a copy of the string # Hint for strings: https://docs.python.org/2/library/string.html#string-functions # Hint for files: https://docs.python.org/2/library/io.html#text-i-o # & Operatii cu fisiere section from the lab import io def main(): FILE_NAME = "fisier_input" f = open(FILE_NAME, "r") content = "" # lines are entites in file so: for line in f: print line content += line # print the number of chars in file counter = 0 for char in content: counter += 1 print "\t\n============================\n" print "Number of chars in file: %s" % counter if __name__ == '__main__': main()
true
ff45db96bea58216fd59217d243851303bea14ef
popescuaaa/Computer-Architecture
/labs/lab no #2/task2.py
2,676
4.3125
4
""" Create and run more than 1000 threads that work together. They share a list, input_list, and an integer variable. When they run, they each select one random item from the input list, that was not previously selected, and add it to that variable. When they finish, all elements in the list should have been selected. Make the critical section(s) as short as possible. Requirements: * the length of the input list is equal to the number of threads * the threads have a random delay when running (see time.sleep), before accessing the input_list, in the order of 10-100ms * before starting the threads compute the sum of the input list * after the threads stopped, the shared variable should be identical to the sum of the input list Hint: * In CPython some operations on data structures are atomic, some are not. Use locks when the operations are not thread-safe. * Useful links: https://docs.python.org/2/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe """ import random import sys from threading import Thread, Lock from functools import reduce import time # global var VAR = 0 INPUT_LIST = [] class CustomThread(Thread): def __init__(self, thread_id, lock): Thread.__init__(self) self.thread_id = thread_id self.lock = lock def run(self): global VAR # play it global index = random.randint(0, len(INPUT_LIST)) time.sleep(random.randint(0, 10)) with lock: curr_elem = INPUT_LIST[index][0] while INPUT_LIST[index][1]: index = random.randint(0, len(INPUT_LIST)-1) curr_elem = INPUT_LIST[index][0] INPUT_LIST[index][1] = True # marked as selected VAR += curr_elem print("Current thread: %s has a value for the shared variable equal to: %s" % (self.thread_id, VAR)) if __name__ == "__main__": num_threads = int(sys.argv[1]) input_list = [random.randint(0, 500) for i in range(num_threads)] initial_sum = reduce(lambda x, y: x + y, input_list) input_dict = [] for entry in input_list: input_dict.append([entry, False]) INPUT_LIST = input_dict print(" ".join([str(x) for x in input_list])) lock = Lock() thread_array = [] for i in range(num_threads): thread_array.append(CustomThread(i, lock)) for entry in thread_array: entry.start() for entry in thread_array: entry.join() print(VAR)
true
e47a323e7ac9969c3247247fe21c59291e9aa03e
ProjectFullStack/oop-python
/1_Introduction/main.py
804
4.28125
4
""" Main.py 20210915 ProjectFullStack """ class Dog: """ A class to represent dogs """ scientific_name = "Canis lupus familiaris" def __init__(self, name): """ Constructor method that will run every time we create a new dog object :param name: name :type name: str """ self.name = name def bark(self): """ Returns the string "bark bark bark!" :return: "bark bark bark!" :rtype: str """ return "bark bark bark!" dog_object1 = Dog("Basil") dog_object2 = Dog("Bronson") # Interact with the dog_object1 (which is "Basil") print(dog_object1.name) print(dog_object1.bark()) # Interact with the dog_object2 (which is "Bronson") print(dog_object2.name) print(dog_object2.bark())
false
9fa9143d56b1bd70f38c2fd7a193a33896519e8e
SENSEI-9/LabWork2
/2question.no.11.py
421
4.3125
4
'''given three integers, print the smallest one. (three integers should be user input)''' a=int(input('Enter first number : ')) b=int(input('Enter second number : ')) c=int(input('Enter third number : ')) if a<b and a<c: print(f'{a} is the smallest number among {a},{b},{c}') elif b<a and b<c: print(f'{b} is the smallest number among {a},{b},{c}') else: print(f'{c} is the smallest number among {a},{b},{c}')
true
d299dabb9bcb5b7b57c739ab5bf16dbf41a3aebe
MedeusAl/RuszGlowaPyth
/R02/eggs.py
668
4.125
4
pharse = "podaj jajko!" plist = list(pharse) print(pharse) print(plist) # for letter in plist: # if letter == 'p': # plist.remove(letter) # elif letter == 'k': # plist.remove(letter) for letter in range (len(plist),len(plist)-3,-1): plist.pop() plist.remove('p') plist.remove('a') plist.remove('j') new_pharse = ''.join(plist) print(plist) print(new_pharse) print("====nowy przyklad====") pharse = "podaj jajko!" plist = list(pharse) print(pharse) print(plist) firstStep = plist[1:7] print(firstStep) firstStep.insert(2, firstStep.pop()) firstStep.insert(2, firstStep.pop()) new_pharse = ''.join(firstStep) print(new_pharse) print(plist)
false
167d59883e080f7245e68a38b30691ff692386dd
NeighbourLizard/from0toHero
/String Manipulation/string.py
410
4.59375
5
mystring = 'abcdefghijk' # to show a particular element of string # negative number just counts string from the last element print(mystring[2]) # To grab section of string we can use ":" print(mystring[2:]) # End of the section can be written after column print(mystring[2:4]) # A third number states how many elements should it jump print(mystring[::2]) # To reverse a string one can use print(mystring[::-1])
true
524e86c21847f7884d1133dec7fef5d2f0cf4de2
NeighbourLizard/from0toHero
/Section 3 Exam/exam.py
1,350
4.5
4
# Examples s = 'hello' # grab "e" print[s[1]] # Reverse string s print(s[::-1]) # Produce letter "o" in two different methods print(s[-1]) print(s[4]) # Build this list [0,0,0] in two separate ways list1 = [0,0,0] # Reeassign 'hello' in this nested list to say # 'goodbye' instead list3 = [1,2,[3,4,'hello']] insideList = list3[-1] insideList[-1] = 'goodbye' print(list3) print(insideList) # Sort the list below list4 = [5,3,4,6,1] print(list4) list4.sort() print(list4) # Using keys and indexing, grab the 'hello' # from the following dictionaries d = {'simple_key':'hello'} # Grab Hello print("Grab Hello from Dictionary : ", d) print(d['simple_key']) # Grab Hello d2 = {'k1':{'k2':'hello'}} print("Grab Hello from Dictionary : ", d2) print(d2['k1']['k2']) # Grab Hello d3 = {'k1':[{'nest_key':['this is deep',['hello']]}]} print("Grab Hello from Dictionary : ", d3) # first = d3['k1'] # second=first[0]['nest_key'][1] # second=d3['k1'][0]['nest_key'][1] # print(first) print(d3['k1'][0]['nest_key'][1]) print("__________________________") # Grab Hello dragon = {'k1':[1,2,{'k2':['this is tricky', {'though':[1,2,['hello']]}]}]} print("Grab Hello from Dictionary : ", dragon) one = dragon['k1'][2]['k2'][1]['though'][2] print(one) # What is the difference between tuples and lists? # Tuple elements cannot be changed while list's can
false
17350464be4a6384d2ce6e7760357a8596229172
danielns-op/CursoEmVideo
/Python/exercicios/ex100.py
886
4.15625
4
# Faça um programa que tenha uma lista chamada números e duas funções # chamadas sorteio() e somaPar(). A primeira função vai sortear 5 números # e vai colocálos dentro da lista e a segunda função vai mostrara soma # entre todos os valores PARES sorteados pela função anterior. from random import randint from time import sleep numeros = [] def sorteia(): print('Sorteando 5 valores para a lista:', end=' ', flush=True) for n in range(0, 5): sleep(0.5) valor = randint(1, 10) numeros.append(valor) print(valor, end=' ', flush=True) print('PRONTO!') def somaPar(): soma = 0 print(f'Somando os valores pares de {numeros},', end=' ', flush=True) for valor in numeros: if valor % 2 == 0: soma += valor sleep(1) print(f'temos {soma}.') sorteia() somaPar()
false
a43dcd4a04dbbf57c4dfdafbca53693f44096ab8
giangjason/StudyNotes2020
/Elements of Programming Interviews in Python/Arrays_CH5/multiply_two_integer_arrays_5-3.py
1,023
4.34375
4
# Write a program that accepts two arrays representing two integers and returns an array representing their product # Ex.1 input = [1,2,3], [2,3] output = [2,8,2,9] from helper import Helper from typing import List import random import sys def multiple_two_interger_arrays(num1: List[int], num2: List[int]) -> List[int]: return [] def main(): h = Helper() args = sys.argv if len(args) > 1: num1 = [int(digit) for digit in list(args[1])] num2 = [int(digit) for digit in list(args[2])] else: low, high, length = 0, 9, 4 num1 = h.generate_random_list(low, high, length) num2 = h.generate_random_list(low, high, length) print("Num1:", num1) print("Num2:", num2) tmp = str(int(''.join([str(digit) for digit in num1])) * int(''.join([str(digit) for digit in num2]))) expected = [int(digit) for digit in tmp] actual = multiple_two_interger_arrays(num1, num2) print("Expected:", expected) print("Actual:", actual) main()
true
6ceafa414a8fe111091575a702653a60c8c2088d
giangjason/StudyNotes2020
/Elements of Programming Interviews in Python/Heaps_CH10/sort_almost_sorted_array_10-3.py
955
4.125
4
# Write a program that takes an input a k-sorted array of integers and returns a completely sorted list of integers. # A k-sorted array is defined as each number is at most k away from its correctly sorted position. # Ex. arr = [3, -1, 2, 6, 4, 5, 8], k = 2. Each item in arr is no more than k=2 away from its final sorted position # Brownie points if you can do in place from typing import List import heapq def sort_k_sorted_array(arr: List[int], k: int) -> None: heap = [] replace_idx = 0 for i in range(len(arr)): if len(heap) < k: heapq.heappush(heap, arr[i]) else: num = heapq.heappushpop(heap, arr[i]) arr[replace_idx] = num replace_idx += 1 while replace_idx < len(arr): num = heapq.heappop(heap) arr[replace_idx] = num replace_idx += 1 def main(): nums = [3, -1, 2] k = 2 sort_k_sorted_array(nums, k) print(nums) main()
true
7f1fa514025dfeeea1cb187c1e7e0ae1448bbe14
giangjason/StudyNotes2020
/Elements of Programming Interviews in Python/Arrays_CH5/increment_integer_array_5-2.py
965
4.21875
4
# Write a program that takes in an array representing an integer number and adds 1 to it. # Ex.1 input = [1,3,1] output = [1,3,2] # Ex.2 input = [9,9,9] output = [1,0,0,0] from typing import List import random import sys def generate_random_list(digits: int) -> List[int]: return [random.randint(1,9) for _ in range(digits)] def increment_interger_array(arr: List[int]) -> List[int]: n = len(arr)-1 arr[n] += 1 place = 0 for i in range(n, -1, -1): arr[i] += place place = arr[i] // 10 arr[i] %= 10 if place == 0: return if place > 0: return [place] + arr return arr def main(): args = sys.argv if len(args) > 1: tmp = list(args[1]) nums = [int(digit) for digit in tmp] else: digits = 3 nums = generate_random_list(digits) print("Before:", nums) plus_one = increment_interger_array(nums) print("After:", plus_one) main()
true
9db42c62593835a9a0d85c6fb9ef618ed4156d2f
Erick-ViBe/LeetCodePython
/Integers/reverseInteger.py
593
4.625
5
""" Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Example 4: Input: x = 0 Output: 0 """ def reverse(x): x = [int(y) for y in str(x)] x.reverse() y = "".join(str(x)) return y if __name__ == '__main__': x = reverse(123) print(x)
true
ce6f0d12a4c672b0c5141d79b0770f3d3748e412
clorenza/PythonBattleship
/Battleship.py
1,113
4.15625
4
Celia = 'Celia' from random import randint #Making the 'Ocean' 6x6 board ocean = [] for item in range(6): ocean.append(['o']*6) def print_ocean(ocean): for row in ocean: print ' '.join(row) #Having the ship randomly assigned to a spot in the ocean #Note that randint includes the second number.... ship_row = randint(0,5) ship_column = randint(0,5) #for temporary debugging print ship_row print ship_column #Game! print 'BATTLESHIP!' print 'Your mission objective is to destroy the enemy ship. Aim your cannon for coordinates between 1 and 6.' while True: guess_row = int(raw_input('Guess Row?')) - 1 guess_column = int(raw_input('Guess Column?')) - 1 if guess_row == ship_row and guess_column == ship_column : print 'You sunk the enemy ship! You win!' break elif guess_row < 0 or guess_row > 5 or guess_column < 0 or guess_column > 5: print 'Out of range. Aim your cannon better.' print_ocean(ocean) else: print 'Oh no, you missed! Try harder!' ocean[guess_row][guess_column] = 'x' print_ocean(ocean)
true
15459b1e8d2003fabab0e5b42d7362e40a76d1fc
emguffy/ProjectEuler
/005_smallestMultiple.py
1,503
4.25
4
multiplesList = range(1,21) primeList = [2,3,5,7,11,13,17,19] pointer = 1 primeFactor = 1 masterPrimes = [] # Iterate backwards through the list of multiples to see if they are factors # If so, we'll add their unique prime factors to a list # Then, we'll take the product of that list and add it to our pointer to make our algorithm greedy for multiple in reversed(multiplesList): print "Mulitple = " + str(multiple) while (pointer % multiple != 0): pointer += primeFactor print "Pointer = " + str(pointer) # Build a list to hold prime factors of the multiple multiplePrimes = [] residual = multiple print "residual = " + str(residual) while (residual != 1): for prime in primeList: if residual % prime == 0: multiplePrimes.append(prime) residual /= prime break print "multiplePrimes: " + str(multiplePrimes) print "masterPrimes: " + str(masterPrimes) j = 0 for item in multiplePrimes: if j == len(masterPrimes): masterPrimes.append(item) while (j<len(masterPrimes)): if item == masterPrimes[j]: j += 1 break elif item >= masterPrimes[j]: j += 1 if j == len(masterPrimes): masterPrimes.append(item) else: masterPrimes.insert(j,item) j += 1 break print "masterPrimes: " + str(masterPrimes) # reset the primeFactor to 1 each time through primeFactor = 1 for prime in masterPrimes: primeFactor *= prime print "primeFactor = " + str(primeFactor) print "final pointer: " + str(pointer)
true
bfd84de4d693fe83e0a3f08331ddfc7f82a45b41
Arzana/INFDEV02-1
/code/INF1E_Examples/IsoTriangle.py
1,835
4.46875
4
from Utils import GetIntInput, Populate # Import the functions GetIntInput and Populate from the Utils file. def GetIsoTriangleStr(height: int): # Define a function for creating a triangle in string format. scalar = 2 # Define a variable for the the amount of '*' added per vertical iteration. width = (height - 1) * scalar + 1 # Get the absolute width of the final triangle. result = '' # Define a variable named 'result' for storing the characters calculated. x = 1 # Define the amount of '*' characters used in the current iteration. for y in range(1, height + 1): # Loop through the height specified (starts at 1 for ease of use later). spaces = (width - x) >> 1 # Get the amount of spaces needed at both ends of the triangle ('>> 1' does the same as '/ 2', its just faster). result += Populate(' ', spaces) # Add the right sided spaces to the result string. result += Populate('*', x) # Add the '*' characters to the result string. result += Populate(' ', spaces) # Add the left sided spaces to the result string. if (y < height): result += '\n' # At the end of every vertical iteration add a newline to the string, unless it is the last iteration. x += scalar # Add the scalar to the horizontal specifier. return result; # Return the complete result string. def Main(): h = GetIntInput("Please specify the height of the isosceles triangle: ") # Get the height of the triangle from the user. print(GetIsoTriangleStr(h)) # Print the triangle generated to the screen. input("Press any key to continue...") # Display an message so the user know what to do next. if (__name__ == "__main__"): Main()
true
389e4912efb5d6c8bd35e6c86b723dabfeaf2676
Arzana/INFDEV02-1
/code/INF1E_Examples/Utils.py
1,198
4.1875
4
def GetIntInput(msg: str): # Define a function for safely getting integral input from the user. result = None # Define a variable named 'result' for storing the integral value. while (result == None): # Loop until we have a valid input. print(msg, end = '') # Display the message specified and make sure the user can type on the end of that line. try: # Define a 'try catch' structure to catch exceptions. result = int(input()) # Get the input from the user and try to convert it to a int. except: # If this raises an error do nothing; otherwise result is an int and the loop can end. pass return result def Populate(char: chr, amount: int): # Define a function to replace the 'string * int' operator. if (amount < 0): # If the specified amount if less than zero throw an exception. raise ValueError("Amount must be bigger or equal to zero!") result = '' # Define a variable named 'result' for storing the string output. for i in range(amount): # Add the specified char to the result for the specified amount. result += char return result
true
c50cc896917447ef75a568f3b4b46b5861e9d461
Arzana/INFDEV02-1
/code/INF1E_Examples/Sorting/Insertion.py
274
4.15625
4
# Executes a insertion style sort over the specified int32 numbers def Sort_Insertion(numbers): for i in range(1, len(numbers)): newI = i for j in range(i - 1, -1, -1): if (numbers[j] > numbers[i]): newI = j if (newI != i): numbers.insert(newI, numbers.pop(i))
true
2aeb8a1e7d83a8f416e08648c815805ce784ccca
FunWithPythonProgramming/coding-bat-exercises
/week_2_Feb_5/make_bricks/george_soluition.py
1,127
4.71875
5
""" We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops. See also: Introduction to MakeBricks make_bricks(3, 1, 8) → True make_bricks(3, 1, 9) → False make_bricks(3, 2, 10) → True """ def make_bricks(small, big, goal): first = small * 1 second = big * 5 if (first + second) == goal: return True elif small == (goal - second): return True elif second == goal: return True elif goal % 5 == (second % 5) + small: return True else: return False print(make_bricks(3, 1, 8)) # Expects True print(make_bricks(3, 1, 9)) # Expects False print(make_bricks(3, 2, 10)) # Expects True print(make_bricks(3, 2, 8)) # Expect True print(make_bricks(3, 2, 9)) # Expects False print(make_bricks(3, 2, 9)) # Expects → False print(make_bricks(1, 4, 11)) # Expects True print(make_bricks(0, 3, 10)) # Expects True
true
f7562642762c1d7f0bfd11c9794bea6b4603d41e
hemangbehl/Data-Structures-Algorithms_practice
/leetcode_session2/practice_linkedlist_basics_1.py
847
4.1875
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None #initialize linkedlist as empty at the start def printList(self): #prints linked list from start to end curr = self.head while (curr != None): print (curr.data) curr = curr.next def addNodeAtStart(self, ele): curr = self.head new_node = Node(ele) #create a new node for ele if curr == None: self.head = new_node elif curr.next == None: curr.next = new_node else: #go to next in list curr = curr.next ll = LinkedList() ll.head = Node(1) ll.head.next = Node(2) ll.head.next.next = Node(3) ll.head.next.next.next = Node(4) ll.printList()
true