blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
62bbb74e43256f78b67050821d847af478d4669c
netor27/codefights-solutions
/arcade/python/arcade-intro/12_Land of Logic/052_longestWord.py
637
4.21875
4
def longestWord(text): ''' Define a word as a sequence of consecutive English letters. Find the longest word from the given string. ''' maxLen, maxStart, currStart, currLen = 0, 0, 0, 0 for i in range(len(text)): if text[i].isalpha(): if currLen == 0: currStart = i currLen += 1 else: if currLen > maxLen: maxLen = currLen maxStart = currStart currLen = 0 if currLen > maxLen: maxLen = currLen maxStart = currStart return text[maxStart:maxStart + maxLen]
true
6cc342813a5cf0ab9e54f0ebb7bf05911b66e9b0
netor27/codefights-solutions
/arcade/python/arcade-theCore/05_ListForestEdge/040_IsSmooth.py
996
4.125
4
def isSmooth(arr): ''' We define the middle of the array arr as follows: if arr contains an odd number of elements, its middle is the element whose index number is the same when counting from the beginning of the array and from its end; if arr contains an even number of elements, its middle is the sum of the two elements whose index numbers when counting from the beginning and from the end of the array differ by one. An array is called smooth if its first and its last elements are equal to one another and to the middle. Given an array arr, determine if it is smooth or not. ''' length = len(arr) if length % 2 == 1: middle = arr[length//2] else: middle = arr[length//2] + arr[length//2 - 1] return arr[0] == middle and arr[length-1] == middle print(isSmooth([7, 2, 2, 5, 10, 7])) print(isSmooth([-5, -5, 10])) print(isSmooth([4, 2])) print(isSmooth([45, 23, 12, 33, 12, 453, -234, -45]))
true
df112813c067411853941f8455d31fed51a2c1fa
netor27/codefights-solutions
/arcade/python/arcade-theCore/01_IntroGates/005_MaxMultiple.py
349
4.21875
4
def maxMultiple(divisor, bound): ''' Given a divisor and a bound, find the largest integer N such that: N is divisible by divisor. N is less than or equal to bound. N is greater than 0. It is guaranteed that such a number exists. ''' num = bound - (bound % divisor) return max(0, num) print(maxMultiple(3, 10))
true
4360bfb5399e8fc6a7d7453b8582063d04704139
netor27/codefights-solutions
/arcade/python/arcade-intro/02_Edge of the Ocean/008_matrixElementsSum.py
1,100
4.1875
4
def matrixElementsSum(matrix): ''' After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains an integer that represents the price of the room. Some rooms are free (their cost is 0), but that's probably because they are haunted, so all the bots are afraid of them. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable for the bots to live in. Help the bots calculate the total price of all the rooms that are suitable for them. ''' maxX = len(matrix) maxY = len(matrix[0]) total = 0 # Sum every colum until we found a 0, then move to the next column for y in range(maxY): for x in range(maxX): if matrix[x][y] == 0: break total += matrix[x][y] return total print(matrixElementsSum([[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]))
true
9ab6e5d04bdd7d278e9f6c1188160ff8ae892e14
netor27/codefights-solutions
/arcade/python/arcade-theCore/04_LoopTunnel/029_AdditionWithoutCarrying.py
763
4.375
4
def additionWithoutCarrying(param1, param2): ''' A little boy is studying arithmetics. He has just learned how to add two integers, written one below another, column by column. But he always forgets about the important part - carrying. Given two integers, find the result which the little boy will get. ''' result = 0 currentDigit = 0 while(param1 != 0 or param2 != 0): result = result + (param1 + param2) % 10 * 10 ** currentDigit currentDigit += 1 param1 = param1 // 10 param2 = param2 // 10 return result print(additionWithoutCarrying(456, 1734)) print(additionWithoutCarrying(99999, 0)) print(additionWithoutCarrying(999, 999)) print(additionWithoutCarrying(0, 0))
true
cb03a35c7e74fc7ca73545dadc59c16bce5c6f7a
netor27/codefights-solutions
/arcade/python/arcade-theCore/08_MirrorLake/059_StringsConstruction.py
634
4.1875
4
def stringsConstruction(a, b): ''' How many strings equal to a can be constructed using letters from the string b? Each letter can be used only once and in one string only. Example For a = "abc" and b = "abccba", the output should be stringsConstruction(a, b) = 2. We can construct 2 strings a with letters from b. ''' continueSearching = True r = 0 while continueSearching: for i in a: j = 0 while j < len(b) and i != b[j]: j+=1 if j >= len(b): return r b = b[:j] + b[j+1:] r += 1 return r
true
5cf96612d1c9bdb7f2fd851e8a00b424c2da2b6f
mixelpixel/CS1-Code-Challenges
/cc69strings/strings.py
2,486
4.28125
4
# cc69 strings # https://repl.it/student/submissions/1855286 # https://developers.google.com/edu/python/ # http://pythoncentral.io/cutting-and-slicing-strings-in-python/ ''' For this challenge, you'll be writing some basic string functions. Simply follow along with each exercise's prompt. You may find the following article helpful with regards to how to perform string slicing in Python: http://pythoncentral.io/cutting-and-slicing-strings-in-python/ ''' # 1. Donuts # Given an int count of a number of donuts, return a string # of the form 'Number of donuts: <count>', where <count> is the number # passed in. However, if the count is 10 or more, then use the word 'many' # instead of the actual count. # So donuts(5) returns 'Number of donuts: 5' # and donuts(23) returns 'Number of donuts: many' def donuts(count): # Your code here if count < 10: reply = str(count) else: reply = 'many' # print("Number of donuts: ", count if count < 10 else 'many') return "Number of donuts: " + reply print(donuts(5)) print(donuts(23)) print(donuts(4)) # 2. both_ends # Given a string s, return a string made of the first 2 # and the last 2 chars of the original string, # so 'spring' yields 'spng'. However, if the string length # is less than 2, return instead the empty string. def both_ends(s): # Your code here if len(s) < 2: return '' return s[0:2] + s[-2:] print(both_ends("Scooby Snacks")) print(both_ends("Jesh doesn't share his candy")) # 3. fix_start # Given a string s, return a string # where all occurences of its first char have # been changed to '*', except do not change # the first char itself. # e.g. 'babble' yields 'ba**le' # Assume that the string is length 1 or more. # Hint: s.replace(stra, strb) returns a version of string s # where all instances of stra have been replaced by strb. def fix_start(s): letter = s[0] s = s.replace(letter, '*') starring = letter + s[1:] return starring print(fix_start("well, why weren't we welcome?")) print(fix_start("Scooby Snacks Sound Simply Scrumptuous!")) # 4. mix_up # Given strings a and b, return a single string with a and b separated # by a space '<a> <b>', except swap the first 2 chars of each string. # e.g. # 'mix', pod' -> 'pox mid' # 'dog', 'dinner' -> 'dig donner' # Assume a and b are length 2 or more. def mix_up(a, b): new_a = b[:2] + a[2:] new_b = a[:2] + b[2:] return new_a + ' ' + new_b print(mix_up("What", "the???")) print(mix_up("Patrick", "Kennedy"))
true
c2bad1043e0499dfcd0fed9d617d9200ebede882
lijerryjr/MONIAC
/textFunctions.py
1,637
4.21875
4
################### # rightJustifyText # This contains the text justifier code from HW3 ################### import string def replaceWhiteSpace(text): #replace white space in text with normal spaces #inspired by recitation 3 video inWhiteSpace=False result='' for c in text: if not inWhiteSpace and c.isspace(): inWhiteSpace=True elif inWhiteSpace and not c.isspace(): inWhiteSpace=False result+=' '+c elif not inWhiteSpace and not c.isspace(): result+=c return result def breakLines(text, width): #break into lines of required width newText='' lineLen=0 for word in text.split(' '): if lineLen+len(word) > width: newText+='\n'+word+' ' lineLen=len(word)+1 else: newText+=word+' ' lineLen+=len(word)+1 return newText def removeTrailingSpaces(text): #remove trailing white space in each line newText='' for line in text.splitlines(): newText+=line.strip()+'\n' return newText def createNewText(text, width): #return clean lines of required width with above functions text=text.strip() text=replaceWhiteSpace(text) text=breakLines(text, width) text=removeTrailingSpaces(text) return text def rightJustifyText(text, width): #return right-justified text text=createNewText(text, width) newText='' #add white space before text to align right for line in text.splitlines(): newText+=' '*(width-len(line))+line+'\n' #remove '\n' at end newText=newText[:-1] return newText
true
4c92c735e5966ba9de1cd9c0538c82040271139a
cloudsecuritylabs/pythonProject_1
/ch_01/19.comparisonoperators..py
812
4.125
4
''' Let's learn about comparison operators ''' age = 0 if age <= 100: print("You are too young") elif age >100: print("You are a strong kid") else: print("We need to talk") if True: print("hey there") # this does not print anything if False: print("Oh No!") string = "he he" if string: print("dont smile") if not string: print("can't smile") mylist = [] if mylist: print("dont smile") if not mylist: print("can't smile") myDict = {} if myDict: print("dont smile") if not myDict: print("can't smile") list1 = [1,2,3] list2 = [4,5,6] if list1 == list2: print("hello identical") cat = "tom" dog = 'jerry' if cat == 'tom': if dog == 'jerry': print("Hi cartoon") if cat == 'tom' and dog == 'jerry': print("Hi cartoon") # truth table
true
da2004b72fdf6dc722bd025c1c6580a9e9aaed8e
ahmad-atmeh/my_project
/CA10/3.py
592
4.34375
4
# 3.You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency. # Input: find_frequencies(['cat', 'bat', 'cat']) # Return: {'cat': 2, 'bat': 1} # Creating an empty dictionary def find_frequencies(word): freq ={} for item in word: if (item in freq): freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print ("% s : % s"%(key, value)) # Driver function word =['cat', 'bat', 'cat'] find_frequencies(word)
true
36cda705b3d2e83c671be0582bbaf1cb45b7484d
ahmad-atmeh/my_project
/CA10/4.py
384
4.125
4
#4. You are given a list of integers. Write a function cumulative_sum(numbers) which calculates the cumulative sum of the list. The cumulative sum of a list numbers = [a, b, c, ...] can be defined as [a, a+b, a+b+c, ...]. # Input: numbers = [1, 2, 3, 4] # Return: cumulative_sum_list = [1, 3, 6, 10] lis = [1, 2, 3, 4] from itertools import accumulate print(list(accumulate(lis)))
true
2e2eccaa840f0fbf6bde633cf87834b7b4b62173
ahmad-atmeh/my_project
/CA07/Problem 3/circle.py
2,002
4.46875
4
# Class Circle import math class Circle: # TODO: Define an instance attribute for PI def __init__(self, radius=1.0): # TODO: Define an instance attribute for the radius self.PI=3.14 self.radius=radius # TODO: Define the string representation method and print # r = {self.radius} c = {self.get_circumference()} a = {self.get_area()} def __str__(self): return f"r = {self.radius} c = {self.get_circumference()} a = {self.get_area()}" # TODO: Define a get_area() method and return the area def get_area(self): return self.PI * (self.radius ** 2) # TODO: Define a get_circumference() method and return the circumference def get_circumference(self): return 2 * self.PI * self.radius # TODO: Define a set_color(color) method which sets the object attribute def set_color(self, color): self.color = color # TODO: Define a get_color() method which returns the object attribute def get_color(self): return self.color # Playground # TODO: Create two circles one with radius 3, and one with the default radius c1=Circle(3) c2=Circle() # TODO: Set the colors of your circles using the setter method c1.set_color('black') c2.set_color('green') # TODO: Print the colors of your circles using the getter method print(f" the color of circles 1 is {c1.get_color()}") print(f" the color of circles 2 is {c2.get_color()}") # TODO: Print your circles. How does this work? print(c1) print(c2) # TODO: Print the radius and areas of your cricles print(f" the area of cricles is {c1.get_area()} and the radius is {c1.radius} ") print(f" the area of cricles is {c2.get_area()} and the radius is {c2.radius} ") # TODO: Print the circumference of your circles using the getter method print(f" the area of circumference 1 is {c1.get_circumference()}") print(f" the area of circumference 2 is {c2.get_circumference()}")
true
eb954e96ab4f8a34e70891920d417a2d93822b44
Dipin-Adhikari/Python-From-Scratch
/Dictionary/dictionary.py
1,398
4.125
4
"""Dictionaries is collection of keyvalue pairs.it is ordered and changeable but it doesnot allow duplicates values..""" dictionary = { "python": "Python is an interpreted high-level general-purpose programming language.", "django": "Django is a Python-based free and open-source web framework that follows the model–template–views architectural pattern", "flask": "Flask is a micro web framework written in Python.", } for key, value in dictionary.items(): # .items() return a list of key & values tuples print(key, ":", value) print( dictionary.keys() ) # .keys() will return and prints keys only from dictionary ! # .update() will update values in dictionary dictionary.update( { "django": "Django is a python based webframework that follow MVT architectural pattern" } ) # value of django is updated now ! """.get() returns values of specifed keys but if given value is not present in dictionary it will return none whereas | dictionary.["keyname"] | throws an error if key is not present in dictionary""" # print(dictionary["notindict"]) #it will throw an error because key is not present in dictionary print(dictionary.get("django")) # prints value of given keys name (django) print(dictionary.get("flask")) # prints value of given keys name (flask) print(dictionary.get("python")) # prints value of given keys name (python)
true
b578a4a9a57922b7b6a13472a074c1ad883b0421
Aadit017/code_sharing
/month to days.py
756
4.1875
4
while True: name=input("Enter name of month: ") name=name.lower() if(name=="january"): print("days=31") elif(name=="february"): print("days=28") elif(name=="march"): print("days=31") elif(name=="april"): print("days=30") elif(name=="may"): print("days=31") elif(name=="june"): print("days=30") elif(name=="july"): print("days=31") elif(name=="august"): print("days=31") elif(name=="september"): print("days=30") elif(name=="october"): print("days=31") elif(name=="november"): print("days=30") elif(name=="december"): print("days=31") else: print("INVALID input")
true
a6759a0d5fb17142435d89d87ccbd4ce64629a39
Abhilash11Addanki/cspp1-assignments
/Module 22 Week Exam/Check Sudoku/check_sudoku.py
1,741
4.28125
4
''' Sudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid contains all of the digits from 1 to 9. Complete the check_sudoku function to check if the given grid satisfies all the sudoku rules given in the statement above. ''' def check_row(sudoku): '''function for checking the rules for row''' for row in sudoku: if sum([int(ele) for ele in row]) != 45:#Sum of numbers in a row should be equal to 45 return False return True def check_column(sudoku): '''function for checking the rules for column''' for row, list_ in enumerate(sudoku): sum_res = 0 for column in range(len(list_)): sum_res += int(sudoku[column][row]) if sum_res != 45: return False return True def check_sudoku(sudoku): ''' Your solution goes here. You may add other helper functions as needed. The function has to return True for a valid sudoku grid and false otherwise ''' if check_row(sudoku) and check_column(sudoku): return True return False def main(): ''' main function to read input sudoku from console call check_sudoku function and print the result to console ''' # initialize empty list sudoku = [] # loop to read 9 lines of input from console for row in range(9): # read a line, split it on SPACE and append row to list row = input().split(' ') sudoku.append(row) # call solution function and print result to console print(check_sudoku(sudoku)) if __name__ == '__main__': main()
true
174ca0fb814021e716969bcd6b681fca98d5fbb9
Abhilash11Addanki/cspp1-assignments
/Practice Problems/Code Camp matrix/matrix_operations.py
2,042
4.125
4
'''Matrix operations.''' def mult_matrix(m_1, m_2): ''' check if the matrix1 columns = matrix2 rows mult the matrices and return the result matrix print an error message if the matrix shapes are not valid for mult and return None error message should be "Error: Matrix shapes invalid for mult" ''' if len(m_1[0]) != len(m_2): print("Error: Matrix shapes invalid for mult") return None res_m = [[sum([m_1[i][k]*m_2[k][j] for k in range(len(m_2))]) for j in range(len(m_2[0]))] for i in range(len(m_1))] return res_m def add_matrix(m_1, m_2): ''' check if the matrix shapes are similar add the matrices and return the result matrix print an error message if the matrix shapes are not valid for addition and return None error message should be "Error: Matrix shapes invalid for addition" ''' if len(m_1) == len(m_2): add_mat = [[i+j for i, j in zip(m_1[i], m_2[i])] for i in range(len(m_1))] return add_mat print("Error: Matrix shapes invalid for addition") return None def read_matrix(): ''' read the matrix dimensions from input create a list of lists and read the numbers into it in case there are not enough numbers given in the input print an error message and return None error message should be "Error: Invalid input for the matrix" ''' rows_mat, cols_mat = input().split(",") read_mat = [input().split(" ") for i in range(int(rows_mat))] mat = [[int(j) for j in i] for i in read_mat] if any([True if len(i) != int(cols_mat) else False for i in mat]): print("Error: Invalid input for the matrix") return None return mat def main(): '''Main Function.''' matrix_1 = read_matrix() matrix_2 = read_matrix() if matrix_1 and matrix_2 is not None: print(add_matrix(matrix_1, matrix_2)) print(mult_matrix(matrix_1, matrix_2)) if __name__ == '__main__': main()
true
6485a65aaf4ecbcdbf3e86c954a792aeaa5c8948
BabaYaga007/Second-1
/stone_paper_scissor.py
1,198
4.1875
4
from random import randint def print_menu(): print('1 for Stone') print('2 for Paper') print('3 for Scissor') print('Enter your choice') def print_score(a,b): print('---Score---') print('Player =',a) print('Computer =',b) choice = ['stone','paper','scissor'] a=0 b=0 while(True): print_menu() ch = int(input()) if ch==1 : player = 'stone' elif ch==2 : player = 'paper' elif ch==3 : player = 'scissor' else : print('Invalid Choice. Try Again') continue rand = randint(0,2) computer = choice[rand] print('You chose',player) print('Computer chose',computer) if player=='stone' and computer=='paper': b += 1 elif player=='stone' and computer=='scissor': a += 1 elif player=='paper' and computer=='stone': a += 1 elif player=='paper' and computer=='scissor': b += 1 elif player=='scissor' and computer=='stone': b += 1 elif player=='scissor' and computer=='paper': a += 1 else: print("It's a Tie!!!") print_score(a,b) if a==5 or b==5: break
true
238f30f035a54ede9b8a3cae148c074bbd806ec3
ralsouza/python_data_structures
/section7_arrays/searching_an_element.py
440
4.1875
4
from array import * arr1 = array("i", [1,2,3,4,5,6]) def search_array(array, value): for i in array: # --------------------------------------> O(n) if i == value:# ------------------------------------> O(1) return array.index(value) # --------------------> O(1) return "The element does not exist in this array." # ---> O(1) print(search_array(arr1,3)) print(search_array(arr1,6)) print(search_array(arr1,7))
true
3f9c04833a87be9b112078e462c08aa7369dc9bc
ralsouza/python_data_structures
/section8_lists/chal6_pairs.py
550
4.21875
4
# Pairs # Write a function to find all pairs of an integer array whose sum is equal to a given number. # Example: pair_sum([2,4,3,5,6,-2,4,7,8,9], 7) # Output: ['2+5', '4+3', '3+4', '-2+9'] my_list = [2,4,3,5,6,-2,4,7,8,9] def pair_sum(list, num_sum): output = [] for i in range(len(list)): for j in range(i+1, len(list)): if list[i] + list[j] == num_sum: # print(f"{list[i]} + {list[j]} = {num_sum}") output.append(f"{list[i]}+{list[j]}") return output print(pair_sum(my_list, 7))
true
49ab45268ba1099af5637316d5584e075a601dab
ralsouza/python_data_structures
/section28_sorting_algorithms/293_bubbles_sort.py
490
4.25
4
# Bubble Sort # - Bubble sort is also referred as Sinking sort # - We repeatedly compare each pair of adjacent items and swap them if # they are in the wrong order def bubble_sort(custom_list): for i in range(len(custom_list)-1): for j in range(len(custom_list)-i-1): if custom_list[j] > custom_list[j+1]: custom_list[j], custom_list[j+1] = custom_list[j+1], custom_list[j] print(custom_list) c_list = [2,1,7,6,5,3,4,9,8] bubble_sort(c_list)
true
6adcebfeff79bf2c97bf0587a49e658e71b7b503
ralsouza/python_data_structures
/section8_lists/proj3_finding_numer_in_array.py
399
4.15625
4
# Project 3 - Finding a number in a array # Question 3 - How to check if an array contains a number in Python import numpy as np my_list = list(range(1,21)) my_array = np.array(my_list) def find_number(array, number): for i in range(len(array)): if array[i] == number: print(f"The number {number} exists at index {i}.") find_number(my_array, 13) find_number(my_array, 21)
true
c22fbab5afe23a79783eeaa86b6d0041c5c01b7d
viratalbu1/Python-
/AccesingInstanceVariable.py
513
4.25
4
#This Example is used for understanding what is instance variable class test: def __init__(self,name,rollno): self.name=name self.rollno=rollno def info(self): print(self.name) print(self.rollno) #In Above Example state creation of constructor and object method # For Accessing it just create Object t=test("Virat",1) t.info() #This method will print the value of instance variable print(t.name) #above and below method will also give yo the instance variable value print(t.rollno)
true
78e9924735898785f3963c59531b866f1f44138b
viratalbu1/Python-
/IteratorAndGeneratorExample.py
695
4.875
5
# Iterator is used for creating object for iteratable object such as string, list , tuple itr_list=iter([1,2,3,4]) itr_tuple=iter((1,2,3,4)) itr_string=iter('String') print('--------List ------') for val in itr_list: print(val) print('-----Tuple----------') for val in itr_tuple: print(val) print('------String---------') for val in itr_string: print(val) print('Genertor Examples') def GetCubes(a): for num in range(a): yield num**3 print(GetCubes(5)) print('This is Object so now we can call this object and get the result') for val in GetCubes(5): print(val) print('Other Varient for Using Generator') print(list(GetCubes(2)))
true
ad96b449267f2c830b6ebc0f6f0d8f13a1300f0a
bongjour/effective_python
/part1/zip.py
672
4.15625
4
from itertools import zip_longest names = ['dante', 'beerang', 'sonic'] letters = [len(each) for each in names] longest_name = None max_letter = 0 # for i, name in enumerate(names): # count = letters[i] # # if count > max_letter: # longest_name = name # max_letter = count for name, count in zip(names, letters): if count > max_letter: longest_name = name max_letter = count print(max_letter) print(longest_name) names.append('billy') # zip은 크기가 틀리면 이상하게 동작한다. for name, count in zip(names, letters): print(name) for name, count in zip_longest(names, letters): print(name, count)
true
4f1ee7021d8707fcf351345b18d164ecc0ccd3db
aFuzzyBear/Python
/python/mystuff/ex24.py
1,953
4.28125
4
# Ex24- More Python Practicing #Here we are using the escape \\ commands int eh print statement. print "Let's practice everything." print "You\'d need to know \'bout dealing with \\escape statements\\ that do \n newlines and \t tabs" #Here we have made the poem a multilined print statement poem = """ \tThe lovely world with logic so firmly planted cannot dicern \n the needs of love nor comprehend passion from intuition and requires and explanation \n\t\twhere there is none. """ #Here we are outputing the varible poem as a call funtion to print print "--------------------" print poem print "--------------------" #Here a varible is calculating the math of the varible and calling it into the print statement five = 10 - 2 + 3- 6 print "this should be five: %s" % five #Here we are defining a function with variables set to return the values of their respective arguements. def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates #Here we are introducing values to the function start_point = 1000 #tbh we could do a raw_input to get the user to enter the value here beans, jars, crates = secret_formula(start_point) # beans and jelly_beans are synonomis with each other, the varible inside the function is temporary, when it is returned in the function it can be called assigned to a varible for later, here beans just holds the value for jelly_beans print "With a starting point of: %d" % start_point print "We'd have %d beans, %d jars, and %d crates" % secret_formula(start_point) start_point = start_point /10 print "We can also do that this way: " print "We'd have %d beans, %d Jars, and %d crates" % secret_formula(start_point)# I tried to use {} tuples to enter the arguements into the statement, however was given IndexError: tuple index out of range. This is probalby down to the fact the arguements being called is stored within the function. idk
true
09f90dc3135c90b4e3a62d3ef3553f160c621f4a
aFuzzyBear/Python
/python/mystuff/ex33.py
1,228
4.375
4
#While Loops """A While loop will keep executing code if the boolean expression is True. It is a simple If-Statement but instead of running a block of code once if True, it would keep running through the block untill it reaches the first False expression. The issue with while-loops is that they sometimes dont stop. They can keep going on forever. To avoid this issue follow the following rules: 1) Make sure that you use While-loops sparingly. For loops are always better! 2) Review the while loops to make sure the logic behind it will produce a false expression at one point. 3)when in doubt print out a test varible at the top and bottom of the while-loop to see what it's doing """ i = 0 numbers = [] #This is saying while i equal to values less than 6 print keep doing the block of code. while i < 6: print "At the top i is %d" % i numbers.append(i)#Here we are adding to the list for every iteratation i = i + 1 #This is a strange one, telling to change the i varible by taking the current value and adding its new value for the iteration to itself. probably could be written as i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num
true
1766f40560f8a404a0c964a89198d185304c20c7
aFuzzyBear/Python
/python/mystuff/ex20.py
606
4.15625
4
#Functions and Files from sys import argv scrit, input_file = argv def print_all(f): print f.read() def rewind (f): f.seek(0) def print_a_line(line_count, f): print line_count, f.readline() current_file = open(input_file) print "First let's print the whole file: \n" print_all(current_file) print "Now let's rewind, kinda like a tape.\n" rewind(current_file) print "Lets print three lines.\n" current_line = 1 current_line += current_line print_a_line (current_line, current_file) print_a_line (current_line, current_file) print_a_line (current_line, current_file) #I really dont get this!
true
d37e27a702a74af02dce7b41c3a6a368f714ba2e
szhongren/leetcode
/129/main.py
1,697
4.15625
4
""" Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / \ 2 3 The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Return the sum = 12 + 13 = 25. """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def make_tree(ls): """ :type ls: List[int] :rtype: TreeNode """ list_nodes = list(map(lambda x: TreeNode(x) if x != None else None, ls)) length = len(list_nodes) for i in range(length // 2): if list_nodes[i] != None: if i * 2 + 1 < length: list_nodes[i].left = list_nodes[i * 2 + 1] if i * 2 + 2 < length: list_nodes[i].right = list_nodes[i * 2 + 2] return list_nodes[0] def dfs(root, num, sum): if root == None: return sum num = num * 10 + root.val if root.left == None and root.right == None: sum += num return sum sum = dfs(root.left, num, sum) + dfs(root.right, num, sum) return sum class Solution(object): def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ if root == None: return 0 else: return dfs(root, 0, 0) ans = Solution() print(ans.sumNumbers(make_tree([1, 1]))) print(ans.sumNumbers(make_tree([1, 2, 3])))
true
1a1a9e775108be74c02d4e90c42bf1928f94ca4f
szhongren/leetcode
/337/main.py
2,378
4.15625
4
""" The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night. Determine the maximum amount of money the thief can rob tonight without alerting the police. Example 1: 3 / \ 2 3 \ \ 3 1 Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. Example 2: 3 / \ 4 5 / \ \ 1 3 1 Maximum amount of money the thief can rob = 4 + 5 = 9. """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def make_tree(ls): """ :type ls: List[int] :rtype: TreeNode """ if len(ls) == 0: return None list_nodes = list(map(lambda x: TreeNode(x) if x != None else None, ls)) length = len(list_nodes) for i in range(length // 2): if list_nodes[i] != None: if i * 2 + 1 < length: list_nodes[i].left = list_nodes[i * 2 + 1] if i * 2 + 2 < length: list_nodes[i].right = list_nodes[i * 2 + 2] return list_nodes[0] class Solution(object): def rob(self, root): """ :type root: TreeNode :rtype: int """ def transformTree(node): if node == None: return TreeNode([0, 0]) node.left = transformTree(node.left) node.right = transformTree(node.right) curr_val = node.val node.val = [None, None] rob = 0 notrob = 1 node.val[notrob] = node.left.val[rob] + node.right.val[rob] node.val[rob] = max(node.val[notrob], curr_val + node.left.val[notrob] + node.right.val[notrob]) return node # only works when space between houses robbed can only be 1 return max(transformTree(root).val) ans = Solution() print(ans.rob(make_tree([3, 2, 3, None, 3, None, 1]))) print(ans.rob(make_tree([3, 4, 5, 1, 3, None, 1]))) print(ans.rob(make_tree([])))
true
522b1b01a64b08202f162b7fae780dbf2219066e
szhongren/leetcode
/473/main.py
1,692
4.3125
4
""" Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has. Example 1: Input: [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. Example 2: Input: [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks. Note: The length sum of the given matchsticks is in the range of 0 to 10^9. The length of the given matchstick array will not exceed 15. """ class Solution(object): def makesquare(self, nums): """ :type nums: List[int] :rtype: bool """ total = 0 max_match = 0 count = 0 for v in nums: count += 1 total += v max_match = max(v, max_match) if count < 4 or max_match > total // 4 or total % 4 != 0: return False nums.sort() side = total // 4 return self.makeSquareRecur(nums, [side for _ in range(4)], side) def makeSquareRecur(self, nums, sides, side): return True ans = Solution() print(ans.makesquare([1, 1, 2, 2, 2])) print(ans.makesquare([3, 3, 3, 3, 4]))
true
4671c9f8d366e45e97a92920d6190e1d7c65d894
tdongsi/effective_python
/ep/item13b.py
1,973
4.15625
4
NUMBERS = [8, 3, 1, 2, 5, 4, 7, 6] GROUP = {2, 3, 5, 7} def sort_priority(numbers, group): """ Sort the input numbers but put those in "group" first. :param numbers: list of input numbers. :param group: set of numbers in priority group. :return: True if any number in priority is found. """ found = False def helper(x): if x in group: found = True return (0, x) return (1, x) numbers.sort(key=helper) return found def main_original(): numbers = NUMBERS[:] print(sort_priority_solved(numbers, GROUP)) print(numbers) def sort_priority_python_3(numbers, group): """ Sort the input numbers but put those in "group" first. :param numbers: list of input numbers. :param group: set of numbers in priority group. :return: True if any number in priority is found. """ found = False def helper(x): if x in group: # nonlocal found found = True return (0, x) return (1, x) numbers.sort(key=helper) return found def sort_priority_python_2(numbers, group): """ Sort the input numbers but put those in "group" first. :param numbers: list of input numbers. :param group: set of numbers in priority group. :return: True if any number in priority is found. """ found = [False] def helper(x): if x in group: found[0] = True return (0, x) return (1, x) numbers.sort(key=helper) return found[0] class CheckSpecial(object): def __init__(self, group): self.group = group self.found = False def __call__(self, x): if x in self.group: self.found = True return (0, x) return (1, x) def sort_priority_solved(numbers, group): helper = CheckSpecial(GROUP) numbers.sort(key=helper) return helper.found if __name__ == '__main__': main_original()
true
6c73b0dade33e1a6dfbd3bfc1bb9e43ec21dabbf
tdongsi/effective_python
/ep/item13.py
924
4.46875
4
meep = 23 def enclosing(): """ Variable reference in different scopes. When referring to a variable not existing in the inner scope, Python will try to look up in the outer scope. """ foo = 15 def my_func(): bar = 10 print(bar) # local scope print(foo) # enclosing scope print(meep) # global scope print(str) # built-in scope # print(does_not_exist) my_func() enclosing() def enclosing_assignment(): """ Variable assignment in different scopes. Different from variable reference. When assigning to a variable not existing in the inner scope, Python will create a new local variable. """ foo = 15 foo = 25 def my_func(): foo = 15 bar = 5 print(foo) print(bar) my_func() print(foo) # print(bar) # Does not exist enclosing_assignment()
true
3d8fa1d96a89e06299f099b1f4ccc88cf33b5d97
oigwe/learning_data_analyzing
/python/Step 1/2.Python Data Analysis Basics: Takeaways.py
1,229
4.1875
4
#Python Data Analysis Basics: Takeaways #by Dataquest Labs, Inc. - All rights reserved © 2020 #Syntax #STRING FORMATTING AND FORMAT SPECIFICATIONS #Insert values into a string in order: continents = "France is in {} and China is in {}".format("Europe", "Asia") #Insert values into a string by position: squares = "{0} times {0} equals {1}".format(3,9) #Insert values into a string by name: population = "{name}'s population is {pop} million".format(name="Brazil", pop=209) #Format specification for precision of two decimal places: two_decimal_places = "I own {:.2f}% of the company".format(32.5548651132) #Format specification for comma separator: india_pop = The approximate population of {} is {}".format("India",1324000000) #Order for format specification when using precision and comma separator: balance_string = "Your bank balance is {:,.2f}"].format(12345.678) #Concepts #The str.format() method allows you to insert values into strings without explicitly converting them. #The str.format() method also accepts optional format specifications, which you can use to format values so they are easier to read. #Resources #Python Documentation: Format Specifications #PyFormat: Python String Formatting Reference
true
0a4042a5c22e529574bc1ccb8f1f6bbfad9c7894
oigwe/learning_data_analyzing
/python/Step 1/Lists and For Loops: Takeaways.py
1,567
4.375
4
#Lists and For Loops: Takeaways #by Dataquest Labs, Inc. - All rights reserved © 2020 #Syntax #Creating a list of data points: row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5] row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5] #Creating a list of lists: data = [row_1, row_2] #Retrieving an element of a list: first_row = data[0] first_element_in_first_row = first_row[0] first_element_in_first_row = data[0][0] last_element_in_first_row = first_row[-1] last_element_in_first_row = data[0][-1] #Retrieving multiple list elements and creating a new list: row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5] rating_data_only = [row_1[3], row_1[4]] #Performing list slicing: row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5] second_to_fourth_element = row_1[1:4] #Opening a data set file and using it to create a list lists: opened_file = open('AppleStore.csv') from csv import reader #reader is a function that generates a reader object read_file = reader(opened_file) apps_data = list(read_file) #Repeating a process using a for loop: row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5] for data_point in row_1: print(data_point) #Concepts #A data point is a value that offers us some information. #A set of data points make up a data set. A table is an example of a data set. #Lists are data types which we can use to store data sets. #Repetitive process can be automated using for loops. #Resources #Python Lists #Python For Loops #More on CSV files #A list of keywords in Python — for and in are examples of keywords (we used for and in to write for loops)
true
28d231a0a4e9f1a42c968643e77bd1598e0da992
jonag-code/python
/dictionary_list_tuples.py
1,675
4.25
4
List =[x**2 for x in range(5)] Dictionary = {0:'zero', 1:'one', 2:'four', 3:'nine', 4:'sixteen'} Tuple = tuple(List) #The following doesn't work as with lists: Tuple2 =(x**2 for x in range(10)). #Also the entries of tuples cannot be modified like in lists or dictionaries. #This is useful when storing important information. print("The following is a list followed by tuple: \n%s\n%s \n" %(List,Tuple)) print("This was the old dictionary: \n %s \n" %Dictionary) for i in range(len(List)): print("%s \t%s \t%s " % (List[i], Tuple[i], Dictionary[i]) ) print("\n") #Note how all three types are referenced the same way, In a given #dictionary only the "value" is printed, for instance, # where the reference is the "key": Dictionary[key_0] = value_0. Copy_Dictionary = dict(Dictionary) #NOTE: Copy_Dictionary = Dictionary will not only copy, but both #will change dynamically. Here unwanted. In for loop fine? print("This is a copied dictionary: \n%s " %Copy_Dictionary) #-------------------------------------------------------------------------------- #THE CODE BELOW HAS TWO BETTER VERSIONS IN: dictionaries_from_lists.py #ACTUALLY REALLY BAD CODE HERE, AS THE FOR LOOP CRITICALLY DEPENDS ON #THE FIRST "key" OF dictionary TO BE EQUAL TO 0. dictionary = {0:'zero', 1:'one', 2:'four'} copy_dictionary = dict(dictionary) VALUES = list(dictionary.values()) for n in range(len(dictionary)): #Copy_Dictionary[ VALUES[n] ] = Copy_Dictionary.pop(n) copy_dictionary[ VALUES[n] ] = copy_dictionary[n] del copy_dictionary[n] print("\n \nThis is the old dictionary: \n %s" %dictionary) print("This is the new dictionary: \n %s\n" %copy_dictionary)
true
4e5a34a5a570d67a33a414124f62dd3b498e06a2
Robin-Andrews/Serious-Fun-with-Python-Turtle-Graphics
/Chapter 8 - The Classic Snake Game with Python Turtle Graphics/2. basic_snake_movement.py
1,362
4.25
4
# Import the Turtle Graphics module import turtle # Define program constants WIDTH = 500 HEIGHT = 500 DELAY = 400 # Milliseconds between screen updates def move_snake(): stamper.clearstamps() # Remove existing stamps made by stamper. # Next position for head of snake. new_head = snake[-1].copy() new_head[0] += 20 # Add new head to snake body snake.append(new_head) # Remove last segment of snake snake.pop(0) # Draw snake for segment in snake: stamper.goto(segment[0], segment[1]) stamper.stamp() # Refresh screen screen.update() # Rinse and repeat turtle.ontimer(move_snake, DELAY) # Create a window where we will do our drawing screen = turtle.Screen() screen.setup(WIDTH, HEIGHT) # Set the dimensions of the window screen.title("Snake") screen.bgcolor("pink") screen.tracer(0) # Turn off automatic animation # Stamper Turtle # This Turtle is defined at the global level, so is available to move_snake() stamper = turtle.Turtle("square") stamper.penup() # Create snake as a list of coordinate pairs. This variable is available globally. snake = [[0, 0], [20, 0], [40, 0], [60, 0]] # Draw snake for the first time for segment in snake: stamper.goto(segment[0], segment[1]) stamper.stamp() # Set animation in motion move_snake() # Finish nicely turtle.done()
true
501ca8c5a71b67cd7db14e7577be41fcd6646fd7
shantanusharma95/LearningPython
/DataStructures/priority_queue.py
2,988
4.25
4
import sys class node: def __init__(self,data,priority): self.data=data self.priority=priority self.next=None class queue: def __init__(self): self.Head=self.Tail=None self.queueSize=0 #adds a new value to queue, based on priority of data #this will make enqueue operation time complexity to O(n) against O(1) in normal queue def enqueue(self,data,priority): temp=node(data,priority) if self.Head==None: self.Head=temp self.Tail=temp else: if(self.queueSize==1): if(temp.priority>self.Head.priority): temp.next=self.Head self.Tail=temp else: self.Tail.next=temp self.Head=temp else: temp2=self.Tail temp3=self.Tail while(temp2!=None and temp.priority<=temp2.priority): temp3=temp2 temp2=temp2.next if(temp2==temp3): temp.next=temp3 self.Tail=temp else: temp3.next=temp temp.next=temp2 self.queueSize+=1 #removes the most oldest inserted value def dequeue(self): if self.queueSize==0: print("Queue is empty!\n") return temp=self.Tail self.Tail=temp.next del(temp) self.queueSize-=1 def sizeCheck(self): print("Size of queue is ",self.queueSize) def display(self): print("The queue contains...\n") temp=self.Tail while(temp!=None): print(temp.data," ") temp=temp.next def main(): queueObj=queue() while(True): #add a new element at head of queue print("1. Enqueue") #remove element from tail of queue print("2. Dequeue") #display size of stack print("3. Size Check") #display size of stack print("4. Display Queue") print("5. Exit") user_choice=input("Enter your Choice!\n") user_choice=int(user_choice) if user_choice == 1: data=input("Enter data : ") priority=int(input("Enter priority, lowest from 1 and onwards : ")) if(priority>0): queueObj.enqueue(data,priority) print("Updated Queue : \n") queueObj.display() else: print("Enter valid priority!") continue elif user_choice == 2: print("Removing from queue...") queueObj.dequeue() elif user_choice == 3: queueObj.sizeCheck() elif user_choice == 4: queueObj.display() elif user_choice == 5: sys.exit(0) else: print("Please enter a valid choice!") if __name__=='__main__': main()
true
08951c8a90dc3bffde4ce992e89a15ff0ba31acf
adudjandaniel/Fractions
/lib/fraction/fraction.py
2,313
4.1875
4
class Fraction(): '''A basic fraction data type in python''' def __init__(self, a=0, b=1): self.a = a self.b = b if b else 1 def __str__(self): '''Converts the instance to a string''' return "{}/{}".format(self.a, self.b) def __repr__(self): '''View of the instance in console''' return self.__str__() def __add__(self, next_fraction): '''Adds two instances (+)''' new_numerator = self.a * next_fraction.b + self.b * next_fraction.a new_denominator = self.b * next_fraction.b return Fraction(new_numerator, new_denominator).simplified() def __sub__(self, next_fraction): '''Subtracts the second instance passed to the function from the first (-)''' new_numerator = self.a * next_fraction.b - self.b * next_fraction.a new_denominator = self.b * next_fraction.b return Fraction(new_numerator, new_denominator).simplified() def __eq__(self, next_fraction): '''Test equality (==)''' return self.simplified().__str__() == next_fraction.simplified().__str__() def __mul__(self, next_fraction): '''Multiply two instances (*)''' new_numerator = self.a * next_fraction.a new_denominator = self.b * next_fraction.b return Fraction(new_numerator, new_denominator).simplified() def __truediv__(self, next_fraction): '''Divide the first instance by the second (/)''' next_fraction = Fraction(next_fraction.b, next_fraction.a) return self.__mul__(next_fraction) def simplify(self): '''Simplify the fraction. Return None.''' a = self.a b= self.b if b > a: a, b = b, a while b != 0: remainder = a % b a, b = b, remainder gcd = a self.a = int(self.a / gcd) self.b = int(self.b / gcd) def simplified(self): '''Simplify the fraction. Return the simplified fraction.''' a = self.a b= self.b if b > a: a, b = b, a while b != 0: remainder = a % b a, b = b, remainder gcd = a a = int(self.a / gcd) b = int(self.b / gcd) return Fraction(a,b)
true
41f9eaee34956ebf3e6688ebca4d55b095552448
yafiimo/python-practice
/lessons/11_ranges.py
992
4.21875
4
print('\nloops from n=0 to n=4, ie up to 5 non-inclusive of 5') for n in range(5): print(n) print('\nloops from 1 to 6 non-inclusive of 6') for n in range(1,6): print(n) print('\nloop from 0 to 20 in steps of 4') for n in range(0, 21, 4): print(n) print('\nloop through list like a for loop') food = ['chapatti', 'sambusa', 'katlesi', 'biryani', 'samaki'] for n in range(len(food)): print(n, food[n]) print('\nloop through list backwards') for n in range(len(food) - 1, -1, -1): print(n, food[n]) # starting from n=4, loop in steps of -1 until n=-1 non-inclusive # which covers all items in food array going backwards # range(x, y, z) # x is the starting point # y is the end point non-inclusive # z is the step size # LOOPING BACKWARDS THROUGH A LIST # using len(list)-1 as x makes the starting point the index of the last item in the list # using -1 as z makes the loop go backwards # using -1 as y (end point) loops through whole list including index 0
true
842079f591bef1485312dad98a8d44ad0cbace44
yafiimo/python-practice
/lessons/27_writing_files.py
941
4.125
4
# must use 'w' as 2nd argument to write to a file, and file_name as first argument with open('text_files/write_file.txt', 'w') as write_file: text1 = 'Hello, I am writing my first line to a file using Python!' print('Writing first line to file...') write_file.write(text1) # if you want to ammend a file, you must use the 'a' argument with open('text_files/write_file.txt', 'a') as write_file: text2 = '\nWriting a second line into the text file.' print('Adding a second line to file...') write_file.write(text2) quotes = [ '\nI\'m so mean I make medicine sick' '\nThe best preparation for tomorrow is doing your best today' '\nI am always doing that which I cannot do, in order that I may learn how to do it' ] # writing lines into a text file from list separated lines with open('text_files/write_file.txt', 'a') as write_file: print('Adding quotes to file...') write_file.writelines(quotes)
true
a40506eaf66ec0af19289816a30e8ff2039e5868
zerodayz/dailycoding
/Examples/Recursion.py
350
4.1875
4
def recursive(input): print("recursive(%s)" %input) if input <= 0: print("returning 0 into output") return input else: print("entering recursive(%s)" %( input -1 )) output = recursive(input -1) print("output = %s from recursive(%s)" %(output, input - 1)) return output print(recursive(3))
true
fd0494ab43d057e55d61d3a0b0c2797406da3e47
arpitsingh17/DataStructures
/binarysearch.py
697
4.125
4
# Binary Search # Input list must be sorted in this search method. def bin(alist,item): aalist = alist midterm = alist[(len(alist)//2)] found = False while True: try: if item < midterm: #print (alist[:((alist.index(midterm)))]) return(bin(alist[:((alist.index(midterm)))],item)) elif item > midterm: #print(alist.index(midterm)) return(bin(alist[(alist.index(midterm)+1):],item)) #print alist[(alist.index(midterm)+1):] elif item==midterm: return("Found") break except: return "Not Found" print (bin([1,2,3,4,5],42))
true
d5b0e6cae118c886d8ac206b3af3e16ca0b4edf5
j-thepac/Python_snippets
/SmallHighPow/smallhighpow.py
896
4.21875
4
""" We have the number 12385. We want to know the value of the closest cube but higher than 12385. The answer will be 13824. Now, another case. We have the number 1245678. We want to know the 5th power, closest and higher than that number. The value will be 1419857. We need a function find_next_power ( findNextPower in JavaScript, CoffeeScript and Haskell), that receives two arguments, a value val, and the exponent of the power, pow_, and outputs the value that we want to find. Let'see some cases: find_next_power(12385, 3) == 13824 find_next_power(1245678, 5) == 1419857 The value, val will be always a positive integer. The power, pow_, always higher than 1. Happy coding!! """ def find_next_power(val, pow_): n=2 while (n**pow_ < val): n+=1 return n**pow_ assert find_next_power(12385, 3) == 13824 assert find_next_power(1245678, 5) == 1419857 print("done")
true
08f2d5e5f13dcb98a8e419568b391b56439ae6cf
j-thepac/Python_snippets
/IntSeq/python/intseq.py
1,626
4.21875
4
""" Description: Complete function findSequences. It accepts a positive integer n. Your task is to find such integer sequences: Continuous positive integer and their sum value equals to n For example, n = 15 valid integer sequences: [1,2,3,4,5] (1+2+3+4+5==15) [4,5,6] (4+5+6==15) [7,8] (7+8==15) The result should be an array [sequence 1,sequence 2...sequence n], sorted by ascending order of the length of sequences; If no result found, return []. Some examples: findSequences(3) === [[1,2]] findSequences(15) === [[7,8],[4,5,6],[1,2,3,4,5]] findSequences(20) === [[2, 3, 4, 5, 6]] findSequences(100) === [[18, 19, 20, 21, 22], [9, 10, 11, 12, 13, 14, 15, 16]] findSequences(1) === [] """ def find_sequences(n): n1=n//2 res=[] for i in range(0,n1): tempRes=[] while True: i=i+1 tempRes.append(i) if(sum(tempRes)==n): res.append(tempRes) break elif (sum(tempRes)>n):break return res[::-1] def find_sequences2(n): n1=n//2 res=[] for i in range(1,n1+1): tempRes=[] for j in range(i,n-1): tempRes.append(j) if(sum(tempRes)>n):break elif(sum(tempRes)==n): res.append(tempRes) break print(n,res) return res[::-1] test_cases = [ # ( 3, [[1,2]]), ( 15, [[7,8], [4,5,6], [1,2,3,4,5]]), ( 20, [[2,3,4,5,6]]), (100, [[18,19,20,21,22], [9,10,11,12,13,14,15,16]]), ( 1, []), ] for n, expected in test_cases: assert(find_sequences(n)== expected) print("Done")
true
c7dfc6b9bbf3f103a6c4a127119edc8f0e0df1bd
j-thepac/Python_snippets
/Brackets/brackets.py
1,423
4.21875
4
""" Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false """ def isValid2(s: str) -> bool: s=s.replace("()","").replace("[]","").replace("{}","") if(len(s)%2!=0):return False if(s.count("(")!=s.count(")") or s.count("[")!=s.count("]") or s.count("{") != s.count("}")):return False l=list(s) while(len(l)!=0): m=(len(l)//2) if(l[m-1]=='(' and l[m]==')' or l[m-1]=='[' and l[m]==']' or l[m-1]=="{" and l[m]=='}'): del l[m] del l[m-1] else: return False return True def isValid(s: str) -> bool: if(len(s)%2!=0):return False if(s.count("(")!=s.count(")") or s.count("[")!=s.count("]") or s.count("{") != s.count("}")):return False while (len(s)>0): count=len(s) s=s.replace("()","").replace("[]","").replace("{}","") if(len(s)==count): return False return True assert (isValid("[([[]])]")==True) assert (isValid("(([]){})")==True) assert (isValid("()[]{}")==True) # assert(isValid("(]")==False)
true
ebf04b862009e61e6993d8216c0ffdb3db6cf5a2
j-thepac/Python_snippets
/SameCase/samecase.py
1,069
4.1875
4
""" Write a function that will check if two given characters are the same case. 'a' and 'g' returns 1 'A' and 'C' returns 1 'b' and 'G' returns 0 'B' and 'g' returns 0 '0' and '?' returns -1 If any of characters is not a letter, return -1. If both characters are the same case, return 1. If both characters are letters and not the same case, return 0. docker run -it --name samecase -p 5000:5000 -v $PWD:/home/app -w /home/app python:3.9-slim python samecase.py """ def same_case(a, b): if(len(a)>1 or len(b) > 1) :return -1 elif(ord(a) not in range(65,91) and ord(a) not in range(97,123) ):return -1 elif(ord(b) not in range(65,91) and ord(b) not in range(97,123) ): return -1 # (ord(b) in range(97,123) if( (a.isupper() and b.islower()) or (a.islower() and b.isupper()) ):return 0 else:return 1 assert(same_case('C', 'B')== 1) assert(same_case('b', 'a')== 1) assert(same_case('d', 'd')== 1) assert(same_case('A', 's')== 0) assert(same_case('c', 'B')== 0) assert(same_case('b', 'Z')== 0) assert(same_case('\t', 'Z')== -1) print("done")
true
14c7bf781e52c8f4eaa62b0d30dab3939d452180
j-thepac/Python_snippets
/Phoneno/phoneno.py
1,032
4.21875
4
""" Write a function that accepts an array of 10 integers (between 0 and 9)== that returns a string of those numbers in the form of a phone number. Example create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890" The returned format must be correct in order to complete this challenge. Don't forget the space after the closing parentheses! docker run -it --name phoneno -v $PWD:/home/app -w /home/app -p 5000:5000 python:3.9-slim python phoneno.py docker build -t phoneno:v1 . """ def create_phone_number(n): n="".join(str(i) for i in n) return "({}) {}-{}".format(n[0:3],n[3:6],n[6:]) assert(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])== "(123) 456-7890") assert(create_phone_number([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])== "(111) 111-1111") assert(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])== "(123) 456-7890") assert(create_phone_number([0, 2, 3, 0, 5, 6, 0, 8, 9, 0])== "(023) 056-0890") assert(create_phone_number([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])== "(000) 000-0000") print("done")
true
e362ff3a5d949f03cceb6f8de2602b06d1d2cac4
barthelemyleveque/Piscine_Python
/D00/ex06/recipe.py
2,559
4.125
4
import sys import time cookbook= { 'sandwich': { 'ingredients':['ham', 'bread', 'cheese', 'tomatoes'], 'meal':'lunch', 'prep_time':10, }, 'cake' : { 'ingredients':['flour', 'sugar', 'eggs'], 'meal':'dessert', 'prep_time':60 }, 'salad':{ 'ingredients':['avocado', 'arugula', 'tomatoes', 'spinach'], 'meal':'lunch', 'prep_time':15, } } def print_recipe(name): if name in cookbook: recipe = cookbook[name] print("Recipe for "+name+":") print("Ingredients list:" + str(recipe['ingredients'])) print("To be eaten for: "+str(recipe["meal"]+".")) print("Takes "+str(recipe["prep_time"])+" minutes of cooking.") else: print("Recipe doesn't exist") def delete_recipe(name): if name in cookbook: del cookbook[name] print(name + " recipe has been deleted\n") else: print("Cannot delete a recipe that doesn't exist") def add_recipe(name, ingredients, meal, prep_time): if name in cookbook: print("Recipe already exists") else: cookbook[name] = { 'ingredients': ingredients, 'meal': meal, 'prep_time': prep_time, } print("\nRecipe has been added :\n") print_recipe(name) def print_all(): for key in cookbook: print_recipe(key) print("----") i = input('Please select an option by typing the corresponding number:\n1: Add a recipe\n2: Delete a recipe\n3: Print a recipe\n4: Print the cookbook\n5: Quit\n') while (i.isdigit() != 0 or int(i) > 5 or int(i) == 0): if (int(i) == 1): recipe = input('Please enter the recipe name to add:\n') str_ingredients = input('Please enter the ingredients of the recipe, separated by commas and no spaces:\n') ingredients = str_ingredients.split(",") meal = input('Please enter which meal it is best for :\n') prep_time = input('Please enter which prep time :\n') add_recipe(recipe, ingredients, meal, prep_time) if (int(i) == 2): delete_recipe(input('Please enter the recipe name to delete:\n')) if (int(i) == 3): print_recipe(input('Please enter the recipe name to get details:\n')) if (int(i) == 4): print_all() if (int(i) == 5): sys.exit("Goodbye !\n") time.sleep(4) i = input('Please select an option by typing the corresponding number:\n1: Add a recipe\n2: Delete a recipe\n3: Print a recipe\n4: Print the cookbook\n5: Quit\n')
true
ce499afe3bf4323bc35f81eda9cb02bbeb866f2b
anand13sethi/Data-Structures-with-Python
/Queue/QueueReverse.py
963
4.15625
4
# Reversing a Queue implemented using singly link list using stack. from QueueUsingLinkList import Queue class Stack: def __init__(self): self.stack = [] self.size = 0 def is_empty(self): return self.size <= 0 def push(self, data): self.stack.append(data) self.size += 1 def pop(self): if self.is_empty(): raise ValueError("Underflow!") else: self.size -= 1 return self.stack.pop() def peek(self): if self.is_empty(): raise ValueError("Peeking Into Empty Stack!") else: return self.stack[self.size] def reverse_queue(que=Queue()): aux_stack = Stack() if que.is_empty(): raise ValueError("Empty Queue!") else: while not que.is_empty(): aux_stack.push(que.dequeue()) while not aux_stack.is_empty(): que.enqueue(aux_stack.pop()) return que
true
1b6bc1d29ff40669e1d3f47d92f5675934c4c8c8
joeybtfsplk/projecteuler
/10.py
1,353
4.125
4
#!/usr/bin/env python """ file: 10.py date: Thu Jul 31 09:25:11 EDT 2014 from: Project Euler: http://projecteuler.net auth: tls purp: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Ans: 142913828922 on Fri Aug 1 22:34:07 EDT 2014 """ def prime_list(num): """ From: http://en.wikibooks.org/wiki/Efficient_Prime_Number_Generating_ Algorithms Return primes up to but not including num. Acts goofy below 20. """ from math import sqrt pp=2 ep=[pp] pp+=1 tp=[pp] ss=[2] #lim=raw_input("\nGenerate prime numbers up to what number? : ") lim= int(num) while pp<int(lim): pp+=ss[0] test=True sqrtpp=sqrt(pp) for a in tp: if a>sqrtpp: break if pp%a==0: test=False break if test: tp.append(pp) ep.reverse() [tp.insert(0,a) for a in ep] return tp def main(): """ """ num= 2000000 ans= prime_list(num) print("Sum of primes found between 2 and %d: %d" % (num, sum(ans))) print("Found a total of %d primes." % len(ans)) if len(ans) <= 6: print("Primes: %s" % str(ans)) else: print("From %s... to ...%s" % (str(ans[:3]),ans[-3:])) return 0 if __name__ == "__main__": main()
true
0cd3f80f80bed75176e9ca50eb0f928d73df4cc6
zw-999/learngit
/study_script/find_the_largest.py
481
4.21875
4
#!/usr/bin/env python # coding=utf-8 import sys def find_largest(file): fi = open(file,"r") for line in fi: line = line.split() print line #fi.close() #line = fi.readline() largest = -1 for value in line.split(): v = int(value[:-1]) if v > largest: largest = v return largest if __name__=='__main__': file = '/home/ellen/learngit/aaa.txt' test = find_largest(file) print test
true
87424e37b3e029ddd8fcc1ccd752b23fc5864b33
Kavitajagtap/Python3
/Day8.py
1,852
4.59375
5
# 1.Write a program to create dictionary and access all elements with keys and values dict = eval(input("Enter dictionary = ")) print("Accessing Elements from dictionary -->") for key in dict: print(key,dict[key]) ''' Output : Enter dictionary = {'Apple':2017,'Microsoft':1985,'Facebook':2012,'Amazon':1997} Accessing Elements from dictionary --> Apple 2017 Microsoft 1985 Facebook 2012 Amazon 1997 ''' --------------------------------------------------------------------------------------------------- # 2.Write a Program to sort (ascending and descending) a dictionary by value. dict = {} n = int(input("Enter elements: ")) for i in range(n): k = (input("key: ")) v = int(input("value: ")) dict[k] = v print("dictionary =",dict) print("sorted dictionary in ascending order =",sorted(dict.items(), key=lambda x: x[1])) print("sorted dictionary in descending order =",sorted(dict.items(), key=lambda x: x[1],reverse = True)) ''' Output: Enter elements: 4 key: a value: 4 key: b value: 1 key: c value: 6 key: d value: 3 dictionary = {'a': 4, 'b': 1, 'c': 6, 'd': 3} sorted dictionary in ascending order = [('b', 1), ('d', 3), ('a', 4), ('c', 6)] sorted dictionary in descending order = [('c', 6), ('a', 4), ('d', 3), ('b', 1)] ''' ------------------------------------------------------------------------------------------------------ # 3.Write a Program to add a key to a dictionary. dict = eval(input("Enter dictionary:")) key = input("key: ") value = int(input("value: ")) dict.update({key:value}) print("updated dictionary =",dict) ''' Output: Enter dictionary:{'Apple':2017,'Microsoft':1985,'Facebook':2012} key: Amazon value: 1997 updated dictionary = {'Apple': 2017, 'Microsoft': 1985, 'Facebook': 2012, 'Amazon': 1997} ''' -------------------------------------------------------------------------------------------------
true
71432b142344cfa33686bf7bdcaeafb4f2d4b372
Kavitajagtap/Python3
/Day16.py
1,528
4.3125
4
""" 1. Write program to sort Counter by value. Sample data : {'Math':81, 'Physics':83, 'Chemistry':87} Expected data: [('Chemistry', 87), ('Physics', 83), ('Math', 81)] """ dict = {} n = int(input("Enter elements: ")) for i in range(n): k = (input("key: ")) v = int(input("value: ")) dict[k] = v print("dictionary = ",dict) print("Dictionary sorted by value = ") print(sorted(dict.items(), key=lambda x: x[1], reverse=True)) ------------------------------------------------------------------------------------------------------------ ## 2. Write a program to create a dictionary from two lists without losing duplicate values. l1 = [] num = int(input("First list\nlength of a list:")) print("Enter elements of list:") for i in range(num): l1.append((input())) l2 = [] num = int(input("Second list\nlength of a list:")) print("Enter elements of list:") for i in range(num): l2.append(int(input())) d = {l1[i]: l2[i] for i in range(len(l1))} print("dictionary =",d) ------------------------------------------------------------------------------------------------------------ ## 3. Write a program to replace dictionary values with their average. dict = {} n = int(input("Enter elements: ")) for i in range(n): k = (input("key: ")) v = eval(input("value: ")) dict[k] = v print("dictionary = ",dict) d1 = {k:sum(v)/len(v) for k, v in dict.items()} print("New dictionary =",d1) ------------------------------------------------------------------------------------------------------------
true
b369a56787f0a1d15519d7e228ac7ef2ef6b849a
VolodymyrMeda/Twittmap
/json_navigator.py
1,646
4.1875
4
import json def reading_json(file): ''' str -> dict Function reads json file and returns dictionary ''' with open(file, mode='r', encoding='utf-8') as rd: json_read = json.load(rd) return json_read def json_navigation(json_read): ''' Function navigates user in json dictionary ''' step_set = set() for step in json_read: step_set.add(step) navigate = input('Enter one of the list words to go to the next ' 'json step or enter 0 to go to the first stage ' 'enter 1 to exit: \n' + str(step_set) + '\n') if navigate == '1': return quit() elif navigate == '0': return json_navigation(reading_json(file='json_api.json')) elif navigate not in step_set: print('You entered the wrong word! Try again') return json_navigation(json_read) elif navigate in step_set: if type(json_read[navigate]) == dict: print(str(json_read[navigate]) + ' - this is the result') return json_navigation(json_read[navigate]) else: print(str(json_read[navigate]) + ' - this is the final result') stay = input('Enter 1 to quit or 0 to go to the first stage of json: ') if stay == '1': quit() elif stay == '0': return json_navigation(reading_json(file='json_api.json')) else: print('You entered the wrong word! Try again') return json_navigation(json_read) if __name__ == '__main__': print(json_navigation(reading_json('json_api.json')))
true
a75fa80c8412141fd7e8b28978b5a7f92643fbed
annmag/Student-manager
/generator_function.py
985
4.21875
4
# Generator function - a way of crating iterators (objects which you can iterate over) # Creating generator - defining function with at least one yield statement (or more) instead of return statement # Difference: return terminates a function entirely # yield pauses the function saving all it's states and continues there on successive calls # Once the function yields, the function is paused and the control is transferred to the caller students = [] def read_students(file): # This is a generator function for line in file: # For loop - to iterate over the file yield line def read_file(): try: file = open("students.txt", "r") for student in read_students(file): # For loop - to go through all the results from called function students.append(student) # and add them to the list file.close() except Exception: print("The file can't be read") read_file() print(students)
true
0bd27accb7021db31fbfd540a9318d768adb366c
gokullogu/pylearn
/tutorial/list/add.py
550
4.25
4
#to add the the value to end of list use append cars=["audi","bens","rolls royce"] cars.append("bmw") print(cars) #['audi', 'bens', 'rolls royce', 'bmw'] #to append the list to the list use extend fruit=["apple","mango","banana"] veg=["carrot","beetroot","brinjal"] fruit.extend(veg) print(fruit) #['apple', 'mango', 'banana', 'carrot', 'beetroot', 'brinjal'] #to append the set,tuples,dictionaries to list use extend name=["john", "peter", "kenn"] details=(18, "america") name.extend(details) print(name) #['john', 'peter', 'kenn', 18, 'america']
true
50e3a4dbe8af7537d416e830a6882fcacf7fce1e
gokullogu/pylearn
/tutorial/list/remove.py
778
4.28125
4
#remove() removes item sepecified fruit=["mango","orange","papaya"] fruit.remove("mango") print(fruit) #['orange', 'papaya'] #pop() removes the list item at specified index this_list=["john","19","poland"] this_list.pop(1) print(this_list) #['john', 'poland'] #pop() removes the last item if unspecified this_list1 = ["john", "19", "poland"] this_list1.pop() print(this_list1) #['john', '19'] #del without index deletes the list completely thislist2=["xenon","randon","zinc"] del thislist2 #print(thislist2) #NameError: name 'thislist2' is not defined #del woth index delete the item at specified index chem=["H2O","H2","OH"] del chem[0] print(chem) #['H2', 'OH'] #clear method empties the list but do not delete it lan=["c","cpp","java","python"] lan.clear() print(lan)
true
bff509e7057885d4a0c7e480c09a4605db36bcb8
ChadevPython/WeeklyChallenge
/2017/02-06-2017/EthanWalker/main.py
240
4.3125
4
#!/usr/bin/env python3 from reverse_str import reverse_line import sys #open file and get lines with open(sys.argv[1], 'r') as in_file: file = in_file.readlines() # print reversed lines for line in file: print(reverse_line(line))
true
9a63728319bc7a007e3edcc2acf916c0e32b988a
Arunken/PythonScripts
/2_Python Advanced/8_Pandas/10_Sorting.py
1,643
4.46875
4
# -*- coding: utf-8 -*- """ Created on Thu Jun 21 14:30:07 2018 @author: SilverDoe """ ''' There are two kinds of sorting available in Pandas : 1. By Label 2. By Actual Value ''' '''================== Sorting By Label ========================================''' import pandas as pd import numpy as np unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1']) # based on row index sorted_df=unsorted_df.sort_index(axis=0,ascending=True)# ascending order. # ascending is true by default,axis = 0 by default print(sorted_df) sorted_df = unsorted_df.sort_index(axis=0,ascending=False) # descending order print(sorted_df) #based on columns sorted_df=unsorted_df.sort_index(axis=1,ascending=True)# ascending order print(sorted_df) sorted_df = unsorted_df.sort_index(axis=1,ascending=False) # descending order print(sorted_df) '''=================== Sorting By Value =======================================''' ''' Like index sorting, sort_values() is the method for sorting by values. It accepts a 'by' argument which will use the column name of the DataFrame with which the values are to be sorted ''' import pandas as pd import numpy as np unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]}) # based on a specific column sorted_df = unsorted_df.sort_values(by='col1') print(sorted_df) # based on multiple columns sorted_df = unsorted_df.sort_values(by=['col1','col2']) print(sorted_df) # specifying sorting alorithm sorted_df = unsorted_df.sort_values(by='col1' ,kind='mergesort') # mergesort, heapsort and quicksort print(sorted_df)
true
991d140f7e4100ae35f740c3b97f1ed62de4e7f9
Krishnaarunangsu/LoggingDemonstration
/python_slice_1.py
1,427
4.5
4
# The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step). # The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method). # Slice object represents the indices specified by range(start, stop, step). # The syntax of slice() are: # slice(stop) # slice(start, stop, step) # slice() Parameters # slice() mainly takes three parameters which have the same meaning in both constructs: # start - starting integer where the slicing of the object starts # stop - integer until which the slicing takes place. The slicing stops at index stop - 1. # step - integer value which determines the increment between each index for slicing # If a single parameter is passed, start and step are set to None. print(slice(3)) print(slice(1, 5, 2)) # Get substring from a given string using slice object py_string: str = 'Python' # Contains indices(0, 1, 1, 2) # i.e. that is P, y, t index_1=slice(3) print(py_string[index_1]) # contains indices (1, 3) # i.e. y and h index_2 = slice(1, 5, 2) print(py_string[index_2]) index_3 = slice(2) print(py_string[index_3]) # contains indices (-1, -2, -3) # i.e. n, o and h index_4 = slice(-1, -4, -1) print(index_4) print(py_string[index_4]) # https://www.programiz.com/python-programming/methods/built-in/slice
true
f718803b224aff52828ca1c194f63fdb8706e64f
yashshah4/python-2
/ex6.py
725
4.375
4
#creating a string x with formatting method %d x = "There are %d types of people." % 10 #creating further strings binary = "binary" do_not = "don't" #creating a second string with string formatting method y = "Those who know %s and those who %s" %(binary, do_not) #printing the first two strings print x print y #using two printing methods below to highlight the difference between %r & %s print "I said %r." %x print "I also said : `%s`." % y #further highlighting the usage of %r hilarious = False joke_evaluation = "Isnt't that joke so funny?! %r" print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side" #concatenating two strings using '+' print w + e
true
07cf522b16d5d13d48a8a8422ea10b84a60c81b4
Gladarfin/Practice-Python
/turtle-tasks-master/turtle_11.py
319
4.1875
4
import turtle turtle.shape('turtle') turtle.speed(100) def draw_circle(direction, step): angle=2*direction for i in range(180): turtle.forward(step) turtle.left(angle) step=2.0 turtle.left(90) for i in range(0, 10, 1): draw_circle(1, step) draw_circle(-1, step) step+=0.3
true
e0b4849d6bea59c51b50017d00ba93b5defb7963
johnmarkdaniels/python_practice
/odd_even.py
272
4.125
4
num = int(input('Please input a number: ')) if num % 2 == 0: print(f'Your number ({str(num)}) is an even number.') if num % 4 == 0: print('Incidentally, your number is evenly divisible by 4.') else: print(f'Your number ({str(num)}) is an odd number.')
true
508e4a3139bca354467178cbc2687416924599ea
Harpreetkaurpanesar25/python.py
/anagram.py
267
4.1875
4
#an anagram of a string is another string that contains same char, only the order of characters are different def anagram(s1,s2): if sorted(s1)==sorted(s2): print("yes") else: print("no") s1=str(input("")) s2=str(input("")) anagram(s1,s2)
true
56c6c4417ca6f8dd1bc1880957484ed343b2a81d
teayes/Python
/Experiments/Exp6.py
731
4.15625
4
class stringValidation: def __init__(self): self.open= ["[", "{", "("] self.close= ["]", "}", ")"] def validate(self,string): stack = [] for char in string: if char in self.open: stack.append(char) elif char in self.close: pos = self.close.index(char) if len(stack) and (self.open[pos] == stack[-1]): stack.pop() else: return False if not len(stack): return True sv=stringValidation() string=input("Enter a string:") check=sv.validate(string) if check: print("The brackets are in order") else: print("The brackets are not in order")
true
77c6300b4d7a20a073b857c545c8d702eee86595
AlexKasapis/Daily-Coding-Problems
/2019-02-23.py
1,252
4.125
4
# PROBLEM DESCRIPTION # Given a sorted list of integers, square the elements and give the output in sorted order. # For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81]. # # SOLUTION # Lets assume two pointers, pointing to the start and end of the list. The pointer which points to the number with the # highest absolute value moves towards the other. The number, after it has been squared, is inserted to the start of # the output list. This loop stops when the two pointers pass each other. This solution has a time complexity of O(n). if __name__ == '__main__': numbers = [-9, -2, 0, 2, 3] # Example list output = [] # Initiate the left and right pointers left_pointer = 0 right_pointer = len(numbers) - 1 # Loop until the two pointers pass each other, meaning that right pointer will be on the left side of the left # pointer and thus having a lower value than the right pointer. while left_pointer <= right_pointer: if abs(numbers[left_pointer]) > abs(numbers[right_pointer]): output.insert(0, pow(numbers[left_pointer], 2)) left_pointer += 1 else: output.insert(0, (pow(numbers[right_pointer], 2))) right_pointer -= 1 print(output)
true
527835943216d348696b0ad6ed7f8ba521e5a56d
afrahaamer/PPLab
/III Regular Expressions/1 RegEx Functions/findall/Metacharachters/ends with.py
241
4.21875
4
# $ - Pattern ends with # ^ - Pattern starts with import re t = "Hello, How are you World" # Checks if string ends with World? x = re.findall("World$",t) print(x) # Checks if string starts with Hello x = re.findall("^Hello",t) print(x)
true
312c35e0ee73ce3aa7b0836cf8f594d030ac1054
MostDeadDeveloper/Python_Tutorial_Exercises
/exercise3.py
357
4.21875
4
# Challenge - Functions Exercise # Create a function named tripleprint that takes a string as a parameter # and prints that string 3 times in a row. # So if I passed in the string "hello", # it would print "hellohellohello" def tripleprint(val): print(val*3) return val*3 #tripleprint("hello") # ^ - remove this to see the function call.
true
0340d501babc4af06989c1455a8026e0b76c7cc8
bchhun/Codes-Kata
/prime_factors.py
1,509
4.21875
4
#coding: utf-8 """ Compute the prime factors of a given natural number. Bernard says: What is a prime factor ? http://en.wikipedia.org/wiki/Prime_factor Test Cases ([...] denotes a list) primes(1) -> [] primes(2) -> [2] primes(3) -> [3] primes(4) -> [2,2] primes(5) -> [5] primes(6) -> [2,3] primes(7) -> [7] primes(8) -> [2,2,2] primes(9) -> [3,3] """ import unittest, math def is_prime(num): """ http://en.wikipedia.org/wiki/Prime_number """ i = 2 while i <= math.sqrt(num): if num % i == 0: return False i += 1 return True def primes(num): primes_list = [] base = 2 possibilities = xrange(base, num+1) possibility = base while (not primes_list) and (possibility in possibilities): if is_prime(possibility) and num % possibility == 0: primes_list = primes_list + [possibility] + primes(num/possibility) possibility += 1 return primes_list class primesTest(unittest.TestCase): def test_unique(self): self.assertEqual(primes(1), []) self.assertEqual(primes(2), [2]) self.assertEqual(primes(3), [3]) self.assertEqual(primes(5), [5]) self.assertEqual(primes(7), [7]) def test_multiple(self): self.assertEqual(primes(4), [2,2]) self.assertEqual(primes(6), [2,3]) self.assertEqual(primes(8), [2,2,2]) self.assertEqual(primes(9), [3,3]) def main(): unittest.main() if __name__ == '__main__': main()
true
c3272a68e7f7705810f956609b24d6a6477d2faa
kimmvsrnglim/DigitalCrafts
/week2/print_triangle.py
222
4.1875
4
def triangle(height): for x in range(0, height, 2): space = " " * ((height - x)/2) print space + "*" * (x + 1) user_input = int(raw_input("What's the height of your triangle?")) triangle (user_input)
true
ee0d216b772925a8a2713e8ed7be384cd2e4f5fd
xandhiller/learningPython
/stringTidbits.py
454
4.40625
4
print('Enter a string: ') n = input() print("\nLength of string is: " + str(len(n))) print() # Starting i at 1 because i determines the non-inclusive upper limit of string # truncation. for i in range(1, len(n)+1): print("string[0:"+str(i)+"]: \t" + n[0:i]) print() # Conclusions: # The operator 'string[0:8]' will take the zeroth element up to element 7. # The operator 'string[1:8]' will take element one (second letter) up to # element 7.
true
b1c3fa918bcbc2fa1ac9f877291389d52eaf0278
JuanDAC/holbertonschool-higher_level_programming
/0x06-python-classes/101-square.py
1,910
4.5625
5
#!/usr/bin/python3 """File with class Square""" class Square: """Class use to represent a Square""" def __init__(self, size=0, position=(0, 0)): """__init__ constructor method""" self.size = size self.position = position @property def size(self): return self.__size @size.setter def size(self, value): if type(value) is not int: raise TypeError("size must be an integer") if value < 0: raise ValueError("size must be >= 0") self.__size = value @property def position(self): return self.__position @position.setter def position(self, value): if type(value) is not tuple or len(value) != 2: raise TypeError("position must be a tuple of 2 positive integers") for i in range(len(value)): if type(value[i]) is not int or value[i] < 0: raise TypeError( "position must be a tuple of 2 positive integers") self.__position = value def area(self): """area that returns the current square area""" return self.size ** 2 def my_print(self): """my_print that prints in stdout the square with the character #""" if not self.size: print() print(self) def __str__(self): """__string__ that prints in stdout the square with the character #""" string = "" size = self.size if size: string += (self.position[1] * "\n") for i in range(size): newline = "\n" if (size - 1 != i) else "" string += (self.position[0] * " " + size * "#") + newline return string if __name__ == "__main__": my_square = Square(5, (0, 0)) print(my_square) print("--") my_square = Square(5, (4, 1)) print(my_square) print("--") my_square.my_print()
true
2aac08cdac3ed1a5dc6c875d5ebb9f91e900bb81
daveshanahan/python_challenges
/database_admin_program.py
1,848
4.15625
4
log_on_info = { "davids1":"MahonAbtr!n1", "lydiam2":"Password1234", "carlynnH":"scheduling54321", "maryMcN":"Forecaster123", "colinM":"paymentsG145", "admin00":"administrator5", } print("Welcome to the database admin program") username = input("\nPlease enter your username: ").strip() # logic for control flow if username in log_on_info: password = input("Please enter your password: ").strip() if password in log_on_info[username]: print("\nHello " + username + "! You are logged in") # if admin logs in if username == "admin00": print("Here is the current database:\n") for keys, values in log_on_info.items(): print("Username: " + keys + "\t\tPassword: " + values) else: # if other user logged in change_choice = input("Would you like to change your password: ").lower() if change_choice.startswith("y"): new_password = input("What would you like to change your password to: ") # check password length and add to dict if correct length if len(new_password) >= 8: log_on_info[username] = new_password print("\n" + username + ", your new password is " + new_password) # else reject password and display original elif len(new_password) < 8: print(new_password + " is not the minimum password length of 8 characters.") print("\n" + username + ", your password is " + password) elif change_choice.startswith("n"): print("Ok. Thank you for using the database admin program.") else: print("Password incorrect!") else: print("Username not found. Goodbye!")
true
78fd793c2ca6e3021894ee562e7d7cc5ad32b990
daveshanahan/python_challenges
/Quadratic_Equation_Solver_App.py
1,261
4.375
4
import cmath # print introduction print("Welcome to the Quadratic Equation Solver App") print("\nA Quadratic equation is of the form ax^2 + bx + c = 0.") print("Your solutions can be real or complex numbers.") print("A complex number has two parts: a + bj") print("Where a is the real portion and bj is the imaginary portion.") # gather user input and create list to iterate over num_equations = int(input("\nHow many equations would you like to solve today: ")) list_equations = list(range(0,num_equations)) #loop through interable to solve for roots of each equation for i in list_equations: print("\nSolving equation #" + str(i + 1)) print("----------------------------------") a = float(input("\nPlease enter your value of a (coefficient of x^2: ")) b = float(input("Please enter your value of b (coefficient of x): ")) c = float(input("Please enter your value of c (coefficient): ")) d = (b**2)-(4*a*c) print("\nThe solutions to " + str(a) + "x^2 + " + str(b) + "x + " + str(c) + " = 0 are:") x1 = (-b+cmath.sqrt(d))/2*a print("\nx1 = " + str(x1)) x2 = (-b-cmath.sqrt(d))/2*a print("x2 = " + str(x2)) print("\nThank you for using the Quadratic Equation Solver App. Goodbye.")
true
c6ab0fa71832cc589f844da6120d509fedd04a15
daveshanahan/python_challenges
/guess_my_number_game.py
893
4.21875
4
import random print("Welcome to the Guess My Number App") # gather user input name = input("\nHello! What is your name: ").title().strip() # generate random number print("Well " + name + ", I am thinking of a number between 1 and 20.") random_num = random.randint(1,20) # initialise guess counter and get user to take guesses guess_count = 0 for i in range(5): guess = int(input("\nTake a guess: ")) if guess < random_num: guess_count += 1 print("Too low!") elif guess > random_num: guess_count += 1 print("Too high!") else: guess_count += 1 break # print game recap statement if guess == random_num: print("\nGood job, " + name + "! You guessed my number in " + str(guess_count) + " guesses.") else: print("\nGame over! The number I was thinking of is " + str(random_num) + ".")
true
0deda362dc460620ab43364b17599182f1f12e87
daveshanahan/python_challenges
/grade_point_average_calculator.py
2,658
4.4375
4
print("Welcome to the average calculator app") # gather user input name = input("\nWhat is your name? ").title().strip() num_grades = int(input("How many grades would you like to enter? ")) print("\n") # initialise list and append number of grades depending on user input grades = [] for i in range(num_grades): grades.append(int(input("Please enter a grade: "))) # sort grades and print list of grades in descending order grades.sort(reverse=True) print("\nGrades Highest to Lowest: ") for i in grades: print("\t" + str(i)) # calculate average grade avg_grade = round(float(sum(grades)/len(grades)), 2) # print summary table print("\n" + name + "'s Grade Summary:\n\tTotal number of grades: " + str(len(grades)) + "\n\tHighest grade: " + str(max(grades)) + "\n\tLowest grade: " + str(min(grades)) + "\n\tAverage grade: " + str(avg_grade)) # get user input to calculate grade needed to get new average desired_avg = float(input("\nWhat is your desired average? ")) req_grade = (desired_avg*(len(grades)+1))-float(sum(grades)) # print req_grade message for user print("\nGood luck " + name + "!\nYou will need to get a " + str(req_grade) + " on your next assignment to earn a " + str(desired_avg) + " average.") print("\nLet's see what your average could have been if you did better/worse on an assignment.") # make copy of list to use for rest of program grades_two = grades.copy() # gather user input to change grade ch_grade = int(input("What grade would you like to change: ")) new_grade = int(input("What grade would you like to change " + str(ch_grade) + " to: ")) # remove old grade, add new grade grades_two.remove(ch_grade) grades_two.append(new_grade) # sort grades and print list of grades in descending order grades_two.sort(reverse=True) print("\nGrades Highest to Lowest: ") for i in grades_two: print("\t" + str(i)) # calculate new average grade new_avg_grade = round(float(sum(grades_two)/len(grades_two)), 2) # print summary again with new grades print("\n" + name + "'s New Grade Summary:\n\tTotal number of grades: " + str(len(grades_two)) + "\n\tHighest grade: " + str(max(grades_two)) + "\n\tLowest grade: " + str(min(grades_two)) + "\n\tAverage grade: " + str(new_avg_grade)) # print comparison of average scores and last statements print("Your new average would be a " + str(new_avg_grade) + " compared to your real average of " + str(avg_grade) + ".\nThat is a change of " + str(round(new_avg_grade-avg_grade, 2)) + " points!") print("\nToo bad your original grades are still the same!\n" + str(grades) + "\nYou should go ask for extra credit!")
true
a85f63d5cfc5b211612bb92d388bbfb9526de482
davidac2007/python_tutorials
/numbers.py
2,448
4.5
4
# Python numbers # There are three numeric types in Pythom: # int x = 1 # float y =2.8 # complex z = 1j print(type(x)) print(type(y)) print(type(z)) # Int # Int or integer, is a whole number, positive or negative, without decimals, # of unlimited length. x = 1 y = 366376429 z = -3255522 print(type(x)) print(type(y)) print(type(z)) # Float # Float, or "floating point number",positive or negative, # containing one or more decimals. x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) # Float can also be scientific numbers with an "e" to indicate the power of 10. x = 35e3 y = 12E4 z = -87.7e100 print(type(x)) print(type(y)) print(type(z)) # Complex # Complex numbers are written with a "j" as the imaginary part: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) # Type conversion # You can convert from one type to another with the int(), float(), amd complex() methods: x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) # You cannot convert complex numbers into another number type. # Random number # Python does not have a random() function to make a random number, # but Python has a built-in module called random that can be used # to make random numbers: # Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1,10)) # Python Casting # Casting in python is therefore done using constructor functions: ''' int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals ''' # Integers x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3 # Floats x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2 # Strings: x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0'
true
9dda68c3e93388399b7d1026d82efa2d41ea26a5
GuhanSGCIT/Trees-and-Graphs-problem
/The lost one.py
2,750
4.375
4
""" Shankar the Artist had two lists that were permutations of one another. He was very proud. Unfortunately, while transporting them from one exhibition to another, some numbers were lost out of the first list. Can you find the missing numbers? As an example, the array with some numbers missing, arr=[7,2,5,3,5,3]. The original array of numbers brr=[7,2,5,4,6,3,5,3]. The numbers missing are [4,6]. Notes: If a number occurs multiple times in the lists, you must ensure that the frequency of that number in both lists is the same. If that is not the case, then it is also a missing number. You have to print all the missing numbers in ascending order. Print each missing number once, even if it is missing multiple times. The difference between the maximum and minimum number in the second list is less than or equal to 100. arr: the array with missing numbers brr: the original array of numbers timing:2sec level:6 Input: There will be four lines of input: N is the size of the first list, arr. The next line contains N space-separated integers arr[i]. M is the size of the second list, brr. The next line contains M space-separated integers brr[i]. Output: Output the missing numbers in ascending order separated by space. Constraints 1≤n,m≤2 X 10^5 n≤m 1≤brr[i]≤10^4 Xmax - Xmin ≤100 Sample Input: 10 203 204 205 206 207 208 203 204 205 206 13 203 204 204 205 206 207 205 208 203 206 205 206 204 Sample Output: 204 205 206 EXPLANATION: 204 is present in both arrays. Its frequency in arr is 2, while its frequency in brr is 3. Similarly, 205 and 206 occur twice in arr, but three times in brr. The rest of the numbers have the same frequencies in both lists. input: 12 1 5 6 7 9 11 2 3 6 7 10 11 4 11 20 9 11 output: 20 input: 8 12 23 45 56 13 23 46 47 5 1 3 5 2 4 output: 1 2 3 4 5 input: 6 111 333 555 222 402 302 7 103 204 506 704 204 511 699 output: 704 103 204 506 699 511 input: 3 1 5 2 4 10 20 30 10 output: 10 20 30 hint: The main task is to find the frequency of numbers in each array. This can be done using count array. If the frequency of a number is different, then print that number. we can have two count arrays for each array. Then we need to run a loop for the count array. While traversing the array if frequencies mismatch, print that number. """ from sys import stdin,stdout n=int(stdin.readline()) d={} arr=[int(num) for num in stdin.readline().split()] m=int(stdin.readline()) brr=[int(num) for num in stdin.readline().split()] if n-m==0: print(0) else: for i in set(brr): if brr.count(i)!=arr.count(i): print(i,end=' ')
true
60652845c16c2840261f73b47b9225abd39ca9b0
GuhanSGCIT/Trees-and-Graphs-problem
/Spell Bob.py
2,515
4.3125
4
""" Varun likes to play with cards a lot. Today, he's playing a game with three cards. Each card has a letter written on the top face and another (possibly identical) letter written on the bottom face. Varun can arbitrarily reorder the cards and/or flip any of the cards in any way he wishes (in particular, he can leave the cards as they were). He wants to do it in such a way that the letters on the top faces of the cards, read left to right, would spell out the name of his favorite friend Bob. Determine whether it is possible for Varun to spell "bob" with these cards. Input The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single string with length 3 denoting the characters written on the top faces of the first,second and third card. The second line contains a single string with length 3 denoting the characters written on the bottom faces of the first,second and third card. Output For each test case, print a single line containing the string "yes" (without quotes) if Chef can spell "bob" or "no" (without quotes) if he cannot. Constraints 1≤T≤20,000 each string contains only lowercase English letters Example Input 3 bob rob dbc ocb boc obc Example Output yes yes no Explanation Example case 1: The top faces of the cards already spell out "bob". Example case 2: Chef can rearrange the cards in the following way to spell "bob": the second card non-flipped, the first card flipped and the third card flipped. Example case 3: There is no way for Chef to spell out "bob". input: 5 kok obo kol bbo mom bob lok non bbo boo output: no yes yes no yes input: 1 boo oob output: yes input: 2 ooo bbb bob bob output: yes yes input: 5 bbb oob ooo bob obo obc abs abb boa ala output: yes yes no no no hint: First, fix the letter ooo for the middle card. Now, try the remaining cards and check if both of them contain a “b” on either side of them. """ T = int(input()) for _ in range(T): s = input() t = input() ok = False for i in range(3): if s[i] == 'o' or t[i] == 'o': cnt = 0 for j in range(3): if j != i: if s[j] == 'b' or t[j] == 'b': cnt += 1 if cnt == 2: ok = True print("yes" if ok else "no");
true
4472990ca9ef518a8e02dfcd668a19b7fcefd1ab
GuhanSGCIT/Trees-and-Graphs-problem
/snake pattern.py
1,244
4.28125
4
""" Given an M x N matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern. i des First line contains two space separated integers M,N,which denotes the dimensions of matrix. Next for each M lines contains N space separated integers,denotes the values. Odes print the snake Exp From sample the first row is printed as same and the second row is appended reversed with the first. 1 2 3 7 6 5 Hin We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. In 3 3 1 2 3 4 5 6 7 8 9 Ot 1 2 3 6 5 4 7 8 9 In 2 3 1 2 3 5 6 7 ot 1 2 3 7 6 5 In 1 1 1 ot 1 In 3 2 1 1 1 1 1 1 ot 1 1 1 1 1 1 In 5 3 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 ot 1 2 3 6 5 4 7 8 9 3 2 1 4 5 6 T 600 """ M,N=map(int,input().split()) def printf(mat): global M, N for i in range(M): if i % 2 == 0: for j in range(N): print(str(mat[i][j]), end = " ") else: for j in range(N - 1, -1, -1): print(str(mat[i][j]), end = " ") mat=[] for i in range(M): l=list(map(int,input().split())) mat.append(l) printf(mat)
true
6012371aef940cf255e34f4d6960533564924be4
GuhanSGCIT/Trees-and-Graphs-problem
/Guna and grid.py
1,212
4.125
4
""" Recently, Guna got a grid with n rows and m columns. Rows are indexed from 1 to n and columns are indexed from 1 to m. The cell (i,j) is the cell of intersection of row i and column j. Each cell has a number written on it. The number written on cell (i,j) is equal to (i+j). Now, Guna wants to select some cells from the grid, such that for every pair of selected cells , the numbers on the cells are co-prime. Determine the maximum number of cells that Guna can select. Timing:1sec level:4 Input Description: Single line containing integers n and m denoting number of rows and number of columns respectively. Output description: Single line containing the answer. Constraints 1≤n,m≤106 Input: 3 4 Output: 4 input: 45 65 Output: 29 input: 8 9 Output: 7 input: 5 6 Output: 5 input: 0 1 Output: 0 solution: """ def Sieve(n): prime = [1 for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n+1, p): prime[i] = 0 p += 1 return prime try: n,m=list(map(int,input().split())) x=Sieve(n+m) print(sum(x)-2) except: pass
true
d0ae84a9f2cb762c24b70b92ea1cab0e3acbe92d
GuhanSGCIT/Trees-and-Graphs-problem
/Egg Dropping Puzzle-Samsung.py
2,110
4.40625
4
""" Suppose you have N eggs and you want to determine from which floor in a K-floor building you can drop an egg such that it doesn't break. You have to determine the minimum number of attempts you need in order find the critical floor in the worst case while using the best strategy.There are few rules given below. An egg that survives a fall can be used again. A broken egg must be discarded. The effect of a fall is the same for all eggs. If the egg doesn't break at a certain floor, it will not break at any floor below. If the eggs breaks at a certain floor, it will break at any floor above. timing:1.5sec level:6 Input: The first line of input is T denoting the number of testcases.Then each of the T lines contains two positive integer N and K where 'N' is the number of eggs and 'K' is number of floor in building. Output: For each test case, print a single line containing one integer the minimum number of attempt you need in order find the critical floor. Constraints: 1<=T<=30 1<=N<=10 1<=K<=50 Example: Input: 2 2 10 3 5 Output: 4 3 input: 3 1 5 2 16 2 8 output 5 6 4 input: 2 1 6 3 15 output 6 5 input: 1 2 8 output 4 input: 4 1 5 2 7 2 9 1 9 output 5 4 4 9 hint: calculate the minimum number of droppings needed in the worst case. The floor which gives the minimum value in the worst case is going to be part of the solution. In the following solutions, we return the minimum number of trials in the worst case; these solutions can be easily modified to print floor numbers of every trial also. """ import sys def eggDrop(n, k): if (k == 1 or k == 0): return k if (n == 1): return k min = sys.maxsize for x in range(1, k + 1): res = max(eggDrop(n - 1, x - 1), eggDrop(n, k - x)) if (res < min): min = res return min + 1 if __name__ == "__main__": for i in range(int(input())): n,k=map(int,input().split()) print(eggDrop(n, k))
true
cbc7d523b97ec18e747d0955b769c475c6935aff
alfonso-torres/eng84_OOP_exercises
/Fizzbuzz.py
1,403
4.4375
4
# Exercise 1 - Fizzbuzz # Write a program that outputs sequentially the integers from 1 to 100, but on some conditions prints a string instead: # when the integer is a multiple of 3 print “Fizz” instead of the number, # when it is a multiple of 5 print “Buzz” instead of the number, # when it is a multiple of both 3 and 5 print “FizzBuzz” instead of the number. # Notes: must be in a class and method format # Let's create the Fizzbuzz class class Fizzbuzz: def __init__(self): self.three = 3 # Integer to check if is a multiple of 3 self.five = 5 # Integer to check if is a multiple of 5 # Function that will check if the number is multiple of 3 or 5 and print the correct answer def fizzbuzz_prints(self): i = 1 while i <= 100: # loop while from 1 to 100 if i % self.three == 0 and i % self.five == 0: # check if is multiple of both print("FizzBuzz") elif i % self.three == 0: # check if is multiple of 3 print("Fizz") elif i % self.five == 0: # check if is multiple of 5 print("Buzz") else: print(i) # number that is not dividable by 3 or 5 i += 1 # Let's create an object of the Fizzbuzz Class object_fizzbuzz = Fizzbuzz() # Call the function that will print the corrects answers object_fizzbuzz.fizzbuzz_prints()
true
6ed4d522eed64bb845676e0b9bcbd24e21ffa1ff
taroserigano/coderbyte
/Arrays/Consecutive.py
737
4.1875
4
''' Consecutive Have the function Consecutive(arr) take the array of integers stored in arr and return the minimum number of integers needed to make the contents of arr consecutive from the lowest number to the highest number. For example: If arr contains [4, 8, 6] then the output should be 2 because two numbers need to be added to the array (5 and 7) to make it a consecutive array of numbers from 4 to 8. Negative numbers may be entered as parameters and no array will have less than 2 elements. Examples Input: [5,10,15] Output: 8 Input: [-2,10,4] Output: 10 ''' def Consecutive(arr): return max(arr) - min(arr) - len(arr) +1 # keep this function call here print Consecutive(raw_input([5,10,15))
true
4d03565e948a1b5f093d0ff0cb589ead794f8d21
taroserigano/coderbyte
/Trees & Graphs/SymmetricTree.py
1,203
4.5
4
''' Symmetric Tree HIDE QUESTION Have the function SymmetricTree(strArr) take the array of strings stored in strArr, which will represent a binary tree, and determine if the tree is symmetric (a mirror image of itself). The array will be implemented similar to how a binary heap is implemented, except the tree may not be complete and NULL nodes on any level of the tree will be represented with a #. For example: if strArr is ["1", "2", "2", "3", "#", "#", "3"] then this tree looks like the following: For the input above, your program should return the string true because the binary tree is symmetric. Use the Parameter Testing feature in the box below to test your code with different arguments. "["1", "2", "2", "3", "#", "#", "3"]" ''' def SymmetricTree(a): # code goes here arr, branch, store = list(a), 1, [] while len(arr) > 0: #squeeze out x = [] for i in range(branch): x.append(arr[0]) del arr[0] store.append(x) branch *= 2 for i in store: if i != list(reversed(i)) : return 'false' return 'true' # keep this function call here print SymmetricTree(raw_input())
true
75bb3cbcba0b24a5487276691650603e261e416d
mgomez9638/CIS-106-Mario-Gomez
/Assignment 8/Activity 1.py
668
4.40625
4
# Activity 1 # This program gives the user access to create a multiplication table. # You simply begin with entering a value, entering a starting point, and the size of the table. def getExpressions(): print("Enter the number of expressions") expressions = int(input()) return expressions def getValue(): print("Enter a value: ") value = int(input()) return value # Main value = getValue() expressions = getExpressions() multiplierValue = 1 while multiplierValue <= expressions: total = value * multiplierValue print(str(value) + " * " + str(multiplierValue) + " = " + str(total)) multiplierValue = multiplierValue + 1
true
bf3a761daa923e3fc486c37ed4a522d4cbb57d45
mgomez9638/CIS-106-Mario-Gomez
/Assignment 5/Activity 6.py
2,061
4.34375
4
# Activity 6 # This program is intended to determine how much paint is required to paint a room. # It, also, expresses how much the gallons of paint cost. def get_length(): length = float(input("Enter the length of the room(in feet): ")) return length def get_width(): width = float(input("Enter the width of the room(in feet): ")) return width def get_height(): height = float(input("Enter the height of the room(in feet): ")) return height def get_price_per_gallon(): price_per_gallon = float(input("Enter the price per gallon of paint: $")) return price_per_gallon def get_square_feet_per_gallon(): square_feet_per_gallon = float(input("Enter the square feet that a gallon of paint will cover: ")) return square_feet_per_gallon def calculate_total_area(length, width, height): total_area = round(2 * length * height + 2 * width * height, 2) return total_area def calculate_gallons(total_area, square_feet_per_gallon): gallons = int(round(total_area / square_feet_per_gallon + 0.5)) return gallons def calculate_total_price_of_paint(gallons, price_per_gallon): total_price_of_paint = round(gallons * price_per_gallon, 2) return total_price_of_paint def display_result(total_area, gallons, total_price_of_paint): print("The total area of the room is " + str(total_area) + " square feet. The number of gallons needed are " + str(gallons) + ". The total cost of the paint is $" + str(total_price_of_paint) + ".") def main(): length = get_length() width = get_width() height = get_height() price_per_gallon = get_price_per_gallon() square_feet_per_gallon = get_square_feet_per_gallon() total_area = calculate_total_area(length, width, height) gallons = calculate_gallons(total_area, square_feet_per_gallon) total_price_of_paint = calculate_total_price_of_paint(gallons, price_per_gallon) display_result(total_area, gallons, total_price_of_paint) main()
true
3031e95c3286a9b596e179e6e08b8903b99625ba
mgomez9638/CIS-106-Mario-Gomez
/Assignment 4/Activity 3.py
439
4.15625
4
# Assignment Three # This program gives the user access to calculate the distance in U.S. standard lengths. # It converts miles into yards, feet, and inches. print("Enter distance in miles: ") miles = float(input()) yards = 1760 * miles feet = 5280 * miles inches = 63360 * miles print("The distance in yards is " + str(yards) + ". The distance in feet is " + str(feet) + ". The distance in inches is " + str(inches) + ".")
true
1c132cd8d307833a17f4860c3d0267c89e0f83c6
Sridevi333/Python-Deep-Learning-Programming
/ICP2/wordsperline.py
355
4.125
4
fileName = input("Enter file name: ") f = open(fileName, "r") # Open file for input lines=0 mostWordsInLine = 0 for lineOfText in f.readlines(): wordCount = 0 lines += 1 f1=lineOfText.split() wordCount=wordCount+len(f1) if len(f1) > mostWordsInLine: mostWordsInLine = len(f1) print ((str(lineOfText)),str(wordCount))
true
1a0e41d3b08f4c98db46d0f7e01e7ae247b21298
Chuukwudi/Think-python
/chapter8_exercise8_5.py
2,544
4.28125
4
''' str.islower() Return True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise. ''' def any_lowercase1(s): for c in s: if c.islower(): return True else: return False '''Here, the funtion takes the first character, if it is Upper case, it returns false, if it is lower case, it returns true. it does not iterate over other characters in the string s''' # ----------------------------------------------------------------------------------------------------------------------- def any_lowercase2(s): for c in s: if 'c'.islower(): return 'True' else: return 'False' '''this function checks only the string 'c' is lower, which always returns True''' # ----------------------------------------------------------------------------------------------------------------------- def any_lowercase3(s): for c in s: flag = c.islower() return flag '''This would have been a nice code except that it only returns after iterating completly. Hence, the output is based on the last letter of the string you're checking, it ignores the state of other characters but only return its last check ''' # ----------------------------------------------------------------------------------------------------------------------- def any_lowercase4(s): flag = False for c in s: flag = flag or c.islower() return flag '''This is the perfect code. During the iteration, once a lowercase is met, the flag changes to True. if another lower case is met, c.islower changes to false but the flag still maintains True because if the "or" gate''' # ----------------------------------------------------------------------------------------------------------------------- def any_lowercase5(s): for c in s: if not c.islower(): return False return True '''This code returns True by default but, it will only work when the string being tested has not more that one upper case letter. Once it encounters an upper case letter, it returns a value and the if statement doesnt run anymore. ''' # ----------------------------------------------------------------------------------------------------------------------- print(any_lowercase1('WaSEe')) print(any_lowercase2('CSEc')) print(any_lowercase3('ccSEc')) print(any_lowercase4('CSddE')) print(any_lowercase5('EeE'))
true
a1af47bd51c847b5ec8815835a24f13e89aa3053
ckaydevs/learning_python
/class/draw art/squre.py
924
4.3125
4
import turtle def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) some_turtle.right(90) def draw_art(): window=turtle.Screen() window.bgcolor("red") #Create the turtle brad- Draws a square brad=turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(10) for i in range (1,37): draw_square(brad) brad.right(10) #Create the turtle pit- Draws a circle #pit = turtle.Turtle() #pit.shape("arrow") #pit.color("blue") #pit.circle(100) ''' window.exitonclick() draw_art() ''' I wrote this at first to make circle from square angle=0 while(angle<360): brad.forward(100) brad.right(90) brad.forward(100) brad.right(90) brad.forward(100) brad.right(90) brad.forward(100) brad.right(90) brad.right(5) angle+=5 '''
true
7a4f8c8d68bd58f1cd327f3e41bc09329a5c3e6a
joelgarzatx/portfolio
/python/Python3_Homework03/src/decoder.py
752
4.125
4
""" Decoder provided function alphabator(list) accepts an integer list, which returns the list of integers, substituting letters of the alphabet for integer values from 1 through 26 """ def alphabator(object_list): """ Accepts a list of objects and returns the objects from the list, replacing integer values from 1 to 26 with the corresponding letter of the English alphabet """ alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for object in object_list: if object in range(1,27): # object is integer from 1 - 26 ret_val = alphabet[object-1] # grab corresponding letter from alphabet list else: # other integer value or object ret_val = object yield ret_val
true
bb47cb2a447892832f217c28d2570902d1c9709e
AdamBorg/PracCP1404
/Prac03/asciiTable.py
774
4.21875
4
def main(): lower = 33 upper = 127 num_entered = get_number(lower,upper) print("{:>3} {:>6} \n".format(num_entered, chr(num_entered))) print_ascii_table(lower, upper) def get_number(lower,upper): num_entered = 0 exit_character = 'e' while num_entered < 33 or num_entered > 127 or exit_character == 'e': try: num_entered = int(input("please enter a number between {} and {} \n".format(lower, upper))) exit_character = 'i' except ValueError: print("Please enter a valid number") return num_entered def print_ascii_table(lower, upper): for i in range(lower, upper): print("{:>3} {:>6}".format(i, chr(i))) main() #made change to see what happens when pushed to gitHub
true
ae2357e9ae0dc6da9f2aef9c4bd6897259cf9018
sstoudenmier/CSCI-280
/Assignment5/PathNode.py
1,798
4.15625
4
''' Class representing a map location being searched. A map location is defined by its (row, column) coordinates and the previous PathNode. ''' class PathNode: def __init__(self, row=0, col=0, previous=None): self.row = row self.col = col self.previous = previous ''' Gets the row number for the PathNode. @return: the value of the row for the PathNode ''' def getRow(self): return self.row ''' Gets the column number for the PathNode. @return: the value of the column for the PathNode ''' def getCol(self): return self.col ''' Gets the previous node for the PathNode. @return: the pathnode that was previous looked at ''' def getPrevious(self): return self.previous ''' Sets the previous node for the PathNode. @param: previous - value to set for the previous node ''' def setPrevious(self, previous): self.previous = previous ''' Override the equals method so that it can compare two PathNode objects. @param: other - another PathNode class to compare self to @return: true if self and other are equal in row and column; false otherwise ''' def __eq__(self, other): if self.getRow() == other.getRow() and self.getCol() == other.getCol(): return True return False ''' Overide the hash method. @return: a hash value for the PathNode objects ''' def __hash__(self): return 31 * self.getRow() + self.getCol() ''' Override the toString method for PathNode so that it can print out the coordinates. @return: a string representation of the PathNode ''' def __str__(self): return "(" + str(self.getRow()) + ", " + str(self.getCol()) + ")"
true
3a41918c0f0137427561146e947191acd06963a5
akash639743/Python_Assignment
/Dictionary.py
912
4.5
4
# Dictionary #1. Create a Dictionary with at least 5 key value pairs of the Student students={1:"akash",2:"rohit",3:"simran",4:"mohit",5:"sonam"} print(students) # 1.1. Adding the values in dictionary students[6]="soni" print(students) # 1.2. Updating the values in dictionary students.update({7: "mukesh"}) print(students) # 1.3. Accessing the value in dictionary x = students[3] print(x) # 1.4. Create a nested loop dictionary myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } print(myfamily) # 1.5. Access the values of nested loop dictionary x=myfamily["child2"] print(x) # 1.6. Print the keys present in a particular dictionary print(students.keys()) print(myfamily.keys()) # 1.7. Delete a value from a dictionary del myfamily print(myfamily)
true
b983ae86176ffd7877a2e0b6351249487a5215cd
akash639743/Python_Assignment
/Access_Modifiers.py
2,223
4.125
4
# Access Modeifiers # 1. Create a class with PRIVATE fields class Geek: # private members __name = None __roll = None __branch = None # constructor def __init__(self, name, roll, branch): self.__name = name self.__roll = roll self.__branch = branch # private member function def __displayDetails(self): # accessing private data members print("Name: ", self.__name) print("Roll: ", self.__roll) print("Branch: ", self.__branch) # public member function def accessPrivateFunction(self): # accesing private member function self.__displayDetails() # creating object obj = Geek("R2J", 1706256, "Information Technology") # calling public member function of the class obj.accessPrivateFunction() # 2. Create a class with PROTECTED fields and methods. # super class class Student: # protected data members _name = None _roll = None _branch = None # constructor def __init__(self, name, roll, branch): self._name = name self._roll = roll self._branch = branch # protected member function def _displayRollAndBranch(self): # accessing protected data members print("Roll: ", self._roll) print("Branch: ", self._branch) # derived class class Geek(Student): # constructor def __init__(self, name, roll, branch): Student.__init__(self, name, roll, branch) # public member function def displayDetails(self): # accessing protected data members of super class print("Name: ", self._name) # accessing protected member functions of super class self._displayRollAndBranch() # creating objects of the derived class obj = Geek("R2J", 1706256, "Information Technology") # calling public member functions of the class obj.displayDetails() # 3. Create a class with PUBLIC fields and methods. class Geek: # constructor def __init__(self, name, age): # public data mambers self.geekName = name self.geekAge = age # public member function def displayAge(self): # accessing public data member print("Age: ", self.geekAge) # creating object of the class obj = Geek("R2J", 20) # accessing public data member print("Name: ", obj.geekName) # calling public member function of the class obj.displayAge()
true
eaf51afa470cdb8bb97633aa5d624075d47ba331
dieg0varela/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,044
4.3125
4
#!/usr/bin/python3 """Define class Square""" class Square: """Class Square""" def __init__(self, new_size=0): """Init Method load size""" if (isinstance(new_size, int) is False): raise TypeError("size must be an integer") if (new_size < 0): raise ValueError("size must be >= 0") self.__size = new_size def area(self): """Area calculation""" return (self.__size * self.__size) def my_print(self): """Print square of your size""" if (self.__size == 0): print() else: for x in range(self.__size): for y in range(self.__size): print("#", end='') print() @property def size(self): return self.__size @size.setter def size(self, val): if (isinstance(val, int) is False): raise TypeError("size must be an integer") if (val < 0): raise ValueError("size must be >= 0") self.__size = val
true
3c8374bfdcac02646aa651cb2eca1f4b79f0dbb9
thorenscientific/py
/TypeTrip/TypeTrip.py
422
4.15625
4
# A simple script demonstrating duck typing... print "How trippy are Python Types??" print "Let's start with x=1...." x = 1 print "x's value:" print x print "x's type:" print type(x) print "Now do this: x = x * 1.01" x = x * 1.01 print "x's value:" print x print "x's type:" print type(x) print "Now do this: x = x + 1*j" x = x + 1j print "x's value:" print x print "x's type:" print type(x)
true
c1ad2b3ac87e01b9a230b71b9aca5af6bb34d9ed
flora5/py_simple
/map_reduce_filter.py
1,062
4.21875
4
""" filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. """ str = ['a','b','c','d'] def func(s): if s!='a': return s else: return None print filter(func,str) #['b', 'c', 'd'] a = [1, 2, 3] b = [4, 5, 6, 7] c = [8, 9, 1, 2, 3] L = map(lambda x: len(x), [a, b, c]) # L == [3, 4, 5] """ reduce(...) reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. """ # L == [3, 4, 5] N = reduce(lambda x, y: x+y, L) # 3+4 +5 # N == 12
true
f5df8af88f3449e2124e9cc0899300bc2eff9fb7
mzanzilla/Python-For-Programmers
/Files/ex3.py
1,239
4.5
4
#Updating records in a text file #We want to update the name for record number 300 - change name from White to Williams #Updating textfiles can affect formattting because texts may have varrying length. #To address this a temporary file will be created import os tempFile = open("tempFile.txt", "w") accounts = open("accounts.txt", "r") #The 'with' statement manages two resource objects with accounts, tempFile: #Loop through each line or record in the text file for record in accounts: #I split and unpack each line into variables account, name, balance = record.split() #If the account number is not equal to the record number 300, I want to put that record (or line) #in a temporary text file else I want to join the existing record with the name "Williams" to create #a new record if account != "300": tempFile.write(record) else: newRecord = ' '.join([account, "Williams", balance]) tempFile.write(newRecord + "\n") #delete the accounts text file #remove should be used with caution as it does not warn you about deleting a file os.remove("accounts.txt") #rename tempFile to accounts.txt os.rename("tempFile.txt", "accounts.txt")
true