blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ee4770920fb96f25fea3462b58418c4919891758
tberhanu/elts-of-coding
/Sorting/sort_linked_list.py
844
4.1875
4
def sort_linked_list(ll): """ Strategy: 1. Loop through the linked list and append each Node to the ARRAY, O(N), since looping through N number of Nodes, and APPENDING to Array takes only O(1), unlike INSERTING w/c takes O(N). 2. Sort the array in REVERSE OREDER i.e. array.sort(reverse=True) w/c takes O(N log N) 3. Add each NODE from the Array to the Linked List, O(N), as adding more Node to Linked List takes O(1) Therefore, overall Time: O(N log N), and Space: O(N) Page 198 got solutions: Solution 1. Time: O(N * N) and Space: (N) Solution 2. Time: O(N * N) and Space: (1) Solution 3. Time: O(N log N) and Space: O(log N) using Merge Sort Concept. Check them out !!!! """ pass
true
f46cec3b67374f498a85f493aa0e90b10a4094fe
tberhanu/elts-of-coding
/GreedyAlgorithms/two_sum.py
1,386
4.125
4
def two_sum(arr, target): """ Given a sorted array of integers, and a target value, get two numbers that adds up to the TARGET. Strategy 1: Brute-force: Double for loop checking each and every pair: O(N * N) Strategy 2: HashTable: Putting the arr in HashTable or SET, and check if (Target - e) found in HashTable where e is each element of the array. O(N) for converting ARR to SET. Strategy 3: Use two pointers i.e at index=0 and at index=len(arr)-1, then if the start and end add up to be greater than the TARGET, then decrement the end_index; otherwise increment the start_index until getting equal. O(N) """ i, j = 0, len(arr) - 1 while i < j: # i <= j if want to consider DUPLICATION TO BE ALLOWED summed = arr[i] + arr[j] if summed == target: return (arr[i], arr[j]) elif summed > target: j -= 1 else: i += 1 return False if __name__ == "__main__": arr = [4, 3, 5, 6, 9, 9, -3, -2] target = 12 result = two_sum(sorted(arr), target) print(result) target = 0 result = two_sum(sorted(arr), target) print(result) arr = [3, 5, 6, 9, 9, -3, -2] target = 10 result = two_sum(sorted(arr), target) print(result) # Not found since DUPLICATION NOT ALLOWED (while i < j) not (while i <= j)
true
b49ddda99c07271539c9bfd92ea9b63d8d1dfc34
tberhanu/elts-of-coding
/Searching/search_sorted_matrix.py
1,862
4.21875
4
def search_sorted_matrix(matrix, num): """ Question: Given a sorted 2D array, matrix, search for NUM SORTED MATRIX: means each ROW is increasing, and each COL is increasing Solution: Brute-force approach of looping thru the double array takes O(N * N) Smart approach is: 1. Grab the TOP RIGHT element, and return the indexes if it is equal to the NUM 2. If NUM is greater than the TOP RIGHT element, then the number we are searching won't be in that row, so remove that row by incrementing index i. 3. If NUM is less than the TOP RIGHT element, then the number we are searching won't be in that col, so remove that col by decrementing index j. 4. If row index i > len(matrix) or col index j < 0, then NUM is not found in the MATRIX, so return (-1, -1) Time Complexity: O(row + col) since every step, we do one comparison to remove one row or one col so in the worst situation we remove all row/col and left with empty matrix. """ row = len(matrix) col = len(matrix[0]) i, j = 0, col - 1 while i < row and j >= 0: corner = matrix[i][j] if num == corner: return (i, j) elif num > corner: # can't find in that row, so remove it i += 1 else: # can't find in that col, so remove it j -= 1 return (-1, -1) if __name__ == "__main__": matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] result = search_sorted_matrix(matrix, 11) print(result) result = search_sorted_matrix(matrix, 1) print(result) result = search_sorted_matrix(matrix, 16) print(result) result = search_sorted_matrix(matrix, 99) print(result)
true
f6ca9a0bd17be2e8f4547a2f65b94b546e33a3e9
tberhanu/elts-of-coding
/GreedyAlgorithms/optimum_task_assignment.py
1,076
4.3125
4
def optimum_task_assignment(task_durations): """ Consider assigning tasks to workers where each worker must be assigned exactly TWO TASKS, and each task has a fixed amount of time it takes. Design an algorithm that takes as input a set of tasks and returns an optimum assignment. Note: Simply enumerating all possible sets of pairs of tasks is not feasible, takes too much, N!/(2 ** N/2) so better to use Greedy Algorithm. Strategy: Order the tasks and assign the one with smallest time and the one with the largest time to one worker, and continue doing that. Ex. [1, 2, 4, 4, 5, 6] >> (1, 6), (2, 5), and (4, 4) """ from collections import namedtuple PairedTasks = namedtuple('PairedTasks', ('small_task', 'large_task')) task_durations.sort() result = [PairedTasks(task_durations[i], task_durations[~i]) for i in range(len(task_durations) // 2)] return result if __name__ == "__main__": task_durations = [5, 2, 1, 6, 4, 4] result = optimum_task_assignment(task_durations) print(result)
true
45677c2998c579fefea3630fde8fc71beb5c5f37
tberhanu/elts-of-coding
/Arrays/even_odd.py
863
4.28125
4
def even_odd(arr): """ Page 37. Rearranging evens first and odds later. Time Complexity: O(N) Space Complexity: O(1) arr = [2, 3, 4, 5, 6, 7, 8, 3, 0, 2, 4, 5] :returns: [2, 4, 6, 8, 0, 2, 4, 3, 5, 7, 5, 5] """ i, j = 0, 0 while j < len(arr) - 1: if arr[i] % 2 == 0: i += 1 else: e = arr.pop(i) arr.append(e) j += 1 return arr def array_propeties(): import copy arr = [9, 8, 7] k = arr[::-1] print(arr, k) arr2 = list(arr) arr3 = list(arr) d = {1: 2, 3: 4} dd = dict.copy(d) ddd = arr[:] ddd.pop() print(dd) print(ddd) print(arr) print(id(arr), id(arr2), id(arr3), id(k)) if __name__ == "__main__": # arr = [2, 3, 4, 5, 6, 7, 8, 3, 0, 2, 4, 5] # print(even_odd(arr)) array_propeties()
false
caccbb5a383caf682478494c3288e2f45424e298
jimmy1087/codeKatas
/sorting/bubbleSort.py
836
4.21875
4
''' o(n^2) 5 * 5 = 25 steps to sort an array of 5 elements that were in desc order. ''' def bubbleSort(array): steps = 0 outerLoop = 1 sorted = False sortedElements = 0 while not sorted: steps += 1 print('[[loop]]', outerLoop) outerLoop += 1 sorted = True for i in range(len(array)-sortedElements-1): print('i', i) steps += 1 if array[i] > array[i+1]: print('Swap', array[i], array[i+1]) steps += 1 swap(i, array) sorted = False sortedElements += 1 print('Total steps: ', steps) return array def swap(i, array): array[i], array[i+1] = array[i+1], array[i] #a = [3,4,-6,2,1,4,6,-2,-3,0] #print(bubbleSort(a)) a = [5,4,3,2,1] print(bubbleSort(a))
true
6e131e58dba3ebaa6ffb342e6ab3d7f0023d646a
eriksLapins/datu_analize_kursi
/Day7_Dicts_files/day7_uzd1.py
1,289
4.1875
4
#%% my version # uztaisīt tā, lai lietotājs ievada informāciju par studentu, jāsagatavo vārdnīca un jāizvada informācija # visa ievade un izvade notiek main funckijā, bet visa loģika - vārdnīcas sagatavošana un atgriešana notiek citā failā from day7_uzd1_logic import create_dict_student def create_student(): student_name = input("Lūdzu ievadiet studenta vārdu!") student_surname = input("Lūdzu ievadiet studenta uzvārdu") student_course = int(input("Lūdzu ievadiet studenta kursu")) student = create_dict_student(student_name, student_surname, student_course) return student if __name__ == '__main__': print(create_student()) #%% other version import day7_uzd1_logic as stParse if __name__ == "__main__": # ievadīt inputus var arī bez atsevišķas funkcijas name = input("Lūdzu ievadiet studenta vārdu!") last_name = input("Lūdzu ievadiet studenta uzvārdu") course = int(input("Lūdzu ievadiet studenta kursu")) student_dict = stParse.create_student_dict(name, last_name, course) for key, val in student_dict.items(): # .items() is used to look for keys AND values, we ask for what we want # .values() - get values # .keys() - get keys print(key + ": " + str(val))
false
9e5e40c15f41762cf4fcc76c484260d6bcebb9f1
bradg4508/self_taught_challenges
/chp_4.py
1,479
4.4375
4
#1 def square(x): """ Returns x^2. :param x: int. :return: int x raised to the second power. """ return x**2 print(square(2)) #2 def print_string(word): """ Prints a string passed in by user. :param word: str. """ print(word) print_string("This is a sentence.") #3 def add_numbers(x, y, z, a=4, b=5): """ Returns the result of the sum of 3 required parameters and 2 optional parameters. :param x: int. :param y: int. :param z: int. :param a: int. :param b: int. :return: int of sum of parameters. """ return x + y + z + a + b result = add_numbers(1, 2, 3) print(result) #4 def divide(x): """ Returns the result of an integer divided by 2. :param x: int. :return: int of quotient x divided by 2. """ return x / 2 def multiply(x): """ Returns the result of an integer multiplied by 4. :param x: int. :return: int of product x and 4. """ return x * 4 y = divide(4) z = multiply(y) print(z) #5 def string_to_float(string): """ Converts passed in str to float and prints the result if possible, otherwise it prints an error message. :param string: str. """ try: print(float(string)) except ValueError: print("Could not convert the string to a float.") string_to_float("55.8") #6 #Answer was to add docstrings to 1-5
true
924f623d0dae965902aba3b2c4d2abc9e14d3e4e
marcovnyc/penguin-code
/1000_exercises/1000_exercises_02.py
563
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 3 22:59:33 2021 @author: Marco M """ print("Let's calculate the area of a rectangle") print("Formula: A = w * l") print("Enter width and height") width_value = int(input("enter width -> ")) height_value = int(input("enter height -> ")) area = width_value * height_value print("The area is", area) """ Print circumference of a rectangle formula is C = 2 * ( w + l) """ circumference = int(2 * (width_value + height_value)) print("the circumference of this rectangle is", circumference)
true
cc2b260b8fe52136b91c440c2b264dd1ef93e126
marcovnyc/penguin-code
/Impractical-Python-Projects/chapter_8_9/syllable_counter.py
2,095
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 17 16:29:46 2019 @author: toddbilsborough Project 15 - Counting Syllables from Impractical Python Projects Objective - Write a Python program that counts the number of syllables in an English word or phrase Notes - First experience with natural language processing and the corpus, so I'll mostly be copying from the book to get a sense of how all this works - The CMU Corpus puts a numeral in front of each vowel sound; those can be counted to count the number of syllables - Had to adjust the count_syllables to return None if it can't find the word in either list """ import sys from string import punctuation import json from nltk.corpus import cmudict with open('missing_words.json') as f: MISSING_WORDS = json.load(f) CMUDICT = cmudict.dict() def count_syllables(words): """Use corpora to count syllables in English word or phrase Mostly copied from book""" words = words.replace('-', ' ') words = words.lower().split() num_syllables = 0 for word in words: word = word.strip(punctuation) if word.endswith("'s"): word = word[:-2] if word in MISSING_WORDS: num_syllables += MISSING_WORDS[word] elif word in CMUDICT.keys(): for phonemes in CMUDICT[word][0]: for phoneme in phonemes: if phoneme[-1].isdigit(): num_syllables += 1 else: return return num_syllables def main(): """Counts syllables in a word or phrase Mostly copied from book""" print("Syllable Counter") while True: word = input("Enter word or phrase, enter to exit: ") if word == '': sys.exit() try: num_syllables = count_syllables(word) print("Number of syllables in \"{}\" is: {}" .format(word, num_syllables)) print() except KeyError: print("Word not found. Try again.\n", file=sys.stderr) if __name__ == '__main__': main()
true
91e78752c499744a110c0dc947a52cfbf60a0594
utep-cs-systems-courses/python-intro-ecrubio
/wordCount.py
2,127
4.125
4
import sys # command line arguments import re # regular expression tools import os # checking if file exists #Checking that the correct format is used when running the program. #When running the file it should also have the input and output files in the argument def argumentCheck(): if len(sys.argv) is not 3: print("Correct usage: wordCount.py <input text file> <output file>") exit() else: inputFile = sys.argv[1] outputFile = sys.argv[2] return inputFile, outputFile #Checking if the files provided in the arguments exist def fileCheck(inputFile, outputFile): if not os.path.exists(inputFile): print ("text file input %s doesn't exist. Exiting" % inputFile) exit() if not os.path.exists(outputFile): print("output file %s doesn't exist. Exiting" % outputFile) exit() #Creating a new dictionary and splitting the lines into words then inserting #the word into dictionary and adding 1 to the count of the word def openFile(mainFile, outputFile): wordDict = {} with open(mainFile, 'r') as inputFile: for line in inputFile: #get rid of newline charachters line = line.strip() #Finding all the words and excluding special characters wordList = re.findall("[a-zA-Z]+", line) for word in wordList: word = word.lower() if word in wordDict.keys(): wordDict[word] += 1 else: wordDict[word] = 1 sortedDict = sorted(wordDict) #sorted keys into text file with open(outputFile, 'w') as data: for key in sortedDict: data.write(key + ' ' + str(wordDict[key]) + '\n') print(key + ' ' + str(wordDict[key])) def main(): mainInput, mainOutput = argumentCheck() fileCheck(mainInput, mainOutput) #If output file has any text then this will clear it open(mainOutput, 'w').close() openFile(mainInput, mainOutput) if __name__ == '__main__': main()
true
d4cded95c436c9973d914324a537690e1e2b0060
MohamedGassem/ai_for_tetris
/src/AI/metrics.py
2,554
4.125
4
import numpy as np def compute_holes(board): """ Compute the number of holes in the board Note: a hole is defined as an empty cell with a block one or more blocks above Parameters ---------- board: 2d array_like The tetris board """ holes = 0 size = board.shape for j in range(0, board.shape[1]): is_one = False for e in board[:, j]: if is_one and e == 0: holes += 1 elif e == 1: is_one = True return holes def compute_height(board): """ Compute the maximum height of the board Parameters ---------- board: 2d array_like The tetris board """ max_height = 0 for j in range(0, board.shape[1]): column_j = board[:, j] if np.count_nonzero(column_j) == 0: min_index_j = 0 else: min_index_j = column_j.shape[0] - np.argmax(column_j) max_height = max(max_height, min_index_j) return max_height def compute_bumpiness(board): """ Compute bumpiness of a given board The bumpiness measure how flat is the last layer of the board. For two adjacent columns, the relative bumpiness is the absolute value of the difference between the height of the columns. The total bumpiness is the sum of all relative bumpiness and is therefor a positive integer Parameters ---------- board: 2d array_like The tetris board filled with 1 (for a block) or 0 for empty space """ bumpiness = 0 for j in range(0, board.shape[1] - 1): col_j = np.transpose(np.array([board[:, j]])) col_jp = np.transpose(np.array([board[:, j + 1]])) columnj_height = compute_height(col_j) columnjp_height = compute_height(col_jp) bumpiness += abs(columnj_height - columnjp_height) return bumpiness def compute_sum_height(board): """ Compute the sum of all columns heights Parameters ---------- board: 2d array_like The tetris board """ sumH = 0 for j in range(0, board.shape[1]): for i in range(0, board.shape[0]): if board[i, j] == 1: sumH += board.shape[0] - i break return sumH
true
c10bacef9eab1132af932f4aeae83d954093cc7f
burnacct36/lpthw
/ex29.py
756
4.3125
4
# An if-statement creates what is called # a "branch" in the code. The if-statement # tells your script, "If this boolean expression # is True, then run the code under it, otherwise skip it." people = 20 cats = 30 dogs = 15 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry!" dogs += 5 # What does += mean? # The code x += 1 is the same as doing x = x + 1 but # involves less typing. if people >= dogs: print "People are greater than or equal to dogs." if people <= dogs: print "People are less than or equal to dogs." if people == dogs: print "People are dogs."
true
0540e9ef0c4fd0a078d4c36d7e52f87996b171e6
Davie704/My-Beginner-Python-Journey
/IfStatementsBasic.py
1,048
4.21875
4
# If statement basics # Ex 1 salary = 8000 if salary > 5000: print("My salary is too low!") else: print("My salary is above average, its okay right now.") # Ex 2 age = 55 if age > 50: print("You're a senior Developer, for sure!") elif age > 40: print("You're more than 40 years old.") elif age > 35: print("You're more than 35 years old.") else: print("Doesn't matter what age you are. Let's start learning programming!") # Ex 3 Logical Operators a = 10 b = 5 c = 2 if a > b or a > c: print("\nOne of the conditions is true") else: print("\nNone of them is true") if b < a < c: print("\nOne of the conditions is true") else: print("\nOne or None of them is true") # Ex 4 Nested 'If Statement' age = 30 name = "James" married = True if age > 20 and name =="James": if married == True: print("\nCongratulations! The statement is TRUE!") else: print("\nThe statement is FALSE :(.") else: print("\nThis is from the parent 'else'.")
true
71a34df3b3807a67a682d0ff908b5d4c3cdf07c8
Davie704/My-Beginner-Python-Journey
/Variables.py
1,241
4.5
4
# My Learning Python Journey # A simple string example short_string_example = "Have a great week, Ninjas!" print(short_string_example) # Print the first letter of a string variable, index 9 first_letter_variable = "New York City"[9] print(first_letter_variable) # Mixed upper and lowercase variable mixed_letter_variable = "ThiS iS a MIxED vaRiAble" print(mixed_letter_variable.lower()) # Length of the variable print(len(mixed_letter_variable)) # Use '+' sign inside a print command first_name = "David" print("First Name is: " + first_name) # Adding String and Integer age = 25 print("Age: " + str(age)) # Replace a part of a string first_serial_num = "ABC123" print("Change serial number: " + first_serial_num.replace('123', '456')) # Replace a part of a string TWICE second_serial_num = "ABC123ABC123ABC" print("Changed serial number 2: " + second_serial_num.replace('ABC', 'ZZZ', 2)) # Take a part of a variable according to specific index range range_of_indexes = second_serial_num[2:7] print(range_of_indexes) # Adding spaces between multiple variables in print first_word = "Thank" second_word = "You" third_word = "Python" print(first_word + " " + second_word + " " + third_word)
true
7b2270e4177a957ff674f6a17a22041910889efa
FarazMannan/Magic-8-Ball
/Magic8Ball.py
2,755
4.1875
4
import random count = 0 # count = count + 1 print("Welcome to Faraz's Magic 8 Ball") # Faraz, wrap the code below in a loop so the user can # keep asking the magic 8 ball questions... Go! # Challenge number 2 before we call it a day... # create a variable to keep track of whether we should keep running # the magic 8 ball program. Then at the end of the loop, prompt the user # and ask he or she whether they would like to keep asking the magic 8 # ball questions. If they reply no or yes or whatever, then change the # value of the variable, so that the loop quits running. Also, tell the # user goodbye if they choose to exit. Go! # Faraz, change this while loop to where it it keeps running # while some variable is equal to true keep_running = True keep_playing = "fo sho" while keep_running == True: count = count + 1 question = input("Ask me a question") my_list = [ "is is certain", "it is decidedly so", "without a doubt", "Yes - definetly", "You may rely on it", "As I see it yes", "Most likely", "Outlook, good", "Yes.", "Signs point yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] random_number = random.randint(0, 19) # you don't want blablabla == True, # you wan't if this string method returns -1, # print yes of course!] ''' if question.find("coding") >= 0: print("Yes, of course!") else: print(my_list[random_number]) if question.find("code") >= 0: print("Yes, of course!") else: print(my_list[random_number]) ''' question = question.lower() # convert to lowercase for string comparison if question.find("coding") >= 0: print("Yes, of course!") elif question.find("code") >= 0: print("Yes, of course!") elif question.find("program") >= 0: print("Yes, of course!") elif question.find("programming") >= 0: print("Yes, of course!") else: print(my_list[random_number]) if count % 3 == 0: #then question.input("Woud") keep_playing = input("Would you like to keep playing? Enter 'y' for yes, 'n' for no>>> ") keep_playing = keep_playing.lower() if keep_playing.find("n") >= 0: print("Goodbye!") # right here, is where you will turn off the loop keep_running = False # Faraz, if the user wants to stop playing, tell the user goodbye # and shut down the loop... Go!
true
66cfcfab59440263d4a5d8c583dacb8c00f0ef15
PAPION93/python-playground
/01_python_basic/07-2-Inheritance.py
1,473
4.5
4
# 파이썬 클래스 # 상속, 다중상속 class Car: """Parent Class""" def __init__(self, type, color): self.type = type self.color = color def show(self): return 'Car Class show()' class BmwCar(Car): """Sub Class""" def __init__(self, car_name, type, color): super().__init__(type, color) self.car_name = car_name def show_model(self) -> None: return "Your Car Name : %s" % self.car_name class BenzCar(Car): """Sub Class""" def __init__(self, car_name, type, color): super().__init__(type, color) self.car_name = car_name def show_model(self) -> None: return "Your Car Name : %s" % self.car_name def show(self): print(super().show()) return "Car Info : %s %s %s" %(self.car_name, self.type, self.color) # Use model1 = BmwCar('520d', 'sedan', 'red') print(model1.color) print(model1.type) print(model1.car_name) print(model1.show()) print(model1.show_model()) print(model1.__dict__) print() # Method Overriding model2 = BenzCar("s", "suv", "black") print(model2.show()) print() # Parent Method call model3 = BenzCar("c", "sedan", "blue") print(model3.show()) print() # Inheritance print(BmwCar.mro()) print(BenzCar.mro()) print() print() # 다중상속 class X(): pass class Y(): pass class Z(): pass class A(X, Y): pass class B(Y,Z): pass class M(B, A, Z): pass print(M.mro())
false
562aab1605b9c5e77f75b11d9a3b74552ca2c5da
ProdigyX6217/interview_prep
/char_count.py
251
4.4375
4
user_str = input("Please enter a string: ") # This variable will be used to hold the number of characters in the string. count = 0 # This for loop adds 1 to count for each character in user_str. for char in user_str: count += 1 print(count)
true
8851c47cc61d585a02bbe8ab035c3248afd5e3a6
ProdigyX6217/interview_prep
/convert_degrees.py
720
4.5
4
celsius = int(input("Please enter an integer value for degrees celsius: ")) def fahrenheit(cel): # To avoid the approximation error that would occur if the float 1.8 was used in the calculation, 1.8 * 10 is used # instead, resulting in the integer 18. To balance this out, 32 is also multiplied by 10 to get 320. After the # calculations in the parentheses are finished, the result is divided by 10, which gives the correct Fahrenheit # temperature. return (18 * cel + 320) / 10 # print("The Fahrenheit equivalent of " + str(celsius) + " degrees Celsius is " + str(fahrenheit(celsius)) + ".") print(str(celsius) + " degrees Celsius is " + str(fahrenheit(celsius)) + " degrees Fahrenheit.")
true
b679551cca213b2b705d70eff7e45b61c2b3f010
karaspd/leetcode-problem
/python/6/ZigzagConversion.py
1,477
4.15625
4
""" 6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". """ class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows==1 or numRows>len(s): return s zig=True k=0 list_num=['']*numRows j=0 while j <len(s): if zig: list_num[k] +=s[j] k+=1 j+=1 if k==numRows: zig=False k =numRows-1 else: if numRows>2: k -=1 list_num[k]+=s[j] if k==1: zig=True k=0 j+=1 else: zig=True k=0 return ''.join(list_num) def convert2(self, s, numRows): # faster solution from leetcode solutions """ :type s: str :type numRows: int :rtype: str """ if numRows == 1 or numRows >= len(s): return s L = [''] * numRows index, step = 0, 1 for x in s: L[index] += x if index == 0: step = 1 elif index == numRows -1: step = -1 index += step return ''.join(L) s="ABC" print Solution().convert(s,2) print Solution().convert2('PAYPALISHIRING',3)
true
ada4a46a88954707cb958f23a0b13332d4ed37eb
shavvo/Projects
/Projects/PtHW_Ex/ex15_open_files.py
668
4.25
4
from sys import argv script, filename = argv txt = open(filename) # 'open' is a command that reads the files # ( as long as you put the name of the file in # the command line when you run the script) print "Here is your file %r:" % filename print txt.read() # txt is the variable of object and the . (dot) # is to add a command, "read" in this case. # The parentheses () have to be there but in # this case there are no arguments to pass # And these do it all over from within the script: print "Type the filename again:" file_again = raw_input("> ") txt_again = open(file_again) print txt_again.read() # Also need to close the files txt.close txt_again.close
true
b0ff17bb9b8e449491605256305d1873e21c322d
RedPython20/New-Project
/weight_conv.py
460
4.3125
4
#Weight Converter app #Convert your weight to either pounds or kilos. #This section gets the user's data weight = input("How much do you weigh? ") unit = input("(L)bs or (K)gs? ") #Pounds to kilos if unit == "L": new_weight = int(weight) // 2.205 print("Your weight in kilos is : ", str(new_weight)) #Kilos to pounds if unit == "K": new_weight = int(weight) * 2.205 print ("Your weight in pounds is: ", str(new_weight))
true
54de09d1bfb95805012c167e2dfbe9dbe9fc3751
MarkBenjaminKatamba/python_sandbox
/python_sandbox_starter/conditionals.py
1,704
4.46875
4
# If/ Else conditions are used to decide to do something based on something being true or false c = 16 d = 16.4 # Comparison Operators (==, !=, >, <, >=, <=) - Used to compare values # Simple if # if c > d: # print(f'{c} is greater than {d}') # If/else # if c > d: # print(f'{c} is greater than {d}') # else: # print(f'{d} is greater than {c}') # elif # if c > d: # print(f'{c} is greater than {d}') # elif c==d: # print(f'{c} is equal to {d}') # else: # print(f'{d} is greater than {c}') # Nested if (Not always recommended; better to use logcal operators) # if c > 2: # if c <= 10: # print(f'{c} is greater than 2 and less than or equal to 10') # Logical operators (and, or, not) - Used to combine conditional statements # # and (here, both conditions have to be true) # if c > 2 and c <= 10: # print(f'{c} is greater than 2 and less than or equal to 10') # # or (here, either one or the other of the conditions should be true) # if c > 2 or c <= 10: # print(f'{c} is greater than 2 or less than or equal to 10') # # not # if not(c == d): # print(f'{c} is not equal to {d}') # Membership Operators (in, not in) - Membership operators are used to test if a sequence is presented in an object numbers = [1,2,3,4,5,6,7,8,9] # # in # if c in numbers: # print(c in numbers) # This will just give us a true of false # # not in # if c not in numbers: # print(c not in numbers) # Identity Operators (is, is not) - Compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: # # is # if c is d: # print(c is d) # # is not # if c is not d: # print(c is not d)
true
a0261cafabef291f465553216412ee185a0a84ca
flash-drive/Python-First-Go
/Homework 2 Fall Time.py
759
4.15625
4
# Homework 2 Fall time # Mark Tenorio 5/10/2018 # Write a program that determines the time it takes for an object # to hit the ground from a given height # Recall the kinematics equation: # distance = velocity(initial) * t + (1/2)*acceleration*time^2 # Assume that velocity(initial) is zero m/s. # Assume that acceleration is a constant 9.8 m/s. # Function to find time it takes for an object to reach the ground def time(height): time = ((float(height) * 2) / 9.8) ** (1/2) time = round(time,2) return time # Handle user input print('Input a height in meters') height = input() # Call function time = time(height) # Print output print('It takes '+(str(time))+' seconds to reach the ground from '+str(height)+' meters.')
true
d9e16a8ffdcbac930cb679cce804e6d2478ddedc
flash-drive/Python-First-Go
/Homework 3 Weather Stats.py
976
4.28125
4
# Homework 3 Weather Stats # Mark Tenorio 5/13/2018 # Write a program that takes in a list # comprised of a vector and a string. Output the maximum and average # of the vector and output the string. # Import modules from statistics import mean import ast # Function to output max, average, and string from list def weatherStats(info): numbers = info[0] forecast = str(info[1]) maxNum = max(numbers) avgNum = mean(numbers) avgNum = round(avgNum) return maxNum, avgNum,forecast # Handle user input print('Please input the vector and forecast in a list') print('The format should be [[vector],string]') info = input() # Convert string list into actual list info = ast.literal_eval(info) # Call function [maxNum,avgNum,forecast] = weatherStats(info) # Print output print("Today's weather was "+forecast.lower()+", with a high temperature of "+str(maxNum)+" degrees and an average temperature of "+str(avgNum)+" degrees.")
true
c68142b091a3f615de97fc4aeb5a46cfac02f508
flash-drive/Python-First-Go
/Classes.py
1,440
4.46875
4
#### Class #### # Classes are blueprints where you can make objects # Objects contain different variables and methods (function) # Differences between a class and an object is that the values that belong # to the variables are not defined. It will not refer to a specific object. # class Robot: # def introduce_self(self): # print("My name is "+self.name) #self is like "this" in Java # # r1 = Robot() #Python constructor(?) # r1.name = "Tom" # r1.color = "red" # r1.weight = 30 # Here a new object has been created and been assigned to r1 # and the attributes have been set. # # r1.introdue_self() # # r2.Robot() # r2.name = 'Jerry' # r2.color = 'blue' # r2.weight = 40 # r1.introduce_self() #### Another way to do it with constructors #### # class Robot: # def __init__(self,Name,Color,Weight): # this is a constructor #need self # self.name = givenName # self.color = givenColor # self.weight = givenWeight # # def introduce_self(self): # print("My name is "+self.name) #self is like "this" in Java # # # r1 = Robot("tom","red",30) # r2 = Robot("Jerry","blue",40) # # r1.introduce_self() # r2.introduce_self() # # # # class Person: # def __init__(self,n,p,): # self.name = n # self.personality = p # self.is_sitting = i # # def sit_down(self): # self.is+sitting = True # def stand_up(self): # sef.is_sitting= False
true
c974d7b78b2410ef05689f39ebe0ff1e277f44fc
RashiKndy2896/Guvi
/Dec19_hw31strong.py
561
4.28125
4
maximum = int(input(" Please Enter the Maximum Value: ")) def factorial(number): fact = 1 if number == 0 or number == 1 : return fact for i in range(2, number + 1) : fact *= i return fact for Number in range(1, maximum): Temp = Number Sum = 0 while(Temp > 0): Reminder = Temp % 10 Factorial = factorial(Reminder) Sum = Sum + Factorial Temp = Temp // 10 if (Sum == Number): print(" %d is a Strong Number" %Number)
true
06ea689737eb486f770bec009b657f706d863656
euphoria-paradox/py_practice
/2_helloworld_unicode.py
289
4.25
4
# This program displays the unicode encoding for 'Hello World!' # Intro greeting print('The Unicode encoding for \'Hello World!\' is: ') # Output results. print(ord('H'), ord('e'), ord('l'), ord('l'), ord('o'), ord(' '), ord('W'), ord('o'), ord('r'), ord('l'), ord('d'), ord('!'))
false
75d9e3de14c2f7e2fda2de6f6be687625176f389
euphoria-paradox/py_practice
/p_d_3/3_fruit_display.py
346
4.34375
4
# P1 3 # Program to display respective fruit name for # the user input of Alphabets(A,B or C) alphabet = input('Enter the character(A or B or C): ') # checking for condition if alphabet == 'A': print('Apple') elif alphabet == 'B': print('Banana') elif alphabet == 'C': print('Coconut') else: print('INVALID character')
true
266cc73a414731724b29a33a8bf3aaba718ca3a4
euphoria-paradox/py_practice
/p_d_3/monthly_mortgage.py
1,647
4.46875
4
# Home Loan Amortization # This program calculates the monthly mortgage payments for a given loan amount # term and range of interests from 3 to 18% # the formula for determinig the mortgage is A/D # A - original loan amount # D - discount factor given by D = ((1+r)^n -1)/r(1+r)^n # n- number of payments, r-interest rate expressed in decimal divided by 12 # Greet print(format('Welcome to Monthly Mortgage calculator', '-^44')) # get input for loan amount and term(number of years) A = float(input('Enter the loan amount: $')) term = int(input('Enter the term of loan amount: ')) # no of years # interest rates are from 3 to 18% # calculate the mortgage interest_rate = 3 blank_char = ' ' header = 'Loan Amount: $' + str(A) + ' Term: ' + str(term) + ' years\n' blank_spaces = str(len(header)- 28) # for proper alignment print('\nLoan Amount: $' + str(A) + ' Term: ' + str(term) + ' years\n') print('Interest Rate' + format(blank_char, blank_spaces) + 'Monthly Payment\n') ''' n = term * 12 r = (interest_rate/100)/12 num = (1 + r)**n - 1 denom = r print(num) ''' while interest_rate <= 18: n = term * 12 r = (interest_rate/100)/12 D = ((1 + r)**n - 1) / (r*(r + 1)**n) monthly_payment = A/D # monthly mortgage if interest_rate < 10: print(format(blank_char,'5') + str(interest_rate) + '%' + format(blank_char,'21') + str(format(monthly_payment,'.2f')) + '\n') else: print(format(blank_char,'5') + str(interest_rate) + '%' + format(blank_char,'20') + str(format(monthly_payment,'.2f')) + '\n') interest_rate += 1
true
3341c9c72a7ed6f6233ca4eca015aa38020106ed
euphoria-paradox/py_practice
/p_d_3/3.3.1_sum_even.py
274
4.1875
4
# Addition of even numbers between 100 and 200 # Init num = 100 sum_of_even = 0 # summing of even numbers using a while loop while num <= 200: sum_of_even += num num += 2 # Display of result of addition print('Sum of even numbers between 100 & 200:', sum_of_even)
true
6b4ea4370106b2820c50f7d8f62f10498a1fbef7
euphoria-paradox/py_practice
/p_d_3/lif_signs.py
1,440
4.375
4
# Life Signs # This is a test program to that determines number of breaths # and the number of heartbeats the person had in their life # based on their age. # The average respiration rate of people changes during different # stages of development. # the breath rates used are : # Infant - 30-60 breaths per min # 1-4 years - 20-30 breaths per min # 5-14 years - 15-25 breaths per min # adults - 12-20 # Avg heart rate is 67.5 beats per second. # Greet print('Welcome to the program') print('''This is a test program to that determines number of breaths and the number of heartbeats the person had in their life based on their age.''') #init valid = True #user input of age age = int(input('Enter your age: ')) # calculate the breaths. if age>=1 and age<=4: num_breaths = (((30+60)//2)*60*24*365)+((age)*((20+30)//2)*60*24*365) elif age>4 and age<=14: num_breaths = (((30+60)//2)*60*24*365)+(4*((20+30)//2)*60*24*365)+ (age*(15+25//2)*60*24*365) elif age>14: num_breaths = (((30+60)//2)*60*24*365)+(4*((20+30)//2)*60*24*365)+ (14*(15+25//2)*60*24*365)+(age*((12+20)/2)*60*24*365) else: valid = False print('Enter the correct age') if valid: heart_rate = age*67.5*60*24*365 print('The approximate number of breaths taken by you in',age,'years is',format(num_breaths,','),'\n', 'The approximate number of heartbeats you had in',age,'years is',format(heart_rate,','),'\n')
true
a65ddcbd2e1e57a05a1e7573e821a4bec1418062
CampbellD84/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
1,885
4.125
4
class Node: def __init__(self, value=None, next_node=None): # the value at this linked list node self.value = value # reference to the next node in the list self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): # set this node's next_node reference to the passed in node self.next_node = new_next class LinkedList: def __init__(self): # reference to the head of the list self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False # get a reference to the node we're currently at; update this as we traverse the list current = self.head # check to see if we're at a valid node while current: # return True if the current value we're looking at matches our target value if current.get_value() == value: return True # update our current node to the current node's next node current = current.get_next() # if we've gotten here, then the target node isn't in our list return False def reverse_list(self): # init a variable to store node(s) prev_node = None # set current to the head node curr = self.head # loop through linked list # swap nodes as long as curr is NOT None while curr is not None: self.next_node = curr.next_node curr.next_node = prev_node prev_node = curr curr = self.next_node # set head to previous node (former tail node) self.head = prev_node
true
bd92d14b3a8498cf4aadb39a31a3071d33c4d7c0
AlexanderPoleshchuk/Docker-sort
/sorting.py
381
4.125
4
def bubble_sort(my_list): last_index = len(my_list) - 1 for i in range(0, last_index): for j in range(0, last_index - i): if my_list[j] > my_list[j + 1]: my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j] return my_list if __name__ == '__main__': example_list = [4,1,8,7,10,9,3,2,5,6] print(bubble_sort(example_list))
false
08a06f8bf0c3c4084f4e361c6294225f7f9f091f
damiati-a/CURSO-DE-PYTHON
/Mundo 1/aula 6.py
976
4.21875
4
# CONDIÇÕES """ if e else (se e senão) se carro.esquerda() bloco_v_ senão bloco_f_ correto if carro.esquerda(): bloco True else: bloco False """ """ tempo = int(input('Quantos anos tem seu carro? ')) if tempo <=3: print('carro novo') else: print('carro velho') print('--FIM--') """ """ CONDIÇÃO SIMPLIFICADA tempo = int(input('Quantos anos tem seu carro? ')) print('carro novo' if tempo <=3 else 'carro velho') print('--FIM--') """ # PARTE PRATICA """ nome = str(input('Qual o seu nome?')) if nome == 'André': print('Bem vindo homem mais gostoso da Terra') print('Acesso permitido, {}!'.format(nome)) print('Acesso restringido'.format(nome)) """ n1 = float(input('Digite a nota 1: ')) n2 = float(input('Digite a nota 2: ')) m = (n1 + n2)/2 print('A sua média foi {:.1f}'.format(m)) if m >= 6.0: print('Parabéns, você passou de ano') else: print('Ta mal hein, bora estudar!')
false
47e774c6d56bac7a2e0bb9e249e70a95c1b79542
damiati-a/CURSO-DE-PYTHON
/Mundo 1/ex018.py
514
4.125
4
# Seno, Cosseno e Tangente import math an = float(input('Digite o angulo que deseja? ')) sen = math.sin(math.radians(an)) print('O angulo de {} tem o seno de {:.2f}'.format(an, sen)) cos = math.cos(math.radians(an)) print('O angulo de {} tem o cosseno de {:.2f}'.format(an, cos)) tan = math.tan(math.radians(an)) print('O angulo de {} tem a tangente de {}'.format(an, tan)) # ou, importando somente os dados utilizaveis. Ai tirando as referencias a 'math'. from math import radians, sin, cos, tan
false
33ef25bcd74c64f23733386d5c48ebea36968d89
rjdoubleu/GSU
/Design and Analysis of Algortithms/Python/Depth_First_Search.py
1,943
4.15625
4
# Python program to print DFS traversal from a given given graph # Visits all verticies and computes their mean and variance from collections import defaultdict #from random import randint # This class represents a directed graph using adjacency list representation class Graph: # Constructor def __init__(self): # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self,v,visited): # Mark the current node as visited and print it visited[v]= True print(v) global s, c, verticies s += v verticies.append(v) c += 1 # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.DFSUtil(i, visited) # The function to do DFS traversal. It uses # recursive DFSUtil() def DFS(self,v): # Mark all the vertices as not visited visited = [False]*(len(self.graph)+1) # Call the recursive helper function to print # DFS traversal self.DFSUtil(v,visited) # Driver code # Create a graph given in the above diagram # Each vertex is labeled with a unique integer L(u) from the set {1,2,...,|V|} g = Graph() g.addEdge(1, 2) g.addEdge(2, 3) g.addEdge(3, 3) g.addEdge(1, 4) g.addEdge(4, 4) g.addEdge(2, 5) g.addEdge(5, 3) g.addEdge(3, 4) g.addEdge(5, 1) # global sum and count variables to compute average s = 0.0 c = 0 verticies = [] print("Following is DFS from (starting from vertex 5)") g.DFS(5) v_mean = s/c print("Vertex Mean: " + str(v_mean)) #reset value of s for new sum operation s = 0.0 for v in verticies: s += (v - v_mean)**2 v_variance = s/len(verticies) print("Vertex Variance " + str(v_variance))
true
5a5a1b03c9b6fb68c07014256b34cf9e7af6d7e0
vijaybnath/python
/vijay16.py
464
4.21875
4
energy = int(input('enter the number you want to convert ')) units = input('which type of convertion you want to do only (kw)kilowatts to watts , (kv) kilovolt to volt or (v)olt to watt ') if (units == "kw"): converted = energy * 1000 print(f"the converted energy = {converted} watt") elif(units == "kv"): converted = energy * 1000 print(f"the energy = {converted} volt") else: converted = energy * 1 print(f"the energy = {converted} watt")
true
1aa3363b36796f3672ff6db15c6771b93839c360
RNTejas/programming
/Python_Flow_Control/Python Flow Control/8.For loop.py
304
4.375
4
print("Welcome to the For Loop") """ The computer can perform the repeated tasks very quickly or earlier like, For Loop While Loop List Comprehension and Generators it executes the block of code for each iterable """ parrot = "Norwegian Blue" for character in parrot: print(character)
true
e5d92fbeff64e9a91d4a94b2329a840970f77372
RNTejas/programming
/Python_Flow_Control/Python Flow Control/1.if Statements.py
742
4.25
4
# the input function will returns the value as a string # name = input("Please enter your name: ") # age =int(input(f"How old are you, {name}?")) # print(age) # this will print out the age but we can't add the string to this number # print(f"{name}, is {age} Years old") # age = int(age) # print(2 + age * 10) # print(type(age)) a = float(input("Please enter your age in years and month followed by '.' like 12.4, 18.9 : ")) print(a) #b = range(101, 9999) #the following code is a voting age generator if a < 18: print( "Come back in {} Years for Vote".format(18 - a)) elif a == range(101, 1000): print("You have Died!!!!") else: print("You are enough to Vote") print("Please put your Vote in the box")
true
a4a88d8eb3ab92368571017794feb22f99a1893d
byui-cse/cse210-student-solo-checkpoints-complete
/06-nim/nim/game/board.py
2,039
4.3125
4
import random class Board: """A designated playing surface. The responsibility of Board is to keep track of the pieces in play. Stereotype: Information Holder Attributes: _piles (list): The number of piles of stones. """ def __init__(self): """The class constructor. Args: self (Board): an instance of Board. """ self._piles = [] self._prepare() def apply(self, move): """Applies the given move to the playing surface. In this case, that means removing a number of stones from a pile. Args: self (Board): an instance of Board. move (Move): The move to apply. """ pile = move.get_pile() stones = move.get_stones() self._piles[pile] = max(0, self._piles[pile] - stones) def is_empty(self): """Determines if all the stones have been removed from the board. Args: self (Board): an instance of Board. Returns: boolean: True if the board has no stones on it; false if otherwise. """ empty = [0] * len(self._piles) return self._piles == empty def to_string(self): """Converts the board data to its string representation. Args: self (Board): an instance of Board. Returns: string: A representation of the current board. """ text = "\n--------------------" for pile, stones in enumerate(self._piles): text += (f"\n{pile}: " + "O " * stones) text += "\n--------------------" return text def _prepare(self): """Sets up the board with a random number of piles containing a random number of stones. Args: self (Board): an instance of Board. """ piles = random.randint(2, 5) for n in range(piles): stones = random.randint(1, 9) self._piles.append(stones)
true
7493c538d11bf91f27a028d505b5f3e98cf7f61e
UtsavRaychaudhuri/Learn-Python3-the-Hard-Way
/ex9.py
446
4.125
4
# assigning the variable days="Mon Tue Wed Thu Fri Sat Sun" # assigning to a variable but with new line inbuilt into the string months="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # printing print("Here are the days:",days) # printing print("Here are the months:",months) # Multiline string print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Evem 4 lines if we want, 5, or 6. """)
true
8857381167f42e0a633e6d27d17f1b3e70ecc8c9
bergolho/curso_python_ufsj
/codes/grambery/sample_4/numpy_array_copy.py
710
4.15625
4
import numpy as np def copy_by_reference (): # Criando um array x x = np.array([ 1., 2., 3.5 ]) # Agora o ponteiro 'a' aponta para o array 'x' a = x print("a") print(a) print("x") print(x) # Alterando o ultimo elemento de 'a' a[-1] = 3 print("a") print(a) print("x") print(x) def copy_by_value (): # Criando um array x x = np.array([ 1., 2., 3.5 ]) # (sem usar ponteiro) # Copiando os elementos do array 'x' para 'a' a = x.copy() print("a") print(a) print("x") print(x) # Alterando o ultimo elemento de 'a' a[-1] = 9 print("a") print(a) print("x") print(x) print("Copia por referencia") copy_by_reference() print() print("Copia por valor") copy_by_value()
false
79d97d8382aaf7b9993e108b7a2fa0580b6cf53b
Aaryan1734/RPS
/RPS.py
1,758
4.21875
4
# ROCK PAPER SCISSORS GAME # Remember the rules: # rock beats scissors # scissors beats paper # paper beats rock import getpass print("""Let's play a game of rock paper scissors!! You'll need a partner to play this game. To End the Game input any response other than rock, paper or scissors.""") print("-" * 100) play_again = "y" u1_score = 0 u2_score = 0 while play_again == "y": user_1 = getpass.getpass( prompt="Player 1, enter your choice from Rock, Paper or Scissors ").lower() user_2 = getpass.getpass( prompt="Player 2, enter your choice from Rock, Paper or Scissors ").lower() print("Player 1 typed", user_1.capitalize()) print("Player 2 typed", user_2.capitalize()) if user_1 == user_2: print("Game tied!!") elif user_1 == "rock" and user_2 == "scissors": print("Player 1 wins!!") u1_score += 1 elif user_1 == "paper" and user_2 == "rock": print("Player 1 wins!!") u1_score += 1 elif user_1 == "scissors" and user_2 == "paper": print("Player 1 wins!!") u1_score += 1 elif user_1 == "scissors" and user_2 == "rock": print("Player 2 wins!!") u2_score += 1 elif user_1 == "rock" and user_2 == "paper": print("Player 2 wins!!") u2_score += 1 elif user_1 == "paper" and user_2 == "scissors": print("Player 2 wins!!") u2_score += 1 else: print("Somebody typed something incorrect") play_again = input("Do you want to play again? (y/n) ") if play_again == "n": break print("Game Over") print("The final score is Player 1: ", u1_score, "| Player 2:", u2_score)
true
bbced53efb44e572f6c919da5a7bd7b2dc510c8e
porregu/unit5
/claswork8.py
306
4.15625
4
user_number = int(input("what number do you want to put?")) while user_number!=1: print(user_number) if user_number%2==0: user_number/=2 print("new number = ",user_number)# print the new number else: user_number=user_number*3+1 print("new number = ",user_number)
true
1320d84cad763e584256cd1f8be502618534221b
Zchap1/Old_Python
/guess my number game.py
645
4.125
4
print ("\tWelcome to 'guess my numer'!") print ("\n I'm thinking of a number between 1 and 1000.") print ("Try to guess it in as few attempts as possible.\n") # set the initial values import random the_number = random.randint(1, 1000) #guess = int(input("take a guess: ")) guess = 0 tries = 0 #guessing loops5 while guess != the_number: guess = int(input("take a guess: ")) tries += 1 if guess > the_number: print ("lower...") else: print ("higher...") print (" You guessed it! The number was",the_number) print ("And it only took you ",tries, "tries.") input("\n\n\tPress the enter key to exit.")
true
b21dc12fd76fb85352c1ea0a9ebbed5ec9e730f1
Jean13/convenience
/unscramble.py
1,470
4.15625
4
# Template for unscrambling words # Compares a scrambled wordlist with original wordlist and unscrambles unscrambled = [] def main(): readFiles() # Read the original wordlist and the txt file with the scrambled words def readFiles(): # Makes the words from the files available to the whole program global words global scrambled print("[+] Reading Wordlist") # Original wordlist - modify accordingly mf = open("wordlist.txt", "r") words = mf.readlines() mf.close() print("[+] Reading Scrambled Wordlist") # Scrambled word list - modify accordingly mf2 = open("scrambled.txt", "r") scrambled = mf2.readlines() mf2.close() matchStrings() def matchStrings(): print("[+] Matching Scrambled With Unscrambled") for text in scrambled: # rstrip() [right-strip] removes trailing characters text = text.rstrip("\n") txtSorted = ''.join(sorted(text)) for word in words: word = word.rstrip("\n").rstrip("\r") wordSorted = ''.join(sorted(word)) if txtSorted == wordSorted: unscrambled.append(word) displayUnscrambled() def displayUnscrambled(): global unscrambled print("[+] Task Complete --> All Strings Matched") print("[+] Unscrambled Words:") unscrambled = ','.join(map(str, unscrambled)) print('-' * 80) print(unscrambled) print('-' * 80) if __name__ == '__main__': main()
true
4fcad62bea4bb3df5080548ab6e1ed117d7c747b
VolanNnanpalle/Python-Projects
/rock_paper_scissors.py
1,650
4.46875
4
# -*- coding: UTF-8 -*- """ Rock, Paper, Scissors Game Make a rock-paper-scissors game where it is the player vs the computer. The computer’s answer will be randomly generated, while the program will ask the user for their input. """ from random import randint #rock beats scissors #paper beats rock #scissors beats paper rock = 1 paper = 2 scissors = 3 computer = randint(1, 3) print("\n\nWelcome to Rock, Paper, Scissors Game\n\n") print("\n\n Rock = 1\n Paper = 2\n Scissors = 3\n\n") print ("You will be playing the computer\n\n") print("Plelae enter the respective valuese\n\n") user_input = int(input("Rock, Paper, Scissors, SHOOT!")) if(user_input == 1 & computer == 3): print ("YOU WIN!\n") print(computer,"\n") print("You chose ROCK & the computer chose SCISSORS\n") elif(user_input == 1 & computer == 2): print ("YOU LOSE!\n") print(computer, "\n") print("You chose ROCK & the computer chose PAPER\n") elif(user_input==2 & computer==1): print ("YOU WIN!\n") print(computer, "\n") print("You chose PAPER & the computer chose ROCK\n") elif(user_input==2 & computer==3): print ("YOU LOSE!\n") print(computer, "\n") print("You chose PAPER & the computer chose SCISSORS\n") elif(user_input==3 & computer==2): print ("YOU WIN!\n") print(computer, "\n") print("You chose SCISSORS & the computer chose PAPER\n") elif(user_input==3 & computer==1): print ("YOU LOSE!\n") print(computer, "\n") print("You chose SCISSORS & the computer chose ROCK\n") elif(user_input == computer): print ("ITS A TIE!\n") print(computer, "\n") print(computer) print(user_input)
true
dc7fd3fa3c12fc96a59261296a9d8b0bd097153b
yuvaraj950/pythonprogram
/averageof list.py
247
4.15625
4
#Take a list list1 = [5,6,8,9,7,5] #Average of number = sum of numbers in list /total members in list length = len(list1) print(length) sum_list1 = sum(list1) print(sum_list1) #output average_list1 = (sum_list1 / length) print(average_list1)
true
9d3f29045a19aaa700f9c4d46780013ca88eb829
SameerShiekh77/Python-Tutorial
/tut11.py
742
4.3125
4
print("CALCULATOR DEVELOP BY IT EDUCATION\n\n\n\n") num1 = int(input("Enter your first number: ")) num2 = int(input("Enter your second number: ")) op = input("Select your operator\n\t+\t-\t*\t/\t%\n") if op == '+': { print("The sum of num1 and num2 is: ", num1 + num2) } elif op == '-': { print("The subtraction of num1 and num2 is: ", num1 - num2) } elif op == '*': { print("The multiplication of num1 and num2 is: ", num1 * num2) } elif op == '/': { print("The division of num1 and num2 is: ", num1 / num2) } elif op == '%': { print("The remainder of num1 and num2 is: ", num1 % num2) } else: print("Invalid Operator")
false
365898eb7874e64e2dcd5a04e21eb28b667ad119
miguelhasbun/Proyecto-1_SI
/main.py
871
4.15625
4
from trie import * from levenshtein import * WORD_TARGET = sys.argv[1] for word in WORDS: trie.insert(word) l = levenshtein() if WORD_TARGET=="grep" or WORD_TARGET=="ping" or WORD_TARGET=="ls": result = WORD_TARGET else: print ("Did you meant to say:",l.search(WORD_TARGET)) result = l.search(WORD_TARGET) if len(result) == 0: print('You have not written any commands!') else: if result == "grep": print('grep is a command-line utility for searching plain-text data sets for lines that match a regular expression') elif result == "ping": print('The ping is used to test the ability of the source computer to reach a specified destination computer. ') elif result == "ls": print('ls is a command to list computer files in Unix and Unix-like operating systems.') else: print('Unrecognised argument.')
true
7037a8f4a82695fdbc29207f80336fed27d15ec1
alexander-mcdowell/Algorithms
/python/InsertionSort.py
1,131
4.4375
4
# Insertion Sort: Simple sorting algorithm that works relatively well for small lists. # Worst-case performance: O(n^2) where n is the length of the array. # Average-case performance: O(n^2) # Best-case performance: O(n) # Worst-case space complexity: O(1) # Method: # 1. Loop through the array. If array[i + 1] < array[i], insert array[i + 1] into the subarray to the left such that the subarray is sorted. # 1 cont. For example, if [3, 7, 8, 5] is the part of the array that has been seen thusfar, 5 is inserted in between 3 and 7 so that the subarray is [3, 5, 7, 8]. def insertionSort(array): sorted = [] iterations = 0 for i in range(len(array)): count = 0 for k in range(len(sorted)): if array[i] > sorted[k]: count += 1 iterations += 1 sorted.insert(count, array[i]) return sorted, iterations a = [3, 7, 8, 5, 2, 1, 9, 5, 4, 4, 7, 5, 3, 4, 8, 7, 3, 7, 9, 2, 5, 8, 0, 2, 6, 6, 1] print("Unosorted list: " + str(a)) a, iterations = insertionSort(a) print("Sorted list: " + str(a)) print("Sort took " + str(iterations) + " iterations.")
true
1781d10e402e177dec64720c36b491c8167acbdd
alexander-mcdowell/Algorithms
/python/ShellSort.py
1,847
4.3125
4
import math # Shell sort: a variant of isertion sort that sorts via the use of "gaps." # Worst-case complexity: O(n log n) where n is the length of the array. # Average-case complexity: O(n^4/3) # Best-case complexity: O(n^3/2) # Worst-case space complexity: O(1) # Method: # 1. Initialize the gap values. # 2. Loop through the possible gap values: # 2a. Group values that are index + multiple * gap length # 2b. Insertion sort the partitions. Combine the sorted partitions. # 3. The final list has been sorted. def insertionsort(array): sorted = [] iterations = 0 for i in range(len(array)): count = 0 for k in range(len(sorted)): if array[i] > sorted[k]: count += 1 iterations += 1 sorted.insert(count, array[i]) return sorted, iterations def shellsort(array): iterations = 0 intervals = [int((3 ** k - 1) / 2) for k in range(1, math.ceil(math.log(2 * len(array) - 1) / math.log(3)))][::-1] for interval in intervals: if interval == 1: break partitions = [] for i in range(interval): a = [] k = 0 while True: x = interval * k + i if x > len(array) - 1: break a.append(array[x]) k += 1 partitions.append(a) b = [] for p in partitions: x, iter = insertionsort(p) b += x iterations += iter array = b array, iter = insertionsort(array) iterations += iter return array, iterations a = [3, 7, 8, 5, 2, 1, 9, 5, 4, 4, 7, 5, 3, 4, 8, 7, 3, 7, 9, 2, 5, 8, 0, 2, 6, 6, 1] print("Unosorted list: " + str(a)) a, iterations = shellsort(a) print("Sorted list: " + str(a)) print("Sort took " + str(iterations) + " iterations.")
true
29a4361f03d95b3e5ace4e4b90c3d870a88e4794
alexander-mcdowell/Algorithms
/python/ExponentiationSqr.py
1,445
4.28125
4
import math # There are two algorithms here: Exponentiation by Squaring and Modulo of Exponentiation by Squaring. # Both algorithms use O(log n) squarings and O(log n) multiplications. # Exponentiation by Squaring: Quickly computes the value n^k by using properties of squaring. # This method works because of the property that n^k = n^a * n^b where a is a power of 2 and b is a number such that the equality is true. # Example: 5^10 # Init: (d, x, c) = (10, 5, 1) # (d, x, c) = (5, 25, 1) # (d, x, c) = (2, 625, 25) # (d, x, c) = (1, 390625, 25) # Result = x * c = 9765625 # Modulo of Exponentiation by Squaring: Quickly computes the value mod(n^k, p) by using properties of squaring. # This method uses the same technique as above except that everytime a multiplication happens, mod p is applied to it. # Example: 5^10 mod 9. # Init: (d, x, c) = (10, 5, 1) # (d, x, c) = (5, 7, 1) # (d, x, c) = (2, 4, 7) # (d, x, c) = (1, 7, 7) # Result = x * c mod 9 = 49 mod 9 = 4 def expBySqr(n, k): d = k x = n c = 1 while d > 1: if (d % 2 == 1): c *= x x *= x d = math.floor(d / 2) print((d, x, c)) return x * c def modExpBySqr(n, k, p): d = k x = n % p c = 1 while d > 1: if (d % 2 == 1): c *= x % p x *= x % p d = math.floor(d / 2) return (x * c) % p n = 5 k = 10 print(expBySqr(n, k))
true
ba99261bb0e910510ca11ab149de4e417a60495f
gauravdn47/SyllabusHandsOn
/chapter3_Python Operators and Expressions.py
962
4.125
4
# Expressions vs Statements # Expression 4 + 5 4 * 9 True False # Statements # If Condition # Converting int to str and vice-versa x = 5 type_of_x = type(x) print(type_of_x) y = str(x) type_of_y = type(y) print(type_of_y) a = '5' type_of_a = type(a) print(type_of_a) b = int(a) type_of_b = type(b) print(type_of_b) # Comparing output of '/' and '//' x = 5 y = 2 Division = x/y print("The division output is:",Division) x = 5 y = 2 Division = x//y print("The division output is:",Division) # Demonstrating Manual approach of bitwise operation print(~12) # Bitwise Ones' Compliment operator a = 12 b = 13 c = a & b # Bitwise AND Operator print(c) a = 12 b = 13 c = a | b # Bitwise OR Operator print(c) a = 10 b = 7 c = a ^ b # Bitwise XOR Operator print(c) a = 10 b = 2 c = a << b # Bitwise Left Shift Operator print(c) a = 10 b = 1 c = a >> b # Bitwise Right shift Operator print(c)
false
b89316b96fe7dfd9153ad9e474f2f9b9e6362f2d
imeixi/python_fishc_test
/020/closure.py
881
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 如果在一个内部函数里,对在外部作用域的变量进行了引用,那么这个内部函数就被称为闭包。 def fun_x(x): """返回一个函数名,不加()""" def fun_y(y): return x * y return fun_y # # fun_y就是一个闭包 # 调用1,先返回一个函数 f = fun_x(8) print(f) result = f(5) print(result) # 调用2 print(fun_x(8)(10)) def fun1(): """nonlocal 使内嵌函数引用外部变量 ----推荐 """ x = 5 def fun2(): nonlocal x x *= x return x return fun2() print(fun1()) def fun11(): """ python2 使内嵌函数引用外部变量----不推荐 """ x = [5] def fun2(): x[0] *= x[0] return x[0] return fun2() print("使用容器方式,在内嵌函数中调用外部函数变量" + fun11())
false
677b93fab786b8e3997ab0b8c42db26093ff6b20
gaomigithub/Leetcode
/GraphValidTree.py
1,696
4.25
4
# Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. # For example: # Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true. # Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false. # Hint: # 1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? # 2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.” # 3. Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. class Solution(object): def validTree(self, n, edges): """ :typen n: int :type edges: List[List[int]] :rtype: bool """ # It must have those numbers of edges as a tree if len(edges) != n-1: return False # for example # 3 -> 0 -> 1 -> 4 # ↓ # 2 # build hashtable: # {3: 0} # {0: 1,2,3} # {1: 0,4} # {2: 0} # {4: 1} neighbors = {i:[] for i in range(n)} for v, w in edges: neighbors[v].append(w) neighbors[w].append(v) # BFS, put 0 in the queue first, then pop queue in the neighbors queue = [0] while queue: queue.extend(neighbors.pop(queue.pop(0), [])) return not neighbors
true
5157bf522b57563d8d340a3c06e15863c5c43f7c
YooMo/PythonLearn
/python基础操作/LEARN2 字符串类型.py
848
4.28125
4
# PYTHON的数据类型 # 常见的数据类型 # 1.字符串类型 love = "i love u" like = "你真棒" helloworld = "你好 世界!" print(love, helloworld, like) # 大字符串可以换行,也很帅,也是str类型 # 大字符串还可以当注释使用(当你没有把此字符串赋值给某一变量时) s = ''' 这是一个大字符串 我用s来接收了 绿色的好看是这样的 ''' print(s, type(s)) # 在python中,type()用于返回数据类型 # <class 'str'>字符串类型 print(love, type(love)) # # 单双引号可以互相嵌套 # s = 'i love u' # s = 'i "love" u ' 此情况可以嵌套 打印出来的效果是带着引号的 # # 关于转义字符 在字符串内使用 # \n 换行 # \t 制表符 c = 'yoom\no\n' d = r'yoo\nmo\n' # 在字符串前加r可以去除转义字符效果 e = 'wo\\wp' print(c, d, e)
false
b13d1b40e5fe1b97f94bc9a2380542cba9640364
viniciuszambotti/statistics
/Binomial_Distribution/code.py
584
4.1875
4
''' Task The ratio of boys to girls for babies born in Russia is 1.09: 1 . If there is 1 child born per birth, what proportion of Russian families with exactly 6 children will have at least 3 boys? Write a program to compute the answer using the above parameters. Then print your result, rounded to a scale of 3 decimal places (i.e.,1.234 format). ''' import math def bi_dist(x, n, p): b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x)) return(b) b, p, n = 0, 1.09/2.09, 6 for i in range(3,7): b += bi_dist(i, n, p) print("%.3f" %b)
true
8b012009d004b277dcd911213be55ad4e62b12f1
qbarefoot/python_basics_refreshers
/pbrf1.8_sorting_lists.py
1,076
4.59375
5
#we can use the ".sort()" statement to put a list in alphabetical order. horses = [ "appalose", "fresian", "mustang", "clydesdale", "arabian" ] horses.sort() print(horses) #we can also arrange our list in alphabetical order backwards with the ".sort(reverse=True)". horses = [ "appalose", "fresian", "mustang", "clydesdale", "arabian" ] horses.sort(reverse=True) print(horses) #you can maintain your original list but presented it in a sorted order with the "sorted() statement" horses = [ "appalose", "fresian", "mustang", "clydesdale", "arabian" ] print("See our original list") print(horses) print("\n See the new sorted list down here") print(sorted(horses)) #you can also put a list in reverse order without being arranged in order with the ".reverse()" statement. flowers = [ "sunflower, daisy", "tulip", "rose" ] print(flowers) flowers = [ "sunflower, daisy", "tulip", "rose" ] flowers.reverse() print(flowers) #you can find the length of a list with the "len()" statement. footwear = [ "sneakers", "boots", "heels", "sandals", "loafers" ] print (len(footwear))
true
090041cd7dc95f2a3176b13985a691c289379037
smh82/Python_Assignments
/Vowels.py
335
4.34375
4
# Write a Python program to test whether a passed letter is a vowel or not letter = input ("enter the letter to be checked : ") v = "AEIOU" for i in v: if i.upper() == letter.upper(): print("the letter {t} is a vowel".format(t=letter)) break else : print( "the letter {t} is not a vowel ".format(t=letter))
true
06881534aeb302011ff5229bbb4feae0047d4e3f
smh82/Python_Assignments
/Area_of_Circle.py
214
4.4375
4
# Python program which accepts the radius of a circle from the user and compute the area import math radius = float(input ("Enter Area of Cirle ")) print("Area of Circle is : " + str( math.pi*radius**2 ))
true
7e431309e3ea62fc8f056f7ea302c05281cc6a13
mulongxinag/xuexi
/L10数据库基础和sqlite/2sqlite示例1.py
1,775
4.1875
4
# (重点)sqlite示例 import sqlite3 connect = sqlite3.connect("testsqlite.db") cursor = connect.cursor() # cursor.execute("""CREATE TABLE student( # id INT PRIMARY KEY , # name VARCHAR(10) # );""") cursor.execute(""" INSERT INTO student(id,name)VALUES (2,"小明"); """) cursor.close() connect.commit() connect.close() """ (了解)数据库驱动:数据库有自己本身的软件构造和操作语言,数据库暴露出操作接口,方便其他各种编程语言对接。编程语言到数据库的对接中介 叫驱动。所以我们用python操作数据库要使用驱动。 步骤: 1.引用驱动包 2.连接数据库,得到会话。 中大型数据库需要先用户名、密码验证,再创建数据库,再连接数据库;而轻量级的sqlite省略了前面的过程直接连接,如果这个数据库不存在的话,会生成一个库,数据保存在一个单bd文件中。 (了解)sqlite3.connect( 3.生成游标。 游标:游标是对数据库某一行某一格进行增删改查的操作者,就好像操作excel表格时的鼠标。 4.插入一些数据。注意主键id列不能重复。 5.关闭游标。这一步可以省略。 6.提交 commit。 除了查询,增加、修改、删除、操作都需要在执行sql提交,否则不生效,好像平时用软件保存时的确认对话框。 7.断开回话连接,释放资源。 """ """ 可能的异常: 1.唯一的约束错误,主键重复。 sqlite3.IntegrityError: UNIQUE constraint failed: student.id 2. 表已存在重复创建。sqlite3.OperationalError: table student already exists 3.无法操作已关闭的数据库。sqlite3 .ProgrammingError:Cannot operate on a closed database. """
false
fb303846e73f0a2ab5be9110c2c45c4b23681aa5
ParkerCS/ch15-searches-bernhardtjj
/ch15Lab.py
1,452
4.15625
4
""" Complete the chapter lab at http://programarcadegames.com/index.php?chapter=lab_spell_check """ import re # This function takes in a file of text and returns # a list of words in the file. def split_file(file): return [x for line in file for x in re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line.strip())] dict_words = split_file(open("dictionary.txt")) def split_file(file): # this returns it in lines return [re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line.strip()) for line in file] alice = split_file(open("AliceInWonderLand200.txt")) print("--- Linear Search ---") for n in range(len(alice)): for word in alice[n]: i = 0 while i < len(dict_words) and dict_words[i] != word.upper(): i += 1 if i >= len(dict_words): print("Line", n + 1, "possible misspelled word:", word) print("--- Binary Search ---") for i in range(len(alice)): for word in alice[i]: lower_bound = 0 upper_bound = len(dict_words) - 1 found = False while lower_bound <= upper_bound and not found: target = (lower_bound + upper_bound) // 2 if dict_words[target] < word.upper(): lower_bound = target + 1 elif dict_words[target] > word.upper(): upper_bound = target - 1 else: found = True if not found: print("Line", i + 1, "possible misspelled word:", word)
false
9d7e5b798dac265dbd23c4c5f8bca62db8cad843
projectinnovatenewark/student_repository
/todos/3_classes_and_beyond/17_classestodo.py
1,656
4.53125
5
""" Creating classes for your classmates """ # TODO: Create a class for an Employee, and include basic data # TODO: like hours worked, salary, first name, last name, age, and title # TODO: Create a function inside the class and print out a formatted # TODO: set of strings explaining the details from the employee. Use the f shorthand # TODO: for formatting that was used in the previous example. # TODO: Then, call that function to print out those strings with a class # TODO: of Employee set equal to a variable employeeOne # TODO: Set up a child class that derives from the Employee class and add the attribute 'h_benefits'. # TODO: Define a function 'intro' to print: # TODO: "Hi, my name is Garrett Palmeri. I am 24 year old Financial Analyst that makes $40000 per year. # TODO: I do not have insurance." # TODO: Create a class named 'Animal' with the attributes no_of_legs, weight, height # TODO: Then you will create 2 classes derived from 'Animal' named 'Mammal' and 'Fish' # TODO: Define the variable 'habit' for 'Mammal' and 'Fish' to = 'Land' and 'Water' respectively, # TODO: so that it will apply to all Mammals and Fish. # TODO: Also give 'Mammal' a new attribute - 'can_fly' # TODO: Then set the class 'Dog' derived from 'Mammal' and 'Shark' derived from 'Fish'. # TODO: Give a new attribute to each - 'd_type' and 's_type' respectively. # TODO: Define a function in 'Dog' that prints the statement # TODO: "Golden Retriever: 4 legs, 65 lbs, 47 inches. Habitat: Land" # TODO: Define a function in 'Shark' that prints the statement # TODO: "Great White: 0 legs, 2100 lbs, 144 inches. Habitat: Water" # TODO: Print each statement
true
493f8f4a9e1529d7275944c2f094f4c71829c3a9
ambosing/PlayGround
/Python/Problem Solving/BOJ/boj10768.py
239
4.125
4
mon = int(input()) day = int(input()) if mon > 2: print("After") if mon == 2: if day == 18: print("Special") if day > 18: print("After") if day < 18: print("Before") if mon < 2: print("Before")
false
7d66b8782ac7e066a550125483791c7ec6c8beaf
alive-web/paterns
/src/strategy/second.py
1,920
4.125
4
__author__ = 'plevytskyi' class PrimeFinder(object): def __init__(self, algorithm): """ Constructor, takes a callable object called algorithm. algorithm should take a limit argument and return an iterable of prime numbers below that limit. """ self.algorithm = algorithm self.primes = [] def calculate(self, limit): """ Will calculate all the primes below limit. """ self.primes = self.algorithm(limit) def out(self): """ Prints the list of primes prefixed with which algorithm made it """ print(self.algorithm.__name__) print(self.primes) def hard_coded_algorithm(limit): """ Has hardcoded values for all the primes under 50, returns a list of those which are less than the given limit. """ hardcoded_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] primes = [] for prime in hardcoded_primes: if prime < limit: primes.append(prime) return primes def standard_algorithm(limit): """ Not a great algorithm either, but it's the normal one to use. It puts 2 in a list, then for all the odd numbers less than the limit if none of the primes are a factor then add it to the list. """ primes = [2] # check only odd numbers. for number in range(3, limit, 2): is_prime = True # divide it by all our known primes, could limit by sqrt(number) for prime in primes: if number % prime == 0: is_prime = False break if is_prime: primes.append(number) return primes if __name__ == "__main__": hardcoded_primes = PrimeFinder(hard_coded_algorithm) hardcoded_primes.calculate(50) hardcoded_primes.out() standard_primes = PrimeFinder(standard_algorithm) standard_primes.calculate(50) standard_primes.out()
true
098f4f60e0a9eafe5e039ff135354b073b1b1016
andizzle/flipping-game
/board.py
1,188
4.125
4
from Move import move class Board: size = 0 moves = 0 def __init__(self, board_size): """ Construct a board grid like """ x = 0 self.grid = [] self.size = board_size while(x < board_size): row = [1 for size in range(board_size)] self.grid.append(row) x = x + 1 def print_grid(self): """ Print the game board like a board """ print '-' * len(self.grid) * 3 for x in self.grid: print x print '-' * len(self.grid) * 3 def flip(self, move): """ Flip the board within the range e.g, upper_right = (3, 0) """ upper_right = move.upper_right width = move.width height = move.height self.moves = self.moves + 1 x = upper_right[0] while(width > 0): y = upper_right[1] width = width - 1 loop_height = height while(loop_height > 0): loop_height = loop_height - 1 self.grid[y][x] = 1 if self.grid[y][x] == 0 else 0 y = y + 1 x = x - 1
true
41ca379a56bc9ec574862380c660d00ef6948eb7
MMelendez526/Comp_Hmwk
/Melendez_hw3_p3.py
1,356
4.1875
4
#Computational Homework #3, Problem #3 #Calculate the heat capacity of a solid import math import matplotlib.pyplot as plt import numpy as np V = 0.001 #in m^3 p = 6.022e28 #in m^-3 theta = 428 #in K k = 1.38e-23 T = float(input('Please enter the desired temperature: ')) CV = (9*V*p*k)*((T/theta)**3) def C(x): return ((x**4)*(math.e**x))/(((math.e**x)-1)**2) N = 1000 #Number of steps in integration a = 0.00 #lower integration bound b = theta/T #upper integration bound h = (b-a)/N s = 0.5*C(b) for j in range (1, N): s += C(a+j*h) print("The Heat Capacity for a Solid at a Temperature of ", T, "K is: ", round(CV*h*s, 3)) Temp = np.linspace(5,500, 495, endpoint = True) temp = [] for T in range(5, 500): N = 1000 a = 0.00 b = theta/T h = (b-a)/N CV = (9*V*p*k)*((T/theta)**3) s2 = 0.5*C(b) for m in range (1, N): s2 += C(a+m*h) tem = s2*CV*h temp.append(tem) plt.plot(Temp, temp) plt.title('Heat Capacity of a Solid') plt.xlabel('Temperature (K)') plt.ylabel('Heat Capacity') plt.savefig('Heat_Capacity.eps') plt.show() ########################################### #Aside from the graph, the code yields the following: #Please enter the desired temperature: #If I put in, say 100, then I return: #The Heat Capacity for a Solid at a Temperature of 100.0 K is: 1152.722
false
429c33062fd855385134e8294ad03cb3fd7d1a43
Thatguy027/Learning
/Learning_python/ex3.py
923
4.34375
4
# print text in quotes print "I will now count my chickens:" # calculates 25 + (30/6) print "Hens", 25 + 30 / 6 # % or modulus gives you the remainder of 75/4 = 3 print 75 % 4 # 100 - (25*3)%4 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" print 5 % 2 print 1 - 1/4 + 6 # calculates everything to right of modulus first # then takes modulus and resumes order of operations # ends up looking like: # 5 % 2 = 1 # 1 - 1/4 + 6 # rounds this calulation to 7 # include number after decimal place to generate float variable print 1 / 4 print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4.0 + 6 # testing equalities print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
c9f9b5ddce63734ae225e8f899707b6db253945e
melardev/PythonAlgorithmSnippets
/sort_nested_iterable_by_index.py
420
4.375
4
""" We will sort a list of tuples based on the index of a tuple that is contained in the list This would also work for list of lists (shown in other demo) """ def sort_callback(value): return value[1] my_list_of_tuples = [(1, 2), (2, 3), (3, 4), (2, 2), (2, 1)] my_list_of_tuples.sort(key=sort_callback) print(my_list_of_tuples) my_list_of_tuples.sort(key=sort_callback, reverse=True) print(my_list_of_tuples)
true
d192f485a91461f5cffadb07c247d22f9335578c
sharepusher/leetcode-lintcode
/data_structures/tree/trie/implement_trie.py
2,514
4.125
4
## Reference # http://www.lintcode.com/en/problem/implement-trie/ # 208 https://leetcode.com/problems/implement-trie-prefix-tree/#/description ## Tags - Medium; Blue # Trie; Facebook; Uber; Google ## Description # Implement a trie with insert, search, and startsWith methods. # NOTE: # You may assume that all inputs are consist of lowercase letter a-z # Example: # insert("lintcode") # search("code") # >>> false # startsWith("lint") # >>> true # startsWith("linterror") # >>> false # insert("linterror") # search("lintcode) # >>> true # startsWith("linterror") # >>> true ## Analysis # Trie is a 26 tree. # There are two ways to implement trie: hashmap or arraylist # arraylist spends more space, as which has to pre-allocate # 1) trie node definition # Each node has a word label to indicates whether the word traverse finished. # and there's should be a 26bits list or a hashmap to store the reference to other trie nodes # 2) trie build: trie is not like the segment tree, there's no need to build the tree, but just insert # as trie should be a kind of ds that change oftenly. # while segment tree is based on a list, that's why it should be build first. # Trie build process is performed during insertion. # 3) trie query ## Solutions # Trie # implement trie with hash class TrieNode(object): def __init__(self): self.children = {} # each children contains TrieNode - "w": TrieNode() self.is_word = False self.num = 0 class Trie(object): def __init__(self): """Initialize the data structure. """ self.root = TrieNode() # @return: None # build trie tree def insert(self, word): # corner case if not word: return walker = self.root for letter in word: if letter not in walker.children: walker.children[letter] = TrieNode() walker = walker.children[letter] current.is_word = True return # @return: True if find the word def search(self, words): # corner case if not word: return False if not self.root: return False current = self.root for letter in word: if letter not in current.children: return False current = current.children[letter] return current.is_word def startswith(self, word): if not word or not self.root: return False current = self.root for letter in word: if letter not in current.children: return False current = current.children[letter] return True
true
cab50d418dfc432d379e5754a0367d499ae620e2
sharepusher/leetcode-lintcode
/data_structures/hashtable/hash_function.py
1,688
4.25
4
## Reference # http://www.lintcode.com/en/problem/hash-function/ ## Tags - Easy # Hash Table ## Description # In data structure hash, hash function is used to convert a string (or any other type) # into an integer smaller than hash size and bigger or equal to zero. # The objective of designing a hash function is to "hash" the keys as unreasonable as possible. # A good hash function can avoid collision as less as possible. # A widely used hash function algorithm is using a magic number 33, consider any string as a 33 based # big integer like follow: # hashcode("abcd") = (ascii(a)*33^3 + ascii(b)*33^2+ascii(c)*33+ascii(d)) % HASH_SIZE # = (97*33^3 + 98*33^2 + 77*33 + 100) % HASH_SIZE # here HASH_SIZE is the capacity of the hash table(you can assume a hash table is like an array with index 0~HASH_SIZE-1). # Given a string as a key and the size of hash table, return the hash value of this key. ## Clarification # For this problem, you are not necessary to design your own hash algorithm or consider any collision issue, you just need to # implement the algorithm as described. # Example: For key= "abcd", and size=1000, return 78. ## Analysis # base 33 => ord: convert ONE character to ascii number # ans = (ans*33 + ord(x)) ## Solution class Solution: def hashCode(self, key, HASH_SIZE): ans = 0 # whenever one character more, the 33 will be increased for x in key: ans = (ans*33 + ord(x)) % HASH_SIZE return ans if __name__ == "__main__": ans = Solution() key = "abcd" size = 100 if 78 == ans.hashCode(key, size): print("Passed: Hash Function.") else: print("Failed: Hash Function.")
true
0eb832f03503b99fbca623515c4230512846cb9b
superstones/LearnPython
/Part1/week1/Chapter6/directory_exercise/directory_table_6.3&6.4.py
758
4.28125
4
# 6.3词汇表 directory = { 'print': 'Output statement', 'min': 'Find the smallest number in the list', 'max': 'Find the largest number in the list', 'sum': 'Sum the list', 'pop': 'Delete the list of element', 'for': 'Repeat statement', '+': 'Add two objects', '-': 'Get a negative number or subtract one number from another', '*': 'Multiply two numbers or return a string repeated several times', '%': 'Returns the remainder of the division', } print("print: " + directory['print']) print("min: " + directory['min']) print("max: " + directory['max']) print("sum: " + directory['sum']) print("pop: " + directory['pop']) print("\n") # 6.5词汇表2 for word, means in directory.items(): print(word + ":" + means)
true
d1373ab395a8a6200cf0193c02d52e74ef112a17
superstones/LearnPython
/Part1/week1/Chapter4/Exercise/cut_4.10.py
301
4.5
4
#4.10切片 items = ['beautiful', 'handsome', 'brilliant', 'nice', 'prefect', 'regret', 'forgive'] print("The first three items in the list are:") print(items[:3]) print("Three items from the middle of the list are:") print(items[2:5]) print("The last three items in the list are:") print(items[-3:])
true
7394d5ab482418b278d95c53be799cbe3c47bf8a
nchen0/Data-Structures-Algorithms
/Data Structures/Queues & Stacks/Intro - Queue.py
1,085
4.15625
4
# Queues follow a FIFO (First in first out) approach. # It's tempting to use a similar approach as stack for implementing the queue, with an array, but it becomes tragically inefficient. When pop is called on a list with a non-default index, a loop is executed to shift all elements beyond the specified index to the left, so as to fill the hole in the sequence caused by the pop. Therefore, a call to pop(0) always causes the worst-case behavior of O(n) time. # Implentation with a normal array (see above, can be inefficient) class Queue: def __init__(self): self.data = [] def isEmpty(self): return self.data == [] def enqueue(self, item): self.data.insert(0, item) def dequeue(self): return self.data.pop(0) def size(self): return len(self.data) # An implementation of a more 'efficient' way to make a queue is in DSAiP, but Python has an implementation of a deque class for us already (deque class = a double ended queue, or FIFO/LILO) from collections import deque D = dequeue() D.append('j') D.appendleft('f')
true
85d196557625563dfc6d3cee88445d373d18529c
nchen0/Data-Structures-Algorithms
/Data Structures/Queues & Stacks/Circular LinkedList as Queue.py
1,204
4.28125
4
class CircularQueue: """Queue implementation using circular linked list for storage""" def __init__(self): self.tail = None self.size = 0 def isEmpty(self): return self.size == 0 def first(self): if self.isEmpty(): return "List is empty" head = self.tail.next return head.value def dequeue(self): """Remove and return the first element of the queue""" if self.isEmpty(): return "List is empty" oldHead = self.tail.next if self.size == 1: self.tail = None else: self.tail.next = oldHead.next self.size -= 1 return oldHead.value def enqueue(self, item): """Add an element to the back of the queue""" newItem = self.Node(item) if self.isEmpty(): newItem.next = newItem else: newItem.next = self.tail.next # Which was the previous head self.tail.next = newest self.tail = newest self.size += 1 def rotate(self): """Rotate front element to the back of the queue""" if self.size > 0: self.tail = self.tail.next
true
00d1bbd2552698704a794b6881a07bd33f750db8
jnajman/hackaton
/03_recursion/03_draw_01_nautilus.py
1,350
4.3125
4
''' In this exercise, you'll understand the concepts of recursion using selected programs - Fibonacci sequence, Factorial and others. We will also use Turtle graphics to simulate recursion in graphics. Factorial Fibonacci Greatest common divisor Once we understand the principles of recursion, we can do fun stuff with Turtle graphics and DRAW: a square a nautilus a spiral a circles (many circles) a hexagram a Koch star a snowflake a tree ''' # ------------------ #turtle # ------------------ import turtle from math import cos,sin from math import radians as deg2rad from math import degrees as rad2deg def F(n): if n == 0: return 0 elif n == 1: return 1 else: return F(n-1)+F(n-2) m=13 # turtle.shape('turtle') turtle.forward(F(m)) turtle.left(90) for j in range(m,0,-1): a=F(j) zlomy=5 angle1=90/(zlomy+1) d=2*a*sin(deg2rad(angle1/2)) turn_angle=(angle1/2) for i in range(0,zlomy+1): turtle.left(turn_angle) turtle.forward(d) turtle.left(angle1/2) turtle.exitonclick() # a=200 # zlomy=20 # angle1=90/(zlomy+1) # d=2*a*sin(deg2rad(angle1/2)) # turn_angle=(angle1/2) # # # turtle.forward(a) # turtle.left(90) # # for i in range(0,zlomy+1): # turtle.left(turn_angle) # turtle.forward(d) # turtle.left(angle1/2) # # # turtle.shape('turtle') # turtle.exitonclick()
true
8e065ebbc6e027da7d048c8678bb8efd0922c4cd
MaxBabii/home_work_python_starter
/home_work_3(1).py
1,369
4.34375
4
#Напшите программу калькулятор в которой пользователь сможет выбрать операцию, #ввести необходимые числа и получить результат. #Операции, которые необходимо реализовать: сложение, вычитание, умножение, деление, возведение в степень, синус, косинус и тангенс числа import math operation = input(""" + - * / ** sin cos tan Select operation: """) number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) if operation == "+": print("Your result: ", number_1 + number_2) elif operation == "-": print("Your result: ", number_1 - number_2) elif operation == "*": print("Your result: ", number_1 * number_2) elif operation == "/": print("Your result: ", number_1 / number_2) elif operation == "**": print("Your result: ", "power first number:", number_1 ** 2, " power second number:", number_2 ** 2 ) elif operation == "sin": print("Result from the first digit: ", math.sin(number_1)) elif operation == "cos": print("Result from the first digit: ", math.cos(number_1)) elif operation == "tg": print("Result from the first digit: ", math.tan(number_1)) else: print("Error")
false
b08d237c10a08e9e5de0e43cc1cd2905b693e209
CharlotteKings/Data14Python
/introduction/Advanced_FizzBuzz.py
962
4.40625
4
# Function to check if inputted values are integers def check(val): while not val.isnumeric(): val = input("Please type a valid number? \n") if val.isnumeric: return int(val) # Assign counter = check(input("What number do you want to start from? \n")) limit = check(input("What number do you want to finish at? \n")) multiple1 = check(input("Choose the first number")) Fizz = input(f"What would you like to say when the number is divisible by {multiple1}? \n") multiple2 = check(input("Choose a second number")) Buzz = input(f"What would you like to say when the number is divisible by {multiple2}? \n") # FizzBuzz for number in range(int(counter),int(limit),1): if number % multiple1 == 0 and number % multiple2 ==0: # Change values for fizz and buzz print(f"{Fizz}{Buzz}") elif number % multiple1 == 0: print(f"{Fizz}") elif number % multiple2 ==0: print(f"{Buzz}") else: print(number)
true
3a3845be749058ed1c1c4141bcd36584ca49da17
any027/PyTest_Examples
/pytest_venv/calculator/calculator.py
856
4.21875
4
class CalculatorError(Exception): """ An exception class for Calculator """ class Calculator(): """ Example Calculator """ def add(self, a, b): self.check_operands(a) self.check_operands(b) return a + b def subtract(self, a, b): self.check_operands(a) self.check_operands(b) return a - b def multiply(self, a, b): self.check_operands(a) self.check_operands(b) return a * b def divide(self, a, b): self.check_operands(a) self.check_operands(b) try: return a // b except ZeroDivisionError: raise CalculatorError("Cannot divide by 0") def check_operands(self, operand): if not isinstance(operand , (int, float, complex) ): raise CalculatorError(f'"{operand}" is not a number')
true
f63cfe08575a4b76beb41bfe211128f4bf5766df
tomasdecamino/CS_TOLIS
/PressButton/PressButton.pyde
900
4.1875
4
# Tomas de Camino Beck #CS course with Pyhton # Simple press button code # button list # list is organized [x,y,size, True/False] buttons = [ [10,10,50,True], [60,10,50, False], [110,10,50, False], [160,10,50, False] ] pressButton = False def setup(): size(300, 300) def draw(): background(0) stroke(200) global buttons # draw buttons for button in buttons: if button[3]: fill(255) else: fill(0) rect(button[0], button[1], button[2], button[2]) # event that is triggered when mouse button pressed def mousePressed(): pressButtons() # check if mouse is over a button def pressButtons(): global buttons for button in buttons: if (button[0]< mouseX < (button[0]+button[2]) and button[1]< mouseY < (button[1]+button[2])): button[3] = not button[3]
true
9cbc49a3f4fd7034880f2b2afae37ba371ace4a5
rmanovv/python
/task23/overlap_files.py
950
4.1875
4
''' Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of all prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000. (If you forgot, prime numbers are numbers that can’t be divided by any other number. And yes, happy numbers are a real thing in mathematics - you can look it up on Wikipedia. The explanation is easier with an example, which I will describe below.) ''' def overlap(): with open('One.txt', 'r') as file: numbers = file.read() list_numbers = list(map(int, numbers.split())) with open('the other.txt', 'r') as file_two: numbers_two = file_two.read() list_prime_numbers = list(map(int, numbers_two.split())) overlap_number = [i for i in list_numbers if i in list_prime_numbers] [print(i) for i in overlap_number] if __name__ == '__main__': overlap()
true
9a3a63ab84c5b99872331e30e1ac230d76e04982
rmanovv/python
/checkIO/electronic_station/Clock Angle.py
1,342
4.34375
4
# You are given a time in 24-hour format and you should calculate a lesser angle between the hour and minute hands in degrees. # Don't forget that clock has numbers from 1 to 12, so 23 == 11. The time is given as a string with the follow format "HH:MM", # where HH is hours and MM is minutes. Hours and minutes are given in two digits format, so "1" will be writen as "01". The result # should be given in degrees with precision ±0.1. def clock_angle(time): hour, minute = time.split(':') hour = int(hour) % 12 minute = int(minute) hour_angle = (hour + minute/60.0) * 30.0 minute_angle = 6.0 * minute angle = (minute_angle - hour_angle) % 360 if angle > 180: angle = 360 - angle return angle if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert clock_angle("02:30") == 105, "02:30" assert clock_angle("13:42") == 159, "13:42" assert clock_angle("01:42") == 159, "01:42" assert clock_angle("01:43") == 153.5, "01:43" assert clock_angle("00:00") == 0, "Zero" assert clock_angle("12:01") == 5.5, "Little later" assert clock_angle("18:00") == 180, "Opposite" print("Now that you're finished, hit the 'Check' button to review your code and earn sweet rewards!")
true
609940a97b34d5dc2553c55e3b706366d537c647
brockco1/E01a-Control-Structues
/main10.py
2,198
4.40625
4
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print('Greetings!') # displays the text Greetings! when you run the program colors = ['red','orange','yellow','green','blue','violet','purple'] # these are the pool of colors this program is picking from to come up with an answer to the question play_again = '' # lets you play the game again best_count = sys.maxsize # the biggest number while (play_again != 'n' and play_again != 'no'): # the two responses to the question play again match_color = random.choice(colors) # choices a color from the pool of colors as the answer to the question count = 0 # counts your number of tries color = '' while (color != match_color): # running the main program color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line color = color.lower().strip() # how the program reads the answers given to the question count += 1 # count goes up by one each time if (color == match_color): # tells that the answer is correct print('Correct!') # displays correct on the screen else: # alternative response to an answer print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #displays Sorry, try again and then how many guesses you have on the screen print('\nYou guessed it in {0} tries!'.format(count)) # displays on the screen how many gesses it took you to put in the right answer if (count < best_count): # displays your record of tries print('This was your best guess so far!') # displays a hint best_count = count play_again = input("\nWould you like to play again? ").lower().strip() # displays Would you like to play again on the screen when you solve the question print('Thanks for playing!') # displays Thanks for playing on the screen when the game is over
true
6bfc6fc9b3e30c9ace200101ca2897a3bae19f2a
doulgeo/project-euler-python
/divisable.py
872
4.25
4
""" The general idea is that each of the numbers that have to divide the answer, can be assigned to a list of bools. So if your test number is 2520, then if 11 divides it then you have a true value appended in a list. If all 8 booleans in this list are true then that means that every number divides the test. """ step = 2520 #start with 2520 as we know it is divided by range(1,10) n = 2520 c = [11,13,14,16,17,18,19,20] #only these numbers are neccessary d = [] switch = 1 while switch == 1: for i in c: if not(n%i==0): #first test if number is not divisable for speed break else: d.append(True) print d if all(d) and len(d) == 8: #len(d) must be 8 if every num. in c divides n print n switch = 0 break else: del d[:] n = n + step
true
51613767a95f88083e372dd54761467f91241a2b
amresh1495/LPTHW-examples-Python-2.X
/ex19.py
1,065
4.28125
4
# Function to show that variables in a function are not connected to the variables in script. # We can pass any variable as an arguement of the function just by using "=" sign. def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses." % cheese_count print "You have %d boxes of crackers." % boxes_of_crackers print "Man that's enough for party !" print "Get a blanket \n" print "We can just give the input directly." cheese_and_crackers(20, 30) #------ numbers as arguments print "Or we can use variables from our script." amount_of_cheese = 40; amount_of_crackers = 50; cheese_and_crackers(amount_of_cheese, amount_of_crackers) #------ new variables from the script passed as arguments print "We can even do math inside !" cheese_and_crackers(10 + 20, 10 + 30) #------ math operation while passing the arguments print "Or we can combine the variables with numbers." cheese_and_crackers(amount_of_cheese + 32, amount_of_crackers + 34) #------ variables and math combination in the function
true
a00c1c4a2319b4d9564eac7519a93d2fa866c0c4
gistable/gistable
/all-gists/5653532/snippet.py
975
4.125
4
# coding=UTF-8 """ Faça um Programa que leia um número inteiro menor que 1000 e imprima a quantidade de centenas, dezenas e unidades do mesmo. Observando os termos no plural a colocação do "e", da vírgula entre outros. Exemplo: 326 = 3 centenas, 2 dezenas e 6 unidades """ number = int(raw_input("Digite um numero: ")) if number > 0 and number < 1000: centenas = number / 100 dezenas = (number % 100) / 10 unidades = (number % 100) % 10 msg = list() msg.append("%s =" % number) if centenas == 1: msg.append("%s centena," % centenas) else: msg.append("%s centenas," % centenas) if dezenas == 1: msg.append("%s dezena e" % dezenas) else: msg.append("%s dezenas e" % dezenas) if unidades == 1: msg.append("%s unidade" % unidades) else: msg.append("%s unidades" % unidades) print ' '.join(msg) else: print "Insira um numero maior que zero (0) ou menor que (1000)"
false
b6fa8168713b014478c8057a2ccefa4069d2c998
gistable/gistable
/dockerized-gists/76d774879245b355e8bff95f9172f9f8/snippet.py
488
4.375
4
# Example of using callbacks with Python # # To run this code # 1. Copy the content into a file called `callback.py` # 2. Open Terminal and type: `python /path/to/callback.py` # 3. Enter def add(numbers, callback): results = [] for i in numbers: results.append(callback(i)) return results def add2(number): return number + 2 def mul2(number): return number * 2 print add([1,2,3,4], add2) #=> [3, 4, 5, 6] print add([1,2,3,4], mul2) #=> [2, 4, 6, 8]
true
bf74fdd5ad7fd81c5f2990d51c114d2347a3c460
gistable/gistable
/all-gists/1867612/snippet.py
2,481
4.28125
4
class Kalman: """ USAGE: # e.g., tracking an (x,y) point over time k = Kalman(state_dim = 6, obs_dim = 2) # when you get a new observation — someNewPoint = np.r_[1,2] k.update(someNewPoint) # and when you want to make a new prediction predicted_location = k.predict() NOTE: Setting state_dim to 3*obs_dim automatically implements a simple acceleration-based model, i.e. x(t+1) = x(t) + v(t) + a(t)/2 You're free to implement whichever model you like by setting state_dim to what you need, and then directly modifying the "A" matrix. The text that helped me most with understanding Kalman filters is here: http://www.njfunk.com/research/courses/652-probability-report.pdf """ import numpy as np def __init__(self, state_dim, obs_dim): self.state_dim = state_dim self.obs_dim = obs_dim self.Q = np.matrix( np.eye(state_dim)*1e-4 ) # Process noise self.R = np.matrix( np.eye(obs_dim)*0.01 ) # Observation noise self.A = np.matrix( np.eye(state_dim) ) # Transition matrix self.H = np.matrix( np.zeros((obs_dim, state_dim)) ) # Measurement matrix self.K = np.matrix( np.zeros_like(self.H.T) ) # Gain matrix self.P = np.matrix( np.zeros_like(self.A) ) # State covariance self.x = np.matrix( np.zeros((state_dim, 1)) ) # The actual state of the system if obs_dim == state_dim/3: # We'll go ahead and make this a position-predicting matrix with velocity & acceleration if we've got the right combination of dimensions # The model is : x( t + 1 ) = x( t ) + v( t ) + a( t ) / 2 idx = np.r_[0:obs_dim] positionIdx = np.ix_(idx, idx) velocityIdx = np.ix_(idx,idx+obs_dim) accelIdx = np.ix_(idx, idx+obs_dim*2) accelAndVelIdx = np.ix_(idx+obs_dim, idx+obs_dim*2) self.H[positionIdx] = np.eye(obs_dim) self.A = np.eye(state_dim) self.A[velocityIdx] += np.eye(obs_dim) self.A[accelIdx] += 0.5 * np.eye(obs_dim) self.A[accelAndVelIdx] += np.eye(obs_dim) def update(self, obs): if obs.ndim == 1: obs = np.matrix(obs).T # Make prediction self.x = self.A * self.x self.P = self.A * self.P * self.A.T + self.Q # Compute the optimal Kalman gain factor self.K = self.P * self.H.T * inv(self.H * self.P * self.H.T + self.R) # Correction based on observation self.x = self.x + self.K * ( obs - self.H * self.x ) self.P = self.P - self.K * self.H * self.P def predict(self): return np.asarray(self.H*self.x)
true
11cab5af1cd5e36fba209f005e2353c71b8a7729
gistable/gistable
/all-gists/2438498/snippet.py
1,686
4.125
4
#! /usr/bin/python # # Church numerals in Python. # See http://en.wikipedia.org/wiki/Church_encoding # # Vivek Haldar <vh@vivekhaldar.com> # # https://gist.github.com/2438498 zero = lambda f: lambda x: x # Compute the successor of a Church numeral, n. # Apply function one more time. succ = (lambda n: lambda f: lambda x: f(n(f)(x))) one = succ(zero) # Add two Church numerals, n, m. add = (lambda m: lambda n: lambda f: lambda x: n(f)(m(f)(x))) # Multiply two Church numerals, n, m. mult = (lambda m: lambda n: lambda f: lambda x: n(m(f))(x)) # Exponentiation: n^m exp = lambda m: lambda n: n(m) # Convert a Church numeral into a concrete integer. # n = 0, f = (add 1 to a number) plus1 = lambda x: x + 1 church2int = lambda n: n(plus1)(0) # Convert a concrete integer into a church numeral. def int2church(i): if i == 0: return zero else: return succ(int2church(i - 1)) # Eval and print a string def peval(s): print s, ' = ', eval(s) peval('church2int(zero)') peval('church2int(succ(zero))') peval('church2int(one)') peval('church2int(succ(one))') peval('church2int(succ(succ(one)))') peval('church2int(succ(succ(succ(one))))') peval('church2int(add(one)(succ(one)))') peval('church2int(add(succ(one))(succ(one)))') peval('church2int(mult(succ(one))(succ(one)))') peval('church2int(exp(succ(one))(succ(one)))') peval('church2int(int2church(0))') peval('church2int(int2church(1))') peval('church2int(int2church(111))') c232 = int2church(232) c421 = int2church(421) peval('church2int(mult(c232)(c421))') print '232 * 421 = ', 232 * 421 c2 = int2church(2) c10 = int2church(10) peval('church2int(exp(c2)(c10))') print '2 ** 10 = ', 2 ** 10
false
ca98687acf174fa07c31df1305ce8eb81c26b4a9
gistable/gistable
/all-gists/9231107/snippet.py
1,103
4.3125
4
#!/usr/bin/env python2 # Functional Python: reduce, map, filter, lambda, *unpacking # REDUCE EXAMPLE add = lambda *nums: reduce(lambda x, y: x + y, nums) def also_add(*nums): '''Does the same thing as the lambda expression above.''' def add_two_numbers(x, y): return x + y return reduce(add_two_numbers, nums) print add(1, 2, 3) # 6 print add(*range(10)) # sum of 0-9: 45 # MAP EXAMPLE squares = lambda *nums: map(lambda x: x * x, nums) def also_squares(*nums): '''Does the same thing as the lambda expression above.''' def double(x): return x * x return map(double, nums) print squares(1, 2, 3) # [1, 4, 9] print squares(*range(10)) # list of squares 0-9 print add(*squares(*range(10))) # sum of the above squares: 285 # FILTER EXAMPLE evens = lambda *nums: filter(lambda x: x % 2 == 0, nums) def also_evens(*nums): '''Does the same thing as the lambda expression above.''' def is_even(x): return x % 2 == 0 return filter(is_even, nums) print evens(1, 2, 3) # (2,) print evens(1, 3) # () print evens(*range(10)) # (0, 2, 4, 6, 8)
true
7a106333ddb52a4ea723a68648b65d201a072591
gistable/gistable
/all-gists/91c49ddaceb38c0a6b241df6831a141b/snippet.py
2,995
4.125
4
import random, math #Ignore def monte_carlo(): ...im just defining a function def monte_carlo(): #At the end sums will add up all the f(n) sums = 0 #just creating a dictionary, ignore this, not too important functions = {'1': 'x', '2': 'x^2', '3': 'sin', '4': 'cos', '5': 'exp'} print("Choose your function") #This is just a print of all available functions to chose...ignore it! choice = input("""Enter 1 for: f(x) = x Enter 2 for: f(x) = x^2 Enter 3 for: f(x) = sin(x) Enter 4 for: f(x) = cos(x) Enter 5 for: f(x) = exp(x) Choose your function: """) #Just creating a list of options valid_options = ['1', '2', '3', '4', '5'] #if user does not type any of the options from 1 to 5 (above list) then terminate programme if choice not in valid_options: print("Enter a valid option next time. \n") return 0 #otherwise carry on with programme else: #this asks user for the number of simulations no_of_simulations = input('Enter the number of similations: ') #if user types in anything if no_of_simulations: #terminate the programme if user typed in a negative number or any jibberish! if not no_of_simulations.isdigit(): print("Please enter a valid number next time \n") return 0 #if user types in positive number then carry on else: #ask user for the number of simulations no_of_simulations = int(no_of_simulations) #this will itterate through 0, 1, 2, 3,...,no_of_simulations #so num = 0,1,2,3... etc for num in range(no_of_simulations): #this gives new random number everytime num updates random_num = random.uniform(0,1) #This if statement is basically saying if user picked sin(x), cos(x) or exp(x) if int(choice) >= 3: #result is basically f(x). E.g. if your random number is 0.4 and # you picked sin(x) then result will calculate sin(0.4) # result will be result = eval('math.%s(%s)' % (functions.get(choice), random_num)) #This sums adds the results. E.g. if user picked 2 for number of simulations #then you will generate 2 random numbers say 0.4 and 0.2. #then sums = sin(0.4) + sin(0.2) sums += result #If user picked x^2 then... elif int(choice) == 2: result = random_num * random_num sums += result #If user picked x then... elif int(choice) == 1: sums += random_num #this is just dividing by n. print(float(sums/no_of_simulations)) monte_carlo()
true
523f130fc786632ba04c2fa319472d483395c2f0
gistable/gistable
/all-gists/1546736/snippet.py
2,317
4.28125
4
#!/usr/bin/env python # coding: utf-8 """ String to Brainfuck. Converts a string to a brainfuck code that prints that string. Author: j0hn <j0hn.com.ar@gmail.com> """ import sys def char2bf(char): """Convert a char to brainfuck code that prints that char.""" result_code = "" ascii_value = ord(char) factor = ascii_value / 10 remaining = ascii_value % 10 result_code += "%s\n" % ("+" * 10) result_code += "[\n" result_code += " >\n" result_code += " %s\n" % ("+" * factor) result_code += " <\n" result_code += " -\n" result_code += "]\n" result_code += ">\n" result_code += "%s\n" % ("+" * remaining) result_code += ".\n" result_code += "[-]\n" return result_code def str2bf(string): """Convert a string to brainfuck code that prints that string.""" result = "" for char in string: result += char2bf(char) return result def print_help(): """Print the help message.""" message = "python %s: missing arguments\n\n" % sys.argv[0] message += "Usage: %s [OPTIONS] STRING\n" % sys.argv[0] message += "Options:\n" message += " -h, --help displays this help message.\n" message += " -s, --small prints the code in one liner.\n" message += " -n, --newline adds a new line character " message += "at the end of the string.\n" sys.stderr.write(message) def main(): """Reads the arguments from stdin and outputs the code.""" if len(sys.argv) < 2: print_help() sys.exit(0) add_new_line = False small_output = False if "-n" in sys.argv or "--newline" in sys.argv: add_new_line = True try: sys.argv.remove("-n") except ValueError: sys.argv.remove("--newline") if "-s" in sys.argv or "--small" in sys.argv: small_output = True try: sys.argv.remove("-s") except ValueError: sys.argv.remove("--small") if "-h" in sys.argv or "--help" in sys.argv: print_help() sys.exit(0) input_string = " ".join(sys.argv[1:]) result = str2bf(input_string + ("\n" * add_new_line)) if small_output: result = result.replace(" ", "").replace("\n", "") print result if __name__ == "__main__": main()
true
4953f3f11c03077361bea42f30ecc6f2fb1fb7e3
gistable/gistable
/dockerized-gists/1253276/snippet.py
1,145
4.21875
4
import datetime class Timer(object): """A simple timer class""" def __init__(self): pass def start(self): """Starts the timer""" self.start = datetime.datetime.now() return self.start def stop(self, message="Total: "): """Stops the timer. Returns the time elapsed""" self.stop = datetime.datetime.now() return message + str(self.stop - self.start) def now(self, message="Now: "): """Returns the current time with a message""" return message + ": " + str(datetime.datetime.now()) def elapsed(self, message="Elapsed: "): """Time elapsed since start was called""" return message + str(datetime.datetime.now() - self.start) def split(self, message="Split started at: "): """Start a split timer""" self.split_start = datetime.datetime.now() return message + str(self.split_start) def unsplit(self, message="Unsplit: "): """Stops a split. Returns the time elapsed since split was called""" return message + str(datetime.datetime.now() - self.split_start)
true
ae23d72d889981dc4790a74d30d43148053e1f87
gistable/gistable
/dockerized-gists/986af2a657d331a848d5/snippet.py
1,348
4.125
4
# -*- coding: utf-8 -*- def calcular_dv(numero): """ Función para el cálculo de el dígito de verificación utilizado en el NIT y CC por la DIAN Colombia. >>> calcular_dv(811026552) 9 >>> calcular_dv(890925108) 6 >>> calcular_dv(800197384) 0 >>> calcular_dv(899999034) 1 >>> calcular_dv(8600123361) 6 >>> calcular_dv(899999239) 2 >>> calcular_dv(890900841) 9 """ coeficientes = [3, 7, 13, 17, 19, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71] sumatoria = 0 cnt = 0 dv = None # Convierte número en string y lo itera de atras hacia adelante for digito in str(numero)[::-1]: sumatoria += int(digito) * coeficientes[cnt] cnt += 1 residuo = sumatoria % 11 if residuo > 1: dv = 11 - residuo else: dv = residuo return dv def validar_dv(numero, dv): """ Valida si el número y el dígito de verificación corresponden >>> validar(811026552,0) False >>> validar(890925108,6) True >>> validar(800197384,1) False >>> validar(899999034,1) True >>> validar(8600123361,3) False >>> validar(899999239,2) True >>> validar(890900841,7) False """ return calcular_dv(numero) == dv if __name__ == "__main__": import doctest doctest.testmod()
false
79e24593006755464c5495cdab9b72ddad11df1d
gistable/gistable
/all-gists/e515a92542fc41ea5911/snippet.py
400
4.15625
4
import math def stringNorm(s): norm = 0 for c in s: if not c==" ": norm+=math.pow(ord(c),2) return math.sqrt(norm) def anagram_detection(s1,s2): return stringNorm(s1)==stringNorm(s2) s1 = input("Please enter first string: ").lower() s2 = input("Please enter second string: ").lower() print ("Anagram.") if anagram_detection(s1,s2) else print ("Not Anagram.")
false
3cc4c5610432cf98e385c8fe476e9554c6f52ab7
gistable/gistable
/dockerized-gists/2004597/snippet.py
2,504
4.40625
4
# This function prints out all of the values and sub-values in any variable, including # lists, tuples and classes. It's not very efficient, so use it for testing/debugging # purposes only. Examples are below: #------------------------------------------------------------------------------------- # ShowData(range(10)) # (list) # (int) 0 # (int) 1 # (int) 2 # (int) 3 # (int) 4 # (int) 5 # (int) 6 # (int) 7 # (int) 8 # (int) 9 #------------------------------------------------------------------------------------- # ShowData([[j for j in range(1, i)] for i in range(1, 5)]) # (list) # # (list) # # (list) # (int) 1 # # (list) # (int) 1 # (int) 2 # # (list) # (int) 1 # (int) 2 # (int) 3 #--------------------------------------------------------------------------------------- # class example: # x = 5 # y = 10.24 # z = 43.5 # # ShowData(example()) # (instance) # (dict pair)(str)y : (float)10.24 # (dict pair)(str)x : (int)5 # (dict pair)(str)z : (float)43.5 #---------------------------------------------------------------------------------------- #(or use the 'index' keyword argument to show list indicies) # ShowData(range(10), index=True) # (list) # [0](int) 0 # [1](int) 1 # [2](int) 2 # [3](int) 3 # [4](int) 4 # [5](int) 5 # [6](int) 6 # [7](int) 7 # [8](int) 8 # [9](int) 9 # Returns "int"/"float"/"list", etc. def typeStr(variable): return str(type(data))[7: -2] def ShowData(data, prefix='', **kargs): _type = typeStr(data) if type(data) in [None, bool, int, float, str]: print '{0}({1}) {2}'.format(prefix, _type, data) else: #Format dictionaries manually to get a nice looking result if type(data) is dict: for (key, value) in data.items(): print '{0}(dict pair)({1}){2} : ({3}){4}'.format(prefix, typeStr(key), key, typeStr(value), value) #Normal iterators elif type(data) in [list, tuple, set]: print '\n{0}({1})'.format(prefix, _type) if 'index' in kargs and kargs['index']: for (number, i) in enumerate(data): ShowData(i, prefix + '{0} [{1}]'.format(prefix, number)) else: for i in data: ShowData(i, prefix + '{0} '.format(prefix)) #any other, non-common class else: print '\n{0}({1})'.format(prefix, _type) # Destructure instance so we can print what's inside pairs = dict((name, getattr(data, name)) for name in dir(data) if not name.startswith('__')) ShowData(pairs, prefix + ' ')
true
6636fb368009ddcb070c71b5c9900d8856c28501
chanshik/codewars
/sum_digits.py
627
4.25
4
""" Write a function named sumDigits which takes a number as input and returns the sum of the absolute value of each of the number's decimal digits. For example: sumDigits(10) # Returns 1 sumDigits(99) # Returns 18 sumDigits(-32) # Returns 5 Let's assume that all numbers in the input will be integer values. """ def sumDigits(number): return sum(map(int, list(str(abs(number))))) from unittest import TestCase class TestSumDigits(TestCase): def test_sum_digits(self): self.assertEquals(sumDigits(10), 1) self.assertEquals(sumDigits(99), 18) self.assertEquals(sumDigits(-32), 5)
true
420879938f42c8d3c2fa6b472f35cb3f1d7f6fad
chanshik/codewars
/triangle_type.py
1,507
4.4375
4
# coding=utf-8 """ In this kata, you should calculate type of triangle with three given sides a, b and c. If all angles are less than 90°, this triangle is acute and function should return 1. If one angle is strictly 90°, this triangle is right and function should return 2. If one angle more than 90°, this triangle is obtuse and function should return 3. If three sides cannot form triangle, or one angle is 180° (which turns triangle into segment) - function should return 0. Input parameters are sides of given triangle. All input values are non-negative floating point or integer numbers (or both). """ # Should return triangle type: # 0 : if triangle cannot be made with given sides # 1 : acute triangle # 2 : right triangle # 3 : obtuse triangle def triangle_type(a, b, c): lengths = sorted([a, b, c]) squares = map(lambda x: x * x, lengths) if lengths[0] + lengths[1] <= lengths[2]: return 0 if squares[0] + squares[1] > squares[2]: return 1 if squares[0] + squares[1] == squares[2]: return 2 return 3 from unittest import TestCase class TestTriangleType(TestCase): def test_triangle_type(self): self.assertEquals(triangle_type(7, 3, 2), 0) # Not triangle self.assertEquals(triangle_type(2, 4, 6), 0) # Not triangle self.assertEquals(triangle_type(8, 5, 7), 1) # Acute self.assertEquals(triangle_type(3, 4, 5), 2) # Right self.assertEquals(triangle_type(7, 12, 8), 3) # Obtuse
true