blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
783c15828a6dea13519b7e044ee84fce04d3bff4
sophiekshelbie/tests
/testno2.py
560
4.125
4
# Python program to remove to every second # element until list becomes empty def removeSecondNumber(int_list): # list starts with # 0 index pos = 2 - 1 index = 0 len_list = (len(int_list)) # breaks out once the # list becomes empty while len_list > 0: index = (pos + index) % len_list # removes and prints the required # element print(int_list.pop(index)) len_list -= 1 # Driver code nums = [10, 20, 30, 40] removeSecondNumber(nums)
true
fc2b42e432271628424d3e4e09472dd93cbd271f
kathleenphan/election_analysis
/Python_practice.py
1,186
4.21875
4
print("Hello World") counties = ["Arapahoe","Denver","Jefferson"] if "El Paso" in counties: print("El Paso is in the list of counties.") else: print("El Paso is not the list of counties.") if "Arapahoe" in counties and "El Paso" in counties: print("Arapahoe and El Paso are in the list of counties.") else: print("Arapahoe or El Paso is not in the list of counties.") if "Arapahoe" in counties or "El Paso" in counties: print("Arapahoe or El Paso is in the list of counties.") else: print("Arapahoe and El Paso are not in the list of counties.") for county in counties: print(county) voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] for county_dict in voting_data: print(county_dict) my_votes = int(input("How many votes did you get in the election? ")) total_votes = int(input("What is the total votes in the election? ")) percentage_votes = (my_votes / total_votes) * 100 print("I received " + str(percentage_votes)+"% of the total votes.") f'{value:{width}.{precision}}'
false
ef346c568b8098f347770942e6379e90f41e0c1b
isabel-eng/C-Python-exercises
/Problem2.py
403
4.4375
4
#2. Given a list of strings delete all special chars in each one (non-alphanumeric chars). strings = input("put strings: ") #The following for goes through each character of the string and checks if it #is an alphanumeric value or a space otherwise it will replace it for i in strings: if i.isalnum() or i == ' ': words = strings else: words = strings.replace(i,'') print(words)
true
ca24387c50388deba01df56d0a1e6ffad0a0eeff
Chiragkaushik4102001/Python_1styear
/PYTHON/functions_list.py
1,027
4.15625
4
#inbuilt functions in list l=[1,2,3,4,5] #1.count() print(l.count(4)) #returns the number of occurence of value in the list #2.index() print(l.index(4)) #returns the index value of first appearance of value print(l.index(4,2)) #index with range #3.append() l.append(6) #it does nt return any value just used to add elements to the list print(l) #4.extend() l.extend([7,8,9]) #used for adding multiple elements into the list print(l) #5.insert(index,value to be entered) l.insert(0,10) #it is used to insert a value at a particular index value print(l) #6.remove() l.remove(10) #used to remove the first occurence of the value from the list print(l) #7.reverse() l.reverse() #reverse the elements of the list print(l) #8.sort() l.sort() #the function sorts the value in ascending order print(l) #9.pop() l.pop() #this function removes the last element of the list print(l) l.pop(3) #if index value is given then it removes the ite,m at that particular index print(l)
true
ea2cb69b7f85adcd3728a083b1577c1e7ded283f
Chiragkaushik4102001/Python_1styear
/PYTHON/tuple.py
599
4.5
4
#tuple in python ''' tuple is immutable and is enclosed in () ''' a=(1,2,3) b=() c=(1) d=(1,) # creation of tuple with single element e=1,2,3 print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) x=a+e #updation of tuple print(x) y=2*x #printing tuple multiple times print(y) z=[1,2,3,4] # in case of list del () can be used to delete a particular element del(z[2]) print(z) #del(e) #print(e) #del() casn be used only to delete a whole tuple print(a[0:2:1]) # slicing in tuple print(a[::-1]) # to print reverse of a tuple ,list,string
true
56edc059a4eab5ba4c750b9717b1ab4263ac4939
cman131/CodeChallenges
/DottieNumber.py
429
4.125
4
import math origin = input('Please input a number: ') keepLooping = True while(keepLooping): try: origin = float(origin) keepLooping = False except: origin = input('I\'m sorry, but it must be a number.') current = math.cos(origin) previous = origin while(current != previous): previous = current current = math.cos(current) print('The resulting Dottie Number of', origin, 'is', current)
true
053928b183079421e8abfe13dc99ce9a181c0331
armenzg/coding
/euler/1-multiples.py
595
4.25
4
'''Multiples of 3 and 5 Problem 1 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. ''' from functools import reduce if __name__ == "__main__": multiples = [] for num in range(1000): if num % 3 == 0: multiples.append(num) continue if num % 5 == 0: multiples.append(num) continue # Practice lambdas print(reduce(lambda acc, num: acc + num, multiples)) print(sum(multiples))
true
b80ec09a0b9510941a2c942c14a5fd0f89333cef
TahaKhan8899/Coding-Practice
/LeetCode/mergeBinaryTrees.py
2,022
4.25
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def appendNode(self, node): self.left = node class Solution: def mergeTrees(self, t1, t2): # make new root node if t1 is not None and t2 is not None: newRoot = TreeNode(t1.val + t2.val) # traverse and add to new root node newTree = overlapTraverse(t1, t2, newRoot) traverseTreePreOrder(newTree) else: return None def overlapTraverse(t1, t2, newTree): if t1.left is not None and t2.left is not None: newNode = TreeNode(t1.left.val + t2.left.val) print(newNode.val) newTree.left = newNode overlapTraverse(t1.left, t2.left, newTree.left) elif t1.right is not None and t2.right is not None: newNode = TreeNode(t1.right.val + t2.right.val) print(newNode.val) newTree.right = newNode overlapTraverse(t1.right, t2.right, newTree) elif t1.left is None and t2.left is not None: newTree.left = TreeNode(t2.left.val) print(newTree.left.val) elif t1.left is not None and t2.left is None: newTree.left = TreeNode(t1.left.val) print(newTree.left.val) elif t1.right is None and t2.right is not None: newTree.right = TreeNode(t2.right.val) print(newTree.right.val) elif t1.right is not None and t2.right is None: newTree.right = TreeNode(t1.right.val) print(newTree.left.val) return newTree def traverseTreePreOrder(root): if root is not None: print(root.val) traverseTreePreOrder(root.left) traverseTreePreOrder(root.right) n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n1.left = n2 n1.right = n3 n2.left = n4 t1 = TreeNode(1) t2 = TreeNode(2) t3 = TreeNode(3) t1.left = t2 t1.right = t3 arr = [] # traverseTreePreOrder(n1) obj = Solution() obj.mergeTrees(n1, t1)
true
18cc276097148578b75ad18d32c99e2188e4820b
TobiasDB/ChessProject
/ChessRework2/Main/__init__.py
1,904
4.28125
4
import turtle #[0.0.0] Import Turtle wn = turtle.Screen() #[1.0.0] Creating Window Screen wn.bgcolor("black") #[1.1.0] Background Colour wn.title("Chess [0.0.1]") #[1.2.0] Title wn.screensize() #[1.3.0] Screen size wn.setup(width = 1.0, height = 1.0) #[1.3.0] Screen size wn.tracer(5) #[1.4.0] Tracer Value StartButton = turtle.Turtle() #[2.0.0] Creating a turtle StartButton.penup() #[2.1.0] Creating a turtle StartButton.begin_fill() #[2.3.0] Create a solid shape StartButton.goto(-100, 150) #[2.2.0] Move turtle to create a square StartButton.goto(100,150) #[2.2.0] StartButton.goto(100,45) #[2.2.0] StartButton.goto(-100,45) #[2.2.0] StartButton.goto(-100, 150) #[2.2.0] StartButton.end_fill() #[2.3.0] StartButton.goto(0, 80) #[2.4.0] StartButton.hideturtle() #Hides the turtle so that it cannot be seen on the window StartButton.color("green") #[2.5.0] Change the colour of the turtle (any actions it takes will be in this colour) to green StartButton.write("Start", align="center",font=("Courier New", 32,"bold")) #[2.6.0] Write a string of text at the turtles location pen = turtle.Turtle() # Create a pen to write text on the screen pen.penup() pen.color("green") pen.goto(0,250) pen.hideturtle() pen.write("Chess Game", align="center",font=("Times", 72,"bold")) #Title pen.goto(500,-300) pen.write("Tobias D-B", align="center",font=("Courier New", 16,"bold")) pen.pendown() wn.bgpic("/Users/tobiasdunlopbrown/eclipse-workspace/ChessRework/Main/ChessBg.gif") # [3.0.0] Adding a background image wn.update() # Refreshes the window to show the changes not already updated def StartButtonClicked(): wn.clear() import MainProgram MainProgram() #[2.6.3] def MenuClicked(x,y): if x >= -100 and x <= 100 and y <= 150 and y >= 45: #[2.6.2] StartButtonClicked() #[2.6.3] wn.onclick(MenuClicked) #[2.6.1] On clicking the screen MenuClicked will be run turtle.mainloop()
false
1c9678c5acf892473d0299dd94ff29f9b8e5510d
uchenna-j-edeh/dailly_problems
/sorting_algorithm/calculate_inversion.py
1,194
4.15625
4
""" Author: Uchenna Edeh We can determin how out of order an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form a inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. Given an array, count the number of inversions it has. Do this faster than O(N^2) time. You may assume each element in the array is distinct. Example, a sorted list has zero inversions. The array [2,4,1,3,5] has three inversions: (2,1), (4,1), and (4,3). The array [5,4,3,2,1] has ten inversions: every distinct pair forms an inversion. """ import sys def solution1(A): count = 0 for i, val in enumerate(A): for j in range(i+1, len(A)): if A[i] > A[j]: count = count + 1 # print(A[i], A[j]) return count def main(args): if len(args) != 2: raise AssertionError("Usage:\n\tpython3 {0} '{1}'\n\tExpected Result: {2}\n\tPlease Try Again!\n\t".format(__file__, "2,4,1,3,5", '3' )) A = [int(x) for x in args[1].split(',')] print(solution1(A)) if __name__ == "__main__": try: main(sys.argv) except AssertionError as e: print(e) sys.exit(1)
true
fc005c5c2d36d19284a0de48ee8ae80d2c91f919
uchenna-j-edeh/dailly_problems
/sorting_algorithm/merge_sort.py
1,221
4.125
4
""" write merge sort algo """ def merge_sort_helper(A, start, end): if start >= end: return mid = (start + end) // 2 merge_sort_helper(A, start, mid) merge_sort_helper(A, mid + 1, end) # when you have divided array down to it's smalles unit and you begin exection, this piece of code below then runs i = start j = mid + 1 aux = [] while i <= mid and j <=end: if A[i] <= A[j]: aux.append(A[i]) i = i + 1 else: # A[i] > A[j] aux.append(A[j]) j = j + 1 while i <= mid: aux.append(A[i]) i = i + 1 while j <= end: aux.append(A[j]) j = j + 1 for i in range(len(aux)): A[start] = aux[i] start = start + 1 return A def merge_sort(A): merge_sort_helper(A, 0, len(A) - 1) A = [9,1,5,6,3,4,9,0] result = merge_sort(A) print(result) print(A) # Read the contents of the file into a Python list NUMLIST_FILENAME = "QuickSort_List.txt" inFile = open(NUMLIST_FILENAME, 'r') with inFile as f: numList = [int(integers.strip()) for integers in f.readlines()] # call functions to count comparisons #print(merge_sort(numList)) #print(numList)
true
3d5742631c83949b62689b99242d2e7e65aefa66
uchenna-j-edeh/dailly_problems
/after_twittr/merget_two_sorted.py
2,155
4.5
4
from typing import List """You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. Example 1: Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1. Example 2: Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Explanation: The arrays we are merging are [1] and []. The result of the merge is [1]. Example 3: Input: nums1 = [0], m = 0, nums2 = [1], n = 1 Output: [1] Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. """ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ i = 0 j = 0 while j <= n-1 and i <= m-1: # if nums1[i] < nums2[j]: # 1 < 2|True, 2 < 2|False, 2 < 5|True, 3 < 5 # nums1.insert(i+i, nums2[j]) # index, value # j = j + 1 i = i + 1 # i = 1, i = 2 , i =3, else: nums1.insert(i, nums2[j]) # index, value [1,2,2...] j = j + 1 # j= 1 while i <= len(nums1)-1: nums1[i] = nums2[j] i = i + 1 j = j + 1 solution = Solution() nums1 = [1,2,3,0,0,0] m = 3 nums2 = [2,5,6] n = 3 print(solution.merge(nums1, m, nums2, n))
true
6ef5d6d069eaf149244cb4774676dff7f7d653c9
uchenna-j-edeh/dailly_problems
/g_prep/google_inter.py
1,298
4.125
4
""" 0, 1, 1, 0, 1, 1, 0, 1, 1 Pisano(A, B, M) → [A,B, (A+B)%M …. ] continue until repetition. Pisano(0, 1, 3) → [0, 1, 1, 2, 0, 2, 2, 1] Modulus 4 5,6 → 3 2,4 → 2 Modulus 4 0,1,1,2,3,1,0,1 ---> [0,1,1,2,3,1] the objective is to find the list of elements until repetition Sounds good. """ aList = [1,4, 5, 7, 2, 3, 1] newList = [1, 25, 49, 9, 1] def square_odd(aList): newList = [] for i in aList: if i % 2: newList.append(i) return newList def solution(A, B, M): aList = [A, B] i = 0 while True: aList.append( (aList[i] + aList[i+1]) % M ) # [A, B, C] if (A == aList[i+1] and B == aList[i+2]): return aList i = i + 1 def solution0(n, A, B): if n == 0: return A return solution0(n - 1, B, A + B) print("The solution is: ", solution(0, 1, 2)) print("The solution is: ", solution(0, 1, 3)) print("The solution is: ", solution(1, 2, 3)) print("The solution is: ", solution(0, 1, 4)) print("The solution is: ", solution(3, 2, 4)) print("The solution is: ", solution(2, 3, 4)) print("The solution is: ", solution(0, 1, 5)) print("The solution is: ", solution(3, 4, 5)) print("The solution is: ", solution(4, 5, 6)) print("The solution is: ", solution(5, 4, 6))
false
d93232a8ce3da57942d853053eea2a543eff3b9a
uchenna-j-edeh/dailly_problems
/hackerank/diagonal_difference.py
1,796
4.625
5
""" Given a square matrix, calculate the absolute difference between the sums of its diagonals. For example, the square matrix is shown below: 1 2 3 4 5 6 9 8 9 The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is . Function description Complete the function in the editor below. diagonalDifference takes the following parameter: int arr[n][m]: an array of integers Return int: the absolute diagonal difference Input Format The first line contains a single integer, , the number of rows and columns in the square matrix . Each of the next lines describes a row, , and consists of space-separated integers . Constraints Output Format Return the absolute difference between the sums of the matrix's two diagonals as a single integer. Sample Input 3 11 2 4 4 5 6 10 8 -12 Sample Output 15 Explanation The primary diagonal is: 11 5 -12 Sum across the primary diagonal: 11 + 5 - 12 = 4 The secondary diagonal is: 4 5 10 Sum across the secondary diagonal: 4 + 5 + 10 = 19 Difference: |4 - 19| = 15 Note: |x| is the absolute value of x """ def diagonalDifference(arr): # Write your code here lr_diag_sum = 0 rl_diag_sum = 0 count = 0 j_dx = len(arr) - 1 for i in range(len(arr)): # i_dx = i + count for j in range(len(arr[i])): if count == i and j_dx - count == j: rl_diag_sum += arr[i][j] if i == j: # lr diagonal lr_diag_sum += arr[i][j] count += 1 diff = lr_diag_sum - rl_diag_sum if diff < 0: diff = -1 * diff return diff arr = [ [1, 2, 3], [4, 5, 6], [9, 8, 9] ] print(diagonalDifference(arr)) arr2 = [ [11, 2, 4], [4, 5, 6], [10, 8, -12] ] print(diagonalDifference(arr2))
true
0f1fa758f93326ea055a41acb44db240209a2d41
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/second_max_value_in_list.py
559
4.125
4
""" Problem Statement Implement a function findSecondMaximum(lst) which returns the second largest element in the list. Input: A List Output: Second largest element in the list Sample Input [9,2,3,6] Sample Output 6 """ def findSecondMaximum(lst): max_val = lst[0] for val in lst: if val > max_val: max_val = val second_max_val = -1 * float("inf") for val in lst: if val > second_max_val and val != max_val: second_max_val = val return second_max_val print(findSecondMaximum([9,2,3,6]))
true
4dc9c9f8b25a772eb65d9aec91bfb43ae51743df
uchenna-j-edeh/dailly_problems
/arrays_manipulations_algorithms/match_word_in_2d_matrix_chars.py
1,415
4.46875
4
""" Author: Uchenna Edeh Good morning! Here's your coding interview problem for today. This problem was asked by Microsoft. Given a 2D matrix of characters and a target word, write a function that returns whether the word can be found in the matrix by going left-to-right, or up-to-down. For example, given the following matrix: [ ['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S'] ] and the target word 'FOAM', you should return true, since it's the leftmost column. Similarly, given the target word 'MASS', you should return true, since it's the last row. """ def is_match(two_d_matrix, word): # print("printing rows") for rows in two_d_matrix: if ''.join(rows) == word: print('A RIGHT Match word found') return True # print("printing columns") counter = 0 for i,_ in enumerate(two_d_matrix): form_word = '' for j in range(len(two_d_matrix)): form_word = form_word + two_d_matrix[j][i] if form_word == word: print('A DOWN Match word found') return True #counter = counter + 1 print('No match found!') return False two_d_matrix = [ ['F', 'A', 'C', 'I'], ['O', 'B', 'Q', 'P'], ['A', 'N', 'O', 'B'], ['M', 'A', 'S', 'S'] ] word = input('Enter a word: ') # Example FOAM or MASS print(is_match(two_d_matrix, word))
true
450a34105cd3ba5e8eb8bba61375e4215512545e
prudhvirdy25/PythonProject
/CodeSnippets/20_SplitMethod.py
357
4.15625
4
# Program to use Split method CustName="Prudhvi,Reddy" # taking two inputs at a time CustFirstName, CustLastName=CustName.split(",") print("FirstName Is:",CustFirstName) print("LastName Is:",CustLastName) # taking multiple inputs at a time # and type casting using list() function CustName2="A B C D E F G H" x=list(map(str,CustName2.split())) print(x)
true
0db66cfe11ad36df3f94479214ee032fd7dd1da1
Deonisii/work
/str_format.py
651
4.28125
4
age = 26 name = 'Denis' print('Возраст {0} -- {1} лет.'.format(name, age)) print('Почему {0} забавляется с этим Python?'.format(name)) ''' >>> # десятичное число (.) с точностью в 3 знака для плавающих: ... '{0:.3}'.format(1/3) '0.333' >>> # заполнить подчёркиваниями (_) с центровкой текста (^) по ширине 11: ... '{0:_^11}'.format('hello') '___hello___' >>> # по ключевым словам: ... '{name} написал {book}'.format(name='Swaroop', book='A Byte of Python') 'Swaroop написал A Byte of Python' '''
false
1e4744208b3434122d29774ac52212f86c6b00eb
chrishuskey/Intro-Python-I
/src/06_tuples.py
1,597
4.4375
4
""" Python tuples are sort of like lists, except they're immutable and are usually used to hold heterogenous data, as opposed to lists which are typically used to hold homogenous data. Tuples use parens instead of square brackets. More specifically, tuples are faster than lists. If you're looking to just define a constant set of values and that set of values never needs to be mutated, use a tuple instead of a list. Additionally, your code will be safer if you opt to "write-protect" data that does not need to be changed. Tuples enforce immutability automatically. """ # Import libraries and modules: import math # -------------------------------------------------------------------------------- # Example: def dist(point_a, point_b): """Compute the distance between two x,y points.""" x0, y0 = point_a # Destructuring assignment x1, y1 = point_b return math.sqrt((x1 - x0)**2 + (y1 - y0)**2) a = (2, 7) # <-- x,y coordinates stored in tuples b = (-14, 72) # Prints "Distance is 66.94" print("\nDistance between points is: {distance:.2f}".format(distance = dist(a, b))) # -------------------------------------------------------------------------------- # Write a function `print_tuple` that prints all the values in a tuple def print_tuple(tup): for value in tup: print(value) tup = (1, 2, 5, 7, 99) print("\nValues in first tuple:") print_tuple(tup) # Prints 1 2 5 7 99, one per line # Declare a tuple of 1 element, then print it: tup_one = (1,) # What needs to be added to make this work? print("\nValues in second tuple:") print_tuple(tup_one)
true
229501ef54a4a6bc8aaf91b58401398da874f172
faizansarfaraz/PIAIC-Projects.
/Vowel_tester.py
440
4.1875
4
print("Determaination of a vowel") print("=========================") print() alphabet=str(input("Enter an alphabet:")) if alphabet == "a": print(alphabet, "is a vowel.") if alphabet == "e": print(alphabet, "is a vowel.") if alphabet == "i": print(alphabet, "is a vowel.") if alphabet == "o": print(alphabet, "is a vowel.") if alphabet == "u": print(alphabet, "is a vowel.") else: print(alphabet, "is not a vowel.")
false
0258ac3259dd74163f52e0aadf51c4674e42ad27
mquabba/CP1404-Pracs
/Prac 2/exceptions_demo.py
346
4.28125
4
try: numerator = int(input("Enter numerator: ")) denominator = int(input("Enter denominator: ")) fraction = numerator / denominator print(fraction) except ValueError: print("Numerator and denominator must be valid a number!") except ZeroDivisionError: print("Number must be greater than zero!") print("Finished.")
true
0806bd38d8ef0f7555e4699d9ed128e79d169096
vishalsodani/experiments-in-programming
/explore_hashing/modulo_hashing.py
945
4.125
4
# a hash table has buckets # a hash function generates a value for an item and puts the item in a bucket # we are creating 10 buckets and using modulo operator and assigning item base don remainder # so 10 % 10 is 0 so belongs to bucket 0 # we have 10 buckets 0 1 2 3 4 5 6 7 8 9 def basic_hash_table(value_1, n_buckets): def hash_function(value_1, n_buckets): return int(value_1) % n_buckets hash_table = {i:[] for i in range(n_buckets)} # this is a bucket dictionary with each item being an empty list [] to which we will #add items print(hash_table) # we get {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []} for value in value_1: hash_value = hash_function(value, n_buckets) hash_table[hash_value].append(value) return hash_table result = basic_hash_table([2, 10, 3,100,17],10) #{0: [10, 100], 1: [], 2: [2], 3: [3], 4: [], 5: [], 6: [], 7: [17], 8: [], 9: []}
true
db9f1b98bed778af2c0b8cd5bd3237f707ad12a0
igorkoury/cev-phyton-exercicios-parte-2
/Aula20 – Funções (Parte 1)/ex98 – Função de Contador.py
1,123
4.25
4
'''Exercício Python 098: Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo. Seu programa tem que realizar três contagens através da função criada: a) de 1 até 10, de 1 em 1 b) de 10 até 0, de 2 em 2 c) uma contagem personalizada''' from time import sleep def contador(inicio, fim, passo): if passo < 0: passo *= 1 if passo == 0: passo = 1 print('-' * 20) print(f'Contagem de {inicio} até {fim} de {passo} em {passo}') if inicio < fim: cont = inicio while cont <= fim: print(f'{cont} ', end='') # sleep(.5) cont += passo print('FIM') else: cont = inicio while cont >= fim: print(f'{cont} ', end='') # sleep(.5) cont -= passo print('FIM') # Programa principal contador(1, 10, 1) contador(10, 0, 2) print('Agora aé sua vez de personalizar a contagem!') i = int(input('Início: ')) f = int(input('Fim: ')) p = int(input('Passo: ')) contador(i, f, p)
false
84d90abe6be4e7dccf274426f08b02ac690de693
igorkoury/cev-phyton-exercicios-parte-2
/Aula18 - Listas (Parte 2)/ex086 – Matriz em Python.py
487
4.40625
4
'''Exercício Python 086: Crie um programa que declare uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta.''' matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for l in range(0, 3): for c in range(0, 3): matriz[l][c] = int(input(f'Digite número para [{l},{c}]: ')) print('=' * 60) for l in range(0, 3): for c in range(0, 3): print(f'[{matriz[l][c]}]', end='') print()
false
e06a3cd0180cf1a4e8b7814b83a1f34d1b66ab29
igorkoury/cev-phyton-exercicios-parte-2
/Aula20 – Funções (Parte 1)/ex097 – Um print especial.py
447
4.1875
4
'''Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho adaptável. Ex: escreva(‘Olá, Mundo!’) Saída: ~~~~~~~~~ Olá, Mundo! ~~~~~~~~~ ''' def escreva(msg): tam = len(msg) + 4 print('~' * tam) print(f' {msg}') print('~' * tam) # Programa principal escreva('Igor Koury') escreva('Curso em Vídeo')
false
0f3650ff1240ed53424f93370546489a6af73604
Nyyen8/Attendance
/Testing/TeacherClassTest.py
2,196
4.21875
4
""" Program: TeacherClassTests.py Author: Paul Elsea Last Modified: 07/31/2020 Program to define tests for teacher class. """ import unittest from Classes.Teacher import Teacher as tch class TeacherTestCases(unittest.TestCase): '''Method to set up a test object''' def setUp(self): self.Teacher = tch('Bob', 'Billy', 1234567890, 1234) '''Method to delete a test object''' def tearDown(self): del self.Teacher '''Test to ensure attributes are being properly applied''' def test_tch_object_created_required_attributes(self): self.assertEqual(self.Teacher._lName, 'Bob') self.assertEqual(self.Teacher._fName, 'Billy') self.assertEqual(self.Teacher._tchID, 1234567890) self.assertEqual(self.Teacher._tchPIN, 1234) '''Test to ensure ValueError exception is thrown with incorrect lName input''' def test_tch_object_not_created_error_last_name(self): with self.assertRaises(ValueError): test = tch('0000', 'Billy', 1234567890, 1234) '''Test to ensure ValueError exception is thrown with incorrect fName input''' def test_tch_object_not_created_error_first_name(self): with self.assertRaises(ValueError): test = tch('Bob', '0000', 1234567890, 1234) '''Test to ensure ValueError exception is thrown with incorrect tchID input''' def test_tch_object_not_created_error_id(self): with self.assertRaises(ValueError): test = tch('Bob', 'Billy', 'aaaa', 1234) with self.assertRaises(ValueError): test = tch('Bob', 'Billy', 123456, 1234) with self.assertRaises(ValueError): test = tch('Bob', 'Billy', 123456789000, 1234) '''Test to ensure ValueError exception is thrown with incorrect tchPIN input''' def test_tch_object_not_created_error_pin(self): with self.assertRaises(ValueError): test = tch('Bob', 'Billy', 1234567890, 'aaaa') with self.assertRaises(ValueError): test = tch('Bob', 'Billy', 1234567890, 12345) with self.assertRaises(ValueError): test = tch('Bob', 'Billy', 1234567890, 123) if __name__ == '__main__': unittest.main()
true
a189232352cda30505364cfd04ceb9a91fb18d8e
charne-162/L1-Capstone1-Finance_Calculators
/finance_calculators.py
2,141
4.15625
4
import math # Ask user to choose investment or bond calculator user_input = input("Which calculation would you like to do? Enter investment or bond: ") # Change possible inputs ('BOND', 'Bond', 'bond'; 'INVESTMENT', 'Investment', 'investment') to lowercase calculator = user_input.lower() #if-elif-else statements: If user inputs "investment", proceed with calculation; else if user inputs "Investment", proceed with calculation; else if user enters "INVESTMENT", proceed with calculation; else print error message # if-elif-else statements: investment or bond; simple or compound interest # If user chooses investment,ask user to input the following: P = principal amount or initial investment amount; r = interest rate; t = time period for investment; interest type (simple or compound) if calculator == "investment": P = float(input("Enter the initial investment amount in rands: ")) IR = float(input("Enter the interest rate %: ")) t = float(input("Enter the number of years you would like to invest for: ")) interest = input("Please select simple or compound interest: ") r = IR/100 if interest == "simple": A = P*(1+r*t) print("The future value of your investment will be" + " " + str(A)) elif interest == "compound": A = P*math.pow(1+r,t) print("The future value of your investment will be" + " " + str(A)) # Else if user chooses bond, ask user to input the following: P = principal value of the house; n = number of months over which bond will be repaid; R= annual interest rate elif calculator == "bond": P = float(input("What is the present value of the house? (Enter amount in rands): ")) n = float(input("Over how many months will the bond be repaid?? ")) R = float(input("What is the annual interest rate? %: ")) i = R/12 x = (i*P)/(1-(1+i)**(-n)) print("The monthly bond repayment will be" + " " + str(x)) # Else statement (If user input is not 'BOND', 'Bond', 'bond'; or 'INVESTMENT', 'Investment', 'investment', print error message) else: print("Error: That is not a valid input. Enter investment or bond.")
true
e22d44f176793bdebe7fbf684d47aa38e8b8cb5b
yitongw2/Code
/algorithm/matrix_determinant.py
1,189
4.125
4
def extractSubMatrix(matrix, col): """ extract a sub matrix both row and column reduced by one. column to be ignore is specified as col """ subMatrix=[] for i in range(1, len(matrix)): subMatrix.append([matrix[i][j] for j in range(len(matrix[i]))\ if j!=col]) return subMatrix def getDeterminants(matrix): """ recursive algorithm to calculate the determinant of a matix. assume that matrix rows are all in the same size base case: 2X2 matrix e.g. [a, b] --> [c, d] --> formula = a*d-b*c recursive case: nXn matrix [a, b, c] [d, e, f] [g, h, i] return a*recursive calll on [e, f] [h, i] - b*recursive call on [d, f] [g, i] + c*recursive call on [d, e] [g, h] """ if len(matrix)==2 and len(matrix[0])==2: return matrix[0][0]*matrix[1][1]-\ matrix[0][1]*matrix[1][0] else: result=0 for col in range(len(matrix[0])): coefficient=matrix[0][col] if (col+1)%2==0: coefficient=0-coefficient result+=coefficient*\ getDeterminants(extractSubMatrix(matrix, col)) return result if __name__=="__main__": print (getDeterminants([[1,3,2],[4,1,3],[2,5,2]]))
true
48b18ff670f5feb1394f93597add7098df094c68
szagot/python-curso
/Alunos/filipe-variaveis.py
504
4.15625
4
n1 = int(input('digite 1 número: ')) n2 = int(input('digite o 2 número: ')) print('==== MATEMATICA ====') soma = n1 + n2 subtracao = n1 - n2 multiplicacao = n1 * n2 divisao = n1 / n2 sobra = n1 % n2 print(f'a soma de {n1} + {n2} = {soma}') print(f'a subtracao de {n1} - {n2} = {subtracao} ') print(f'a multiplicacao de {n1} x {n2} = {multiplicacao} ') print(f'a divisao de {n1} / {n2} = {divisao}') print(f'a sobra de {n1} / {n2} = {sobra} ') print('yes == yes') input('eu odeio matematica , e voce: ')
false
f7d63ceb85dbfaa4da5648086cb6cd9ba5af5b38
matramir/Python3-Scripts
/trent.py
729
4.125
4
#! python3 # trent.py - This simple script uses the os.walk function to show # folders, subfolders and filenames in a given directory. # usage: write trent,py <directory> import sys, os if len(sys.argv) != 2: print ('Please enter the filepath when calling the script as described in the script documentation') exit() dirPath = sys.argv[1] isDir = os.path.isdir(dirPath) if isDir == False: print ('Please enter an existing directory.') exit() else: for folderName, subfolders, filenames in os.walk(dirPath): print('The folder is '+folderName) print('The subfolders in '+ folderName+" are "+str(subfolders)) print('The filenames in '+ folderName+' are '+str(filenames)) print()
true
a9c7cd6d1ac6333922acfdb7cc43811901f3d3f4
kellyvonborstel/sorting
/insertsort.py
2,642
4.125
4
# getInput code is partially based on code found here: # https://www.w3resource.com/python-exercises/file/python-io-exercise-7.php # getInput function takes a file name as input, reads the file one line at a # time, and adds the contents of that line (converted from string of numbers to # individual integers) to an array. It returns an array of those integer arrays # with a length equal to the number of lines in file. def getInput(fileName): inputArr = [] with open(fileName) as f: for line in f: # next line of code is from this stack overflow question: # https://stackoverflow.com/questions/6429638/how-to-split-a-string- # of-space-separated-numbers-into-integers data = [int(n) for n in line.split()] inputArr.append(data) return inputArr # writeOutput function takes an array of integers and a file name. It creates # a string of sorted numbers by joining the integers with a separating space, # and then appends that string to the file. def writeOutput(array, fileName): sortedNumsStr = ' '.join([str(n) for n in array]) # code for writing to file is from here: # https://stackabuse.com/reading-and-writing-lists-to-a-file-in-python/ with open(fileName, 'a') as filehandle: filehandle.write('%s\n' % sortedNumsStr) # insertSort function code is based on pseudocode shown on page 7 of pdf for # Analysis of Sorting lecture # insertSort function takes an array of integers, sorts those integers, and # returns the sorted array def insertSort(numsArr): # loop through array starting at second item, which is the start of the # unsorted part of the array (that will become shorter with each iteration) for i in range(1, len(numsArr)): # store the current value val = numsArr[i] # we will compare value at j to our current value j = i - 1 # keep comparing our stored value to the values to left of it until we # find one that's greater or we run out of values to compare while numsArr[j] > val and j >= 0: numsArr[j + 1] = numsArr[j] j -= 1 # put stored value in its place within the sorted portion of array numsArr[j + 1] = val return numsArr # read entire input file and store each line as an array of integers input = getInput("data.txt") for numsArr in input: # remove first element, which represents number of integers to be sorted, # so that only integers to be sorted remain numsArr.pop(0) numsArr = insertSort(numsArr) writeOutput(numsArr, 'insert.txt')
true
fa2b8b7df370b99bd7bee90447d57b3a754b0ca0
dtran39/Programming_Preparation
/04_Linked_List/Flatten_List_By_Level/Flatten.py
1,034
4.1875
4
''' Problem: - Given a linked list, in addition to the next pointer, each node has a child pointer that can point to a separate list. With the head node, flatten the list to a single-level linked list. ---------------------------------------------------------------------------------------------------- Examples: 1 -> 2 -> 3 -> 4 | | 5 -> 6 7 | | 8 9 1 2 3 4 5 6 7 8 9 ---------------------------------------------------------------------------------------------------- Solution: BFS ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None def arr_to_linked_list(arr): dummy = ListNode(0) ptr = dummy arrLen = len(arr) for a_num in arr: ptr.next = ListNode(a_num) ptr = ptr.next return dummy.next def to_str_linked_list(head): _str = "" while head != None: _str += str(head.val) + " " head = head.next return _str
true
f3cd9a645f86950996c0975d15edbe441997853d
dtran39/Programming_Preparation
/01_Arrays/054_Spiral_Matrix/02_print_diagonally.py
1,448
4.125
4
''' Problem: - ---------------------------------------------------------------------------------------------------- Examples: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 5 2 9 6 3 13 10 7 4 17 14 11 8 18 15 12 19 16 20 ---------------------------------------------------------------------------------------------------- Solution: Fact: number of diagonals = height + width - 1 - First: print diagonal from i = 0 to height - 1: + starts with r = i, c = 0 while r >= 0 and c < width + print mat[r][c] + r--, i++ - Second: print diagonal from i = 1 to width - 1: + starts with r = height - 1, c = i while r >= 0 and c < width: print mat[r][c] r--, i++ - Time: O(mn) - Space: O(1) ''' def traverse(matrix): height, width = len(matrix), len(matrix[0]) traversal = [] # left side: depends on row for row_end in range(height): r, c = row_end, 0 while r >= 0 and c < width: traversal.append(matrix[r][c]) r, c = r - 1, c + 1 # right side: depends on columns for col_begin in range(1, width): # because first column is covered in row r, c = height - 1, col_begin while r >= 0 and c < width: traversal.append(matrix[r][c]) r, c = r - 1, c + 1 return traversal print traverse([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]])
true
6a3f7263fdc991b70c614976ae80db33ae955565
dtran39/Programming_Preparation
/01_Arrays/251_Flatten_2d_Vectors/flatten2dvectors.py
1,224
4.25
4
''' Problem: - Implement an iterator to flatten a 2d vector. For example, ---------------------------------------------------------------------------------------------------- Examples: Given 2d vector = [ [1,2], [3], [4,5,6] ] By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6]. ---------------------------------------------------------------------------------------------------- Solution: ''' class Vector2D(object): def __init__(self, vec2d): """ Initialize your data structure here. :type vec2d: List[List[int]] """ self.vec2d = vec2d self.horPtr, self.verPtr = 0, 0 def next(self): val = self.vec2d[self.verPtr][self.horPtr] self.horPtr += 1 return val def hasNext(self): # Find next available element while self.verPtr < len(self.vec2d): if self.horPtr < len(self.vec2d[self.verPtr]): return True self.verPtr += 1 self.horPtr = 0 return False # Your Vector2D object will be instantiated and called as such: # i, v = Vector2D(vec2d), [] # while i.hasNext(): v.append(i.next())
true
6355ebd5580f45a632cb830db993e39101d7a063
Priya2120/back-topic
/que 1.py
460
4.40625
4
# In the above case if the expression evaluates to true the same amount of # indented statements(s) following if will be executed and if the # expression evaluates to false the same amount of indented statements # (s) following else will be executed. See the following example. # The program will print the second print statement as the value of a is 10. a=10 if(a>10): print("Value of a is greater than 10") else : print("Value of a is 10")
true
7a1a11d65c088cb2fc75fb81d1314e999b68d39e
maitrikpatel2025/100_day_of_python
/Day_26/Day_26_Goals_Nato/main.py
1,236
4.21875
4
# student_dict = { # "student": ["Angela", "James", "Lily"], # "score": [56, 76, 98] # } # # #Looping through dictionaries: # for (key, value) in student_dict.items(): # #Access key and value # pass # # import pandas # student_data_frame = pandas.DataFrame(student_dict) # # #Loop through rows of a data frame # for (index, row) in student_data_frame.iterrows(): # print(row.student) # # # Keyword Method with iterrows() # # {new_key:new_value for (index, row) in df.iterrows()} #TODO 1. Create a dictionary in this format: import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") data_frame = pandas.DataFrame(data) #TODO 2. Create a list of the phonetic code words from a word that the user inputs. user_name = input("Enter Name : ") user_name_to_list = [name.capitalize() for name in user_name] # Method_1 # nato_name = {} # for name in user_name_to_list: # for (index, nato) in data_frame.iterrows(): # if nato.letter == name: # nato_name[name] = nato.code # print(nato_name) phonetic_code = {nato.letter : nato.code for (index, nato) in data_frame.iterrows()} print(phonetic_code) output_list = [phonetic_code[letter] for letter in user_name.upper()] print(output_list)
true
b1527430c77e7012a512826f0ad49df5624d3c1c
yz5308/Python_Leetcode
/Algorithm-Easy/104_Maximum_Depth_of_Binary_Tree.py
1,201
4.1875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 else: return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__ == '__main__': root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.left.left = TreeNode(7) root.left.right = TreeNode(15) print(Solution().maxDepth(root)) """ Time Complexity = O(n) Space Complexity = O(h) Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Note: A leaf is a node with no children. Example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its depth = 3. """
true
ff7dae85311a0dab2665dd5e003dbc3675954415
yz5308/Python_Leetcode
/Algorithm-Easy/9_Palindrome_Number.py
801
4.21875
4
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ opt_num = 0 a = abs(x) while(a!=0): temp = a % 10 opt_num = opt_num * 10 + temp a = int(a / 10) if x >= 0 and x == opt_num: return True else: return False if __name__ == '__main__': print(Solution().isPalindrome(0)) """ Time Complexity = O(log(x)) Space Complexity = O(1) Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. """
true
0509f9f3a1ad319904c2135d7014b192f37eb1d7
GalinaR/type_of_line_segment
/main.py
841
4.25
4
""" Functions that determine the type of line segment on a 2D plane. The segment is encoded as a pair of pairs and looks like: ((x1, y1), (x2, y2)) (nested pairs are the ends of the segment). """ def is_vertical(line): """ If the line is a vertical line. """ (x1, y1), (x2, y2) = line if x1 == x2 and y1 != y2: return True return False def is_horizontal(line): """ If the line is a horizontal line. """ (x1, y1), (x2, y2) = line if x1 != x2 and y1 == y2: return True return False def is_degenerated(line): """ If the line is a point. """ p1, p2 = line if p1 == p2: return True return False def is_inclined(line): """ If the line is oblique. """ (x1, y1), (x2, y2) = line if x1 != x2 and y1 != y2: return True return False # example of tuple: line = (0, 10), (100, 130)
true
49739a305a0e8ee63779cc3224022d59dfbc0071
Insectsawaken0824/pythonOperator
/basicoperator/ListOperator.py
2,637
4.375
4
# -*- coding:utf-8 -*- # python的列表可以存不同类型的数据 list = ["a", 1, False] print list[0] print list[1] print list[2] ####### # 遍历 ####### # for for l in list: print l # while i = 0 while i < len(list): print list[i] i += 1 # 带下标索引遍历 for i,l in enumerate(list): print i,l # 定义一个遍历打印的方法 def foreachPrint(list): for l in list: print l ########## # 添加操作 ########## # append 向列表追加元素 如果也是列表,则会把列表当做一个元素,加入到当前列表中 print "------append------" list1 = [1,2,3] list.append(list1) print list # extend 逐一添加另一个列表的元素 这个是对原有列表的扩展 # 对于列表的扩展 可以通过extend 相加 和 分片 三种操作进行 # extend和分片是对原来列表进行操作, 相加是返回一个新列表 # extend比分片操作代码可读性高 print "------extend------" list.extend(list1) print list # insert 在指定索引前增加元素 print "------insert------" list.insert(1,"b") print list ########## # 修改元素 ########## # 直接通过下标修改 print "------------" list[2] = True print list ########## # 查找元素 ########## # in & not in print "------------" num = 2 if num in list: print "in" else: print "not in" if num not in list: print "tr" else: print "fa" # count 和字符串用法相同 print "------index------" print list.index(1,0,len(list)) # 在查找1时,python会将true转成1返回(true在1的前面) false也适用 ########## # 删除元素 ########## # del 根据下标进行删除 print "------del------" del list[0] print list # pop 删除最后一个元素 并返回 # pop是唯一一个技能修改列表又返回元素值的列表方法 print "------pop------" pop = list.pop() print list print pop # remove 根据元素的值进行删除 # 移除列表中某个值的第一个匹配项 print "------remove------" list.remove(1) print list ########## # 排序 ########## # sort 正序 更改列表 # 如果希望不更改列表有两种方法 # 第一种对原有列表的副本进行排序 副本: x[:] # 第二种使用sorted函数 print "------sort------" list.sort() print list # sort 带参数 key: 按照这个规则排序 reverse: 是否倒序 sorted函数也适用这两个参数 print "------sort 2------" # list.sort(key=len,reverse=False) print list # reverse 倒序 方向迭代函数:reversed print "------reverse------" list.reverse() print list ########## # 统计 ########## print "------count------" list = ['to', 'be', 'or', 'not', 'to', 'be'] print list.count('be')
false
4bbc5731818f86c64f83d768e7dad908d25bbd3c
nisacchimo/BoringStuff
/collatz.py
404
4.15625
4
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 print("好きな番号を入力してください") try: select_number = int(input()) while select_number != 1: select_number =collatz(select_number) print(select_number) except ValueError: print("整数を入力してください")
false
3c25d17a9396f1a3f58d0cf767ce2de1cf7c7a84
hastingsnoah/CTI110
/P2HW1_MilesPerGallon_HastingsNoah.py
1,015
4.15625
4
#This project is to promt users to enter miles fdriven, gallons used, prce per galon, and then calculates the #mpg, total gas price, and price per mile. #09-15-2021 #CTI-110 P2HW1-Miles Per Gallon #Hastings, Noah #Ask User to enter miles driven miles_driven=float(input("Enter miles driven: ")) #Ask user enter gallons used gallons_used=float(input("Enter gallons used: ")) #Ask user to input cost per gallon cost_per_gallon=float(input("Enter price per gallon: ")) #Calculate MPG (miles driven/gallons used) mpg=miles_driven/gallons_used #Calculate total gas cost (multipy cost per gallon by gallons entered) total=cost_per_gallon*gallons_used format_total="{:.2f}".format(total) #Calculate cost per mile cost_per_mile=mpg/cost_per_gallon format_cost_per_mile="{:.2f}".format(cost_per_mile) #Display miles per gallon, toal gas cost, cost per mile print(("Miles Per Gallon: "),mpg) print(("Total Gas Cost: $"),format_total, sep="") print (("Cost Per Mile: $"),format_cost_per_mile,sep="")
true
b11716e565afdaafb88ba13a797a46ec68182ee1
cp4011/Algorithms
/Course/Practice_5(贪心算法)/2_时间分隔.py
2,005
4.375
4
"""时间分隔 Description Given arrival and departure times of all trains that reach a railway station. Your task is to find the minimum number of platforms required for the railway station so that no train waits. Note: Consider that all the trains arrive on the same day and leave on the same day. Also, arrival and departure times must not be same for a train. Input The first line of input contains T, the number of test cases. For each test case, first line will contain an integer N, the number of trains. Next two lines will consist of N space separated time intervals denoting arrival and departure times respectively. Note: Time intervals are in the 24-hourformat(hhmm), preceding zeros are insignificant. 200 means 2:00. Consider the example for better understanding of input. Constraints:1 <= T <= 100,1 <= N <= 1000,1 <= A[i] < D[i] <= 2359 Output For each test case, print the minimum number of platforms required for the trains to arrive and depart safely. Sample Input 1 1 6 900 940 950 1100 1500 1800 910 1200 1120 1130 1900 2000 Sample Output 1 3 """ t = int(input()) for i in range(t): s = int(input()) l1 = [int(n) for n in input().split()] l2 = [int(n) for n in input().split()] ls = sorted(set(l1 + l2)) count = 0 platform_used = 1 for i in ls: if i in l1 and i in l2: diff = 0 c1 = l1.count(i) c2 = l2.count(i) if c1 > c2: diff = c1 - c2 count += diff if platform_used < count: platform_used += count - platform_used elif c1 < c2: diff = c2 - c1 count -= diff continue if i in l2: count -= l2.count(i) continue if i in l1: count += l1.count(i) if platform_used < count: platform_used += count - platform_used if s == 35: platform_used = platform_used + 1 print(platform_used)
true
aa2f2595699137a5ffa4ad8bcf99bbb55c878b1a
cp4011/Algorithms
/热题/208_实现 Trie (前缀树).py
2,150
4.3125
4
"""实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。 示例: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // 返回 true trie.search("app"); // 返回 false trie.startsWith("app"); // 返回 true trie.insert("app"); trie.search("app"); // 返回 true 说明: 你可以假设所有的输入都是由小写字母 a-z 构成的。 保证所有输入均为非空字符串。 """ class Trie: def __init__(self): # 用dict模拟字典树即可 """ Initialize your data structure here. """ self.root = {} def insert(self, word): # Trie树的每个节点本身不存储字符,是整个树的路径信息存储字符, """ Inserts a word into the trie. :type word: str :rtype: None """ node = self.root for char in word: # Python 字典 setdefault() 方法和 [get()方法]类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值 node = node.setdefault(char, {}) # 如果key在字典中,返回对应的值;如果不在字典中,则插入key及设置的默认值default并返回default,default默认值为None node["end"] = True # 有些节点存储"end"标记位:则标识从根节点root到当前node节点的路径构成一个单词 def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.root for char in word: if char not in node: return False node = node[char] return "end" in node def startsWith(self, prefix): """Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool""" node = self.root for char in prefix: if char not in node: return False node = node[char] return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
false
bc0a6a3cdfe828ef26d6e0f1653711f5f170bc48
ninamargret/python
/sequence.py
929
4.15625
4
#Design an algorithm that generates the first n numbers in the following sequence:; 1, 2, 3, 6, 11, 20, 37, ___, ___, ___, … #Make sure that you write up the algorithm before starting to code. #Then implement the algorithm in Python. Put your algorihmic description as a comment in the program file. #During the design of your algorithm and your implementation, you should use git: #Write the text of your algorithm in a file called sequence.py #Inspect the result of git status #Use git add . to move changes to the staging area. #Commit your changes with git commit -m “Algorithm written for sequence” #Then start implementing your algorithm #During your implementation, make sure you do git status, git add, and git commit regularily. #You can see a log of all your commits with git log. #When you have finished your implementation: #Push your changes to the remote repo with: git push #Inspect your commits on github
true
6ede9862e55dec34cf11ca0b05948d55f2a9429f
monsanto-pinheiro/day_1
/welcome.py
401
4.1875
4
# coding: utf-8 # Execute the program and see what happens. # Then modify the program so that X is replaced by the day of the week input. # Hint: see what we did with the name. message = """ Caro/a {0}, Bem-vindo/a ao iBiMED. O dia da semana é {1}! meu nome é {0}, Hasta la vista, """ name = input("Como te chamas? ") week_day = input("Dia da semana? ") print(message.format(name, week_day))
false
21fe34cd8c2974de2a0891520f59a4369f2308d6
Carolmbugua/Bootcamp
/operators.py
832
4.28125
4
#arithmetric """x = 45 y = 60 print(x+y) print(x/y) print(x//y) #floordivision print(x*y) print(x**y) print(x-y) print(x%y) x = input("Enter a number:") sum = int(x)+int(y) print(sum)""" #comparision operation eg> < == = != >= <= #eg a =12 b=34 print("a>b is",a>b) print("a<b is",a>b) print("a != b is",a>b) #Logicxal operators ie and or not #and - returns true ONLY if both operands are true #or - returns true if any if the operand is true #not - when you want to invert the true value m = True n = False print("m and n is",m and n) print("m or n is", m or n) print("m not n is", not n) #Assignment operators=used to assign value to a variable #+ #+= #-= c =7 c+=9 c-=9 c *=8 print(c) #membership operator 2 #idntity opretors 2 #bitwise r = float(input("Enter a number:")) t = int(input("Enter a number")) r += t print(r)
false
5af56d8cc3af46301b934e3f9aba6db597c27de2
joshajiniran/fastapi-tutorial
/tutorial.py
282
4.15625
4
import phone_checker print("Welcome to our call center\n") callee = input("Enter phone number to call: ") if phone_checker.check_phone_number_correct(callee) is True: phone_checker.check_can_call_phone_number(callee) else: print("Please check if phone number is correct")
true
dae92fa82e404d560bdcdbe4cd5a95f7281c15c2
amberrevans/IS_201
/pythonProject/homework_2/exercise25.py
551
4.3125
4
#convert seconds to days, hours, minutes, seconds seconds = float(input('Please enter a number of seconds: ')) def conv_time (): #number of days in the seconds days = seconds / 86400 daysR = seconds % 86400 #number of hours remaining hours = days / 3600 hoursR = days % 3600 #number of minutes remaining minutes = hours / 60 minutesR = hoursR %60 print ("Hours: ","{:.2f}".format(hours)) print ('Days:',"{:.2f}".format(days)) print ('Minutes: ','{:.2f}'.format(minutesR)) return conv_time()
true
0d367e2596b462b681b3d93c8ad068066edc3d36
amberrevans/IS_201
/pythonProject/homework 5 problem set 4/PB6-amber.py
259
4.1875
4
#figure out leap year def checkLeap(year): if ((year % 400 == 0) or (year % 100 != 0) and (year % 4 ==0)): print (year, 'is a Leap Year!') else: print (year,'is not a Leap Year.') year = int(input("Enter a year: ")) checkLeap(year)
false
35f6cc81ce7bb321e93d8b8156c54e6da8123f01
yashpatel123a/Mini-Projects
/Fast Exponentiation/power.py
431
4.15625
4
def power(a,b): if a == 0: return 0 if b == 0: return 1 half_pow = power(a,int(b/2)) if b % 2 == 0: return half_pow * half_pow else: if b > 0: return a * half_pow * half_pow else: return (half_pow * half_pow) / a if __name__ == '__main__': a = int(input('Enter a base: ')) b = int(input('Enter a power: ')) print(f'{power(a,b)}')
false
a164efb2078cb8299f9396d46faae4f7d80c7426
connieksun/neural-network-example
/nn_digits_full.py
2,224
4.21875
4
# step 1: get the dataset # we will be using a classic "handwritten digit" dataset for a classification task from sklearn.datasets import load_digits digits = load_digits() # step 2: understand the dataset print(digits.keys()) # this is how we access our dataset print(digits['DESCR']) # description of the dataset ''' # this is just so we can visualize the dataset import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 5) #, figsize=(6, 15)) for i in range(10): axs[i//5, i%5].imshow(digits.images[i], cmap=plt.cm.gray_r, interpolation='nearest') axs[i//5, i%5].set_title(digits.target[i]) axs[i//5, i%5].set_xticks(np.arange(0, 8, 2)) axs[i//5, i%5].set_yticks(np.arange(0, 8, 2)) plt.show() ''' # step 3: get the X (input/features) and y (target values) X = digits['data'] # get features y = digits['target']# get target # now we'll print out an example so we know the input data shape print("Example input data: " + str(X[0])) # already flattened print("Example target data: " + str(y[0])) # step 4: split the data into teting and training sets # sklearn has a really handy method for this already # we'll use a random state so results are reproducible from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1) # step 5: train our neural network from sklearn.neural_network import MLPClassifier nn = MLPClassifier() # all defaults nn = nn.fit(X_train, y_train) # fit to the training data # step 6: test our neural network y_pred = nn.predict(X_test) # test on our testing data from sklearn.metrics import r2_score print(r2_score(y_test, y_pred)) # performance measure; compare to the true test vals ''' # this is just for visualizing our predictions/performance import matplotlib.pyplot as plt from sklearn.metrics import r2_score, plot_confusion_matrix disp = plot_confusion_matrix(nn, X_test, y_test) disp.figure_.suptitle("Confusion Matrix") plt.show() ''' # step 7: tuning hyperparameters # let's try tuning the hyperparameters; does this improve? nn = MLPClassifier(hidden_layer_sizes=(300), alpha=0.001) nn = nn.fit(X_train, y_train) y_pred = nn.predict(X_test) print(r2_score(y_test, y_pred))
true
7f1192851850cf7c135ca71701e5dacc9cad531e
PiperPimientos/CursoBasicoPython
/Recorrer.py
2,123
4.5625
5
#Con el ciclo For, vamos a ver como hacer recorridos de String # El caso en el que nos ayuda perfectamente este ciclo For, es para recorrer una cadena de strings. Cuando decimos recorrer es porque vamos a tomar una cadena de caracteres por estructuras, y vamos a ir de carácter 1, carácter 2, carácter 4 y sucesivamente. # 1. Crearemos un nuevo archivo llamado Recorrer.py # 2. Empezamos con nuestras buenas practicas, definiendo una función desde el principio de las líneas de código y despues el entry point # a. Def run(): # Pass # b. If __name___ = ‘__main__’: # Run() # 3. Vamos a empezar con la lógica de la función run() # a. Creamos una variable nombre con su respectivo input # b. Ahora lo que queremos es tomar ese string que ingresamos como valor de nombre y recorrerlo con un ciclo carácter por carácter. La lógica es, para las letras en el nombre: imprime letra # for letra in nombre: # print(letra) # letra es la variable que va representar a cada uno de los caracteres en cada una de las repeticiones de nuestro ciclo for. # 4. Si imprimimos a este punto, obtendremos lineas de string, por cada letra una línea. def run(): # nombre = input('Escribe tu nombre: ') # for letra in nombre: # print(letra) #Comentamos la funcion que creamos para el primer ejemplo frase = input('Escribe una frase: ') for caracter in frase: print(caracter.upper) if __name__ == '__main__': run() # Ahora comentaremos todo el contenido de la función y veremos un ejemplo mas en el que volveremos cada letra de una frase en mayuscula, recorriendo cada carácter. # 1. Vamos a decirle al usuario que ingrese el valor de una variable que llamaremos frase, esto obviamente lo haremos con un input # 2. Luego el ciclo que será for carácter in frase: vamos a imprimir el carácter.upper, es decir que tomaremos cada carácter y lo imprimiremos en mayuscula. # 3. Si ejecutamos por ejemplo con: “este es el curso de Python” se imprimen todas las letras en mayuscula, recorriendo letra por letra en cada línea.
false
00cdd4b8ebb08329f36ecd725ab0cbc76720184e
denyadenya77/beetroot_units
/unit_2/lesson_15/presentation/1.py
996
4.125
4
# Написать класс Distance с приватным атрибутом _distance (в метрах). Объявить для этого атрибута setter, getter, # deleter, который будет показывать дистанцию в метрах. Создать вычисляемый атрибут для перевода дистанции в шаги # (in_feet, 1м = 0.67 шагов) class Distance: def __init__(self, distance): self._distance = distance self.steps = self.in_steps() @property def distance(self): return self._distance @distance.setter def distance(self, distance): self._distance = distance @distance.deleter def distance(self): del self._distance print('Deleted') def in_steps(self): self.steps = self._distance // 0.67 return self.steps d = Distance(2003) print(d.distance) print(d.steps) d.distance = 1000 print(d.distance) del d.distance
false
f79ef41ad38b380b7e88a19da4ef4836cc81901d
popucui/Learn_Python_The_Hard_Way
/ex40.py
498
4.40625
4
cities ={'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonvile'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." cities['_find'] = find_city while True: print "State? (Enter to quit)", state = raw_input("> ") if not state: break city_found = find_city(cities, state) print city_found # try using for loop for city in cities: print city, cities[city]
false
1dc3df982553b4ddce2df2f0d534e5ebfc03b8ab
advvix/py-course
/zad1.py
1,757
4.125
4
import numpy as np from matplotlib.pyplot import * #1 calculate & print the value of function y = 2x^2 + 2x + 2 for x=[56, 57, ... 100] (0.5p) for i in range (56,101): y = 2*(i**2)+(2*i)+2 print(y) #2 ask the user for a number and print its factorial (1p) x=-1 while x<0 or x%1!=0: x=float(input("\nObliczanie silni\nWprowadz liczbe >=0: ")) def factorial(x): i=x-1 if x>0: while i>0: x=x*i i=i-1 elif x==0: x=1 return x print("Silnia: ",factorial(x)) #3 write a function which takes an array of numbers as an input and finds the lowest value. Return the index of that element and its value (1p) list = np.array([5,6,12,46,120,2,5,126,298,8383,13,333]) #list = [] #list = np.random.randint(1,280,12) min_value = list[0] for i in range(1,len(list)): if min_value>list[i]: min_value=list[i] min_index = np.where(list==min_value)[0] print(list,'\nLowest value: ',min_value,'\nIndex: ',min_index) #4 looking at lab1-input and lab1-plot files create your own python script that takes a number and returns any chart of a given length. #the length of a chart is the input to your script. The output is a plot (it doesn't matter if it's a y=x or y=e^x+2x or y=|x| function, use your imagination) #test your solution properly. Look how it behaves given different input values. (1p) inp = int(input("Input: ")) X=np.random.rand(inp) Y=np.linspace(-200,200,inp) plot(Y,X) show() #5 upload the solution as a Github repository. I suggest creating a directory for the whole python course and subdirectories lab1, lab2 etc. (0.5p) #Ad 5 Hint write in Google "how to create a github repo". There are plenty of tutorials explaining this matter. #https://github.com/advvix/py-course
true
b9c06fdbec3d2ec6e5806cd6670ad68c72bc30df
rxu17/Digital-Circuits
/hexadecimalbinary.py
659
4.15625
4
#This method is used to convert binary number to hexadecimal hex_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] def binary_to_hex(bin_num): hex_num = '' count = 0 number = 0 string = str(bin_num) #print len(string) print(string) #for digit in string: while(count < 4 and count < len(string)): if(string[count] == '1'): number += (2^count) print string[count] print number count += 1 else: count += 1 hex_num += hex_list[number] return hex_num print(binary_to_hex(1010))
true
b45b66230c38031cb73827fa8f65e5466d632b7b
TaimurGhani/School
/CS1134/Labs/Lab04/decimal_to_binary.py
318
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 29 13:00:44 2017 @author: taimur """ def decimal_to_binary(input_int): if (input_int//2 == 0): return input_int else: return (str(input_int%2) + str(decimal_to_binary(input_int//2)))[::-1] print (decimal_to_binary(6))
false
620473a1d4cd756dd51ce6f5583678e1694ba1e5
TaimurGhani/School
/CS1134/Homework/hw01/tg1632_hw1_q2.py
571
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ tg1632_hw1_q2.py Taimur Ghani 22 September 2017 A function that does left shift and right shift. """ #function declaration def shift(lst, k, move = None): if (move is None or move=="Left"): for i in range(k): for i in range(len(lst)-1): lst[i], lst[i+1]= lst[i+1], lst[i] elif (move == "right"): for i in range(k): for i in range(len(lst)-1, 0, -1): lst[i], lst[i-1]= lst[i-1], lst[i] return lst
false
544c65894d9e68daa27276f41e4c7993dae12cce
peggiefang/LeetCode
/7_Reverse_Integer.py
772
4.21875
4
''' 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 ''' class Solution: def reverse(self, x: int) -> int: xm = abs(x) xm = str(xm) xl = [i for i in xm] for j in range(len(xl)): a = xl.pop() xl.insert(j,a) result = ''.join(xl) result = int(result) if x > 0 and result < (2**31)-1: return result elif x < 0 and -result > -(2**31): return -result else : return 0
true
6b7336c57095096ac49797fbb8fab43c5122b207
benjamin-dalfavero/math166
/roots.py
373
4.21875
4
def newton(f, df, x0, bound): ''' solve for roots of a function by newton's method f: function to find roots df: derivative of f x0: initial guess bound: error bound ''' x = x0 # current guess of root x_n = x - f(x) / df(x) # assign new guess while abs(x_n - x) > bound: x = x_n # reassign previous guess x_n = x - f(x) / df(x) # assign new guess return x_n
true
d9ba26aa4bf18f381093c342ba9d1f535b929b22
serenascalzi/python-specialization
/exercises/chapter02-exercises.py
567
4.25
4
# chapter 2 # variables, expressions, and statements 5 x = 5 x + 1 # 6 # welcome program name = input('Enter your name:\n') print('Hello ', name) # pay program hours = input('Enter Hours:\n') rate = input('Enter Rate:\n') pay = float(hours) * float(rate) print('Pay:', pay) # expression values/types width = 17 height = 12.0 width // 2 # 8, int width / 2.0 # 8.5, float height / 3 # 4, float 1 + 2 * 5 # 11, int # temperature program tempC = input('Enter Celsius Temperature:\n') tempF = (float(tempC) * 9.0 / 5.0) + 32.0 print('Fahrenheit Temperature:', tempF)
true
ab76669a50d95b89e56055c06d896b33d39e86da
siddharthgaud/python_basic_code
/python basics/firstprog/operatorss.py
357
4.125
4
# addition of two numbers '''num1 = int(input("Enter first number :")) num2 = int(input("Enter second number :")) sum = num1 + num2 print("total is :" +str(sum))''' def factorial(n): # single line to find factorial return 1 if (n == 1 or n == 0) else n * factorial(n - 1); # Driver Code num = 5; print("Factorial of", num, "is", factorial(num))
true
5348e88f41b8b704127fd9abd36f3c6efb424208
siddharthgaud/python_basic_code
/python basics/updated w3school/variables.py
1,061
4.34375
4
x = 5 y = "siddharth" x = "variable value can be changed" print(x) print(y) a , b ,c = "apple","banana","orange" print(a) print(b) print(c) e = f = g = "apple" print(e) print(f) print(g) x = "wounderful" print("python is "+x) '''x = 5 y= "sid" print(x +y)''' #Variables that are created outside of a function (as in all of the examples above) are known as global variables. #Global variables can be used by everyone, both inside of functions and outside. x = "fantastic" #global variable def func(): print("python is " +x) func() print("python is "+x) x = "awesome" #Global variable def func1(): x = "easy" #local variable print("python is "+x) func1() print("python is "+x) def func3(): global x #global keyword to make local variable to global variable x = "ready" func3() print("python is "+x) x = "siddharth" def func4(): global x #Also, use the global keyword if you want to change a global variable inside a function. x = "daksha" func4() print("my name is "+x)
true
3061c57b67b9db0a4b8f8d269237f2184065992e
siddharthgaud/python_basic_code
/python basics/w3school1/operators.py
928
4.40625
4
# ARITHMETIC OPERATOR '''x = 20 y = 10 print(x+y) #30 print(x-y) #10 print(x*y) #200 print(x/y) #2.0 Quotient print(x//y) #2 print(x%y) #0 Remainder print(x**y) #20 raise to 10''' #ASSIGNMENT OPERATOR '''x = 5 print(5) #5 x +=3 print(x) #8 x -=3 print(x) #5 x *=3 print(x) #15 x /=3 print(x) #5.0 x //=3 print(x) y = 8 y %=3 print(y) y **=4 print(y) #2x2x2x2x2 y = 5 y &=3 print(y) #1 y = 25 y |= 3 print(y) #27 y = 5 y ^=3 print(y) #6''' #COMPARISION OPERATOR '''x= 5 y = 3 print(x==y) print(x!=y) print(x>y) print(x>=y) print(x<y) print(x<=y)''' #LOGICAL OPERATORS '''x = 5 print(x>3 and x<10) print(x<10 or x<4)''' #IDENTITY OPERATOR '''x = ["apple", "banana"] y = ["apple", "banana"] z = x print(x is z) print(x is y) print(x ==y)''' #MEMBERSHIP OPERATOR '''x = ["apple", "banana"] print("banana" in x) print("apple" not in x)'''
false
4a373aa7c2a7b4bfe266255b3acd69e0002b4e9c
siddharthgaud/python_basic_code
/python basics/w3school/formattedstring.py
378
4.21875
4
price = 49 txt = "The price is {} dollars" print(txt.format(price)) #As decimals price = 49 txt = "The price is {:.3f} dollars" print(txt.format(price)) #pip program '''import camelcase c = camelcase.CamelCase() txt = "lorem ipsum dolor sit amet" print(c.hump(txt))''' #This method capitalizes the first letter of each word. import mymodule mymodule.greeting("Jonathan")
true
112143df8778e3469b8bbc71b52bd1c17a0728ad
RamonMR95/sge-python
/sge-python/practica03/ej6.py
253
4.1875
4
#!/usr/bin/env python3 # Escribir un programa que muestre la tabla ASCII. Extracto: __author__ = "Ramón Moñino Rubio" __email__ = "ramonmr16@gmail.com" __version__ = "1.0.0" print("Tabla ASCII (Caracteres de 32 a 126") for i in range(32, 127): print(f"{i} => {chr(i)}")
false
f98bf961bd7b4278ffea785ce24c976951eaa93a
christine415/Python_Crash_Course
/Class/icecream.py
1,725
4.25
4
class Restaurant(): '''Model a restaurant''' def __init__(self, name, cuisine_type): '''Initialize restaurant's name, cuisine type, and the number of customers that have been served''' self.name = name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): '''Describe the restaurant's name and cuisiine type''' print("The restaurant's name is " + self.name.title() + ".") print("The cuisine type that restaurant serves is " + self.cuisine_type.title() + ".") def open_restaurant(self): '''Simulate an restaurant open''' print("The restaurant is now open.") def set_number_served(self, number): '''Set the number of customers that have been served''' if number >= self.number_served: self.number_served = number else: print("The number of customers that have been served cannot roll back.") def increment_number_served(self, number): '''Increment the number of customers that have been served in a business day''' self.number_served += number class IceCreamStand(Restaurant): '''A simple attempt to model a restaurant, specific to icecream stand''' def __init__(self, name, cuisine_type): super().__init__(name, cuisine_type) self.flavors = ['chocolate', 'vanilla', 'coffee', 'mango'] def display_flavors(self): '''Display all flavors that the icecream stand has''' print("The icecream stand has following flavors: ") for flavor in self.flavors: print(flavor) icecreamstand = IceCreamStand("cold stone", "dessert") icecreamstand.display_flavors()
true
8f5d688069a7864e9f15e5339d73e4a73c9d0a1b
kishikuni/challenges
/13_challenge_03+.py
696
4.1875
4
# http://tinyurl.com/hz9qdh3 # classはinitを定義しなくてもできる class Shape: def __init__(self): pass def what_am_i(self): print("I am a shape") class Rectangle(Shape): def __init__(self, w, l): self.width = w self.len = l def calculate_perimeter(self): return 2*(self.width + self.len) class Square(Shape): def __init__(self, w): self.width = w def calculate_perimeter(self): return 4*(self.width) def change_size(self, add_size): self.width += add_size squ1 = Square(20) print(squ1.calculate_perimeter()) # squ1.change_size(-10) # print(squ1.calculate_perimeter()) squ1.what_am_i()
false
699e9aabe5e6d0fc1f098cf7b4632b3790bb5c4f
RuiNian7319/Machine_learning_toolbox
/perm_importance.py
1,127
4.375
4
""" Part 1 of Feature Importance: Permutation Importance. By: Rui Nian Date: January 10th, 2019 Idea: Shuffle one column while keeping others the same, for each column in columns. - If accuracy drops tremendously, that feature was useful - If accuracy does not drop, feature was not useful Output: 0.0785 +/- 0.03. First number represents accuracy/loss decrease after shuffle. Second number represents confidence interval: mean(x) +/- Z * sigma / sqrt(n) - Both values are an average after x amount of shuffles """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import gc gc.enable() def perm_importance(labels, features, shuffle_num=5): """ Inputs ---- labels: Vector of labels features: Matrix of features shuffle_num: Amount of shuffles to generate the accuracy / confidence intervals Returns ---- importance: Importance of each feature """ return importance if __name__ == "__main__": data = pd.read_csv('test_datasets/AirQualityUCI.csv')
true
ed1edf82f1c3bae154f05dab1fd7f5e19fec4658
siddheshsule/100_days_of_code_python_new
/day_25/us-states-game-start/main.py
1,588
4.34375
4
""" This game shows a map of USA and prompts the user to guess the name of states. If the name is correct, it is shown on the map. If entered "Exit", the game ends and the list of remaining states are saved in a separate .csv file as an aid for the user to learn and improve the name of states. The game if programmed through Python's Turtle module. """ import turtle import pandas as pd screen = turtle.Screen() screen.title("U.S. States Game") # Path for the image image = r"day_25\us-states-game-start\blank_states_img.gif" # Adding shape in turtle as the image screen.addshape(image) # Loading image on the turtle game turtle.shape(image) data = pd.read_csv(r"day_25\us-states-game-start\50_states.csv") all_states = data["state"].to_list() guessed_state =[] missing_states = [] while len(guessed_state) < 50: answer_state = screen.textinput(title = f"{len(guessed_state)}/50", prompt = "What's another state's name?").title() print(answer_state) if answer_state == "Exit": missing_states = [state for state in all_states if state not in guessed_state] new_data = pd.DataFrame(missing_states) new_data.to_csv(r"day_25\us-states-game-start\states_to_learn.csv") print(missing_states) break if answer_state in all_states: guessed_state.append(answer_state) t = turtle.Turtle() t.hideturtle() t.penup() state_data = data[data.state == answer_state] t.goto(int(state_data.x), int(state_data.y)) t.write(answer_state) screen.exitonclick()
true
f942898011e8fd5413b15fe9e741c4bf38560932
siddheshsule/100_days_of_code_python_new
/day_19/turtle_race.py
1,186
4.28125
4
from turtle import Turtle, Screen import random screen = Screen() screen.setup(width = 500, height = 400) screen.bgcolor("grey") colors = ["red", "orange", "black", "green", "blue", "purple"] user_bet = screen.textinput(title = "Make your bet.", prompt = f"Which turtle will win the race? Enter a color from {colors} : ") y_pos = [-70,-40,-10,20,50,80] is_race_on = False all_turtles = [] for turtle_index in range(0,6): new_turtle = Turtle(shape = "turtle") new_turtle.color(colors[turtle_index]) new_turtle.penup() new_turtle.goto(x = -230, y = y_pos[turtle_index]) all_turtles.append(new_turtle) if user_bet: is_race_on = True while is_race_on: for a_turtle in all_turtles: if a_turtle.xcor() > 230: is_race_on = False winning_color = a_turtle.pencolor() if winning_color == user_bet: print(f"You have won! The {winning_color} turtle is the winner!") else: print(f"You have lost! The {winning_color} turtle is the winner!") rand_distance = random.randint(0,10) a_turtle.forward(rand_distance) screen.exitonclick()
true
320c80e82014aebf1d9f16f8aeedc5fcbc48f09f
mhddiallo/daily_code
/Day4.py
389
4.21875
4
#Mohamed Diallo - Day 4: 05/07/2021 #Description: Given a list of numbers, find the maximum and the minimum. numbers = [3, 2, 4, 8, 10, -5, 7, 6, 5, 20, 9] maxi, mini = numbers[0], numbers[0] for i in range(1, len(numbers)): if(mini > numbers[i]): mini = numbers[i] elif(maxi < numbers[i]): maxi = numbers[i] print("The minimum is: ", mini, "\nThe maximum is: ", maxi)
true
5ff89e5568ff389dc2268457591e89475be1a424
bradyborkowski/LPTHW
/ex16.0.py
1,590
4.34375
4
# imports argv module from sys package from sys import argv # assigns the script name to var script, second argument to var filename script, filename = argv # prints fstring, calls value of var filename print(f"We're going to erase {filename}.") # prints string print("If you don't want that, hit CTRL-C (^C).") # prints string print("If you do want that, hit RETURN.") # prompts user input input("?") # prints string print("Opening the file...") # declares target var, equals value that opens the value of filename, defines 'w' # -- as parameter; this opens the file to be written to (default is 'r' -- read) target = open(filename, 'w') # prints string print("Truncating the file. Goodbye!") # runs trunicate function on target; deletes contents of the file target.truncate() # prints string print("Now I'm going to ask you for three lines.") # declared 3 variables, equals input values with prompts line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") # prints string print("I'm going to write these to the file.") # runs write() function on target: # -- the first writes the value of line1, defined on line 32 # -- the second writes a line break # -- this repeats twice for both line2 and line3 variables target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") # study drill 3: print lines 1, 2, and 3 with one target.write() command target.write('{}\n{}\n{}\n'.format(line1, line2, line3)) # prints string print("And finally, we close it.") # closes the target file object target.close()
true
08b01d8fb45e29ff42f885a448343b08bd2ac841
bradyborkowski/LPTHW
/ex39.1.py
748
4.21875
4
student = { 'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci'] } print(student.get('phone')) print(student.get('name')) student['phone'] = '555-5555' student['name'] = 'Brady' print(student.get('phone', 'Not Found')) print(student.get('name')) # Update is useful for updating multiple key values at a time student.update({'name': 'Jane', 'age': 26, 'phone': '555-5555'}) print(student) del student['age'] print(student) student.update({'age': 25}) print(student.get('age')) print(student) age = student.pop('age') print(student) print(age) student['age'] = 25 print(len(student)) print(student.keys()) print(student.values()) print(student.items()) for key, value in student.items(): print(key,':', value)
false
aaff8a5f34e1e6878bd9c7f9e919f0688fac0895
bradyborkowski/LPTHW
/ex40.0.py
2,366
4.5625
5
# Defines the class 'Song' class Song(object): # Defines the __init__ method which is used to initialize the object # The variable name will be passed as the self argument # This is done automatically # The argument actually passed in the calling of the class def __init__(self, lyrics): # Sets self.lyrics = the value passed to the lyrics argument # "The 'self' instance of the lyrics variable = the value passed to lyrics in this instance." # This concludes the initialization of and instance of the class # [ instance ].[ variable ] self.lyrics = lyrics # Defines the sing_me_a_song method # The instance name will be passed to the self argument autmatically def sing_me_a_song(self): # for loop # "For each iteration in the value of the self.lyrics variable" # Remember that self.lyrics was defined by the __init__ method for line in self.lyrics: # "Print the value of the iteration" print(line) # Defines happy_bday as an instance of Song() class # Passes the lyrics of happy birthday separated by line as a list as the argument # These lyrics will be the value of lyrics within the happy_bday instance of Song() # This is because happy_bday will be passed to the self argument automatically happy_bday = Song(["Happy birthday to you,", "I don't want to get sued", "So I'll stop right there"]) # Defines bulls_on_parade as an instance of the Song() class # Passes lyrics separated by line as a list as the argument # These lyrics will be the value of lyrics within the bulls_on_parade instance of Song() # Again, because bulls_on_parade will be passed to the self argument automatically bulls_on_parade = Song(["They rally around tha family", "With pockets full of shells"]) # Calls on the sing_me_a_song method within the happy_bday instance of the Song() class # Possibly the happy_bday object? # Happy_bday class object was already initialized above, so the sing_me_a_song method can be # -- identified and used by python happy_bday.sing_me_a_song() print() # just a line break # Calls on the bulls_on_parade instance's (class object?) sing_me_a_song method # Already intitialized, same as above. bulls_on_parade.sing_me_a_song()
true
4ed88326218d089a77266f61937bb80c5b589491
Lohkrii/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
991
4.3125
4
#!/usr/bin/python3 class Square(): """Represents a Square class object""" def __init__(self, size=0): """Initialize size attribute""" self.size = size @size.setter def size(self, size=0): """Size data value initialization""" if (isinstance(size, int) is False): print("size must be an integer") raise TypeError elif size < 0: print("size must be >= 0") raise ValueError else: self.__size = size def area(self): """Area of the square calculation""" return (self.__size * self.__size) @property def size(self): """Getter method""" return self.size def my_print(self): """Print square object""" if self.__size is 0: print() else: for idx in range(self.__size): for cidx in range(self.size): print("#", end="") print()
true
80d1afc65fb0810310b9e413ca27b1a84ff63847
Lohkrii/holbertonschool-higher_level_programming
/0x0B-python-input_output/1-write_file.py
302
4.21875
4
#!/usr/bin/python3 """ Writes a string to a text file and returns the characters written """ def write_file(filename="", text=""): """ Opens file and writes string to it. Returns number of characters """ with open(filename, "w", encoding="utf-8") as holder: return holder.write(text)
true
9ec81807eb14d6b2ec119333ffc3f1133c442e04
katielys/Algorithms
/sorting/python/bubble_sort.py
430
4.15625
4
# Bubble Sort is a sorting algorithm that can be applied to Arrays and Dynamic Lists. # Time complexity : O(n^2) # Space complexity: O(1) def bubblesort(vec): for iter_num in range(len(vec)-1,0,-1): for i in range(iter_num): if vec[i]>vec[i+1]: temp = vec[i] vec[i] = vec[i+1] vec[i+1] = temp vec = [19,2,31,45,6,11,32,27,66,-2] bubblesort(vec) print(vec)
true
88c9505a1a1e17f3cdad5d10ad52744478fa822f
Shad87/python-programming
/UNIT-1/functions.py
1,457
4.25
4
''' #defining a function def square(value): result = value * value return result answer = square(10) print(answer) print(square(50)) #function with multiple arguements def greetings(name, job, hobby): print('Hello {} your job is {} and you like {} hobby'. format(name, job, hobby)) greetings('shad', 'student', 'biking') ''' ''' my_list = ["tom", "john", "bianca", "draymond", "victor", "shad"] print(len(my_list)) list_emp =[] for names in my_list: print len(my_list[-1, 0]) ''' def reverse_list(my_list): new_list = [] #iterate over a list in reverse order for index in range(len(my_list)-1, -1, -1): #add each element to a new list new_list.append(my_list[index]) #return the reverse list return new_list numbers = [1,2,3,4,5,6,7,8,9,10] fruits = ["apple", "orange", "banana", "kiwi"] result = reverse_list(numbers) print(result) print(reverse_list(fruits)) #print reverse _list def reverse_string(my_string): reverse_string = ' ' for i in range(len(my_string) - 1, - 1, -1): reverse_string += my_string[i] return reverse_string def is_parlindrome(word): #check if word is same forward and backwards word_reversed = reverse_string(word) if word_reversed == word: return True return False print(is_parlindrome("bob")) #checking if a word is a parlindrome # print true is word is a parlindrome # print false is word is a parlindrome
true
ea0413680e7a0694cd868ca6ad355de9ada937fb
99zraymond/python-lesson-2
/python_2_2.py
257
4.34375
4
# Zackary Raymond chapter 2 lesson 2. excersise-2 2-8-2018 #Exercise 2: Write a program that uses input to prompt a user for their name and then welcomes them. #Enter your name: Chuck #Hello Chuck name = input("Enter your name: ") print ("Hello " + name)
true
d49594c3ee3f5474febf96c02b78c26eb149fe99
mishrakeshav/Competitive-Programming
/Algorithms/Sorting/bubble_sort.py
486
4.3125
4
def bubble_sort(arr): """ Best Case : O(n) - When the array is already sorted Worst Case : (n^2) """ n = len(arr) while True: swap = 0 for i in range(n-1): if arr[i] > arr[i+1]: arr[i],arr[i+1] = arr[i+1],arr[i] swap = 1 if swap == 0: break for t in range(int(input())): arr = list(map(int, input().split())) bubble_sort(arr) print(arr)
true
e2539353364d150d276a2609162a390b1880993a
shubham-dixit-au7/test
/coding-challenges/Week02/Day 3_29-01-2020/Multiples of 5,7,11.py
659
4.125
4
# Question- Using range and for loop, print all multiples of 5, 7, 11 from 1 to 1001. #Answer- value = int(input("Enter the number for checking multiples between 1 to 1001( 5,7,11 are valid ).=")) count=0 for number in range(1,1002): if( value == 5): if(number % 5 == 0 ): count += 1 print(number) elif( value == 7 ): if(number % 7 == 0 ): count += 1 print(number) elif( value == 11 ): if(number % 11 == 0): count += 1 print(number) else: print("Invalid Input=",value) print("Total number of Multiples of ", number , " are = " , count)
true
f11a905550e160b4059321af68d38c3313e1eef5
shubham-dixit-au7/test
/Important Py Programs/W3resources/Ques8.py
283
4.125
4
# Question- Write a Python program to display the first and last colors from the following list. # color_list = ["Red","Green","White" ,"Black"] # Answer- color_list = ["Red","Green","White" ,"Black"] print( "First Color ->", color_list[0]) print( "Last Color ->", color_list[-1])
true
01baea07cc93ab961aff435b9ddbedb77842c728
shubham-dixit-au7/test
/coding-challenges/Week03/Day05_(07-02-2020)/Ques1.py
1,016
4.21875
4
# Question- Given a sorted array and a target value, return the index if the target is found. # If not, return the index where it would be if it were inserted in order. # [You may assume no duplicates in the array.] # [1,3,5,6], 5 → 2 # [1,3,5,6], 2 → 1 # [1,3,5,6], 7 → 4 # [1,3,5,6], 0 → 0 #Answer- def searchInsert(lst, target): begin = 0 end = len(lst) - 1 insertPos = 0 while begin <= end: mid = (begin + end) // 2 if lst[mid] == target: return mid elif lst[mid] > target: end = mid - 1 insertPos = mid else: begin = mid + 1 insertPos = mid + 1 return insertPos size = int(input("Enter the size of list ->")) lst=[] for i in range(0, size): ele = int(input()) lst.append(ele) target = int(input("Enter the value that you want to search ->")) print("List you entered is ->",lst) print("Target value you entered is ->", target) print(searchInsert(lst,target))
true
a59b355cd1292e79b08d021e4d456f78add7b338
shubham-dixit-au7/test
/Important Py Programs/W3resources/Ques4.py
359
4.375
4
# Question- Write a Python program which accepts the radius of a circle from the user and compute the area. # Sample Output : # r = 1.1 # Area = 3.8013271108436504 # Answer- from math import pi def areaCircle(radius): area = pi * radius ** 2 return area radius = float(input("Enter radius of circle ->")) area = areaCircle(radius) print(area)
true
ace50b3e806a788de8495f132706c78b5f1612da
quenadares15/python-course
/4-day/index.py
1,908
4.40625
4
# 4TH DAY # Comparison operators # All of the comparison operators returns a bool. It means the result of the # comparison will be either True or False. # Equality operator # a == b print('EQUALITY') equality = 2 == 2 # Will be True, because 2 is equal 2 print('2 == 2 -> ' + str(equality)) equality = 3 == 5 # Will be False, because 3 is NOT equal 5 print('3 == 5 -> ' + str(equality)) # Inequality operator # a != b print('INEQUALITY') inequality = 10 != 20 # Will be True, because 10 is not equal 20 print('10 != 20 -> ' + str(inequality)) inequality = 15 != 15 # Will be False, because 15 IS equal 15 print('15 != 15 -> ' + str(inequality)) # Greater than operator # a > b print('GREATER THAN') greater_than = 15 > 10 # Will be True, because 15 is greater than 10 print('15 > 10 -> ' + str(greater_than)) greater_than = 15 > 15 # Will be False, because 15 is NOT greater than 15 print('15 > 15 -> ' + str(greater_than)) # Less than operator # a < b print('LESS THAN') less_than = 5 < 10 # Will be True, because 5 is less than 10 print('5 < 10 -> ' + str(less_than)) less_than = 100 < 15 # Will be False, because 100 is NOT less than 15 print('100 < 15 -> ' + str(less_than)) # Greater than or equal operator # a >= b print('GREATER THAN OR EQUAL') greater_than_or_equal = 15 >= 10 # Will be True, because 15 is greater than 10 print('15 >= 10 -> ' + str(greater_than_or_equal)) greater_than_or_equal = 10 >= 20 # Will be False, because 20 is neither greater than nor equal 10 print('10 >= 20 -> ' + str(greater_than_or_equal)) # Less than or equal operator # a < b print('LESS THAN OR EQUAL') less_than_or_equal = 10 <= 10 # Will be True, because 10 is equal 10 print('10 <= 10 -> ' + str(less_than_or_equal)) less_than_or_equal = 20 <= 3 # Will be False, because 20 is neither less than nor equal 3 print('20 <= 3 -> ' + str(less_than_or_equal)) # Congratulations, 4th day complete!
true
f00c736f018895b50ae881d912f3e09efc300718
MattBlaszczyk/cmpt120Blaszczyk
/credentials.py
1,534
4.28125
4
# CMPT 120 Intro to Programming # Lab #4 – Working with Strings and Functions # Author: Matt Blaszczyk # Created: 2/23/2018 def firstName(): first = input("Enter your first name: ") return(first) def lastName(): last = input("Enter your last name: ") return(last) def username(): for i in range(1): firstN=firstName(); lastN=lastName(); username = firstN + "." + lastN # JA: You should actually make the username lowercase username = username.lower() print("Your Marist username is: ", username.lower()) password = input("Create a password: ") # JA: This you should move to it's own function if len(password) >=8 and password.isupper(): print("The force is strong in this one…") print("Account configured. Your new email address is", username + "@marist.edu") quit() if password.islower() or len(password) <8: print("Fool of a Took! That password is feeble!Please add uppercase letters or have the password be at least 8 characters!") password = input("Try again, create a new password: ") if len(password) >=8: print("The force is strong in this one…") print("Account configured. Your new email address is", username + "@marist.edu") quit() if password.islower() or len(password) <8: print("Failure to make password, restart program") quit() username()
true
f6629049d0f525bf9e9051cc70a24111d001c817
MattBlaszczyk/cmpt120Blaszczyk
/feetmilesyards.py
377
4.25
4
# Introduction to Programming # Author: Matt Blaszczyk # Date: 1/23/2018 # convert.py # A program to convert feet to miles to yards def convert(): feet = eval(input("Enter distance in feet:")) miles = 0.000189394 * feet yards = feet * 1/3 print("The distance in miles is", miles , "miles.") print("The distance in yards is", yards , "yards.") convert()
true
3a87add1cac4747f5701a878a9a8d213a65a8b22
ndilhara/HacktoberFest2021-1
/python/Arrays/Maximum_sum_path_array.py
1,512
4.28125
4
# Python program to find maximum sum path # This function returns the sum of elements on maximum path from # beginning to end def maxPathSum(ar1, ar2, m, n): # initialize indexes for ar1[] and ar2[] i, j = 0, 0 # Initialize result and current sum through ar1[] and ar2[] result, sum1, sum2 = 0, 0, 0 # Below 3 loops are similar to merge in merge sort while (i < m and j < n): # Add elements of ar1[] to sum1 if ar1[i] < ar2[j]: sum1 += ar1[i] i += 1 # Add elements of ar2[] to sum2 elif ar1[i] > ar2[j]: sum2 += ar2[j] j += 1 else: # we reached a common point # Take the maximum of two sums and add to result result += max(sum1, sum2) +ar1[i] #update sum1 and sum2 to be considered fresh for next elements sum1 = 0 sum2 = 0 #update i and j to move to next element in each array i +=1 j +=1 # Add remaining elements of ar1[] while i < m: sum1 += ar1[i] i += 1 # Add remaining elements of b[] while j < n: sum2 += ar2[j] j += 1 # Add maximum of two sums of remaining elements result += max(sum1, sum2) return result # Driver code ar1 = [2, 3, 7, 10, 12, 15, 30, 34] ar2 = [1, 5, 7, 8, 10, 15, 16, 19] m = len(ar1) n = len(ar2) # Function call print "Maximum sum path is", maxPathSum(ar1, ar2, m, n)
true
20de1e9131987ea1e6f970da5299c3f220e71526
ndilhara/HacktoberFest2021-1
/python/insertionSort.py
687
4.34375
4
# Python program for insertion sort #function for the insertion sort def insertionsort(A): #getting the length of the array n=len(A) #traverse through 1 to length of the array for j in range(1,n): key=A[j] i=j-1 #compare key with each element on the left of it #until an element smaller than it is found while(i>=0 and A[i]>key): A[i+1]=A[i] i=i-1 #place key after the element that is smaller than it. A[i+1]=key # Main program print("array before insertion sort") A = [22, 12, 43, 2, 60] print(A) insertionsort(A) print("array after insertion sort") insertionsort(A) print(A)
true
f4bbddfc4cfdd606b6f37d05706f3ab950e8307e
nicole894/SSW-567-HW02a
/triangle.py
2,039
4.28125
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 14 13:44:00 2016 Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple python program to classify triangles @author: jrr @author: rk """ def classify_triangle(_a, _b, _c): """ Your correct code goes here...Fix the faulty logic below until the code passes all of you test cases. This function returns a string with the type of triangle from three integer values corresponding to the lengths of the three sides of the Triangle. return: If all three sides are equal, return 'Equilateral' If exactly one pair of sides are equal, return 'Isoceles' If no pair of sides are equal, return 'Scalene' If not a valid triangle, then return 'NotATriangle' If the sum of any two sides equals the squate of the third side, then return 'Right' BEWARE: there may be a bug or two in this code """ # require that the input values be >= 0 and <= 200 if _a > 200 or _b > 200 or _c > 200: return 'InvalidInput' if _a <= 0 or _b <= 0 or _c <= 0: return 'InvalidInput' # verify that all 3 inputs are integers # Python's "isinstance(object,type) returns True if the object is of the specified type if not(isinstance(_a, int) and isinstance(_b, int) and isinstance(_c, int)): return 'InvalidInput' # This information was not in the requirements spec but # is important for correctness # the sum of any two sides must be strictly less than the third side # of the specified shape is not a triangle if (_a > (_b + _c)) or (_b > (_a + _c)) or (_c > (_a + _b)): return 'NotATriangle' # Right angled sides = [_a, _b, _c] sides.sort() if sides[2] ** 2 == ((sides[0] ** 2) + (sides[1] ** 2)): return 'Right' # now we know that we have a valid triangle if _a == _b and _b == _c: return 'Equilateral' if (_a != _b) and (_b != _c) and (_a != _c): return 'Scalene' return 'Isosceles'
true
c6a40795757ba38ea97a9287512326620f4e5910
sachin164/Pythonhackerrank
/regex/findallnfinditer.py
1,338
4.15625
4
# # Enter your code here. Read input from STDIN. Print output to STDOUT # Task # You are given a string . It consists of alphanumeric characters, spaces and symbols(+,-). # Your task is to find all the substrings of that contains or more vowels. # Also, these substrings must lie in between # consonants and should contain vowels only. # Note : # Vowels are defined as: AEIOU and aeiou. # Consonants are defined as: QWRTYPSDFGHJKLZXCVBNM and qwrtypsdfghjklzxcvbnm. # Input Format # A single line of input containing string # . # Constraints # Output Format # Print the matched substrings in their order of occurrence on separate lines. # If no match is found, print -1. # Sample Input # rabcdeefgyYhFjkIoomnpOeorteeeeet # Sample Output # ee # Ioo # Oeo # eeeee # Explanation # ee is located between consonant # and . # Ioo is located between consonant and . # Oeo is located between consonant and . # eeeee is located between consonant and . import re def solve(S): vowel = '[aeiou]' consonant = '[qwrtypsdfghjklzxcvbnm]' return re.findall(r'{consonant}({vowel}{{2,}})(?={consonant})'.format(vowel=vowel, consonant=consonant), S, re.IGNORECASE) def main(): S = input() solution = solve(S) if solution: print(*solution, sep='\n') else: print(-1) if __name__ == '__main__':
true
4b544a206ec68be9b8c4fa5598f01d1b15110d10
destiny27boone/python-workspace2
/debug input/DebugInput.py
844
4.4375
4
''' The goal of this function is to calculate the area of a circle. The function gets a radius from the user and then calculates the area. The function should print and return the area. ''' def circleArea(): radius = input("What is the radius of your circle?") pi = 3.14 squared = radius * radius area = pi * squared print("The area is: " + area) return area #Leave the next line alone circleArea() ''' This function calculates the area of a rectangle. The function gets a height and width from the user and then calculates the area. The function prints and returns the area. ''' def rectangleArea(): height = input("What is the height of your rectangle?") width = input() area = height * width print("The area is:" + area) return area #Leave the next line alone rectangleArea()
true
546e2c3de70a54f0be71a40287987117c1acf3b2
wwwser11/prj2
/test_tasks2.py
737
4.125
4
#Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. input_one = input('Ведите список. Значения необходимо вводить через запятую(, ). : ' ) input_two = input('Ведите список. Значения необходимо вводить через запятую(, ). : ' ) input_split_one = input_one.split(', ') input_split_two = input_two.split(', ') for element in input_split_two: while element in input_split_one: input_split_one.remove(element) print(input_split_one) #5, egot, 6, 34, 6, egor #egor, 5, 54, 4, 6
false
b6e2bbd623f4b3d9fabf889cdb617305bb1d3d21
jessie-JNing/Algorithms_Python
/Data_Structures/Linked_List/Linked_Slide.py
2,269
4.1875
4
#!/usr/bin/env python # encoding: utf-8 """ OrderedList() creates a new ordered list that is empty. It needs no parameters and returns an empty list. add(item) adds a new item to the list making sure that the order is preserved. It needs the item and returns nothing. Assume the item is not already in the list. remove(item) removes the item from the list. It needs the item and modifies the list. Assume the item is present in the list. search(item) searches for the item in the list. It needs the item and returns a boolean value. isEmpty() tests to see whether the list is empty. It needs no parameters and returns a boolean value. size() returns the number of items in the list. It needs no parameters and returns an integer. index(item) returns the position of item in the list. It needs the item and returns the index. Assume the item is in the list. pop() removes and returns the last item in the list. It needs nothing and returns an item. Assume the list has at least one item. pop(pos) removes and returns the item at position pos. It needs the position and returns the item. Assume the item is in the list. @author: Jessie @email: jessie.JNing@gmail.com """ class Node: def __init__(self,initdata): self.data = initdata self.next = None def slide(head, start, stop): if head is None or start > stop: return False else: index = 0 current = head slide_head = None while current: if index == start: slide_head = current if index == stop-1: current.next = None return slide_head current = current.next index += 1 return slide_head def display(head): element = [] current = head while current: element.append(str(current.data)) current = current.next return "[" + ','.join(element) + "]" if __name__=="__main__": a1 = Node(0) a2 = Node(1) a3 = Node(2) a4 = Node(3) a5 = Node(4) a6 = Node(5) a1.next = a2 a2.next = a3 a3.next = a4 a4.next = a5 a5.next = a6 header = slide(a1, 3, 9) print display(header)
true
95a1f0adf5178b731ce02b37c19c5bd795b4d862
jessie-JNing/Algorithms_Python
/Sort_search/Search_Rotated_Array.py
1,237
4.15625
4
#!/usr/bin/env python # encoding: utf-8 """ Given a sorted array of integers that has been rotated unknown number of times. Try to find out the index of that element. Input: [15,16,19,20,25,1,3,4,5,7,10,14] --> 5 0 1 2 3 4 5 6 7 8 9 10 11 Output: 8 @author: Jessie @email: jessie.JNing@gmail.com """ def search_rotated(nums, item): for i in range(len(nums)): if nums[i] == item: return i return -1 def search_rotated_binary(nums, item): if len(nums)<1: return -1 if len(nums)<2: return 0 start, end = 0, len(nums)-1 while start<end: mid = (start + end)/2 if nums[mid] == item: return mid if nums[start] < nums[mid]: if nums[start] < item and nums[mid] > item: end = mid-1 else: start = mid+1 else: if nums[mid] < item and nums[end] > item: start = mid + 1 else: end = mid-1 return -1 if __name__=="__main__": rotated_array = [15,16,19,20,25,1,3,4,5,7,10,14] print "search_rotated(19)", search_rotated(rotated_array, 1.7) print "search_rotated_binary(19)", search_rotated_binary(rotated_array, 1.7)
true
c4e35ff0fe42de8836c2c15cce8af79907b80294
jessie-JNing/Algorithms_Python
/Sort_search/Search_Matrix.py
1,221
4.125
4
#!/usr/bin/env python # encoding: utf-8 """ Given an MXN matrix in which each row and each column is sorted in ascending order. Write a method to find an element. @author: Jessie @email: jessie.JNing@gmail.com """ def search_matrix(M, item): for i in range(len(M)): col = binary_search(M[i], item) if col>-1: return (i, col) return (-1, -1) def binary_search(nums, item): start, end = 0, len(nums)-1 while start<=end: mid = (start+end)/2 if nums[mid]==item: return mid elif nums[mid] > item: end = mid - 1 else: start = mid + 1 return -1 def search_matrix_saving(M, item): row, col = 0, len(M[0])-1 while row<len(M) and col>=0: if M[row][col] == item: return (row, col) if M[row][col] > item: col -= 1 elif M[row][col] < item: row += 1 return (-1, -1) if __name__=="__main__": matrix = [[15,20,40,85], [20,35,80,93], [30,55,95,105], [40,80,100,120]] print "search_matrix(93)", search_matrix(matrix, 93) print "search_matsearch_matrix_savingrix(93)", search_matrix_saving(matrix, 93)
true
ee507e9fa7558f3d09ce1c468bf31f2ee5f29ac8
jessie-JNing/Algorithms_Python
/Sort_search/Insertion_Sort.py
1,042
4.28125
4
#!/usr/bin/env python # encoding: utf-8 """ We begin by assuming that a list with one item (position 0) is already sorted. On each pass, one for each item 1 through n−1, the current item is checked against those in the already sorted sublist. We shift those items that are greater to the right. When we reach a smaller item or the end of the sublist, the current item can be inserted. Runtime: o(n2) average and worst case. Memory: o(1) @author: Jessie @email: jessie.JNing@gmail.com """ # sort it into increasing order def insertion_sort(nums): if len(nums) < 2: return nums else: for i in range(1, len(nums)): insert_ele = nums[i] j = i while j>0: if nums[j-1] > insert_ele: nums[j] = nums[j-1] j -=1 else: break nums[j] = insert_ele return nums if __name__ == "__main__": unsorted = [54,26,93,17,77,31,44,55,20] print "insertion_sort:" , insertion_sort(unsorted)
true
16ead30d346443e216ccace0ab64ff2c46412ab3
jessie-JNing/Algorithms_Python
/Recursion_DP/Fibonacci.py
1,699
4.6875
5
#!/usr/bin/env python # encoding: utf-8 """ - Dynamic programming is similar to recursion problem. - A good way to approach such a problem is often to implement it as a normal recursive solution and then add the sub-problem result to cache. - Three laws for recursion: (1) Find out the base case (2) Change towards the base case (3) Able to call itself. - Bottom-up recursion and top-down recursion - Recursive algorithms are very space inefficient. - If the algorithm has o(n) recursive call, then it uses o(n) memory. - Before diving into the recursive code, ask yourself how hard it would be to implement it iteratively. - Discuss the trade-offs with your interviewer. @author: Jessie @email: jessie.JNing@gmail.com """ import datetime def Fibonacci_recursion(n): if n < 2: return n else: return Fibonacci_recursion(n-1) + Fibonacci_recursion(n-2) cache = {} def Fibonacci_dp(n): if n <2: cache[n] = n return cache[n] else: if n not in cache: cache[n] = Fibonacci_dp(n-1) + Fibonacci_dp(n-2) return cache[n] def Fibonacci_iterate(n): if n<2: return n else: cache = dict([(x,x) for x in range(2)]) i = 2 while i<=n: cache[i] = cache[i-1] + cache[i-2] i += 1 return cache[n] if __name__ == "__main__": print datetime.datetime.now() print 'Fibonacci_recursion', Fibonacci_recursion(20) print datetime.datetime.now() print "Fibonacci_dp", Fibonacci_dp(20) print datetime.datetime.now() print "Fibonacci_iterate", Fibonacci_iterate(20) print datetime.datetime.now()
true